-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_experiment.cc
More file actions
62 lines (57 loc) · 964 Bytes
/
thread_experiment.cc
File metadata and controls
62 lines (57 loc) · 964 Bytes
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
#include <pthread.h>
#include <iostream>
#include <vector>
#include <malloc.h>
/*
* This program is a simple version of multi-thread
* bubble sort. I only create one thread and pass a
* vector<int> to it.
*/
typedef struct {
int *nums;
int length;
} thread_arg;
void *bubbleSort(void * arg)
{
thread_arg *p = (thread_arg*)arg;
bool changed = true;
int swap;
while(changed)
{
changed = false;
for(int i=0; i < 10-1; i++)
{
if(p->nums[i] > p->nums[i+1])
{
swap = p->nums[i];
p->nums[i] = p->nums[i+1];
p->nums[i+1] = swap;
changed = true;
}
}
}
}
int main()
{
thread_arg *arg;
int *a;
int l = 10;
a = (int *)malloc(10*sizeof(int));
for(int i=0; i < 10; i++)
{
a[i] = 10-i;
}
for(int i=0; i < 10; i++)
{
printf("%d\n", a[i]);
}
arg->nums = a;
arg->length = l;
pthread_t t;
pthread_create(&t, NULL, bubbleSort, arg);
pthread_join(t, NULL);
for(int i=0; i < 10; i++)
{
printf("%d\n", a[i]);
}
}