sem_init 和 pthread_mutex_init

battyman17

我正在编写 2 个类似的代码,用于使用互斥锁和信号量从给定的数字集中打印奇数和偶数。这两个代码都可以正常工作。

但是,在使用互斥锁时,即使我不声明该pthread_mutex_init函数,程序仍然可以毫无问题地执行。但信号量不是这种情况。对于这种情况,我必须sem_init在 main() 中声明,否则程序执行会卡住sem_wait()(在调试后发现)。

那么,在互斥锁的情况下,即使不声明init(),程序如何执行呢?

作为参考,我附上了信号量代码。

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

sem_t mutex;
pthread_t tid[2];
unsigned int shared_data[] = {23,45,67,44,56,78,91,102};
unsigned int rc;
int len=(sizeof(shared_data)/sizeof(shared_data[0]));
int i=0;

void *even(void *arg) {
    rc = sem_wait(&mutex);
    int temp = rc;
    if(rc)
        printf("Semaphore failed\n");

    do{
        if(shared_data[i] %2 == 0) {
            printf("Even: %d\n",shared_data[i]);
            i++;
        }
        else
            rc = sem_post(&mutex);
    }while(i<len);
}

void *odd(void *arg) {
    rc = sem_wait(&mutex);
    if(rc)
        printf("Semaphore failed\n");

    do {
        if(shared_data[i] %2 != 0) {
            printf("Odd: %d\n",shared_data[i]);
            i++;
        }
        else
            rc = sem_post(&mutex);
    }while(i<len);
}

int main() {
    sem_init(&mutex, 0,1);
    pthread_create(&tid[0], 0, &even, 0);
    pthread_create(&tid[1], 0, &odd, 0);

    pthread_join(tid[0],NULL);
    pthread_join(tid[1],NULL);

    sem_destroy(&mutex);

    return 0;
}

编辑:也附加互斥锁代码。

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

pthread_t tid[2];
unsigned int shared_data []= {23,45,67,44,56,78,91,102};
pthread_mutex_t mutex;
unsigned int rc;
int len=(sizeof(shared_data)/sizeof(shared_data[0]));
int i=0;

void* PrintEvenNos(void *ptr)
{
    rc = pthread_mutex_lock(&mutex);
    if(rc)
        printf("Mutex lock has failed\n");
    do
    {
       if(shared_data[i]%2 == 0)
       {
         printf("Even:%d\n",shared_data[i]);
         i++;
       } else {
          rc=pthread_mutex_unlock(&mutex);
       }
    } while(i<len);
}

void* PrintOddNos(void* ptr1)
{
    rc = pthread_mutex_lock(&mutex);
    if(rc)
        printf("Mutex lock has failed\n");
    do
    {
       if(shared_data[i]%2 != 0)
       {
         printf("Odd:%d\n",shared_data[i]);
         i++;
       } else {
          rc=pthread_mutex_unlock(&mutex);
       }
    } while(i<len);
}

void main(void)
{   
    pthread_create(&tid[0],0,PrintEvenNos,0);
    pthread_create(&tid[1],0,PrintOddNos,0);

    pthread_join(tid[0],NULL);
    pthread_join(tid[1],NULL);
}
安德鲁·亨勒

那么,在互斥锁的情况下,即使不声明init(),程序如何执行呢?

这是未定义的行为,因此没有正确的结果。每个 POSIXpthread_mutex_lock()

如果mutex不引用初始化的互斥锁对象的行为pthread_mutex_lock()pthread_mutex_trylock()以及pthread_mutex_unlock()不确定。

“似乎工作”是未定义行为的一种可能结果。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章