进程中互斥量、加锁、减锁!

进程中互斥量、加锁、减锁!_第1张图片

先看代码

#include
#include
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// 返回:若成功返回0,否则返回错误编号
int g_data=0;
pthread_mutex_t mutex;
void *func1(void *argc)
{
        pthread_mutex_lock(&mutex);
        printf("t1:%ld thread is created!\n",(unsigned long)pthread_self());
        printf("t1:param id %d\n",*((int *)argc));
        pthread_mutex_unlock(&mutex);
}
void *func2(void *argc)
{
        pthread_mutex_lock(&mutex);
        printf("t2:%ld thread is created!\n",(unsigned long)pthread_self());
        printf("t2:param id %d\n",*((int *)argc));
        pthread_mutex_unlock(&mutex);

}
int main()
{
        int ret;
        int param=100;
        pthread_t t1;
        pthread_t t2;

        pthread_mutex_init(&mutex,NULL);


        ret = pthread_create(&t1,NULL,func1,(void *)&param);
        if(ret ==0)
        {
                printf("main:crest t1 success!\n");
        }
        ret = pthread_create(&t2,NULL,func2,(void *)&param);
        if(ret ==0)
        {
                printf("main:crest t2 success!\n");
        }
        printf("main:%ld\n",(unsigned long)pthread_self());
        pthread_join(t1,NULL);
        pthread_join(t2,NULL);
        pthread_mutex_destroy(&mutex);
        return 0;
}
~  

进程中互斥量、加锁、减锁!_第2张图片
可见,被加锁的部分执行顺序不会变(不会出现t1出现之后紧接着出现t2,会等两个t1出现完后再出现t2,但t1.t2谁先出不能确定,都上了锁的)

你可能感兴趣的:(嵌入式软件)