pthread中未定义的引用

时间:2013-08-08 03:48:18

标签: c++ pthreads undefined

我有这个错误,我无法弄清楚。我不明白为什么引用是未定义的。 pthread_attr_t先前初始化为a1,根据参数,我认为它应该是正确的。这是我的代码和错误。感谢您解决这个烂摊子的任何帮助。

#include <iostream>
#include "buffer.h"
#include <pthread.h>
#include <semaphore.h>

using namespace std; 

sem_t sem_mutex;

/* create the semaphore */
//sem_init(&sem_mutex, 0, 1);
/* acquire the semaphore */
//sem_wait(&sem_mutex);

/*** critical section ***/

/* release the semaphore */
//sem_post(&mutex);

int insert(buffer_item item);
int remove(buffer_item *item);
//void *thread_entry(void *param);
//create_mutex_lock(&mutex, NULL);
//pthread_mutex_lock(&mutex);
//release_mutex_lock(&mutex);


int insert(buffer_item item)
{
    bool added=false;
    /* insert an item into buffer */
    item=item+1;

    cout<<"The producer added "<<item<<endl;


    if (added==true)// return 0 if successful, otherwise
        return 0; //return -1 indicating an error condition */
    else
        return -1;
}

int remove(buffer_item *item) 
{
    bool removed=false;
    item=item-1;/* remove an object from buffer and placing it in item*/

    cout<<"the consumer removed "<< item<<endl;

    if(removed==true)
        return 0;// return 0 if successful
    else
        return -1;//otherwise return -1 indicating an error condition 
}
void *thread_entry(void *param) 
{   /* the entry point of a new thread */
    pthread_t new_entry;

}

/* create the mutex lock */
//create_mutex_lock(&mutex, NULL);

/* acquire the mutex lock */
//pthread_mutex_lock(&mutex);

/*** critical section ***/

/* release the mutex lock */
//release_mutex_lock(&mutex);


int main()
{
    /* 1. Answer the three command lines argument */
    pthread_t t1;
    pthread_attr_t a1;
    buffer_item buffer=0;/* 2. Initialize buffer, mutex, semaphores, and other global vars */
    buffer_item mutex=0;
    buffer_item semaphore=0;

    insert(buffer);/* 3. Create producer thread(s) */


    /* get the default attribute */
    pthread_attr_init(&a1);

    /* create a new thread */
    pthread_create(&t1, &a1, thread_entry, NULL);
//remove(*buffer);/* 4. Create consumer thread(s) */
        /* 5. Sleep */
        /* 6. Destroy mutex and semaphores */
    return 0; /* 7. Exit */
}

错误

  [Linker error] undefined reference to `_imp__pthread_attr_init' 
  [Linker error] undefined reference to `_imp__pthread_create' 
  ld returned 1 exit status 

感谢您提供的任何帮助!

1 个答案:

答案 0 :(得分:1)

您可能犯的错误是您没有使用-lpthread-pthread进行编译。

但这并不重要,因为C ++ 11具有本机线程

C ++ 11有一大堆并发功能here实际上比pthreads更好用

请注意,您仍需要与pthread链接