C++ Multithread Tutorial
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C++ Multithread Tutorial,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2106字,纯文字阅读大概需要4分钟。
内容图文
![C++ Multithread Tutorial](/upload/InfoBanner/zyjiaocheng/1163/1ee09f8c0d284d0f803f816bffa6e334.jpg)
---恢复内容开始---
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
---恢复内容结束---
原文:http://www.cnblogs.com/zhouzhuo/p/3710116.html
内容总结
以上是互联网集市为您收集整理的C++ Multithread Tutorial全部内容,希望文章能够帮你解决C++ Multithread Tutorial所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。