2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
线程:进程中的一个实体,是CPU调度和分派的基本单位。线程自己基本上不拥有系统资源,只拥有一点在运行中必不可少的资源(如程序计数器、一组寄存器和栈),但它可以与同属一个进程的其他线程共享进程所拥有的全部资源。一个线程可以创建和撤销另一个线程;同一个进程中的多个线程之间可以并发执行。线程在运行中呈现间断性。(以上来自《计算机四级教程——操作系统原理》)
谈到线程,就有必要说说进程的定义:进程是具有一定独立功能的程序关于某个数据集合上的一次运行活动,进程是系统进行资源分配和调度的一个独立单位。(以上来自《计算机四级教程——操作系统原理》)
进程的定义有点绕口,我们看看进程由什么组成:程序、数据和进程控制块。其中程序,对应进程定义中“具有一定独立功能的程序”,但是进程除了程序本身,还需要有数据(可以理解为资源),以及,进程控制块。数据和进程控制块是程序运行时必不可少的资源,程序依赖这些资源进行相应的活动,就是我们说的“进程”了。
进程的两个基本属性:
进程是一个可拥有资源的独立单位;
进程是一个可以独立调度和分派的基本单位。
线程建立之初,就是为了将进程的上述两个属性分开,线程构成了“CPU调度和分派的基本单位”,这样一个进程中可以有很多线程,操作系统对线程进行调度和分派,可以更好地实现进程的并打执行;同时同一个进程下的线程可以共享该进程的全部资源,可以满足同一个进程下不同线程对进程资源的访问。线程的出现,巧妙地将进程的两个属性分开,使得进程可以更好地处理并行执行的需求。
线程就是一个正在运行的函数。posix线程是一套标准,而不是一套实现。还有别的标准如:openmp线程。
线程标识:pthread_t (不知道具体的内容,各家实现不同,linux下是int)
px axm命令 看到进程和线程--代表进程下的线程。 px ax -L查看轻量级线程。
int pthread_equal(pthread_t t1, pthread_t t2); 比较两个线程的ID号。相同返回非0,不同返回0.
pthread_t pthread_self(void); 获取当前线程的线程ID
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
线程的调度取决与调度器的策略。
- #include <stdlib.h>
- #include <stdio.h>
- #include <pthread.h>
- #include <string.h>
-
- void* myfunc(void *p)
- {
- puts("Thread is run!");
-
- printf("thread %ld n",pthread_self());
- return NULL;
- }
-
- int main()
- {
- puts("Begin!");
- pthread_t tid;
- int ret;
- ret = pthread_create(&tid,NULL,myfunc ,NULL);
- if(ret)
- {
- fprintf(stderr,"%s n",strerror(ret));
- exit(1);
- }
- printf("main %ld n",pthread_self());
-
-
-
- puts("End!");
- }
1.线程从启动例程返回,返回值就是线程的退出码。
2. 线程可以被同一进程中的其他线程取消。
3.线程调用pthread_exit()函数。 void pthread_exit(void *retval);
int pthread_join(pthread_t thread, void **retval); 相当于进程的wait,用于收尸。
- #include <stdlib.h>
- #include <stdio.h>
- #include <pthread.h>
- #include <string.h>
-
- void* myfunc(void *p)
- {
- puts("Thread is run!");
-
- pthread_exit(NULL);//线程专用清理函数。
- // return NULL;
- }
-
-
- int main()
- {
- puts("Begin!");
- pthread_t tid;
- int ret;
- ret = pthread_create(&tid,NULL,myfunc ,NULL);
- if(ret)
- {
- fprintf(stderr,"%s n",strerror(ret));
- exit(1);
- }
- pthread_join(tid,NULL); //收尸
-
- puts("End!");
- }
pthread_cleanup_push(); //相当于atexit
pthread_cleanup_pop(); //相当于可以主动取数据。
void pthread_cleanup_push(void (*routine)(void *), 是宏的实现,gcc -E查看预处理
void *arg);
void pthread_cleanup_pop(int execute); //选择是否调用。必须成对出现,用宏实现
- #include <stdlib.h>
- #include <stdio.h>
- #include <pthread.h>
- #include <string.h>
-
-
- void cleanup_fun(void*p)
- {
- puts(p);
- }
-
- void* myfunc(void *p)
- {
- puts("Thread is run!");
-
- pthread_cleanup_push(cleanup_fun,"cleanup:1");
- pthread_cleanup_push(cleanup_fun,"cleanup:2");
- pthread_cleanup_push(cleanup_fun,"cleanup:3");
-
- puts("push over!");
-
-
-
- pthread_exit(NULL);//线程专用清理函数。
- // return NULL;
- pthread_cleanup_pop(1) //线程退出后,全部都会调用;
- pthread_cleanup_pop(0);
- pthread_cleanup_pop(1);
- }
-
-
- int main()
- {
- puts("Begin!");
- pthread_t tid;
- int ret;
- ret = pthread_create(&tid,NULL,myfunc ,NULL);
- if(ret)
- {
- fprintf(stderr,"%s n",strerror(ret));
- exit(1);
- }
- pthread_join(tid,NULL); //收尸
-
- puts("End!");
- }
正在运行的线程要是想要收尸收回来,那么就需要先进行取消(pthread_cancel)在进行收尸(pthread_join)。
线程取消:int pthread_cancel(pthread_t thread);
取消有两种状态:允许和不允许。
不允许取消:继续执行代码,不受任何影响。
允许取消又分为:异步cancel,和推迟cancel(默认)->推迟到cancel点在响应。
cancal点:Posix定义的cancel点,都是可能引发堵塞的系统调用。
pthread_setcancelstate:可以设置取消状态。
pthread_setcanceltype:可以设置取消方式。
pthread_testcancel:函数什么都不做,就是取消点。
线程分离: int pthread_detach(pthread_t thread);
动态模块单次初始化函数:int pthread_once(pthread_once_t *once_control,
void (*init_routine)(void));
pthread_once_t once_control = PTHREAD_ONCE_INIT;
- #include <stdlib.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <string.h>
- #include <pthread.h>
- #define LEFT 30000000
- #define RIGHT 30000200
- #define THRNUM (RIGHT-LEFT+1)
-
- void* thr_prime(void*p);
-
- int main()
- {
- pthread_t tid[THRNUM];
- int i,j,mark;
- int err;
- for(i =LEFT;i<=RIGHT;i++)
- {
- err= pthread_create(tid+(i-LEFT),NULL,thr_prime,&i);
- if(err)
- {
- fprintf(stderr,"pthread_create():%sn",strerror(err));
- }
- }
-
- for(i=LEFT;i<=RIGHT;i++)
- {
- pthread_join(tid[i-LEFT],NULL);
- }
-
- return 0;
- }
-
- void* thr_prime(void*p)
- {
- int i,j,mark;
-
- i = *(int*)p;
-
- mark = 1;
- for(j=2;j<i/2;j++)
- {
- if(i%j ==0)
- {
- mark = 0;
- break;
- }
- }
- if(mark)
- printf("%d is a primer n",i);
- pthread_exit(NULL);
- return NULL;
- }
以上代码运行会出现竞争的现象。因为传递参数用的是地址传参,数据需要取*才能拿到,不能保证上一个线程是否进行了该操作,最简单的是使用值传递。
primer0.c
- #include <stdlib.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <string.h>
- #include <pthread.h>
- #define LEFT 30000000
- #define RIGHT 30000200
- #define THRNUM (RIGHT-LEFT+1)
-
- void* thr_prime(void*p);
-
- int main()
- {
- pthread_t tid[THRNUM];
- int i,j,mark;
- int err;
- for(i =LEFT;i<=RIGHT;i++)
- {
- err= pthread_create(tid+(i-LEFT),NULL,thr_prime,(void *)i);
- // err= pthread_create(tid+(i-LEFT),NULL,thr_prime,&i);
- if(err)
- {
- fprintf(stderr,"pthread_create():%sn",strerror(err));
- }
- }
-
- for(i=LEFT;i<=RIGHT;i++)
- {
- pthread_join(tid[i-LEFT],NULL);
- }
-
- return 0;
- }
-
- void* thr_prime(void*p)
- {
- int i,j,mark;
-
- i = (int)p;
- // i = *(int*)p;
-
- mark = 1;
- for(j=2;j<i/2;j++)
- {
- if(i%j ==0)
- {
- mark = 0;
- break;
- }
- }
- if(mark)
- printf("%d is a primer n",i);
- pthread_exit(NULL);
- return NULL;
- }
primer0_e.c
- #include <stdlib.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <string.h>
- #include <pthread.h>
-
- #define LEFT 30000000
- #define RIGHT 30000200
- #define THRNUM (RIGHT-LEFT+1)
-
- struct thr_arg_st
- {
- int n;
- };
-
- void* thr_prime(void*p);
-
- int main()
- {
- pthread_t tid[THRNUM];
- int i,j,mark;
- int err;
- struct thr_arg_st* p;
- void *ptr;
- for(i =LEFT;i<=RIGHT;i++)
- {
- p = malloc(sizeof(*p));
- if(p ==NULL)
- {
- perror("malloc");
- exit(1);
- }
- p->n = i;
- err= pthread_create(tid+(i-LEFT),NULL,thr_prime,p); // p就是结构体指针就是n的地址
- // err= pthread_create(tid+(i-LEFT),NULL,thr_prime,&i);
- if(err)
- {
- fprintf(stderr,"pthread_create():%sn",strerror(err));
- }
- //free 不能在这里free,必须取走数据在free
- }
-
- for(i=LEFT;i<=RIGHT;i++)
- {
- pthread_join(tid[i-LEFT],&ptr);// 收尸并且接受返回参数。
- free(ptr);
-
- }
-
- return 0;
- }
-
- void* thr_prime(void*p)
- {
- int i,j,mark;
-
- i = ((struct thr_arg_st*)p)->n;
-
- mark = 1;
- for(j=2;j<i/2;j++)
- {
- if(i%j ==0)
- {
- mark = 0;
- break;
- }
- }
- if(mark)
- printf("%d is a primer n",i);
- pthread_exit(p); //返回值返回p
- return NULL;
- }
add.c
- #include <stdlib.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <string.h>
- #include <pthread.h>
-
- #define FILENAME "/tmp/out"
- #define THRNUM (20)
-
- void* thr_add(void*p);
-
- int main()
- {
- pthread_t tid[THRNUM];
- int i,j,mark;
- int err;
- for(i =0;i<=THRNUM;i++)
- {
- err= pthread_create(tid+(i),NULL,thr_add,NULL);
- if(err)
- {
- fprintf(stderr,"pthread_create():%sn",strerror(err));
- }
- }
-
- for(i=0;i<=THRNUM;i++)
- {
- pthread_join(tid[i],NULL);
- }
-
- return 0;
- }
-
- void* thr_add(void*p)
- {
- FILE*fp;
- char line_buf[1024];
- int len_size = 1024;
- fp = fopen(FILENAME,"r+");
-
- fgets(line_buf,len_size,fp);
-
- fseek(fp,0,SEEK_SET);
-
- fprintf(fp,"%d n",atoi(line_buf)+1);
-
- fclose(fp);
-
- pthread_exit(NULL);
-
- return NULL;
- }
二十个线程同时在一个文件中读数据写数据时会出现竞争和冲突。一个线程还没有写进入时,另一个线程读到了上次的数据。
- #include <stdlib.h>
- #include <stdio.h>
- #include <error.h>
- #include <string.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <errno.h>
- #include <signal.h>
- #include <pthread.h>
-
- #include "mytbf.h"
-
- struct mytbf_st
- {
- int cps;
- int burst;
- int token;
- int pos;
- pthread_mutex_t mut;
- };
- static pthread_mutex_t mut_job = PTHREAD_MUTEX_INITIALIZER;
- static pthread_t tid_alrm;
- pthread_once_t init_once = PTHREAD_ONCE_INIT;
-
- static struct mytbf_st* job[MYTBF_MAX];
-
- typedef void (*sighandler_t)(int);
-
-
- static int get_free_pos_unlocked(void)
- {
- for(int i=0;i< MYTBF_MAX;i++)
- {
- if(job[i]==NULL)
- return i;
- }
- return -1;
- }
-
- static void* thr_alrm(void*p)
- {
- while(1)
- {
- pthread_mutex_lock(&mut_job);
- for(int i=0;i<MYTBF_MAX;i++)
- {
- if(job[i] != NULL)
- {
- pthread_mutex_lock(&job[i]->mut);
- job[i]->token += job[i]->cps;
- if(job[i]->token >job[i]->burst )
- {
- job[i]->token = job[i]->burst;
- }
- pthread_mutex_unlock(&job[i]->mut);
- }
- }
- pthread_mutex_unlock(&mut_job);
- sleep(1);
- }
- return NULL;
- }
-
- static void module_unload()
- {
- pthread_cancel(tid_alrm);
- pthread_join(tid_alrm,NULL);
- //只能一个人掉,二个人调用容易出差
- for(int i=0;i<MYTBF_MAX;i++)
- {
- if(job[i]!=NULL)
- {
- mytbf_destroy(job[i]);
- }
- }
- pthread_mutex_destroy(&mut_job);
-
- }
-
- static void module_load()
- {
- int err;
- err = pthread_create(&tid_alrm,NULL,thr_alrm,NULL);
- if(err)
- {
- fprintf(stderr,"create errorn");
- exit(1);
- }
- atexit(module_unload);
- }
-
- mytbf_t* mytbf_init(int cps ,int burst) //C语言中,void*可以赋值给任何类型的指针,任何类型的指针也都可以赋值给void*
- {
- struct mytbf_st*me;
- int pos;
- pthread_once(&init_once,module_load); //只初始化一次
- me = malloc(sizeof(*me));
- if(me == NULL)
- return NULL;
-
- me->cps = cps;
- me->burst = burst;
- me->token = 0;
-
- pthread_mutex_init(&me->mut,NULL);
-
- pthread_mutex_lock(&mut_job);
-
- pos = get_free_pos_unlocked();
- if(pos < 0)
- {
-
- pthread_mutex_unlock(&mut_job);
- free(me);
- return NULL;
- }
- me->pos = pos;
- job[pos] = me;
-
- pthread_mutex_unlock(&mut_job);
-
- return me;
-
- }
- int mytbf_fetchtoken(mytbf_t*ptr,int size) //获取token
- {
- if(size <= 0)
- return -EINVAL; //参数非法
- struct mytbf_st*me = ptr;
- pthread_mutex_lock(&me->mut);
- while(me->token <= 0 ) //token为空就等待
- {
- pthread_mutex_unlock(&me->mut);
- sched_yield();
- pthread_mutex_lock(&me->mut);
- }
-
- int n = (me->token>size?size:me->token);
- me->token -= n;
- pthread_mutex_unlock(&me->mut);
- return n;
- }
-
- int mytbf_returntoken(mytbf_t*ptr,int size) //返还token
- {
- if(size<=0)
- return -EINVAL;
- struct mytbf_st*me = ptr;
-
- pthread_mutex_lock(&me->mut);
-
- me->token+= size;
- if(me->token > me->burst)
- me->token = me->burst;
-
- pthread_mutex_unlock(&me->mut);
- return size;
- }
-
- int mytbf_destroy(mytbf_t*ptr)
- {
- struct mytbf_st *me;
- me = ptr;
- pthread_mutex_lock(&mut_job);
- job[me->pos] = NULL;
- pthread_mutex_unlock(&mut_job);
- pthread_mutex_destroy(&me->mut);
- free(ptr);
- return 0;
-
- }
相当于一把锁,必须先进行解锁才能操作。(查询法)
如果man pthread_mutex_init报错,请安装依赖:
sudo apt-get install manpages-posix manpages-posix-dev
int pthread_mutex_destroy(pthread_mutex_t *mutex); //销毁锁
int pthread_mutex_init(pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr); 动态初始化
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; 静态初始化
int pthread_mutex_lock(pthread_mutex_t *mutex); //加锁
int pthread_mutex_trylock(pthread_mutex_t *mutex);//尝试加锁,抢不上就继续执行
int pthread_mutex_unlock(pthread_mutex_t *mutex);//解锁
add.c
- #include <stdlib.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <string.h>
- #include <pthread.h>
-
- #define FILENAME "/tmp/out"
- #define THRNUM (20)
-
- pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
-
- void* thr_add(void*p);
-
- int main()
- {
- pthread_t tid[THRNUM];
- int i,j,mark;
- int err;
- for(i =0;i<THRNUM;i++)
- {
- err= pthread_create(tid+(i),NULL,thr_add,NULL);
- if(err)
- {
- fprintf(stderr,"pthread_create():%sn",strerror(err));
- }
- }
-
- for(i=0;i<THRNUM;i++)
- {
- pthread_join(tid[i],NULL);
- }
- pthread_mutex_destroy(&mut);
- return 0;
- }
-
- void* thr_add(void*p)
- {
- FILE*fp;
- char line_buf[1024];
- int len_size = 1024;
-
- pthread_mutex_lock(&mut);
-
-
- fp = fopen(FILENAME,"r+");
- fgets(line_buf,len_size,fp);
-
- fseek(fp,0,SEEK_SET);
-
- fprintf(fp,"%d n",atoi(line_buf)+1);
- fclose(fp);
- pthread_mutex_unlock(&mut);
-
- pthread_exit(NULL);
-
- return NULL;
- }
abcd.c
- #include <stdlib.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <string.h>
- #include <pthread.h>
-
- #define FILENAME "/tmp/out"
- #define THRNUM (4)
-
- pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
-
- void* thr_abcd(void*p);
-
- int main()
- {
- pthread_t tid[THRNUM];
- int i,j,mark;
- int err;
- for(i =0;i<THRNUM;i++)
- {
- err= pthread_create(tid+(i),NULL,thr_abcd,(void*)i);
- if(err)
- {
- fprintf(stderr,"pthread_create():%sn",strerror(err));
- }
- }
- alarm(2);
-
- for(i=0;i<THRNUM;i++)
- {
- pthread_join(tid[i],NULL);
- }
- pthread_mutex_destroy(&mut);
- return 0;
- }
-
- void* thr_abcd(void*p)
- {
- int c = 'a'+ (int)p;
- while(1)
- {
- write(1,&c,1);
- }
-
- pthread_exit(NULL);
-
- return NULL;
- }
abcd.c
使用锁链进行加锁解锁。
- #include <stdlib.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <string.h>
- #include <pthread.h>
-
- #define FILENAME "/tmp/out"
- #define THRNUM (4)
-
- pthread_mutex_t mut[THRNUM];
-
- void* thr_abcd(void*p);
-
- int main()
- {
- pthread_t tid[THRNUM];
- int i,j,mark;
- int err;
- for(i =0;i<THRNUM;i++)
- {
- pthread_mutex_init(mut+i,NULL); //初始化四个锁
- pthread_mutex_lock(mut+i);
-
- err= pthread_create(tid+(i),NULL,thr_abcd,(void*)i);
- if(err)
- {
- fprintf(stderr,"pthread_create():%sn",strerror(err));
- }
- }
- pthread_mutex_unlock(mut+0);
- alarm(2);
-
- for(i=0;i<THRNUM;i++)
- {
- pthread_join(tid[i],NULL);
- }
- pthread_mutex_destroy(&mut);
- return 0;
- }
- int next(int n)
- {
- if(n +1 ==THRNUM)
- return 0;
- return n+1;
- }
- void* thr_abcd(void*p)
- {
- int c = 'a'+ (int)p;
- int n = (int)p;
- while(1)
- {
- pthread_mutex_lock(mut+n);
- write(1,&c,1);
- pthread_mutex_unlock(mut+next(n) );
- }
- pthread_exit(NULL);
-
- return NULL;
- }
池类算法实现算质数(查询法)
- #include <stdlib.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <string.h>
- #include <pthread.h>
- #define LEFT 30000000
- #define RIGHT 30000200
- #define THRNUM (RIGHT-LEFT+1)
-
- void* thr_prime(void*p);
-
- int main()
- {
- pthread_t tid[THRNUM];
- int i,j,mark;
- int err;
- for(i =LEFT;i<=RIGHT;i++)
- {
- err= pthread_create(tid+(i-LEFT),NULL,thr_prime,(void *)i);
- // err= pthread_create(tid+(i-LEFT),NULL,thr_prime,&i);
- if(err)
- {
- fprintf(stderr,"pthread_create():%sn",strerror(err));
- }
- }
-
- for(i=LEFT;i<=RIGHT;i++)
- {
- pthread_join(tid[i-LEFT],NULL);
- }
-
- return 0;
- }
-
- void* thr_prime(void*p)
- {
- int i,j,mark;
-
- i = (int)p;
- // i = *(int*)p;
-
- mark = 1;
- for(j=2;j<i/2;j++)
- {
- if(i%j ==0)
- {
- mark = 0;
- break;
- }
- }
- if(mark)
- printf("%d is a primer n",i);
- pthread_exit(NULL);
- return NULL;
- }
通知法进行通信。
int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_cond_init(pthread_cond_t *restrict cond,
const pthread_condattr_t *restrict attr);
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int pthread_cond_broadcast(pthread_cond_t *cond); //叫醒所有的等待
int pthread_cond_signal(pthread_cond_t *cond);//叫醒任意一个等待
int pthread_cond_timedwait(pthread_cond_t *restrict cond, //超时等待
pthread_mutex_t *restrict mutex,
const struct timespec *restrict abstime);
int pthread_cond_wait(pthread_cond_t *restrict cond, //死等
pthread_mutex_t *restrict mutex);
mytbf.c(通知法)
- #include <stdlib.h>
- #include <stdio.h>
- #include <error.h>
- #include <string.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <errno.h>
- #include <signal.h>
- #include <pthread.h>
-
- #include "mytbf.h"
-
- struct mytbf_st
- {
- int cps;
- int burst;
- int token;
- int pos;
- pthread_mutex_t mut;
- pthread_cond_t cond;
-
- };
- static pthread_mutex_t mut_job = PTHREAD_MUTEX_INITIALIZER;
- static pthread_t tid_alrm;
- pthread_once_t init_once = PTHREAD_ONCE_INIT;
-
- static struct mytbf_st* job[MYTBF_MAX];
-
- typedef void (*sighandler_t)(int);
-
-
- static int get_free_pos_unlocked(void)
- {
- for(int i=0;i< MYTBF_MAX;i++)
- {
- if(job[i]==NULL)
- return i;
- }
- return -1;
- }
-
- static void* thr_alrm(void*p)
- {
- while(1)
- {
- pthread_mutex_lock(&mut_job);
- for(int i=0;i<MYTBF_MAX;i++)
- {
- if(job[i] != NULL)
- {
- pthread_mutex_lock(&job[i]->mut);
- job[i]->token += job[i]->cps;
- if(job[i]->token >job[i]->burst )
- {
- job[i]->token = job[i]->burst;
- }
- pthread_cond_broadcast(&job[i]->cond);
- pthread_mutex_unlock(&job[i]->mut);
- }
- }
- pthread_mutex_unlock(&mut_job);
- sleep(1);
- }
- return NULL;
- }
-
- static void module_unload()
- {
- pthread_cancel(tid_alrm);
- pthread_join(tid_alrm,NULL);
- //只能一个人掉,二个人调用容易出差
- for(int i=0;i<MYTBF_MAX;i++)
- {
- if(job[i]!=NULL)
- {
- mytbf_destroy(job[i]);
- }
- }
- pthread_mutex_destroy(&mut_job);
-
- }
-
- static void module_load()
- {
- int err;
- err = pthread_create(&tid_alrm,NULL,thr_alrm,NULL);
- if(err)
- {
- fprintf(stderr,"create errorn");
- exit(1);
- }
- atexit(module_unload);
- }
-
- mytbf_t* mytbf_init(int cps ,int burst) //C语言中,void*可以赋值给任何类型的指针,任何类型的指针也都可以赋值给void*
- {
- struct mytbf_st*me;
- int pos;
- pthread_once(&init_once,module_load); //只初始化一次
- me = malloc(sizeof(*me));
- if(me == NULL)
- return NULL;
-
- me->cps = cps;
- me->burst = burst;
- me->token = 0;
-
- pthread_mutex_init(&me->mut,NULL);
- pthread_cond_init(&me->cond,NULL);
- pthread_mutex_lock(&mut_job);
-
- pos = get_free_pos_unlocked();
- if(pos < 0)
- {
-
- pthread_mutex_unlock(&mut_job);
- free(me);
- return NULL;
- }
- me->pos = pos;
- job[pos] = me;
-
- pthread_mutex_unlock(&mut_job);
-
- return me;
-
- }
- int mytbf_fetchtoken(mytbf_t*ptr,int size) //获取token
- {
- if(size <= 0)
- return -EINVAL; //参数非法
- struct mytbf_st*me = ptr;
- pthread_mutex_lock(&me->mut);
- while(me->token <= 0 ) //token为空就等待
- {
- pthread_cond_wait(&me->cond,&me->mut); //解锁等待,等待conad_broadcast和conad_signal的到来
-
- /*
- pthread_mutex_unlock(&me->mut);
- sched_yield();
- pthread_mutex_lock(&me->mut);
- */
- }
-
-
- int n = (me->token>size?size:me->token);
- me->token -= n;
- pthread_mutex_unlock(&me->mut);
- return n;
- }
-
- int mytbf_returntoken(mytbf_t*ptr,int size) //返还token
- {
- if(size<=0)
- return -EINVAL;
- struct mytbf_st*me = ptr;
-
- pthread_mutex_lock(&me->mut);
-
- me->token+= size;
- if(me->token > me->burst)
- me->token = me->burst;
- pthread_cond_broadcast(&me->cond);
- pthread_mutex_unlock(&me->mut);
- return size;
- }
-
- int mytbf_destroy(mytbf_t*ptr)
- {
- struct mytbf_st *me;
- me = ptr;
- pthread_mutex_lock(&mut_job);
- job[me->pos] = NULL;
- pthread_mutex_unlock(&mut_job);
- pthread_mutex_destroy(&me->mut);
- pthread_cond_destroy(&me->cond);
- free(ptr);
- return 0;
-
- }
primer0_pool.c
- #include <stdlib.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <string.h>
- #include <pthread.h>
- #include <sched.h>
-
- #define LEFT 30000000
- #define RIGHT 30000200
- #define THRNUM (4)
-
- static int num = 0;
- static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
- static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
-
- void* thr_prime(void*p);
-
- int main()
- {
- pthread_t tid[THRNUM];
- int i,j,mark;
- int err;
-
- for(i =0;i<=THRNUM;i++)
- {
- err= pthread_create(tid+(i),NULL,thr_prime,(void *)i);
- if(err)
- {
- fprintf(stderr,"pthread_create():%sn",strerror(err));
- }
- }
- //下发任务
- for(i=LEFT;i<RIGHT;i++)
- {
- pthread_mutex_lock(&mut);
- while(num !=0) //不是0就需要等待任务被取走
- {
- pthread_cond_wait(&cond,&mut);
- }
-
- num = i; //下发任务
- pthread_cond_signal(&cond); //下游叫醒任意一个
- pthread_mutex_unlock(&mut);
- }
- pthread_mutex_lock(&mut);
- while(num!= 0)
- {
- pthread_mutex_unlock(&mut);
- sched_yield(); //出让调度器给别的线程
- }
- num = -1; //用于线程退出
- pthread_cond_broadcast(&cond);
-
- pthread_mutex_unlock(&mut);
-
- for(i=0;i<=THRNUM;i++)
- {
- pthread_join(tid[i],NULL);
- }
- pthread_mutex_destroy(&mut);
- pthread_cond_destroy(&cond);
- return 0;
- }
-
- void* thr_prime(void*p)
- {
- int i,j,mark;
- while(1)
- {
- pthread_mutex_lock(&mut);
- while(num == 0)
- {
- pthread_cond_wait(&cond,&mut);
- }
- if(num == -1)
- {
- pthread_mutex_unlock(&mut); //走到这里必须要解锁。
- break;
- }
-
- i= num;
- num = 0;
- pthread_cond_broadcast(&cond);
-
- pthread_mutex_unlock(&mut);
-
- mark = 1;
- for(j=2;j<i/2;j++)
- {
- if(i%j ==0)
- {
- mark = 0;
- break;
- }
- }
- if(mark)
- printf("[%d]%d is a primer n",(int)p,i);
- }
-
- pthread_exit(NULL);
- return NULL;
- }
abcd_cond.c
- #include <stdlib.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <string.h>
- #include <pthread.h>
-
- #define FILENAME "/tmp/out"
- #define THRNUM (4)
-
- pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
- pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
- int num;
-
- void* thr_abcd(void*p);
-
- int main()
- {
- pthread_t tid[THRNUM];
- int i,j,mark;
- int err;
- for(i =0;i<THRNUM;i++)
- {
-
- err= pthread_create(tid+(i),NULL,thr_abcd,(void*)i);
- if(err)
- {
- fprintf(stderr,"pthread_create():%sn",strerror(err));
- }
- }
-
- alarm(2);
-
- for(i=0;i<THRNUM;i++)
- {
- pthread_join(tid[i],NULL);
- }
- pthread_cond_destroy(&cond);
- pthread_mutex_destroy(&mut);
- return 0;
- }
- int next(int n)
- {
- if(n +1 ==THRNUM)
- return 0;
- return n+1;
- }
- void* thr_abcd(void*p)
- {
- int c = 'a'+ (int)p;
- int n = (int)p;
- while(1)
- {
- pthread_mutex_lock(&mut);
- while(num != n)
- {
- pthread_cond_wait(&cond,&mut);
- }
- write(1,&c,1);
- num = next(num);
- pthread_cond_broadcast(&cond);
- pthread_mutex_unlock(&mut );
- }
- pthread_exit(NULL);
-
- return NULL;
- }
互斥量是bool类型,信号量(semaphore)是int类型,使用的时候进行自减,不够就等待。
mysem.c
- #include <stdlib.h>
- #include <stdio.h>
- #include <pthread.h>
- #include <string.h>
- #include <unistd.h>
- #include "mysem.h"
-
- struct mysem_st
- {
- int value;
- pthread_mutex_t mut;
- pthread_cond_t cond;
-
- };
-
- mysem_t* mysem_init(int initval)
- {
- struct mysem_st*me;
- me = malloc(sizeof(*me));
- if(me==NULL)
- return NULL;
- me->value = initval;
- pthread_mutex_init(&me->mut,NULL);
- pthread_cond_init(&me->cond,NULL);
-
- return me;
-
- }
-
- int mysem_add(mysem_t*ptr ,int n)
- {
- struct mysem_st*me = ptr;
-
- pthread_mutex_lock(&me->mut);
-
- me->value+= n;
- pthread_cond_broadcast(&me->cond);
- pthread_mutex_unlock(&me->mut);
-
- return n;
- }
-
- int mysem_sub(mysem_t*ptr ,int n )
- {
- struct mysem_st*me = ptr;
-
- pthread_mutex_lock(&me->mut);
- while(me->value <n)
- {
- pthread_cond_wait(&me->cond,&me->mut);
- }
- me->value -=n;
-
- pthread_mutex_unlock(&me->mut);
- return n;
- }
-
- void mysem_destroy(mysem_t*ptr)
- {
- struct mysem_st*me = ptr;
- pthread_mutex_destroy(&me->mut);
- pthread_cond_destroy(&me->cond);
- free(me);
- }
-
-
-
mysem.h
- #ifndef MYSEM_H
- #define MYSEM_H
-
- typedef void mysem_t;
-
- mysem_t* mysem_init(int initval);
-
- int mysem_add(mysem_t*,int);
-
- int mysem_sub(mysem_t*,int);
-
- void mysem_destroy(mysem_t*);
-
-
-
- #endif
main.c
- #include <stdlib.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <string.h>
- #include <pthread.h>
- #include "mysem.h"
-
- #define LEFT 30000000
- #define RIGHT 30000200
- #define THRNUM (RIGHT-LEFT+1)
-
- #define N 4
- static mysem_t* sem;
-
- void* thr_prime(void*p);
-
- int main()
- {
- pthread_t tid[THRNUM];
- int i,j,mark;
- int err;
-
- sem = mysem_init(N);
- if(sem ==NULL)
- {
- fprintf(stderr,"mysem_init n");
- exit(1);
- }
-
- for(i =LEFT;i<=RIGHT;i++)
- {
- mysem_sub(sem,1);
-
- err= pthread_create(tid+(i-LEFT),NULL,thr_prime,(void *)i);
- if(err)
- {
- fprintf(stderr,"pthread_create():%sn",strerror(err));
- }
- }
-
- for(i=LEFT;i<=RIGHT;i++)
- {
- pthread_join(tid[i-LEFT],NULL);
- }
-
- mysem_destroy(sem);
-
- return 0;
- }
-
- void* thr_prime(void*p)
- {
- int i,j,mark;
-
- i = (int)p;
- // i = *(int*)p;
-
- mark = 1;
- for(j=2;j<i/2;j++)
- {
- if(i%j ==0)
- {
- mark = 0;
- break;
- }
- }
- if(mark)
- printf("%d is a primer n",i);
-
- sleep(5); //ps ax -L 可以观察到对线程进行了限制,只创建了四个线程
-
- mysem_add(sem,1);
- pthread_exit(NULL);
-
- return NULL;
- }
makefile
- all:mysem
- CFLAGS+=-g -Wall -pthread
- LDFLAGS+= -pthread
-
- mysem:main.o mysem.o
- gcc $^ $(CFLAGS) $(LDFLAGS) -o $@
-
- clean:
- rm -rf *.o mysem
互斥量和信号量的综合使用。分为读锁(信号量)和写锁(互斥量)。一般读写要设置上限。
需要防止写者饿死的情况发生。
pthread_create第二个参数是线程的属性。
int pthread_attr_init(pthread_attr_t *attr);
int pthread_attr_destroy(pthread_attr_t *attr);
测试程序创建最大线程个数。()
- #include <stdlib.h>
- #include <stdio.h>
- #include <pthread.h>
-
- void* func(void)
- {
- int i;
-
- // printf("%pn",&i);
- pthread_exit(NULL);
- return NULL;
- }
-
- int main()
- {
- int err;
- pthread_t tid;
- pthread_attr_t attr;
- pthread_attr_init(&attr);
- pthread_attr_setstacksize(&attr,1024*1024); //1mb
-
- int i = 0;
- for(;;i++)
- {
- err = pthread_create(&tid,&attr,func,NULL);
- if(err)
- {
- fprintf(stderr,"create errn");
- break;
- }
- }
- printf("max = %d n",i);
- pthread_attr_destroy(&attr);
- return 0;
- }
互斥量属性:
int pthread_mutexattr_init(pthread_mutexattr_t *attr);
Refer to pthread_mutexattr_destroy().
int pthread_mutexattr_getpshared(const pthread_mutexattr_t *attr, //跨进程起作用
int *pshared);
int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr,
int pshared);
//创建一个子进程,可以共享文件描述符数组.也可以选择不共享。linux下不区分进程和线程
int clone(int (*fn)(void *), void *stack, int flags, void *arg, ...
/* pid_t *parent_tid, void *tls, pid_t *child_tid */ );
int pthread_mutexattr_gettype(const pthread_mutexattr_t *restrict attr,
int *restrict type);
int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type);
条件变量属性:
int pthread_condattr_destroy(pthread_condattr_t *attr);
int pthread_condattr_init(pthread_condattr_t *attr);
读写锁属性:
一个可重入的函数简单来说就是可以被中断的函数,也就是说,可以在这个函数执行的任何时刻中断它,转入OS调度下去执行另外一段代码,而返回控制时不会出现什么错误;而不可重入的函数由于使用了一些系统资源,比如全局变量区,中断向量表等,所以它如果被中断的话,可能会出现问题,这类函数是不能运行在多任务环境下的。
多线程中的IO。unlocked函数结尾的都是(不可重入函数,不支持多线程并发)。man putc_unlocked,查看不支持的IO操作。
int pthread_sigmask(int how, const sigset_t *set, sigset_t *oldset);
int sigwait(const sigset_t *set, int *sig);
int pthread_kill(pthread_t thread, int sig);
参考官网:www.OpenMp.org
gcc4.0之后都支持openmp语法标记。有几个CPU就可以实现多少并发
hello.c
- #include <stdio.h>
- #include <stdlib.h>
-
- int main()
- {
- #pragma omp parallel //实现并发
- {
- puts("Hello ");
- puts(" World");
- }
- return 0;
- }
makefile
CFLAGS += -Wall -fopenmp
make hello编译,并且运行。
- #include <stdio.h>
- #include <stdlib.h>
- #include <omp.h>
-
- int main()
- {
- #pragma omp parallel sections
- {
- #pragma omp section
- printf("[%d:]Hello n",omp_get_thread_num() );
- #pragma omp section
- printf("[%d:]World n",omp_get_thread_num() );
- }
- return 0;
- }