首页 > 代码库 > thread_17

thread_17

#include <stdlib.h>#include <pthread.h>#include <stdio.h>#include <sched.h>#include <sched.h>pthread_mutex_t mu;void *consumer1(void *p) {         //pthread_mutex_init(&mu, NULL);      pthread_mutex_lock(&mu);                printf("get mutex(1)\n");        pthread_mutex_unlock(&mu);} void *consumer2(void *p) {        //pthread_mutex_init(&mu, NULL);      pthread_mutex_lock(&mu);                 printf("get mutex(2)\n");         pthread_mutex_unlock(&mu); } int main(int argc, char *argv[]) {         pthread_t  t1, t2, t3;       int ret;         pthread_mutex_init(&mu, NULL);                 //pthread_mutex_lock(&mu);        ret = pthread_create(&t1, NULL, consumer1, NULL);        ret = pthread_create(&t2, NULL, consumer2,NULL);         if(ret != 0)        {                printf("create failed,%d\n", ret);                exit(1);         }        sleep(11);       printf("main returned\n");     return 0; }/*互斥锁在使用前都被初始化,锁已经失去效果。运行结果:get mutex(2)get mutex(1)main returned*//*锁可以被动态或静态创建,可以用宏PTHREAD_MUTEX_INITIALIZER来静态的初始化锁,采用这种方式比较容易理解,互斥锁是pthread_mutex_t的结构体,而这个宏是一个结构常量,如下可以完成静态的初始化锁:    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;    另外锁可以用pthread_mutex_init函数动态的创建,函数原型如下:*/

 

thread_17