(原創) 如何建立一个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

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
