C语言线程创建与锁机制

#include<stdio.h>
#include<pthread.h>   //线程
#include<semaphore.h> //锁
#define N 10

void *thread(void *vargp);
char **ptr;

static int count = 0;

int main(int argc, char **argv)
{
    int i;
    pthread_t tid;
    char *msgs[N] = { "0","1","2","3","4",
                      "5","6","7","8","9"};
    
    ptr = msgs;
    
    for(i=0;i<N;i++)
    {
        pthread_create(&tid, NULL, thread, (void*)i); 
    }
    
    pthread_exit(NULL);
    
    return 0;
}
struct __sem_t *muteX;//锁
void *thread(void *vargp)
{
    int myid = (int)vargp;
    static int cnt = 0;
    count ++;
    sem_init(&muteX, 0, 1);
    sem_wait(&muteX);
    printf("[%d]: %s (cnt = %d), %d\n", 
            myid, ptr[myid], ++cnt, count);
    sem_post(&muteX);
    
    return NULL;
}

编译与运行:

$ gcc pthread.c
$ ./a.exe
[0]: 0 (cnt = 1), 1
[1]: 1 (cnt = 2), 2
[2]: 2 (cnt = 3), 3
[3]: 3 (cnt = 4), 4
[4]: 4 (cnt = 5), 5
[5]: 5 (cnt = 6), 6
[6]: 6 (cnt = 7), 7
[7]: 7 (cnt = 8), 8
[8]: 8 (cnt = 9), 9
[9]: 9 (cnt = 10), 10
此为笔记。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值