c - 当我们从任何一个线程中出来时,如何杀死剩余的线程?

标签 c multithreading pthreads

#include <pthread.h>
#include <stdio.h>

#include <stdlib.h>
#define NUM_THREADS     5


void *PrintHello(void *threadid)
{
    long tid;
    tid = (long)threadid;
    printf("Hello World! It's me, thread #%ld!\n", tid);
    pthread_exit(NULL);
}

int main (int argc, char *argv[])//main
{

    int rc;
    long t;
    for(t=0; t<NUM_THREADS; t++){
        pthread_mutex_lock(&lock);
        printf("In main: creating thread %ld\n", t);
        rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);//creating thread

        if (rc){
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
        }
    }

    /* Last thing that main() should do */
    pthread_exit(NULL);

}

当一个线程被释放时如何杀死剩余的所有线程

最佳答案

杀死另一个线程是糟糕的设计。标准设计是使用变量来指示线程它应该完成。每个线程应在代码中的适当位置检查变量并相应退出。

原因是只有线程知道什么时候退出,然后它才能自行清理。

关于c - 当我们从任何一个线程中出来时,如何杀死剩余的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27075001/

相关文章:

c - 我不明白deleteall(key)函数中这条语句 "cur = prev->next;"的逻辑

c - UART接收字符串

python - 编写在 Python 中使用的并行 C/C++ 模块的最简单方法

c++ - htop 和 OpenMP 线程

c - 我怎样才能得到一个非常大的整数的平方根?

c - 我想要一个读取文件并返回 ascii 值之和的函数

c# - 如何杀死主线程?

c++ - 在使用 PIN 的模拟器上对 Pthread 进行安全编程

c - 在c中挂起一个线程

c - 无法重新获取互斥量并在线程之间正确传递值