linux 多线程编程互斥锁,纯C(LINUX)多线程编程例子——使用互斥锁

多线程轮流给一个数字加1,使用互斥锁。

1.[代码][C/C++]代码

#include

#include

#include

#include

int count = 0;

#define SIG_MAX 30

struct prodcons {

pthread_mutex_t lock;

pthread_cond_t sig[SIG_MAX];

int ref;

};

struct prodcons buffer;

int init(struct prodcons *b)

{

int i = 0;

pthread_mutex_init(&b->lock, NULL);

for (i = 0; i < SIG_MAX; i++) {

pthread_cond_init(&b->sig[i], NULL);

}

b->ref = 0;

}

void put(struct prodcons *b, int data, int sig)

{

while(1) {

pthread_mutex_lock(&b->lock);

b->ref |= (1 << sig);

pthread_cond_wait(&b->sig[sig], &b->lock);

b->ref &= ~(1 << sig);

count++;

printf("signal: %d data: %d count:%d\n", sig, data, count);

pthread_mutex_unlock(&b->lock);

int tmp;

while( !(tmp = (b->ref & (1 << ((sig + 1) % SIG_MAX)))) )

printf("while-tmp:%d\n", tmp);

pthread_cond_signal(&b->sig[(sig + 1) % SIG_MAX]);

}

}

void producer_put(int x)

{

printf("starting pthread:%d\n", x);

put(&buffer, x, x);

return;

}

void *producer(void *data)

{

int d = *(int *)data;

producer_put(d);

return NULL;

}

int main(void)

{

int i;

int resource[SIG_MAX];

pthread_t p[SIG_MAX];

void *retval;

init(&buffer);

for (i = 0; i < SIG_MAX; i++) {

resource[i] = i;

pthread_create(&p[i], NULL, producer, &resource[i]);

}

printf("Starting %d pthreads...\n"

"Pthreads would print numbers one by one~\n\n", SIG_MAX);

while(buffer.ref != ((1 << SIG_MAX) - 1));

printf("\nSending signal[0] to trigger a start\n");

sleep(1);

pthread_cond_signal(&buffer.sig[0]);

for (i = 0; i < SIG_MAX; i++) {

pthread_join(p[i], &retval);

}

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值