C++ 中线程的简单示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/266168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple example of threading in C++
提问by Zak
Can someone post a simple example of starting two (Object Oriented) threads in C++.
有人可以发布一个在 C++ 中启动两个(面向对象)线程的简单示例。
I'm looking for actual C++ thread objects that I can extend run methods on (or something similar) as opposed to calling a C-style thread library.
我正在寻找可以扩展运行方法(或类似的东西)而不是调用 C 样式线程库的实际 C++ 线程对象。
I left out any OS specific requests in the hopes that whoever replied would reply with cross platform libraries to use. I'm just making that explicit now.
我省略了任何特定于操作系统的请求,希望回复的人会回复要使用的跨平台库。我现在只是明确说明这一点。
回答by MasterMastic
Create a function that you want the thread to execute, eg:
创建一个您希望线程执行的函数,例如:
void task1(std::string msg)
{
std::cout << "task1 says: " << msg;
}
Now create the thread
object that will ultimately invoke the function above like so:
现在创建thread
最终将调用上述函数的对象,如下所示:
std::thread t1(task1, "Hello");
(You need to #include <thread>
to access the std::thread
class)
(您需要#include <thread>
访问std::thread
该类)
The constructor's arguments are the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction.
构造函数的参数是线程将执行的函数,后跟函数的参数。线程在构造时自动启动。
If later on you want to wait for the thread to be done executing the function, call:
如果稍后您想等待线程完成执行函数,请调用:
t1.join();
(Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution).
(加入意味着调用新线程的线程将等待新线程完成执行,然后才能继续自己的执行)。
The Code
编码
#include <string>
#include <iostream>
#include <thread>
using namespace std;
// The function we want to execute on the new thread.
void task1(string msg)
{
cout << "task1 says: " << msg;
}
int main()
{
// Constructs the new thread and runs it. Does not block execution.
thread t1(task1, "Hello");
// Do other things...
// Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
t1.join();
}
More information about std::thread here
- On GCC, compile with
-std=c++0x -pthread
. - This should work for any operating-system, granted your compiler supports this (C++11) feature.
- 在 GCC 上,使用
-std=c++0x -pthread
. - 这应该适用于任何操作系统,前提是您的编译器支持此 (C++11) 功能。
回答by Edward KMETT
Well, technically any such object will wind up being built over a C-style thread library because C++ only just specified a stock std::thread
model in c++0x, which was just nailed down and hasn't yet been implemented. The problem is somewhat systemic, technically the existing c++ memory model isn't strict enough to allow for well defined semantics for all of the 'happens before' cases. Hans Boehm wrote an paper on the topic a while back and was instrumental in hammering out the c++0x standard on the topic.
好吧,从技术上讲,任何这样的对象最终都会在 C 风格的线程库上构建,因为 C++ 只是std::thread
在 c++0x 中指定了一个库存模型,该模型刚刚确定并且尚未实现。这个问题有点系统性,从技术上讲,现有的 c++ 内存模型不够严格,无法为所有“发生在之前”的情况提供明确定义的语义。Hans Boehm 不久前写了一篇关于该主题的论文,并在制定有关该主题的 c++0x 标准方面发挥了重要作用。
http://www.hpl.hp.com/techreports/2004/HPL-2004-209.html
http://www.hpl.hp.com/techreports/2004/HPL-2004-209.html
That said there are several cross-platform thread C++ libraries that work just fine in practice. Intel thread building blocks contains a tbb::thread object that closely approximates the c++0x standard and Boost has a boost::thread library that does the same.
也就是说,有几个跨平台线程 C++ 库在实践中工作得很好。Intel 线程构建块包含一个 tbb::thread 对象,该对象非常接近 c++0x 标准,而 Boost 有一个 boost::thread 库,可以执行相同的操作。
http://www.threadingbuildingblocks.org/
http://www.threadingbuildingblocks.org/
http://www.boost.org/doc/libs/1_37_0/doc/html/thread.html
http://www.boost.org/doc/libs/1_37_0/doc/html/thread.html
Using boost::thread you'd get something like:
使用 boost::thread 你会得到类似的东西:
#include <boost/thread.hpp>
void task1() {
// do stuff
}
void task2() {
// do stuff
}
int main (int argc, char ** argv) {
using namespace boost;
thread thread_1 = thread(task1);
thread thread_2 = thread(task2);
// do other stuff
thread_2.join();
thread_1.join();
return 0;
}
回答by Hohenheimsenberg
There is also a POSIX library for POSIX operating systems. Checkfor compatability
还有一个用于 POSIX 操作系统的 POSIX 库。 检查兼容性
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>
void *task(void *argument){
char* msg;
msg = (char*)argument;
std::cout<<msg<<std::endl;
}
int main(){
pthread_t thread1, thread2;
int i1,i2;
i1 = pthread_create( &thread1, NULL, task, (void*) "thread 1");
i2 = pthread_create( &thread2, NULL, task, (void*) "thread 2");
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
return 0;
}
compile with -lpthread
用 -lpthread 编译
回答by Caner
#include <thread>
#include <iostream>
#include <vector>
using namespace std;
void doSomething(int id) {
cout << id << "\n";
}
/**
* Spawns n threads
*/
void spawnThreads(int n)
{
std::vector<thread> threads(n);
// spawn n threads:
for (int i = 0; i < n; i++) {
threads[i] = thread(doSomething, i + 1);
}
for (auto& th : threads) {
th.join();
}
}
int main()
{
spawnThreads(10);
}
回答by livingtech
When searching for an example of a C++ class that calls one of its own instance methods in a new thread, this question comes up, but we were not able to use any of these answers that way. Here's an example that does that:
在搜索在新线程中调用其自己的实例方法之一的 C++ 类的示例时,会出现这个问题,但我们无法以这种方式使用这些答案中的任何一个。这是一个这样做的例子:
Class.h
类.h
class DataManager
{
public:
bool hasData;
void getData();
bool dataAvailable();
};
Class.cpp
类.cpp
#include "DataManager.h"
void DataManager::getData()
{
// perform background data munging
hasData = true;
// be sure to notify on the main thread
}
bool DataManager::dataAvailable()
{
if (hasData)
{
return true;
}
else
{
std::thread t(&DataManager::getData, this);
t.detach(); // as opposed to .join, which runs on the current thread
}
}
Note that this example doesn't get into mutex or locking.
请注意,此示例未涉及互斥锁或锁定。
回答by Daksh
Unless one want a separate function in global namespacs, we can use lambda functions for creating threads.
除非想要在全局命名空间中使用单独的函数,否则我们可以使用 lambda 函数来创建线程。
One of the major advantage of creating thread using lambda is that we don't need to pass local parameters as an argument list. We can use capture list for the same and the closure property of lambda will take care of the lifecycle.
使用 lambda 创建线程的主要优点之一是我们不需要将本地参数作为参数列表传递。我们可以使用捕获列表,并且 lambda 的闭包属性将处理生命周期。
Here is a sample code
这是一个示例代码
int main() {
int localVariable = 100;
thread th { [=](){
cout<<"The Value of local variable => "<<localVariable<<endl;
}}
th.join();
return 0;
}
By far, I've found C++ lambdas to be the best way of creating threads especially for simpler thread functions
到目前为止,我发现 C++ lambdas 是创建线程的最佳方式,尤其是对于更简单的线程函数
回答by LorenzCK
It largely depends on the library you decide to use. For instance, if you use the wxWidgets library, the creation of a thread would look like this:
这在很大程度上取决于您决定使用的库。例如,如果您使用 wxWidgets 库,线程的创建将如下所示:
class RThread : public wxThread {
public:
RThread()
: wxThread(wxTHREAD_JOINABLE){
}
private:
RThread(const RThread ©);
public:
void *Entry(void){
//Do...
return 0;
}
};
wxThread *CreateThread() {
//Create thread
wxThread *_hThread = new RThread();
//Start thread
_hThread->Create();
_hThread->Run();
return _hThread;
}
If your main thread calls the CreateThread method, you'll create a new thread that will start executing the code in your "Entry" method. You'll have to keep a reference to the thread in most cases to join or stop it. More info here: wxThread documentation
如果您的主线程调用 CreateThread 方法,您将创建一个新线程,该线程将开始执行“Entry”方法中的代码。在大多数情况下,您必须保留对线程的引用才能加入或停止它。更多信息:wxThread 文档