標籤:參數 errno.h 建立 for exit()函數 rgs failed div 返回
//線程間的通訊#include <stdio.h>#include <stdlib.h>#include <string.h>#include <errno.h>#include <unistd.h>#include <pthread.h>/*線程1與控制線程通訊方法1--全域變數*/int g_num=10;void *thread_run(void *arg){ //線程1被分離了,但最好不要使用pthread_join()函數接受,多線程下報錯記憶體溢出 pthread_detach(pthread_self()); int *p=(int *)arg; (*p)++; g_num=12; /*線程1與控制線程通訊方法2--pthread_exit()函數的參數*/ //pthread_exit(p); //執行pthread_exit()函數後,線程會直接退出 printf("線程1退出了!\n"); /*線程1與控制線程通訊方法3--線程中return*/ return p;}int main(int arg,char *args[]){ /* * 每個線程都擁有各自的棧記憶體,但是彼此之間的棧記憶體是可以互相訪問, * 比如在控制線程定義的變數,可以線上程1中訪問 * 線程1中定義變數可能無法在控制線程訪問,因為無法確定變數是否因為線程執行完畢被釋放了 * */ int index=0; pthread_t thr1; if(pthread_create(&thr1,NULL,thread_run,&index)!=0) { printf("pthread_create() failed !\n"); return -1; } //等待線程1 int *p=NULL; pthread_join(thr1,(void **)&p); printf("線程1的傳回值%d\n",*p); printf("控制線程的index=%d\n",index); printf("g_num=%d\n",g_num); return 0;}
//線程的並存執行#include <stdio.h>#include <stdlib.h>#include <string.h>#include <errno.h>#include <unistd.h>#include <pthread.h>void *thread_run(void *arg){ //pthread_detach(pthread_self()); if (arg != NULL) { int *p = (int *) arg; int i = 0; for (i = 0; i < *p; i++) { printf("這是線程%d的第%d圈!\n", (int) pthread_self(), i); sleep(1); } } return NULL;}int main(int arg, char *args[]){ int i = 0; int num1 = 10; int num2 = 10; printf("請輸入建立線程的個數:\n"); scanf("%d", &num1); printf("請輸入每個線程的圈數:\n"); scanf("%d", &num2); pthread_t thrs[200]; /* * 多線程是並行啟動並執行 * */ for (i = 0; i < num1; i++) { if (pthread_create(&thrs[i], NULL, thread_run, &num2) != 0) { printf("pthread_create() failed !\n"); return -1; } } for (i = 0; i < num1; i++) { /*如果沒有pthread_join(),那麼控制線程不會等待子線程,會直接退出*/ pthread_join(thrs[i],NULL); } return 0;}
Linux 進程與線程六