c - printf保存keepalive定时器

标签 c multithreading sockets timer pthreads

我有一个服务器程序,它为每个新创建的客户端生成保活线程。我已经使用clock()实现了keepalive机制。如果只有一个客户端连接到服务器,则一切正常。

当我尝试将多个客户端连接(不完全是 CONNECT,它的 UDP)到服务器时,就会出现问题。就在第二个客户端连接到服务器后,两个客户端/其中一个客户端无缘无故超时,即。在其实际超时之前。

由于有多个客户端,我将更新的时钟时间(每当服务器从客户端接收到保活数据包时更新)推送到 map (每个客户端一个条目)。另外,在计时器逻辑中,我每次都需要从 map 中获取更新的时钟时间。为了调试这个问题,我在计时器逻辑中添加了一个 printf 。唉!令我惊讶的是,这个 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);
....
....
....

最佳答案

可能是因为the '\n' causes printf to flush the buffer并且需要额外的时间来完成你的事情。要进行测试,请注释掉 printf 并添加一个 sleep() 调用,时间要长于超时时间,然后看看它是否有效。还可以从 printf 中删除换行符以避免缓冲区刷新并查看它是否再次中断。

如果有效,那么您可以延长超时持续时间,添加 sleep() 调用,或找到不同的同步机制。

如果您对信号感到满意并且只计划在 Linux 上使用 posix,那么您可以使用 wait(),但您必须以不同的方式协调线程。

附加信息: 来自 IBM

If you use the system() function in your program, do not rely on clock() for program timing, because calls to system() may reset the clock.

In a multithread POSIX C application, if you are creating threads with a function that is based on a POSIX.4a draft standard, the clock() function is thread-scoped.

双重编辑:没关系,我看到你的 sec 是一个 int,不是共享的。 值得注意的是要避免的 system() 调用,尽管我在这里没有看到它。

关于c - printf保存keepalive定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57424422/

相关文章:

c - K&R 第 2 版,示例 1.9 字符数组

c++ - C/C++ 控制结构限制?

java - Hibernate 4.1.9(最新的最终版本)报告 `nested transactions not supported`

java - 如果 netstat 另有说明,为什么我会得到 "java.net.BindException: Only one usage of each socket address"?

php - PHP 中的套接字标签?

c - getchar() 在 C 中不起作用

c - time.h 中的 time() 如何工作?

c++ - 使成员函数线程出现问题

javascript - node.js 是否在主线程中运行异步文件读取/写入?

windows - 如何暂停 IOCP TCP 套接字服务器?