多线程编程,线程同步,线程互斥示例

本文提供了一个使用C语言实现的互斥锁与信号量的示例程序,通过对比两种同步机制,展示了如何在多线程环境下保护共享资源。程序包括创建线程、初始化互斥锁及信号量、进行线程同步等关键步骤。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
int count,v1,v2;
int flags = 1;
sem_t sem;
pthread_mutex_t mt;
void *fun(void *arg)
{
    int ret = -1;
    while(1)
    {
#if 0
        ret = sem_wait(&sem);
        if ( -1 == ret )
        {
            perror("sem_init");
            return ;
        }
#else
        ret = pthread_mutex_lock(&mt);
        if (0 != ret)
        {
            perror("pthread_mutex_lock");
            return -1;
        }

#endif
        if ( v1 != v2 )
            printf("******* %d,%d\n",v1,v2);
#if 0
        ret = sem_post(&sem);
        if ( -1 == ret )
        {
            perror("sem_init");
            return ;
        }
#else
        ret = pthread_mutex_unlock(&mt);
        if (0 != ret)
        {
            perror("pthread_mutex_lock");
            return -1;
        }
#endif
    }
    *((int *)arg) = 3;
    pthread_exit("fun");//exit
}
int main(int argc,char **argv)
{
    int a = 0;
    pthread_t id;
    int ret = -1;
    void * val = NULL;
#if 0
    ret = sem_init(&sem,0,1);
    if ( -1 == ret )
    {
        perror("sem_init");
        return -1;
    }
#else  
    ret = pthread_mutex_init(&mt,NULL);
    if( 0 != ret)
    {
        perror("pthread_mutex_init");
        return -1;
    }
#endif
    ret = pthread_create(&id,NULL,fun,(void*)&a);//fork
    if ( 0 != ret )
    {
        perror("pthread_creat");
        return -1;
    }

    while(1)
    {
#if 0
        ret = sem_wait(&sem);
        if ( -1 == ret )
        {
            perror("sem_init");
            return -1;
        }
#else 
        ret = pthread_mutex_lock(&mt);
        if (0 != ret)
        {
            perror("pthread_mutex_lock");
            return -1;
        }
#endif
        count++;
        v1=count;
        v2=count;
#if 0
        ret = sem_post(&sem);
        if ( -1 == ret )
        {
            perror("sem_init");
            return -1;
        }
#else 
        ret = pthread_mutex_unlock(&mt);
        if (0 != ret)
        {
            perror("pthread_mutex_lock");
            return -1;
        }
#endif
    }
    ret = pthread_join(id,&val);//wait
    if ( 0 != ret )
    {
        perror("pthread_join");
        return -1;
    }
    printf("return val is %s\n",val);
    printf("%d**\n",a);
    return 0;
}

 

转载于:https://www.cnblogs.com/smile-at-you/p/3363788.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值