Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.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
C 线程中的sleep()也会导致main睡眠_C_Multithreading_Timer_Pthreads_Sleep - Fatal编程技术网

C 线程中的sleep()也会导致main睡眠

C 线程中的sleep()也会导致main睡眠,c,multithreading,timer,pthreads,sleep,C,Multithreading,Timer,Pthreads,Sleep,我有一个网关服务器和两个客户端(由Oracle VM VirtualBox制造) 在我的网关服务器中,我让listener.c监听所有数据包。(在while(1)循环中) 如果客户端发送一个有效的令牌,我必须将其放入我的授权MAC列表中,来自授权MAC的所有数据包必须转发180秒。(换句话说,互联网接入时间为180秒) 180秒前,只有一个用户的东西开始工作 /* authorized MACs list */ char *auth_macs[5]; int client; pthread_mu

我有一个网关服务器和两个客户端(由Oracle VM VirtualBox制造)

在我的网关服务器中,我让listener.c监听所有数据包。(在
while(1)
循环中)

如果客户端发送一个有效的令牌,我必须将其放入我的授权MAC列表中,来自授权MAC的所有数据包必须转发180秒。(换句话说,互联网接入时间为180秒)

180秒前,只有一个用户的东西开始工作

/* authorized MACs list */
char *auth_macs[5];
int client;
pthread_mutex_t lock;

/* after 3 min remove the client from auth list */
void *timer(void *arg){
    sleep(180);
    pthread_mutex_lock(&lock);  
    auth_macs[client] = " ";
    client--;
    pthread_mutex_unlock(&lock);
    return NULL;
}
这就是我试图实现计时器线程的方式<代码>客户端是一个在主功能中更改的全局变量

if(has_token == 1){
    client++;
    sprintf(client_ip, "./accept.sh %s", sender);
    system(client_ip);
    auth_macs[client] = client_mac;
    /* start timer thread */
    pthread_t tid;
    pthread_create(&tid, NULL, timer,NULL);
    pthread_join(tid, NULL);
}
这就是我开始这条线的地方
accept.sh
是一个允许转发的shell脚本

我的问题是我以为定时器线程中的
睡眠(180)
只会自动停止。但是,
listener.c
停止接收数据包

我怎样才能解决这个问题?我想定时器等待180秒,但仍然能够在主功能接收数据包

sleep()
仅挂起调用线程。因此,它不会影响主线程

有问题的是
pthread\u join()
调用:

 pthread_create(&tid, NULL, timer,NULL);
 pthread_join(tid, NULL);
这实际上使多线程变得毫无意义。因为只有一个线程会在主线程等待创建的线程完成时取得进展

如果主线程需要连接,则需要删除
pthread\u join()
调用,并可能在
while(1)
循环之外删除该调用。或者,您可以在线程创建循环外部调用
pthread\u exit(0)
,以便main在其他线程执行时完成执行,如果在主线程运行时仍处于活动状态
中断其循环,可以继续执行。

pthread\u join
将等待线程终止。不管它休眠多长时间。或者他可以使用守护进程线程而不是普通线程,这样他就不需要加入它了。@JohnBollinger这种技术的问题是,当主线程退出时,可能会释放出守护进程线程仍在使用的资源,从而导致守护进程线程中出现未定义的行为。最好有一个有序的关机顺序。