View difference between Paste ID: rpgkppB0 and vHKqJcum
SHOW: | | - or go back to the newest paste.
1
#define _GNU_SOURCE 
2
#include <stdio.h>
3
#include <stdlib.h>
4
#include <pthread.h>
5
#include <time.h>
6
#include <unistd.h>
7
8
#define		DATA_SIZE		((int)	100)
9
#define		NUM_THREADS 	((int)	40)
10
#define		NUM_SWAPS		((int)	 2000000)
11
12
int data[DATA_SIZE];
13
14
pthread_mutex_t m;
15
16
void *B(void *arg)
17
{
18
	while(1) {
19
		sleep(1);
20
		printf("*\n");
21
		int *instancount=(int*)malloc(sizeof(int)*DATA_SIZE); 
22
		for(int i=0;i<DATA_SIZE;i++)
23
		{
24
			instancount[i]=0;
25
		}
26
		//pthread_mutex_lock(&m);
27
		for(int i=0;i<DATA_SIZE;i++)
28
		{
29
			instancount[data[i]]++;
30
		}
31
		//pthread_mutex_unlock(&m);
32
		int errors=0;
33
		for(int i=0;i<DATA_SIZE;i++)
34
		{
35
			if(instancount[data[i]]!=1)
36
				errors++;
37
		}
38
		if(errors>0)
39
			printf("Count Missing = %d\n",errors);
40
	}
41
}
42
43
//check that each number from 0 to n occurs exactly once in the array
44
pthread_t DataSpawn()
45
{
46
	pthread_t tid;
47
	pthread_attr_t attr;
48
	pthread_attr_init(&attr);
49
	pthread_create(&tid,&attr,B,NULL);
50
	//pthread_join(tid,NULL);
51
	return tid; 		
52
}
53
54
void swap(int *a, int *b)
55
{
56
	int temp;
57
	temp = *a;
58
	*a = *b;
59
	*b = temp;
60
61
}
62
63
void ZeroInit()// to do: change this name later
64
{
65
	for(int i=0;(i+3)<=DATA_SIZE+2;i++)
66
	{
67
		data[i]=i; 
68
	}
69
}
70
71
void* A(void *arg)// 
72
{
73
	int limit=NUM_SWAPS;
74
	int idx1=0;
75
	int idx2=0; 
76
	//srand(time(NULL));
77
	for(int i=0;i<limit;i++)
78
	{
79
		idx1= rand()%DATA_SIZE;
80
		idx2= rand()%DATA_SIZE;
81
		//pthread_mutex_lock(&m);
82
		swap(&data[idx1],&data[idx2]);
83
		//pthread_mutex_unlock(&m);
84
	}
85
	//return 0;
86
	pthread_exit(0);
87
}
88
89
90
91
void SpawnThreads(unsigned int n)
92
{
93
	int ret=-1;
94
	pthread_t *threadArray=malloc(sizeof(pthread_t)*n);
95
	pthread_t checkerThread;
96
	for(int i=0;i<n;i++)
97
	{
98
		ret=pthread_create(&threadArray[i],NULL,A,NULL);
99
		if(ret != 0)
100
		{
101
			printf("Pthread error"); 		
102
		}
103
		
104
	}
105
	checkerThread = DataSpawn();
106
	for(int i=0;i<n;i++)
107
	{
108
		pthread_join(threadArray[i],NULL);
109
	}
110
	pthread_cancel(checkerThread);
111
	pthread_join(checkerThread,NULL);
112
}
113
114
115
116
117
118
int main(int argc, char **argv)
119
{
120
	ZeroInit();
121
	pthread_mutex_init(&m,NULL);
122
	SpawnThreads(NUM_THREADS);
123
}