Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <pthread.h>
- #include <math.h>
- #include <unistd.h>
- #include <errno.h>
- #include <time.h>
- pthread_mutex_t mutex;
- pthread_cond_t cond;
- int total = 0;
- int retcode;
- void* request(){
- long int numberToSleep;
- numberToSleep = (rand() % 30) + 1;
- printf("Tempo: %ld\n", numberToSleep);
- sleep(numberToSleep);
- pthread_mutex_lock(&mutex);
- total += numberToSleep;
- pthread_mutex_unlock(&mutex);
- pthread_exit(NULL);
- }
- void* timeout(){
- sleep(8);
- pthread_mutex_lock(&mutex);
- first = -1;
- pthread_cond_signal(&cond);
- }
- void* joiner(void* args){
- }
- int gateway(int num_replicas) {
- struct timeval now;
- struct timespec timeout;
- pthread_t pthreads[num_replicas];
- pthread_t threadTimeout;
- for (int i = 0; i < num_replicas; i++) {
- pthread_create(&pthreads[i], NULL, &request, NULL);
- }
- // pthread_create(threadTimeout, NULL, &timeout, NULL);
- for (int i = 0; i < num_replicas; i++) {
- pthread_join(pthreads[i], NULL);
- }
- pthread_mutex_lock(&mutex);
- gettimeofday(&now);
- printf("%d seconds\n", now.tv_sec);
- timeout.tv_sec = now.tv_sec + 15;
- timeout.tv_nsec = now.tv_usec * 1000;
- retcode = 0;
- while(total > 16) {
- retcode = pthread_cond_timedwait(&cond, &mutex, &timeout);
- if (retcode == ETIMEDOUT) {
- printf("Timeout 16s");
- total = -1;
- pthread_mutex_unlock(&mutex);
- }
- }
- pthread_mutex_unlock(&mutex);
- printf("\nTempo Total: %d\n", total);
- return total;
- }
- int main(int argc, char *argv[]){
- int num_replicas;
- scanf("%d", &num_replicas);
- gateway(num_replicas);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement