C ++ concurrent programming learning notes & lt; 2 & gt; thread management, learning notes thread

Source: Internet
Author: User

C ++ concurrent programming learning notes <2> thread management and learning notes thread
Thread Management

 

 

Basic thread management

 

Start a thread

 

<1> the simplest type

void do_some_work();std::thread my_thread(do_some_work);

 

 


<2> function object format

#include<iostream>#include<thread>using namespace std;class Say_hello{public:    void operator()(){cout<<"hello";}};int main(){    Say_hello hello;    std::thread t(hello);    t.join();    return 0;}

 

Once a thread is started, you need to explicitly decide whether to wait for it to end (through the join () function) or let it run on its own in the background (through the detach function)

If you do not decide before the std: thread object is destroyed, the program will be terminated. If you do not want to wait for the thread to end, make sure that

Before the bundle, the data it accesses is valid.

 

 

 

Wait for the thread to finish

 

Thread_name.join ();

Thread_name.detach ();

As mentioned above, you need to determine whether to wait for the thread to end before the object is destroyed. If you call the detach () function, it is generally called immediately after the thread is enabled.

What is the problem. However, if you want to call the join () function, you should be careful to select the location where the function is called. Because after the thread is enabled, join ()

An exception is thrown before the function is called, and the join () function may be skipped, resulting in an error.

 

One solution:

class thread_guard{    std::thread& t;public:    explicit thread_guard(std::thread& t_):t(t_){};    ~thread_guard()    {        if(t.joinable())         {            t.join();         }    }    thread_guard(thread_guard const&)=delete;     thread_guard& operator=(thread_guard const&)=delete;};void f(){    std::thread t(hello);    thread_guard g(t);    do_something_in_current_thread();}


In this way, when the object g analysis is structured, it will determine whether t is joinable and call t. join (), regardless of whether an exception is thrown.

 

 

 

 

Background running thread instance

 

void edit_document(std::string const& filename){    open_document_and_display_gui(filename);    while(!done_editing())    {        user_command cmd=get_user_input();        if(cmd.type==open_new_document)        {            std::string const new_name=get_filename_from_user();            std::thread t(edit_document,new_name);             t.detach();         }        else        {            process_user_input(cmd);        }    }      }


 

 

 

Passing parameters to the thread function

 

It is easy to pass parameters to a thread function. You only need to append the function parameters to the constructor of the thread.

 

Example 1

 

void f(int i,std::string const& s);std::thread t(f,3,”hello”); 

A thread object t with the entry function f (3, "hello ")

 

 

When passing a parameter with reference

 

Example 2

 

#include<iostream>#include<thread>using namespace std;void hello(int &i){    cout<<--i<<endl;}int main(){     int j=3;     cout<<j<<endl;     std::thread t(hello,ref(j));     t.join();     cout<<j<<endl;     return 0;}


 

The ref () is used to pass the object reference. The result output is 3, 2, 2.

 


 

 

 

 


 


 


 


What is the connection between java concurrent programming and multi-thread programming?

Concurrency must be implemented using multiple threads.
Web development generally does not require multithreading, but some special functions may be used.

C language Thread Programming in linux

Void thread1 ()
{
Int I;
For (I = 0; I <8; I ++)
{
Sleep (1 );
Printf ("thread1 \ n ");
}
}
Void thread2 ()
{
Int I;
For (I = 0; I <8; I ++)
{
Sleep (1 );
Printf ("thread2 \ n ");
}
}
Int main ()
{
Pthread_t id;
Int I, ret;
Ret = pthread_create (& id, NULL, (void *) thread1, NULL); // create thread 1
If (ret! = 0)
{
Printf ("Create thread error! \ R \ n ");
Exit (1 );
}

Ret = pthread_create (& id, NULL, (void *) thread2, NULL); // create thread 2
If (ret! = 0)
{
Printf ("Create thread error! \ R \ n ");
Exit (1 );
}

Sleep (10000000); // ensure that the main thread ends after both threads end.
Return 0;
}

The above program has created two threads. After multiple executions, you will find that the order of the printed information is different. I will carefully figure out the mysteries of concurrent thread execution.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.