linux c使用互斥锁实现同步

来源:互联网 发布:繁体字转换软件 编辑:程序博客网 时间:2024/05/22 15:21

1. 需要使用到的库pthread.h

2. 需要使用到的函数有pthread_mutex_init, pthread_mutex_destory, pthread_mutex_lock, pthread_unlock,

3. 需要保护的数据结构为

typedef struct cnt_sum {int cnt;pthread_mutex_t _mutex;} cnt_sum

两个操作线程分别对此结构数据进行累加操作,以下为具体的累加函数

add1函数如下所示:

void *add1(void *arg) {    ct_sum *ct = (ct_sum*) arg;    int i;    for (i = 0; i < 50; i++) {        pthread_mutex_lock(&(ct->_mutex));        ct->sum += i;        printf("thread 1 sum %d\n", i);         custom_sleep(10);        pthread_mutex_unlock(&(ct->_mutex));    }       return (void *)0;}

add2函数如下所示:

void *add2(void *arg) {    ct_sum *ct = (ct_sum*) arg;    int i;    for (i = 50; i < 100; i++) {        pthread_mutex_lock(&(ct->_mutex));        ct->sum += i;        printf("thread 2 sum %d\n", i);        custom_sleep(10);        pthread_mutex_unlock(&(ct->_mutex));    }    return (void *0);}

自带的sleep函数睡眠时间为1s,时间太长,编写了一个精度为毫秒的休眠函数,以下为具体的休眠函数代码

void custom_sleep(int ms) {    struct timeval delay;    delay.tv_sec = 0;    delay.tv_usec = ms * 1000;    select(0, NULL, NULL, NULL, &delay);}

程序的完成代码如下所示:

#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <pthread.h>#include <sys/select.h>#include <time.h>typedef struct ct_sum {    int sum;    pthread_mutex_t _mutex;} ct_sum;void custom_sleep(int ms) {    struct timeval delay;    delay.tv_sec = 0;    delay.tv_usec = ms * 1000;    select(0, NULL, NULL, NULL, &delay);}void *add1(void *arg) {    ct_sum *ct = (ct_sum*) arg;    int i;    for (i = 0; i < 50; i++) {        pthread_mutex_lock(&(ct->_mutex));        ct->sum += i;        printf("thread 1 sum %d\n", i);        custom_sleep(10);        pthread_mutex_unlock(&(ct->_mutex));    }    return 0;}void *add2(void *arg) {    ct_sum *ct = (ct_sum*) arg;    int i;    for (i = 50; i < 100; i++) {        pthread_mutex_lock(&(ct->_mutex));        ct->sum += i;        printf("thread 2 sum %d\n", i);        custom_sleep(10);        pthread_mutex_unlock(&(ct->_mutex));    }    return 0;}int main(void) {    int i;    pthread_t tid1, tid2;    int sum = 0;    ct_sum cnt;    pthread_mutex_init(&(cnt._mutex), NULL);    cnt.sum = 0;    pthread_create(&tid1, NULL, add1, (void*) &cnt);    pthread_create(&tid2, NULL, add2, (void*) &cnt);    sleep(1);    pthread_mutex_lock(&(cnt._mutex));    printf("sum %d\n", cnt.sum);    pthread_mutex_unlock(&(cnt._mutex));    pthread_join(tid1, NULL);    pthread_join(tid2, NULL);    printf("sum %d\n", cnt.sum);    pthread_mutex_destroy(&(cnt._mutex));    return 0;}

编译程序代码

gcc -o mutex mutex.c

运行代码即可看到相应的结果

./mutex

可以看到示例如下: