pthread中未定义的引用

undefined reference in pthread

本文关键字:引用 未定义 pthread      更新时间:2023-10-16

我有一个无法解决的错误。我不明白为什么引用没有定义。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 

感谢您提供的任何帮助!

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

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

C++11在这里有一大堆并发特性,这些特性实际上比pthreads 更好用

请记住,您仍然需要与pthread

链接