term在c语言多线程编程中的应用

   2024-09-30 3830
核心提示:在C语言多线程编程中,term 通常是指线程(thread)的终止以下是一个使用POSIX线程库(pthread)创建两个线程并在主线程中等待它

在C语言多线程编程中,term 通常是指线程(thread)的终止

以下是一个使用POSIX线程库(pthread)创建两个线程并在主线程中等待它们完成的示例:

#include<stdio.h>#include <stdlib.h>#include <pthread.h>void* thread_function(void *arg) {    int id = *((int*)arg);    printf("Thread %d is running.\n", id);    sleep(1); // 模拟线程执行时间    printf("Thread %d has finished.\n", id);    return NULL;}int main() {    pthread_t thread1, thread2;    int id1 = 1, id2 = 2;    // 创建线程1    if (pthread_create(&thread1, NULL, thread_function, &id1) != 0) {        perror("Failed to create thread 1");        exit(1);    }    // 创建线程2    if (pthread_create(&thread2, NULL, thread_function, &id2) != 0) {        perror("Failed to create thread 2");        exit(1);    }    // 等待线程1和线程2完成    pthread_join(thread1, NULL);    pthread_join(thread2, NULL);    printf("All threads have finished.\n");    return 0;}

在这个示例中,我们创建了两个线程并分别传递了不同的参数。当主线程调用 pthread_join() 函数时,它会等待指定的线程完成。在这种情况下,主线程将等待线程1和线程2完成,然后输出 “All threads have finished.”。

请注意,这个示例使用了POSIX线程库(pthread),这是Linux和其他Unix-like系统上的一个常见线程库。在Windows上,可以使用Windows API或其他线程库(如C++11的` 库)实现类似的功能。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号