鱼C论坛

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

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

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

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

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

x
  1. #include <iostream>
  2. #include <thread>
  3. using namespace std;
  4. void thread_1()
  5. {
  6.     while(1)
  7.     {
  8.         cout<<"子线程1111"<<endl;
  9.     }
  10. }
  11. void thread_2(int x)
  12. {
  13.     while(1)
  14.     {
  15.         cout<<"子线程2222"<<endl;
  16.     }
  17. }
  18. int main()
  19. {
  20.     thread first ( thread_1);     // 开启线程,调用:thread_1()
  21.     thread second (thread_2,100);  // 开启线程,调用:thread_2(100)

  22.     first.join();
  23.     second.join();
  24.     while(1)
  25.     {
  26.         std::cout << "主线程\n";
  27.     }
  28.     return 0;
  29. }
复制代码

程序报错(linux):
  1. /usr/bin/ld: /tmp/cc3NaPCp.o: in function `std::thread::thread<void (&)(), , void>(void (&)())':
  2. g.cpp:(.text._ZNSt6threadC2IRFvvEJEvEEOT_DpOT0_[_ZNSt6threadC5IRFvvEJEvEEOT_DpOT0_]+0x44): undefined reference to `pthread_create'
  3. /usr/bin/ld: /tmp/cc3NaPCp.o: in function `main':
  4. g.cpp:(.text.startup+0x57): undefined reference to `pthread_create'
  5. collect2: error: ld returned 1 exit status
复制代码

程序报错(windows):

  1. In function 'int main()':
  2. [Error] 'thread' was not declared in this scope
  3. [Note] 'std::thread' is defined in header '<thread>'; did you forget to '#include <thread>'?
  4. ...
复制代码
最佳答案
2022-12-1 14:47:52
Windows 不熟
Linux 编译的时候您可能需要添加一个 -lpthread 来链接到需要用到的库
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

评分

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

查看全部评分

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

好的,试试
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

主要是Windows
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-12-2 09:13:13 | 显示全部楼层
有人吗?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-4-23 01:35

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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