Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
linux:每秒钟执行一次线程_Linux_Sockets_Pthreads - Fatal编程技术网

linux:每秒钟执行一次线程

linux:每秒钟执行一次线程,linux,sockets,pthreads,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

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

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

// 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);

您最好学习如何使用非阻塞套接字和一个线程。从这里开始:我不明白?为什么接收/发送线程不能维护计数?