Created
May 19, 2019 15:04
-
-
Save diogocapela/549ba22610cf678448423a50efd773b3 to your computer and use it in GitHub Desktop.
ex07.c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <errno.h> | |
#include <fcntl.h> | |
#include <pthread.h> | |
#include <semaphore.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/mman.h> | |
#include <sys/stat.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
#include <time.h> | |
#include <unistd.h> | |
#define CHUNK_SIZE 1000 | |
#define NUMBER_OF_KEYS 10000 | |
#define NUMBER_OR_THREADS 10 | |
typedef struct { | |
int normal[5]; | |
int special; | |
} Key; | |
// Keys | |
Key keys[NUMBER_OF_KEYS]; | |
// Mutex | |
pthread_mutex_t mutex; | |
int getRandomIntBetween(int min, int max) { | |
return (rand() % max) + min; | |
} | |
void* generateKeys(void* arg) { | |
int index = *((int*)arg); | |
printf("Thread with id %lu is now running...\n", pthread_self()); | |
fflush(stdout); | |
int start = index * CHUNK_SIZE; | |
int finish = (index + 1) * CHUNK_SIZE; | |
if (pthread_mutex_lock(&mutex) != 0) { | |
perror("Error at pthread_mutex_lock()\n"); | |
} | |
int i; | |
for (i = start; i < finish; i++) { | |
int n; | |
for (n = 0; n < 5; n++) { | |
keys[i].normal[n] = getRandomIntBetween(1, 49); | |
} | |
keys[i].special = getRandomIntBetween(1, 5); | |
} | |
if (pthread_mutex_unlock(&mutex) != 0) { | |
perror("Error at pthread_mutex_unlock()\n"); | |
} | |
pthread_exit((void*)NULL); | |
} | |
int main(int argc, char* agrv[]) { | |
// Randomize Seed | |
srand(time(NULL)); | |
// Threads | |
pthread_t threads[NUMBER_OR_THREADS]; | |
// Initialize mutex | |
pthread_mutex_init(&mutex, NULL); | |
// Make each thread fill their corresponding part of the array of keys | |
int i; | |
for (i = 0; i < NUMBER_OR_THREADS; i++) { | |
int index = i; | |
pthread_create(&threads[i], NULL, generateKeys, (void*)&index); | |
} | |
// Wait for all threads to finish their job | |
int k; | |
for (k = 0; k < NUMBER_OR_THREADS; k++) { | |
pthread_join(threads[k], NULL); | |
} | |
// Destroy mutex | |
pthread_mutex_destroy(&mutex); | |
// Print generated numbers | |
int j; | |
for (j = 0; j < 15; j++) { | |
int num1 = keys[j].normal[0]; | |
int num2 = keys[j].normal[1]; | |
int num3 = keys[j].normal[2]; | |
int num4 = keys[j].normal[3]; | |
int num5 = keys[j].normal[4]; | |
int special = keys[j].special; | |
printf("%d %d %d %d %d : %d\n", num1, num2, num3, num4, num5, special); | |
fflush(stdout); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment