1 、创建线程,使用pthread_create 函数创建新线程,并使用结构体传递了多个参数
codes:
root@ubuntu:/code/chap10# cat test1.c #include<pthread.h> #include<stdio.h> #include<stdlib.h> #include<string.h> struct message { int i; int j; }; void * hello(struct message* str) { printf("the arg.i is %d/n",str->i); printf("the arg.j is %d/n",str->j); } int main() { pthread_t thread_id; struct message test; test.i=10; test.j=20; pthread_create(&thread_id,NULL,(void*)*hello,&test); printf("the new thread id is %u/n",thread_id); pthread_join(thread_id,NULL); return 0; }
结果:
root@ubuntu:/code/chap10# ./run1 the new thread id is 2858739472 the arg.i is 10 the arg.j is 20
2、线程间同步--互斥锁
主线程负责从标准输入设备中读取数据存储在全局数据区,另一个线程负责将读入的数据输出到stdout。全局数据区加互斥锁。
codes:
root@ubuntu:/code# cat test1.c #include<stdio.h> #include<unistd.h> #include<stdlib.h> #include<pthread.h> #include<semaphore.h> #include<string.h> void * thread_function(void * arg); pthread_mutex_t work_mutex; //全局互斥锁对象 #define WORK_SIZE 1024 char work_area[WORK_SIZE]; int time_to_exit=0; int main() //主线程负责输入 { int res=pthread_mutex_init(&work_mutex,NULL); //初始化互斥锁 if(res!=0){ perror("init"); exit(EXIT_FAILURE); } pthread_t a_thread; res=pthread_create(&a_thread,NULL,thread_function,NULL); //创建线程 if(res!=0){ perror("create"); exit(EXIT_FAILURE); } pthread_mutex_lock(&work_mutex); //加锁 printf("input/n"); while(!time_to_exit) { fgets(work_area,WORK_SIZE,stdin); pthread_mutex_unlock(&work_mutex); //解锁 while(1) //直到内容被输出 { pthread_mutex_lock(&work_mutex); if(work_area[0]=='/0'){ break; } else{ pthread_mutex_unlock(&work_mutex); sleep(1); } } } pthread_mutex_unlock(&work_mutex); void * result; res=pthread_join(a_thread,&result); //等待线程退出 if(res!=0){ perror("join"); exit(EXIT_FAILURE); } pthread_mutex_destroy(&work_mutex); exit(EXIT_SUCCESS); } void * thread_function(void * arg) //新建的线程负责 输出 { sleep(1); pthread_mutex_lock(&work_mutex); while(strncmp("end",work_area,3)!=0) { printf("the line is %s/n",work_area); work_area[0]='/0'; pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); while(work_area[0]=='/0') //直到内存中出现新的内容 { pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); } } time_to_exit=1; work_area[0]='/0'; pthread_mutex_unlock(&work_mutex); pthread_exit(0); }
结果:
root@ubuntu:/code# ./run1 input Jason the line is Jason is the line is is a the line is a cool the line is cool man the line is man end