循序渐进学unix——上机记录(八),Thread
本次上机主题为线程。一个程序可以包含多个进程,而一个进程又可以创建多个线程,每个线程都共享此进程的上下文环境。
在unix下使用gcc编译带有线程操作的程序时需要加上 -pthread选项。
基本的线程函数:
#include <pthread.h>
创建线程:后两个参数为待调用的函数及传递的参数
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);在进程中等待相应线程的结束:
int pthread_join(pthread_t thread, void **retval);
1,创建一个能实现两数相加的线程,使用3个线程实现(a + b) * (c + d)/(e + f)。为此,我们使用一个结构体传递加数及结果:
typedef struct _Calcul { float op1, op2, result; } Calcul;
/*The barrier is a way to synchronise threads during their executions,while pthread_join(), which is called in the body of the process,only synchronize the end of threads.pthread_barrier_t barrier;pthread_barrier_init(&barrier, NULL, THREAD_NUM);// Init the barrier with a number.pthread_barrier_wait(&barrier);//The calling thread can continue only if there areTHREAD_NUM threads who call this method.pthread_barrier_destroy(&barrier);*/#include<stdio.h>#include<stdlib.h>#include<errno.h>#include<unistd.h>#include<pthread.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#define THREAD_NUM 5pthread_barrier_t barrier;void travailler( ){int duree = ((int)random())%5+1;int threadid=pthread_self();printf("Pthread %d a une tache de %d seconds.\n", threadid, duree);int i = 0;for(;i<duree;i++){//If we put wait here, when a thread terminates, all others will be //suspended, because there will nerver be enough threads who call wait()//pthread_barrier_wait(&barrier);printf("Pthread %d, second %d.\n", threadid, i);sleep(1);}pthread_barrier_wait(&barrier);printf("Pthread %d termine.\n", threadid);}void main(){int val_return;pthread_t ptrs[THREAD_NUM];pthread_barrier_init(&barrier, NULL, THREAD_NUM);int i = 0;for(;i<THREAD_NUM;i++){if( (val_return=pthread_create(ptrs+i, NULL, (void*)travailler, NULL)) != 0){perror("pthread_create");exit(1);}}for(i=0;i<THREAD_NUM;i++){pthread_join( ptrs[i], NULL);//Si le proc termine, les threads sont aussi terminésprintf("Join thread %d .\n", i);}//pthread_barrier_destroy(&barrier);}