【问题标题】:Error when passing arguments to pthread_create()将参数传递给 pthread_create() 时出错
【发布时间】:2022-01-01 21:11:50
【问题描述】:

我正在尝试为pthreads 创建一个类似线程池的结构来为网络编程执行相同的工作,这与this question 非常相似。但是,当我尝试将init() 方法的参数传递给pthread_create() 时出现问题。

代码

class ThreadPool{
    public:
        BlockingQueue socket_bq;
        pthread_mutex_t* threads[THREAD_NUM];   // store the pointer of threads

        ThreadPool();
        void init(pthread_attr_t* attr, void*start_routine(void*), void* arg);
};

void ThreadPool::init(pthread_attr_t* attr, void*start_routine(void*), void* arg){
    // create threads
    for(int i = 0; i < THREAD_NUM; i++){
        if(pthread_create(threads[i], attr, start_routine, arg)!=0){
            fprintf(stderr, "Thread Pool Init: falied when creatng threads");
            exit(1);
        }
    }
}

错误信息

error: no matching function for call to 'pthread_create'
        if(pthread_create(threads[i], attr, start_routine, arg)!=0){
           ^~~~~~~~~~~~~~
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/pthread.h:329:5: note: candidate function not viable: no known conversion from 'pthread_mutex_t *' (aka '_opaque_pthread_mutex_t *') to 'pthread_t  _Nullable * _Nonnull' (aka '_opaque_pthread_t **') for 1st argument
int pthread_create(pthread_t _Nullable * _Nonnull __restrict,
    ^
1 error generated.

【问题讨论】:

  • 您将 pthread_mutex_t * 作为第一个参数传递。应该是pthread_t *
  • 感谢@G.M.,它解决了问题!
  • 从C++11开始,你真的应该直接使用std::thread而不是pthreads
  • 嗨,@RemyLebeau 谢谢你的建议!但由于这是学校作业,讲师坚持我们应该使用操作系统提供的pthread,我想我只能忍受一段时间了。我一定会在我未来的项目中使用std::thread

标签: c++ macos arguments pthreads


【解决方案1】:

threads 的定义不正确。应该是:

pthread_t* threads[THREAD_NUM];

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 2014-05-28
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    相关资源
    最近更新 更多