linux:每隔一秒执行一次线程

标签 linux sockets pthreads

我正在使用线程,我已经实现了两个线程,一个用于接收数据包,另一个用于发送数据包。我想在后台实现一个新线程,该线程每隔一秒运行一次,并维护接收和发送数据包数量的计数器。

最佳答案

嗯,这是一种可能的解决方案:

// globally accesible variables - can be defined as extern if needed
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int synchronized_received = 0;
int synchronized_sent = 0;

// third threads' main function
void *third_thread_main(void *args){
  while(1){
    struct timespec time;
    time.tv_sec = 1;
    time.tv_nsec = 0;
    nanosleep(&time, NULL);
    int received, sent;
    pthread_mutex_lock(&mutex);
    received = synchronized_received;
    sent = synchronized_sent;
    pthread_mutex_unlock(&mutex);
    fprintf(stdout, "Received %d, Sent %d\n", received, sent);
  }
  return NULL;
}

// in receiving thread put this after received packet
pthread_mutex_lock(&mutex);
synchronized_received++;
pthread_mutex_unlock(&mutex);

// in sending thread put this after packet sent
pthread_mutex_lock(&mutex);
synchronized_sent++;
pthread_mutex_unlock(&mutex);

关于linux:每隔一秒执行一次线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28447339/

相关文章:

c - 如何使用 write() 函数写入 non-char*?

Java 服务器在 32 位工作,但在 64 位工作。为什么?

python - 使用套接字 : address already in use 监听 ip 地址

php - 在 linux 控制台中返回一行?

linux - telnet 端口转发是如何工作的?

c++ - 每个进程可配置的核心转储目录

php - 在 php 中处理实时通知的最佳方法是什么?

c - 在 C 中多线程时同步无法正常工作

c++ - C++创建线程进程

从主线程关闭套接字