【多线程例子】c语言写一个多线程案例

您所在的位置:网站首页 线程的线怎么写 【多线程例子】c语言写一个多线程案例

【多线程例子】c语言写一个多线程案例

2023-08-11 15:01| 来源: 网络整理| 查看: 265

第一个多线程程序 #include #include //定义线程要执行的函数,arg 为接收线程传递过来的数据 void *Thread1(void *arg) { printf("http://c.biancheng.net\n"); return "Thread1成功执行"; } //定义线程要执行的函数,arg 为接收线程传递过来的数据 void* Thread2(void* arg) { printf("C语言中文网\n"); return "Thread2成功执行"; } int main() { int res; pthread_t mythread1, mythread2; void* thread_result; /*创建线程 &mythread:要创建的线程 NULL:不修改新建线程的任何属性 ThreadFun:新建线程要执行的任务 NULL:不传递给 ThreadFun() 函数任何参数 返回值 res 为 0 表示线程创建成功,反之则创建失败。 */ res = pthread_create(&mythread1, NULL, Thread1, NULL); if (res != 0) { printf("线程创建失败"); return 0; } res = pthread_create(&mythread2, NULL, Thread2, NULL); if (res != 0) { printf("线程创建失败"); return 0; } /* 等待指定线程执行完毕 mtThread:指定等待的线程 &thead_result:接收 ThreadFun() 函数的返回值,或者接收 pthread_exit() 函数指定的值 返回值 res 为 0 表示函数执行成功,反之则执行失败。 */ res = pthread_join(mythread1, &thread_result); //输出线程执行完毕后返回的数据 printf("%s\n", (char*)thread_result); res = pthread_join(mythread2, &thread_result); printf("%s\n", (char*)thread_result); printf("主线程执行完毕"); return 0; }

假设我们将程序编写在 thead.c 文件中,调用 gcc 编译器编译(包含链接)此程序:

[root@localhost ~]# gcc thread.c -o thread.exe -lpthread

在保证程序没有语法错误的前提下,执行此命令会生成一个名为 thread.exe 的可执行文件。需要强调的是,命令中必须包含 “-plthread” 参数,否则会导致程序链接失败。

在当前目录下找到新生成的 thread.exe 文件,执行如下命令即可看到程序的执行结果:

[root@localhost ~]# ./thead.exe http://c.biancheng.net C语言中文网 Thread1成功执行 Thread2成功执行 主线程执行完毕

程序中共存在 3 个线程,包括本就存在的主线程以及两个调用 pthread_create() 函数创建的线程(又称子线程),其中名为 mythread1 的线程负责执行 thread1() 函数,名为 mythread2 的线程负责执行 thread2() 函数。

程序中调用了两次 pthread_join() 函数,第 47 行 pthread_join() 函数的功能是令主线程等待 mythread1 线程执行完毕后再执行后续的代码,第 51 行处 pthread_join() 函数的功能是令主线程等待 mythread2 线程执行完毕后在执行后续的代码。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3