#include<stdio.h>
#include<pthread.h>
static pthread_mutex_t testlock;
pthread_t test;
void *func()
{
pthread_mutex_lock(&testlock);
printf("FUNC LOCK!\n");
pthread_mutex_unlock(&testlock);
}
int main()
{
pthread_mutex_init(&testlock,NULL);
pthread_mutex_lock(&testlock);
printf("MAIN FUNCTION LOCK\n");
pthread_create(&test,NULL,func,NULL);
sleep(2);
printf("MAIN FUNCTION UNLOCK\n");
pthread_mutex_unlock(&testlock);
pthread_join(test,NULL);
pthread_mutex_destroy(&testlock);
return 0;
}
/*运行结果:
MAIN FUNCTION LOCK
MAIN FUNCTION UNLOCK
FUNC LOCK!
*/
/*结果分析:
主进程进行封锁后创建了线程。但是线程在尝试进行lock的时候被阻塞
直到主进程解锁后继续执行。
*/
#include<semaphore.h>
#include<sys/types.h>
#include<stdio.h>
#include<unistd.h>
int number;
sem_t sem_id1,sem_id2;
void *thread_one_func(void *arg)
{
while(1){
sem_wait(&sem_id1);
printf("thread_one have the semaphore\n");
number++;
printf("number=%d\n",number);
sem_post(&sem_id2);}
}
void *thread_two_func(void *arg)
{
while(1){
sem_wait(&sem_id2);
printf("thread_two have the semaphore\n");
number--;
printf("number=%d\n",number);
sem_post(&sem_id1);}
}
int main()
{
number=1;
pthread_t id1,id2;
sem_init(&sem_id1,0,1);
sem_init(&sem_id2,0,0);
pthread_create(&id1,NULL,thread_one_func,NULL);
pthread_create(&id2,NULL,thread_two_func,NULL);
pthread_join(id1,NULL);
pthread_join(id2,NULL);
printf("main!\n");
return 0;
}