简单的例子是最好的学习方式:
example 1,从书上摘录的
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<pthread.h> #include<string.h> void *thr_fn1(void *arg){ printf("thread 1 returning\n"); return((void*)1); } void *thr_fn2(void *arg){ printf("thread 2 exiting\n"); pthread_exit((void*)2); } int main(){ int err; pthread_t tid1,tid2; void *tret; err = pthread_create(&tid1,NULL,thr_fn1,NULL); if (err != 0) printf("can't create thread 1:%s\n",strerror(err)); err = pthread_create(&tid2,NULL,thr_fn2,NULL); if (err != 0) printf("can't create thread 2:%s\n",strerror(err)); err = pthread_join(tid1,&tret); if (err != 0) printf("can't join with thread 1:%s\n",strerror(err)); printf("thread 1 exit code %d\n",(int)tret); err = pthread_join(tid2,&tret); if (err != 0) printf("can't join with thread 2:%s\n",strerror(err)); printf("thread 2 exit code %d\n",(int)tret); exit(0); }
example 2: 自己写的,刚接触pthread时写的,忘记了当初想验证什么,
#include <stdio.h> #include <pthread.h> const int thread_num = 4; static int array[8]; void * print(void *arg){ // int id = * (int *)arg; int id = (int )arg; printf("thread %d it's sequn is %d\n", (int)pthread_self(), id); array[id] = id+100; return (void *)(&array[id]); // return (void *)(array[id]); } int main(int argc, char *argv[]){ int i; pthread_t tid[thread_num]; for(i=0; i<thread_num; i++){ pthread_create(&tid[i], NULL, print, (void *)i); // pthread_create(&tid[i], NULL, print, (void *)&i); } void *ret; for(i=0; i<thread_num; i++){ // pthread_join(tid[i], NULL); pthread_join(tid[i], &ret); printf("ret value = %d\n", *(int*)ret); // printf("ret value = %d\n", (int)ret); } return 0; }
给自己看的,做个纪念。。。