码迷,mamicode.com
首页 > 编程语言 > 详细

C++ Multithread Tutorial

时间:2014-05-07 17:41:05      阅读:335      评论:0      收藏:0      [点我收藏+]

标签:blog   class   code   int   string   com   

---恢复内容开始---

Example 1

Creating and terminating thread by using

pthread_create, pthread_exit(status)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <cstdlib>
#include <pthread.h>
 
using namespace std;
 
#define NUM_THREADS     5
 
void *PrintHello(void *threadid)
{
   long tid;
   tid = (long)threadid;
   cout << "Hello World! Thread ID, " << tid << endl;
   pthread_exit(NULL);
}
 
int main ()
{
   pthread_t threads[NUM_THREADS];
   int rc;
   int i;
   for( i=0; i < NUM_THREADS; i++ ){
      cout << "main() : creating thread, " << i << endl;
      rc = pthread_create(&threads[i], NULL,
                          PrintHello, (void *)i);
      if (rc){
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }
   pthread_exit(NULL);
}

compile it with g++ xxx.cpp -o test -lphread

 

Example 2

Passing Arguments to Threads

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <cstdlib>
#include <pthread.h>
 
using namespace std;
 
#define NUM_THREAD 5
 
struct thread_data  {
    int thread_id;
    char *message;
};
 
void *PrintHello(void *threadarg)  {
    struct thread_data *my_data;
    my_data = (struct thread_data*) threadarg;
 
    cout << "Thread ID : " << my_data->thread_id << endl;
    cout << "message : " << my_data->message << endl;
 
    pthread_exit(NULL);
}
 
int main()  {
    pthread_t threads[NUM_THREAD];
    struct thread_data td[NUM_THREAD];
 
    int rc;
    int i;
 
    for(i = 0; i < NUM_THREAD; i ++)  {
        cout << "main() : creating thread " << i << endl;
        td[i].thread_id = i;
        td[i].message = "This is message";
        rc = pthread_create(&threads[i], NULL, PrintHello, (void*)&td[i]);
         
        if(rc)  {
            cout << "Error : unable to create thread " << rc << endl;
            exit(-1);
        }
    }
    pthread_exit(NULL);
}

 

Example 3

Joining and Detaching thread

 

 

---恢复内容结束---

C++ Multithread Tutorial,布布扣,bubuko.com

C++ Multithread Tutorial

标签:blog   class   code   int   string   com   

原文地址:http://www.cnblogs.com/zhouzhuo/p/3710116.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!