同步模型:
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <pthread.h> #include <semaphore.h> //#define EXIT_SUCCESS 0 //#define EXIT_FAILURE 1 //假设有6个同学{姜涵,张柏芝,刘思思,孙燕姿,赵敏,马苏},依次按照顺序报数 //f(x) = f(x+6) 周期性 // 关键是理解 临界区需要怎么去操作 选择什么样技术 static int pthread_run = 1; static void print(char*s); static sem_t sem[6]; //sem_init(&sem, 0, 0) static void* J_H_Pthread(void *arg) { int a ; while(pthread_run) { //printf("pthread run "); sem_wait(&sem[0]); print(__func__); sem_post(&sem[1]); } return (void*)NULL; } static void* Z_B_Z_Pthread(void *arg) { int a ; while(pthread_run) { //printf("pthread run "); sem_wait(&sem[1]); print(__func__); sem_post(&sem[2]); } return (void*)NULL; } static void* L_S_SPthread(void *arg) { int a ; while(pthread_run) { //printf("pthread run "); sem_wait(&sem[2]); print(__func__); sem_post(&sem[3]); } return (void*)NULL; } static void* S_Y_Zthread(void *arg) { int a ; while(pthread_run) { //printf("pthread run "); sem_wait(&sem[3]); print(__func__); sem_post(&sem[4]); } return (void*)NULL; } static void* Z_M_Pthread(void *arg) { int a ; while(pthread_run) { //printf("pthread run "); sem_wait(&sem[4]); print(__func__); sem_post(&sem[5]); } return (void*)NULL; } static void* M_S_Pthread(void *arg) { int a ; while(pthread_run) { //printf("pthread run "); sem_wait(&sem[5]); print(__func__); sem_post(&sem[0]); } return (void*)NULL; } // 定义一个临界区资源 static void print(char*s) { if(s==NULL) { printf("int value error "); return 0; } printf("I'm here %s ",s); } int main() { printf("EXIT_SUCCESS is %d ",EXIT_SUCCESS); printf("EXIT_FAILURE is %d ",EXIT_FAILURE); int ret = -1; pthread_t j_h_ptid,z_b_ztid,l_s_stid,s_yztid,z_mtid,m_stid; //int ret = pthread_create(&tid,NULL,Noise_USB_Pthread,NULL); //printf("ret is %d ",ret); //ret = pthread_join(tid,NULL); //printf("ret is %d ",ret); int i; for(i =0;i<6;i++) { if(i==0) sem_init(&sem[i],0,1); else sem_init(&sem[i],0,0); } ret = pthread_create(&j_h_ptid,NULL,J_H_Pthread,NULL); printf("ret is %d ",ret); ret = pthread_create(&z_b_ztid,NULL,Z_B_Z_Pthread,NULL); printf("ret is %d ",ret); ret = pthread_create(&l_s_stid,NULL,L_S_SPthread,NULL); printf("ret is %d ",ret); ret = pthread_create(&s_yztid,NULL,S_Y_Zthread,NULL); printf("ret is %d ",ret); ret = pthread_create(&z_mtid,NULL,Z_M_Pthread,NULL); printf("ret is %d ",ret); ret = pthread_create(&m_stid,NULL,M_S_Pthread,NULL); printf("ret is %d ",ret); pthread_join(j_h_ptid,NULL); pthread_join(z_b_ztid,NULL); pthread_join(l_s_stid,NULL); pthread_join(s_yztid,NULL); pthread_join(s_yztid,NULL); pthread_join(m_stid,NULL); for(i =0;i<6;i++) { sem_destroy(&sem[i]); } while(1); return 0; }
同步模型