简体   繁体   English

试图了解C ++中的线程

[英]Trying to understand threading in C++

I am a C# programmer and i need to create a program in c++ now. 我是C#程序员,现在需要用c ++创建一个程序。 What i'm trying to achieve is make an infinite thread and give it a sleep time. 我想要达到的目的是制作一个无限线程并给它一个睡眠时间。

In c# i could easily do this like 在C#中,我可以轻松地这样做

in main function 在主要功能上

new Thread(taskfunction).Start();

and taskfunction 和任务功能

    private void taskfunction()
    {
    while(true){Thread.Sleep(2500); // do stuff}
    }

so this would work in the background as long as my program is on. 因此只要打开我的程序,它就可以在后台运行。 I am trying to achieve the same thing in c++ like: 我正在尝试在c ++中实现相同的目标:

in main function 在主要功能上

std::thread somethread(taskfunction);
somethread.join();

and taskfunction 和任务功能

void taskfunction()
{
while(true){this_thread::sleep_for(chrono::milliseconds(2500));// Do Stuff}
}

So, while c# thread starts and moves on, c++ thread waits on somethread.join(); 因此,当c#线程启动并继续运行时,c ++线程等待somethread.join(); . What is the difference and How can i achieve what i do in c# also in c++? 有什么区别?如何在c#和c ++中实现我的目标?

Thank you 谢谢

std::thread::join() block current thread of execution until thread, that you call it on, finishes it execution (returns from thread procedure). std :: thread :: join()阻止当前执行线程,直到调用它的线程完成执行(从线程过程返回)。

This is useful, if (for example) you want to create temporary threads, that should perform some computations and generate results, that you wait on and use immediately. 如果(例如)您要创建临时线程,该线程应该执行一些计算并生成结果,然后等待并立即使用,这将很有用。

In your case, you should not use this method - at least not immediately after thread's creation. 就您而言,不应使用此方法-至少不要在创建线程后立即使用此方法。 Note, however, that std::thread must be either joined or detached: 但是请注意, 必须std::thread连接或分离:

std::thread::~thread()

Destroys the thread object. 销毁线程对象。

If *this has an associated thread ( joinable() == true ), std::terminate() is called. 如果*this具有关联的线程( joinable() == true ),则调用std::terminate()

So you need to either: 因此,您需要:

  • detach() thread if it should be executed independently from main thread (resources allocated by thread will be automatically released when thread finishes its execution) detach()线程(如果它应独立于主线程执行)(由线程分配的资源将在线程完成其执行时自动释放)
  • proceed in main() and when you reach end of your program, signal thread, that it should end and then join() it. main()继续,当您到达程序末尾时,发出信号,表明该线程应该结束,然后再join()它。

您可以detach()线程使其独立。

use std::tread::detach(). 使用std :: tread :: detach()。 this function separates the thread of execution from the thread object, allowing execution to continue independently. 此函数将执行线程与线程对象分开,从而允许执行独立地继续。 Any allocated resources will be freed once the thread exits. 线程退出后,将释放所有分配的资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM