C++ PThreads 有问题,而不是编译

C++ having problems with PThreads, not compiling

本文关键字:编译 PThreads 有问题 C++      更新时间:2023-10-16

以下函数似乎是问题的原因"

template <class Type>
void * server_work(void * arg)
{
    int ii;
    int cno;
    Server<Type> * server = (Server<Type> *) arg;
    Customer<Type> newcust;
    for(ii=0; ii<QUEUE_LENGTH; ii++)
    {
        size_t length = rand()%(MAX_RANGE-MIN_RANGE)+MIN_RANGE ; // Generate the number, assign to variable.
        pthread_mutex_lock(&MUTEX);
        cno=CUSTOMER_COUNT;
        CUSTOMER_COUNT++;
        pthread_mutex_unlock(&MUTEX);
        newcust=Customer<Type>(cno, cno,cno,length);
        if(CUSTOMER_COUNT<=QUEUE_LENGTH)
        {
            server->IncreaseNumOfCustomers();
            for(size_t i = 0; i < length; ++i)
            {
                newcust.getLinkedList().insertFirst(1000);
            }
            server->getCustomers()[ii]=newcust;
        }
        else
        {
            break;
        }
    }
    return NULL;
}

编译器读取以下代码段时出现问题:

int main(int argc, char** argv)
{

    pthread_t threads[NUMBER_OF_SERVERS];
    int i,j;

    if(pthread_mutex_init(&MUTEX, NULL))
    {
        cout<<"Unable to initialize a MUTEX"<<endl;
        return -1;
    }
    Server<int> servs[NUMBER_OF_SERVERS];
    for(i = 0; i < NUMBER_OF_SERVERS; i++)
    {
        servs[i].setServerNum(i);
        pthread_create(threads+i, NULL, server_work, (void *)&servs[i]);//<<--compiler flags here
    }
    // Synchronization point
    for(i = 0; i < NUMBER_OF_SERVERS; i++)
    {
        pthread_join(*(threads+i), NULL);
    }
    cout<<"SERVER-NOtCUSTOMER-NOtARRIVAL-TIMEtWAITING-TIMEtTRANSACTION-TIME"<<endl;
    for(i = 0; i < NUMBER_OF_SERVERS; i++)
    {
        for(j=0; j<servs[i].getCustomersServed(); j++)
        {
            cout<<i<<"tt"<<servs[i].getCustomers()[j].getCustomerNumber()<<"tt"<<servs[i].getCustomers()[j].getArrivalTime()<<"tt"<<servs[i].getCustomers()[j].getWaitingTime()<<"tt"<<servs[i].getCustomers()[j].getTransactionTime()<<endl;
        }
    }
    cout<<endl;
    cout<<endl;

我从编译器收到以下错误:

主.cpp:84:71:错误:不匹配将函数"server_work"转换为类型"void* ()(void)" 主.cpp:26:8:错误:候选为:模板无效* server_work(无效*)

你有错误的原型:

template <class Type>
void * server_work(void * arg)

虽然 pthread 期待这样的事情

void * server_work(void * arg)

但是,解决此问题并不难,例如:

void* CoolWrapper(void* arg)
{
     return server_work<desired_type>(arg);
}