【学习笔记】天嵌2440第三季下学期——linux多线程同步

来源:互联网 发布:golang python 编辑:程序博客网 时间:2024/06/06 03:14

实现线程同步可以通过低级的编程手段实现:

上代码:

#include <stdio.h>#include <pthread.h>pthread_t thread[2];int number = 0;pthread_mutex_t mut;void studentA(){int i;for (int i = 0; i < 5; i++){//扫一次地printf("swaping%d\n", number);pthread_mutex_lock(&mut);number++;if (number >= 5)printf("studentA finish;\n");pthread_mutex_unlock(&mut);//休息一秒钟sleep(1);}//退出pthread_exit(NULL);}void studentB(){while (1){pthread_mutex_lock(&mut);//判断A同学是否已经扫完5次地if(number>=5){//拖地number = 0;pthread_mutex_unlock(&mut);printf("student B has finish\n");break;}else{pthread_mutex_unlock(&mut);//睡眠2秒钟sleep(2);}pthread_exit(NULL);}}int main(){pthread_mutex_init(&mut, NULL);//1、创建A同学进程pthread_create(&thread[0], NULL, studentA, NULL);//2、创建B同学进程pthread_create(&thread[1], NULL, studentB, NULL);//3、等待A同学进程结束pthread_join(thread[0], NULL);//4、等待B同学进程结束pthread_join(thread[1], NULL);return 0;}

期间遇到核心段错误,经过gdb调适,发现是创建线程的传进了错误的参数形式:

pthread_create(thread[0], NULL, studentA, NULL);
线程的id必须要以地址的形式传入,上述代码已经订正。

但这种编程方式低效,可采用linux线程同步技术的特有函数:

pthread_cond_wait:

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;int    pthread_cond_init(pthread_cond_t    *cond,    pthread_condattr_t *cond_attr);int pthread_cond_signal(pthread_cond_t *cond);int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
上述有两种初始化,据man手册提示,第一种属于静态初始化(initialized statically),教程采用这种方式。

上代码:

#include <stdio.h>#include <pthread.h>pthread_t thread[2];int number = 0;pthread_mutex_t mut;pthread_cond_t cond_ready = PTHREAD_COND_INITIALIZER;void studentA(){int i;for (i = 0; i < 5; i++){//扫一次地printf("swaping%d\n", i);pthread_mutex_lock(&mut);number++;if (number >= 5){printf("student A finish;\n");pthread_cond_signal(&cond_ready);}pthread_mutex_unlock(&mut);//休息一秒钟sleep(1);}//退出pthread_exit(NULL);}void studentB(){pthread_mutex_lock(&mut);if (number <= 5)pthread_cond_wait(&cond_ready, &mut);number = 0;pthread_mutex_unlock(&mut);printf("student B finish\n");//退出pthread_exit(NULL);}int main(){pthread_mutex_init(&mut, NULL);//1、创建A同学进程pthread_create(&thread[0], NULL, studentA, NULL);//2、创建B同学进程pthread_create(&thread[1], NULL, studentB, NULL);//3、等待A同学进程结束pthread_join(thread[0], NULL);//4、等待B同学进程结束pthread_join(thread[1], NULL);return 0;}

pthread_cond_wait函数里面会自动进行解锁与加锁访问共享资源number。


阅读全文
0 0