在C ++中简单的线程示例 [英] Simple example of threading in C++

查看:131
本文介绍了在C ++中简单的线程示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以发布一个简单的例子,在C ++中启动两个(面向对象)线程。



我正在寻找实际的C ++线程对象,我可以扩展运行方法(或类似的东西),而不是调用C风格的线程库。



更新 - 我没有任何操作系统特定的请求,希望谁回复将回复与跨平台库使用。

解决方案

创建一个你希望线程执行的函数。我将演示一个简单的例子:

  void task1(std :: string msg)
{
std :: cout<< task1说:< msg;
}



现在创建线程对象,它将最终调用上面的函数,如下:

  std :: thread t1(task1,Hello); 

(您需要 #include< thread> 访问 std :: thread 类)



如你所见,构造函数的参数是函数



最后,将它加入到你的主线程中,如下所示:

  t1.join(); 

(加入意味着调用新线程的线程将等待新线程完成执行,


b b b b b b b pre> #include< string>
#include< iostream>
#include< thread>

using namespace std;

//我们想在新线程上执行的函数。
void task1(string msg)
{
cout<< task1说:< msg;
}

int main()
{
//构造新线程并运行它。不阻止执行。
thread t1(task1,Hello);

//使主线程等待新线程完成执行,因此阻止它自己的执行。
t1.join();
}

有关std :: thread的详细信息




  • 在GCC上, -std = c ++ 0x -pthread 。

  • 这适用于任何操作系统,授予您的编译器支持此(C ++ 11)功能。


Can someone post a simple example of starting two (Object Oriented) threads in 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.

Update - 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.

解决方案

Create a function that you want the thread to execute. I'll demonstrate with a trivial example:

void task1(std::string msg)
{
    std::cout << "task1 says: " << msg;
}

Now create the thread object that will ultimately invoke the function above like so:

std::thread t1(task1, "Hello");

(You need to #include <thread> to access the std::thread class)

As you can see, the constructor's arguments are the function the thread will execute, followed by the function's parameters.

Finally, join it to your main thread of execution like so:

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 it's 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");

    // 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.

这篇关于在C ++中简单的线程示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆