小编Sem*_*ics的帖子

二进制信号量保持并发

我试图使用二进制信号量实现一个多线程程序.这是代码:

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

int g = 0;

sem_t *semaphore;

void *myThreadFun(void *vargp)
{
    int myid = (int)vargp;
    static int s = 0;
    sem_wait(semaphore);
    ++s; ++g;
    printf("Thread ID: %d, Static: %d, Global: %d\n", myid, s, g);
    fflush(stdout);
    sem_post(semaphore);
    pthread_exit(0);
}

int main()
{   

    int i;
    pthread_t tid;
    if ((semaphore = sem_open("/semaphore", O_CREAT, 0644, 3))==SEM_FAILED) {
    printf("semaphore initialization failed\n");
    }


    for (i = 0; i < 3; i++) {
        pthread_create(&tid, NULL, myThreadFun, (void *)i); …
Run Code Online (Sandbox Code Playgroud)

c multithreading posix semaphore

0
推荐指数
1
解决办法
353
查看次数

标签 统计

c ×1

multithreading ×1

posix ×1

semaphore ×1