-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmulti_thread.cpp
100 lines (76 loc) · 1.97 KB
/
multi_thread.cpp
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
* NCYU 109 Network Programming
* Week 14: multiple thread exchange data
* Created by linwebs on 2021/5/24.
*/
#include <iostream>
#include <winsock.h>
using namespace std;
void *thread_add(void *thread_arg);
void *thread_sub(void *thread_arg);
/**
* structure of arguments to pass to client thread
*/
struct thread_args {
int a;
int b;
int c;
};
int main() {
// thread_id from CreateThread()
int thread_id_add;
int thread_id_sub;
// pointer to argument structure for thread
thread_args *thread_arg;
thread_arg = new thread_args;
thread_arg->a = 5;
thread_arg->b = 3;
cout << "Hello World from main()." << endl;
// thread_add
if (CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE) thread_add, thread_arg, 0, (LPDWORD) &thread_id_add) ==
nullptr) {
cout << "CreateThread() failed" << endl;
} else {
cout << "Thread " << thread_id_add << " created." << endl;
}
Sleep(1);
// thread_sub
if (CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE) thread_sub, thread_arg, 0, (LPDWORD) &thread_id_sub) ==
nullptr) {
cout << "CreateThread() failed" << endl;
} else {
cout << "Thread " << thread_id_sub << " created." << endl;
}
Sleep(30);
free(thread_arg); // deallocate memory for argument
return 0;
}
/**
* Main program of a thread_add
* @param thread_arg
* @return
*/
void *thread_add(void *thread_arg) {
int i, j, k;
i = ((struct thread_args *) thread_arg)->a;
j = ((struct thread_args *) thread_arg)->b;
k = i + j;
((struct thread_args *) thread_arg)->c = k;
// Sleep(30);
cout << i << " + " << j << " = " << ((struct thread_args *) thread_arg)->c << endl;
return nullptr;
}
/**
* Main program of a thread_sub
* @param thread_arg
* @return
*/
void *thread_sub(void *thread_arg) {
int i, j, k;
i = ((struct thread_args *) thread_arg)->a;
j = ((struct thread_args *) thread_arg)->b;
k = i - j;
((struct thread_args *) thread_arg)->c = k;
cout << i << " - " << j << " = " << ((struct thread_args *) thread_arg)->c << endl;
return nullptr;
}