我正在使用线程,我实现了两个线程1来接收数据包,另一个用于发送数据包。我想在后台实现一个新的线程,每隔一秒运行一次,并保持计数器没有收到和发送的数据包。
答案 0 :(得分:0)
嗯,这是一个可能的解决方案:
// 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);