(原創) 如何建立一个thread? (OS) (Linux) (C/C++) (C)
此范例demo如何在Linux下建立一个thread。
1
/*
2
(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4
Filename : pthread_create.cpp
5
Compiler : gcc 4.10 on Fedora 5 / gcc 3.4 on Cygwin 1.5.21
6
Description : Demo how to create thread in Linux.
7
Release : 12/03/2006
8
Compile : g++ -lpthread pthread_create.cpp
9
*/
10
#include <stdio.h>
11
#include <stdlib.h> // exit(), EXIT_SUCCESS
12
#include <pthread.h> // pthread_create(),pthread_join()
13
14
void* helloWorld(void* arg);
15
16
int main() {
17
// Result for System call
18
int res = 0;
19
20
// Create thread
21
pthread_t thdHelloWorld;
22
res = pthread_create(&thdHelloWorld, NULL, helloWorld, NULL);
23
if (res) {
24
printf("Thread creation failed!!\n");
25
exit(EXIT_FAILURE);
26
}
27
28
// Wait for thread synchronization
29
void *threadResult;
30
res = pthread_join(thdHelloWorld, &threadResult);
31
if (res) {
32
printf("Thread join failed!!\n");
33
exit(EXIT_FAILURE);
34
}
35
36
exit(EXIT_SUCCESS);
37
}
38
39
void* helloWorld(void* arg) {
40
printf("Hello World\n");
41
}
/* 2
(C) OOMusou 2006 http://oomusou.cnblogs.com3

4
Filename : pthread_create.cpp5
Compiler : gcc 4.10 on Fedora 5 / gcc 3.4 on Cygwin 1.5.216
Description : Demo how to create thread in Linux.7
Release : 12/03/20068
Compile : g++ -lpthread pthread_create.cpp 9
*/10
#include <stdio.h>11
#include <stdlib.h> // exit(), EXIT_SUCCESS12
#include <pthread.h> // pthread_create(),pthread_join()13

14
void* helloWorld(void* arg);15

16
int main() {17
// Result for System call18
int res = 0;19

20
// Create thread21
pthread_t thdHelloWorld; 22
res = pthread_create(&thdHelloWorld, NULL, helloWorld, NULL);23
if (res) {24
printf("Thread creation failed!!\n");25
exit(EXIT_FAILURE);26
}27

28
// Wait for thread synchronization29
void *threadResult;30
res = pthread_join(thdHelloWorld, &threadResult);31
if (res) {32
printf("Thread join failed!!\n");33
exit(EXIT_FAILURE);34
}35

36
exit(EXIT_SUCCESS);37
}38

39
void* helloWorld(void* arg) {40
printf("Hello World\n");41
}


浙公网安备 33010602011771号