C/C ++: multi-thread programming BASICS (1)

Source: Internet
Author: User

Using several articlesArticleA simple record of C and C ++ multi-thread programming BasicsProgramTo record.These chapters are organized from simple to deep,Dead dog!

Let's talk about it in the comments!

[CPP] View plaincopy
  1. # Include <iostream>
  2. # Include <pthread. h> // the header file is required and complies with POSIX standards to enable program porting to many platforms
  3. Using NamespaceSTD;
  4. # Define num_threads 5
  5. Void* Say_hello (Void* ARGs)// The Running function of the thread, which must be void *. If it is not specified, a universal pointer and a universal pointer are returned.
  6. {
  7. Cout <"Hello ..."<Endl;
  8. }
  9. IntMain ()
  10. {
  11. Pthread_t tids [num_threads];// Define the ID variable of the thread. Multiple variables can be declared as arrays.
  12. For(IntI = 0; I <num_threads; ++ I)
  13. {
  14. IntRet = pthread_create (& tids [I], null, say_hello, null );// The parameters are the ID of the created thread, the thread parameter, the name of the called function, and the input function parameters.
  15. If(Ret! = 0)
  16. {
  17. Cout <"Pthread_create error: error_code ="<RET <Endl;
  18. }
  19. }
  20. Pthread_exit (null );// Wait until the threads exit before the process ends. Otherwise, the process is forced to end and the thread may not respond;
  21. }

Compile command:

G ++-lpthread-O test. out test. cpp

Specifically, calling the static library file pthread is required, and then running the test, Owen!

[Plain] View plaincopy
      1. [CPP @ node2 pthread] $./ex_create
      2. Hello...
      3. Hello...
      4. Hello...
      5. Hello...
      6. Hello...
      7. [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.