【问题标题】:linux: execute thread after every one secondlinux:每隔一秒执行一次线程
【发布时间】:2015-02-11 05:42:18
【问题描述】:

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

【问题讨论】:

  • 你最好学习如何使用非阻塞套接字和一个线程。从这里开始:kegel.com/c10k.html#strategies
  • 我不明白?为什么接收/发送线程不能保持计数?

标签: linux sockets pthreads


【解决方案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 %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);

【讨论】:

    猜你喜欢
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-17
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多