c - 当一个线程失败时退出所有线程

标签 c pthreads

我有一个程序,其中用户输入的线程数量添加和删除到双向链表。但是,如果一个线程在添加或删除元素时被抢占,并且下一个线程遇到损坏的链表,则整个程序应该退出。

当其中一个线程调用退出时,是否有某种方法可以退出整个程序?

这是线程执行的函数,当链接列表损坏时我设置了退出调用

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/

相关文章:

c - 使用 vsprintf 将字符串添加到另一种格式字符串的有效方法

c++ - 带有 pthreads 的后台线程

C - execvp() 进程间通信

c - 标记化数组 : signal SIGABRT error 上的 realloc()

用 gcc 编译 .c

java - Python、Java 和 C 中的嵌套循环比较

c - 如何修复调用 pthread_create 时偶尔出现的 EINVAL 错误

c - Pthreads、fread() 和 printf() : Getting random D4's in my string

c - 如何计算 pthread 矩阵乘法程序的运行时间?

C 预处理器概念