text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> void* SHM_alloc(char* shm_name, size_t len) { int fd = shm_open(shm_name, O_RDWR|O_CREAT,0644); if(fd < 0) { printf("create share memory error."); return 0; } if(ftruncate(fd,len)!=0) { error("truncate share memory error."); return 0; } void* shm_vir_addr = mmap(0,len,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); if(shm_vir_addr) mlock(shm_vir_addr,len); return shm_vir_addr; } int SHM_free(char* shm_name,void* shm_vir_addr,long len) { if(munmap(shm_vir_addr,len)<0 || munlock(shm_vir_addr,len)<0) return -1; int fd = shm_open(shm_name, O_RDWR,0644); if(fd < 0) return -1; char filelock[50]; sprintf(filelock,"/dev/%s_lock",shm_name); shm_unlink(shm_name); unlink(filelock); return 0; } void* SHM_get(char* shm_name,size_t len) { int fd = shm_open(shm_name,O_RDWR,0644); if(fd < 0) return 0; void* shm_vir_addr = mmap(0,len,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); if(shm_vir_addr) mlock(shm_vir_addr,len); return shm_vir_addr; } int SHM_mutex_init(pthread_mutex_t* lock) { pthread_mutexattr_t ma; pthread_mutexattr_init(&ma); pthread_mutexattr_setpshared(&ma, PTHREAD_PROCESS_SHARED); pthread_mutexattr_setrobust(&ma, PTHREAD_MUTEX_ROBUST); return pthread_mutex_init(lock, &ma); } void SHM_mutex_lock(pthread_mutex_t* lock) { if(pthread_mutex_lock(lock) == EOWNERDEAD) { error("will consistent mutex, please check if any process has terminated while holding this mutex."); pthread_mutex_consistent(lock); } } void SHM_mutex_unlock(pthread_mutex_t* lock) { pthread_mutex_unlock(lock); } int SHM_trylock(char* lockname) { if(shm_open(lockname,O_CREAT|O_EXCL,0644)<0) return -1; return 1; } int SHM_lock(char* lockname) { int n = 0; while(shm_open(lockname,O_CREAT|O_EXCL,0644)<0) { char msg[50]; sprintf(msg,"trying lock '%s': %d times",lockname,++n); info(msg); sleep(1); } return n; } int SHM_lock_n_check(char* lockname) { int n = 0; while(shm_open(lockname,O_CREAT|O_EXCL,0644)<0) { char msg[50]; sprintf(msg,"trying lock '%s': %d times",lockname,++n); info(msg); sleep(1); } char lock[50]; char chk[50]; sprintf(lock,"/dev/shm/%s",lockname); sprintf(chk,"/dev/shm/%s_chk",lockname); int l = link(lock,chk); return l; } int SHM_unlock(char* lockname) { return shm_unlink(lockname); }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; char const LETTERS[11] = "ABCDEFGHIJ"; void* thread_print(void*); int turn = 0; int main(int argc, char const *argv[]) { long i; int j; pthread_t threads[10]; for (j = 0; j < 5; j++) { for (i = 0; i < 10; i++) pthread_create(&threads[i], 0, thread_print, (void*)i); for (i = 0; i < 10; i++) pthread_join(threads[i], 0); printf("\\n"); } return 0; } void *thread_print(void* arg) { int i; long tid = (long)(arg); pthread_mutex_lock(&mutex); if (turn % 10 != tid) pthread_cond_wait(&cond, &mutex); printf("%c", LETTERS[turn]); turn = (turn + 1) % 10; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); pthread_exit(0); }
0
#include <pthread.h> static pthread_mutex_t queue_mutex; void initBTServer(void (*acceptCallback)(), void (*readerCallback)(char*,int), void (*disconnectCallback)()) { _readerCallback = readerCallback; _acceptCallback = acceptCallback; _disconnectCallback = disconnectCallback; socketHandler = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM); loc_addr.rc_family = AF_BLUETOOTH; loc_addr.rc_bdaddr = *BDADDR_ANY; loc_addr.rc_channel = (uint8_t) 1; bind(socketHandler, (struct sockaddr *)&loc_addr, sizeof(loc_addr)); listen(socketHandler, 1); int retval; retval = pthread_create(&acceptThread, 0, acceptFunction, 0); if(retval) { fprintf(stderr,"Error - pthread_create() return code: %d\\n",retval); exit(1); } queue = initQueue(); } void *acceptFunction(void *ptr) { char buf[1024] = { 0 }; clientHandler = accept(socketHandler, (struct sockaddr *)&rem_addr, &opt); ba2str( &rem_addr.rc_bdaddr, buf ); fprintf(stderr, "accepted connection from %s\\n", buf); _acceptCallback(); int retval; retval = pthread_create(&readerThread, 0, readerLoop, 0); if(retval) { fprintf(stderr,"Error - pthread_create() return code: %d\\n",retval); exit(1); } retval = pthread_create(&writerThread, 0, writerLoop, 0); if(retval) { fprintf(stderr,"Error - pthread_create() return code: %d\\n",retval); exit(1); } } void *readerLoop(void *ptr) { char buf[1024] = { 0 }; memset(buf, 0, sizeof(buf)); reader_loop = 1; int bytes_read = 0; while (reader_loop) { bytes_read = read(clientHandler, buf, sizeof(buf)); if( bytes_read > 0 ) { printf("received [%s]\\n", buf); _readerCallback(buf, bytes_read); } } } void *writerLoop(void *ptr) { writer_loop = 1; int status; while (writer_loop) { pthread_mutex_lock(&queue_mutex); char *buf = (char *)takeFromQueue(queue); pthread_mutex_unlock(&queue_mutex); if (buf != 0) { status = write(clientHandler, buf, sizeof(buf)); free(buf); buf = 0; if (status < 0) { perror("Error while writint to bluetoth client"); writer_loop = 0; _disconnectCallback(); break; } } } } void btWrite(char *buf, int size) { pthread_mutex_lock(&queue_mutex); pushToQueue(queue, (void*)buf); pthread_mutex_unlock(&queue_mutex); } void stopBTServer() { reader_loop = 0; writer_loop = 0; pthread_join( readerThread, 0); pthread_join( writerThread, 0); close(clientHandler); close(socketHandler); destroyQueue(queue); }
1
#include <pthread.h> int summer_shared_index; pthread_mutex_t max_mutex, thresh_mutex, summ_mutex; struct summ_args { int ma; double *a, *afunc, *sum; }; void *dataworker() { } void *summer(void * packed_args) { struct summ_args *args = (struct summ_args *)packed_args; int ma = args->ma; double *a = args->a, *afunc = args->afunc, *sum = args->sum; int local_index; double partial_sum = 0; do { pthread_mutex_lock(&summ_mutex); local_index = summer_shared_index; summer_shared_index++; pthread_mutex_unlock(&summ_mutex); if (local_index <= ma) { partial_sum += (*(a+local_index)) * (*(afunc+local_index)); } } while (local_index <= ma); pthread_mutex_lock(&summ_mutex); *sum += partial_sum; pthread_mutex_unlock(&summ_mutex); return 0; } void svdfit_d(double x[], double y[], double sig[], int ndata, double a[], int ma, double **u, double **v, double w[], double *chisq, void (*funcs)(double, double [], int)) { void svbksb_d(double **u, double w[], double **v, int m, int n, double b[], double x[]); void svdcmp_d(double **a, int m, int n, double w[], double **v); int j,i,k; double wmax,tmp,thresh,sum,*b,*afunc; b=dvector(1,ndata); afunc=dvector(1,ma); for (i=1;i<=ndata;i++) { (*funcs)(x[i],afunc,ma); for (j=1;j<=ma;j++) u[i][j]=afunc[j]/sig[i]; b[i]=y[i]/sig[i]; } svdcmp_d(u,ndata,ma,w,v); wmax=0.0; double *wptr = &(w[1]); for (j=1;j<=ma;j++, wptr++) if (*(wptr) > wmax) wmax=*(wptr); thresh=1.0e-12*wmax; wptr = &(w[1]); for (j=1;j<=ma;j++,wptr++) if (*(wptr) < thresh) *(wptr)=0.0; svbksb_d(u,w,v,ndata,ma,b,a); *chisq=0.0; for (i=1; i<=ndata; i++) { (*funcs)(x[i],afunc,ma); for (sum=0.0,j=1;j<=ma;j++) sum += a[j] * afunc[j]; *chisq += (tmp=(y[i]-sum)/sig[i], tmp*tmp); } free_dvector(afunc,1,ma); free_dvector(b,1,ndata); }
0
#include <pthread.h> extern char **environ; pthread_mutex_t env_mutex; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void thread_init(void) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&env_mutex, &attr); pthread_mutexattr_destroy(&attr); } int getenv_r(const char *name, char *buf, int buflen) { int i, len, olen; pthread_once(&init_done, thread_init); len = strlen(name); pthread_mutex_lock(&env_mutex); for (i = 0; environ[i] != 0; i++) { if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { olen = strlen(&environ[i][len+1]); if (olen >= buflen) { pthread_mutex_unlock(&env_mutex); return(ENOSPC); } strcpy(buf, &environ[i][len+1]); pthread_mutex_unlock(&env_mutex); return(0); } } pthread_mutex_unlock(&env_mutex); return(ENOENT); }
1
#include <pthread.h> struct TErrNode { struct TErrNode *next; pthread_t thread; size_t used; size_t size; struct LineInfo { char file[64]; char function[64]; size_t line; } *stack; } ; static struct TErrNode *top = 0; static pthread_mutex_t mutex; static struct TErrNode *getnode(); static void errchkinit(void) ; void errchkinit(void) { pthread_mutex_init(&mutex, 0); } struct TErrNode *getnode() { pthread_t thread; struct TErrNode *node; thread = pthread_self(); for (node = top; node != 0; node = node->next) { if (node->thread == thread) { return node; } } assert((node = (struct TErrNode *)malloc(sizeof(struct TErrNode))) != 0); node->thread = thread; node->next = top; node->used = 0; node->size = 1; assert((node->stack = (struct LineInfo *)malloc(node->size*sizeof(struct LineInfo))) != 0); return node; } void errchkcleanup() { pthread_t thread; struct TErrNode **prev, *node; thread = pthread_self(); pthread_mutex_lock(&mutex); for (prev = &top, node = top; node != 0; prev = &node->next, node = node->next) { if (pthread_equal(node->thread, thread)) { *prev = node->next; free(node->stack); free(node); } } pthread_mutex_unlock(&mutex); } void pushlineinfo(const char *file, const char *function, size_t line) { struct TErrNode *node; pthread_mutex_lock(&mutex); node = getnode(); if (node->used + 1 > node->size) { node->size *= 2; assert((node->stack = realloc(node->stack, node->size*sizeof(struct LineInfo))) != 0); } strncpy(node->stack[node->used].file, file, sizeof(node->stack[node->used].file) - 1); strncpy(node->stack[node->used].function, function, sizeof(node->stack[node->used].function) - 1); node->stack[node->used].line = line; node->used++; pthread_mutex_unlock(&mutex); } void printlineinfo() { struct TErrNode *node; size_t i; pthread_mutex_lock(&mutex); node = getnode(); assert(fprintf(stderr, "Error Trace:\\n") >= 0); for (i = 0; i < node->used; i++) { assert(fprintf(stderr, "file:%s:%s:%ld\\n", node->stack[i].file, node->stack[i].function, node->stack[i].line) >= 0); } pthread_mutex_unlock(&mutex); }
0
#include <pthread.h> int id; double balance; bool bInUse; pthread_mutex_t mutex; pthread_cond_t freeAcc; } Account; Account bank[5]; pthread_mutex_t lock[5]; bool withdraw(Account* acc, double amount) { pthread_mutex_lock(&lock[acc->id]); if(acc->balance - amount >= 0) { acc->balance -= amount; pthread_mutex_unlock(&lock[acc->id]); return 1; } return 0; } void deposit(Account* acc, double amount) { pthread_mutex_lock(&lock[acc->id]); acc->balance += amount; pthread_mutex_unlock(&lock[acc->id]); } void transfer(Account* from, Account* to, double amount) { Account* acc1 = from; Account* acc2 = to; bool bDone = withdraw(from,amount); if(bDone) deposit(to,amount); } double bankInit() { double sum = 0; int i; for(i=0;i<5;i++) { bank[i].id = i; bank[i].balance = 10000; bank[i].bInUse = 0; sum += bank[i].balance; if (pthread_mutex_init(&bank[i].mutex, 0) != 0) { printf("mutex error\\n"); } if (pthread_cond_init(&bank[i].freeAcc, 0) != 0) { printf("error initializing condition\\n"); } } return sum; } void* randomMoves(void *args){ double amount = (double)(rand()%500); int ac1 = rand()%5 , ac2 = rand()%5; while(ac1 == ac2)ac2 = rand()%5; deposit(&bank[ac1],amount); if(!withdraw(&bank[ac2],amount)){ withdraw(&bank[ac1],amount); } transfer(&bank[ac1],&bank[ac2],amount); } int main(int argc, char *argv[]) { time_t t; srand((unsigned) time(&t)); int i; for(i = 0; i < 5 ; ++i) if( pthread_mutex_init(&lock[i],0) != 0){ printf("Error creating the lock\\n"); } double sum = bankInit(); printf("Initial bank capital: %f\\n",sum); pthread_t tid[10000]; for(i = 0 ; i < 10000 ; ++i){ pthread_create(&tid[i], 0,randomMoves,(void *)0); } int e = 0; for(i = 0 ; i < 10000 ; ++i) if(pthread_join(tid[i],0)) { printf("Error joining thread\\n"); return 2; } double sumEnd = 0; for(i=0;i<5;i++) { printf("Account %d balance : %f\\n",i,bank[i].balance); sumEnd += bank[i].balance; } if(sumEnd != sum) printf("ERROR : ******** CORRUPT BANK!!!!!! *******"); else printf("Final bank sum: %f\\n",sum); return 0; }
1
#include <pthread.h> int grades[10] = {0}; int total_grade = 0; int total_bellcurve = 0; pthread_barrier_t barr1; pthread_barrier_t barr2; pthread_mutex_t mutex; void* read_grades(){ FILE *grade_file = fopen("grades.txt","r"); if(grade_file == 0){ perror("Error opening file.\\n"); exit(1); } for(int j=0; j<10; j++){ fscanf(grade_file, "%d", &grades[j]); } fclose(grade_file); pthread_barrier_wait(&barr1); return 0; } void* save_bellcurve(void *arg){ int *grade = (int *) arg; pthread_mutex_lock(&mutex); total_grade += *grade; *grade = *grade * 1.5; total_bellcurve += *grade; pthread_mutex_unlock(&mutex); pthread_barrier_wait(&barr2); return 0; } int main() { pthread_t read; if(pthread_barrier_init(&barr1, 0, 2)){ printf("Could not initialize barrier.\\n"); } pthread_create(&read, 0, read_grades, (void *) "Read"); int rc = pthread_barrier_wait(&barr1); if(rc!=0 && rc!=PTHREAD_BARRIER_SERIAL_THREAD){ printf("Could not wait on barrier.\\n"); } if(pthread_barrier_init(&barr2, 0, sizeof(grades)/sizeof(grades[0])+1)){ printf("Could not initialize barrier.\\n"); } if(pthread_mutex_init(&mutex, 0)) { printf("Unable to initialize a mutex\\n"); return -1; } pthread_t bell[10]; for(int i=0; i<10; i++){ pthread_create(&bell[i], 0, save_bellcurve, (void *) &grades[i]); } rc = pthread_barrier_wait(&barr2); if(rc!=0 && rc!=PTHREAD_BARRIER_SERIAL_THREAD){ printf("Could not wait on barrier.\\n"); } pthread_mutex_destroy(&mutex); printf("Pre-Bellcurve Grade Total: %d, Pre-Bellcurve Grade Average: %d\\n", total_grade, (total_grade/10)); printf("Post-Bellcurve Grade Total: %d, Post-Bellcurve Grade Average: %d\\n", total_bellcurve, (total_bellcurve/10)); FILE *bellcurved_grades = fopen("bellcurved_grades.txt", "w"); for(int i=0; i<10; i++){ fprintf(bellcurved_grades, "%d\\n", grades[i]); } fclose(bellcurved_grades); return 0; }
0
#include <pthread.h> void *Producer(void *arg); void *Consumer(void *arg); time_t time; int no; pid_t kernelThreadID; pthread_t posixThreadID; } InfoStruct; sem_t full, empty; pthread_mutex_t mutex; int bufferSize = 0; InfoStruct buffer[5]; int main(void) { pthread_t producer[2], consumer[2]; void *proRes, *conRes; int res, i; res = sem_init(&full, 0, 0); if(res != 0) { perror("Semaphore full initialization"); exit(1); } res = sem_init(&empty, 0, 5); if(res != 0) { perror("Semaphore empty initialization"); exit(1); } res = pthread_mutex_init(&mutex, 0); if(res != 0) { errno = res; perror("Mutex initialization"); exit(1); } for(i = 0; i < 2; i++) { res = pthread_create(&consumer[i], 0, Consumer, 0); if(res != 0) { errno = res; perror("Thread consumer creation"); exit(1); } res = pthread_create(&producer[i], 0, Producer, 0); if(res != 0) { errno = res; perror("Thread producer creation"); exit(1); } } printf("\\nWaiting for thread Consumers and Producers to finish...\\n"); for(i = 0; i < 2; i++) { res = pthread_join(consumer[i], &conRes); if(res != 0) { perror("Thread consumer join"); exit(1); } printf("Thread consumer %d joined.\\n", i); res = pthread_join(producer[i], &proRes); if(res != 0) { perror("Thread producer join"); exit(1); } printf("Thread producer %d joined.\\n", i); } res = sem_destroy(&full); if(res != 0) { perror("Semaphore full destroy"); exit(1); } res = sem_destroy(&empty); if(res != 0) { perror("Semaphore empty destroy"); exit(1); } res = pthread_mutex_destroy(&mutex); if(res != 0) { perror("Mutex destroy"); exit(1); } exit(0); } void *Producer(void *arg) { int no; for(no = 1; no <= 10; no++) { sem_wait(&empty); pthread_mutex_lock(&mutex); time(&buffer[bufferSize].time); buffer[bufferSize].no = no; buffer[bufferSize].kernelThreadID = syscall(SYS_gettid); buffer[bufferSize].posixThreadID = pthread_self(); bufferSize++; sleep(1); pthread_mutex_unlock(&mutex); sem_post(&full); } pthread_exit(0); } void *Consumer(void *arg) { int i; for(i = 0; i < 10; i++) { sem_wait(&full); pthread_mutex_lock(&mutex); bufferSize--; printf("kernel thread ID: %d, POSIX thread ID: 0x%x, No. %d, time: %s", buffer[bufferSize].kernelThreadID, (unsigned int)buffer[bufferSize].posixThreadID, buffer[bufferSize].no, asctime(localtime(&buffer[bufferSize].time))); sleep(1); pthread_mutex_unlock(&mutex); sem_post(&empty); } pthread_exit(0); }
1
#include <pthread.h> struct mt { int num; pthread_mutex_t mutex; pthread_mutexattr_t mutexattr; }; int main(void) { int fd, i; struct mt *mm; pid_t pid; fd = open("mt_test", O_CREAT | O_RDWR, 0777); ftruncate(fd, sizeof(*mm)); mm = mmap(0, sizeof(*mm), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); close(fd); memset(mm, 0, sizeof(*mm)); pthread_mutexattr_init(&mm->mutexattr); pthread_mutexattr_setpshared(&mm->mutexattr,PTHREAD_PROCESS_SHARED); pthread_mutex_init(&mm->mutex, &mm->mutexattr); pid = fork(); if (pid == 0){ for (i=0;i<10;i++){ pthread_mutex_lock(&mm->mutex); mm->num += 1; printf("子进程:num = :%d\\n",mm->num); pthread_mutex_unlock(&mm->mutex); sleep(0.2); } } else if (pid > 0) { for (i=0; i<10; i++){ pthread_mutex_lock(&mm->mutex); mm->num += 1; printf("父进程:num = :%d\\n",mm->num); pthread_mutex_unlock(&mm->mutex); sleep(0.2); } wait(0); } pthread_mutex_destroy(&mm->mutex); pthread_mutexattr_destroy(&mm->mutexattr); munmap(mm,sizeof(*mm)); unlink("mt_test"); return 0; }
0
#include <pthread.h> static pthread_mutex_t *config_openssl_mutexes; static void gfarm_openssl_lock(int mode, int n, const char *file, int line) { if (mode & CRYPTO_LOCK) pthread_mutex_lock(&config_openssl_mutexes[n]); else pthread_mutex_unlock(&config_openssl_mutexes[n]); } static unsigned long gfarm_openssl_threadid(void) { return (pthread_self()); } void gfarm_openssl_initialize() { int num_locks, i; static int initialized = 0; static const char diag[] = "gfarm_openssl_initialize"; if (initialized) return; SSL_library_init(); num_locks = CRYPTO_num_locks(); GFARM_MALLOC_ARRAY(config_openssl_mutexes, num_locks); if (config_openssl_mutexes == 0) gflog_fatal(GFARM_MSG_1004292, "%s: no memory", diag); for (i = 0; i < num_locks; ++i) pthread_mutex_init(&config_openssl_mutexes[i], 0); CRYPTO_set_locking_callback(gfarm_openssl_lock); CRYPTO_set_id_callback(gfarm_openssl_threadid); initialized = 1; }
1
#include <pthread.h> pthread_mutex_t barrier; pthread_mutex_t minBarrier; pthread_mutex_t maxBarrier; pthread_cond_t go; int numWorkers; int numArrived = 0; int value; int xIndex; int yIndex; } MINMAX; MINMAX min; MINMAX max; void Barrier() { pthread_mutex_lock(&barrier); numArrived++; if (numArrived == numWorkers) { numArrived = 0; pthread_cond_broadcast(&go); } else pthread_cond_wait(&go, &barrier); pthread_mutex_unlock(&barrier); } double read_timer() { static bool initialized = 0; static struct timeval start; struct timeval end; if( !initialized ) { gettimeofday( &start, 0 ); initialized = 1; } gettimeofday( &end, 0 ); return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec); } double start_time, end_time; int size, stripSize; int sums[10]; int matrix[10000][10000]; void *worker(void *); int main(int argc, char *argv[]) { int i, j; long l; pthread_attr_t attr; pthread_t workerid[10]; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); pthread_mutex_init(&barrier, 0); pthread_mutex_init(&minBarrier,0); pthread_mutex_init(&maxBarrier,0); pthread_cond_init(&go, 0); size = (argc > 1)? atoi(argv[1]) : 10000; numWorkers = (argc > 2)? atoi(argv[2]) : 10; if (size > 10000) size = 10000; if (numWorkers > 10) numWorkers = 10; stripSize = size/numWorkers; for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { matrix[i][j] = rand()%99; } } min.value = matrix[0][0]; max.value = matrix[0][0]; start_time = read_timer(); for (l = 0; l < numWorkers; l++) pthread_create(&workerid[l], &attr, worker, (void *) l); pthread_exit(0); } void * worker(void *arg) { long myid = (long) arg; int total, i, j, first, last; first = myid*stripSize; last = (myid == numWorkers - 1) ? (size - 1) : (first + stripSize - 1); total = 0; for (i = first; i <= last; i++) for (j = 0; j < size; j++) { if(matrix[i][j] > max.value) { pthread_mutex_lock(&maxBarrier); if(matrix[i][j] > max.value) { max.value = matrix[i][j]; max.yIndex = i; max.xIndex = j; } pthread_mutex_unlock(&maxBarrier); } if(matrix[i][j] < min.value) { pthread_mutex_lock(&minBarrier); if(matrix[i][j] < min.value){ min.value = matrix[i][j]; min.yIndex = i; min.xIndex = j; } pthread_mutex_unlock(&minBarrier); } total += matrix[i][j]; } sums[myid] = total; Barrier(); if (myid == 0) { total = 0; for (i = 0; i < numWorkers; i++) total += sums[i]; end_time = read_timer(); printf("The total is %d\\n", total); printf("Max value : %d\\n", max.value); printf("Max x position %d\\n", max.xIndex); printf("Max y position %d\\n", max.yIndex); printf("Min value : %d\\n", min.value); printf("Min x position %d\\n", min.xIndex); printf("Min y position %d\\n", min.yIndex); printf("The execution time is %g sec\\n", end_time - start_time); } }
0
#include <pthread.h> pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER; void *functionCount1(); void *functionCount2(); int count = 0; main() { pthread_t thread1, thread2; pthread_create( &thread1, 0, &functionCount1, 0); pthread_create( &thread2, 0, &functionCount2, 0); pthread_join( thread1, 0); pthread_join( thread2, 0); printf("Final count: %d\\n",count); exit(0); } void *functionCount1() { for(;;) { pthread_mutex_lock( &count_mutex ); pthread_cond_wait( &condition_var, &count_mutex ); count++; printf("Counter value functionCount1: %d\\n",count); pthread_mutex_unlock( &count_mutex ); if(count >= 10) return(0); } } void *functionCount2() { for(;;) { pthread_mutex_lock( &count_mutex ); if( count < 3 || count > 6 ) { pthread_cond_signal( &condition_var ); } else { count++; printf("Counter value functionCount2: %d\\n",count); } pthread_mutex_unlock( &count_mutex ); if(count >= 10) return(0); } }
1
#include <pthread.h> struct interval { double seconds; struct timespec *time_start; pthread_mutex_t *time_start_mutex; struct rusage *rusage_start; struct timespec last_time; }; static inline void set_uninitialized(struct timespec *ts) { ts->tv_sec = ts->tv_nsec = 0; } static inline int is_uninitialized(struct timespec *ts) { return ts->tv_sec == 0 && ts->tv_nsec == 0; } static void ensure_initialized(struct interval *itv, struct timespec now) { if (is_uninitialized(&itv->last_time)) { pthread_mutex_lock(itv->time_start_mutex); if (is_uninitialized(itv->time_start)) { getrusage(RUSAGE_SELF, itv->rusage_start); *itv->time_start = now; } pthread_mutex_unlock(itv->time_start_mutex); itv->last_time = *itv->time_start; } } struct interval *interval_create(double interval_in_seconds, struct thread *t) { struct interval *itv; itv = malloc(sizeof(*itv)); if (!itv) PLOG_FATAL(t->cb, "malloc"); itv->seconds = interval_in_seconds; itv->time_start = t->time_start; itv->time_start_mutex = t->time_start_mutex; itv->rusage_start = t->rusage_start; set_uninitialized(&itv->last_time); return itv; } static inline double to_seconds(struct timespec a) { return a.tv_sec + a.tv_nsec * 1e-9; } static void get_next_time(struct interval *itv, double duration) { double new_time, int_part, frac_part; new_time = to_seconds(itv->last_time); new_time += floor(duration / itv->seconds) * itv->seconds; frac_part = modf(new_time, &int_part); itv->last_time.tv_sec = int_part; itv->last_time.tv_nsec = frac_part * 1e9; } void interval_collect(struct flow *flow, struct thread *t) { struct interval *itv = flow->itv; struct timespec now; double duration; clock_gettime(CLOCK_MONOTONIC, &now); ensure_initialized(itv, now); duration = seconds_between(&itv->last_time, &now); if (duration < itv->seconds) return; add_sample(t->index, flow, &now, &t->samples, t->cb); get_next_time(itv, duration); } void interval_destroy(struct interval *itv) { if (itv) free(itv); }
0
#include <pthread.h> int timer_create (clock_id, evp, timerid) clockid_t clock_id; struct sigevent *evp; timer_t *timerid; { int retval = -1; struct timer_node *newtimer = 0; struct thread_node *thread = 0; if (0 ) { __set_errno (ENOTSUP); return -1; } if (clock_id != CLOCK_REALTIME) { __set_errno (EINVAL); return -1; } pthread_once (&__timer_init_once_control, __timer_init_once); if (__timer_init_failed) { __set_errno (ENOMEM); return -1; } pthread_mutex_lock (&__timer_mutex); newtimer = __timer_alloc (); if (__builtin_expect (newtimer == 0, 0)) { __set_errno (EAGAIN); goto unlock_bail; } if (evp != 0) newtimer->event = *evp; else { newtimer->event.sigev_notify = SIGEV_SIGNAL; newtimer->event.sigev_signo = SIGALRM; newtimer->event.sigev_value.sival_int = timer_ptr2id (newtimer); newtimer->event.sigev_notify_function = 0; } newtimer->event.sigev_notify_attributes = &newtimer->attr; newtimer->creator_pid = getpid (); switch (__builtin_expect (newtimer->event.sigev_notify, SIGEV_SIGNAL)) { case SIGEV_NONE: case SIGEV_SIGNAL: thread = &__timer_signal_thread_rclk; if (! thread->exists) { if (__builtin_expect (__timer_thread_start (thread), 1) < 0) { __set_errno (EAGAIN); goto unlock_bail; } } break; case SIGEV_THREAD: if (evp->sigev_notify_attributes) newtimer->attr = *(pthread_attr_t *) evp->sigev_notify_attributes; else pthread_attr_init (&newtimer->attr); pthread_attr_setdetachstate (&newtimer->attr, PTHREAD_CREATE_DETACHED); thread = __timer_thread_find_matching (&newtimer->attr, clock_id); if (thread == 0) thread = __timer_thread_alloc (&newtimer->attr, clock_id); if (__builtin_expect (thread == 0, 0)) { __set_errno (EAGAIN); goto unlock_bail; } if (! thread->exists && __builtin_expect (! __timer_thread_start (thread), 0)) { __set_errno (EAGAIN); goto unlock_bail; } break; default: __set_errno (EINVAL); goto unlock_bail; } newtimer->clock = clock_id; newtimer->abstime = 0; newtimer->armed = 0; newtimer->thread = thread; *timerid = timer_ptr2id (newtimer); retval = 0; if (__builtin_expect (retval, 0) == -1) { unlock_bail: if (thread != 0) __timer_thread_dealloc (thread); if (newtimer != 0) { timer_delref (newtimer); __timer_dealloc (newtimer); } } pthread_mutex_unlock (&__timer_mutex); return retval; }
1
#include <pthread.h> int reboot(int); static pthread_t DeadmanThread = 0; static int DeadmanActive = 0; static int DeadmanTimeRemaining = 0; static pthread_mutex_t DeadmanMutex = PTHREAD_MUTEX_INITIALIZER; static void deadman_function(void* arg) { while(1) { sleep(1); pthread_mutex_lock(&DeadmanMutex); if(!DeadmanActive) { pthread_mutex_unlock(&DeadmanMutex); continue; } --DeadmanTimeRemaining; if(DeadmanTimeRemaining <= 0) { pthread_mutex_unlock(&DeadmanMutex); wdt_off(); reboot(0); return; } pthread_mutex_unlock(&DeadmanMutex); } } void deadman_activate(int timeout) { pthread_mutex_lock(&DeadmanMutex); if(!DeadmanActive) { DeadmanTimeRemaining = timeout; wdt_reset(timeout + 1); } ++DeadmanActive; if(!DeadmanThread) pthread_create(&DeadmanThread, 0, (void*)deadman_function, 0); pthread_mutex_unlock(&DeadmanMutex); } void deadman_reset(int timeout) { pthread_mutex_lock(&DeadmanMutex); DeadmanTimeRemaining = timeout; wdt_reset(timeout + 1); pthread_mutex_unlock(&DeadmanMutex); } void deadman_deactivate() { pthread_mutex_lock(&DeadmanMutex); if(DeadmanActive > 0) { --DeadmanActive; } if(DeadmanActive <= 0) { DeadmanActive = 0; wdt_off(); } pthread_mutex_unlock(&DeadmanMutex); }
0
#include <pthread.h> int array[1000]; int result[8]; int availableIndex = -1; pthread_mutex_t lock; void *threadFunction (void *arg) { int subArraySize= 1000/8; int threadIndex = (int)arg; int beginIndex = threadIndex * subArraySize; int endIndex = beginIndex+subArraySize; int res = 0, i; for (i=beginIndex; i<endIndex; i++) res += array[i]; if (threadIndex == 8 -1)for (i=endIndex; i<1000; i++) res += array[i]; pthread_mutex_lock(&lock); availableIndex ++; result[availableIndex] = res; pthread_mutex_unlock(&lock); return (void*)res; } int main (int argc, char **argv) { int i, res; clock_t t; for (i=0; i<1000; i++) array[i] = i; printf("----------------------\\n\\n"); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; int flag; } event_t; event_t main_event; void * test_thread (void *ms_param) { int status = 0; event_t foo; struct timespec time; struct timeval now; long ms = (long) ms_param; printf("thread %d begin!\\n", pthread_self()); pthread_cond_init(&foo.cond, 0); pthread_mutex_init(&foo.mutex, 0); foo.flag = 0; printf("waiting %ld ms ...\\n", ms); gettimeofday(&now, 0); time.tv_sec = now.tv_sec + ms/1000 + (now.tv_usec + (ms%1000)*1000)/1000000; time.tv_nsec = ((now.tv_usec + (ms%1000)*1000) % 1000000) * 1000; pthread_mutex_lock(&foo.mutex); printf("begin wait time.tv_sec:%d,time.tv_nsec:%d\\n",time.tv_sec,time.tv_nsec); printf("the in pthread_cond_timedwait \\n"); while (foo.flag == 0 && status != ETIMEDOUT) { status = pthread_cond_timedwait(&foo.cond, &foo.mutex, &time); } printf("the out pthread_cond_timedwait \\n"); pthread_mutex_unlock(&foo.mutex); pthread_mutex_lock(&main_event.mutex); main_event.flag = 1; pthread_cond_signal(&main_event.cond); pthread_mutex_unlock(&main_event.mutex); printf("thread %d over!\\n", pthread_self()); return (void*) status; } int main (void) { unsigned long count; setvbuf (stdout, 0, _IONBF, 0); pthread_cond_init(&main_event.cond, 0); pthread_mutex_init(&main_event.mutex, 0); main_event.flag = 0; for (count = 0; count < 10; ++count) { pthread_t thread; int status; status = pthread_create (&thread, 0, test_thread, (void*) (count*100)); if (status != 0) { printf ("status = %d, count = %lu: %s\\n", status, count, strerror (errno)); return 1; } else { pthread_mutex_lock(&main_event.mutex); while (main_event.flag == 0) { pthread_cond_wait(&main_event.cond, &main_event.mutex); } printf("main_event.flag==1\\n"); main_event.flag = 0; pthread_mutex_unlock(&main_event.mutex); printf ("count = %lu\\n", count); } usleep (10); } return 0; }
0
#include <pthread.h> pthread_mutex_t pid_mutex; pid_t pid; }pid_data_t; pid_t thisPID; pthread_mutexattr_t myattr; int set_priority(int priority); int get_priority(); int main(int argc, char *argv[]) { printf("Welcome to the server\\n"); int fildescr=shm_open("/sharedpid",O_RDWR|O_CREAT,S_IRWXU); ftruncate(fildescr,sizeof(pid_data_t)); pid_data_t *ptr=mmap(0,sizeof(pid_data_t),PROT_READ|PROT_WRITE,MAP_SHARED,fildescr,0); pthread_mutexattr_init(&myattr); pthread_mutexattr_setpshared(&myattr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&ptr->pid_mutex,&myattr); int channelID=ChannelCreate(0); struct _msg_info info; thisPID=getpid(); int msgID; pthread_mutex_lock(&ptr->pid_mutex); ptr->pid=thisPID; pthread_mutex_unlock(&ptr->pid_mutex); printf("Added %u to memloc\\n",thisPID); set_priority(10); char databuffer[50]; char replyBuf="Received data"; while(1){ printf("Before, priority: %i",get_priority()); msgID=MsgReceive(channelID,&databuffer,sizeof(databuffer),&info); printf("After, priority: %i",get_priority()); if(msgID!=0&&(msgID!=EFAULT||msgID!=EINTR||msgID!=ESRCH||msgID!=ETIMEDOUT)){ printf("\\nReceived msg from PID: %i and TID: %i\\n",info.pid,info.tid); MsgReply(msgID,EOK,&replyBuf, sizeof(replyBuf)); printf(databuffer); printf("\\n"); } }; return 0; } int set_priority(int priority) { int policy; struct sched_param param; if (priority < 1 || priority > 63) return-1; pthread_getschedparam(pthread_self(), &policy, &param); param.sched_priority = priority; return pthread_setschedparam(pthread_self(),policy, &param); } int get_priority() { int policy; struct sched_param param; pthread_getschedparam(pthread_self(), &policy, &param); return param.sched_curpriority; }
1
#include <pthread.h> int main() { pthread_mutex_t mu1, mu2; pthread_mutex_init(&mu1, 0); pthread_mutex_init(&mu2, 0); pthread_mutex_lock(&mu1); pthread_mutex_lock(&mu2); pthread_mutex_unlock(&mu2); pthread_mutex_unlock(&mu1); pthread_mutex_lock(&mu2); pthread_mutex_lock(&mu1); pthread_mutex_unlock(&mu1); pthread_mutex_unlock(&mu2); pthread_mutex_destroy(&mu1); pthread_mutex_destroy(&mu2); }
0
#include <pthread.h> struct ThreadsafeBufferContext* threadsafe_buffer_context_new() { struct ThreadsafeBufferContext* context = (struct ThreadsafeBufferContext*) malloc(sizeof(struct ThreadsafeBufferContext)); if (context != 0) { context->buffer_size = 0; context->buffer = 0; pthread_mutex_init(&context->lock, 0); } return context; } void threadsafe_buffer_context_free(struct ThreadsafeBufferContext* context) { if (context != 0) { if (context->buffer != 0) free(context->buffer); free(context); } } size_t threadsafe_buffer_peek(struct ThreadsafeBufferContext* context, uint8_t* results, size_t results_size) { size_t bytes_read = 0; if (context == 0) return 0; pthread_mutex_lock(&context->lock); if (context->buffer != 0 && context->buffer_size > 0) { bytes_read = results_size < context->buffer_size ? results_size : context->buffer_size; memcpy(results, context->buffer, bytes_read); } pthread_mutex_unlock(&context->lock); return bytes_read; } size_t threadsafe_buffer_read(struct ThreadsafeBufferContext* context, uint8_t* results, size_t results_size) { size_t bytes_read = 0; if (context == 0) return 0; pthread_mutex_lock(&context->lock); if (context->buffer != 0 && context->buffer_size > 0) { bytes_read = results_size < context->buffer_size ? results_size : context->buffer_size; libp2p_logger_debug("threadsafe_buffer", "read: We want to read %d bytes, and have %d in the buffer. Therefore, we will read %d.\\n", results_size, context->buffer_size, bytes_read); memcpy(results, context->buffer, bytes_read); } if (bytes_read > 0) { if (context->buffer_size - bytes_read > 0) { size_t new_buffer_size = context->buffer_size - bytes_read; uint8_t* new_buffer = (uint8_t*) malloc(new_buffer_size); memcpy(new_buffer, &context->buffer[bytes_read], new_buffer_size); free(context->buffer); context->buffer = new_buffer; context->buffer_size = new_buffer_size; } else { free(context->buffer); context->buffer = 0; context->buffer_size = 0; } } pthread_mutex_unlock(&context->lock); return bytes_read; } size_t threadsafe_buffer_write(struct ThreadsafeBufferContext* context, const uint8_t* bytes, size_t bytes_size) { if (context == 0) return 0; if (bytes_size == 0) return 0; size_t bytes_copied = 0; pthread_mutex_lock(&context->lock); uint8_t* new_buffer = (uint8_t*) realloc(context->buffer, context->buffer_size + bytes_size); if (new_buffer != 0) { memcpy(&new_buffer[context->buffer_size], bytes, bytes_size); context->buffer_size += bytes_size; context->buffer = new_buffer; bytes_copied = bytes_size; libp2p_logger_debug("threadsafe_buffer", "write: Added %d bytes. Buffer now contains %d bytes.\\n", bytes_size, context->buffer_size); } pthread_mutex_unlock(&context->lock); return bytes_copied; }
1
#include <pthread.h> sem_t maitreD; int sem_init(sem_t *maitreD, int pshared, unsigned int value); int rendezvous_count = 0; pthread_mutex_t rendezvous_count_mutex; pthread_cond_t rendezvous_count_threshold_cv; int rendezvous_oncePerCycle = 0; void *task (void *t) { int i; int busyTime; long my_id = (long)t; printf ("Starting thread-%ld\\n", my_id); for (i=0; i < 4; i++) { busyTime = rand()%10 + 1; printf ("Thread-%ld Busy, working for %i seconds...\\n", my_id, busyTime); sleep(busyTime); pthread_mutex_lock(&rendezvous_count_mutex); rendezvous_count++; printf ("Thread-%ld work complete, waiting on barrier\\n", my_id); while (rendezvous_count < 3) { pthread_cond_wait(&rendezvous_count_threshold_cv, &rendezvous_count_mutex); } if (rendezvous_count == 3) { if (!rendezvous_oncePerCycle) { printf("All threads at barrier\\n"); pthread_cond_broadcast(&rendezvous_count_threshold_cv); } rendezvous_oncePerCycle++; if (rendezvous_oncePerCycle == 3) { rendezvous_oncePerCycle = 0; rendezvous_count = 0; } } pthread_mutex_unlock(&rendezvous_count_mutex); sleep(1); } pthread_exit(0); } int main(int argc, char *argv[]) { int i, rc; long t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_attr_t attr; sem_init ( &maitreD, 0, 4 ); srand( time(0) ); pthread_mutex_init(&rendezvous_count_mutex, 0); pthread_cond_init (&rendezvous_count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, task, (void *)t1); pthread_create(&threads[1], &attr, task, (void *)t2); pthread_create(&threads[2], &attr, task, (void *)t3); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf("\\n"); pthread_attr_destroy(&attr); pthread_mutex_destroy(&rendezvous_count_mutex); pthread_cond_destroy(&rendezvous_count_threshold_cv); pthread_exit (0); }
0
#include <pthread.h> void *calculSomme(void *args); struct matrice { unsigned int nbLigne; unsigned int nbColonne; int **element; int sommeFinal; }; pthread_mutex_t mutex; struct matrice *matrice = 0; int main(int argc, char *argv[]) { srand(time(0)); int i = 0, j = 0; if (argc != 3) { fprintf(stderr, "USAGE: ./main <ligne> <colonne>\\n"); exit(1); } matrice = (struct matrice *) malloc(sizeof(struct matrice)); matrice->nbLigne = atoi(argv[1]); matrice->nbColonne = atoi(argv[2]); matrice->element = (int**)malloc(matrice->nbLigne * sizeof(int *)); for(i = 0; i < matrice->nbLigne; ++i) matrice->element[i] = (int *)calloc(matrice->nbColonne, sizeof(int)); matrice->sommeFinal = 0; pthread_t *thread_id = (pthread_t *) malloc(matrice->nbColonne * sizeof(pthread_t)); for(i = 0; i < matrice->nbLigne; ++i) for(j = 0; j < matrice->nbColonne; ++j) matrice->element[i][j] = rand()%10; for(i = 0; i < matrice->nbLigne; ++i) { for(j = 0; j < matrice->nbColonne; ++j) printf("%d ",matrice->element[i][j]); printf("\\n"); } if (pthread_mutex_init(&mutex, 0) != 0) { perror("pthread_mutex_init"); exit(1); } for(i = 0; i < matrice->nbColonne; ++i) if (pthread_create( &thread_id[i], 0, &calculSomme, &matrice) != 0) { perror("pthread_create"); exit(1); } for(i = 0; i < matrice->nbColonne; ++i) pthread_join( thread_id[i], 0); pthread_mutex_destroy(&mutex); printf("somme final : %d\\n", matrice->sommeFinal); free (matrice); return 0; } void *calculSomme(void *args) { if (args != 0) { struct matrice *p_matrice = args; pthread_mutex_lock(&mutex); p_matrice->sommeFinal++; printf("%d\\n",p_matrice->sommeFinal); pthread_mutex_unlock(&mutex); } pthread_exit(0); }
1
#include <pthread.h> const int MAX_THREADS = 1024; long thread_count; long long n; double total_int; double a, b, h; pthread_mutex_t mutex; void* Trap (void* rank); double f (double x); void Get_args(int argc, char* argv[]); void Usage(char* prog_name); int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; double start, finish, elapsed; Get_args(argc, argv); thread_handles = (pthread_t*) malloc (thread_count*sizeof(pthread_t)); pthread_mutex_init(&mutex, 0); h = (b-a) / n; total_int = 0.0; GET_TIME(start); for (thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], 0, Trap, (void*)thread); for (thread = 0; thread < thread_count; thread++) pthread_join(thread_handles[thread], 0); GET_TIME(finish); elapsed = finish - start; printf("With n = %lld,\\n", n); printf(" Our estimate of the integral = %.15f\\n", total_int); printf("The elapsed time is %.10lf seconds\\n", elapsed); pthread_mutex_destroy(&mutex); free(thread_handles); return 0; } void* Trap (void* rank) { long my_rank = (long) rank; long i, local_n; double local_a, local_b; double x, local_int; local_n = n / thread_count; local_a = a + my_rank*local_n*h; local_b = local_a + local_n*h; local_int = (f(local_a) + f(local_b)) / 2.0; for (i = 1; i < local_n; i++) { x = local_a + i*h; local_int += f(x); } local_int *= h; pthread_mutex_lock(&mutex); total_int += local_int; pthread_mutex_unlock(&mutex); return 0; } void Get_args(int argc, char* argv[]) { if (argc != 5) Usage(argv[0]); thread_count = strtol(argv[1], 0, 10); if (thread_count <= 0 || thread_count > MAX_THREADS) Usage(argv[0]); n = strtoll(argv[2], 0, 10); a = atof(argv[3]); b = atof(argv[4]); if (n <= 0) Usage(argv[0]); } void Usage(char* prog_name) { fprintf(stderr, "usage: %s <number of threads> <n> <a> <b>\\n", prog_name); fprintf(stderr, " n is the total number of intervals for the integration\\n"); fprintf(stderr, " n should be evenly divisible by the number of threads\\n"); fprintf(stderr, " a is the lower limit for the integration\\n"); fprintf(stderr, " b is the upper limit for the integration\\n"); exit(0); } double f (double x) { return sin(x)*exp(x); }
0
#include <pthread.h> char *messages[8]; pthread_mutex_t mutexsum; struct thread_data { int thread_id; int sum; char *message; }; struct thread_data thread_data_shared; void *PrintHello(void *threadarg) { int taskid, sum; char *hello_msg; struct thread_data * my_data; my_data = (struct thread_data *) threadarg; taskid = my_data->thread_id; sum = my_data->sum; hello_msg = my_data->message; pthread_mutex_unlock (&mutexsum); printf("Thread %d: %s Sum=%d\\n", taskid, hello_msg, sum); pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t threads[8]; int *taskids[8]; int rc, t, sum; pthread_mutex_init(&mutexsum, 0); sum=0; messages[0] = "English: Hello World!"; messages[1] = "French: Bonjour, le monde!"; messages[2] = "Spanish: Hola al mundo"; messages[3] = "Klingon: Nuq neH!"; messages[4] = "German: Guten Tag, Welt!"; messages[5] = "Russian: Zdravstvytye, mir!"; messages[6] = "Japan: Sekai e konnichiwa!"; messages[7] = "Latin: Orbis, te saluto!"; pthread_mutex_lock (&mutexsum); for(t=0;t<8;t++) { sum = sum + t; thread_data_shared.thread_id = t; thread_data_shared.sum = sum; thread_data_shared.message = messages[t]; printf("Creating thread %d\\n", t); rc = pthread_create(&threads[t], 0, PrintHello, (void *)&thread_data_shared); pthread_mutex_lock (&mutexsum); if (rc) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } pthread_exit(0); }
1
#include <pthread.h> { pthread_mutex_t fine_sondaggio; sem_t barrier; int sondaggi_terminati; } Barriera; { pthread_mutex_t lock; int voti[10]; } Sondaggio; Sondaggio sondaggi[10]; Barriera b; pthread_mutex_t film_lock; pthread_t spettatori[10]; int winner; int found_winner(); void init_sync(); int found_winner() { int max = 0; for(int i = 0; i < 10; i++) { int somma = 0; int avg = 0; for(int j = 0; j < 10; j++) { somma += sondaggi[i].voti[j]; } avg = somma / 10; if(avg > max) max = avg; } return max; } void * spettatore(void * t) { int tid = (unsigned int) t; for(int i = 0; i < 10; i++) { pthread_mutex_lock(&sondaggi[i].lock); sondaggi[i].voti[tid] = rand() % 10; pthread_mutex_unlock(&sondaggi[i].lock); } pthread_mutex_lock(&b.fine_sondaggio); b.sondaggi_terminati++; printf("Sondaggio terminato...\\n"); pthread_mutex_unlock(&b.fine_sondaggio); if(b.sondaggi_terminati == 10) { printf("Sondaggi terminati... calcolo vincitore...\\n"); winner = found_winner(); printf("The winner is %d\\n", winner); printf("Sblocco la barriera\\n"); sem_post(&b.barrier); } sem_wait(&b.barrier); sem_post(&b.barrier); pthread_mutex_lock(&film_lock); printf("Spettatore %d...... visione film %d in corso...\\n", tid, winner); sleep(2); pthread_mutex_unlock(&film_lock); return 0; } void init_sync() { pthread_mutex_init(&b.fine_sondaggio, 0); sem_init(&b.barrier, 0, 0); b.sondaggi_terminati = 0; for(int i = 0; i < 10; i++) { pthread_mutex_init(&sondaggi[i].lock, 0); for(int j = 0; j < 10; j++) sondaggi[i].voti[j] = 0; } pthread_mutex_init(&film_lock, 0); winner = -1; } int main(int argc, char * argv[]) { int result; void * status; printf("Inizializzazione\\n"); srand((unsigned int) time(0)); init_sync(); for(int i = 0; i < 10; i++) { result = pthread_create(&spettatori[i], 0, spettatore, (void *)(intptr_t)i); if(result) { perror("Errore nella creazione dei thread\\n"); exit(-1); } } for(int i = 0; i < 10; i++) { result = pthread_join(spettatori[i], &status); if(result) { perror("Errore nella terminazione dei threads\\n"); exit(-1); } } printf("Exit\\n"); return 0; }
0
#include <pthread.h> pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER; void prepare(void) { printf("prepare locks...\\n"); pthread_mutex_lock(&lock1); pthread_mutex_lock(&lock2); } void parent(void) { printf("parent locks ...\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void child(void) { printf("child locks ...\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void *thr_fn(void *arg) { printf("thread started...\\n"); pause(); return 0; } int main(void) { int err; pid_t pid; pthread_t tid; if ((err = pthread_atfork(prepare, parent, child)) != 0) { printf("pthread_atfork failed[%s]\\n", strerror(err)); return -1; } err = pthread_create(&tid, 0, thr_fn, 0); if (err) { printf("pthread_create failed[%s]\\n", strerror(err)); return -1; } sleep(2); printf("parent about to fork...\\n"); if ((pid = fork()) < 0) { perror("fork error"); return -1; } else if (pid == 0) { printf("child return from fork\\n"); } else printf("parent return from fork\\n"); return 0; }
1
#include <pthread.h> pthread_mutex_t gmutex; int x = 0; void *thread_func(void *arg) { int myid = (int) arg; pthread_mutex_lock(&gmutex); x = x + myid; printf("Hello from thread %d x = %d\\n", myid, x); pthread_mutex_unlock(&gmutex); pthread_exit((void *) myid + 100); } int main(int argc, char *argv[]) { pthread_t t1, t2; int rv1, rv2; printf("Hello from main x = %d\\n", x); pthread_mutex_init(&gmutex, 0); if (pthread_create(&t1, 0, thread_func, (void *) 1) != 0) { printf("pthello: pthread_create error\\n"); exit(1); } if (pthread_create(&t2, 0, thread_func, (void *) 2) != 0) { printf("pthello: pthread_create error\\n"); exit(1); } pthread_join(t1, (void **) &rv1); printf("Main joined with thread 1 retval = %d x = %d\\n", rv1, x); pthread_join(t2, (void **) &rv2); printf("Main joined with thread 2 retval = %d x = %d\\n", rv2, x); }
0
#include <pthread.h> void *gpsdthread(void *ptarg) { struct gps_data_t data; struct gpsdthread_context *ctx; int r; double last_update = 0; struct timespec ts; ctx = (struct gpsdthread_context *)ptarg; r = gps_open("localhost", DEFAULT_GPSD_PORT, &data); if (r != 0) { fprintf(stderr, "gps_open: %s\\n", gps_errstr(errno)); return 0; } gps_stream(&data, WATCH_ENABLE | WATCH_JSON, 0); for (;;) { r = gps_waiting(&data, 500000); if (!r && (errno != 0)) { fprintf(stderr, "gps_waiting: %s\\n", gps_errstr(errno)); return 0; } else if (r == 1) { errno = 0; r = gps_read(&data); if (r == 0) fprintf(stderr, "Surprisingly, no data available!\\n"); else if (r == -1) { if (errno == 0) { fprintf(stderr, "Socket has closed\\n"); return 0; } else { fprintf(stderr, "gps_read: %s\\n", gps_errstr(errno)); return 0; } } else { if (data.set & STATUS_SET) { data.set ^= STATUS_SET; pthread_mutex_lock(&ctx->mutex); ctx->status = data.status; pthread_mutex_unlock(&ctx->mutex); clock_gettime(CLOCK_REALTIME, &ts); last_update = (double)ts.tv_sec + (double)ts.tv_nsec / 1.0E9; } } clock_gettime(CLOCK_REALTIME, &ts); double now = (double)ts.tv_sec + (double)ts.tv_nsec / 1.0E9; if ((last_update > 0) && ((now - last_update) > 3)) { pthread_mutex_lock(&ctx->mutex); ctx->status = STATUS_NO_FIX; pthread_mutex_unlock(&ctx->mutex); } } } gps_close(&data); return 0; }
1
#include <pthread.h> pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER; void prepare(void) { printf("preparing locks...\\n"); pthread_mutex_lock(&lock1); pthread_mutex_lock(&lock2); } void parent(void) { printf("parent unlocking locks...\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void child(void) { printf("child unlocking locks...\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void *thr_fn(void *arg) { printf("thread started...\\n"); pause(); return(0); } int main(void) { int err; pid_t pid; pthread_t tid; if ((err = pthread_atfork(prepare, parent, child)) != 0) err_exit(err, "can't install fork handlers"); err = pthread_create(&tid, 0, thr_fn, 0); if (err != 0) err_exit(err, "can't create thread"); sleep(2); printf("parent about to fork...\\n"); if ((pid = fork()) < 0) err_quit("fork failed"); else if (pid == 0) printf("child returned from fork\\n"); else printf("parent returned from fork\\n"); exit(0); }
0
#include <pthread.h> static void *threader(void *args) { struct async *self = (struct async *)args; struct async_task *tmp; struct async_task task; for (;;) { pthread_mutex_lock(&self->lock); if (self->count == 0 && !self->shutdown) pthread_cond_wait(&self->notify, &self->lock); if (self->count == 0 && self->shutdown) { pthread_mutex_unlock(&self->lock); break; } tmp = self->head; task = *tmp; if (self->count == 1) self->head = self->tail = 0; else self->head = self->head->next; free(tmp); self->count--; pthread_mutex_unlock(&self->lock); task.func(task.args); } pthread_exit(0); } static void async_destroy(struct async *self) { pthread_mutex_destroy(&self->lock); pthread_cond_destroy(&self->notify); free(self->threads); free(self); } struct async *async_create(int thread_num) { int i; struct async *self; self = malloc(sizeof(*self)); if (!self) return 0; self->count = 0; self->shutdown = 0; self->head = self->tail = 0; self->thread_num = thread_num; self->threads = malloc(sizeof(pthread_t) * thread_num); if (!self->threads) { free(self); return 0; } pthread_mutex_init(&self->lock, 0); pthread_cond_init(&self->notify, 0); for (i = 0; i < thread_num; i++) pthread_create(&self->threads[i], 0, threader, self); return self; } int async_send_task(struct async *self, void (*func)(void *args), void *args) { struct async_task *task; task = malloc(sizeof(*task)); if (!task) return 1; task->func = func; task->args = args; task->next = 0; pthread_mutex_lock(&self->lock); if (self->count == 0) { self->head = self->tail = task; } else { self->tail->next = task; self->tail = task; } self->count++; pthread_mutex_unlock(&self->lock); pthread_cond_signal(&self->notify); return 0; } void async_wait(struct async *self) { int i; pthread_mutex_lock(&self->lock); self->shutdown = 1; pthread_mutex_unlock(&self->lock); pthread_cond_broadcast(&self->notify); for (i = 0; i < self->thread_num; i++) pthread_join(self->threads[i], 0); async_destroy(self); } struct async_operations Async = { .create = async_create, .send_task = async_send_task, .wait = async_wait, };
1
#include <pthread.h> static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static int currentLockOwerId = -1; void std_inst_lock(); void std_inst_unlock(); static FILE* ofile = 0; extern long g_flag; FILE* OutputFile() { if (ofile == 0) { ofile = fopen("llfi.stat.trace.txt", "w"); } return ofile; } static long instCount = 0; static long cutOff = 0; void printInstTracer(long instID, char *opcode, int size, char* ptr, int maxPrints) { std_lock(); int i; instCount++; if (start_tracing_flag == TRACING_FI_RUN_FAULT_INSERTED) { start_tracing_flag = TRACING_FI_RUN_START_TRACING; cutOff = instCount + maxPrints; } if ((start_tracing_flag == TRACING_GOLDEN_RUN) || ((start_tracing_flag == TRACING_FI_RUN_START_TRACING) && (instCount < cutOff))) { fprintf(OutputFile(), "ID: %ld\\tOPCode: %s\\tValue: ", instID, opcode); if (isLittleEndian()) { for (i = size - 1; i >= 0; i--) { fprintf(OutputFile(), "%02hhx", ptr[i]); } } else { for (i = 0; i < size; i++) { fprintf(OutputFile(), "%02hhx", ptr[i]); } } fprintf(OutputFile(), "\\n"); fflush(OutputFile()); } if ((start_tracing_flag != TRACING_GOLDEN_RUN) && instCount >= cutOff ) { start_tracing_flag = TRACING_FI_RUN_END_TRACING; } std_unlock(); } void postTracing() { if (ofile != 0) fclose(ofile); } void std_inst_lock() { pthread_mutex_lock(&lock); pthread_t thrd = pthread_self(); currentLockOwerId = (int) thrd; } void std_inst_unlock() { currentLockOwerId = -1; pthread_mutex_unlock(&lock); }
0
#include <pthread.h> struct readerArgs { int fd; size_t number; }; union semun { int val; struct semid_ds *buf; unsigned short *array; struct seminfo *__buf; }; ssize_t pgetLine(int fd, char *str, size_t maxLength, off_t offset); void getCurrentTime(char *str, size_t maxLength); void* readerFunc(readerArgs *args); void* writerFunc(void *fd); void clearResources(int fd); int semid; sembuf lockOp = {0, -1, 0}; sembuf unlockOp = {0, 1, 0}; pthread_mutex_t stdoutMutex = PTHREAD_MUTEX_INITIALIZER; int main() { int fd = open("File", O_CREAT | O_RDWR | O_TRUNC, 00777); pthread_t readers[10], writer; readerArgs args[10]; semun semVal; semid = semget(IPC_PRIVATE, 1, 00777); if (fd == -1 || semid == -1) { printf("Error: %s", strerror(errno)); clearResources(fd); return -1; } semVal.val = 1; semctl(semid, 0, SETVAL, semVal); errno = pthread_create(&writer, 0, writerFunc, &fd); if (errno != 0) { printf("Error: %s\\n", strerror(errno)); clearResources(fd); return -1; } for (int i = 0; i < 10; i++) { args[i].fd = fd; args[i].number = i + 1; errno = pthread_create(readers + i, 0, (void* (*)(void*)) readerFunc, args + i); if (errno != 0) { printf("Error: %s\\n", strerror(errno)); clearResources(fd); return -1; } } pthread_join(writer, 0); for (int i = 0; i < 10; i++) pthread_join(readers[i], 0); clearResources(fd); return 0; } ssize_t pgetLine(int fd, char *str, size_t maxLength, off_t offset) { char buf[maxLength]; ssize_t retVal = pread(fd, buf, maxLength, offset); size_t newLinePos; if (retVal == -1) return -1; newLinePos = strcspn(buf, "\\n"); if (newLinePos == strlen(buf)) return 0; newLinePos++; strncpy(str, buf, newLinePos); return newLinePos; } void* readerFunc(readerArgs *args) { char str[100]; int fd = args->fd; ssize_t number = args->number, bytesCount; off_t offset = 0; do { semop(semid, &lockOp, 1); bytesCount = pgetLine(fd, str, 100, offset); semop(semid, &unlockOp, 1); if (bytesCount <= 0) { pthread_mutex_lock(&stdoutMutex); printf("Thread%lu wait for data...\\n", number); pthread_mutex_unlock(&stdoutMutex); sleep(1); continue; } offset += bytesCount; if (strncmp(str, "END", 3) == 0) break; pthread_mutex_lock(&stdoutMutex); printf("Thread%lu %s", number, str); fflush(stdout); pthread_mutex_unlock(&stdoutMutex); if (offset > 100*10) return 0; } while (1); pthread_mutex_lock(&stdoutMutex); printf("Thread%lu END\\n", number); fflush(stdout); pthread_mutex_unlock(&stdoutMutex); return 0; } void* writerFunc(void *fd) { int _fd = *(int*)fd; char str[100], timeStr[50]; for (int i = 1; i < 10 + 1; i++) { getCurrentTime(timeStr, 50); sprintf(str, "Line %d Current time %s\\n", i, timeStr); semop(semid, &lockOp, 1); write(_fd, str, strlen(str)); semop(semid, &unlockOp, 1); } semop(semid, &lockOp, 1); write(_fd, "END\\n", 4); semop(semid, &unlockOp, 1); return 0; } void getCurrentTime(char *str, size_t maxLength) { static struct timeval timer; gettimeofday(&timer, 0); strftime(str, maxLength, "%T.", localtime(&timer.tv_sec)); sprintf(str + strlen(str), "%ld", timer.tv_usec); } void clearResources(int fd) { close(fd); semctl(semid, 0, IPC_RMID); pthread_mutex_destroy(&stdoutMutex); }
1
#include <pthread.h> pthread_mutex_t lock; int num=0; void* numOne(void *p){ pthread_mutex_lock(&lock); while (num) { num=0; } pthread_mutex_unlock(&lock); return 0; } void* numZero(void *p){ pthread_mutex_lock(&lock); while(!num) { num=1; } pthread_mutex_unlock(&lock); return 0; } int main(){ struct timespec start, end; pthread_t thread1; pthread_t thread2; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); pthread_create(&thread1, 0, numOne , 0); pthread_create(&thread2, 0, numZero , 0); pthread_join(thread1, 0); pthread_join(thread2, 0); clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); double result = (end.tv_sec - start.tv_sec)* 1e3 + (end.tv_nsec - start.tv_nsec) * 1e-6; printf("%fms : Minimal Function Call\\n", result ); return 0; }
0
#include <pthread.h> long NTHREADS = 8; double pi = 0; long t_atis; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* runner(void* arg) { long a; int pi_t = 0; unsigned int random = rand(); unsigned int* random_ptr = &random; for (a = 0; a < t_atis; a++) { double k = rand_r(random_ptr) / ((double) 32767 + 1) * 2.0 - 1.0; double l = rand_r(random_ptr) / ((double) 32767 + 1) * 2.0 - 1.0; if (k * k + l * l < 1) { pi_t = pi_t + 1; } } pthread_mutex_lock(&mutex); pi = pi + pi_t; pthread_mutex_unlock(&mutex); } int main(int argc, char *argv[]) { pthread_t *threads = malloc(NTHREADS * sizeof(pthread_t)); int i; long totalpoints = atol(argv[1]); int NTHREADS = atoi(argv[2]); t_atis = totalpoints / NTHREADS; for (i = 0; i < NTHREADS; i++) { pthread_create(&threads[i], 0, runner, 0); } for (i = 0; i < NTHREADS; i++) { pthread_join(threads[i], 0); } pthread_mutex_destroy(&mutex); printf(" Pi Sayisi: %f\\n", (4. * pi) / ((double) t_atis * NTHREADS)); return 0; }
1
#include <pthread.h> static void thread_create(pthread_t *tid,void *(*fun)(void *)); static void thread_wait(pthread_t tid); void * fun1(void *arg); void * fun2(void *arg); pthread_mutex_t lock; int sum = 0; int main(int argc, char const *argv[]) { pthread_mutex_init(&lock,0); pthread_t tid1; pthread_t tid2; thread_create(&tid1,fun1); thread_create(&tid2,fun2); thread_wait(tid1); thread_wait(tid2); return 0; } static void thread_create(pthread_t *tid,void *(*fun)(void *)) { int res = 0; res = pthread_create(tid,0,fun,0); if (res == 0) printf("successfully create"); sleep(4); } static void thread_wait(pthread_t tid) { int res = 0; int status = 0; res = pthread_join(tid,(void *)&status); if (res == 0){ printf("wait thread %lu successfully\\n",tid); printf("the return val:%d\\n",status ); } else perror("join thread"); } void * fun1(void *arg) { printf(" thread 1\\n"); int i = 0; for (; ; ) { pthread_mutex_lock(&lock); sum +=i; i++; printf("thread 1 sum:%d\\n",sum ); if (sum >100) { } pthread_mutex_unlock(&lock); sleep(2); } pthread_exit((void *)0); } void * fun2(void *arg) { int i =0; printf(" thread 2\\n"); pthread_mutex_lock(&lock); while(sum >0) { sum -=i; i++; printf("thread 2 sum:%d\\n", sum); } pthread_mutex_unlock(&lock); sleep(1); pthread_exit((void *)0); }
0
#include <pthread.h> int N; int maxnum; char *Init; int PRINT; matrix A; double b[4096]; double y[4096]; { pthread_mutex_t lock; pthread_cond_t cond; int count; } barrier_t; static barrier_t barrier; int thread_num = 8; void work(void); void *gaussian_work(void* thr_id); void Init_Matrix(void); void Print_Matrix(void); void Init_Default(void); int Read_Options(int, char **); int main(int argc, char **argv) { int i, timestart, timeend, iter; Init_Default(); Read_Options(argc,argv); Init_Matrix(); work(); if (PRINT == 1) Print_Matrix(); } void work() { pthread_t threads[32]; pthread_attr_t attr; pthread_attr_init (&attr); barrier.count = 0; pthread_mutex_init(&barrier.lock, 0); pthread_cond_init(&barrier.cond,0); int i; for (i = 0; i < thread_num; i++) { pthread_create(&threads[i],&attr,gaussian_work,(void *)i); } for (i = 0; i < thread_num; i++) pthread_join(threads[i], 0); } void *gaussian_work(void* thr_id) { int i,j,k; long my_id = (long) thr_id; for (k = 0; k<N; k++) { if ((k%thread_num) == my_id) { for (j = k+1; j<N; j++) A[k][j] = A[k][j]/A[k][k]; y[k] = b[k] / A[k][k]; A[k][k] = 1; } pthread_mutex_lock(&barrier.lock); barrier.count++; if (barrier.count != thread_num) pthread_cond_wait(&barrier.cond,&barrier.lock); else { barrier.count = 0; pthread_cond_broadcast(&barrier.cond); } pthread_mutex_unlock(&barrier.lock); for (i = k+1; i<N; i++) { if ((i%thread_num) == my_id) { for (j = k+1; j<N; j++) { A[i][j] = A[i][j]- A[i][k]*A[k][j]; } b[i] = b[i] - A[i][k]*y[k]; A[i][k] = 0; } } pthread_mutex_lock(&barrier.lock); barrier.count++; if (barrier.count != thread_num) pthread_cond_wait(&barrier.cond,&barrier.lock); else { barrier.count = 0; pthread_cond_broadcast(&barrier.cond); } pthread_mutex_unlock(&barrier.lock); } } void Init_Matrix() { int i, j; printf("\\nthread_num = %d",thread_num); printf("\\nsize = %dx%d ", N, N); printf("\\nmaxnum = %d \\n", maxnum); printf("Init = %s \\n", Init); printf("Initializing matrix..."); if (strcmp(Init,"rand") == 0) { for (i = 0; i < N; i++){ for (j = 0; j < N; j++) { if (i == j) A[i][j] = (double)(rand() % maxnum) + 5.0; else A[i][j] = (double)(rand() % maxnum) + 1.0; } } } if (strcmp(Init,"fast") == 0) { for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { if (i == j) A[i][j] = 5.0; else A[i][j] = 2.0; } } } for (i = 0; i < N; i++) { b[i] = 2.0; y[i] = 1.0; } printf("done \\n\\n"); if (PRINT == 1) Print_Matrix(); } void Print_Matrix() { int i, j; printf("Matrix A:\\n"); for (i = 0; i < N; i++) { printf("["); for (j = 0; j < N; j++) printf(" %5.2f,", A[i][j]); printf("]\\n"); } printf("Vector b:\\n["); for (j = 0; j < N; j++) printf(" %5.2f,", b[j]); printf("]\\n"); printf("Vector y:\\n["); for (j = 0; j < N; j++) printf(" %5.2f,", y[j]); printf("]\\n"); printf("\\n\\n"); } void Init_Default() { N = 8; Init = "rand"; maxnum = 15.0; PRINT = 1; } int Read_Options(int argc, char **argv) { char *prog; prog = *argv; while (++argv, --argc > 0) if (**argv == '-') switch ( *++*argv ) { case 'p': --argc; thread_num = atoi(*++argv); break; case 'n': --argc; N = atoi(*++argv); break; case 'h': printf("\\nHELP: try sor -u \\n\\n"); exit(0); break; case 'u': printf("\\nUsage: sor [-n problemsize]\\n"); printf(" [-D] show default values \\n"); printf(" [-h] help \\n"); printf(" [-I init_type] fast/rand \\n"); printf(" [-m maxnum] max random no \\n"); printf(" [-P print_switch] 0/1 \\n"); exit(0); break; case 'D': printf("\\nDefault: n = %d ", N); printf("\\n Init = rand" ); printf("\\n maxnum = 5 "); printf("\\n P = 0 \\n\\n"); exit(0); break; case 'I': --argc; Init = *++argv; break; case 'm': --argc; maxnum = atoi(*++argv); break; case 'P': --argc; PRINT = atoi(*++argv); break; default: printf("%s: ignored option: -%s\\n", prog, *argv); printf("HELP: try %s -u \\n\\n", prog); break; } return 1; }
1
#include <pthread.h> static volatile int counter = 0; int threshold; pthread_mutex_t lock; void *mythread(void *arg) { int i; int localCounter = 0; for (i = 0; i < 1000000; i++) { localCounter++; if (localCounter == threshold) { pthread_mutex_lock(&lock); counter = counter + threshold; pthread_mutex_unlock(&lock); localCounter = 0; } } return 0; } int main (int argc, char *argv[]) { if (argc < 2) { printf("usage: name number\\n"); return 0; } threshold = atoi(argv[1]); pthread_t p1,p2,p3,p4,p5; int pres = pthread_mutex_init(&lock, 0); int rc; printf("threshold: %d\\n", threshold); clock_t t; t = clock(); rc = pthread_create(&p1, 0, mythread, "A"); rc = pthread_create(&p2, 0, mythread, "B"); rc = pthread_create(&p3, 0, mythread, "C"); rc = pthread_create(&p4, 0, mythread, "D"); rc = pthread_create(&p5, 0, mythread, "E"); rc = pthread_join(p1, 0); rc = pthread_join(p2, 0); rc = pthread_join(p3, 0); rc = pthread_join(p4, 0); rc = pthread_join(p5, 0); t = clock() - t; double time_taken = ((double)t) / CLOCKS_PER_SEC; printf("processed time: %f seconds\\n\\n", time_taken); return 0; }
0
#include <pthread.h> pthread_t tid1, tid2; int g_Flag = 0; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void* thread1(void *); void* thread2(void *); int main(void) { if(pthread_create(&tid2, 0, thread2, 0) != 0) return -2; if(pthread_create(&tid1, 0, thread1, &tid2) != 0) return -1; pthread_cond_wait(&cond, &mutex); exit(0); } void* thread1(void *arg) { printf("this is thread1\\n"); pthread_mutex_lock(&mutex); if(g_Flag == 2) pthread_cond_signal(&cond); g_Flag = 1; pthread_mutex_unlock(&mutex); pthread_join(tid2, 0); pthread_exit(0); } void* thread2(void *arg) { printf("this is thread2\\n"); pthread_mutex_lock(&mutex); if(g_Flag == 1) pthread_cond_signal(&cond); g_Flag = 2; pthread_mutex_unlock(&mutex); pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t me; } track_t; track_t tracks[2]; } station_t; int station; int direction; int id; } train_t; int *choices; int remaining; } selector_t; station_t *stations; track_t *tracks; train_t *trains; int n_stations; int n_trains; selector_t selector; void select_station_and_track_init(int n); void select_station_and_track(int *station, int *track); void *train_f(void *); int main(int argc, char **argv) { int i; pthread_t *tids; if(argc != 3) { fprintf(stderr, "Usage: %s n_stations n_trains\\n", argv[0]); return 1; } n_stations = atoi(argv[1]); n_trains = atoi(argv[2]); if(n_stations <= 0 || n_trains <= 0) { fprintf(stderr, "n_stations and n_trains must be positive integers\\n"); return 1; } tids = calloc(n_trains, sizeof(pthread_t)); stations = calloc(n_stations, sizeof(station_t)); trains = calloc(n_trains, sizeof(train_t)); tracks = calloc(n_stations, sizeof(track_t)); if(tids == 0 || stations == 0 || trains == 0) { fprintf(stderr, "Error allocating resources\\n"); return 1; } for(i = 0; i < n_stations; i++) { pthread_mutex_init(&stations[i].tracks[0].me, 0); pthread_mutex_init(&stations[i].tracks[1].me, 0); pthread_mutex_init(&tracks[i].me, 0); } srand(time(0)); select_station_and_track_init(n_stations); for(i = 0; i < n_trains; i++) { trains[i].id = i; select_station_and_track(&trains[i].station, &trains[i].direction); pthread_mutex_lock(&stations[trains[i].station].tracks[trains[i].direction].me); } for(i = 0; i < n_trains; i++) { pthread_create(&tids[i], 0, train_f, &trains[i]); pthread_detach(tids[i]); } pthread_exit(0); } void *train_f(void *p) { train_t *myself; int sleep_time; int next_track; int next_station; myself = (train_t *)p; while(1) { sleep_time = rand() % 6; printf("Train n. %3d, in station %3d going %s\\n", myself->id, myself->station, (myself->direction == 0)? "CLOCKWISE" : "COUNTERCLOCKWISE"); sleep(sleep_time); if(myself->direction == 0) { next_track = myself->station; next_station = (myself->station + 1) % n_stations; } else { next_track = (myself->station - 1 + n_stations) % n_stations; next_station = (myself->station - 1 + n_stations) % n_stations; } pthread_mutex_lock(&stations[next_station].tracks[myself->direction].me); pthread_mutex_lock(&tracks[next_track].me); pthread_mutex_unlock(&stations[myself->station].tracks[myself->direction].me); printf("Train n. %3d, traveling toward station %3d\\n", myself->id, next_station); sleep(10); pthread_mutex_unlock(&tracks[next_track].me); printf("Train n. %3d, arrived at station %3d\\n", myself->id, next_station); myself->station = next_station; } } void select_station_and_track_init(int n) { int i; selector.remaining = n * 2; selector.choices = calloc(n * 2, sizeof(int)); if(selector.choices == 0) { fprintf(stderr, "Error allocating selectors\\n"); exit(1); } for(i = 0; i < n * 2; i++) { selector.choices[i] = i; } return; } void select_station_and_track(int *station, int *track) { int choice; if(selector.remaining <= 0) { fprintf(stderr, "Error selecting station and track\\n"); exit(1); } choice = rand() % selector.remaining; *station = selector.choices[choice] / 2; *track = selector.choices[choice] % 2; selector.remaining--; selector.choices[choice] = selector.choices[selector.remaining]; }
0
#include <pthread.h> pthread_mutex_t a; void* fn1(void * args){ int x, l, j, k; x = 0; l = 0; pthread_mutex_lock(&a);; j = 0; if( k != 25 ){ if( k == 21 ){ pthread_mutex_unlock(&a);; } else { } } else { k = 13; pthread_mutex_lock(&a);; } pthread_mutex_lock(&a);; k++; l++; } int main() { pthread_t thread1; pthread_create(&thread1, 0, &fn1, 0); return 0; }
1
#include <pthread.h> int count; int pending_posts; } sem_t; sem_t sem_producer; sem_t sem_consumer; pthread_mutex_t mut_buf = {0,0}; pthread_mutex_t mut = {0,0}; pthread_mutex_t mutp = {0,0}; void sem_init(sem_t *sem, int pshared, unsigned int value) { sem->count = value; sem->pending_posts = 0; } void sem_post(sem_t *sem) { pthread_mutex_lock(&mut); sem->count++; if (sem->count <= 0) sem->pending_posts++; pthread_mutex_unlock(&mut); } void sem_wait(sem_t *sem) { pthread_mutex_lock(&mut); int done; sem->count--; if (sem->count < 0) { pthread_mutex_unlock(&mut); sleep: while (sem->pending_posts <= 0) { sleep(1); } pthread_mutex_lock(&mutp); if (sem->pending_posts > 0) { done = 1; sem->pending_posts--; } else { done = 0; } pthread_mutex_unlock(&mutp); if (!done) { goto sleep; } pthread_mutex_lock(&mut); } pthread_mutex_unlock(&mut); } int buf[4]; int first_occupied_slot = 0; int first_empty_slot = 0; void push_buf(int val) { buf[first_empty_slot] = val; first_empty_slot++; if (first_empty_slot >= 4) first_empty_slot = 0; } int take_from_buf() { int val = buf[first_occupied_slot]; first_occupied_slot++; if (first_occupied_slot >= 4) first_occupied_slot = 0; return val; } void *producer(void *arg) { int work_item = 1; while (1) { sleep( rand() % 5 ); sem_wait(&sem_producer); pthread_mutex_lock(&mut_buf); push_buf(work_item++); pthread_mutex_unlock(&mut_buf); sem_post(&sem_consumer); } } void *consumer(void *arg) { while (1) { int work_item; sleep( rand() % 5 ); sem_wait(&sem_consumer); pthread_mutex_lock(&mut_buf); work_item = take_from_buf(); pthread_mutex_unlock(&mut_buf); sem_post(&sem_producer); printf("%d ", work_item); fflush(stdout); } } void run_threads(int count) { sem_init(&sem_producer, 0, 4); sem_init(&sem_consumer, 0, 0); while (count > 0) { count--; pthread_t pp; pthread_t cc; int perr = pthread_create(&pp, 0, &producer, 0); if (perr != 0) { printf("Failed to create producer thread\\n"); } int cerr = pthread_create(&cc, 0, &consumer, 0); if (cerr != 0) { printf("Failed to create consumer thread\\n"); } } while (1) sleep(1); } int main() { run_threads(3); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; int VAR = 0; void* p_inc(void* arg) { struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += 5; ts.tv_nsec = 0; int res = pthread_mutex_timedlock(&mutex, &ts); for (int i = 0; i < 100000; i++) { VAR++; } pthread_mutex_unlock(&mutex); return 0; } void* p_dec(void* arg) { pthread_mutex_lock(&mutex); for (int i = 0; i < 100000; i++) { VAR--; } pthread_mutex_unlock(&mutex); return 0; } int main() { pthread_t thread_inc[10]; pthread_t thread_dec[10]; pthread_mutex_init(&mutex, 0); for (int i = 0; i < 10; i++) { pthread_create(&thread_inc[i], 0, p_inc, 0); pthread_create(&thread_dec[i], 0, p_dec, 0); } for (int i = 0; i < 10; i++) { pthread_join(thread_inc[i], 0); pthread_join(thread_dec[i], 0); } pthread_mutex_destroy(&mutex); printf("VAR = %d\\n", VAR); return 0; }
1
#include <pthread.h> int thread_count = 0; static pthread_mutex_t mutex_stock = PTHREAD_MUTEX_INITIALIZER; struct args { int* a; int n; int level; }; void args_init(struct args * args, int *a , int n, int level) { args->a = a; args->n = n; args->level = level; } void quick_sort (struct args * args); void incr_thread_count() { pthread_mutex_lock(&mutex_stock); thread_count ++; pthread_mutex_unlock(&mutex_stock); } void decr_thread_count() { pthread_mutex_lock(&mutex_stock); thread_count --; pthread_mutex_unlock(&mutex_stock); } void * thread_f(void * params) { struct args * args = (struct args *) params; quick_sort(args); return 0; } void quick_sort (struct args * args) { int *a = args->a; int n = args->n, level = args->level; if (n < 2) return; int p = a[n / 2]; int *l = a; int *r = a + n - 1; while (l <= r) { if (*l < p) { l++; } else if (*r > p) { r--; } else { int t = *l; *l = *r; *r = t; l++; r--; } } struct args args1; struct args args2; args_init(&args1, a, r -a + 1 , level +1 ); args_init(&args2, l, a + n - l, level +1 ); if( thread_count < 10000 && level <2 ){ pthread_t t1; pthread_t t2; pthread_create(&t1, 0, thread_f, (void *) &args1); incr_thread_count(); pthread_create(&t2, 0, thread_f, (void *) &args2); incr_thread_count(); pthread_join(t1, 0); decr_thread_count(); pthread_join(t2, 0); decr_thread_count(); } else { quick_sort(&args1); quick_sort(&args2); } } void print_array(int size, int * a) { int i; for(i=0; i < size; i++ ){ printf("%d ", a[i]); } } void gen_and_sort(int size) { int i; int * a = (int *) malloc(size*sizeof(int)); for (i = 0; i< size; i++) { a[i] = rand() % 10000; } struct args arguments; arguments.a = a; arguments.n = size; arguments.level = 0; quick_sort(&arguments); free(a); } void write_file(FILE* file, double * time) { int i; int curr_size =1; for(i = 0; i < 10; i++) { curr_size *= 2; fprintf(file, "%d %g\\n", curr_size, time[i]); } } int main (void) { int i, j; struct timeval debut, fin; double elapsed[10]; srand(time(0)); FILE * output = fopen("output_par_max.dat", "w"); int curr_size = 1; for(i =0;i < 10; i ++) { curr_size *= 2; gettimeofday(&debut,0); for( j=0; j < 100; j++) { gen_and_sort(curr_size); } gettimeofday(&fin, 0); elapsed[i] += (fin.tv_sec-debut.tv_sec)*1000000 + fin.tv_usec-debut.tv_usec; } write_file(output, elapsed); return 0; }
0
#include <pthread.h> unsigned long top = 0; unsigned long bottom = 1; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* checkPrime(void *arg) { unsigned long num = *(unsigned long *) arg; for (unsigned long i = 2; i <= num / 2; i++) { if (num % i == 0) { pthread_exit(0); return 0; } } pthread_mutex_lock(&mutex); top ++; pthread_mutex_unlock(&mutex); pthread_exit(0); return 0; } int main() { double ratio = 1; unsigned long layer = 1; unsigned long corner[4]; unsigned long side; float threshold = 0.2; clock_t tic = clock(); pthread_t prime[3]; while (ratio > threshold) { side = (1 + ((layer - 1) * 2)); corner[0] = side * side; printf("%d ", corner[0]); for (int i = 1; i < 3; i++) { corner[i] = corner[i - 1] - (side - 1); printf("%d ", corner[i]); } for (int i = 0; i < 2; i++) { pthread_create(&prime[i], 0, checkPrime, &corner[i + 1]); } pthread_join(prime[0], 0); pthread_join(prime[1], 0); pthread_join(prime[2], 0); bottom += 4; layer ++; ratio = (double)top / (double)bottom; printf("Ratio of layer %d = %d / %d = %lf\\n", layer, top, bottom, ratio); } clock_t toc = clock(); printf("Elapsed: %f seconds\\n", (double)(toc - tic) / CLOCKS_PER_SEC); return 0; }
1
#include <pthread.h> int count = 0; pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER; int do_count(void) { int n; pthread_mutex_lock(&counter_mutex); count = count + 5; n = count -5; pthread_mutex_unlock(&counter_mutex); return n; } void my_copy(const char *s, FILE **fp1, FILE **fp2) { int ret = -1; int n; pthread_t tid; char buf[5]; while(ret != 0) { tid = pthread_self(); printf("%s id: %u, has done!\\n", s, (unsigned int)tid); n = do_count(); fseek(*fp1, n, 0); fseek(*fp2, n, 0); memset(buf, '\\0', sizeof(buf)); ret = fread(buf, 1, 5, *fp1); fwrite(buf, 1, ret, *fp2); } return; } void open_file(FILE **fp1, FILE **fp2) { *fp1 = fopen("1", "rb"); *fp2 = fopen("2", "rb+"); if(0 == *fp1) { perror("open file 1"); exit(1); } if(0 == *fp2) { perror("open file 2"); exit(1); } return; } void close_file(FILE **fp1, FILE **fp2) { fclose(*fp1); fclose(*fp2); return; } void *thr_fn(void *arg) { FILE *fp1; FILE *fp2; open_file(&fp1, &fp2); my_copy(arg, &fp1, &fp2); close_file(&fp1, &fp2); return 0; } int main(int argc, char* argv[]) { int err; FILE *fp; pthread_t ntid1, ntid2, ntid3; fp = fopen("2", "w"); if(0 == fp) { perror("create file 2 error!"); exit(1); } fclose(fp); err = pthread_create(&ntid1, 0, thr_fn, "thread 1"); if(err != 0) { fprintf(stderr, "can't create new thread 1: %s", strerror(err)); exit(1); } err = pthread_create(&ntid2, 0, thr_fn, "thread 2"); if(err != 0) { fprintf(stderr, "can't create new thread 2: %s", strerror(err)); exit(1); } err = pthread_create(&ntid3, 0, thr_fn, "thread 3"); if(err != 0) { fprintf(stderr, "can't create new thread 3: %s", strerror(err)); exit(1); } pthread_join(ntid1, 0); pthread_join(ntid2, 0); pthread_join(ntid3, 0); printf("copy finish!\\n"); return 0; }
0
#include <pthread.h> pthread_mutex_t Device_mutex; struct VirtualPCB { int tid; char state; int priority; int arrivetime; int cpuburst; int needtime; int waittime; }PCB[20]; void thread_init() { int n; srand(time(0)); for(n=0; n<20; n++) { PCB[n].tid = n+1; PCB[n].state = 'F'; PCB[n].priority = 1+rand()%19; PCB[n].arrivetime = 0; PCB[n].cpuburst = 1+rand()%19; PCB[n].needtime = PCB[n].cpuburst; PCB[n].waittime = 0; } } void *thread_print(void *num) { int n = *(int *)num; while(1) { pthread_mutex_lock(&Device_mutex); printf("Thread%-2d: ", n); printf("tid:%-2d 优先级:%-2d 到达时间:%-2d 执行时间:%-2d \\n", PCB[n-1].tid, PCB[n-1].priority, PCB[n-1].arrivetime, PCB[n-1].cpuburst); pthread_mutex_unlock(&Device_mutex); sleep(1); break; } pthread_exit(0); } void *Create_children() { int ret[20]; thread_init(); pthread_t tid[20]; pthread_mutex_init(&Device_mutex, 0); int i, j; for(i=0; i<20; i++){ int idnum = i+1; ret[i] = pthread_create(&tid[i], 0, &thread_print, &idnum); if(ret[i]==0){sleep(1);} else{printf("Thread%-2d 创建失败!\\n", idnum);} } for(j=0; j<20; j++){ pthread_join(tid[j], 0); } pthread_mutex_destroy(&Device_mutex); pthread_exit(0); } void FCFS(){ printf("\\n------------------先来先服务FCFS调度算法实现结果------------------\\n"); int i, j; int clock = 0; float total_waittime = 0; float average_waittime = 0; printf("\\t进程\\t 开始时间\\t 运行时间\\n"); for(i=0; i<20/2; i++){ for(j=0; j<20; j++){ if(PCB[j].arrivetime == i && PCB[j].state == 'F'){ printf("\\tThread:%-2d \\t %-3d \\t %-2d\\n", PCB[j].tid, clock, PCB[j].cpuburst); total_waittime = total_waittime + (float)clock; clock = clock + PCB[j].cpuburst; PCB[j].state = 'T'; } } } average_waittime = total_waittime / (float)20; printf("总等待时间:%f\\n", total_waittime); printf("平均等待时间:%f\\n", average_waittime); } void SJF(){ printf("\\n------------------最短作业优先调度SJF调度算法实现结果------------------\\n"); for(int k=0; k<20; k++){ PCB[k].state = 'F'; } int i, j; int clock = 0; float total_waittime = 0; float average_waittime = 0; printf("\\t进程\\t 开始时间\\t 运行时间\\n"); for(i=1; i<20; i++){ for(j=0; j<20; j++){ if(PCB[j].cpuburst == i && PCB[j].state == 'F'){ printf("\\tThread:%-2d \\t %-3d \\t %-2d\\n", PCB[j].tid, clock, PCB[j].cpuburst); total_waittime = total_waittime + (float)clock; clock = clock + PCB[j].cpuburst; PCB[j].state = 'T'; } } } average_waittime = total_waittime / (float)20; printf("总等待时间:%f\\n", total_waittime); printf("平均等待时间:%f\\n", average_waittime); } void RR(int timeslice){ printf("\\n------------------轮转发调度RR调度算法实现结果------------------\\n"); int clock = 0; float total_waittime = 0; float average_waittime = 0; printf("\\t进程\\t 开始时间\\t 运行时间\\n"); for(int i=0; i<20; i++){ PCB[i].state = 'F'; } for(int j=0; j<20*20; j=j+timeslice){ int k = (j%(20*timeslice))/timeslice; if(PCB[k].needtime > 0){ int tempwaittime = timeslice; if(PCB[k].needtime-timeslice <= 0){ tempwaittime = PCB[k].needtime; PCB[k].waittime = clock + tempwaittime - PCB[k].cpuburst; } printf("\\tThread:%-2d \\t %-3d \\t %-2d\\n", PCB[k].tid, clock, tempwaittime); clock = clock + tempwaittime; PCB[k].needtime = PCB[k].needtime - timeslice; } } for(int num=0; num<20; num++){ total_waittime = total_waittime + PCB[num].waittime; } average_waittime = total_waittime / (float)20; printf("总等待时间:%f\\n", total_waittime); printf("平均等待时间:%f\\n", average_waittime); } void Priority(){ printf("\\n------------------优先级Priority调度算法实现结果------------------\\n"); printf("\\t进程\\t 开始时间\\t 运行时间\\n"); for(int k=0; k<20; k++){ PCB[k].state = 'F'; } int i, j; int clock = 0; float total_waittime = 0; float average_waittime = 0; for(i=1; i<20; i++){ for(j=0; j<20; j++){ if(PCB[j].priority == i && PCB[j].state == 'F'){ printf("\\tThread:%-2d \\t %-3d \\t %-2d\\n", PCB[j].tid, clock, PCB[j].cpuburst); total_waittime = total_waittime + (float)clock; clock = clock + PCB[j].cpuburst; PCB[j].state = 'T'; } } } average_waittime = total_waittime / (float)20; printf("总等待时间:%f\\n", total_waittime); printf("平均等待时间:%f\\n", average_waittime); } int main(){ int ret1; pthread_t tid1; ret1 = pthread_create(&tid1, 0, &Create_children, 0); if(ret1==0){ printf("主线程创建成功!\\n"); sleep(20); } else{ printf("主线程创建失败!\\n"); } FCFS(); SJF(); printf("请输入时间片长度:\\n"); int timeslice; scanf("%d", &timeslice); RR(timeslice); Priority(); return 0; }
1
#include <pthread.h> int mystack_init(struct mystack* stack) { pthread_mutexattr_t mutex_attr; pthread_mutexattr_init(&mutex_attr); pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE_NP); pthread_mutex_init(&stack->mutex, &mutex_attr); pthread_mutexattr_destroy(&mutex_attr); stack->data = (void**)calloc(DEF_STACK_SIZE, sizeof(void*)); stack->length = 0; stack->max_length = DEF_STACK_SIZE; return 0; } int mystack_push(struct mystack* stack, void* data) { if (stack->length == stack->max_length) { pthread_mutex_lock(&stack->mutex); stack->max_length += DEF_STACK_SIZE; stack->data = (void**)realloc(stack->data, sizeof(void*) * stack->max_length); pthread_mutex_unlock(&stack->mutex); } pthread_mutex_lock(&stack->mutex); stack->data[stack->length] = data; ++stack->length; pthread_mutex_unlock(&stack->mutex); return 0; } int mystack_pop(struct mystack* stack, void** data) { if (stack->length <= 0) return 1; pthread_mutex_lock(&stack->mutex); --stack->length; (*data) = stack->data[stack->length]; pthread_mutex_unlock(&stack->mutex); if (stack->max_length > DEF_STACK_SIZE && stack->length <= (stack->max_length - DEF_STACK_SIZE)) { pthread_mutex_lock(&stack->mutex); stack->max_length -= DEF_STACK_SIZE/2; stack->data = (void**)realloc(stack->data, sizeof(void*) * stack->max_length); pthread_mutex_unlock(&stack->mutex); } return 0; } int mystack_destroy(struct mystack* stack) { for (int8_t i=0; i < stack->length; ++i) { free(stack->data[i]); } stack->length = 0; free(stack->data); stack->data = 0; stack->max_length = 0; pthread_mutex_destroy(&stack->mutex); return 0; }
0
#include <pthread.h> const int MAX_THREADS = 1024; long thread_count; long long n; double sum; pthread_mutex_t mutex; void* Thread_sum(void* rank); void Get_args(int argc, char* argv[]); void Usage(char* prog_name); double Serial_pi(long long n); int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; double start, finish, elapsed; Get_args(argc, argv); thread_handles = (pthread_t*) malloc (thread_count*sizeof(pthread_t)); pthread_mutex_init(&mutex, 0); sum = 0.0; GET_TIME(start); for (thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], 0, Thread_sum, (void*)thread); for (thread = 0; thread < thread_count; thread++) pthread_join(thread_handles[thread], 0); GET_TIME(finish); elapsed = finish - start; sum = 4.0*sum; printf("With n = %lld terms,\\n", n); printf(" Our estimate of pi = %.15f\\n", sum); printf("The elapsed time is %e seconds\\n", elapsed); GET_TIME(start); sum = Serial_pi(n); GET_TIME(finish); elapsed = finish - start; printf(" Single thread est = %.15f\\n", sum); printf("The elapsed time is %e seconds\\n", elapsed); printf(" pi = %.15f\\n", 4.0*atan(1.0)); pthread_mutex_destroy(&mutex); free(thread_handles); return 0; } void* Thread_sum(void* rank) { long my_rank = (long) rank; double factor; long long i; long long my_n = n/thread_count; long long my_first_i = my_n*my_rank; long long my_last_i = my_first_i + my_n; if (my_first_i % 2 == 0) factor = 1.0; else factor = -1.0; for (i = my_first_i; i < my_last_i; i++, factor = -factor) { pthread_mutex_lock(&mutex); sum += factor/(2*i+1); pthread_mutex_unlock(&mutex); } return 0; } double Serial_pi(long long n) { double sum = 0.0; long long i; double factor = 1.0; for (i = 0; i < n; i++, factor = -factor) { sum += factor/(2*i+1); } return 4.0*sum; } void Get_args(int argc, char* argv[]) { if (argc != 3) Usage(argv[0]); thread_count = strtol(argv[1], 0, 10); if (thread_count <= 0 || thread_count > MAX_THREADS) Usage(argv[0]); n = strtoll(argv[2], 0, 10); if (n <= 0) Usage(argv[0]); } void Usage(char* prog_name) { fprintf(stderr, "usage: %s <number of threads> <n>\\n", prog_name); fprintf(stderr, " n is the number of terms and should be >= 1\\n"); fprintf(stderr, " n should be evenly divisible by the number of threads\\n"); exit(0); }
1
#include <pthread.h> void study(int ID); void * foodDeliveryService(void * size_of_order); void * studentActions(void * ID); pthread_t * students; pthread_t deliveryWorker; int delivery_service_called = 0; int * studentID; pthread_mutex_t food_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t noFood = PTHREAD_COND_INITIALIZER; pthread_cond_t CallDelivery = PTHREAD_COND_INITIALIZER; int piecesOfFood = 0; int delivSize = 5; int main () { students = (pthread_t *) malloc(6 * sizeof(pthread_t)); studentID = (int *) malloc(6 * sizeof(int)); pthread_create(&deliveryWorker, 0, foodDeliveryService, (void *)&delivSize); for(int i = 0; i < 6; i++) { studentID[i] = i; printf("Creating thread with ID %d\\n",i ); pthread_create(&students[i], 0, studentActions, &studentID[i]); } pthread_join(deliveryWorker, 0); for(int i = 0; i < 6; i++) { pthread_join(students[i], 0); } pthread_mutex_destroy(&food_lock); return 0; } void study(int ID){ printf("Student %d: I am studying\\n", ID); sleep(1); } void * foodDeliveryService(void * size_of_order) { int order_size = *(int *) size_of_order; while(1) { sleep(4); pthread_mutex_lock(&food_lock); while (delivery_service_called == 0) pthread_cond_wait(&CallDelivery, &food_lock); piecesOfFood += order_size; printf("*******Delivery has arrived**********\\n"); delivery_service_called = 0; pthread_cond_broadcast(&noFood); pthread_mutex_unlock(&food_lock); } return 0; } void * studentActions(void * ID) { int hasFood = 0; int myID = *(int*)ID; while(1) { pthread_mutex_lock(&food_lock); while(piecesOfFood <= 0) { if(__sync_val_compare_and_swap(&delivery_service_called, 0, 1)==0) { printf("Student %d: Delivery ordered!\\n", myID); pthread_cond_signal(&CallDelivery); } else { printf("Student %d: goodnight.....\\n", myID); pthread_cond_wait(&noFood, &food_lock); } } piecesOfFood--; printf("Food Count: %d\\n",piecesOfFood ); hasFood = 1; pthread_mutex_unlock(&food_lock); if(hasFood) { study(myID); hasFood = 0; } } return 0; }
0
#include <pthread.h> int MyTurn = 0; { pthread_mutex_t *lock; pthread_cond_t *wait; int id; int size; int iterations; char *s; int nthreads; } Thread_struct; void *infloop(void *x) { int i, j, k; Thread_struct *t; t = (Thread_struct *) x; for (i = 0; i < t->iterations; i++) { pthread_mutex_lock(t->lock); while((MyTurn % t->nthreads) != t->id) { pthread_cond_wait(t->wait,t->lock); } for (j = 0; j < t->size-1; j++) { t->s[j] = 'A'+t->id; for(k=0; k < 50000; k++); } t->s[j] = '\\0'; printf("Thread %d: %s\\n", t->id, t->s); MyTurn++; pthread_cond_broadcast(t->wait); pthread_mutex_unlock(t->lock); } return(0); } int main(int argc, char **argv) { pthread_mutex_t lock; pthread_cond_t wait; pthread_t *tid; pthread_attr_t *attr; Thread_struct *t; void *retval; int nthreads, size, iterations, i; char *s; if (argc != 4) { fprintf(stderr, "usage: race nthreads stringsize iterations\\n"); exit(1); } pthread_mutex_init(&lock, 0); pthread_cond_init(&wait, 0); nthreads = atoi(argv[1]); size = atoi(argv[2]); iterations = atoi(argv[3]); tid = (pthread_t *) malloc(sizeof(pthread_t) * nthreads); attr = (pthread_attr_t *) malloc(sizeof(pthread_attr_t) * nthreads); t = (Thread_struct *) malloc(sizeof(Thread_struct) * nthreads); s = (char *) malloc(sizeof(char *) * size); for (i = 0; i < nthreads; i++) { t[i].nthreads = nthreads; t[i].id = i; t[i].size = size; t[i].iterations = iterations; t[i].s = s; t[i].lock = &lock; t[i].wait = &wait; pthread_attr_init(&(attr[i])); pthread_attr_setscope(&(attr[i]), PTHREAD_SCOPE_SYSTEM); pthread_create(&(tid[i]), &(attr[i]), infloop, (void *)&(t[i])); } for (i = 0; i < nthreads; i++) { pthread_join(tid[i], &retval); } return(0); }
1
#include <pthread.h> void signal_dispatch (struct signal_state *ss, siginfo_t *si) { SIGNAL_DISPATCH_ENTRY; int signo = si->si_signo; assert (signo > 0 && signo < NSIG); assert (pthread_mutex_trylock (&ss->lock) == EBUSY); do { if ((sigmask (signo) & STOPSIGS)) { sigdelset (&ss->pending, SIGCONT); sigdelset (&process_pending, SIGCONT); } else if ((signo == SIGCONT)) { ss->pending &= ~STOPSIGS; process_pending &= ~STOPSIGS; } void (*handler)(int, siginfo_t *, void *) = ss->actions[signo - 1].sa_sigaction; if (ss->actions[signo - 1].sa_flags & SA_RESETHAND && signo != SIGILL && signo != SIGTRAP) ss->actions[signo - 1].sa_handler = SIG_DFL; sigset_t orig_blocked = ss->blocked; ss->blocked |= ss->actions[signo - 1].sa_mask; if (! (ss->actions[signo - 1].sa_flags & (SA_RESETHAND | SA_NODEFER))) sigaddset (&ss->blocked, signo); sigdelset (&ss->pending, signo); pthread_mutex_unlock (&ss->lock); pthread_mutex_lock (&sig_lock); sigdelset (&process_pending, signo); pthread_mutex_unlock (&sig_lock); if (handler == (void *) SIG_DFL) { enum sig_action action = default_action (signo); if (action == sig_terminate || action == sig_core) _exit (128 + signo); if (action == sig_stop) panic ("Stopping process unimplemented."); if (action == sig_cont) ; panic ("Continuing process unimplemented."); } else if (handler == (void *) SIG_IGN) ; else handler (signo, si, 0); pthread_mutex_lock (&ss->lock); ss->blocked = orig_blocked; sigset_t pending = ~ss->blocked & ss->pending; if (! pending) pending = ~ss->blocked & process_pending; signo = l4_lsb64 (pending); } while (signo); pthread_mutex_unlock (&ss->lock); SIGNAL_DISPATCH_EXIT; }
0
#include <pthread.h> struct dte_request_queue *dte_req_q; struct dte_alloc_info_t dte_alloc_info; void init_dte_request_queue(struct dte_request_queue **p_dte_req_q) { int i; struct dte_request *reserved_dte_request; *p_dte_req_q = (struct dte_request_queue *)malloc(sizeof(struct dte_request_queue)); if (*p_dte_req_q == 0) { printf("can't alloc dte_request_queue\\n"); assert(*p_dte_req_q != 0); } reserved_dte_request = (struct dte_request *)malloc(sizeof(struct dte_request) * RESERVED_QUEUE_SIZE); dte_alloc_info.remainder = RESERVED_QUEUE_SIZE; dte_alloc_info.head = dte_alloc_info.dte_alloc_table; dte_alloc_info.tail = &dte_alloc_info.dte_alloc_table[RESERVED_QUEUE_SIZE - 1]; for (i = 0; i < RESERVED_QUEUE_SIZE - 1; i++) { dte_alloc_info.dte_alloc_table[i].container = &reserved_dte_request[i]; dte_alloc_info.dte_alloc_table[i].next = &dte_alloc_info.dte_alloc_table[i + 1]; } dte_alloc_info.dte_alloc_table[i].container = &reserved_dte_request[i]; dte_alloc_info.dte_alloc_table[i].next = 0; (*p_dte_req_q)->head = 0; (*p_dte_req_q)->tail = 0; (*p_dte_req_q)->num_of_entries = 0; pthread_mutex_init(&(*p_dte_req_q)->mutex, 0); } struct dte_request* alloc_dte_req() { struct dte_request *dte_req; struct dte_alloc_queue_t *temp_dte_alloc_queue; assert(dte_alloc_info.remainder > 0); temp_dte_alloc_queue = dte_alloc_info.head; dte_req = temp_dte_alloc_queue->container; dte_alloc_info.head = dte_alloc_info.head->next; temp_dte_alloc_queue->container = 0; if (dte_alloc_info.tail->next != 0) { temp_dte_alloc_queue->next = dte_alloc_info.tail->next; dte_alloc_info.tail->next = temp_dte_alloc_queue; } else { temp_dte_alloc_queue->next = 0; dte_alloc_info.tail->next = temp_dte_alloc_queue; } dte_alloc_info.remainder--; return dte_req; } void free_dte_req(struct dte_request* p_free_node) { assert(dte_alloc_info.remainder < RESERVED_QUEUE_SIZE); assert(dte_alloc_info.tail->next != 0); dte_alloc_info.remainder++; dte_alloc_info.tail = dte_alloc_info.tail->next; dte_alloc_info.tail->container = p_free_node; } void dte_request_enqueue(struct dte_request_queue *p_dte_req_q, struct dte_request p_dte_req) { struct dte_request *dte_req; struct dte_request *dte_req_iter; dte_req = alloc_dte_req(); *dte_req = p_dte_req; dte_req->next = 0; dte_req->prev = 0; if (dte_req->deadline == 0) { if (p_dte_req_q->head != 0) { p_dte_req_q->tail->next = dte_req; dte_req->prev = p_dte_req_q->tail; p_dte_req_q->tail = dte_req; } else { p_dte_req_q->head = dte_req; p_dte_req_q->tail = dte_req; } dte_req_q->num_of_entries++; } else { if (p_dte_req_q->head != 0) { for (dte_req_iter = p_dte_req_q->head; dte_req_iter != 0; dte_req_iter = dte_req_iter->next) { if (dte_req_iter->deadline == 0 || dte_req_iter->deadline > dte_req->deadline) { dte_req->next = dte_req_iter; dte_req->prev = dte_req_iter->prev; if (dte_req_iter->prev != 0) dte_req_iter->prev->next = dte_req; else p_dte_req_q->head = dte_req; dte_req_iter->prev = dte_req; break; } } if (dte_req_iter == 0) { p_dte_req_q->tail->next = dte_req; dte_req->prev = p_dte_req_q->tail; p_dte_req_q->tail = dte_req; } } else { p_dte_req_q->head = dte_req; p_dte_req_q->tail = dte_req; } dte_req_q->num_of_entries++; } } void set_dte_request_deadline(struct dte_request_queue *p_dte_req_q, int p_id, long long p_deadline) { struct dte_request *dte_req_iter; for (dte_req_iter = p_dte_req_q->head; dte_req_iter != 0; dte_req_iter = dte_req_iter->next) { if (dte_req_iter->id == p_id) break; } if (dte_req_iter != 0) { if (dte_req_iter == p_dte_req_q->head || dte_req_iter->prev->deadline <= dte_req_iter->deadline) { dte_req_iter->deadline = p_deadline; } else { dte_req_iter->prev->next = dte_req_iter->next; if (dte_req_iter->next != 0) { dte_req_iter->next->prev = dte_req_iter->prev; } else p_dte_req_q->tail = dte_req_iter->prev; dte_req_iter; dte_request_enqueue(p_dte_req_q, *dte_req_iter); free_dte_req(dte_req_iter); } } } struct dte_request get_dte_request(struct dte_request_queue *p_dma_req_q) { struct dte_request dte_req; struct dte_request *temp_dte_req; dte_req = *p_dma_req_q->head; temp_dte_req = p_dma_req_q->head; p_dma_req_q->head = p_dma_req_q->head->next; if (temp_dte_req == p_dma_req_q->tail) p_dma_req_q->tail = 0; p_dma_req_q->num_of_entries--; free_dte_req(temp_dte_req); return dte_req; } void unit_data_transfer(struct dte_request_queue *p_dma_req_q) { struct dte_request *dte_req; dte_req = p_dma_req_q->head; memcpy(dte_req->dst, dte_req->src, DATA_TRANSFER_UNIT); pthread_mutex_lock(&dte_req_q->mutex); dte_req->src = dte_req->src + DATA_TRANSFER_UNIT; dte_req->dst = dte_req->dst + DATA_TRANSFER_UNIT; dte_req->size = dte_req->size - DATA_TRANSFER_UNIT; if (dte_req->size == 0) { get_dte_request(p_dma_req_q); } pthread_mutex_unlock(&dte_req_q->mutex); } int is_data_transfer_done(struct dte_request_queue *p_dma_req_q, int p_id) { struct dte_request *dte_req_iter; int ret = 0; for (dte_req_iter = p_dma_req_q->head; dte_req_iter != 0; dte_req_iter = dte_req_iter->next) { if (dte_req_iter->id == p_id) break; } if (dte_req_iter == 0) ret = 1; return ret; } void *data_transfer_engine() { int in = 0; while (1) { pthread_mutex_lock(&dte_req_q->mutex); if (dte_req_q->num_of_entries) { in = 1; } pthread_mutex_unlock(&dte_req_q->mutex); if (in) { unit_data_transfer(dte_req_q); in = 0; } } }
1
#include <pthread.h> { double *a; double *b; double sum; int veclen; } DOTDATA; int NUMTHRDS; int VECLEN; DOTDATA dotstr; pthread_t *callThd = 0; pthread_mutex_t mutexsum; void *dotprod(void *arg) { int i, start, end, len ; long offset; double mysum, *x, *y; offset = (long)arg; len = dotstr.veclen; start = offset*len; end = start + len; x = dotstr.a; y = dotstr.b; mysum = 0; for (i=start; i<end ; i++) { mysum += (x[i] * y[i]); } pthread_mutex_lock (&mutexsum); dotstr.sum += mysum; printf("Thread %ld did %d to %d: mysum=%f global sum=%f\\n",offset,start,end,mysum,dotstr.sum); pthread_mutex_unlock (&mutexsum); pthread_exit((void*) 0); } int main (int argc, char *argv[]) { NUMTHRDS = 4; VECLEN = 100000; if(argc >= 3){ int entrada1 = atoi(argv[1]); int entrada2 = atoi(argv[2]); if(entrada1 == 0){ printf("\\n"); exit(1); } if(entrada2 == 0){ printf("\\n"); exit(1); } NUMTHRDS = entrada1; VECLEN = entrada2; callThd = malloc(sizeof(pthread_t)*NUMTHRDS); } long i; double *a, *b; void *status; pthread_attr_t attr; a = (double*) malloc (NUMTHRDS*VECLEN*sizeof(double)); b = (double*) malloc (NUMTHRDS*VECLEN*sizeof(double)); for (i=0; i<VECLEN*NUMTHRDS; i++) { a[i]=1; b[i]=a[i]; } dotstr.veclen = VECLEN; dotstr.a = a; dotstr.b = b; dotstr.sum=0; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0;i<NUMTHRDS;i++) { pthread_create(&callThd[i], &attr, dotprod, (void *)i); } pthread_attr_destroy(&attr); for(i=0;i<NUMTHRDS;i++) { pthread_join(callThd[i], &status); } printf ("Sum = %f \\n", dotstr.sum); free (a); free (b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
0
#include <pthread.h> int n; char str[1024]; int print_turn = 0; pthread_cond_t cond_print_turn = PTHREAD_COND_INITIALIZER; pthread_mutex_t mtx_print_turn = PTHREAD_MUTEX_INITIALIZER; void* print_thread(void* my_turn) { long my_turn_idx = (long)my_turn; for (;;) { pthread_mutex_lock(&mtx_print_turn); while (print_turn != my_turn_idx) pthread_cond_wait(&cond_print_turn, &mtx_print_turn); putc(str[my_turn_idx], stdout); print_turn++; pthread_mutex_unlock(&mtx_print_turn); pthread_cond_broadcast(&cond_print_turn); } } int main() { scanf("%d %s", &n, str); int str_len = strlen(str); pthread_t t; for (int i = 0; i < str_len - 1; i++) { pthread_create(&t, 0, print_thread, (void*)(long)i); } int process = 0; while (process != n) { pthread_mutex_lock(&mtx_print_turn); while (print_turn != str_len - 1) pthread_cond_wait(&cond_print_turn, &mtx_print_turn); putc(str[str_len - 1], stdout); process++; if (process != n) { print_turn = 0; } pthread_mutex_unlock(&mtx_print_turn); pthread_cond_broadcast(&cond_print_turn); } return 0; }
1
#include <pthread.h> static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static int scholarship = 4000; static int total = 0; static void *calculate(void *data); struct Data { const char *name; int doze; }; int main(void) { pthread_t tid1; pthread_t tid2; pthread_t tid3; struct Data a = { "A", 2 }; struct Data b = { "B", 1 }; struct Data c = { "C", 1 }; pthread_create(&tid1, 0, calculate, &a); pthread_create(&tid2, 0, calculate, &b); pthread_create(&tid3, 0, calculate, &c); pthread_join(tid1, 0); pthread_join(tid2, 0); pthread_join(tid3, 0); printf("Total given out: %d\\n", total); return 0; } static void *calculate(void *arg) { struct Data *data = arg; float result; while (scholarship > 0) { sleep(data->doze); pthread_mutex_lock(&mutex); result = ceil(scholarship * 0.25); total += result; scholarship -= result; if (result >= 1) printf("%s = %.2f\\n", data->name, result); pthread_mutex_unlock(&mutex); } printf("Thread %s exited\\n", data->name); return 0; }
0
#include <pthread.h> int s = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *ExecutaTarefa (void *threadid) { int i; int tid = (int) threadid; printf("Thread : %d esta executando...\\n", (int) tid); for (i=0; i<10000000; i++) { pthread_mutex_lock(&mutex); s++; pthread_mutex_unlock(&mutex); } printf("Thread : %d terminou!\\n", (int) tid); pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t tid[2]; int t; for(t=0; t<2; t++) { printf("--Cria a thread %d\\n", t); if (pthread_create(&tid[t], 0, ExecutaTarefa, (void *)t)) { printf("--ERRO: pthread_create()\\n"); exit(-1); } } for (t=0; t<2; t++) { if (pthread_join(tid[t], 0)) { printf("--ERRO: pthread_join() \\n"); exit(-1); } } printf("Valor de s = %d\\n", s); pthread_exit(0); }
1
#include <pthread.h> int proto_listenfd; int proto_vsftp_listenfd; int proto_stop = 1; pthread_t proto_listen_tid; void *proto_listen_thread( void *args ); pthread_t proto_reqhand_tid; void *(*proto_reqhand_thread)( void *args ); pthread_mutex_t proto_sockfd_pass_mutex; pthread_cond_t proto_sockfd_pass_cv; pthread_mutex_t proto_dlmgr_mutex; char proto_bind_address[16]; unsigned short proto_bind_port; int proto_listen( const char *localaddr, unsigned short listen_bind_port, unsigned short vsftp_bind_port, void *(*cbthread)( void *) ) { pthread_mutex_init( &proto_sockfd_pass_mutex, 0 ); pthread_cond_init( &proto_sockfd_pass_cv, 0 ); pthread_mutex_init( &proto_dlmgr_mutex, 0 ); if( ( proto_listenfd = tcp_listen( localaddr, listen_bind_port ) ) < 0 ) { return -1; } if( ( proto_vsftp_listenfd = tcp_listen( localaddr, vsftp_bind_port ) ) < 0 ) { return -1; } strcpy( proto_bind_address, localaddr ); proto_bind_port = listen_bind_port; proto_stop = 0; proto_reqhand_thread = cbthread; if( pthread_create( &proto_listen_tid, 0, proto_listen_thread, 0 ) != 0 ) { return -1; } return 0; } int proto_active( void ) { return !proto_stop; } int proto_stop_listen( void ) { int sockfd; char connaddr[16]; proto_stop = 1; if( strcmp( proto_bind_address, "0.0.0.0" ) == 0 ) strcpy( connaddr, "127.0.0.1" ); else strcpy( connaddr, proto_bind_address ); if( ( sockfd = tcp_connect( connaddr, proto_bind_port ) ) < 0 ) { return -1; } close( sockfd ); close( proto_vsftp_listenfd ); pthread_join( proto_listen_tid, 0 ); pthread_mutex_destroy( &proto_sockfd_pass_mutex ); pthread_cond_destroy( &proto_sockfd_pass_cv ); pthread_mutex_destroy( &proto_dlmgr_mutex ); } void *proto_listen_thread( void *args ) { int sockfd; while( !proto_stop ) { if( ( sockfd = accept( proto_listenfd, 0, 0 ) ) < 0 ) { pthread_exit( 0 ); } if( proto_stop ) break; pthread_mutex_lock( &proto_sockfd_pass_mutex ); pthread_create( &proto_reqhand_tid, 0, *proto_reqhand_thread, (void *)&sockfd ); pthread_cond_wait( &proto_sockfd_pass_cv, &proto_sockfd_pass_mutex ); pthread_mutex_unlock( &proto_sockfd_pass_mutex ); } close( sockfd ); close( proto_listenfd ); pthread_exit( 0 ); return 0; }
0
#include <pthread.h> int thread_count; int barrier_thread_counts[100]; pthread_mutex_t barrier_mutex; void Usage(char* prog_name); void *Thread_work(void* rank); int main(int argc, char* argv[]) { long thread, i; pthread_t* thread_handles; double start, finish; if (argc != 2) Usage(argv[0]); thread_count = strtol(argv[1], 0, 10); thread_handles = malloc (thread_count*sizeof(pthread_t)); for (i = 0; i < 100; i++) barrier_thread_counts[i] = 0; pthread_mutex_init(&barrier_mutex, 0); GET_TIME(start); for (thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], 0, Thread_work, (void*) thread); for (thread = 0; thread < thread_count; thread++) { pthread_join(thread_handles[thread], 0); } GET_TIME(finish); printf("Elapsed time = %e seconds\\n", finish - start); pthread_mutex_destroy(&barrier_mutex); free(thread_handles); return 0; } void Usage(char* prog_name) { fprintf(stderr, "usage: %s <number of threads>\\n", prog_name); exit(0); } void *Thread_work(void* rank) { int i; for (i = 0; i < 100; i++) { pthread_mutex_lock(&barrier_mutex); barrier_thread_counts[i]++; pthread_mutex_unlock(&barrier_mutex); while (barrier_thread_counts[i] < thread_count); } return 0; }
1
#include <pthread.h> long i; pthread_t r[10]; pthread_t w[4]; long shared = 999; pthread_mutex_t wlock; pthread_mutex_t rclock; int reader_count = 0; void * writer(void * index) { long w = (long)index; while(1) { pthread_mutex_lock(&wlock); shared = random() % 1000; printf("Writer[%ld] wrote: %ld\\n", w, shared); pthread_mutex_unlock(&wlock); } pthread_exit(0); return 0; } void * reader(void * index) { long r = (long)index; while(1) { pthread_mutex_lock(&rclock); if(reader_count==0) { pthread_mutex_lock(&wlock); } reader_count++; pthread_mutex_unlock(&rclock); printf("Reader[%ld] read: %ld\\n", r, shared); pthread_mutex_lock(&rclock); reader_count--; if(reader_count==0) { pthread_mutex_unlock(&wlock); } pthread_mutex_unlock(&rclock); usleep(random()%10000); } return 0; } void WRITER(long i) { if(pthread_create(&w[i], 0, writer, (void *)i)!=0) { perror("Writer creation failed!"); exit(0); } } void READER(long i) { if(pthread_create(&r[i], 0, reader, (void *)i)!=0) { perror("Reader creation failed!"); exit(0); } } int main (int argc, char *argv []) { pthread_mutex_init(&wlock, 0); for(i=0; i < 4; i++) { WRITER(i); } for(i=0; i < 10; i++) { READER(i); } for(i=0; i < 4; i++) { pthread_join(w[i], 0); } for(i=0; i < 10; i++) { pthread_join(r[i], 0); } return 0; }
0
#include <pthread.h> pthread_mutex_t full_mutex = PTHREAD_MUTEX_INITIALIZER; int full = 0; int count = 0; void* produce(void* x){ while(1){ while(full){ } pthread_mutex_lock(&full_mutex); count++; full = 1; printf("Produced: %d\\n", count); pthread_mutex_unlock(&full_mutex); if(count>=10) break; } } void* consume(void* y){ while(1){ while(!full){ } pthread_mutex_lock(&full_mutex); full = 0; printf("Consumed: %d\\n", count); pthread_mutex_unlock(&full_mutex); if(count>=10) break; } } int main(int argc, char const *argv[]) { pthread_t prod1, cons1; pthread_create(&prod1, 0, produce, 0); pthread_create(&cons1, 0, consume, 0); pthread_join(prod1, 0); pthread_join(cons1, 0); return 0; }
1
#include <pthread.h> pthread_mutex_t global_lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t net_bh_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t net_bh_wakeup = PTHREAD_COND_INITIALIZER; int net_bh_raised = 0; struct task_struct current_contents; int sock_wake_async (struct socket *sock, int how) { return 0; } void * net_bh_worker (void *arg) { pthread_mutex_lock (&net_bh_lock); while (1) { while (!net_bh_raised) pthread_cond_wait (&net_bh_wakeup, &net_bh_lock); net_bh_raised = 0; pthread_mutex_lock (&global_lock); net_bh (); pthread_mutex_unlock (&global_lock); } return 0; }
0
#include <pthread.h> void *hiloGetWEB(void *); void *hiloGetWEB(void *); int conexiones_add (char *url); pthread_t thread_id [5]; pthread_mutex_t mutexPool = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexCounter = PTHREAD_MUTEX_INITIALIZER; int poolCounter = 0; int poolTop = 0; char * pool[100] ; int conexiones_add (char *url){ pthread_mutex_lock( &mutexPool ); pool[poolTop] = url; poolTop++; pthread_mutex_unlock( &mutexPool ); } int conexiones_Inicia () { int i; for(i=0; i < 5; i++) { pthread_create( &thread_id[i], 0, hiloGetWEB, 0 ); } return 0; } int conexiones_joinHilos(){ int j; for(j=0; j < 5; j++) { pthread_join( thread_id[j], 0); } } void *hiloGetWEB(void *dummyPtr) { struct Poolstruct *PoolstructObj = listaPool_newPool(); while (1){ pthread_mutex_lock( &mutexCounter ); int poolCounterActual= -1; if (PoolstructObj->poolTop > PoolstructObj->poolCounter){ poolCounterActual= PoolstructObj->poolCounter; PoolstructObj->poolCounter++; printf("(C)~~~~~Hilo: %ld Elemento %d de %d (%s )\\n", PoolstructObj->id, poolCounterActual, PoolstructObj->poolTop, PoolstructObj->pool[poolCounterActual]); } else{ printf("(C)~~~~~Hilo: %ld Pool sin pendientes \\n", PoolstructObj->id); } pthread_mutex_unlock( &mutexCounter ); if (poolCounterActual!=-1){ char * html; html = socket_getHtml (PoolstructObj->pool[poolCounterActual], "/"); cache_add (html, PoolstructObj->pool[poolCounterActual]); memset(html, 0, sizeof(char ) * strlen (html)); printf("(C)~~~~~Hilo: %ld Finaliza \\n", PoolstructObj->id, PoolstructObj->pool[poolCounterActual]); } sleep (1); } }
1
#include <pthread.h> pthread_mutex_t the_mutex; pthread_cond_t condc, condp, condp2; int buffer[100]; int i = 0; void * producer(void *ptr) { while(1) { printf("producer locking critical region\\n"); pthread_mutex_lock(&the_mutex); while( i == 100) { printf("buffer not empty, producer sleeping\\n"); pthread_cond_wait(&condp, &the_mutex); } printf("producer producing element %d\\n", i); buffer[i] = i; i++; printf("producer signaling consumer to wake up\\n"); pthread_cond_signal(&condc); printf("producer releasing lock on critical region\\n"); pthread_mutex_unlock(&the_mutex); } } void * producer2(void *ptr) { while(1) { printf("producer2 locking critical region\\n"); pthread_mutex_lock(&the_mutex); while( i == 100) { printf("buffer not empty, producer2 sleeping\\n"); pthread_cond_wait(&condp2, &the_mutex); } printf("producer2 producing element %d\\n", i); buffer[i] = i; i++; printf("producer2 signaling consumer to wake up\\n"); pthread_cond_signal(&condc); printf("producer2 releasing lock on critical region\\n"); pthread_mutex_unlock(&the_mutex); } } void * consumer(void *ptr) { while(1) { printf("consumer locking critical region\\n"); pthread_mutex_lock(&the_mutex); while(i == -1) { i = 0; printf("buffer is empty, consumer sleeping\\n"); pthread_cond_wait(&condc, &the_mutex); } printf("consumer consuming element %d\\n", i); buffer[i] = 0; i--; printf("consumer signaling producer(s) to wake up\\n"); pthread_cond_signal(&condp); pthread_cond_signal(&condp2); printf("consumer releasing lock on critical region\\n"); pthread_mutex_unlock(&the_mutex); } } int main() { pthread_t pro, pro2, con; pthread_mutex_init(&the_mutex, 0); pthread_cond_init(&condc, 0); pthread_cond_init(&condp, 0); pthread_create(&con, 0, consumer, 0); pthread_create(&pro, 0, producer, 0); pthread_create(&pro2, 0, producer2, 0); pthread_join(pro, 0); pthread_join(pro2, 0); pthread_join(con, 0); pthread_cond_destroy(&condc); pthread_cond_destroy(&condp); pthread_cond_destroy(&condp2); pthread_mutex_destroy(&the_mutex); return 0; }
0
#include <pthread.h> pthread_mutex_t _sock_lock; void _bb_init_bb(){ if(pthread_mutex_init(&_sock_lock, 0) != 0){ puts("Failed to initialize mutex."); exit(1); } } int blox_sendDirectlyl(char* line, int len){ if(!irc_conn){ return -1; } if(!line){ return 0; } if(bb_isVerbose){ printf(">> %.*s", len, line); } pthread_mutex_lock(&_sock_lock); int ret = irc_conn->write(irc_conn, line, len); pthread_mutex_unlock(&_sock_lock); return ret; } int blox_sendDirectly(char* line){ if(!line){ return 0; } int line_len = strlen(line); return blox_sendDirectlyl(line, line_len); } int blox_send(char* line){ if(!line){ return 0; } long int cT = _bb_curtime(); if((cT - irc_last_msg) > BB_MSG_DEBUF){ blox_sendDirectly(line); irc_last_msg = cT; }else{ _bb_push_queue(line); } return 0; } int blox_sendMsg(char* target, char* msg){ if(!target){ return 0; } if(!msg){ return 0; } size_t lenChan = strlen(target); size_t lenMsg = strlen(msg); char line[12 + lenChan + lenMsg]; strcpy(line, "PRIVMSG "); strcat(line, target); strcat(line, " :"); strcat(line, msg); strcat(line, "\\r\\n"); return blox_send(line); } int blox_join(char* chan){ if(!chan){ return 0; } size_t lenChan = strlen(chan); char line[7 + lenChan]; strcpy(line, "JOIN "); strcat(line, chan); strcat(line, "\\r\\n"); return blox_sendDirectly(line); } int blox_part(char* chan){ if(!chan){ return 0; } size_t lenChan = strlen(chan); char line[7 + lenChan]; strcpy(line, "PART "); strcat(line, chan); strcat(line, "\\r\\n"); return blox_sendDirectly(line); } int blox_partr(char* chan, char* reason){ if(!chan){ return 0; } size_t lenChan = strlen(chan); size_t lenReason = strlen(reason); char line[9 + lenChan + lenReason]; strcpy(line, "PART "); strcat(line, chan); strcat(line, " :"); strcat(line, reason); strcat(line, "\\r\\n"); return blox_sendDirectly(line); } int blox_pong(char* servName){ if(!servName){ return 0; } size_t lenServ = strlen(servName); size_t lenWhole = 8 + lenServ; char line[lenWhole]; strcpy(line, "PONG :"); strcat(line, servName); strcat(line, "\\r\\n"); return blox_sendDirectlyl(line, lenWhole); } unsigned char blox_isAdmin(char* srcNick, char* srcLogin, char* srcHost){ return ((strcmp(srcHost, "openblox/johnmh") == 0) || (strcmp(srcHost, "redvice/safazi") == 0)); } void blox_msgToUser(char* target, char* srcNick, unsigned char isPublic, char* msg){ if(target && isPublic){ char msgBuf[strlen(srcNick) + 2 + strlen(msg)]; strcpy(msgBuf, srcNick); strcat(msgBuf, ": "); strcat(msgBuf, msg); blox_sendMsg(target, msgBuf); }else{ blox_sendMsg(srcNick, msg); } }
1
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top=0; static unsigned int arr[(800)]; pthread_mutex_t m; _Bool flag=(0); void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { (top==0) ? (1) : (0); } int push(unsigned int *stack, int x) { if (top==(800)) { printf("stack overflow\\n"); return (-1); } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (get_top()==0) { printf("stack underflow\\n"); return (-2); } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for( i=0; i<(800); i++) { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint()%(800); if (push(arr,tmp)==(-1)) error(); flag=(1); pthread_mutex_unlock(&m); } } void *t2(void *arg) { int i; for( i=0; i<(800); i++) { pthread_mutex_lock(&m); if (flag) { if (!(pop(arr)!=(-2))) error(); } pthread_mutex_unlock(&m); } } int main(void) { pthread_t id1, id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> struct msg { struct msg *msg_next; time_t msg_time; }; struct msg *head; pthread_cond_t qcond = PTHREAD_COND_INITIALIZER; pthread_mutex_t mlock = PTHREAD_MUTEX_INITIALIZER; void * process (void *arg) { struct msg *mp; for (;;) { pthread_mutex_lock (&mlock); while (head == 0) pthread_cond_wait (&qcond, &mlock); mp = head; head = mp->msg_next; pthread_mutex_unlock (&mlock); printf ("%s\\n", ctime (&mp->msg_time)); free (mp); } } void enquene_msg (struct msg *mp) { pthread_mutex_lock (&mlock); mp->msg_next = head; head = mp; pthread_mutex_unlock (&mlock); pthread_cond_signal (&qcond); } int main () { pthread_t tid; struct msg *tmp; head = 0; pthread_create (&tid, 0, process, 0); while (1) { tmp = malloc (sizeof (struct msg)); if (tmp == 0) return -1; memset (tmp, 0, sizeof (struct msg)); tmp->msg_next = 0; time (&tmp->msg_time); enquene_msg (tmp); sleep(2); } return 0; }
1
#include <pthread.h> static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER; void output_init() { return; } void output( char * string, ... ) { va_list ap; char *ts="[??:??:??]"; struct tm * now; time_t nw; pthread_mutex_lock(&m_trace); nw = time(0); now = localtime(&nw); if (now == 0) printf(ts); else printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec); __builtin_va_start((ap)); vprintf(string, ap); ; pthread_mutex_unlock(&m_trace); } void output_fini() { return; }
0
#include <pthread.h> long counter; pthread_mutex_t lock; time_t end_time; void *c_thread(void *args){ int i; while(time(0) < end_time){ pthread_mutex_lock(&lock); for(i=0;i<10000000;i++){ counter++; } pthread_mutex_unlock(&lock); } return 0; } void *m_thread(void *args){ int misses = 0; while(time(0) < end_time){ usleep(250); if( pthread_mutex_trylock(&lock) == 0){ pthread_mutex_unlock(&lock); }else{ misses++; } } printf("M_THREAD: Missed %d times\\n", misses); return 0; } int main(int argc, char * argv[]){ pthread_t m_thread_id,c_thread_id; end_time = time(0)+15; pthread_mutex_init(&lock, 0); pthread_create(&c_thread_id, 0, c_thread, 0); pthread_create(&m_thread_id, 0, m_thread, 0); pthread_join(c_thread_id, 0); pthread_join(m_thread_id, 0); return 0; }
1
#include <pthread.h> int thread_count = 4; int n = 10000; double a = 0.0; double b = 10.0; double h; int local_n; int flag; sem_t sem; pthread_mutex_t mutex; double total_flag = 0.0; double total_sem = 0.0; double total_mutex = 0.0; void *Thread_work(void* rank); double Trap(double local_a, double local_b, int local_n, double h); double f(double x); int main(int argc, char** argv) { int i; int thread_args[thread_count]; pthread_t* thread_handles; h = (b-a)/n; local_n = n/thread_count; thread_handles = malloc (thread_count*sizeof(pthread_t)); flag = 0; pthread_mutex_init(&mutex, 0); sem_init(&sem, 0, 1); for (i = 0; i < thread_count; i++) { thread_args[i] = i; pthread_create(&thread_handles[i], 0, Thread_work, (void*) &thread_args[i]); } for (i = 0; i < thread_count; i++) { pthread_join(thread_handles[i], 0); } printf("The function f(x) = x² , in the interval [%.4f, %.4f], has an estimate area of:\\n", a,b); printf("busy waiting: %f\\n", total_flag); printf("mutex: %f\\n", total_mutex); printf("semaphore: %f\\n", total_sem); pthread_mutex_destroy(&mutex); sem_destroy(&sem); free(thread_handles); return 0; } void *Thread_work(void* rank) { double local_a; double local_b; double my_int; int my_rank = *((long*) rank); local_a = a + my_rank*local_n*h; local_b = local_a + local_n*h; my_int = Trap(local_a, local_b, local_n, h); while(flag != my_rank); total_flag += my_int; flag = (flag+1) % thread_count; sem_wait(&sem); total_sem += my_int; sem_post(&sem); pthread_mutex_lock(&mutex); total_mutex += my_int; pthread_mutex_unlock(&mutex); return 0; } double Trap( double local_a , double local_b , int local_n , double h ) { double integral; double x; int i; integral = (f(local_a) + f(local_b))/2.0; x = local_a; for (i = 1; i <= local_n-1; i++) { x = local_a + i*h; integral += f(x); } integral = integral*h; return integral; } double f(double x) { double return_val; return_val = x*x; return return_val; }
0
#include <pthread.h> pthread_cond_t cond_empty, cond_full; pthread_mutex_t mutex; int count = 0, in = 0, out = 0; int buffer[3]; void *produtor(void *arg) { while (1) { sleep(rand()%5); pthread_mutex_lock(&mutex); while (count == 3) pthread_cond_wait(&cond_empty, &mutex); buffer[in] = rand()%100; count++; printf("Produzindo buffer[%d] = %d\\n", in, buffer[in]); in = (in + 1) % 3; pthread_cond_signal(&cond_full); pthread_mutex_unlock(&mutex); } } void *consumidor(void *arg) { int my_task; while (1) { sleep(rand()%5); pthread_mutex_lock(&mutex); while (count == 0) pthread_cond_wait(&cond_full, &mutex); my_task = buffer[out]; count--; printf("Consumindo buffer[%d] = %d\\n", out, my_task); out = (out + 1) % 3; pthread_cond_signal(&cond_empty); pthread_mutex_unlock(&mutex); } } int main(int argc, char *argv[]) { pthread_t prod, cons; pthread_cond_init(&cond_empty, 0); pthread_cond_init(&cond_full, 0); pthread_mutex_init(&mutex, 0); pthread_create(&prod, 0, (void *)produtor, 0); pthread_create(&cons, 0, (void *)consumidor, 0); pthread_join(prod, 0); pthread_join(cons, 0); return 0; }
1
#include <pthread.h> struct arg_set{ int count; char *fname; }; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t flag = PTHREAD_COND_INITIALIZER; struct arg_set *mailbox = 0; void *count_words(void *a) { struct arg_set *args = a; FILE *fp; int c, prevc = '\\0'; if((fp = fopen(args->fname, "r")) != 0){ while((c = getc(fp)) != EOF){ if(! isalnum(c) && isalnum(prevc)) args->count++; prevc = c; } fclose(fp); }else perror(args->fname); printf("COUNT: waiting to get lock\\n"); pthread_mutex_lock(&lock); printf("COUNT: have lock, storing data\\n"); if(mailbox != 0) pthread_cond_wait(&flag, &lock); mailbox = args; printf("COUNT: raising flag\\n"); pthread_cond_signal(&flag); printf("COUNT: unlocking box\\n"); pthread_mutex_unlock(&lock); return 0; } int main(int argc, char *argv[]) { struct arg_set arg1, arg2; int total_words = 0; pthread_t t1, t2; int reports_in = 0; if(argc != 3){ perror("usage: ./out file1 file2\\n"); exit(1); } pthread_mutex_lock(&lock); arg1.fname = argv[1]; arg1.count = 0; pthread_create(&t1, 0, count_words, (void *)&arg1); arg2.fname = argv[2]; arg2.count = 0; pthread_create(&t2, 0, count_words, (void *)&arg2); while(reports_in < 2){ printf("MAIN: waiting for flag to go up\\n"); pthread_cond_wait(&flag, &lock); printf("MAIN: Wow! flag was raised, I have the lock\\n"); printf("%7d: %s\\n", mailbox->count, mailbox->fname); total_words += mailbox->count; if(mailbox == &arg1) pthread_join(t1, 0); if(mailbox == &arg2) pthread_join(t2, 0); mailbox = 0; pthread_cond_signal(&flag); reports_in++; } printf("%7d: total words\\n", total_words); }
0
#include <pthread.h> bool receiver_data_raw(struct mux *mx, uint8_t chnum) { struct muxbuf *mxb = &mx->mx_buffer[MUX_IN][chnum]; uint16_t mss; uint8_t *cmd = mx->mx_recvcmd; size_t len1, len2, tail; int err; if (!sock_recv(mx->mx_socket, cmd, MUX_CMDLEN_DATA - 2)) { logmsg_err("Receiver(DATA) Error: recv"); return (0); } mss = GetWord(cmd); if ((mss == 0) || (mss > mxb->mxb_mss)) { logmsg_err("Receiver(DATA) Error: invalid length: %u", mss); return (0); } if ((err = pthread_mutex_lock(&mxb->mxb_lock)) != 0) { logmsg_err("Receiver(DATA) Error: mutex lock: %s", strerror(err)); return (0); } if (mxb->mxb_state != MUX_STATE_RUNNING) { logmsg_err("Receiver(DATA) Error: not running: %u", chnum); mxb->mxb_state = MUX_STATE_ERROR; pthread_mutex_unlock(&mxb->mxb_lock); return (0); } while (mxb->mxb_length + mss > mxb->mxb_bufsize) { logmsg_debug(DEBUG_BASE, "Receiver: Sleep(%u): %u + %u > %u", chnum, mxb->mxb_length, mss, mxb->mxb_bufsize); if ((err = pthread_cond_wait(&mxb->mxb_wait_in, &mxb->mxb_lock)) != 0) { logmsg_err("Receiver(DATA) Error: cond wait: %s", strerror(err)); mxb->mxb_state = MUX_STATE_ERROR; pthread_mutex_unlock(&mxb->mxb_lock); return (0); } logmsg_debug(DEBUG_BASE, "Receiver: Wakeup(%u): %u, %u, %u", chnum, mxb->mxb_length, mss, mxb->mxb_bufsize); if (mxb->mxb_state != MUX_STATE_RUNNING) { logmsg_err("Receiver(DATA) Error: not running: %u", chnum); mxb->mxb_state = MUX_STATE_ERROR; pthread_mutex_unlock(&mxb->mxb_lock); return (0); } } if ((tail = mxb->mxb_head + mxb->mxb_length) >= mxb->mxb_bufsize) tail -= mxb->mxb_bufsize; if ((len1 = tail + mss) > mxb->mxb_bufsize) len2 = len1 - mxb->mxb_bufsize; else len2 = 0; len1 = mss - len2; if (!sock_recv(mx->mx_socket, &mxb->mxb_buffer[tail], len1)) { logmsg_err("Receiver(DATA) Error: recv data"); mxb->mxb_state = MUX_STATE_ERROR; pthread_mutex_unlock(&mxb->mxb_lock); return (0); } if (len2 > 0) { if (!sock_recv(mx->mx_socket, mxb->mxb_buffer, len2)) { logmsg_err("Receiver(DATA) Error: recv data"); mxb->mxb_state = MUX_STATE_ERROR; pthread_mutex_unlock(&mxb->mxb_lock); return (0); } } mx->mx_xfer_in += mss; mxb->mxb_length += mss; if ((err = pthread_cond_signal(&mxb->mxb_wait_out)) != 0) { logmsg_err("Receiver(DATA) Error: cond signal: %s", strerror(err)); mxb->mxb_state = MUX_STATE_ERROR; pthread_mutex_unlock(&mxb->mxb_lock); return (0); } if ((err = pthread_mutex_unlock(&mxb->mxb_lock)) != 0) { logmsg_err("Receiver(DATA) Error: mutex unlock: %s", strerror(err)); return(0); } return (1); }
1
#include <pthread.h> void generate(); void Read(); void *func1(void *arg); void *func2(void *arg); void calculate(); void resultToFile(); int A[1000]={0}; int prefix_sum[1000]={0}; int temp[1000]={0}; int n; pthread_t tids[1000][1000]; pthread_mutex_t mutex; struct S { int i ; int j ; }; int main() { printf("ARRAY'S SCALE : "); scanf("%d",&n); generate(); Read(); clock_t start = clock(); calculate(); resultToFile(); clock_t finish = clock(); printf("COST TIME IS : %.20f second\\n",(double)(finish-start)/CLOCKS_PER_SEC); return 0 ; } void resultToFile() { int i; FILE *file; file = fopen("/home/ly/parallel/2/GetRidOf2DArray.txt","wt"); for(i=1;i<=n;i++) { fprintf(file,"%-6d",prefix_sum[i]); } } void calculate() { int h,i,j,k,l ; for(i=1;i<=n;i++) { struct S* s; s = (struct S*)malloc(sizeof(struct S)); s->i = i; if( pthread_create(&tids[0][i],0,func1,s)) { perror("Fail to create thread!"); exit(1); } } for(j=1;j<=n;j++) pthread_join(tids[0][j],0); k=2; while(k<n) { for(i=1;i<=n;i++) temp[i] = prefix_sum[i]; for(i=k+1;i<=n;i++) { struct S* s; s = (struct S*)malloc(sizeof(struct S)); s->i = i; s->j = k; if( pthread_create(&tids[k][i],0,func2,s)) { perror("Fail to create thread!"); exit(1); } } for(j=k+1;j<=n;j++) pthread_join(tids[k][j],0); for(i=1;i<=n;i++) prefix_sum[i] = temp[i]; k = k + k; } } void *func1(void *arg) { int i ; struct S *p; p = (struct S*)arg; i = p->i; pthread_mutex_lock(&mutex); if(i==1) prefix_sum[i] = A[i]; else prefix_sum[i] = A[i-1] + A[i]; pthread_mutex_unlock(&mutex); pthread_exit(0); } void *func2(void *arg) { int i ,k ; struct S *p; p = (struct S*)arg; i = p->i; k = p->j; pthread_mutex_lock(&mutex); temp[i] = prefix_sum[i-k] + prefix_sum[i]; pthread_mutex_unlock(&mutex); pthread_exit(0); } void generate() { FILE *file; if( (file = fopen("//home/ly/parallel/2/arrayB.txt","wt"))==0 ) { perror("fopen"); exit(1); } int i , j ; srand((unsigned)time(0) ); for( i=1;i<=n;i++ ) fprintf(file,"%-6d",rand()%99); fprintf(file , "\\n"); fclose(file); } void Read() { FILE *file; if( (file = fopen("/home/ly/parallel/2/arrayB.txt","rt"))==0 ) { perror("fopen"); exit(1); } int i , j ; srand((unsigned)time(0) ); for( i=1;i<=n;i++ ) fscanf(file,"%d",&A[i]); fclose(file); }
0
#include <pthread.h> void error_out(int errnum) { switch(errnum) { case 0: fprintf(stderr, "Usage: ./search-engine [num-indexer-threads] [list-of-files.txt]\\n"); exit(1); case 1: fprintf(stderr, "File does not exist.\\n"); exit(1); case 2: fprintf(stderr, "File scanner failed.\\n"); exit(1); case 3: fprintf(stderr, "File indexer failed.\\n"); exit(1); case 4: default: fprintf(stderr, "Search interface failed.\\n"); exit(1); } } void exit_main() { buff_free(); } char* sought_file = 0; int num_lines; int list_scanned = 0; int buf_head = 0; int buf_tail = 0; const int SIZE = 10; pthread_mutex_t fill_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t full_cv; pthread_cond_t empty_cv; int fill() { buf_head++; buf_head %= SIZE; return buf_head; } int empty() { buf_tail++; buf_tail %= SIZE; return buf_tail; } int num_elements() { return (buf_head > buf_tail)? buf_head - buf_tail: SIZE + buf_head - buf_tail; } void* scanning_function(void* the_file) { while(!list_scanned) { pthread_mutex_lock(&fill_mutex); while(is_full()){ pthread_cond_wait(&full_cv, &fill_mutex); } if(file_scanner((char*)the_file) == 1) list_scanned = 1; if(get_count() == 1){ pthread_cond_signal(&empty_cv); } pthread_mutex_unlock(&fill_mutex); } pthread_cond_broadcast(&empty_cv); pthread_exit(0); } void* indexing_function() { while(num_lines > 0) { pthread_mutex_lock(&fill_mutex); while(is_empty() && !list_scanned) { pthread_cond_wait(&empty_cv, &fill_mutex); } file_indexer(); num_lines--; pthread_cond_signal(&full_cv); pthread_mutex_unlock(&fill_mutex); } set_done(); pthread_exit(0); } void* searching_function() { search_interface(); pthread_exit(0); } int main(int argc, char* argv[]) { if(argc != 3) { error_out(0); } int num_threads = atoi(argv[1]); num_lines = get_numfiles(argv[2]); buff_init(num_lines); if(num_threads < 1) { error_out(0); } if(access(argv[2], R_OK) == -1) { error_out(1); } init_index(); pthread_t scanning_thread; pthread_t indexing_thread[num_threads]; pthread_t searching_thread; int i; pthread_create(&scanning_thread, 0, scanning_function, (void*)argv[2]); atexit(exit_main); for(i = 0; i < num_threads; ++i) { pthread_create(&indexing_thread[i], 0, indexing_function, 0); } pthread_create(&searching_thread, 0, searching_function, 0); pthread_join(scanning_thread, 0); for(i = 0; i < num_threads; ++i) { pthread_join(indexing_thread[i], 0); } pthread_join(searching_thread, 0); return 0; }
1
#include <pthread.h> pthread_mutex_t lock; int value; }SharedInt; sem_t sem; SharedInt* sip; int foo = 0; void *functionWithCriticalSection(int* v2) { pthread_mutex_lock(&(sip->lock)); sip->value = sip->value + *v2; int currvalue = sip->value; pthread_mutex_unlock(&(sip->lock)); printf("Current value was %i.\\n", currvalue); foo = currvalue; sem_post(&sem); } int main() { sem_init(&sem, 0, 0); SharedInt si; sip = &si; sip->value = 0; int v2 = 1; pthread_mutex_init(&(sip->lock), 0); pthread_t thread1; pthread_t thread2; pthread_create (&thread1,0,functionWithCriticalSection,&v2); pthread_create (&thread2,0,functionWithCriticalSection,&v2); sem_wait(&sem); sem_wait(&sem); pthread_mutex_destroy(&(sip->lock)); sem_destroy(&sem); printf("%d\\n", sip->value); if(sip->value+foo == 3 || sip->value+foo == 4) { return 0; } else { return 1; } }
0
#include <pthread.h> int nitems; int buff[1000000]; struct { pthread_mutex_t mutex; int nput; int nval; } put = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; struct { pthread_mutex_t mutex; pthread_cond_t cond; int nready; } nready = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0 }; void *producer(void *arg) { for(; ;) { pthread_mutex_lock(&put.mutex); if (put.nput >= nitems) { pthread_mutex_unlock(&put.mutex); return 0; } buff[put.nput] = put.nval; put.nput++; put.nval++; pthread_mutex_unlock(&put.mutex); pthread_mutex_lock(&nready.mutex); if (nready.nready == 0) pthread_cond_signal(&nready.cond); nready.nready++; pthread_mutex_unlock(&nready.mutex); sleep(1); } } void *consumer(void *arg) { int i; for (i = 0; i < nitems; i++) { pthread_mutex_lock(&nready.mutex); while (nready.nready == 0) pthread_cond_wait(&nready.cond, &nready.mutex); nready.nready--; pthread_mutex_unlock(&nready.mutex); printf("%d %d:%d\\n",nready.nready,(int)arg,buff[i]); } } int main(int argc, const char **argv) { int i; pthread_t tid_producer[100], tid_consumer[1]; nitems = 1000000; for (i = 0; i < 100; i++) { pthread_create(&tid_producer[i], 0,producer, 0); } for (i = 0; i < 1; i++) { pthread_create(&tid_consumer[i], 0, consumer, (void *)i); } for (i = 0; i < 100; i++) { pthread_join(tid_producer[i], 0); } for (i = 0; i < 1; i++) { pthread_join(tid_consumer[i], 0); } return 0; }
1
#include <pthread.h> int countA; int countB; pthread_mutex_t mutex; } Counter; void* TF1(void*); void* TF2(void*); sem_t *b1, *b2, *print; Counter *c; int main(int argc, char **argv) { if (argc != 2) { return -1; } b1 = (sem_t *) malloc(sizeof(sem_t)); b2 = (sem_t *) malloc(sizeof(sem_t)); print = (sem_t *)malloc(sizeof(sem_t)); sem_init(b1, 0, 0); sem_init(b2, 0, 0); sem_init(print, 0, 1); c = (Counter *) malloc (sizeof(Counter)); c->countA = 0; c->countB = 0; pthread_mutex_init(&c->mutex, 0); int n = atoi(argv[1]); if(1 > 0) printf ("n is %d\\n", n); pthread_t th_1; pthread_t th_2; pthread_create(&th_1, 0, TF1, (void*) &n); pthread_create(&th_2, 0, TF2, (void*) &n); pthread_join(th_1, 0); pthread_join(th_2, 0); return 0; } void* TF1(void* num) { int *a; int n; a = (int*) num; n= *a; for(int i=0; i<n; i++) { sem_wait(print); printf("A1 "); sem_post(print); pthread_mutex_lock(&c->mutex); c->countA++; if(c->countA == 2) { sem_post(b1); sem_post(b1); c->countA = 0; } pthread_mutex_unlock(&c->mutex); sem_wait(b1); sem_wait(print); printf(" B1"); sem_post(print); pthread_mutex_lock(&c->mutex); c->countB++; if(c->countB == 2) { sem_post(b2); sem_post(b2); c->countB = 0; sem_wait(print); printf("\\n"); sem_post(print); } pthread_mutex_unlock(&c->mutex); sem_wait(b2); } pthread_exit(0); return(0); } void* TF2(void* num) { int *a; int n; a = (int*) num; n= *a; for(int i=0; i<n; i++) { sem_wait(print); printf("A2 "); sem_post(print); pthread_mutex_lock(&c->mutex); c->countA++; if(c->countA == 2) { sem_post(b1); sem_post(b1); c->countA = 0; } pthread_mutex_unlock(&c->mutex); sem_wait(b1); sem_wait(print); printf(" B2"); sem_post(print); pthread_mutex_lock(&c->mutex); c->countB++; if(c->countB == 2) { sem_post(b2); sem_post(b2); c->countB = 0; sem_wait(print); printf("\\n"); sem_post(print); } pthread_mutex_unlock(&c->mutex); sem_wait(b2); } pthread_exit(0); return(0); }
0
#include <pthread.h> { double *a; double *b; double sum; int veclen; } DOTDATA; DOTDATA dotstr; pthread_t callThd[8]; pthread_mutex_t mutexsum; void *dotprod(void *arg){ int i, start, end, len ; long offset; double mysum, *x, *y; offset = (long)arg; len = dotstr.veclen; start = offset*len; end = start + len; x = dotstr.a; y = dotstr.b; mysum = 0; for (i=start; i<end ; i++) { mysum += (x[i] * y[i]); } pthread_mutex_lock (&mutexsum); dotstr.sum += mysum; printf("Thread %ld did %d to %d: mysum=%f global sum=%f\\n",offset,start,end,mysum,dotstr.sum); pthread_mutex_unlock (&mutexsum); pthread_exit((void*) 0); } int main (int argc, char *argv[]){ long i; double *a, *b; void *status; pthread_attr_t attr; a = (double*) malloc (8*12500*sizeof(double)); b = (double*) malloc (8*12500*sizeof(double)); for (i=0; i<12500*8; i++) { a[i]=1; b[i]=a[i]; } dotstr.veclen = 12500; dotstr.a = a; dotstr.b = b; dotstr.sum=0; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0;i<8;i++) { pthread_create(&callThd[i], &attr, dotprod, (void *)i); } pthread_attr_destroy(&attr); for(i=0;i<8;i++) { pthread_join(callThd[i], &status); } printf ("Sum = %f \\n", dotstr.sum); free (a); free (b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
1
#include <pthread.h> pthread_cond_t full_cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t data_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t num_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_t pthread[10]; int num_thread = 0; int isFull = 0; void *accessR (void*); int main (int argc, char** argv) { int i; for(i = 0; i < 10; i++){ pthread_create(&pthread[i], 0, accessR, (void *)(intptr_t)i); } for(i = 0; i < 10; i++){ pthread_join(pthread[i], 0); } return 0; } void *accessR (void* a) { pthread_mutex_lock(&num_mutex); if(num_thread < 3){ if(isFull == 0){ num_thread++; } } else{ isFull = 1; } if(isFull == 1){ printf("Waiting for enter [%d]\\n", a); pthread_cond_wait(&full_cond, &num_mutex); num_thread++; } pthread_mutex_unlock(&num_mutex); printf("Starting... [%d]\\n", a); pthread_mutex_lock(&data_mutex); sleep(2); pthread_mutex_unlock(&data_mutex); printf("Ending... [%d]\\n", a); pthread_mutex_lock(&num_mutex); num_thread--; pthread_mutex_unlock(&num_mutex); if(num_thread == 0 && isFull == 1){ isFull == 0; pthread_cond_signal(&full_cond); pthread_cond_signal(&full_cond); pthread_cond_signal(&full_cond); } pthread_exit(0); }
0
#include <pthread.h> int readersInQueue = 0; int writersInQueue = 0; int readersInLibrary = 0; int writersInLibrary = 0; pthread_mutex_t varMutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t libraryMutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t entryCond = PTHREAD_COND_INITIALIZER; unsigned long uSecSleep = 2000000; perror_exit(char* errorStr) { perror(errorStr); exit(1); } void *readerF(void* arg) { while (1) { pthread_mutex_lock(&varMutex); readersInQueue++; printf("ReaderQ: %d WriterQ: %d [in: R:%d W:%d]\\n", readersInQueue, writersInQueue, readersInLibrary, writersInLibrary); pthread_mutex_unlock(&varMutex); pthread_mutex_lock(&libraryMutex); pthread_mutex_lock(&varMutex); while (writersInQueue || writersInLibrary) { pthread_mutex_unlock(&varMutex); pthread_cond_wait(&entryCond, &libraryMutex); pthread_mutex_lock(&varMutex); } readersInQueue--; readersInLibrary++; printf("ReaderQ: %d WriterQ: %d [in: R:%d W:%d]\\n", readersInQueue, writersInQueue, readersInLibrary, writersInLibrary); pthread_mutex_unlock(&varMutex); pthread_mutex_unlock(&libraryMutex); pthread_cond_broadcast(&entryCond); usleep(rand() % uSecSleep); pthread_mutex_lock(&libraryMutex); pthread_mutex_lock(&varMutex); readersInLibrary--; printf("ReaderQ: %d WriterQ: %d [in: R:%d W:%d]\\n", readersInQueue, writersInQueue, readersInLibrary, writersInLibrary); pthread_mutex_unlock(&varMutex); pthread_mutex_unlock(&libraryMutex); pthread_cond_broadcast(&entryCond); usleep(rand() % uSecSleep); } } void *writerF(void* arg){ while (1) { pthread_mutex_lock(&varMutex); writersInQueue++; printf("ReaderQ: %d WriterQ: %d [in: R:%d W:%d]\\n", readersInQueue, writersInQueue, readersInLibrary, writersInLibrary); pthread_mutex_unlock(&varMutex); pthread_mutex_lock(&libraryMutex); pthread_mutex_lock(&varMutex); while (readersInLibrary || writersInLibrary) { pthread_mutex_unlock(&varMutex); pthread_cond_wait(&entryCond, &libraryMutex); pthread_mutex_lock(&varMutex); } writersInQueue--; writersInLibrary++; printf("ReaderQ: %d WriterQ: %d [in: R:%d W:%d]\\n", readersInQueue, writersInQueue, readersInLibrary, writersInLibrary); pthread_mutex_unlock(&varMutex); pthread_mutex_unlock(&libraryMutex); usleep(rand() % uSecSleep); pthread_mutex_lock(&libraryMutex); pthread_mutex_lock(&varMutex); writersInLibrary--; printf("ReaderQ: %d WriterQ: %d [in: R:%d W:%d]\\n", readersInQueue, writersInQueue, readersInLibrary, writersInLibrary); pthread_mutex_unlock(&varMutex); pthread_mutex_unlock(&libraryMutex); pthread_cond_broadcast(&entryCond); usleep(rand() % uSecSleep); } } int main(int argc, char** argv) { printf("\\nReaders - writers 2nd problem (writers priority)\\n"); int readersCount, writersCount; if ((argv[1] == 0) || (argv[2]) == 0 ) { printf("Number of readers > "); if (scanf("%d", &readersCount) == EOF) perror_exit("scanf"); printf("Number of writers > "); if (scanf("%d", &writersCount) == EOF) perror_exit("scanf"); printf("Starting in 1 sec...\\n\\n"); sleep(1); } else { readersCount = atoi(argv[1]); writersCount = atoi(argv[2]); printf("Number of Readers = %d\\n", readersCount); printf("Number of Writers = %d\\n", writersCount); printf("Starting in 2 sec...\\n\\n"); sleep(2); } srand(time(0)); pthread_t *readerThread = calloc(readersCount, sizeof(pthread_t)); pthread_t *writerThread = calloc(writersCount, sizeof(pthread_t)); long i = 0; printf("ReaderQ: %d WriterQ: %d [in: R:%d W:%d]\\n", readersInQueue, writersInQueue, readersInLibrary, writersInLibrary); for (i = 0; i < readersCount; ++i) { if (pthread_create(&readerThread[i], 0, readerF, (void*)i)) { perror_exit("Error while creating reader thread (pthread_create)"); } } for (i = 0; i < writersCount; ++i) { if (pthread_create(&writerThread[i], 0, writerF, (void*)i)) { perror_exit("Error while creating writer thread (pthread_create)"); } } for (i = 0; i < readersCount; ++i) { if (pthread_join(readerThread[i], 0)) { perror_exit("Error while waiting for reader thread termination (pthread_join)"); } } free(readerThread); for (i = 0; i < writersCount; ++i) { if (pthread_join(writerThread[i], 0)) { perror_exit("Error while waiting for writer thread termination (pthread_join)"); } } free(writerThread); pthread_cond_destroy(&entryCond); pthread_mutex_destroy(&varMutex); pthread_mutex_destroy(&libraryMutex); }
1
#include <pthread.h> static pthread_key_t key; static pthread_once_t init_done = PTHREAD_ONCE_INIT; pthread_mutex_t env_mutex = PHTREAD_MUTEX_INITIALIZER; extern char **environ; static void thread_init(void) { pthread_key_create(&key, free); } char * getenv(const char *name) { int i, len; char *envbuf; pthread_once(&init_done, thread_init); pthread_mutex_lock(&env_mutex); envbuf = (char *)pthread_getspecific(key); if (envbuf == 0) { envbuf = malloc(4096); if (envbuf == 0) { pthread_mutex_unlock(&env_mutex); return(0); } pthread_setspecific(key, envbuf); } len = strlen(name); for (i = 0; environ[i] != 0; i++) { if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { strncpy(envbuf, environ[i][len + 1], 4096 - 1); pthread_mutex_unlock(&env_mutex); return(envbuf); } } pthread_mutex_unlock(&env_mutex); return(0); }
0
#include <pthread.h> static pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER; void *generator_function(void *arg); void *print_function(void *arg); long sum; long finished_producers; int main(void) { pthread_t generatorThread[5]; pthread_t printThread[1]; int i; srand(time(0)); sum = 0; for(i=0;i<5;i++){ pthread_create(&generatorThread[i], 0, &generator_function, 0); } pthread_create(&printThread[0], 0, &print_function, 0); for(i=0; i != 4; i++){ pthread_join(generatorThread[i], 0); } pthread_join(printThread[0], 0); return (0); } void *generator_function(void *arg) { long counter = 0; long sum_this_generator = 0; while (counter < 2000L) { pthread_mutex_lock(&mutex1); long tmpNumber = sum; long rnd_number = rand() % 10; printf("current sum of the generated number up to now is %ld going to add %ld to it.\\n", tmpNumber, rnd_number); sum = tmpNumber + rnd_number; counter++; sum_this_generator += rnd_number; pthread_mutex_unlock(&mutex1); usleep(1000); } printf("--+---+----+----------+---------+---+--+---+------+----\\n"); printf("The sum of produced items for this number generator at the end is: %ld \\n", sum_this_generator); printf("--+---+----+----------+---------+---+--+---+------+----\\n"); finished_producers++; while(1) { if(finished_producers == 5){ pthread_cond_signal(&condition_cond); } break; } return (0); } void *print_function(void *arg) { while(finished_producers !=5){ pthread_cond_wait(&condition_cond, &mutex1); } printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n"); printf("The value of counter at the end is: %ld \\n", sum); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n"); }
1
#include <pthread.h> pthread_mutex_t downloader_mutex, parser_mutex; unsigned long downloaders[MAX_THREADS]; unsigned long parsers[MAX_THREADS]; int downloader_threads = 0; int parser_threads = 0; char *fetch(char *link) { int fd = open(link, O_RDONLY); if (fd < 0) { fprintf(stderr, "failed to open file: %s", link); return 0; } int size = lseek(fd, 0, 2); assert(size >= 0); char *buf = Malloc(size+1); buf[size] = '\\0'; assert(buf); lseek(fd, 0, 0); char *pos = buf; while(pos < buf+size) { int rv = read(fd, pos, buf+size-pos); assert(rv > 0); pos += rv; } int i = 0; unsigned long current_id = (unsigned long) pthread_self(); pthread_mutex_lock(&downloader_mutex); for(i = 0; i < MAX_THREADS; ++i) { if(downloaders[i] == -1) { downloader_threads++; downloaders[i] = current_id; break; } else if(downloaders[i] == current_id) { break; } } pthread_mutex_unlock(&downloader_mutex); sleep(1); close(fd); return buf; } void edge(char *from, char *to) { int i = 0; unsigned long current_id = (unsigned long) pthread_self(); pthread_mutex_lock(&parser_mutex); for(i = 0; i < MAX_THREADS; ++i) { if(parsers[i] == -1) { parser_threads++; parsers[i] = current_id; break; } else if(parsers[i] == current_id) { break; } } pthread_mutex_unlock(&parser_mutex); sleep(1); } int main(int argc, char *argv[]) { pthread_mutex_init(&downloader_mutex, 0); pthread_mutex_init(&parser_mutex, 0); int i = 0; for(i = 0; i < MAX_THREADS; ++i) { downloaders[i] = -1; parsers[i] = -1; } int rc = crawl("/u/c/s/cs537-1/ta/tests/4a/tests/files/num_threads/pagea", 1, 1, 15, fetch, edge); assert(rc == 0); printf("\\ndownloader_threads : %d\\n", downloader_threads); check(downloader_threads == 1, "Expected to spawn 5 download threads\\n"); printf("\\nparser_threads : %d\\n", parser_threads); check(parser_threads == 1, "Expected to spawn 4 parser threads\\n"); return 0; }
0
#include <pthread.h> int x = 0; pthread_mutex_t x_mutex; pthread_cond_t x_cond; void *A (void *t) { int boba1, boba2; printf("A: Comecei\\n"); boba1=10000; boba2=-10000; while (boba2 < boba1) boba2++; printf("HELLO\\n"); pthread_mutex_lock(&x_mutex); x++; if (x==2) { printf("A: x = %d, vai sinalizar a condicao \\n", x); pthread_cond_broadcast(&x_cond); } pthread_mutex_unlock(&x_mutex); pthread_exit(0); } void *B (void *t) { printf("B: Comecei\\n"); pthread_mutex_lock(&x_mutex); if (x < 2) { printf("B: x= %d, vai se bloquear...\\n", x); pthread_cond_wait(&x_cond, &x_mutex); printf("B: sinal recebido e mutex realocado, x = %d\\n", x); } printf("BYE BYE\\n"); pthread_mutex_unlock(&x_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int i; pthread_t threads[4]; pthread_mutex_init(&x_mutex, 0); pthread_cond_init (&x_cond, 0); pthread_create(&threads[0], 0, B, 0); pthread_create(&threads[1], 0, B, 0); pthread_create(&threads[2], 0, A, 0); pthread_create(&threads[3], 0, A, 0); for (i = 0; i < 4; i++) { pthread_join(threads[i], 0); } printf ("\\nFIM\\n"); pthread_mutex_destroy(&x_mutex); pthread_cond_destroy(&x_cond); pthread_exit (0); }
1
#include <pthread.h> sem_t SEntrada; pthread_mutex_t C1; pthread_mutex_t C2; char est[24]; pthread_t th_auto[19]; int lugar; void automovil( void *id ); int entrada( void *id ,int puerta); void salida( void *id ,int salida,int lug); void tiempo(int time); void interfaz(); int main() { int i; for(i=0;i<24;i++) { est[i]=' '; } sem_init( &SEntrada,0,24); pthread_mutex_init(&C1,0); pthread_mutex_init(&C2,0); int res; for(i=0;i<19;i++){ pthread_create( &th_auto[i], 0,(void *) &automovil, (void *) i); } for(i=0;i<19;i++){ pthread_join(th_auto[i],(void *)&res); } return 0; } void automovil( void *id ){ int ent,tie,sal,i; while(1) { ent = rand()%3; tie = rand()%5; sal = rand()%3; int id2 = (int) id; int lug = entrada(id,ent); pthread_mutex_unlock(&C1); tiempo(tie); salida(id,sal,lug); pthread_mutex_unlock(&C1); } sleep(3); } int entrada( void *id ,int puerta) { int id2 = (int) id; char id3 = (char) (id2+48); sem_wait(&SEntrada); printf("%d Entro por la puerta: %d\\n",id2,puerta); pthread_mutex_lock(&C1); lugar = rand()%24; while(est[lugar] != ' ') { lugar = (lugar+1)%24; } est[lugar] = id3; interfaz(); pthread_mutex_unlock(&C1); return lugar; } void salida( void *id ,int salida,int lug) { int id2 = (int) id; char id3 = (char) (id2+48); printf("%d Salio por la puerta: %d\\n",id2,salida); pthread_mutex_lock(&C1); est[lug] = ' '; interfaz(); pthread_mutex_unlock(&C1); sem_post(&SEntrada); } void tiempo(int time){ sleep(time); } void interfaz() { ,est[0],est[1],est[2],est[3],est[4],est[5],est[6],est[7] ,est[8],est[9],est[10],est[11],est[12],est[13],est[14],est[15] ,est[16],est[17],est[18],est[19],est[20],est[21],est[22],est[23]); }
0
#include <pthread.h> struct ThumbQueue { struct ThumbQueue *next; char *uri; char *flavour; int id; }; struct { pthread_mutex_t mutex; struct ThumbQueue *first; struct ThumbQueue *last; sem_t work; pthread_t thread; int counter; } thumb_state; struct ThumbMemBuffer { void *data; int len; }; static struct ThumbMemBuffer load_icon(char *path) { struct archive *a; struct archive_entry *ae; struct meta_package_s mp; struct ThumbMemBuffer tmb; char *icon, icon_path[1024]; tmb.data = 0; if (meta_package_open(path, &mp) < 0) return tmb; if (!(icon = desktop_lookup(mp.df, "Icon", "", "Package Entry"))) goto error; snprintf(icon_path, 1024, "icons/%s", icon); if (!(a = archive_read_new())) goto error; archive_read_support_format_zip(a); if (archive_read_open_filename(a, path, 512) != ARCHIVE_OK) goto error; while (archive_read_next_header(a, &ae) == ARCHIVE_OK) if (!strcmp(icon_path, archive_entry_pathname(ae))) goto found; goto error; found: tmb.len = archive_entry_size(ae); tmb.data = malloc(tmb.len); archive_read_data(a, tmb.data, tmb.len); error: archive_read_free(a); desktop_free(mp.df); return tmb; } static char *locate_thumbnail_file(char *uri) { char *md5, *cache_dir, *thumb_dir; md5 = g_compute_checksum_for_data(G_CHECKSUM_MD5, (uint8_t *) uri, strlen(uri)); if (!(cache_dir = getenv("XDG_CACHE_HOME"))) { if (!getenv("HOME")) return 0; cache_dir = malloc(strlen(getenv("HOME")) + strlen("/.cache") + 1); sprintf(cache_dir, "%s/.cache", getenv("HOME")); } else cache_dir = strdup(cache_dir); thumb_dir = malloc(strlen(cache_dir) + strlen("/thumbnails/normal/") + strlen(md5) + strlen(".png") + 1); sprintf(thumb_dir, "%s/thumbnails/normal/%s.png", cache_dir, md5); free(cache_dir); free(md5); return thumb_dir; } static bool convert_image(struct ThumbMemBuffer buff, struct ThumbQueue *queue, char *url, enum ThumbError *errp, char **errstrp) { FILE *fp; char *tmpname, atime[63], *thumb_file, *thumb_file_write, *errmsg; struct utimbuf newtime; struct stat thumb, file; enum ThumbError err; bool error; Imlib_Image *img; error = 0; if (!(thumb_file = locate_thumbnail_file(queue->uri))) goto error; thumb_file_write = malloc(strlen(thumb_file) + 5); sprintf(thumb_file_write, "%s.prt", thumb_file); if (stat(thumb_file, &thumb) < 0) goto do_thumb; if (!stat(url, &file)) if (thumb.st_mtim.tv_sec >= file.st_mtim.tv_sec) goto exit; do_thumb: tmpname = tempnam(getenv("XDG_RUNTIME_DIR"), "thumb"); if (!(fp = fopen(tmpname, "w"))) { err = THUMB_ERROR_I_AM_A_TEAPOT; errmsg = "Unable to create temporary thumbnail"; goto error; } fwrite(buff.data, buff.len, 1, buff.data); fclose(fp); if (!(img = imlib_load_image_immediately(tmpname))) { fprintf(stderr, "imlib failed to open\\n"); err = THUMB_ERROR_BAD_DATA; errmsg = "File contained an invalid icon"; goto error; } imlib_image_attach_data_value("Thumb::URI", queue->uri, strlen(queue->uri), 0); sprintf(atime, "%lli", (long long int) file.st_mtim.tv_sec); imlib_image_attach_data_value("Thumb::MTime", atime, strlen(atime), 0); unlink(thumb_file_write); imlib_save_image(thumb_file_write); newtime.actime = file.st_atim.tv_sec; newtime.modtime = file.st_mtim.tv_sec; utime(thumb_file_write, &newtime); if (rename(thumb_file_write, thumb_file)) { err = THUMB_ERROR_SAVE_ERROR; errmsg = "Unable to rename thumbnail to final name"; goto error; } goto exit; error: unlink(thumb_file_write); *errp = err; *errstrp = errmsg; error = 1; exit: imlib_free_image(); unlink(tmpname); free(tmpname); free(thumb_file); free(thumb_file_write); return error; } static void create_thumbnail(struct ThumbQueue *queue) { char *path; struct ThumbMemBuffer buff; enum ThumbError err; char *errstr; if (strcmp(queue->flavour, "normal")) { err = THUMB_ERROR_BAD_TASTE; errstr = "Unsupported flavour"; goto error; } buff.data = 0; if (!(path = strstr(queue->uri, "file://"))) path = queue->uri; buff = load_icon(path); if (!buff.data) { err = THUMB_ERROR_BAD_DATA; errstr = "Package is invalid/didn't have an icon"; goto error; } if (!convert_image(buff, queue, path, &err, &errstr)) goto error; free(buff.data); comm_dbus_announce_ready(queue->id, queue->uri); goto exit; error: comm_dbus_announce_error(queue->id, queue->uri, err, errstr); exit: comm_dbus_announce_finished(queue->id); free(buff.data); return; } static void clear_entry(struct ThumbQueue *entry) { free(entry->uri); free(entry->flavour); free(entry); } void *thumb_worker(void *bah) { struct ThumbQueue *this; for (;;) { sem_wait(&thumb_state.work); do { pthread_mutex_lock(&thumb_state.mutex); this = thumb_state.first; if (this) thumb_state.first = this->next; pthread_mutex_unlock(&thumb_state.mutex); if (!this) continue; comm_dbus_announce_started(this->id); create_thumbnail(this); clear_entry(this); } while (this); } } int thumb_queue(const char *uri, const char *flavour) { struct ThumbQueue *new; new = malloc(sizeof(*new)); new->uri = strdup(uri); new->flavour = strdup(flavour); new->next = 0; pthread_mutex_lock(&thumb_state.mutex); thumb_state.last = new; new->id = thumb_state.counter++; pthread_mutex_unlock(&thumb_state.mutex); return new->id; } void thumb_queue_init() { pthread_mutex_init(&thumb_state.mutex, 0); sem_init(&thumb_state.work, 0, 0); thumb_state.first = 0; thumb_state.last = 0; thumb_state.counter = 0; pthread_create(&thumb_state.thread, 0, thumb_worker, 0); }
1
#include <pthread.h> void* handle_clnt(void *arg); void send_msg(char *msg, int len); void error_handling(char *msg); int clnt_cnt = 0; char message[1024]; int clnt_socks[256], level[7]; int max_cnt; int message_cnt=0; pthread_mutex_t mutx=PTHREAD_MUTEX_INITIALIZER; int main(int argc, char *argv[]) { int serv_sock,clnt_sock; struct sockaddr_in serv_adr, clnt_adr; int clnt_adr_sz; pthread_t t_id; if (argc != 2) { printf("Usag : %s<port> \\n", argv[0]); exit(1); } pthread_mutex_init(&mutx, 0); serv_sock = socket(PF_INET, SOCK_STREAM, 0); memset(&serv_adr, 0, sizeof(serv_adr)); serv_adr.sin_family = AF_INET; serv_adr.sin_addr.s_addr = htonl(INADDR_ANY); serv_adr.sin_port = htons(atoi(argv[1])); if (bind(serv_sock, (struct sockaddr*) &serv_adr, sizeof(serv_adr)) == -1) error_handling("bind() error"); if (listen(serv_sock, 10) == -1) error_handling("listen() error"); while (1) { clnt_adr_sz = sizeof(clnt_adr); clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_adr, &clnt_adr_sz); pthread_mutex_lock(&mutx); clnt_socks[clnt_cnt++] = clnt_sock; pthread_mutex_unlock(&mutx); pthread_create(&t_id, 0, handle_clnt, (void*)&clnt_sock); pthread_detach(t_id); printf("Connected client IP:%s \\n", inet_ntoa(clnt_adr.sin_addr)); if(clnt_cnt==4) { send_msg("start",5); } } close(serv_sock); return 0; } void * handle_clnt(void *arg) { int clnt_sock = *((int*)arg); int str_len = 0, i; int n=0; char cnt; for(i=0; i<7; i++) { level[i]=0; } max_cnt=-999; while((str_len=read(clnt_sock,message,sizeof(message)))!=0) { if(strstr(message,"l")) { n = message[1]-48; level[n]++; if(level[n]>max_cnt) max_cnt=level[n]; message_cnt++; if(message_cnt == 4) { cnt=max_cnt+48; message[0]=cnt; send_msg(message, 1); } } else if(strstr(message,"finish")) { } printf("clnt said %s",message); } pthread_mutex_lock(&mutx); for (i = 0; i<clnt_cnt; i++) { if (clnt_sock == clnt_socks[i]) { while (i++<clnt_cnt - 1) clnt_socks[i] = clnt_socks[i + 1]; break; } } clnt_cnt--; pthread_mutex_unlock(&mutx); close(clnt_sock); return 0; } void error_handling(char *message) { fputs(message, stderr); fputc('\\n', stderr); exit(1); } void send_msg(char *message, int len) { int i; pthread_mutex_lock(&mutx); for(i=0;i<clnt_cnt;i++) write(clnt_socks[i],message,len); pthread_mutex_unlock(&mutx); }
0
#include <pthread.h> int count; double values[10]; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; void push(double v) { pthread_mutex_lock(&m); values[count++] = v; pthread_mutex_unlock(&m); } double pop() { pthread_mutex_lock(&m); double v = values[--count]; pthread_mutex_unlock(&m); return v; } int is_empty() { pthread_mutex_lock(&m); int result= count == 0; pthread_mutex_unlock(&m); return result; } int count; pthread_mutex_t m; double *values; } stack_t; stack_t* stack_create(int capacity) { stack_t *result = malloc(sizeof(stack_t)); result->count = 0; result->values = malloc(sizeof(double) * capacity); pthread_mutex_init(&result->m, 0); return result; } void stack_destroy(stack_t *s) { free(s->values); pthread_mutex_destroy(&s->m); free(s); } void stack_push(stack_t *s, double v) { pthread_mutex_lock(&s->m); s->values[(s->count)++] = v; pthread_mutex_unlock(&s->m); } double stack_pop(stack_t *s) { pthread_mutex_lock(&s->m); double v = s->values[--(s->count)]; pthread_mutex_unlock(&s->m); return v; } int stack_is_empty(stack_t *s) { pthread_mutex_lock(&s->m); int result = s->count == 0; pthread_mutex_unlock(&s->m); return result; } int main() { stack_t *s1 = stack_create(10 ); stack_t *s2 = stack_create(10); stack_push(s1, 3.141); stack_push(s2, stack_pop(s1)); stack_destroy(s2); stack_destroy(s1); }
1
#include <pthread.h> static pthread_mutex_t owsl_openssl_user_mutex ; static size_t owsl_openssl_user_count ; static pthread_mutex_t * owsl_openssl_mutex_array = 0 ; static size_t owsl_openssl_mutex_size ; struct CRYPTO_dynlock_value { pthread_mutex_t mutex ; } ; int owsl_openssl_wrapper_initialize (void) { if (pthread_mutex_init (& owsl_openssl_user_mutex, 0)) { return -1 ; } owsl_openssl_user_count = 0 ; return 0 ; } int owsl_openssl_wrapper_terminate (void) { int return_code = 0 ; return_code |= pthread_mutex_destroy (& owsl_openssl_user_mutex) ; return return_code ; } static int owsl_openssl_prng_seed (void) { return 0 ; } static void owsl_openssl_locking_callback ( int action, int index, const char * file, int line ) { if (action & CRYPTO_LOCK) { pthread_mutex_lock (& owsl_openssl_mutex_array [index]) ; } else { pthread_mutex_unlock (& owsl_openssl_mutex_array [index]) ; } return ; } static unsigned long owsl_openssl_thread_id_callback (void) { return (unsigned long) pthread_self () ; } static struct CRYPTO_dynlock_value * owsl_openssl_dynlock_create_callback ( const char * file, int line ) { struct CRYPTO_dynlock_value * dynlock ; dynlock = malloc (sizeof (struct CRYPTO_dynlock_value)) ; if (dynlock == 0) { return 0 ; } pthread_mutex_init (& dynlock->mutex, 0) ; return dynlock ; } static void owsl_openssl_dynlock_destroy_callback ( struct CRYPTO_dynlock_value * dynlock, const char * file, int line ) { pthread_mutex_destroy (& dynlock->mutex) ; free (dynlock) ; return ; } static void owsl_openssl_dynlock_lock_callback ( int action, struct CRYPTO_dynlock_value * dynlock, const char * file, int line ) { if (action & CRYPTO_LOCK) { pthread_mutex_lock (& dynlock->mutex) ; } else { pthread_mutex_unlock (& dynlock->mutex) ; } } static int owsl_openssl_lock_initialize (void) { size_t mutex_index ; owsl_openssl_mutex_size = CRYPTO_num_locks () ; owsl_openssl_mutex_array = malloc (owsl_openssl_mutex_size * sizeof (pthread_mutex_t)) ; if (owsl_openssl_mutex_array == 0) { return -1 ; } for (mutex_index = 0 ; mutex_index < owsl_openssl_mutex_size ; mutex_index ++) { pthread_mutex_init (& owsl_openssl_mutex_array [mutex_index], 0) ; } CRYPTO_set_locking_callback (owsl_openssl_locking_callback) ; CRYPTO_set_dynlock_create_callback (owsl_openssl_dynlock_create_callback) ; CRYPTO_set_dynlock_destroy_callback (owsl_openssl_dynlock_destroy_callback) ; CRYPTO_set_dynlock_lock_callback (owsl_openssl_dynlock_lock_callback) ; return 0 ; } static int owsl_openssl_lock_terminate (void) { int return_code = 0 ; size_t mutex_index ; if (owsl_openssl_mutex_array == 0) { return -1 ; } CRYPTO_set_locking_callback (0) ; CRYPTO_set_dynlock_create_callback (0) ; CRYPTO_set_dynlock_lock_callback (0) ; CRYPTO_set_dynlock_destroy_callback (0) ; for (mutex_index = 0 ; mutex_index < owsl_openssl_mutex_size ; mutex_index ++) { pthread_mutex_destroy (& owsl_openssl_mutex_array [mutex_index]) ; } free (owsl_openssl_mutex_array) ; owsl_openssl_mutex_array = 0 ; return return_code ; } int owsl_openssl_initialize (void) { if (pthread_mutex_lock (& owsl_openssl_user_mutex)) { return -1 ; } if (owsl_openssl_user_count == 0) { SSL_library_init () ; if (owsl_openssl_prng_seed ()) { return -1 ; } CRYPTO_set_id_callback (owsl_openssl_thread_id_callback) ; if (owsl_openssl_lock_initialize ()) { return -1 ; } } owsl_openssl_user_count ++ ; if (pthread_mutex_unlock (& owsl_openssl_user_mutex)) { return -1 ; } return 0 ; } int owsl_openssl_terminate (void) { int return_code = 0 ; if (pthread_mutex_lock (& owsl_openssl_user_mutex)) { return -1 ; } owsl_openssl_user_count -- ; if (owsl_openssl_user_count == 0) { CRYPTO_set_id_callback (0) ; return_code |= owsl_openssl_lock_terminate () ; } if (pthread_mutex_unlock (& owsl_openssl_user_mutex)) { return -1 ; } return return_code ; }
0
#include <pthread.h> double h; double result; int N; double step; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; double exp(double x); double f(double x){ return x*x; } void *partialTrapezoid(void *inter){ double *interval = ((double *) inter); int i; double x_i; double a = interval[0]; double b = a + N-1; double h = (b-a)/(N-1); double temp = 0.0; temp = temp + f(a)+f(b); for(i = 1; i<(N-1); i++){ x_i = a + i*h; temp = temp+ 2*f(x_i); } pthread_mutex_lock(&mutex); result = result + h*0.5*temp; pthread_mutex_unlock(&mutex); } int main(int argc, char **argv){ int a,b, threads; int i; pthread_t *threads_tab; double *thread_args; a = atoi(argv[1]); b = atoi(argv[2]); threads = atoi(argv[3]); N = (b-a)/threads; threads_tab = (pthread_t *)malloc((threads)*sizeof(pthread_t)); thread_args = (double *)malloc(sizeof(double)*threads); pthread_mutex_init(&mutex, 0); for( i = 0; i<threads; i++){ thread_args[i]=i*N; pthread_create(&threads_tab[i], 0, partialTrapezoid, (void *) &thread_args[i]); } for(i=0; i<threads; i++) pthread_join(threads_tab[i], 0); result+=f(b); printf("El resultado final es %f\\n", result ); free(threads_tab); return 0; }
1
#include <pthread.h> static pthread_t buffer_dump_thread, read_log_thread; static char *key, *buf; static int cur_pos = 0, fd; static FILE *flog; static pthread_mutex_t buf_access; static void *buffer_dump(void *arg) { int t; pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &t); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &t); while(1) { pthread_mutex_lock(&buf_access); api_jobs_logs(key, buf); pthread_mutex_unlock(&buf_access); sleep(10); } } static void *read_log(void *arg) { int len, d, t; char str[1025]; pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &t); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &t); while((len = read(fd, str, 1024)) > 0) { str[len] = 0; if(flog != 0) { fwrite(str, len, 1, flog); } pthread_mutex_lock(&buf_access); if(3000 - cur_pos < len) { d = len - (3000 - cur_pos); memmove(buf, buf + d, 3000 - d); cur_pos -= d; } cur_pos += sprintf(buf + cur_pos, "%s", str); pthread_mutex_unlock(&buf_access); } if(flog != 0) { fclose(flog); flog = 0; } return 0; } int start_live_logger(const char *build_id, int read_fd) { pthread_attr_t attr; int res; res = pthread_attr_init(&attr); if(res != 0) { return -1; } pthread_mutex_init(&buf_access, 0); key = malloc(strlen(build_id) + strlen("abfworker::rpm-worker-") + 1); buf = malloc(3001); memset(buf, 0, 3001); cur_pos += sprintf(buf, "\\nStarting build...\\n"); sprintf(key, "abfworker::rpm-worker-%s", build_id); res = pthread_create(&buffer_dump_thread, &attr, &buffer_dump, 0); if(res != 0) { free(key); free(buf); pthread_mutex_destroy(&buf_access); pthread_attr_destroy(&attr); return -1; } flog = fopen("/tmp/script_output.log", "w"); fd = read_fd; res = pthread_create(&read_log_thread, &attr, &read_log, 0); if(res != 0) { free(key); free(buf); pthread_mutex_destroy(&buf_access); pthread_attr_destroy(&attr); pthread_cancel(buffer_dump_thread); return -1; } pthread_attr_destroy(&attr); return 0; } void stop_live_logger() { pthread_mutex_destroy(&buf_access); pthread_cancel(buffer_dump_thread); pthread_cancel(read_log_thread); pthread_join(buffer_dump_thread, 0); pthread_join(read_log_thread, 0); free(key); free(buf); if(flog != 0) { fclose(flog); } close(fd); }
0
#include <pthread.h> pthread_mutex_t mx, my; int x=2, y=2; void *thread1() { int a; pthread_mutex_lock(&mx); a = x; pthread_mutex_lock(&my); y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; pthread_mutex_unlock(&my); a = a + 1; pthread_mutex_lock(&my); y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; pthread_mutex_unlock(&my); x = x + x + a; pthread_mutex_unlock(&mx); assert(x!=47); return 0; } void *thread2() { pthread_mutex_lock(&mx); x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; pthread_mutex_unlock(&mx); return 0; } void *thread3() { pthread_mutex_lock(&my); y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; pthread_mutex_unlock(&my); y=2; return 0; } int main() { pthread_t t1, t2, t3; pthread_mutex_init(&mx, 0); pthread_mutex_init(&my, 0); pthread_create(&t1, 0, thread1, 0); pthread_create(&t2, 0, thread2, 0); pthread_create(&t3, 0, thread3, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); pthread_mutex_destroy(&mx); pthread_mutex_destroy(&my); return 0; }
1
#include <pthread.h> static int buffer[8]; static int n = 0; static pthread_mutex_t lock; static pthread_mutex_t mutex; pthread_cond_t fila = PTHREAD_COND_INITIALIZER; void produtor(void) { int i; for(i = 0; i < 64; i++) { if(n == 8) { pthread_cond_wait(&fila, &mutex); } pthread_mutex_lock(&lock); buffer[n] = rand() % 10; n++; pthread_cond_signal (&fila); pthread_mutex_unlock(&lock); sleep(1); } return; } void consumidor(void) { int i, t; for(i = 0; i < 64; i++) { if(n == 0) { pthread_cond_wait(&fila, &mutex); } pthread_mutex_lock(&lock); printf("%d[%d] consumido.\\n", buffer[0], i); for(t = 0; t < n -1; t++) { buffer[t] = buffer[t+1]; } n--; pthread_cond_signal (&fila); pthread_mutex_unlock(&lock); sleep(2); } return; } int main(void) { pthread_t threads[2]; pthread_create(&threads[0], 0, produtor, 0); pthread_create(&threads[1], 0, consumidor, 0); pthread_join(threads[0],0); pthread_join(threads[1],0); printf("final\\n"); return 0; }
0
#include <pthread.h> pthread_t cons[2]; pthread_t prod[2]; pthread_mutex_t buffer_mutex; int buffer[1000]; int prod_pos=0, cons_pos=0; void *produtor(void *arg) { int n; while(1) { n = (int)(drand48() * 1000.0); pthread_mutex_lock(&buffer_mutex); buffer[prod_pos] = n; prod_pos = (prod_pos+1) % 1000; pthread_mutex_unlock(&buffer_mutex); printf("Produzindo numero %d\\n", n); sleep((int)(drand48() * 4.0)); } } void *consumidor(void *arg) { int n; while(1) { pthread_mutex_lock(&buffer_mutex); n = buffer[cons_pos]; cons_pos = (cons_pos+1) % 1000; pthread_mutex_unlock(&buffer_mutex); printf("Consumindo numero %d\\n", n); sleep((int)(drand48() * 4.0)); } } int main(int argc, char **argv) { int i; srand48(time(0)); pthread_mutex_init(&buffer_mutex, 0); for(i=0; i<2; i++) { pthread_create(&(cons[i]), 0, consumidor, 0); } for(i=0; i<2; i++) { pthread_create(&(prod[i]), 0, produtor, 0); } for(i=0; i<2; i++) { pthread_join(cons[i], 0); } for(i=0; i<2; i++) { pthread_join(prod[i], 0); } return 0; }
1
#include <pthread.h> int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_lock=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t count_hit_threshold=PTHREAD_COND_INITIALIZER; void *inc_count(void *idp) { int i=0, save_state, save_type; int *my_id = idp; for (i=0; i<10; i++) { pthread_mutex_lock(&count_lock); count++; printf("inc_counter(): thread %d, count = %d, unlocking mutex\\n", *my_id, count); if (count == 12) { printf("inc_count(): Thread %d, count %d\\n", *my_id, count); pthread_cond_signal(&count_hit_threshold); } pthread_mutex_unlock(&count_lock); } return(0); } void *watch_count(void *idp) { int i=0, save_state, save_type; int *my_id = idp; printf("watch_count(): thread %d\\n", *my_id); pthread_mutex_lock(&count_lock); while (count < 12) { pthread_cond_wait(&count_hit_threshold, &count_lock); printf("watch_count(): thread %d, count %d\\n", *my_id, count); } pthread_mutex_unlock(&count_lock); return(0); } extern int main(void) { int i; pthread_t threads[3]; pthread_create(&threads[0], 0, inc_count, (void *)&thread_ids[0]); pthread_create(&threads[1], 0, inc_count, (void *)&thread_ids[1]); pthread_create(&threads[2], 0, watch_count, (void *)&thread_ids[2]); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } return 0; }
0
#include <pthread.h> void * enanitos(void *); void * blancanieves(void *); sem_t sillas; pthread_mutex_t comer = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t comiendo = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t puede_comer = PTHREAD_COND_INITIALIZER; void * enanitos(void * p){ int valor_sem; int id = (int)p; while(1){ printf("El enanito %d está en la mina\\n",id+1); sleep(20); sem_wait(&sillas); printf("El enanito %d esta sentado, esperando a Blancanieves...\\n",id+1); pthread_cond_wait(&puede_comer,&comiendo); sem_getvalue(&sillas,&valor_sem); printf("El enanito %d esta comiendo, semaforo %d\\n",id+1,valor_sem); sleep(10); sem_post(&sillas); printf("El enanito %d terminó de comer, semaforo %d\\n",id+1,valor_sem); pthread_mutex_unlock(&comiendo);} pthread_exit(0); } void * blancanieves(void * p){ int valor_sem; while (1) { sem_getvalue(&sillas, &valor_sem); if (valor_sem < 4) { pthread_cond_signal(&puede_comer); } else { pthread_mutex_lock(&comer); printf("Estoy de paseo por 15 segundos...\\n"); sleep(15); pthread_mutex_unlock(&comer); } } pthread_exit(0); } int main (int argc, char* argv[]) { sem_init(&sillas, 0, 4); pthread_t * enanos = (pthread_t *)malloc(sizeof(pthread_t)*7); pthread_t blanca; pthread_create(&blanca,0, blancanieves, (void *)1); for (int i = 0; i < 7 ; i++) { pthread_create(&enanos[i], 0, enanitos, (void *)i); } for (int j = 0; j < 7; j++) { pthread_join(enanos[j], 0); } sem_destroy(&sillas); pthread_mutex_destroy(&comer); pthread_cond_destroy(&puede_comer); free(enanos); return 0; }
1
#include <pthread.h> pthread_mutex_t shortTermSchedulerMutex; bool enableShortTermScheduler; sem_t processInReady_sem; void initializeshortTermScheduler() { pthread_mutex_init(&shortTermSchedulerMutex, 0); sem_init(&processInReady_sem, 1, 0); enableShortTermScheduler = 1; } void destroyshortTermScheduler() { pthread_mutex_destroy(&shortTermSchedulerMutex); sem_destroy(&processInReady_sem); } void shortTermScheduler_lock() { if (enableShortTermScheduler) { enableShortTermScheduler = 0; logInfo("El planificador de corto plazo fue bloqueado"); } else { logInfo("El planificador de corto plazo ya se encontraba bloqueado"); } } void shortTermScheduler_unlock() { if (!enableShortTermScheduler) { shortTermSchedulerMutex_unlock(); enableShortTermScheduler = 1; logInfo("El planificador de corto plazo fue desbloqueado"); } else { logInfo("El planificador de corto plazo ya se encontraba desbloqueado"); } } void shortTermSchedulerMutex_lock() { pthread_mutex_lock(&shortTermSchedulerMutex); } void shortTermSchedulerMutex_unlock() { pthread_mutex_unlock(&shortTermSchedulerMutex); } bool isEnableShortTermScheduler() { return enableShortTermScheduler; } void processInReady_wait() { sem_wait(&processInReady_sem); logInfo("Se decremento (wait) el recurso de 'Procesos en ready'"); } void processInReady_signal() { logInfo("Se incremento (signal) el recurso de 'Procesos en ready'"); sem_post(&processInReady_sem); }
0
#include <pthread.h> int chain; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t w = PTHREAD_COND_INITIALIZER; pthread_cond_t all = PTHREAD_COND_INITIALIZER; void *thread(void *arg) { chain -= 1; pthread_t tid; if (chain == 0) { pthread_mutex_lock(&m); printf("thread %d waiting\\n", (int)pthread_self()); pthread_cond_signal(&all); pthread_cond_wait(&w, &m); pthread_mutex_unlock(&m); printf("thread %d exit\\n", (int)pthread_self()); pthread_exit(0); } pthread_create(&tid, 0, thread, 0); pthread_mutex_lock(&m); printf("thread %d waiting\\n", (int)pthread_self()); pthread_cond_wait(&w, &m); pthread_mutex_unlock(&m); pthread_join(tid, 0); printf("thread %d exit\\n", (int)pthread_self()); pthread_exit(0); } void hand(int sig) { pthread_cond_broadcast(&w); } int main(int argc, char **argv) { sigset_t sigs; pthread_t tid; int if_wait = 0; struct sigaction action; sigfillset(&sigs); sigdelset(&sigs, SIGINT); action.sa_flags = 0; action.sa_mask = sigs; action.sa_handler = hand; sigaction(SIGINT, &action, 0); sigprocmask(SIG_SETMASK, &sigs, 0); chain = (int)strtol(argv[1], 0, 10); if (chain > 0) { if_wait = 1; pthread_create(&tid, 0, thread, 0); pthread_mutex_lock(&m); pthread_cond_wait(&all, &m); pthread_mutex_unlock(&m); printf("all threads created!\\n"); } sigsuspend(&sigs); if (if_wait) pthread_join(tid, 0); printf("All threads finished\\n"); return 0; }
1
#include <pthread.h> void* osl_mutex_create() { int32_t ret = 0; pthread_mutex_t *mt; pthread_mutexattr_t pma; mt = (pthread_mutex_t*)malloc( sizeof(pthread_mutex_t) ); if( mt ) { memset( mt, 0, sizeof(pthread_mutex_t) ); ret |= pthread_mutexattr_init( &pma ); ret |= pthread_mutexattr_settype( &pma, PTHREAD_MUTEX_ERRORCHECK ); ret |= pthread_mutex_init( mt, &pma ); ret |= pthread_mutexattr_destroy( &pma ); } return mt; } void osl_mutex_destroy( void* mutex ) { pthread_mutex_t *mt = (pthread_mutex_t *)mutex; pthread_mutex_destroy( mt ); free( mt ); } int32_t osl_mutex_lock( void* mutex, int32_t timeout ) { uint32_t start, now; if( timeout < 0 ) { return pthread_mutex_lock( (pthread_mutex_t *)mutex ); } else { now = start = osl_get_ms(); while( now < start + timeout && start <= now ) { if( pthread_mutex_trylock( (pthread_mutex_t *)mutex ) == 0 ) return 0; osl_usleep( 1000 ); } } return -1; } void osl_mutex_unlock( void* mutex ) { pthread_mutex_unlock( (pthread_mutex_t *)mutex ); }
0