我有一个程序,其中用户输入的线程数量添加和删除到双向链表。但是,如果一个线程在添加或删除元素时被抢占,并且下一个线程遇到损坏的链表,则整个程序应该退出。
当其中一个线程调用退出时,是否有某种方法可以退出整个程序?
这是线程执行的函数,当链接列表损坏时我设置了退出调用
void *exec_threads(void* arg){
int *counter = (int*)arg;
int index = mult/threads * (*counter);
SortedListElement_t* element = (SortedList_t*)malloc(sizeof(SortedList_t));
for(int i = 0; i < iterations; i++){
element->key = &keys[index + i];
SortedList_insert(list, element);
}
for(int i = 0; i < iterations; i++){
element = SortedList_lookup(list, &keys[index + i]);
if(element == NULL){
fprintf(stderr, "Could not find element %c in the list\n", keys[index+i]);
exit(2);
}
if(SortedList_delete(element)){
fprintf(stderr, "Corrupted list\n");
exit(2);
}
}
free(arg);
return NULL;
}
这就是我得到的结果
Corrupted list
Corrupted list
Could not find element M in the list
最佳答案
exit()
函数确实终止所有线程。
线程可以同时运行,并且可以随时被抢占(例如,在调用exit()
之前),这解释了您看到的输出。许多线程可能会在同一时间发现列表已损坏,然后序列化内部锁以同步对 stdout
的访问。
关于c - 当一个线程失败时退出所有线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48846440/