我有一个服务器程序,为每个新创建的客户端生成保持活力的线程。我使用clock()实现了保活机制。如果只有一个客户端连接到服务器,那么一切都正常。
当我试图将多个客户端连接到服务器(不完全是连接,它的UDP)时,问题就会发生。在第二个客户端连接到服务器之后,两个客户端/其中一个客户端就会无缘无故地超时,即。在它真正超时之前。
由于有多个客户端,所以我将更新的时钟时间(每当服务器从客户端接收保持活动数据包时更新)推送到一个映射(每个客户端一个条目)。在计时器逻辑中,我需要每次从地图中得到更新的时钟时间。为了调试这一点,我在计时器逻辑中添加了一个printf。唉!令我惊讶的是,所有的工作都与这个打印!我不知道为什么。任何帮助都是非常感谢的。谢谢。
....
....
pthread_t thread_id[100];
int thread_no =0;
..
//thread listening for commands from client
while(1)
{
..
if(strcmp(cmd_cli, "1") == 0)
{
..
//this is how I spawn keepalive threads
pthread_create(&thread_id[thread_no], NULL, timer_fun, mac_addr);
thread_no++;
..
}
..
else if(strcmp(cmd_cli, "13") == 0)
{
// Kepalive received from client
if(this_client.state >= RUN)
{
//update timer
this_client.start = clock();
insert(t, mac_addr, this_client);
...
..
}
....
....
//keepalive thread handler on server
struct client_params details = lookup(t, mac);
details.start = clock();
insert(t, mac, details);
int sec=0, delay=8;
do
{
struct client_params details = lookup(t, mac);
clock_t difference = clock() - details.start;
sec = difference / CLOCKS_PER_SEC;
// following printf saves the timer
printf("sec = %d\n", sec);
}while ( sec < delay );
details.state = TIMEOUT;
insert(t, mac, details);
....
....
....发布于 2019-08-13 04:45:56
时钟是导致整个问题的罪魁祸首。clock()测量进程使用的CPU时间。由于我在此过程中生成多个定时器线程,CPU时间变得相当少。因此,clock()返回一个较小的值。但是,使用带有"\n“的printf()会将CPU时间增加到所需的位置,因此问题是不可观察的。
https://stackoverflow.com/questions/57424422
复制相似问题