C + +: Basics of multithreaded programming (i) ___ programming

Source: Internet
Author: User

Use a few articles simple record C and C + + multithreaded programming basic things, each one program to record, Memo. These chapters are organized from one to the other, and depend on the dead dog.

Say it in the comments, Buddha-Lou.

#include <iostream>
#include <pthread.h>//header files are required and are compliant with POSIX standards to allow programs to be ported to many platforms

using namespace std;

#define NUM_THREADS 5

void* Say_hello (void* args)//The running function of the thread, must void*, say no to return universal pointer, input generic pointer
{
    cout << " Hello ... "<< Endl;
}

int main ()
{
    pthread_t tids[num_threads];//defines the ID variable for the thread, and multiple variables can declare an array to use for
    (int i = 0; i < num_threads; ++i
    {
        int ret = pthread_create (&tids[i], NULL, Say_hello, NULL);//parameter in order: Created thread ID, thread parameter, call function name, passed function argument
        if (ret!= 0)
        {
           cout << "Pthread_create error:error_code=" << ret << Endl;
        }
    }

    Pthread_exit (NULL);//etc each thread exits, the process does not end, or the process is forced to end, the thread may not respond;
}

Compile command:

g++-lpthread-o test.out Test.cpp

Where calling the static library file pthread is necessary, and then run the test, Owen.

[cpp@node2 pthread]$, hello ... hello ... hello. ... hello .... [Cpp@node2 pthread]$ 

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.