-1

I am trying to create a Thread-Pool-like structure for pthreads to do identical jobs for network programming, which is very similar to this question. However, a problem occurred as I tried to pass the arguments of the init() method to pthread_create().

Code

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 message

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.
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Navxihziq
  • 43
  • 5
  • You're passing a `pthread_mutex_t *` as the first parameter. It should be a [`pthread_t *`](https://man7.org/linux/man-pages/man3/pthread_create.3.html). – G.M. Nov 23 '21 at 11:15
  • Thanks @G.M., it solves the problem! – Navxihziq Nov 23 '21 at 11:17
  • Since C++11, you really should be using `std::thread` instead of `pthreads` directly. – Remy Lebeau Nov 23 '21 at 20:17
  • Hi, @RemyLebeau thank you for your advice! But since this is a school assignment and the lecturer insisted that we should use the `pthread` provided by the OS, I guess I'll just have to live with it for a while. I'll definitely use `std::thread` in my future projects. – Navxihziq Nov 24 '21 at 06:25

1 Answers1

2

The definition of threads is incorrect. It should be:

pthread_t* threads[THREAD_NUM];
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Ton van den Heuvel
  • 10,157
  • 6
  • 43
  • 82