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



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

这是一个可能的解决方案:

// 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 %dn", 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);

最新更新