【发布时间】:2012-11-08 08:40:36
【问题描述】:
在包含启动线程的源代码之后,过了一会儿我想杀死它。怎么做 ? 无需对线程功能做任何改动
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
pthread_t test_thread;
void *thread_test_run (void *v) // I must not modify this function
{
int i=1;
while(1)
{
printf("into thread %d\r\n",i);
i++;
sleep(1);
}
return NULL
}
int main()
{
pthread_create(&test_thread, NULL, &thread_test_run, NULL);
sleep (20);
// Kill the thread here. How to do it?
// other function are called here...
return 0;
}
【问题讨论】:
-
请注意,直截了当地“杀死”线程是个坏主意。每个线程都应该被正确地设计为从主程序中停止它。仅仅因为存在杀死线程的函数,并不意味着你应该开始以糟糕的方式设计你的线程函数。
-
我建议查看
pthread_join和pthread_attr_setdetachstate... 建立一些机制来告诉线程它现在需要退出并在线程上调用pthread_join以清理使用的东西。 -
我正在使用来自外部库的函数,并且该函数包含无限 while 循环。此函数在随机时间内对全局变量进行 1 次更改。所以我想在全局变量更改后杀死线程。我不再需要线程运行了
-
如果线程函数正在执行系统调用,
pthread_cancel(pthread_t thread);是否会导致阻塞
标签: c multithreading pthreads