【问题标题】:error: ‘pthread_mutex_t’ has no member named ‘wait’错误:“pthread_mutex_t”没有名为“wait”的成员
【发布时间】:2017-11-28 03:11:50
【问题描述】:

Getting error error: ‘pthread_mutex_t’ has no member named ‘wait’ for this code无法理解为什么?我已经在上面声明了 pthread_mutex_t 互斥锁;仍然出现同样的错误。

我正在尝试实现信号量小书中给出的两相障碍。

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>


int thread_count;

pthread_mutex_t mutex;

void* MyThread(void* rank);
   void* Hello(void* rank)

    {

        long my_rank = (long) rank;

        int a = 0,i;

        for(i=0;i<10;i++)

        {

              int n = 5;
              int count = 0;

              mutex = Semaphore(1)

              barrier = Semaphore(0)

                  a = a + 0.9*MAX_INT;

                  printf("this is %d iteration\n",i);

              mutex.wait()

              count = count + 1;

              mutex.signal()

              if count == n: barrier.signal() //unblock ONE thread

              barrier.wait()

              barrier.signal()

       }

    }

【问题讨论】:

  • 您似乎缺少几个分号。 int count = 0 为一。这看起来更像 C++ 代码,因为您无法访问 C 中的函数,例如 mutex.wait(),因为 mutex 不是类的实例
  • 如何在 C 中访问?

标签: c multithreading


【解决方案1】:

pthreads 是 C API,不是面向对象的。因此,该库不会导出带有方法的对象,而是将指向事物的指针作为参数的函数。

您通过调用创建pthread_mutex_t

int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);

或者将其初始化为PTHREAD_MUTEX_INITIALIZER

你通过调用获取互斥锁:

int pthread_mutex_lock(pthread_mutex_t *mutex);

并通过调用释放它:

int pthread_mutex_unlock(pthread_mutex_t *mutex);

在您的示例中,我不知道 Semaphorebarrier 指的是什么。

实际上,if 语句确实是 Pythonic。你是不是想把一些部分转换的 Python 代码塞进 C 编译器的喉咙里?

【讨论】:

猜你喜欢
  • 2022-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-04
  • 2022-01-15
  • 1970-01-01
  • 2013-12-06
相关资源
最近更新 更多