实现一个计程车的流程,打车,taxi,上车,到达
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> //定义头文件 pthread_cond_t taxicond = PTHREAD_COND_INITIALIZER; /*初始化条件变量*/ pthread_mutex_t taximutex = PTHREAD_MUTEX_INITIALIZER; /*初始化互斥锁*/
先写main函数;创建线程
int main (int argc, char **argv) { char *name; pthread_t thread; //线程号 pthread_attr_t threadattr; /*线程属性*/ pthread_attr_init(&threadattr);/*对线程属性变量进行初始化*/ name = "Susan"; pthread_create(&thread, &threadattr, traveler_arrive, name); /*创建一个thread进程,与traveler_arrive函数捆绑在一起,name为Susan*/ sleep(1); name = "Jack"; pthread_create(&thread,&threadattr,taxi_arrive,name);/*创建进程thread,taxi_arrive函数捆绑在一起name为Jack*/ sleep(1); name = "Mike"; pthread_create(&thread,&threadattr,taxi_arrive,name); /*创建进程thread,taxi_arrive函数捆绑在一起name为Mike*/ sleep(1); return 0; }
创建了一个name=Susan的用traveler_arrive函数
创建了一个Jack用taxi_arrive函数
创建了一个Mike用taxi_arrive函数
注:上面已经初始化互斥锁和条件变量
不用写int函数了
下面实现函数
void *traveler_arrive(void *name) { char *p = (char *)name; printf ("Travelr: %s need a taxi now!\n", p); pthread_mutex_lock(&taximutex); /*拿到互斥锁,锁住互斥量*/ pthread_cond_wait(&taxicond, &taximutex);/*令进程等待在条件变量上修改条件*/ pthread_mutex_unlock(&taximutex);/*释放互斥锁*/ printf ("traveler: %s now got a taxi!\n", p); pthread_exit(NULL);/*退出*/ }
传入void* name 给转换为char* 给 *p
输出谁需要taxi
上锁 锁住互斥量,令进程等待在条件变量上修改条件,解锁
输出谁got a taxi
上面的函数是乘车的人的函数
下面是taxi的人的函数
void *taxi_arrive(void *name) { char *p = (char *)name; printf ("Taxi: %s arrives.\n", p); pthread_cond_signal(&taxicond); /*条件改变,发送信号,通知进程thread*/ pthread_exit(NULL); /*退出*/ }
转换为char *
输出taxi 谁 到达
发送信号,通知乘车人进程 进程thread
总代码:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> //定义头文件 pthread_cond_t taxicond = PTHREAD_COND_INITIALIZER; /*初始化条件变量*/ pthread_mutex_t taximutex = PTHREAD_MUTEX_INITIALIZER; /*初始化互斥锁*/ void *traveler_arrive(void *name) { char *p = (char *)name; printf ("Travelr: %s need a taxi now!\n", p); pthread_mutex_lock(&taximutex); /*拿到互斥锁,锁住互斥量*/ pthread_cond_wait(&taxicond, &taximutex);/*令进程等待在条件变量上修改条件*/ pthread_mutex_unlock(&taximutex);/*释放互斥锁*/ printf ("traveler: %s now got a taxi!\n", p); pthread_exit(NULL);/*退出*/ } void *taxi_arrive(void *name) { char *p = (char *)name; printf ("Taxi: %s arrives.\n", p); pthread_cond_signal(&taxicond); /*条件改变,发送信号,通知进程thread*/ pthread_exit(NULL); /*退出*/ } int main (int argc, char **argv) { char *name; pthread_t thread; //线程号 pthread_attr_t threadattr; /*线程属性*/ pthread_attr_init(&threadattr);/*对线程属性变量进行初始化*/ name = "Susan"; pthread_create(&thread, &threadattr, traveler_arrive, name); /*创建一个thread进程,与traveler_arrive函数捆绑在一起,name为Susan*/ sleep(1); name = "Jack"; pthread_create(&thread,&threadattr,taxi_arrive,name);/*创建进程thread,taxi_arrive函数捆绑在一起name为Jack*/ sleep(1); name = "Mike"; pthread_create(&thread,&threadattr,taxi_arrive,name); /*创建进程thread,taxi_arrive函数捆绑在一起name为Mike*/ sleep(1); return 0; }