Linux环境自学多线程报错

环境

  • 设备:Jetson Orin AGX
  • Model:Jetson AGX Orin - Jetpack 5.1.1 [L4T 35.3.1]
  • Distribution: Ubuntu 20.04 focal
  • Release: 5.10.104-tegra
  • CUDA: 11.4.315
  • cuDNN: 8.6.0.166
  • TensorRT: 5.1.1
  • VPI: 2.2.7
  • Vulkan: 1.3.204
  • OpenCV: 4.5.4 - with CUDA: NO

报错代码

// 多线程示例
#include <iostream>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>

// 队列大小
int buffer_size = 10;

// 定义了一个全局变量代表队列
std::queue<int> buffer;

// 互斥锁保证生产者和消费者的不能同时访问缓冲区
std::mutex buffer_mutex;
// 条件变量: 未满
std::condition_variable not_full;
// 条件变量: 未空
std::condition_variable not_empty;

void produce()
{
    // 生产者
    for (int i = 1; i <= 20; i++)
    {
        // 使用互斥锁
        std::unique_lock<std::mutex> lock(buffer_mutex);
        // 队列满时阻塞生产者
        not_full.wait(lock, []
                      { return buffer.size() < buffer_size; });
        // 生产产品
        buffer.push(i);
        std::cout << "生产 " << i << std::endl;
        // 唤醒消费者
        not_empty.notify_one();
    }
}
void consume()
{
    // 消费者
    while (true)
    {
        // 使用互斥锁
        std::unique_lock<std::mutex> lock(buffer_mutex);
        // 队列空时阻塞消费者
        not_empty.wait(lock, []
                       { return !buffer.empty(); });
        // 消费产品
        int val = buffer.front();
        buffer.pop();
        std::cout << "消费 " << val << std::endl;
        // 唤醒生产者
        not_full.notify_one();
        if (val == 20)
        {
            break;
        }
    }
}

int main()
{
    // 多线程
    std::thread producer(produce);
    std::thread consumer(consume);

    producer.join();
    consumer.join();
    return 0;
}


// g++ main.cpp -std=c++14 -pthread
/usr/bin/ld: /tmp/ccXbL3AS.o: in function `std::thread::thread<void (&)(), , void>(void (&)())':
main.cpp:(.text._ZNSt6threadC2IRFvvEJEvEEOT_DpOT0_[_ZNSt6threadC5IRFvvEJEvEEOT_DpOT0_]+0x30): undefined reference to `pthread_create'
/usr/bin/ld: main.cpp:(.text._ZNSt6threadC2IRFvvEJEvEEOT_DpOT0_[_ZNSt6threadC5IRFvvEJEvEEOT_DpOT0_]+0x34): undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status

解决办法

g++ main.cpp -std=c++14 -pthread

原因分析

由于pthread库不是Linux系统默认的库,连接时需要使用库libpthread.a,所以在使用pthread_create创建线程时,在编译中要加-lpthread参数

参考博客

参考博客1

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值