Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _GNU_SOURCE
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <time.h>
- #include <unistd.h>
- #define DATA_SIZE ((int) 100)
- #define NUM_THREADS ((int) 40)
- #define NUM_SWAPS ((int) 2000000)
- int data[DATA_SIZE];
- pthread_mutex_t m;
- void *B(void *arg)
- {
- while(1) {
- sleep(1);
- printf("*\n");
- int *instancount=(int*)malloc(sizeof(int)*DATA_SIZE);
- for(int i=0;i<DATA_SIZE;i++)
- {
- instancount[i]=0;
- }
- //pthread_mutex_lock(&m);
- for(int i=0;i<DATA_SIZE;i++)
- {
- instancount[data[i]]++;
- }
- //pthread_mutex_unlock(&m);
- int errors=0;
- for(int i=0;i<DATA_SIZE;i++)
- {
- if(instancount[data[i]]!=1)
- errors++;
- }
- if(errors>0)
- printf("Count Missing = %d\n",errors);
- }
- }
- //check that each number from 0 to n occurs exactly once in the array
- pthread_t DataSpawn()
- {
- pthread_t tid;
- pthread_attr_t attr;
- pthread_attr_init(&attr);
- pthread_create(&tid,&attr,B,NULL);
- //pthread_join(tid,NULL);
- return tid;
- }
- void swap(int *a, int *b)
- {
- int temp;
- temp = *a;
- *a = *b;
- *b = temp;
- }
- void ZeroInit()// to do: change this name later
- {
- for(int i=0;(i+3)<=DATA_SIZE+2;i++)
- {
- data[i]=i;
- }
- }
- void* A(void *arg)//
- {
- int limit=NUM_SWAPS;
- int idx1=0;
- int idx2=0;
- //srand(time(NULL));
- for(int i=0;i<limit;i++)
- {
- idx1= rand()%DATA_SIZE;
- idx2= rand()%DATA_SIZE;
- //pthread_mutex_lock(&m);
- swap(&data[idx1],&data[idx2]);
- //pthread_mutex_unlock(&m);
- }
- //return 0;
- pthread_exit(0);
- }
- void SpawnThreads(unsigned int n)
- {
- int ret=-1;
- pthread_t *threadArray=malloc(sizeof(pthread_t)*n);
- pthread_t checkerThread;
- for(int i=0;i<n;i++)
- {
- ret=pthread_create(&threadArray[i],NULL,A,NULL);
- if(ret != 0)
- {
- printf("Pthread error");
- }
- }
- checkerThread = DataSpawn();
- for(int i=0;i<n;i++)
- {
- pthread_join(threadArray[i],NULL);
- }
- pthread_cancel(checkerThread);
- pthread_join(checkerThread,NULL);
- }
- int main(int argc, char **argv)
- {
- ZeroInit();
- pthread_mutex_init(&m,NULL);
- SpawnThreads(NUM_THREADS);
- }
Add Comment
Please, Sign In to add comment