Linux中的线程与C中的信号量同步

问题描述 投票:-1回答:1

我有一个示例程序,用于使用Mutex在Linux操作系统上同步线程。线程负责递增计数器值。旁注:我仍然是这方面的初学者,仍然在学习理解这个概念

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

void *thread_func();

phtread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;

int main(){
    int ret1, ret2;
    pthread_t thread1, thread2;

    if((ret1=pthread_create(&thread1, NULL, &thread_func, NULL)))
    printf("Phtread_create is failed: %d\n", ret1);

    if((ret2=pthread_create(&thread2, NULL, &thread_func, NULL)))
    printf("Phtread_create failed: %d\n", ret2);

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

    return 0;
}

void *thread_func(void *param){
    pthread_mutex_lock( &mutex1 );
    counter++;
    printf("Counter value: %d\n",counter);
    pthread_mutex_unlock( &mutex1 );
    pthread_exit(0);
}

我的问题是我想修改上面的程序,以便使用Semaphore完成同步。但我不知道如何修改它。欢迎任何建议和解决方案。非常感谢

c linux synchronization pthreads semaphore
1个回答
0
投票

有必要检查是否可以在不使用pthread_mutex_init()通过引用手册页或在线示例进行初始化的情况下使用互斥锁。有两种类型的信号量,sysV信号量和posix信号量。对于开始posix信号量是好的开始。它命名了信号量(通过sem_open())和未命名的信号量(通过sem_init())。要像mutex一样使用它,只需将其计数为1,每个sem_wait如果计数为1则将其递减为0或等待它从0变为1.一旦信号量被释放sem_post()它。手册页很适合参考。

© www.soinside.com 2019 - 2024. All rights reserved.