【发布时间】:2016-11-08 11:57:27
【问题描述】:
假设您不知道 mutex_locks 并且不允许在程序中使用全局变量,如果返回一个成功的变量,您可以做什么来停止所有正在运行的 pthread?
例如,您有一个传递给 pthread 的数据结构,其中包含:
typedef struct {
char * string1; //info from argv[1]
char * string2; //info from argv[2]
int id; //thread id
} dataStruct;
在 main.c 中创建 pthread 时,您可以这样创建它们:
dataStruct dataStr[nbThread]; //array of dataStructs for each thread
pthread_t tabThread[nbThread]; //Pointers for thread 1
for (int i = 0; i < nbThread; ++i) { //initiation of threads...
dataStr[i].string1 = argv[1];
pthread_create(&tabThread[i], NULL, thread, (void *)&dataStr[i]); //create pthreads and
}
for (int i = 0; i < nbThread; ++i) {
pthread_join(tabThread[i], (void**)&(ptr[i])); //join threads
//printf("\n return value from thread[%d] is [%d]\n",i, *ptr[i]);
}
现在其中一个线程找到了您希望实现的目标,如何让所有线程同时停止?
我可以在结构中有一个指针指向 main 中的一个变量,一旦线程成功就可以将其更改为 true 吗?
我可以使用 pthread 的返回值以某种方式阻止它们吗?
我有点难以理解这些指针。任何帮助表示赞赏。
【问题讨论】:
-
“停止”如暂停?还是像 kill 中的“停止”?
-
raise(SIGABRT);,或等效的kill(getpid(), SIGABRT);,或等效的pthread_kill(pthread_self(), SIGABRT);将以您可以定义“同时”的最佳方式停止所有线程。 -
你确实有一个包含所有线程的数组,遍历它并调用
pthread_cancel,并为每个线程传递pthread_t。就像您在加入线程时所做的一样。 -
只需使用
exit即可退出您的程序。这会结束所有线程,甚至会进行一些清理。 -
exit终止进程,并根据定义终止进程的所有线程。