C ++中线程的简单示例

有人可以发布一个简单的示例来说明如何在C ++中启动两个(面向对象)线程。

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

我遗漏了任何特定于OS的请求,希望任何答复的人都可以使用跨平台库进行答复。 我现在将其明确。


#1楼

创建一个您希望线程执行的函数,例如:

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

现在创建thread对象,该对象最终将调用上述函数,如下所示:

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

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

构造函数的参数是线程将执行的函数,其后是函数的参数。 线程在构建时自动启动。

如果以后要等待线程完成执行该函数,请调用:

t1.join(); 

(加入意味着调用新线程的线程将等待新线程完成执行,然后再继续执行自己的执行)。


编码

#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();
}

有关std :: thread的更多信息,请点击此处

  • 在GCC上,使用-std=c++0x -pthread编译。
  • 只要您的编译器支持此(C ++ 11)功能,这对任何操作系统都适用。

#2楼

还有一个用于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;

}

用-lpthread编译

http://en.wikipedia.org/wiki/POSIX_Threads


#3楼

在很大程度上取决于您决定使用的库。 例如,如果您使用wxWidgets库,则线程的创建将如下所示:

class RThread : public wxThread {

public:
    RThread()
        : wxThread(wxTHREAD_JOINABLE){
    }
private:
    RThread(const RThread &copy);

public:
    void *Entry(void){
        //Do...

        return 0;
    }

};

wxThread *CreateThread() {
    //Create thread
    wxThread *_hThread = new RThread();

    //Start thread
    _hThread->Create();
    _hThread->Run();

    return _hThread;
}

如果您的主线程调用CreateThread方法,则将创建一个新线程,该线程将开始执行“ Entry”方法中的代码。 在大多数情况下,您必须保留对该线程的引用才能加入或停止该线程。 更多信息在这里: wxThread文档


#4楼

好吧,从技术上讲,任何此类对象最终都将基于C风格的线程库构建,因为C ++仅在c ++ 0x中指定了一个普通的std::thread模型,该模型只是被钉住了,尚未实现。 这个问题有点系统性,从技术上讲,现有的c ++内存模型不够严格,无法为所有“发生之前”的情况提供明确定义的语义。 汉斯·勃姆(Hans Boehm)不久前就该主题撰写了一篇论文,并且在制定有关该主题的c ++ 0x标准方面发挥了作用。

http://www.hpl.hp.com/techreports/2004/HPL-2004-209.html

那就是说,有几个跨平台的线程C ++库在实践中工作得很好。 英特尔线程构建块包含一个tbb :: thread对象,该对象非常接近c ++ 0x标准,Boost具有一个boost :: thread库,其功能相同。

http://www.threadingbuildingblocks.org/

http://www.boost.org/doc/libs/1_37_0/doc/html/thread.html

使用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;
}

#5楼

#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);
}

#6楼

在搜索在新线程中调用其自己的实例方法的C ++类的示例时,会出现此问题,但我们无法以这种方式使用任何这些答案。 这是一个执行此操作的示例:

class DataManager
{
public:
    bool hasData;
    void getData();
    bool dataAvailable();
};

类.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
    }
}

请注意,此示例不会进入互斥或锁定状态。


#7楼

除非有人希望在全局命名空间中使用单独的函数,否则我们可以使用lambda函数创建线程。

使用lambda创建线程的主要优点之一是我们不需要将局部参数作为参数列表传递。 我们可以对它使用捕获列表,lambda的闭包属性将照顾生命周期。

这是示例代码

int main() {
    int localVariable = 100;

    thread th { [=](){
        cout<<"The Value of local variable => "<<localVariable<<endl;
    }}

    th.join();

    return 0;
}

到目前为止,我发现C ++ lambda是创建线程的最佳方法,尤其是对于简单的线程函数

发布了0 篇原创文章 · 获赞 2 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/asdfgh0077/article/details/104236505
今日推荐