并发多线程

标签 c multithreading pthreads

我正在尝试了解多线程的工作原理。我写了下面的代码 `

void handler(void *arg)
{
    printf("Printf from cleanup handler: %s\n", (char*)arg);
}

void print(const char *msg)
{
    printf("%7s: Pid=%d Tid:%lu\n", msg, getpid(), pthread_self());
}

void* thread_function1(void *args)
{
    printf("Received: %d\n", (int)args);
    print("Thread");
    pthread_cleanup_push(handler, "hello");
    pthread_cleanup_pop(1);
    printf("Thread Done\n");    
    return (void *) 0;
}

int main(void)
{
    pthread_t tid1, tid2;
    void *tret;
    if(pthread_create(&tid1, NULL, thread_function1, (void *)1))
        exit(1);
    if(pthread_create(&tid2, NULL, thread_function1, (void *)2))
        exit(1);
//  pthread_join(tid2, &tret);
//  pthread_join(tid1, &tret);
}

此代码的问题在于 main 在 thread_function1 完成执行之前完成了它的执行。如果两个注释都被删除,则 thread 2 仅在 thread 1 完成执行后才执行。

我想要做的是让 thread 1thread 2 同时执行,main 应该等待两个线程完成。

最佳答案

The problem with this code is that the main completes its execution before thread_function1 could complete its execution.

那是因为当主线程退出时,进程死亡,包括所有线程。您可以改为从主线程调用 pthread_exit(0),以便其余线程继续执行并退出主线程。

If both the comments are removed then thread 2 is executed only after thread 1 has completeted its execution.

那不是真的。即 tid1tid2 在创建后同时执行(“同时执行”取决于您的硬件、调度策略等——但就您的程序而言,它们可以认为是同时执行)。 pthread_join() 不控制线程的执行顺序。它只影响主线程等待线程完成的顺序,即主线程首先等待tid2完成,然后等待tid1(如果您对这两行进行注释)。

关于并发多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40448786/

相关文章:

c - 获取要打印到屏幕的 arrayDisplay()_fucntion,这是一个已使用 srand() 填充的数组。

c - 我是否转换 malloc 的结果?

c++ - 如何通过阻塞调用来控制线程的执行

python - 多处理的queue.get()什么时候返回DONE?

java - Java中线程的初始化

c - 线程函数时序

c - pthread_create 中的多个参数

c - 关于处理scanf无效输入的问题

c - 当结构中的指针指向结构本身时,C 如何解析循环定义?

c - 等待所有线程计时器回调完成的安全方法