zhangjinxuan 发表于 2022-12-1 13:48:39

C++多线程无法使用,报错了

#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_+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()':
'thread' was not declared in this scope
'std::thread' is defined in header '<thread>'; did you forget to '#include <thread>'?
...

dolly_yos2 发表于 2022-12-1 14:47:52

Windows 不熟
Linux 编译的时候您可能需要添加一个 -lpthread 来链接到需要用到的库

zhangjinxuan 发表于 2022-12-1 14:49:03

dolly_yos2 发表于 2022-12-1 14:47
Windows 不熟
Linux 编译的时候您可能需要添加一个 -lpthread 来链接到需要用到的库

好的,试试

zhangjinxuan 发表于 2022-12-1 15:00:10

dolly_yos2 发表于 2022-12-1 14:47
Windows 不熟
Linux 编译的时候您可能需要添加一个 -lpthread 来链接到需要用到的库

主要是Windows{:10_282:}

zhangjinxuan 发表于 2022-12-2 09:13:13

有人吗?
页: [1]
查看完整版本: C++多线程无法使用,报错了