Linux线程 -- 互斥锁实践

Linux线程互斥锁程序示例

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

#define NUM 5000 

int counter = 0;
/*静态锁*/
pthread_mutex_t c_mutex = PTHREAD_MUTEX_INITIALIZER;

/*线程执行函数*/
void* fun(void *arg)
{
    int i, val;
    for(i = 0; i < 5000; i++){
        /*加锁*/
        pthread_mutex_lock(&c_mutex);

        val = counter;
        printf("tid = %x, 第%d次循环\n", (unsigned int)pthread_self(), val + 1);
        counter = val+1;/*每执行一次,counter的值+1*/
        /*解锁*/
        pthread_mutex_unlock(&c_mutex);
    }
    return NULL;
}

int main()
{
    pthread_t tid_a, tid_b;
    /*创建两个线程*/
    pthread_create(&tid_a, NULL, fun, NULL);
    pthread_create(&tid_b, NULL, fun, NULL);
    /*等待线程执行完毕*/
    pthread_join(tid_a, NULL);
    pthread_join(tid_b, NULL);
    printf("counter = %d\n", counter);

    return 0;
}

最终结果counter = 10000

若不加锁,每次执行后counter的结果都不一样。

你可能感兴趣的:(linux,线程)