鱼C论坛

 找回密码
 立即注册
查看: 1928|回复: 4

[已解决]C++多线程无法使用,报错了

[复制链接]
发表于 2022-12-1 13:48:39 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include <iostream>
#include <thread>
using namespace std;
void thread_1()
{
    while(1)
    {
        cout<<"子线程1111"<<endl;
    }
}
void thread_2(int x)
{
    while(1)
    {
        cout<<"子线程2222"<<endl;
    }
}
int main()
{
    thread first ( thread_1);     // 开启线程,调用:thread_1()
    thread second (thread_2,100);  // 开启线程,调用:thread_2(100)

    first.join();
    second.join();
    while(1)
    {
        std::cout << "主线程\n";
    }
    return 0;
}
程序报错(linux):
/usr/bin/ld: /tmp/cc3NaPCp.o: in function `std::thread::thread<void (&)(), , void>(void (&)())':
g.cpp:(.text._ZNSt6threadC2IRFvvEJEvEEOT_DpOT0_[_ZNSt6threadC5IRFvvEJEvEEOT_DpOT0_]+0x44): undefined reference to `pthread_create'
/usr/bin/ld: /tmp/cc3NaPCp.o: in function `main':
g.cpp:(.text.startup+0x57): undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
程序报错(windows):
In function 'int main()':
[Error] 'thread' was not declared in this scope
[Note] 'std::thread' is defined in header '<thread>'; did you forget to '#include <thread>'?
...
最佳答案
2022-12-1 14:47:52
Windows 不熟
Linux 编译的时候您可能需要添加一个 -lpthread 来链接到需要用到的库
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-12-1 14:47:52 | 显示全部楼层    本楼为最佳答案   
Windows 不熟
Linux 编译的时候您可能需要添加一个 -lpthread 来链接到需要用到的库

评分

参与人数 1鱼币 +5 收起 理由
zhangjinxuan + 5 感谢,linux OK了,但是Windows不知道怎样

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-12-1 14:49:03 | 显示全部楼层
dolly_yos2 发表于 2022-12-1 14:47
Windows 不熟
Linux 编译的时候您可能需要添加一个 -lpthread 来链接到需要用到的库

好的,试试
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-12-1 15:00:10 | 显示全部楼层
dolly_yos2 发表于 2022-12-1 14:47
Windows 不熟
Linux 编译的时候您可能需要添加一个 -lpthread 来链接到需要用到的库

主要是Windows
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-12-2 09:13:13 | 显示全部楼层
有人吗?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-20 20:50

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表