7.7 7.5

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值