C语言多线程互斥锁

互斥锁是为了防止多个线程同时操作临界资源,下面看看用法:

# include 
# include 

pthread_mutex_t mute;
int value = 0;
void *fun(void *arg){
    //上锁,函数是阻塞的
    pthread_mutex_lock(&mute);
    printf("now is %d and old value is %d \n",*((int *)arg), value);
    ++value;
    printf("now is %d and new value is %d \n",*((int *)arg), value);
    //解锁
    pthread_mutex_unlock(&mute);
}
int main(){

    pthread_t threads[5];
    int thread_id[5];
    //创建锁,相当于new一个对象
    pthread_mutex_init(&mute, NULL);
    for(int i=0; i<5; ++i){
        thread_id[i] = i;
        pthread_create(&threads[i], NULL, fun, (void *)&thread_id[i]);
    }
    for(int i=0; i<5; ++i)
        int rc = pthread_join(threads[i], NULL);
    //释放互斥锁
    pthread_mutex_destroy(&mute);
    return 0;
}

运行结果:

C语言多线程互斥锁_第1张图片

可以看出线程的运行顺序是不确定的,一个线程对资源上锁了,其他线程想上锁只能被阻塞。加入去掉互斥锁的结果如下:

C语言多线程互斥锁_第2张图片

可以看出同一个线程内操作value的前后值是异常的。

你可能感兴趣的:(网络相关)