text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> extern void thread_join_int(pthread_t tid, int *rval_pptr); extern int My_pthread_create(pthread_t *tidp, const pthread_attr_t *attr, void *(*start_rtn)(void *), void *arg); static pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; static pthread_t threads[4]; static void* thread_func (void* arg) { pthread_mutex_lock(&mutex); printf("\\n****** Begin Thread:thread id=0x%x ******\\n",pthread_self()); printf("arg is %d\\n",arg); printf("****** End Thread:thread id=0x%x ******\\n\\n",pthread_self()); pthread_mutex_unlock(&mutex); if(pthread_equal(pthread_self(),threads[2])) { int rval=0; thread_join_int(threads[3],&rval); } if(pthread_equal(pthread_self(),threads[1])) { int rval=0; thread_join_int(threads[0],&rval); } sleep(2); return arg; } void test_thread_join() { M_TRACE("--------- Begin test_thread_join() ---------\\n"); pthread_mutex_lock(&mutex); threads[0]=pthread_self(); for(int i=0;i<3;i++) My_pthread_create(threads+i+1,0,thread_func,i); pthread_mutex_unlock(&mutex); int values[3]; for(int i=0;i<2;i++) { thread_join_int(threads[2+i],values+i); } M_TRACE("--------- End test_thread_join() ---------\\n\\n"); }
1
#include <pthread.h> void *controlTask(void *arg) { struct timeval tp; struct timespec ts; pthread_mutex_t verrou; pthread_cond_t cond; pthread_cond_init(&cond, 0); pthread_mutex_init(&verrou, 0); float pitch_cmd = 0.0; float roll_cmd = 0.0; float angular_speed_cmd = 0.0; float vertical_speed_cmd = 0.0; initControl(); pthread_mutex_lock(&mutex_control); control_enable = CONTROL_ENABLED; control_state = STATE_MANUAL; seqNumber = 1; takeOffCalled = 0; landCalled = 0; moveCalled = 0; emergencyCalled = 0; calibHorCalled = 0; calibMagnCalled = 0; initNavDataCalled = 1; move_done = 0; pthread_mutex_unlock(&mutex_control); while(1) { gettimeofday(&tp, 0); ts.tv_sec = tp.tv_sec; ts.tv_nsec = tp.tv_usec * 1000; ts.tv_nsec += CONTROLTASK_PERIOD_MS * 1000000; ts.tv_sec += ts.tv_nsec / 1000000000L; ts.tv_nsec = ts.tv_nsec % 1000000000L; pthread_mutex_lock(&verrou); pthread_mutex_lock(&mutex_control); if(control_enable == CONTROL_ENABLED) { if(control_state == STATE_MISSION) { mission(x_cons, y_cons, z_cons, angle_cons, &pitch_cmd, &roll_cmd, &angular_speed_cmd, &vertical_speed_cmd); sendMovement(seqNumber, 1, pitch_cmd, roll_cmd, vertical_speed_cmd, angular_speed_cmd); checkEndOfMission(); } else if(control_state==STATE_MANUAL || move_done==1) { if(move_done==1) { sendMovement(seqNumber,0,0.0,0.0,0.0,0); move_done = 0; } else if(landCalled==1) { sendLand(seqNumber); landCalled = 0; } else if(takeOffCalled==1) { sendTakeOff(seqNumber); takeOffCalled = 0; } else if(initNavDataCalled==1) { sendNavDataInit(seqNumber); initNavDataCalled = 0; } else if(moveCalled==1) { sendMovement(seqNumber, 1, pitch_move, roll_move, vertical_speed_move, angular_speed_move); move_done = 1; moveCalled = 0; } else if(emergencyCalled==1) { sendEmergency(seqNumber); emergencyCalled = 0; } else if(calibHorCalled==1) { sendCalibHPlan(seqNumber); calibHorCalled = 0; } else if(calibMagnCalled==1) { sendCalibMagn(seqNumber); calibMagnCalled = 0; } else { sendResetWatchdog(seqNumber); } } seqNumber++; } pthread_mutex_unlock(&mutex_control); pthread_cond_timedwait(&cond, &verrou, &ts); pthread_mutex_unlock(&verrou); } } int executeMission(float x_obj, float y_obj, float z_obj, float angle_obj) { if(!canStartMission()) { printf("controlTask : can't start mission\\n"); return -1; } printf("controlTask : executeMission called and running\\n"); pthread_mutex_lock(&mutex_control); x_cons = x_obj; y_cons = y_obj; z_cons = z_obj; angle_cons = angle_obj; control_state = STATE_MISSION; pthread_mutex_unlock(&mutex_control); return 0; } void executeManual() { printf("controlTask : executeManual called\\n"); pthread_mutex_lock(&mutex_control); takeOffCalled = 0; landCalled = 0; moveCalled = 0; emergencyCalled = 0; calibHorCalled = 0; calibMagnCalled = 0; move_done = 1; control_state = STATE_MANUAL; pthread_mutex_unlock(&mutex_control); } void enableControl(int enable) { printf("controlTask : enableControl called with enable=%d\\n",enable); pthread_mutex_lock(&mutex_control); if(enable==CONTROL_ENABLED || enable==CONTROL_DISABLED) { control_enable = enable; } control_state = STATE_MANUAL; takeOffCalled = 0; landCalled = 0; moveCalled = 0; emergencyCalled = 0; calibHorCalled = 0; calibMagnCalled = 0; initNavDataCalled = 0; move_done = 0; pthread_mutex_unlock(&mutex_control); } void initNavData() { printf("controlTask : initNavData called\\n"); pthread_mutex_lock(&mutex_control); initNavDataCalled = 1; pthread_mutex_unlock(&mutex_control); } void takeOff() { printf("controlTask : takeOff called\\n"); pthread_mutex_lock(&mutex_control); takeOffCalled = 1; pthread_mutex_unlock(&mutex_control); } void land() { printf("controlTask : land called\\n"); pthread_mutex_lock(&mutex_control); landCalled = 1; pthread_mutex_unlock(&mutex_control); } void move(float pitch, float roll, float angular_speed, float vertical_speed) { printf("controlTask : move called\\n"); pthread_mutex_lock(&mutex_control); pitch_move = pitch; roll_move = roll; angular_speed_move = angular_speed; vertical_speed_move = vertical_speed; moveCalled = 1; pthread_mutex_unlock(&mutex_control); } void calibHor() { printf("controlTask : calibHor called\\n"); pthread_mutex_lock(&mutex_control); calibHorCalled = 1; pthread_mutex_unlock(&mutex_control); } void calibMagn() { printf("controlTask : calibMagn called\\n"); pthread_mutex_lock(&mutex_control); calibMagnCalled = 1; pthread_mutex_unlock(&mutex_control); } void emergency() { printf("controlTask : emergency called\\n"); pthread_mutex_lock(&mutex_control); emergencyCalled = 1; pthread_mutex_unlock(&mutex_control); } void checkEndOfMission() { if( fabs(x_cons-getX()) < PRECISION_X && fabs(y_cons-getY()) < PRECISION_Y && fabs(z_cons-getZ()) < PRECISION_Z && fabs(diff_angle(angle_cons, getAngle())) < PRECISION_ANGLE ) { move_done = 1; pthread_mutex_unlock(&mutex_control); executeManual(); pthread_mutex_lock(&mutex_control); sendFrame(MISSION_FRAME, 0, 0, 0, MISSION_FINISHED); } }
0
#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; } pthread_t threads[ 3 ]; pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; pthread_t ch; void prepare( void ) { threads[ 0 ] = pthread_self(); } void parent( void ) { threads[ 1 ] = pthread_self(); } void child( void ) { threads[ 2 ] = pthread_self(); } void * threaded( void * arg ) { int ret, status; pid_t child, ctl; ret = pthread_mutex_lock( &mtx ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to lock mutex" ); } ret = pthread_mutex_unlock( &mtx ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to unlock mutex" ); } child = fork(); if ( child == ( pid_t ) - 1 ) { UNRESOLVED( errno, "Failed to fork" ); } if ( child == ( pid_t ) 0 ) { if ( !pthread_equal( ch, threads[ 0 ] ) ) { FAILED( "prepare handler was not called in the thread s context" ); } if ( !pthread_equal( pthread_self(), threads[ 2 ] ) ) { FAILED( "child handler was not called in the thread s context" ); } exit( PTS_PASS ); } if ( !pthread_equal( ch, threads[ 0 ] ) ) { FAILED( "prepare handler was not called in the thread s context" ); } if ( !pthread_equal( pthread_self(), threads[ 1 ] ) ) { FAILED( "parent handler was not called in the thread s context" ); } ctl = waitpid( child, &status, 0 ); if ( ctl != child ) { UNRESOLVED( errno, "Waitpid returned the wrong PID" ); } if ( ( !WIFEXITED( status ) ) || ( WEXITSTATUS( status ) != PTS_PASS ) ) { FAILED( "Child exited abnormally" ); } return 0; } int main( int argc, char * argv[] ) { int ret; output_init(); ret = pthread_mutex_lock( &mtx ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to lock mutex" ); } ret = pthread_create( &ch, 0, threaded, 0 ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to create a thread" ); } ret = pthread_atfork( prepare, parent, child ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to register the atfork handlers" ); } ret = pthread_mutex_unlock( &mtx ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to unlock mutex" ); } ret = pthread_join( ch, 0 ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to join the thread" ); } output( "Test passed\\n" ); PASSED; }
1
#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); }
0
#include <pthread.h> int size; int numWorkers; int stripSize; int array[2000]; int sum=0; pthread_mutex_t lock; void * worker (void * ptr); double timeval_diff(struct timeval *a, struct timeval *b); int main(int argc, char* argv[]){ struct timeval t_ini, t_fin; double secs; gettimeofday(&t_ini, 0); int i, ids[8]; pthread_attr_t attr; pthread_t workers[8]; pthread_attr_init(&attr); pthread_mutex_init(&lock,0); size = atoi(argv[1]); size = (size < 2000 ? size : 2000); numWorkers = atoi(argv[2]); numWorkers = (numWorkers < 8 ? numWorkers : 8); stripSize = size / numWorkers; for (i = 0; i < size; i++) array[ i ] = i+1; for (i = 0; i < numWorkers; i++) { ids[i] = i; pthread_create(&workers[i], &attr, worker, &ids[i]); } for (i = 0; i < numWorkers; i++) pthread_join(workers[i], 0); gettimeofday(&t_fin, 0); secs = timeval_diff(&t_fin, &t_ini); printf("El resultado es: %d. \\n",sum); printf("%.16g milliseconds\\n", secs * 1000.0); return 0; } void * worker (void *arg) { int *ptr_id = (int*) arg; int id = *ptr_id; int local_sum, i, first, last; first = id*stripSize; last = first + stripSize - 1; printf("Primer bloque %d ,%d \\n",first,id); printf("ultimo bloque %d ,%d \\n",last,id); local_sum = 0; for (i = first; i <= last; i++) local_sum += array[i]; pthread_mutex_lock(&lock); sum += local_sum; pthread_mutex_unlock(&lock); pthread_exit (0); } double timeval_diff(struct timeval *a, struct timeval *b) { return (double)(a->tv_sec + (double)a->tv_usec/1000000) - (double)(b->tv_sec + (double)b->tv_usec/1000000); }
1
#include <pthread.h> static pthread_cond_t cond; static pthread_mutex_t mutex; static pthread_t reader; static int fd; static long the_great_array[256]; static unsigned char * buffer; static int buf_size = -1; volatile static short reader_in_mutex = 0; volatile static short main_in_mutex = 0; void * reader_func(void * arg) { while(1) { buffer = malloc(SIZE_OF_SORTED_PACK); if(buffer == 0) errhand("MALLOC!"); buf_size = read(fd,buffer,sizeof(char) * SIZE_OF_SORTED_PACK); if(buf_size < 0) errhand("read error"); pthread_mutex_lock(&mutex); reader_in_mutex = 1; if(main_in_mutex) { pthread_cond_signal(&cond); } pthread_cond_wait(&cond,&mutex); reader_in_mutex = 0; pthread_cond_signal(&cond); pthread_cond_wait(&cond,&mutex); pthread_mutex_unlock(&mutex); if(buf_size <= 0) break; } return 0; } int main(int argc, char ** argv) { int i = 0; unsigned char c; unsigned char * tmp_to_write; unsigned char * my_buffer = 0; int my_size = 0; if(argc <= 1) errhand("arguments!"); for(i = 0; i < 256; ++i) { the_great_array[i] = 0; } fd = open(argv[1],O_RDWR); if(fd == -1) errhand("file!"); pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond, 0); if(pthread_create(&reader,0,reader_func,0)) errhand("thread!"); while(1) { pthread_mutex_lock(&mutex); main_in_mutex = 1; if(!reader_in_mutex) { pthread_cond_wait(&cond,&mutex); } my_buffer = buffer; my_size = buf_size; pthread_cond_signal(&cond); pthread_cond_wait(&cond,&mutex); main_in_mutex = 0; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); if(my_size <= 0) my_size = 0; for(i = 0; i < my_size; ++i) { ++the_great_array[my_buffer[i]]; } free(my_buffer); if(my_size == 0) break; } pthread_join(reader,0); lseek(fd,0,0); for(c = 0; c < 255; ++c) { tmp_to_write = malloc(the_great_array[c]); for(i = 0; i < the_great_array[c]; ++i) { tmp_to_write[i] = c; } write(fd,tmp_to_write,the_great_array[c]); free(tmp_to_write); } pthread_cond_destroy(&cond); pthread_mutex_destroy(&mutex); close(fd); return 0; }
0
#include <pthread.h> struct RawMonitor { pthread_mutex_t mutex; pthread_cond_t cv; }; struct RawMonitor *Create_RawMonitor(){ int err = 0; struct RawMonitor *monitor = malloc(sizeof(struct RawMonitor)); pthread_condattr_t cv_attr; pthread_mutexattr_t mx_attr; err = pthread_condattr_init(&cv_attr); assert(err==0); err = pthread_mutexattr_init(&mx_attr); assert(err==0); err = pthread_cond_init(&(monitor->cv), &cv_attr); assert(err==0); err = pthread_mutex_init(&(monitor->mutex), &mx_attr); assert(err==0); err = pthread_condattr_destroy(&cv_attr); assert(err==0); err = pthread_mutexattr_destroy(&mx_attr); assert(err==0); return monitor; } void Destroy_RawMonitor(struct RawMonitor *monitor){ int err; err = pthread_cond_destroy(&(monitor->cv)); assert(err==0); err = pthread_mutex_destroy(&(monitor->mutex)); assert(err==0); free(monitor); } void Lock_RawMonitor(struct RawMonitor *monitor){ pthread_mutex_lock(&(monitor->mutex)); } void Unlock_RawMonitor(struct RawMonitor *monitor){ pthread_mutex_unlock(&(monitor->mutex)); } void Wait_RawMonitor(struct RawMonitor *monitor){ int err = pthread_cond_wait(&(monitor->cv), &(monitor->mutex)); assert(err==0); } void Notify_RawMonitor(struct RawMonitor *monitor){ int err = pthread_cond_signal(&(monitor->cv)); assert(err==0); } void NotifyAll_RawMonitor(struct RawMonitor *monitor){ int err = pthread_cond_broadcast(&(monitor->cv)); assert(err==0); }
1
#include <pthread.h> char* name; long balance; pthread_mutex_t mutex; } Account; Account* accounts[4]; Account* make_account(char* name, long balance) { Account* acc = malloc(sizeof(Account)); acc->name = strdup(name); acc->balance = balance; pthread_mutex_init(&acc->mutex,0); return acc; } void free_account(Account* acc) { free(acc->name); free(acc); } int transfer1(Account* aa, Account* bb, long amount) { pthread_mutex_lock(&(aa->mutex)); if (aa->balance < amount) { return -1; } aa->balance -= amount; pthread_mutex_unlock(&(aa->mutex)); pthread_mutex_lock(&(bb->mutex)); bb->balance += amount; pthread_mutex_unlock(&(bb->mutex)); return 0; } void lock_both(pthread_mutex_t* aa, pthread_mutex_t* bb) { if(aa < bb) { pthread_mutex_lock(aa); pthread_mutex_lock(bb); } else { pthread_mutex_lock(bb); pthread_mutex_lock(aa); } } int transfer(Account* aa, Account* bb, long amount) { lock_both(&(aa->mutex),&(bb->mutex)); if (aa->balance < amount) { return -1; } aa->balance -= amount; bb->balance += amount; pthread_mutex_unlock(&(aa->mutex)); pthread_mutex_unlock(&(bb->mutex)); return 0; } void* test_thread(void* seed_ptr) { unsigned int seed = *((unsigned int*) seed_ptr); free(seed_ptr); for (int kk = 0; kk < 10000; ++kk) { int ii = rand_r(&seed) % 4; int jj = rand_r(&seed) % 4; int aa = 1 + rand_r(&seed) % 100; if (ii == jj) { continue; } transfer(accounts[ii], accounts[jj], aa); } return 0; } int main(int _ac, char* _av[]) { pthread_t threads[10]; accounts[0] = make_account("Alice", 100000); accounts[1] = make_account("Bob", 100000); accounts[2] = make_account("Carol", 100000); accounts[3] = make_account("Dave", 100000); for (int ii = 0; ii < 10; ++ii) { unsigned int* seed = malloc(sizeof(unsigned int)); *seed = ii + getpid(); pthread_create(&(threads[ii]), 0, test_thread, seed); } for (int ii = 0; ii < 10; ++ii) { pthread_join(threads[ii], 0); } long sum = 0; for (int ii = 0; ii < 4; ++ii) { sum += accounts[ii]->balance; printf("%s:\\t%ld\\n", accounts[ii]->name, accounts[ii]->balance); free_account(accounts[ii]); } printf("\\nSum:\\t%ld\\n", sum); return 0; }
0
#include <pthread.h> void search_by_thread( void* ptr); { char* start_ptr; char* end_ptr; int slice_id; } slice_data; { char* start_ptr; char* end_ptr; int thread_id; int num_slices; int slice_size; char match_str[15]; char* array_address; slice_data* slice_struct_address; } thread_data; int slice_counter = 0; pthread_mutex_t mutex; pthread_mutex_t mutex2; int main(int argc, char* argv[]) { FILE* fRead; char line[15]; char search_str[15]; char* array_ptr; char* temp_ptr; int i = 0; int j = 0; int fchar; int num_inputs = 0; int num_threads; int num_slices; int slice_size = 0; char file_name[] = "fartico_aniketsh_input_partB.txt"; char alt_file[128]; printf("\\n(fartico_aniketsh_input_partB.txt)\\n"); printf("ENTER ALT FILENAME OR (ENTER TO RUN): "); gets(alt_file); if(strcmp(alt_file, "") != 0) { strcpy(file_name, alt_file); } fRead = fopen(file_name, "r"); if(fRead == 0) { perror("FILE OPEN FAILED\\n"); exit(1); } while(EOF != (fchar = fgetc(fRead))) {if ( fchar == '\\n'){++num_inputs;}} if ( fchar != '\\n' ){++num_inputs;} fclose(fRead); if ( num_inputs > 4 ) { num_inputs = num_inputs -3; } fRead = fopen(file_name, "r"); if(fRead == 0) { perror("FILE OPEN FAILED\\n"); exit(1); } fgets(line, sizeof(line), fRead); num_threads = atoi(line); fgets(line, sizeof(line), fRead); num_slices = atoi(line); fgets(search_str, sizeof(search_str), fRead); array_ptr = malloc(num_inputs * sizeof(line)); memset(array_ptr, '\\0', num_inputs * sizeof(line)); if(array_ptr == 0) { perror("Memory Allocation Failed\\n"); exit(1); } temp_ptr = array_ptr; slice_size = num_inputs / num_slices; if( num_inputs%num_slices != 0 ){slice_size = slice_size + 1;} while(fgets(line, sizeof(line), fRead)) { strcpy(&temp_ptr[i*15], line); i++; } printf("\\n"); pthread_t thread_array[num_threads]; thread_data data_array[num_threads]; slice_data slice_array[num_slices]; int k; for( k = 0; k < num_threads; ++k) { data_array[k].start_ptr = &array_ptr[k * slice_size * 15]; data_array[k].end_ptr = &array_ptr[(k+1) * slice_size * 15]; data_array[k].thread_id = k; strcpy(data_array[k].match_str, search_str); data_array[k].array_address = array_ptr; data_array[k].slice_struct_address = slice_array; data_array[k].num_slices = num_slices; data_array[k].slice_size = slice_size; } for ( k = 0; k < num_slices; ++k) { slice_array[k].start_ptr = &array_ptr[k * slice_size * 15]; slice_array[k].end_ptr = &array_ptr[(k+1) * slice_size * 15]; slice_array[k].slice_id = k; } pthread_mutex_init(&mutex, 0); pthread_mutex_init(&mutex2, 0); for( k = 0; k < num_threads; ++k) { pthread_create(&thread_array[k], 0, (void *) & search_by_thread, (void *) &data_array[k]); } for( k =0; k < num_threads; ++k) { pthread_join(thread_array[k], 0); } pthread_mutex_destroy(&mutex); printf("\\n"); return 0; } void search_by_thread( void* ptr) { thread_data* data; data = (thread_data *) ptr; int temp_slice; char* temp_ptr; int i=0; int j; int position_i = -1; int slice_i = -1; char found_i[] = "no"; while(1) { pthread_mutex_lock(&mutex2); if ( slice_counter < data->num_slices) { temp_slice = slice_counter; slice_counter = slice_counter + 1; } else {temp_slice = -1;} pthread_mutex_unlock(&mutex2); if (temp_slice == -1){break;} j =0; temp_ptr = data->slice_struct_address[temp_slice].start_ptr; while( &temp_ptr[j * 15] < data->slice_struct_address[temp_slice].end_ptr) { if (strcmp(&temp_ptr[j*15], data->match_str) == 0) { position_i = (data->slice_struct_address[temp_slice].slice_id *data->slice_size) + j; slice_i = temp_slice; strcpy(found_i, "yes"); } j = j + 1; } i++; usleep(1); } pthread_mutex_lock(&mutex); printf("thread %d, found %s, slice %d, position %d\\n", data->thread_id, found_i, slice_i, position_i); pthread_mutex_unlock(&mutex); pthread_exit(0); }
1
#include <pthread.h> struct queue *create_queue(int size) { struct queue *q = (struct queue *) malloc(sizeof(struct queue)); q->tasks = (struct task_desc **) malloc(sizeof(struct task_desc) * size); q->capacity = size; q->front = 0; q->rear = 0; pthread_mutex_init(&q->lock, 0); sem_init(&q->task_sem, 0, 0); sem_init(&q->spaces_sem, 0, size); return q; } void dispose_queue(struct queue *q) { free(q->tasks); pthread_mutex_destroy(&q->lock); sem_destroy(&q->task_sem); sem_destroy(&q->spaces_sem); free(q); } void enqueue(struct task_desc *task, struct queue *q) { sem_wait(&q->spaces_sem); pthread_mutex_lock(&q->lock); q->tasks[(++q->rear) % (q->capacity)] = task; pthread_mutex_unlock(&q->lock); sem_post(&q->task_sem); } struct task_desc *dequeue(struct queue *q) { struct task_desc *task; sem_wait(&q->task_sem); pthread_mutex_lock(&q->lock); task = q->tasks[(++q->front) % q->capacity]; pthread_mutex_unlock(&q->lock); sem_post(&q->spaces_sem); return task; }
0
#include <pthread.h> static pthread_mutex_t stdout_lock; sem_t male_avail; sem_t female_avail; pthread_mutex_t mutex; int mate_pending; int *male_queue, *female_queue; int male_position, female_position, male_head, female_head; static struct timeval time0; double elapsed_time() { struct timeval tv; gettimeofday(&tv, 0); return (tv.tv_sec - time0.tv_sec + (tv.tv_usec - time0.tv_usec) / 1.e6 ); } void process_whale(int is_male, int id) { int num_males, num_females; pthread_mutex_lock(&mutex); if (is_male) { male_queue[male_position++] = id; sem_post(&male_avail); } else { female_queue[female_position++] = id; sem_post(&female_avail); } sem_getvalue(&male_avail, &num_males); sem_getvalue(&female_avail, &num_females); pthread_mutex_unlock(&mutex); int this_sex = (is_male) ? num_males : num_females; int opposite_sex = (is_male) ? num_females : num_males; if (opposite_sex) { if (!mate_pending) { pthread_mutex_lock(&mutex); mate_pending++; pthread_mutex_lock(&stdout_lock); printf("(t=%f) %d: %s\\n", elapsed_time(), male_queue[male_head], "Found Mate"); fflush(stdout); pthread_mutex_unlock(&stdout_lock); pthread_mutex_lock(&stdout_lock); printf("(t=%f) %d: %s\\n", elapsed_time(), female_queue[female_head], "Found Mate"); fflush(stdout); pthread_mutex_unlock(&stdout_lock); pthread_mutex_unlock(&mutex); } if (this_sex > 1) { while (mate_pending) { pthread_mutex_lock(&mutex); pthread_mutex_lock(&stdout_lock); printf("(t=%f) %d: %s\\n", elapsed_time(), id, "Became MatchMaker"); fflush(stdout); pthread_mutex_unlock(&stdout_lock); sem_wait(&male_avail); sem_wait(&female_avail); pthread_mutex_lock(&stdout_lock); printf("(t=%f) %d: %s\\n", elapsed_time(), male_queue[male_head], "Mated"); fflush(stdout); pthread_mutex_unlock(&stdout_lock); pthread_mutex_lock(&stdout_lock); printf("(t=%f) %d: %s\\n", elapsed_time(), female_queue[female_head], "Mated"); fflush(stdout); pthread_mutex_unlock(&stdout_lock); mate_pending--; male_head++; female_head++; pthread_mutex_unlock(&mutex); } pthread_mutex_lock(&mutex); sem_getvalue(&male_avail, &num_males); sem_getvalue(&female_avail, &num_females); pthread_mutex_unlock(&mutex); } } } void create_male(int id) { pthread_mutex_lock(&stdout_lock); printf("(t=%f) %d: %s\\n", elapsed_time(), id, "Male Created"); fflush(stdout); pthread_mutex_unlock(&stdout_lock); process_whale(1, id); } void create_female(int id) { pthread_mutex_lock(&stdout_lock); printf("(t=%f) %d: %s\\n", elapsed_time(), id, "Female Created"); fflush(stdout); pthread_mutex_unlock(&stdout_lock); process_whale(0, id); } void *create_whale(void* arg) { int id = *((int *) arg); if (rand() & 1) { create_male(id); } else { create_female(id); } pthread_exit(0); } void whale_sleep(int wait_time_ms) { usleep(wait_time_ms * 1000); } void usage(char *arg0) { fprintf(stderr, "Usage: %s num_whales wait_time\\n" "\\tnum_whales - the total number of whales to create\\n" "\\twait_time - the amount of time to wait before creating another whale (seconds)\\n", arg0); exit(-1); } int main(int argc, char *argv[]) { if (argc != 3) { usage(argv[0]); } pthread_mutex_init(&stdout_lock, 0); pthread_mutex_init(&mutex, 0); struct timeval tv; gettimeofday(&tv, 0); srand(tv.tv_usec); gettimeofday(&time0, 0); int num_whales = atoi(argv[1]); int wait_time_ms = atof(argv[2]) * 1000; male_queue = malloc(num_whales*sizeof(int)); female_queue = malloc(num_whales*sizeof(int)); male_position = female_position = male_head = female_head = 0; mate_pending = 0; sem_init(&male_avail, 0, 0); sem_init(&female_avail, 0, 0); pthread_attr_t thread_attr; pthread_attr_init(&thread_attr); pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED); for (int whale = 0; whale < num_whales; whale++) { whale_sleep(wait_time_ms); pthread_t whale_thread_id; pthread_create(&whale_thread_id, &thread_attr, create_whale, (void *) &whale); } whale_sleep(wait_time_ms * 10.0); free(male_queue); free(female_queue); pthread_mutex_destroy(&mutex); pthread_mutex_destroy(&stdout_lock); }
1
#include <pthread.h> pthread_t t1, t2, t3; pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER; pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER; pthread_cond_t cond3 = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex3 = PTHREAD_MUTEX_INITIALIZER; void *thread1_func(void *p) { int i = 0; for (i = 0; i < 10; ++i) { pthread_mutex_lock(&mutex1); pthread_cond_wait(&cond1, &mutex1); printf("thread 1 id = %d\\n", pthread_self()); pthread_mutex_lock(&mutex2); pthread_cond_signal(&cond2); pthread_mutex_unlock(&mutex2); pthread_mutex_unlock(&mutex1); } } void *thread2_func(void *p) { int i = 0; for (i = 0; i < 10; ++i) { pthread_mutex_lock(&mutex2); pthread_cond_wait(&cond2, &mutex2); printf("thread 2 id = %d\\n", pthread_self()); pthread_mutex_lock(&mutex3); pthread_cond_signal(&cond3); pthread_mutex_unlock(&mutex3); pthread_mutex_unlock(&mutex2); } } void *thread3_func(void *p) { int i = 0; for (i = 0; i < 10; ++i) { pthread_mutex_lock(&mutex3); pthread_cond_wait(&cond3, &mutex3); printf("thread 3 id = %d\\n", pthread_self()); pthread_mutex_lock(&mutex1); pthread_cond_signal(&cond1); pthread_mutex_unlock(&mutex1); pthread_mutex_unlock(&mutex3); } } int main(int argc, char *argv[]) { pthread_create(&t1, 0, thread1_func, 0); pthread_create(&t2, 0, thread2_func, 0); pthread_create(&t3, 0, thread3_func, 0); printf("please begin this program: "); getchar(); pthread_mutex_lock(&mutex1); pthread_cond_signal(&cond1); pthread_mutex_unlock(&mutex1); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_t thr1, thr2, thr3; pthread_attr_t attr1, attr2, attr3; void * fonction_2(void * unused) { int i, j; fprintf(stderr, " T2 demarre\\n"); fprintf(stderr, " T2 travaille...\\n"); for (i = 0; i < 100000; i ++) for (j = 0; j < 10000; j ++) ; fprintf(stderr, " T2 se termine\\n"); return 0; } void * fonction_3(void * unused) { int i, j; fprintf(stderr, " T3 demarre\\n"); fprintf(stderr, " T3 demande le mutex\\n"); pthread_mutex_lock(& mutex); fprintf(stderr, " T3 tient le mutex\\n"); fprintf(stderr, " T3 travaille...\\n"); for (i = 0; i < 100000; i ++) for (j = 0; j < 10000; j ++) ; fprintf(stderr, " T3 lache le mutex\\n"); pthread_mutex_unlock(& mutex); fprintf(stderr, " T3 se termine\\n"); return 0; } void * fonction_1(void *unused) { fprintf(stderr, "T1 demarre\\n"); fprintf(stderr, "T1 demande le mutex\\n"); pthread_mutex_lock(& mutex); fprintf(stderr, "T1 tient le mutex\\n"); fprintf(stderr, "reveil de T3\\n"); pthread_create(& thr3, &attr3, fonction_3, 0); fprintf(stderr, "reveil de T2\\n"); pthread_create(& thr2, &attr2, fonction_2, 0); fprintf(stderr, "T1 lache le mutex\\n"); pthread_mutex_unlock(& mutex); fprintf(stderr, "T1 se termine\\n"); return 0; } int main(int argc, char * argv []) { struct sched_param param; pthread_mutex_init(& mutex, 0); pthread_attr_init(& attr1); pthread_attr_init(& attr2); pthread_attr_init(& attr3); pthread_attr_setschedpolicy(& attr1, SCHED_FIFO); pthread_attr_setschedpolicy(& attr2, SCHED_FIFO); pthread_attr_setschedpolicy(& attr3, SCHED_FIFO); param.sched_priority = 10; pthread_attr_setschedparam(& attr1, & param); param.sched_priority = 20; pthread_attr_setschedparam(& attr2, & param); param.sched_priority = 30; pthread_attr_setschedparam(& attr3, & param); pthread_attr_setinheritsched(& attr1, PTHREAD_EXPLICIT_SCHED); pthread_attr_setinheritsched(& attr2, PTHREAD_EXPLICIT_SCHED); pthread_attr_setinheritsched(& attr3, PTHREAD_EXPLICIT_SCHED); if ((errno = pthread_create(& thr1, & attr1, fonction_1, 0)) != 0) { perror("pthread_create"); exit(1); } pthread_join(thr1, 0); return 0; }
1
#include <pthread.h> unsigned char jrgba[] = { 1,2,3,255, 4,5,6,255, 7,8,9,255, 10,11,12,255, 13,14,15,255, 16,17,18,255, 19,20,21,255, 22,23,24,255, 25,26,27,255, 28,29,30,255 }; unsigned char jrgb[30]; { unsigned char *rgba; int rgba_len; unsigned char *rgb; int rgb_len; int stripe; } thread_parameters; volatile int running_threads = 0; pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER; unsigned short red_mask = 0xF800; unsigned short green_mask = 0x7E0; unsigned short blue_mask = 0x1F; void *rgb565_thread(void *param) { int i, j; thread_parameters *params = (thread_parameters *) param; unsigned char *rgba = params->rgba; unsigned short *rgb = (unsigned short *) params->rgb; int half = params->rgba_len >> 1; int start =0, jstart=0, end =-1; if (params->stripe == 0) { start = 0; jstart = 0; end = half; } else { start = half; jstart = half >> 2; end = params->rgba_len; } for (i=start, j=jstart; i<end; i+=4, j++) { if ((i+2)<end) { unsigned short r = (rgba[i] << 11) & red_mask; unsigned short g = (rgba[i+1] << 5) & green_mask; unsigned short b = rgba[i+2] & blue_mask; rgb[j] = r | g | b; printf("%u %d %d %d %0X %0X %0X %0X\\n", params->stripe, rgba[i], rgba[i+1], rgba[i+2], r, g, b, rgb[j]); } } printf("j = %d\\n", j); pthread_mutex_lock(&running_mutex); running_threads--; pthread_mutex_unlock(&running_mutex); } int main(int argc, char **argv) { int ret; pthread_t threads[3]; thread_parameters params[3]; memset(jrgb, 0 , sizeof(jrgb)); int thread; for (thread =0; thread<2; thread++) { params[thread].rgba = jrgba; params[thread].rgba_len = sizeof(jrgba); params[thread].rgb = jrgb; params[thread].rgb_len = sizeof(jrgb); params[thread].stripe = thread; if ( (ret = pthread_create(&threads[thread], 0, rgb565_thread, (void *) &params[thread])) != 0) { perror("Thread creation"); exit(1); } else { pthread_mutex_lock(&running_mutex); running_threads++; pthread_mutex_unlock(&running_mutex); } } struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 100000000L; while (running_threads > 0) { if (nanosleep(&ts, 0) < 0) break; } if (running_threads <= 0) { for (thread =0; thread<2; thread++) pthread_join(threads[thread], 0); } unsigned short *rgb = (unsigned short *) jrgb; for (thread=0; thread<sizeof(jrgba)/4; thread++) { register unsigned short pixel = rgb[thread]; unsigned char r = (pixel & red_mask) >> 11; unsigned char g = (pixel & green_mask) >> 5; unsigned char b = (pixel & blue_mask); printf("%3d %3d %3d 255 %0X", r, g, b, pixel); } printf("\\n"); }
0
#include <pthread.h> pthread_t pong_thread; pthread_t ping_thread; struct thread_arg ta; void start_pong() { int err = pthread_create(&pong_thread, 0, pong_main_thread, &ta); if (err == -1) { fprintf(stderr, "Could not create pong_main_thread thread.\\n"); exit(1); } } void start_ping() { int err = pthread_create(&ping_thread, 0, ping_main_thread, 0); if (err == -1) { fprintf(stderr, "Could not create ping_main_thread thread.\\n"); exit(1); } } int main(int argc, char **argv) { pthread_mutex_t cm = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t ct = PTHREAD_COND_INITIALIZER; ta.m = cm; ta.t = ct; ta.started = 0; if (argc == 1) { start_pong(); pthread_mutex_lock(&ta.m); while (!ta.started) { pthread_cond_wait(&ta.t, &ta.m); } pthread_mutex_unlock(&ta.m); start_ping(); pthread_join(ping_thread, 0); pthread_join(pong_thread, 0); return 0; } else if (argc == 2 ) { if (strcmp(argv[1], "pong") == 0) { start_pong(); pthread_join(pong_thread, 0); return 0; } else if (strcmp(argv[1], "ping") == 0) { start_ping(); pthread_join(ping_thread, 0); return 0; } else { fprintf(stderr, "Bad paramter." " Valid names are \\"pong\\" and \\"ping\\".\\n"); return 1; } } else { fprintf(stderr, "Too many arguments given. None or one expected.\\n"); return 1; } }
1
#include <pthread.h> static pthread_mutex_t deltat_mutex = PTHREAD_MUTEX_INITIALIZER; int deltat_write(long diff_sec) { long cnt, deltat; int r = 0; FILE *fp; pthread_mutex_lock(&deltat_mutex); fp = fopen("/data/misc/rtc/deltat", "r+b"); if (!fp) { fp = fopen("/data/misc/rtc/deltat", "w+b"); if (!fp) { LOGE("create %s failed\\n", "/data/misc/rtc/deltat"); r = -2; goto unlock; } } cnt = fread(&deltat, sizeof(long), 1, fp); if (cnt != 1) { deltat = 0; } deltat += diff_sec; rewind(fp); cnt = fwrite(&deltat, sizeof(long), 1, fp); if (cnt != 1) { LOGE("write deltat failed\\n"); r = -1; } unlock: if (fp) fclose(fp); pthread_mutex_unlock(&deltat_mutex); return r; } int deltat_read_clear(long *diff_sec) { long cnt, deltat; int r = 0; FILE *fp; pthread_mutex_lock(&deltat_mutex); fp = fopen("/data/misc/rtc/deltat", "r+b"); if (!fp) { fp = fopen("/data/misc/rtc/deltat", "w+b"); if (!fp) { LOGE("create %s failed\\n", "/data/misc/rtc/deltat"); r = -2; goto unlock; } } cnt = fread(&deltat, sizeof(long), 1, fp); if (cnt != 1) { deltat = 0; } if (diff_sec) *diff_sec = deltat; deltat = 0; rewind(fp); cnt = fwrite(&deltat, sizeof(long), 1, fp); if (cnt != 1) { LOGE("write deltat failed\\n"); r = -1; } unlock: if (fp) fclose(fp); pthread_mutex_unlock(&deltat_mutex); return r; }
0
#include <pthread.h> double integral = 0; pthread_mutex_t mutex; pthread_t threads[100]; double Function(double x) { return sqrt(1-pow(x,2)); } void* Integrate(void* t) { int threadID = (int)t; pthread_mutex_lock(&mutex); for(int i = 0; i <= 100/100; i++) { double param = i + (100/100 * threadID); integral += 2*Function(param/100); } pthread_mutex_unlock(&mutex); pthread_exit((void*)0); } void main() { pthread_attr_t attr; int err; double pi = 0; void* status; pthread_mutex_init(&mutex, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); printf("Number of threads being used:%d\\n", 100); for(int i = 0; i < 100; i++) { err = pthread_create(&threads[i], &attr, Integrate, (void*)i); if(err != 0) { printf("Error creating thread:%d\\n", i); return; } } pthread_attr_destroy(&attr); for(int i = 0; i < 100; i++) { err = pthread_join(threads[i], &status); if(err != 0) { printf("Error rejoining thread:%d\\n", i); return; } } integral = integral/(2*100); pi = integral * 4; printf("The approximate value of PI is %0.10f", pi); pthread_mutex_destroy(&mutex); pthread_exit(0); }
1
#include <pthread.h> struct msg { struct msg *next; int num; }; struct msg *head; pthread_cond_t has_product = PTHREAD_COND_INITIALIZER; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void *consumer(void *p) { struct msg *mp; while (1) { pthread_mutex_lock(&lock); while (head == 0) pthread_cond_wait(&has_product, &lock); mp = head; head = head->next; pthread_mutex_unlock(&lock); printf("Consume %d\\n", mp->num); free(mp); sleep(rand() % 2); } } void *producer(void *p) { struct msg *mp; while (1) { mp = malloc(sizeof (struct msg)); mp->num = rand() % 100 + 1; printf("Produce %d\\n", mp->num); pthread_mutex_lock(&lock); mp->next = head; head = mp; pthread_mutex_unlock(&lock); pthread_cond_signal(&has_product); sleep(rand() % 5); } } int main(int argc, char *argv[]) { pthread_t ptid, ctid; pthread_create(&ptid, 0, producer, 0); pthread_create(&ctid, 0, consumer, 0); pthread_join(ptid, 0); pthread_join(ctid, 0); return 0; }
0
#include <pthread.h> pthread_mutex_t forks[5]; pthread_t phils[5]; void *philosopher (void *id); int food_on_table (); void get_fork (int, int, char *); void down_forks (int, int); pthread_mutex_t foodlock; int sleep_seconds = 0; int main (int argn, char **argv) { int i; if (argn == 2) sleep_seconds = atoi (argv[1]); pthread_mutex_init (&foodlock, 0); for (i = 0; i < 5; i++) pthread_mutex_init (&forks[i], 0); for (i = 0; i < 5; i++) pthread_create (&phils[i], 0, philosopher, (void *)i); for (i = 0; i < 5; i++) pthread_join (phils[i], 0); return 0; } void * philosopher (void *num) { int id; int left_fork, right_fork, f; id = (int)num; printf ("Philosopher %d sitting down to dinner.\\n", id); right_fork = id; left_fork = id + 1; if (left_fork == 5) left_fork = 0; while (f = food_on_table ()) { if (id == 1) sleep (sleep_seconds); printf ("Philosopher %d: get dish %d.\\n", id, f); get_fork (id, right_fork, "right"); get_fork (id, left_fork, "left "); printf ("Philosopher %d: eating.\\n", id); usleep (30000 * (50 - f + 1)); down_forks (left_fork, right_fork); } printf ("Philosopher %d is done eating.\\n", id); return (0); } int food_on_table () { static int food = 50; int myfood; pthread_mutex_lock (&foodlock); if (food > 0) { food--; } myfood = food; pthread_mutex_unlock (&foodlock); return myfood; } void get_fork (int phil, int fork, char *hand) { pthread_mutex_lock (&forks[fork]); printf ("Philosopher %d: got %s fork %d\\n", phil, hand, fork); } void down_forks (int f1, int f2) { pthread_mutex_unlock (&forks[f1]); pthread_mutex_unlock (&forks[f2]); }
1
#include <pthread.h> pthread_mutex_t m; pthread_cond_t rcv; pthread_cond_t wcv; int writers; short writing; short reading; } rwinfo_t; rwinfo_t * rwinfo_init() { rwinfo_t * rwinfo = malloc(sizeof(rwinfo_t)); pthread_mutex_init(&rwinfo->m, 0); pthread_cond_init(&rwinfo->rcv, 0); pthread_cond_init(&rwinfo->wcv, 0); rwinfo->writers = 0; rwinfo->writing = 0; rwinfo->reading = 0; return rwinfo; } void* safeReader(rwinfo_t * rwinfo, void* (*readFxn)(void*), void* arg) { pthread_mutex_lock(&rwinfo->m); while(rwinfo->writers) pthread_cond_wait(&rwinfo->rcv, &rwinfo->m); rwinfo->reading = 1; pthread_mutex_unlock(&rwinfo->m); void* toReturn = readFxn(arg); pthread_mutex_lock(&rwinfo->m); rwinfo->reading = 0; if(rwinfo->writers) pthread_cond_signal(&rwinfo->wcv); pthread_mutex_unlock(&rwinfo->m); return toReturn; } void safeWriter(rwinfo_t * rwinfo, void (*writeFxn)(void*), void* arg) { pthread_mutex_lock(&rwinfo->m); rwinfo->writers++; while(rwinfo->reading || rwinfo->writing) pthread_cond_wait(&rwinfo->wcv, &rwinfo->m); rwinfo->writing = 1; pthread_mutex_unlock(&rwinfo->m); writeFxn(arg); pthread_mutex_lock(&rwinfo->m); rwinfo->writing = 0; rwinfo->writers--; if(rwinfo->writers) pthread_cond_signal(&rwinfo->wcv); else pthread_cond_broadcast(&rwinfo->rcv); pthread_mutex_unlock(&rwinfo->m); }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; struct info_t{ pthread_t tid; char *msg; struct info_t *next; }*info_list; void enqueue_info (struct info_t *info){ struct info_t *t; info->next = info_list; info_list = info; } void clean_func (void *arg) { struct info_t *info; info = (struct info_t*)arg; if (info != 0){ info = (struct info_t*)arg; printf("clean func: from %s.\\n", info->msg); free(info); }else printf("clean func: info null.\\n"); } void cancel_clean_func (void *arg) { printf("cancel clean func.\\n"); } void *thread (void *arg) { struct info_t *info = 0; pthread_t tid; int ret; printf("into thread.\\n"); if (arg == (void*)1){ pthread_cleanup_push(cancel_clean_func, 0); if (ret = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0)) fprintf(stderr, "pthread_setcancelstate failed.\\n"); else printf("set cancel state ok.\\n"); if (ret = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0)) fprintf(stderr, "pthread_setcanceltype failed.\\n"); else printf("set cancel type ok.\\n"); pause(); pthread_cleanup_pop(0); }else sleep(1); tid = pthread_self(); pthread_mutex_lock(&mutex); while (1){ pthread_cond_wait(&cond, &mutex); struct info_t *prev; for (info = info_list, prev = 0; info != 0; prev = info, info = info->next){ if (pthread_equal(tid, info->tid)){ if (info == info_list){ info_list = info->next; } else prev->next = info->next; pthread_mutex_unlock(&mutex); goto afterwhile; } } } afterwhile: ; pthread_cleanup_push(clean_func, (void*)info); if (strcmp(info->msg, "return") == 0){ printf("return now.\\n"); return 0; } else if (strcmp(info->msg, "pthread_exit") == 0){ printf("pthread_exit now.\\n"); pthread_exit(0); } else if (strcmp(info->msg, "exit") == 0){ sleep(2); printf("exit now.\\n"); exit(0); }else if (strcmp(info->msg, "cancel") == 0){ pthread_t *cancel_id; cancel_id = (pthread_t*)arg; printf("pthread_cancel now.\\n"); int ret; if (ret = pthread_cancel(*cancel_id)){ printf("pthread_cancel failed, errno:%d\\n", ret); } } printf("thread: shouldn't got here. msg:%s\\n", info->msg); pthread_cleanup_pop(1); pthread_exit((void*)1); } int main (void) { pthread_t tids[5]; char *msg[] = {"return", "pthread_exit", "exit", "cancel", 0}; int ret; pthread_mutexattr_t attr; if (ret = pthread_mutexattr_init(&attr)) t_err("pthread_mutexattr_init failed.", ret); if (ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) t_err("pthread_mutexattr_settype failed.", ret); if (ret = pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_PRIVATE)) t_err("pthread_mutexattr_setpshared failed.", ret); if (ret = pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST)) t_err("pthread_mutexattr_setrobust failed.", ret); if (ret = pthread_mutex_init(&mutex, &attr)) t_err("pthread_mutex_init failed.", ret); if (ret = pthread_mutexattr_destroy(&attr)) t_err("pthread_mutexattr_destroy failed.", ret); if (ret = pthread_create(&tids[0], 0, thread, (void*)0)) fprintf(stderr, "pthread_create failed, errno:%d\\n", ret); if (ret = pthread_create(&tids[1], 0, thread, (void*)0)) fprintf(stderr, "pthread_create failed, errno:%d\\n", ret); if (ret = pthread_create(&tids[2], 0, thread, (void*)0)) fprintf(stderr, "pthread_create failed, errno:%d\\n", ret); if (ret = pthread_create(&tids[3], 0, thread, (void*)&tids[4])) fprintf(stderr, "pthread_create failed, errno:%d\\n", ret); if (ret = pthread_create(&tids[4], 0, thread, (void*)1)) fprintf(stderr, "pthread_create failed, errno:%d\\n", ret); sleep(3); int i = 0; for (char **m = msg; *m != 0; m++, i++){ struct info_t *info; if ((info = malloc(sizeof(struct info_t))) == 0) err("malloc failed."); info->tid = tids[i]; info->msg = *m; info->next = 0; pthread_mutex_lock(&mutex); enqueue_info(info); pthread_mutex_unlock(&mutex); } pthread_cond_broadcast(&cond); for (int i = 0; i < sizeof(tids); i++){ int ret; if (ret = pthread_join(tids[i], 0)) printf("pthread_join failed, errno:%d\\n", ret); } return 0; }
1
#include <pthread.h> int ClientManager(void * acceptsd) { if (debug) printf("Hello, I'm the thread %u client manager\\n\\n",(int)pthread_self()); int mysd; int ret; char buffer[1000]; memset(buffer,0,sizeof(buffer)); mysd = *((int *)acceptsd); if (debug) printf("Socket descriptor %d\\n\\nWaiting fo data..\\n",mysd); ret = recv(mysd,buffer,sizeof(buffer),0); send(mysd,&buffer,ret,0); close(mysd); ret = 0; if (debug) printf("Goodbye, I'm the thread %u client manager\\n\\n",(int)pthread_self()); pthread_mutex_lock(&thread_number_mutex); thread_number--; pthread_mutex_unlock(&thread_number_mutex); return(ret); }
0
#include <pthread.h> int nitems; struct { pthread_mutex_t mutex; int buff[1000000]; int nput; int nval; } shared = { PTHREAD_MUTEX_INITIALIZER }; int myMin(int a, int b) { return a < b ? a : b; } void* produce(void *arg) { for( ; ; ) { pthread_mutex_lock(&shared.mutex); if(shared.nput >= nitems) { pthread_mutex_unlock(&shared.mutex); return 0; } shared.buff[shared.nput] = shared.nval; ++shared.nput; ++shared.nval; pthread_mutex_unlock(&shared.mutex); *((int*) arg) += 1; } } void consume_wait(int i) { for( ; ; ) { pthread_mutex_lock(&shared.mutex); if(i < shared.nput) { pthread_mutex_unlock(&shared.mutex); return ; } pthread_mutex_unlock(&shared.mutex); } } void *consume(void *arg) { int i; for(i = 0; i < nitems; ++i) { consume_wait(i); if(shared.buff[i] != i) printf("buff[%d] = %d\\n", i, shared.buff[i]); } return 0; } int main(int argc, const char *argv[]) { int i, nthreads, count[100]; pthread_t tid_produce[100], tid_consume; if(argc != 3) { exit(1); } nitems = myMin(atoi(argv[1]), 1000000); nthreads = myMin(atoi(argv[2]), 100); pthread_setconcurrency(nthreads + 1); for(i = 0; i < nthreads; ++i) { count[i] = 0; pthread_create(&tid_produce[i], 0, produce, &count[i]); } pthread_create(&tid_consume, 0, consume, 0); for(i = 0; i < nthreads; ++i) { pthread_join(tid_produce[i], 0); printf("count[%d] = %d\\n", i, count[i]); } pthread_join(tid_consume, 0); exit(0); }
1
#include <pthread.h> struct connection; struct locked_connection { pthread_mutex_t mutex; struct connection *conn; }; struct connection_pool { struct locked_connection lockedconn[40]; int round_robin; }; struct connection_pool *connection_pool_new (void) { int i; struct connection_pool *r; r = (struct connection_pool *) malloc (sizeof (*r)); memset (r, '\\0', sizeof (*r)); for (i = 0; i < 40; i++) pthread_mutex_init (&r->lockedconn[i].mutex, 0); return r; } void connection_pool_free (struct connection_pool *c) { int i; for (i = 0; i < 40; i++) { pthread_mutex_lock (&c->lockedconn[i].mutex); if (c->lockedconn[i].conn) connection_free (c->lockedconn[i].conn); pthread_mutex_unlock (&c->lockedconn[i].mutex); pthread_mutex_destroy (&c->lockedconn[i].mutex); } memset (c, '\\0', sizeof (*c)); free (c); } struct locked_connection *connection_pool_get_locked_ (struct connection_pool *c, int start) { int i, r; i = start; do { if (!pthread_mutex_trylock (&c->lockedconn[i].mutex)) { if (c->lockedconn[i].conn) return &c->lockedconn[i]; pthread_mutex_unlock (&c->lockedconn[i].mutex); } } while ((i = (i + 1) % 40) != start); assert (i == start); do { if (!pthread_mutex_trylock (&c->lockedconn[i].mutex)) { if (!c->lockedconn[i].conn) c->lockedconn[i].conn = connection_new (); return &c->lockedconn[i]; } } while ((i = (i + 1) % 40) != start); assert (i == start); r = pthread_mutex_lock (&c->lockedconn[start].mutex); assert (!r); if (!c->lockedconn[start].conn) c->lockedconn[start].conn = connection_new (); return &c->lockedconn[start]; } struct locked_connection *connection_pool_get_locked (struct connection_pool *c) { int start; c->round_robin = (c->round_robin + 1) % 40; start = c->round_robin; return connection_pool_get_locked_ (c, start); } void locked_connection_unlock (struct locked_connection *c) { pthread_mutex_unlock (&c->mutex); }
0
#include <pthread.h> int total_time = 0; pthread_mutex_t global_mutex; long long factorial(long n) { long long result = 1; long i; for (i = 1; i <= n; ++i) result *= i; return result; } void *thread_implementation(void *t) { int i; long tid; long long result = 0.0; tid = (long)t; clock_t begin; clock_t end; int compute_time; begin = clock(); printf("Thread %ld starting...\\n",tid); for (i=0; i<10000000; i++) { result = factorial(tid); } end = clock(); compute_time = (end-begin)/(CLOCKS_PER_SEC/1000); printf("Thread %ld done. Result: %ld! = %lld. Time to complete: %d ms\\n", tid, tid, result, compute_time); pthread_mutex_lock(&global_mutex); total_time+=compute_time; printf("Total time: %d ms\\n", total_time); pthread_mutex_unlock(&global_mutex); pthread_exit((void*) t); } int main (int argc, char *argv[]) { pthread_t thread[20]; pthread_attr_t attr; int rc; long i; void *status; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&global_mutex, 0); for(i=0; i<20; i++) { printf("Main: creating thread %ld\\n", i); rc = pthread_create(&thread[i], &attr, thread_implementation, (void *)i); if (rc) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } pthread_attr_destroy(&attr); for(i=0; i<20; i++) { rc = pthread_join(thread[i], &status); if (rc) { printf("ERROR; return code from pthread_join() is %d\\n", rc); exit(-1); } printf("Main: completed join with thread %ld having a status of %ld\\n", i, (long)status); } pthread_mutex_destroy(&global_mutex); printf("Main: program completed. Exiting.\\n"); pthread_exit(0); }
1
#include <pthread.h> int aData[(20 + 1)]; int dwHead; int dwTail; }T_QUEUE, *PT_QUEUE; void InitQue(T_QUEUE *ptQue) { memset(ptQue, 0, sizeof(*ptQue)); } void EnterQue(PT_QUEUE ptQue, int dwElem) { if(IsQueFull(ptQue)) { printf("Elem %d cannot enter Queue %p(Full)!\\n", dwElem, ptQue); return; } ptQue->aData[ptQue->dwTail]= dwElem; ptQue->dwTail = (ptQue->dwTail + 1) % (20 + 1); } int LeaveQue(PT_QUEUE ptQue) { if(IsQueEmpty(ptQue)) { printf("Queue %p is Empty!\\n", ptQue); return -1; } int dwElem = ptQue->aData[ptQue->dwHead]; ptQue->dwHead = (ptQue->dwHead + 1) % (20 + 1); return dwElem; } void DisplayQue(PT_QUEUE ptQue) { if(IsQueEmpty(ptQue)) { printf("Queue %p is Empty!\\n", ptQue); return; } printf("Queue Element: "); int dwIdx = ptQue->dwHead; while((dwIdx % (20 + 1)) != ptQue->dwTail) printf("%d ", ptQue->aData[(dwIdx++) % (20 + 1)]); printf("\\n"); } int IsQueEmpty(PT_QUEUE ptQue) { return ptQue->dwHead == ptQue->dwTail; } int IsQueFull(PT_QUEUE ptQue) { return (ptQue->dwTail + 1) % (20 + 1) == ptQue->dwHead; } int QueDataNum(PT_QUEUE ptQue) { return (ptQue->dwTail - ptQue->dwHead + (20 + 1)) % (20 + 1); } int GetQueHead(PT_QUEUE ptQue) { return ptQue->dwHead; } int GetQueHeadData(PT_QUEUE ptQue) { return ptQue->aData[ptQue->dwHead]; } int GetQueTail(PT_QUEUE ptQue) { return ptQue->dwTail; } T_QUEUE gtQueue; pthread_mutex_t gtQueLock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t gtPrdCond = PTHREAD_COND_INITIALIZER; pthread_cond_t gtCsmCond = PTHREAD_COND_INITIALIZER; void *ProducerThread(void *pvArg) { pthread_detach(pthread_self()); int dwThrdNo = *((int *)(pvArg)); while(1) { pthread_mutex_lock(&gtQueLock); while(IsQueFull(&gtQueue)) pthread_cond_wait(&gtPrdCond, &gtQueLock); EnterQue(&gtQueue, GetQueTail(&gtQueue)); if(QueDataNum(&gtQueue) == 1) pthread_cond_broadcast(&gtCsmCond); printf("[Producer %2u]Current Product Num: %u\\n", dwThrdNo, QueDataNum(&gtQueue)); pthread_mutex_unlock(&gtQueLock); sleep(rand()%3 + 1); } } void *ConsumerThread(void *pvArg) { pthread_detach(pthread_self()); int dwThrdNo = *((int *)(pvArg)); while(1) { pthread_mutex_lock(&gtQueLock); while(IsQueEmpty(&gtQueue)) pthread_cond_wait(&gtCsmCond, &gtQueLock); if(GetQueHead(&gtQueue) != GetQueHeadData(&gtQueue)) { printf("[Consumer %2u]Product: %d, Expect: %d\\n", dwThrdNo, GetQueHead(&gtQueue), GetQueHeadData(&gtQueue)); exit(0); } LeaveQue(&gtQueue); if(QueDataNum(&gtQueue) == (20 -1)) pthread_cond_broadcast(&gtPrdCond); printf("[Consumer %2u]Current Product Num: %u\\n", dwThrdNo, QueDataNum(&gtQueue)); pthread_mutex_unlock(&gtQueLock); sleep(rand()%3 + 1); } } int main(void) { InitQue(&gtQueue); srand(getpid()); pthread_t aThrd[3 + 5]; int dwThrdIdx; for(dwThrdIdx = 0; dwThrdIdx < 3; dwThrdIdx++) { pthread_create(&aThrd[dwThrdIdx], 0, ConsumerThread, (void*)(&dwThrdIdx)); } sleep(2); for(dwThrdIdx = 0; dwThrdIdx < 5; dwThrdIdx++) { pthread_create(&aThrd[dwThrdIdx + 3], 0, ProducerThread, (void*)&dwThrdIdx); } while(1); return 0 ; }
0
#include <pthread.h> pthread_mutex_t db; pthread_mutex_t mutex; int rc; int lr, lw; void read_db(int lr){ printf("Total de %d leitores lendo agora.\\n",rc); sleep(lr); } void use_db(){ int use; use = rand() % 20; printf("Usuário utilizando conhecimento\\n"); sleep(use); } void think_db(){ int think; think = rand() % 10; printf("Escritor pensando no que irá escrever\\n"); sleep(think); } void write_db(int lw){ printf("Escritor escrevendo no banco de dados\\n"); sleep(lw); } void reader() { while (1) { pthread_mutex_lock(&mutex); rc++; if(rc == 1) pthread_mutex_lock(&db); pthread_mutex_unlock(&mutex); read_db(lr); pthread_mutex_lock(&mutex); rc--; if(rc == 0) pthread_mutex_unlock(&db); pthread_mutex_unlock(&mutex); use_db(); } } void writer() { while(1){ think_db(); pthread_mutex_lock(&db); write_db(lw); pthread_mutex_unlock(&db); } } int main(){ int READERS = 0, WRITERS = 0; printf("Quantidade de leitores: "); scanf("%d",&READERS); printf("Quantidade de escritores: "); scanf("%d",&WRITERS); printf("Tempo de leitura: "); scanf("%d",&lr); printf("Tempo de escrita: "); scanf("%d",&lw); pthread_t writerthreads[WRITERS], readerthreads[READERS]; int i; pthread_mutex_init(&db, 0); pthread_mutex_init(&mutex, 0); for(i=0;i < WRITERS;i++) pthread_create( &writerthreads[i], 0,(void *) writer, 0); for(i=0;i < READERS;i++) pthread_create( &readerthreads[i], 0,(void *) reader, 0); for(i=0;i < WRITERS;i++) pthread_join(writerthreads[i], 0); for(i=0;i < READERS;i++) pthread_join(readerthreads[i], 0); return 0; }
1
#include <pthread.h> void do_work () { printf("%s\\n", "working..."); } int counter = 0; int thread_flag; pthread_mutex_t thread_flag_mutex; void initialize_flag () { pthread_mutex_init (&thread_flag_mutex, 0); thread_flag = 1; } void set_thread_flag (int flag_value) { pthread_mutex_lock (&thread_flag_mutex); thread_flag = flag_value; pthread_mutex_unlock (&thread_flag_mutex); } void* thread_function (void* thread_arg) { while (1) { int flag_is_set; pthread_mutex_lock (&thread_flag_mutex); flag_is_set = thread_flag; pthread_mutex_unlock (&thread_flag_mutex); if (flag_is_set && counter < 10) { do_work (); counter++; } else { set_thread_flag (0); } } return 0; } int main() { pthread_t thread_id; initialize_flag(); pthread_create (&thread_id, 0, &thread_function, 0); pthread_join (thread_id, 0); return 0; }
0
#include <pthread.h> int balance = 1000; pthread_mutex_t mutex; struct ex_arguments{ int n; int * trans; }; void * execute( void * args){ struct ex_arguments * xargs = (struct ex_arguments *) args; int i; for(i=0;i<xargs->n;i++){ pthread_mutex_lock(&mutex); balance = balance + xargs->trans[i]; pthread_mutex_unlock(&mutex); } free(xargs); return 0; } int main(){ pthread_t threads[20]; int transactions[100000]; struct ex_arguments * xargs; int i; int expected_bal = 1000; pthread_mutex_init(&mutex, 0); srandom(time(0)); for(i=0;i<100000;i++){ transactions[i] = random() % 100; if(random()%2){ transactions[i] *= -1; } expected_bal += transactions[i]; } for(i=0;i<20;i++){ xargs->n = 100000/20; *xargs->trans = 5000*i; pthread_create(&threads[i], 0, execute, xargs); } for(i=0;i<20;i++){ pthread_join(threads[i], 0); } printf(" Balance: %d\\n", balance); printf("Exp. Bal: %d\\n", expected_bal); pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> char *master; char *slaves; volatile int busy; char *size; pthread_mutex_t lock; pthread_cond_t condp; pthread_cond_t condc; size_t random; char *pattern; char *pattern1; } target_t; void usage() { fprintf(stderr, "Usage:\\n"); fprintf(stderr, "./testreplication -m master -s slave1,slave2 -S size\\n"); } void generate_pattern(target_t *target) { int i = 0; size_t num; size_t *pat = (size_t *)target->pattern; int len = sizeof(target->pattern)/sizeof(target->pattern[0]); for (i = 0; i < 4096/sizeof(size_t); i++) { *(pat+i) = target->random+i; } } int device_type(char *device) { struct stat stat; int fd = open(device, O_RDONLY); fstat(fd, &stat); close(fd); if (S_ISBLK(stat.st_mode)) { return (0); } if (S_ISREG(stat.st_mode)) { return (1); } return (-1); } static void * start_master(void *arg) { int i = 0, ret; target_t *target = (target_t *)arg; int fd; int fd1; char response; char buffer[512]; printf("start master %s\\n", target->master); if (device_type(target->master) == 0) { printf("R u sure Block Device is not root device (Y/N)\\n"); response = getchar(); if (response != 'Y') { exit(0); } } else if (device_type(target->master) == 1) { printf("Testing with regular file\\n"); } else { printf("Not supported file\\n"); exit(0); } fd = open(target->master, O_CREAT|O_RDWR|O_DIRECT, S_IRWXU); if (fd < 0) { pthread_exit(0); perror("open failed...\\n"); return; } for (i = 0; i < atoi(target->size); i++) { pthread_mutex_lock(&target->lock); while (target->busy == 1) { pthread_cond_wait(&target->condc, &target->lock); } target->busy = 1; generate_pattern(target); ret = write(fd, target->pattern, (4096)); pthread_cond_signal(&target->condp); pthread_mutex_unlock(&target->lock); } pthread_exit(0); close(fd); } static void * start_slave(void *arg) { int i = 0, ret; int maxdev = 0; size_t j = 0; char *token; int fd[10]; size_t pattern[512]; target_t *target = (target_t *)arg; printf("start slave %s\\n", target->slaves); token = strtok(target->slaves, ","); while (token != 0) { fd[maxdev] = open(token, O_RDONLY|O_DIRECT); if (fd[maxdev] < 0) { printf("device %s\\n", token); perror("slave open failed."); pthread_exit(0); return; } token = strtok(0, ","); maxdev++; } for (i = 0; i < atoi(target->size); i++) { pthread_mutex_lock(&target->lock); while (target->busy == 0) { pthread_cond_wait(&target->condp, &target->lock); } target->busy = 0; ret = read(fd[rand()%maxdev], target->pattern1, (4096)); if (memcmp(target->pattern1, target->pattern, 4096) != 0) { printf("Replica Verification failed %d\\n", ret); } pthread_cond_signal(&target->condc); pthread_mutex_unlock(&target->lock); } for (i = 0; i < maxdev; i++) { close(fd[i]); } pthread_exit(0); } int starttest(target_t *target) { pthread_t mid; pthread_t sid; int fd; int ret = 0; pthread_mutex_init(&target->lock, 0); pthread_cond_init(&target->condp, 0); pthread_cond_init(&target->condc, 0); target->busy = 0; fd = open("/dev/random", O_RDONLY); read(fd, &target->random, 8); close(fd); ret = posix_memalign((void **)&target->pattern, 4096, 4096); ret = posix_memalign((void **)&target->pattern1, 4096, 4096); if (ret) { perror("posix_memalign"); return -1; } ret = pthread_create(&mid, 0, &start_master, target); ret = pthread_create(&sid, 0, &start_slave, target); pthread_join(mid, 0); pthread_join(sid, 0); pthread_mutex_destroy(&target->lock); pthread_cond_destroy(&target->condc); pthread_cond_destroy(&target->condp); } int main(int argc, char **argv) { int c; target_t target; char *master = 0; char *slaves = 0; while((c = getopt(argc, argv, "m:s:S:")) != -1) { switch(c) { case 'm': target.master = optarg; break; case 's': target.slaves = optarg; break; case 'S': target.size = optarg; break; default: usage(); return; } } if (!target.master || !target.slaves) { usage(); return; } starttest(&target); return (0); }
0
#include <pthread.h> pthread_mutex_t lock; char *data; size_t exec_times; }Info; void* fighting(void *ptr){ pthread_mutex_lock(&lock); char *part = ((Info*) ptr) ->data; size_t exec_times = ((Info*) ptr) ->exec_times; pthread_mutex_unlock(&lock); for(size_t i =0; i< exec_times;i++){ pthread_mutex_lock(&lock); part[i] = part[i]+1; pthread_mutex_unlock(&lock); } return 0; } int main(int argc, char *argv[]){ if(argc != 3){ perror("Incorrect number of arguments (3)"); puts("Remember to include -pthread flag during COMPILING"); puts("\\n Usage: ./a.out <NUM_THREADS> <MESSAGE> \\n"); exit(1); } printf("\\nHi there! This is a multi-threaded C program where users indicate their desired number of threads and a message (with no space in between)\\nThe message length is then divided equally among the threads to increase every character by 1\\n"); puts("Remember to include -pthread flag when COMPILING\\n"); size_t NUM_THREADS = atoi(argv[1]); pthread_t solders[NUM_THREADS]; char mess[strlen(argv[2])]; strcpy(mess,argv[2]); size_t weight = strlen(mess); size_t rem = weight % NUM_THREADS; Info *box; if(weight >= NUM_THREADS){ box = malloc(NUM_THREADS* sizeof(Info)); for(size_t j=0;j< NUM_THREADS;j++){ box[j].data = mess+ j*(weight/NUM_THREADS); box[j].exec_times = weight/NUM_THREADS; } if(weight%NUM_THREADS !=0) box[NUM_THREADS-1].exec_times += weight%NUM_THREADS; }else{ box = malloc(weight* sizeof(Info)); for(size_t j=0;j< weight;j++){ box[j].data = mess+ j; box[j].exec_times = 1; } NUM_THREADS = weight; } for(size_t i = 0;i<NUM_THREADS;i++){ pthread_create(&solders[i],0,fighting, (void*)&box[i]); } for(size_t i =0; i<NUM_THREADS;i++){ pthread_join(solders[i],0); } printf("ENCODED MESSAGE IS: %s\\n",mess); puts(""); return 0; }
1
#include <pthread.h> enum thread_status { RUNING = 0, EXITING, }; pthread_t handle; pthread_mutex_t mutex; sem_t sem_work; sem_t *sem_ctrl; enum thread_status status; int chn_num; int chn_id; int chn_priority; } handle_args; void *thread_work(void *args); void *thread_ctrl(void *args); int multi_thread_init(handle_args **args, int chn, sem_t *sem_ctrl) { handle_args *arg = 0; int i = 0; if (!chn) { do { printf("Invalid chn number.\\n"); } while (0); return -1; } arg = malloc(sizeof(handle_args) * chn);; if (!arg) { do { printf("failed to malloc handle %d.\\n", chn); } while (0); return -1; } for (i = 0; i < chn; i++) { pthread_mutex_init(&(arg[i].mutex), 0); sem_init(&(arg[i].sem_work), 0, 0); arg[i].sem_ctrl = sem_ctrl; arg[i].status = RUNING; arg[i].chn_num = chn; arg[i].chn_id = i; arg[i].chn_priority = 1; } sem_init(sem_ctrl, 0, 1); *args = arg; return 0; } int multi_thread_run(handle_args *args) { pthread_t th_ctrl; int chn = args[0].chn_num; int ret = 0; int i = 0; if (!chn) { do { printf("Invalid chn number.\\n"); } while (0); return -1; } ret = pthread_create(&th_ctrl, 0, thread_ctrl, args); if (ret < 0) { do { printf("failed to create thread ctrl ret %d.\\n", ret); } while (0); return -1; } for (i = 0; i < chn; i++) { ret = pthread_create(&(args[i].handle), 0, thread_work, (void *)&args[i]); if (ret < 0) { do { printf("failed to create thread work ret %d.\\n", ret); } while (0); return -1; } } pthread_join(th_ctrl, 0); for (i = 0; i < chn; i++) pthread_join(args[i].handle, 0); return 0; } int multi_thread_chk_exit(handle_args *args) { int i = 0; int chn = args[0].chn_num; for (i = 0; i < chn; i++) { if (args[i].status != EXITING) return 0; } return 1; } int multi_thread_chk_turn(handle_args *args, int chn, int turn) { int i = 0; int low = turn; for (i = 0; i < chn; i++) { if (args[i].status != EXITING) { if (i > turn) return i; else { if (i < low) low = i; } } } return low; } void *thread_work(void *args) { handle_args *data = args; int end = 0; while (end++ < 5) { pthread_mutex_lock(&(data->mutex)); sem_wait(&(data->sem_work)); data->status = RUNING; { do { printf("chn %d work.\\n", data->chn_id); } while (0); } pthread_mutex_unlock(&(data->mutex)); sem_post(data->sem_ctrl); } data->status = EXITING; sem_post(data->sem_ctrl); do { printf("chn %d exit.\\n", data->chn_id); } while (0); return 0; } void *thread_ctrl(void *args) { handle_args *data = args; sem_t *ctrl = data[0].sem_ctrl; pthread_mutex_t m_ctrl; int chn = data[0].chn_num; int turn = 0; pthread_mutex_init(&m_ctrl, 0); while (1) { pthread_mutex_lock(&m_ctrl); if (multi_thread_chk_exit(data)) break; sem_wait(ctrl); sem_post(&(data[turn].sem_work)); turn = multi_thread_chk_turn(data, chn, turn); pthread_mutex_unlock(&m_ctrl); } return 0; } int main(int argc, char **argv) { int ret = 0; int chn = 6; sem_t sem_ctrl; handle_args *args; ret = multi_thread_init(&args, chn, &sem_ctrl); if (ret < 0) { do { printf("failed to init multi thread.\\n"); } while (0); return -1; } ret = multi_thread_run(args); if (ret < 0) { do { printf("failed to run multi thread.\\n"); } while (0); return -1; } return 0; }
0
#include <pthread.h> void *threadfunc(void *arg); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int count, total, toggle; int main(void) { int ret; pthread_t new; void *joinval; int sharedval; printf("1: condition variable test 5\\n"); ret = pthread_mutex_lock(&mutex); if (ret) err(1, "pthread_mutex_lock(1)"); count = 5000000; toggle = 0; ret = pthread_create(&new, 0, threadfunc, &sharedval); if (ret != 0) err(1, "pthread_create"); printf("1: Before waiting.\\n"); while (count>0) { count--; total++; toggle = 1; pthread_cond_broadcast(&cond); do { pthread_cond_wait(&cond, &mutex); } while (toggle != 0); } printf("1: After the loop.\\n"); toggle = 1; pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); printf("1: After releasing the mutex.\\n"); ret = pthread_join(new, &joinval); if (ret != 0) err(1, "pthread_join"); printf("1: Thread joined. Final count = %d, total = %d\\n", count, total); assert(count == 0); assert(total == 5000000); return 0; } void * threadfunc(void *arg) { printf("2: Second thread.\\n"); pthread_mutex_lock(&mutex); while (count>0) { count--; total++; toggle = 0; pthread_cond_signal(&cond); do { pthread_cond_wait(&cond, &mutex); } while (toggle != 1); } printf("2: After the loop.\\n"); pthread_mutex_unlock(&mutex); return 0; }
1
#include <pthread.h> int occupiedChairs = 0; int taBusy = FALSE; void *simulate_student_programming(void *studentId) { int id = *(int *)studentId; pthread_mutex_lock(&mutex); int programmingSecs = rand() % SLEEP_MAX_SECS + 1; pthread_mutex_unlock(&mutex); printf("\\tStudent %d is programming for %d seconds\\n", id, programmingSecs); while(TRUE) { sleep(programmingSecs); pthread_mutex_lock(&mutex); if (occupiedChairs < NUM_CHAIRS) { occupiedChairs++; printf("\\t\\tStudent %d takes a seat waiting = %d\\n", id, occupiedChairs); sem_post(&semaphore_student); pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex); if (taBusy == FALSE){ printf("Student %d receiving help\\n", id); taBusy = TRUE; } pthread_mutex_unlock(&mutex); sem_wait(&semaphore_ta); } else { programmingSecs = rand() % SLEEP_MAX_SECS + 1; pthread_mutex_unlock(&mutex); printf("\\t\\t\\tStudent %d will try later\\n", id); printf("\\tStudent %d is programming for %d seconds\\n", id, programmingSecs); } } } void *simulate_ta_helping() { while(TRUE) { sem_wait(&semaphore_student); pthread_mutex_lock(&mutex); if (occupiedChairs > 0) { occupiedChairs --; int helpingSecs = rand() % SLEEP_MAX_SECS + 1; printf("Helping a student for %d seconds, waiting students = %d\\n", helpingSecs, occupiedChairs); taBusy = TRUE; sleep(helpingSecs); pthread_mutex_unlock(&mutex); taBusy = FALSE; sem_post(&semaphore_ta); } else { pthread_mutex_unlock(&mutex); } } }
0
#include <pthread.h> static FILE *fp = 0; static char linestr[AU_LINE_MAX]; static char *delim = ":"; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static struct au_class_ent *get_class_area() { struct au_class_ent *c; c = (struct au_class_ent *) malloc (sizeof(struct au_class_ent)); if(c == 0) { return 0; } c->ac_name = (char *)malloc(AU_CLASS_NAME_MAX * sizeof(char)); if(c->ac_name == 0) { free(c); return 0; } c->ac_desc = (char *)malloc(AU_CLASS_DESC_MAX * sizeof(char)); if(c->ac_desc == 0) { free(c->ac_name); free(c); return 0; } return c; } void free_au_class_ent(struct au_class_ent *c) { if (c) { if (c->ac_name) free(c->ac_name); if (c->ac_desc) free(c->ac_desc); free(c); } } static struct au_class_ent *classfromstr(char *str, char *delim, struct au_class_ent *c) { char *classname, *classdesc, *classflag; char *last; classflag = strtok_r(str, delim, &last); classname = strtok_r(0, delim, &last); classdesc = strtok_r(0, delim, &last); if((classflag == 0) || (classname == 0) || (classdesc == 0)) { return 0; } if(strlen(classname) >= AU_CLASS_NAME_MAX) { return 0; } strcpy(c->ac_name, classname); if(strlen(classdesc) >= AU_CLASS_DESC_MAX) { return 0; } strcpy(c->ac_desc, classdesc); c->ac_class = strtoul(classflag, (char **) 0, 0); return c; } struct au_class_ent *getauclassent() { struct au_class_ent *c; char *tokptr, *nl; pthread_mutex_lock(&mutex); if((fp == 0) && ((fp = fopen(AUDIT_CLASS_FILE, "r")) == 0)) { pthread_mutex_unlock(&mutex); return 0; } if(fgets(linestr, AU_LINE_MAX, fp) == 0) { pthread_mutex_unlock(&mutex); return 0; } if((nl = strrchr(linestr, '\\n')) != 0) { *nl = '\\0'; } tokptr = linestr; c = get_class_area(); if(c == 0) { pthread_mutex_unlock(&mutex); return 0; } if(classfromstr(tokptr, delim, c) == 0) { free_au_class_ent(c); pthread_mutex_unlock(&mutex); return 0; } pthread_mutex_unlock(&mutex); return c; } struct au_class_ent *getauclassnam(const char *name) { struct au_class_ent *c; char *nl; if(name == 0) { return 0; } setauclass(); pthread_mutex_lock(&mutex); if((fp == 0) && ((fp = fopen(AUDIT_CLASS_FILE, "r")) == 0)) { pthread_mutex_unlock(&mutex); return 0; } c = get_class_area(); if(c == 0) { pthread_mutex_unlock(&mutex); return 0; } while(fgets(linestr, AU_LINE_MAX, fp) != 0) { if((nl = strrchr(linestr, '\\n')) != 0) { *nl = '\\0'; } if(classfromstr(linestr, delim, c) != 0) { if(!strcmp(name, c->ac_name)) { pthread_mutex_unlock(&mutex); return c; } } } free_au_class_ent(c); pthread_mutex_unlock(&mutex); return 0; } void setauclass() { pthread_mutex_lock(&mutex); if(fp != 0) { fseek(fp, 0, 0); } pthread_mutex_unlock(&mutex); } void endauclass() { pthread_mutex_lock(&mutex); if(fp != 0) { fclose(fp); fp = 0; } pthread_mutex_unlock(&mutex); }
1
#include <pthread.h> sem_t full; sem_t empty; pthread_mutex_t mutex; int buf[5]; int widx = 0; int ridx = 0; pthread_t threads[1 +1]; void* pro(void* arg) { int num = 0; int i; while(1){ sem_wait(&full); pthread_mutex_lock(&mutex); for(i=0; i<5; i++){ printf("%02d", i); if(buf[i] == -1) printf("null"); else printf("%d", buf[i]); if(i == widx) printf("-----"); printf("\\n"); } buf[widx] = num++; widx = (widx+1)%5; pthread_mutex_unlock(&mutex); sem_post(&empty); } } void* cus(void* arg) { int i; while(1){ sem_wait(&empty); pthread_mutex_lock(&mutex); for(i=0; i<5; i++){ printf("%02d", i); if(buf[i] == -1) printf("null"); else printf("%d", buf[i]); if(i == widx) printf("-----"); printf("\\n"); } buf[ridx]; ridx = (ridx+1)%5; pthread_mutex_unlock(&mutex); sem_post(&full); } } int main(void) { sem_init(&full, 0, 5); sem_init(&empty, 0, 0); pthread_mutex_init(&mutex, 0); int i =0 ; for(;i<1; i++){ int *p = (int*)malloc(sizeof(int)); *p = i; pthread_create(&threads[i], 0, pro, (void*)p); } for(i=0; i<1; i++){ int *p = (int*)malloc(sizeof(int)); *p = i; pthread_create(&threads[i], 0, cus, (void*)p); } for(i=0; i<1 +1; i++){ pthread_join(threads[i], 0); } pthread_mutex_destroy(mutex); sem_destroy(&empty); sem_destroy(&full); }
0
#include <pthread.h> void *Worker(void *); void InitializeGrids(double** grid1, double** grid2); void Barrier(); pthread_mutex_t barrier; pthread_cond_t go; int numArrived = 0; int gridSize, numWorkers, numIters, stripSize; double maxDiff[16]; double myms() { struct timeval tp; struct timezone tzp; int i; i = gettimeofday(&tp,&tzp); return ( (double) tp.tv_sec * 1.e+6 + (double) tp.tv_usec); } int main(int argc, char *argv[]) { pthread_t workerid[16]; pthread_attr_t attr; int i, j; double maxdiff = 0.0,tma=0.0; FILE *results; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); pthread_mutex_init(&barrier, 0); pthread_cond_init(&go, 0); if (argc < 4) { printf("jacobi size n_thread n_iter\\n"); exit(0); } gridSize = atoi(argv[1]); numWorkers = atoi(argv[2]); numIters = atoi(argv[3]); stripSize = gridSize/numWorkers; for (i = 0; i < numWorkers; i++) pthread_create(&workerid[i], &attr, Worker, (void *) i); for (i = 0; i < numWorkers; i++) pthread_join(workerid[i], 0); for (i = 0; i < numWorkers; i++) if (maxdiff < maxDiff[i]) maxdiff = maxDiff[i]; printf("number of iterations: %d\\nmaximum difference: %e\\n", numIters, maxdiff); } void *Worker(void *arg) { int myid = (int) arg; double maxdiff, temp; int i, j, iters; int first, last; double **grid1; double **grid2; unsigned long mask = 128; unsigned long maxnode = 8*sizeof(unsigned long); printf("worker %d (pthread id %d) has started\\n", myid, pthread_self()); grid1 = (double**)malloc((stripSize+3)*sizeof(double*)); grid2 = (double**)malloc((stripSize+3)*sizeof(double*)); for(i = 0; i <= stripSize; i++) { grid1[i] = (double*)malloc((gridSize+3)*sizeof(double)); grid2[i] = (double*)malloc((gridSize+3)*sizeof(double)); } Barrier(); InitializeGrids(grid1,grid2); for (iters = 1; iters <= numIters; iters++) { for (i = 1; i < stripSize; i++) { for (j = 1; j <= gridSize; j++) { grid2[i][j] = (grid1[i-1][j] + grid1[i+1][j] + grid1[i][j-1] + grid1[i][j+1]) * 0.25; } } Barrier(); for (i = 1; i < stripSize; i++) { for (j = 1; j <= gridSize; j++) { grid1[i][j] = (grid2[i-1][j] + grid2[i+1][j] + grid2[i][j-1] + grid2[i][j+1]) * 0.25; } } Barrier(); } maxdiff = 0.0; for (i = 1; i <= stripSize; i++) { for (j = 1; j <= gridSize; j++) { temp = grid1[i][j]-grid2[i][j]; if (temp < 0) temp = -temp; if (maxdiff < temp) maxdiff = temp; } } maxDiff[myid] = maxdiff; } void InitializeGrids(double **grid1, double **grid2) { int i, j; for (i = 0; i <= stripSize; i++) for (j = 0; j <= gridSize+1; j++) { grid1[i][j] = 0.0; grid2[i][j] = 0.0; } for (i = 0; i <= stripSize; i++) { grid1[i][0] = 1.0; grid1[i][gridSize+1] = 1.0; grid2[i][0] = 1.0; grid2[i][gridSize+1] = 1.0; } for (j = 0; j <= gridSize+1; j++) { grid1[0][j] = 1.0; grid2[0][j] = 1.0; grid1[stripSize][j] = 1.0; grid2[stripSize][j] = 1.0; } } 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); }
1
#include <pthread.h> int sum = 0; pthread_mutex_t sum_mutex; void *calculate( void * arg ) { printf("thread %d run ...\\n", *( (int *)arg ) ); printf("before calculate in thread %d sum is %d\\n", *( (int *)arg ), sum ); pthread_mutex_lock( &sum_mutex ); sum += *( (int *)arg ); pthread_mutex_unlock( &sum_mutex ); printf("after calculate in thread %d sum is %d\\n", *( (int *)arg ), sum ); printf("thread %d run ...\\n", *( (int *)arg ) ); return 0; } int main(int argc, char const *argv[]) { pthread_t myPhtread[10]; pthread_attr_t attr; int index, indexs[10]; int state; int count = atoi( argv[1] ) > 10? 10: atoi( argv[1] ); pthread_attr_init( &attr ); pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); pthread_mutex_init( &sum_mutex, 0 ); for( index = 0; index < count; index++ ) { indexs[ index ] = index; if( ( state = pthread_create( &myPhtread[index], &attr, calculate, ( void *)&indexs[index] ) ) != 0 ) printf("pthread_create error !\\n"); } pthread_attr_destroy( &attr ); for( index = 0; index < count; index++ ) if( ( state = pthread_join( myPhtread[index], 0 ) ) != 0) printf("pthread_join error !\\n"); pthread_mutex_destroy( &sum_mutex ); printf("finally sum is %d\\n", sum ); return 0; }
0
#include <pthread.h> pthread_mutex_t pth_mutex, pth_mutex_monitor; void vrrp_thread_mutex_lock(void) { pthread_mutex_lock(&pth_mutex); return; } void vrrp_thread_mutex_unlock(void) { pthread_mutex_unlock(&pth_mutex); return; } void vrrp_thread_mutex_lock_monitor(void) { pthread_mutex_lock(&pth_mutex_monitor); return; } void vrrp_thread_mutex_unlock_monitor(void) { pthread_mutex_unlock(&pth_mutex_monitor); return; } void * vrrp_thread_launch_vrrprouter(void *args) { int **args2 = (int **)args; struct vrrp_vr *vr = (struct vrrp_vr *)args2[0]; sem_t *sem = (sem_t *)args2[1]; int returnCode = 0; vr_ptr[vr_ptr_pos] = vr; vr_ptr_pos++; if (vr_ptr_pos == 255) { syslog(LOG_ERR, "cannot configure more than 255 VRID... exiting\\n"); exit(-1); } sem_post(sem); for (;;) { switch (vr->state) { case VRRP_STATE_INITIALIZE: returnCode = vrrp_state_initialize(vr); break; case VRRP_STATE_MASTER: returnCode = vrrp_state_master(vr); break; case VRRP_STATE_BACKUP: returnCode = vrrp_state_backup(vr); break; } if (returnCode < 0) { syslog(LOG_ERR, "vrid [%d] Cannot reach the correct state, disabled: %s\\n", vr->vr_id, strerror(errno)); pthread_exit(0); } } return 0; } char vrrp_thread_initialize(void) { if (pthread_mutex_init(&pth_mutex, 0) != 0) { syslog(LOG_ERR, "can't initialize thread for socket reading [ PTH_MUTEX, NULL ]"); return -1; } if (pthread_mutex_init(&pth_mutex_monitor, 0) != 0) { syslog(LOG_ERR, "can't initialize thread for socket reading [ PTH_MUTEX, NULL ]"); return -1; } return 0; } char vrrp_thread_create_vrid(struct vrrp_vr * vr) { pthread_t pth; pthread_attr_t pth_attr; sem_t sem; void *args[2]; if (sem_init(&sem, 0, 0) == -1) { syslog(LOG_ERR, "can't initialize an unnamed semaphore [ SEM, 0, 0 ]"); return -1; } if (pthread_attr_init(&pth_attr) != 0) { syslog(LOG_ERR, "can't initialize thread attributes [ PTH_ATTR ]"); return -1; } if (pthread_attr_setdetachstate(&pth_attr, PTHREAD_CREATE_DETACHED) != 0) { syslog(LOG_ERR, "can't set thread attributes [ PTH_ATTR, PTHREAD_CREATE_DETACHED ]"); return -1; } args[0] = vr; args[1] = &sem; if (pthread_create(&pth, &pth_attr, vrrp_thread_launch_vrrprouter, args) != 0) { syslog(LOG_ERR, "can't create new thread [ PTH, PTH_ATTR, VRRP_THREAD_READ_SOCKET ]"); return -1; } sem_wait(&sem); sem_destroy(&sem); return 0; } int vrrp_thread_create_moncircuit(void) { pthread_t pth; pthread_attr_t pth_attr; sem_t sem; int delay = VRRP_MONCIRCUIT_MONDELAY; void *args[2]; if (sem_init(&sem, 0, 0) == -1) { syslog(LOG_ERR, "can't initialize an unnamed semaphore [ SEM, 0, 0 ]"); return -1; } if (pthread_attr_init(&pth_attr) != 0) { syslog(LOG_ERR, "can't initialize thread attributes [ PTH_ATTR ]"); return -1; } if (pthread_attr_setdetachstate(&pth_attr, PTHREAD_CREATE_DETACHED) != 0) { syslog(LOG_ERR, "can't set thread attributes [ PTH_ATTR, PTHREAD_CREATE_DETACHED ]"); return -1; } args[0] = &delay; args[1] = &sem; if (pthread_create(&pth, &pth_attr, vrrp_moncircuit_monitor_thread, args) != 0) { syslog(LOG_ERR, "can't create new thread [ PTH, PTH_ATTR, VRRP_THREAD_READ_SOCKET ]"); return -1; } sem_wait(&sem); sem_destroy(&sem); return 0; }
1
#include <pthread.h> int mediafirefs_mkdir(const char *path, mode_t mode) { printf("FUNCTION: mkdir. path: %s\\n", path); (void)mode; char *dirname; int retval; char *basename; const char *key; struct mediafirefs_context_private *ctx; ctx = fuse_get_context()->private_data; pthread_mutex_lock(&(ctx->mutex)); dirname = strdup(path); if (dirname[strlen(dirname) - 1] == '/') { dirname[strlen(dirname) - 1] = '\\0'; } basename = strrchr(dirname, '/'); if (basename == 0) { fprintf(stderr, "cannot find slash\\n"); pthread_mutex_unlock(&(ctx->mutex)); return -ENOENT; } basename[0] = '\\0'; basename++; if (dirname[0] == '\\0') { key = 0; } else { key = folder_tree_path_get_key(ctx->tree, ctx->conn, dirname); } retval = mfconn_api_folder_create(ctx->conn, key, basename); if (retval != 0) { fprintf(stderr, "mfconn_api_folder_create unsuccessful\\n"); pthread_mutex_unlock(&(ctx->mutex)); return -EAGAIN; } free(dirname); folder_tree_update(ctx->tree, ctx->conn, 1); pthread_mutex_unlock(&(ctx->mutex)); return 0; }
0
#include <pthread.h> int thread_count; double sum = 0; int n = 1000000; pthread_mutex_t mutex; int flag = 0; void* thread_sum(void* rank){ long my_rank = (long) rank; int start = n / thread_count * my_rank; int end = n / thread_count * (my_rank + 1); double factor = 1; if (start % 2 == 1) factor = -1; double local_sum = 0; for (int i = start; i < end; i++, factor *= -1){ local_sum += factor / (2 * i + 1); } pthread_mutex_lock(&mutex); sum += local_sum; pthread_mutex_unlock(&mutex); return 0; } int main(int argc, char* argv[]){ if (argc < 2){ printf ("Not Enough Arguments\\n"); exit(0); } long thread; pthread_t* thread_handles; thread_count = strtol(argv[1], 0, 10); thread_handles = malloc(thread_count * sizeof(pthread_t)); pthread_mutex_init(&mutex, 0); 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); pthread_mutex_destroy(&mutex); sum *= 4; printf("Sum = %lf\\n", sum); free(thread_handles); return 0; }
1
#include <pthread.h> char buf[200] = {0}; pthread_mutex_t mutex; unsigned int flag = 0; void *func(void *arg) { sleep(1); while (flag == 0) { pthread_mutex_lock(&mutex); printf("本次输入了%d个字符\\n", strlen(buf)); memset(buf, 0, sizeof(buf)); pthread_mutex_unlock(&mutex); sleep(1); } pthread_exit(0); } int main(void) { int ret = -1; pthread_t th = -1; pthread_mutex_init(&mutex, 0); ret = pthread_create(&th, 0, func, 0); if (ret != 0) { printf("pthread_create error.\\n"); exit(-1); } printf("输入一个字符串,以回车结束\\n"); while (1) { pthread_mutex_lock(&mutex); scanf("%s", buf); pthread_mutex_unlock(&mutex); if (!strncmp(buf, "end", 3)) { printf("程序结束\\n"); flag = 1; break; } sleep(1); } printf("等待回收子线程\\n"); ret = pthread_join(th, 0); if (ret != 0) { printf("pthread_join error.\\n"); exit(-1); } printf("子线程回收成功\\n"); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> int stoj = 0; int minute_vedra = 0; int cakajuci_na_prestavku = 0; int brana = 0; pthread_mutex_t mutex_minute_vedra = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex_pocet_cakajucich = PTHREAD_MUTEX_INITIALIZER; sem_t sem_cakajuci_na_prestavku; sem_t sem_iduci_na_prestavku; void maluj(int id) { printf("%d maluje\\n", id); sleep(2); } void ber(int id) { printf("%d berie farbu\\n", id); pthread_mutex_lock(&mutex_minute_vedra); minute_vedra++; pthread_mutex_unlock(&mutex_minute_vedra); sleep(1); } void oddychuj(int id) { printf("Oddychuje %d\\n", id); sleep(2); } void *maliar( void *ptr ) { int id = (long)ptr; int minute_vedra = 0; while(!stoj) { maluj(id); if(stoj) break; ber(id); minute_vedra++; if(stoj) break; if((minute_vedra % 4) == 0) { printf("%d chce ist na prestavku\\n", id); sem_wait(&sem_cakajuci_na_prestavku); if(stoj) break; printf("%d sa dostal za prvy semafor\\n", id); pthread_mutex_lock(&mutex_pocet_cakajucich); cakajuci_na_prestavku++; printf("%d je za mutexom na pocet cakajucich\\n", id); if(cakajuci_na_prestavku == 3) { printf("%d ide posledny na prestavku\\n", id); int i; cakajuci_na_prestavku = 0; pthread_mutex_unlock(&mutex_pocet_cakajucich); for(i=0;i<(3 -1);i++) { sem_post(&sem_iduci_na_prestavku); sem_post(&sem_cakajuci_na_prestavku); sem_post(&sem_cakajuci_na_prestavku); sem_post(&sem_cakajuci_na_prestavku); } } else { printf("%d caka na poslednecho\\n", id); pthread_mutex_unlock(&mutex_pocet_cakajucich); sem_wait(&sem_iduci_na_prestavku); if(stoj) break; } oddychuj(id); } } printf("Maliar %d minul %d vedier\\n", id, minute_vedra); return 0; } int main(void) { long i; sem_init(&sem_cakajuci_na_prestavku, 0, 3); sem_init(&sem_iduci_na_prestavku, 0, 0); pthread_t maliari[10]; for (i=0;i<10;i++) pthread_create(&maliari[i], 0, &maliar, (void*)i); sleep(30); stoj = 1; for (i=0;i<10;i++) { sem_post(&sem_iduci_na_prestavku); sem_post(&sem_cakajuci_na_prestavku); } for (i=0;i<10;i++) pthread_join(maliari[i], 0); printf("Dokopi sa minulo %d vedier\\n", minute_vedra); exit(0); }
1
#include <pthread.h> void *bandCal(void *pa) { int i,check,flag; long long int *temp; float *tempNorm; int samp; int nacc; int bacc; int bandTVal; int nchans; samp=0; nchans = adc.nfft/2; nacc = adc.nacc; bacc = adc.bacc; temp = (long long int *) malloc(nchans*sizeof(long long int)); finalBand = (float*) malloc(nchans*sizeof(float)); tempNorm = (float*) malloc(sizeof(float)*nchans); pthread_mutex_lock(&foldStop_mutex); flag = foldStop; pthread_mutex_unlock(&foldStop_mutex); while(flag == 1) { pthread_mutex_lock(&foldStop_mutex); flag = foldStop; pthread_mutex_unlock(&foldStop_mutex); pthread_mutex_lock(&band_mutex); check = bandVal; pthread_mutex_unlock(&band_mutex); while(check != 1) { pthread_mutex_lock(&band_mutex); check = bandVal; pthread_mutex_unlock(&band_mutex); pthread_mutex_lock(&foldStop_mutex); flag = foldStop; pthread_mutex_unlock(&foldStop_mutex); if(flag==0) { free(temp); free(finalBand); free(tempNorm); return; } } for(i=0;i<nchans;i++) { temp[i]+=band[i]; } samp++; if(samp > (bacc)/(nacc*timeSample)) { for(i=0;i<nchans;i++) { tempNorm[i] = (float)((long double)temp[i]/(long double)samp); } pthread_mutex_lock(&finalBand_mutex); memcpy(finalBand,tempNorm,nchans*sizeof(float)); pthread_mutex_unlock(&finalBand_mutex); samp=0; } pthread_mutex_lock(&band_mutex); bandVal= 0; pthread_mutex_unlock(&band_mutex); } }
0
#include <pthread.h> pthread_t thread_1; pthread_t thread_2; int counter; pthread_mutex_t lock; void* thread_function(void *arg) { pthread_mutex_lock(&lock); counter += 1; printf("\\nJob %d started\\n", counter); sleep (2); printf("\\nJob %d finished\\n", counter); pthread_mutex_unlock(&lock); return 0; } int main(void) { if (pthread_mutex_init(&lock, 0) != 0) { printf("\\nPthread: mutex init failed\\n"); return 1; } pthread_create(&thread_1,0,thread_function,0); pthread_create(&thread_2,0,thread_function,0); pthread_join(thread_1,0); pthread_join(thread_2,0); pthread_mutex_destroy(&lock); return 0; }
1
#include <pthread.h> int threads_glob; pthread_mutex_t printer = PTHREAD_MUTEX_INITIALIZER; int parent, subrank; } somearg_t; void *subsome(void *argument) { somearg_t *ranks = (somearg_t*)argument; printf("Subthread %d of %d now responding\\n",ranks->subrank,ranks->parent); pthread_exit(0); } void *something(void *argument) { int rank = *(int*)argument; int i; pthread_t subhandle[3]; somearg_t arguments[3]; pthread_mutex_lock(&printer); printf("Thread with assigned rank %d of %d responding\\n",rank,threads_glob); pthread_mutex_unlock(&printer); for (i=0; i<0; i++) { arguments[i].parent = rank; arguments[i].subrank = i; pthread_create(&subhandle[i],0,subsome,&arguments[i]); pthread_join(subhandle[i],0); } pthread_exit(0); } int main(int argc, char *argv[]) { int threads, *rank; int i; int errcode; pthread_t *handle; threads = 1; for (i=1; i<argc&&argv[i][0]=='-'; i++) { if (argv[i][1]=='t') i++,sscanf(argv[i],"%d",&threads); } threads_glob = threads; handle = (pthread_t*)malloc(threads*sizeof(pthread_t)); rank = (int*)malloc(threads*sizeof(int)); for (i=0; i<threads; i++) { rank[i] = i; errcode = pthread_create(&handle[i],0,something,&rank[i]); assert(errcode==0); } for (i=0; i<threads; i++) { pthread_join(handle[i],0); } free(rank); free(handle); return 0; }
0
#include <pthread.h> int q[2]; int qsiz; pthread_mutex_t mq; void queue_init () { pthread_mutex_init (&mq, 0); qsiz = 0; } void queue_insert (int x) { int done = 0; printf ("prod: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz < 2) { done = 1; q[qsiz] = x; qsiz++; } pthread_mutex_unlock (&mq); } } int queue_extract () { int done = 0; int x = -1, i = 0; printf ("consumer: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz > 0) { done = 1; x = q[0]; qsiz--; for (i = 0; i < qsiz; i++) q[i] = q[i+1]; __VERIFIER_assert (qsiz < 2); q[qsiz] = 0; } pthread_mutex_unlock (&mq); } return x; } void swap (int *t, int i, int j) { int aux; aux = t[i]; t[i] = t[j]; t[j] = aux; } int findmaxidx (int *t, int count) { int i, mx; mx = 0; for (i = 1; i < count; i++) { if (t[i] > t[mx]) mx = i; } __VERIFIER_assert (mx >= 0); __VERIFIER_assert (mx < count); t[mx] = -t[mx]; return mx; } int source[7]; int sorted[7]; void producer () { int i, idx; for (i = 0; i < 7; i++) { idx = findmaxidx (source, 7); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 7); queue_insert (idx); } } void consumer () { int i, idx; for (i = 0; i < 7; i++) { idx = queue_extract (); sorted[i] = idx; printf ("m: i %d sorted = %d\\n", i, sorted[i]); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 7); } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; int i; __libc_init_poet (); for (i = 0; i < 7; i++) { source[i] = __VERIFIER_nondet_int(0,20); printf ("m: init i %d source = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); return 0; }
1
#include <pthread.h> double *a, *b, sum; int length; } DOTDATA; DOTDATA dotstr; pthread_mutex_t mutexsum; void *dotprod (void *rank){ int i, start, end, len; double my_sum, *x, *y; int my_rank = (int) rank; len = dotstr.length; start = my_rank*len; end = start + len; x = dotstr.a; y = dotstr.b; my_sum = 0; for(i = start; i<end; i++){ my_sum += x[i]*y[i]; } pthread_mutex_lock(&mutexsum); dotstr.sum += my_sum; pthread_mutex_unlock(&mutexsum); return 0; } int main(int argc, char *argv[]){ printf("%d\\n",atoi(argv[1])); int thread_num = atoi(argv[1]); pthread_t threads[thread_num]; int i; double *x = malloc(thread_num*10000000*sizeof(double)); double *y = malloc(thread_num*10000000*sizeof(double)); for (i = 0; i < thread_num*10000000; i++){ x[i] = 1; y[i] = 1; } dotstr.length = 10000000; dotstr.a = x; dotstr.b = y; dotstr.sum = 0; pthread_mutex_init(&mutexsum, 0); for(i = 0; i<thread_num; i++){ pthread_create(&threads[i], 0, dotprod, (void *) i); } for(i = 0; i<thread_num; i++){ pthread_join(threads[i], 0); } printf("Sum = %f\\n", dotstr.sum); free(x); free(y); pthread_mutex_destroy(&mutexsum); return 0; }
0
#include <pthread.h> int cine[7][20]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t kuz = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t consume_t = PTHREAD_COND_INITIALIZER; pthread_cond_t sits = PTHREAD_COND_INITIALIZER; pthread_cond_t produce_t = PTHREAD_COND_INITIALIZER; void compra(void* arg) { int sala, silla; int cont = 15; while(cont>0) { sala = rand()%7; silla = rand()%20; printf("soy %d, voy a la sala %d, y a la silla %d \\n", (int)arg,sala,silla); pthread_mutex_lock(&kuz); if(cine[sala][silla]==0) { cine[sala][silla]=1; printf("soy %d, voy a la sala %d, y a la silla %d YA RESERVE\\n", (int)arg,sala,silla); cont--; } else printf("soy %d, voy a la sala %d, y a la silla %d ESTABAN OCUPADOS\\n", (int)arg,sala,silla); pthread_mutex_unlock(&kuz); } printf("vi %d peliculas y me voy\\n",15); } int main() { int GUESTS = 3 +2 +2; srand((int)time(0)); pthread_mutex_lock(&kuz); int i, j; for(i=0;i<7;++i) for(j=0; j<20;++j) cine[i][j]=0; pthread_mutex_unlock(&kuz); pthread_t * compradores = (pthread_t *) malloc (sizeof(pthread_t) * GUESTS); int indice = 0; pthread_t * aux; for (aux = compradores; aux < (compradores+GUESTS); ++aux) { printf("comprador: %d \\n", ++indice); pthread_create(aux, 0, compra, (void *) indice); } for (aux = compradores; aux < (compradores+GUESTS); ++aux) pthread_join(*aux, 0); free(compradores); return 0; }
1
#include <pthread.h> pthread_mutex_t locki[32]; int inode[32]; pthread_mutex_t lockb[26]; int busy[26]; pthread_t tids[4]; void * thread_routine1() { int b1; int tid1 = 1; int i1 = tid1 % 32; pthread_mutex_lock(&locki[i1]); if(inode[i1] == 0) { b1 = (i1*2)%26; while(1) { pthread_mutex_lock(&lockb[b1]); if(!busy[b1]){ busy[b1] = 1; inode[i1] = b1+1; pthread_mutex_unlock(&lockb[b1]); break; } pthread_mutex_unlock(&lockb[b1]); b1 = (b1+1)%26; } } pthread_mutex_unlock(&locki[i1]); return 0; } void * thread_routine2() { int b2; int tid2 = 2; int i2 = tid2 % 32; pthread_mutex_lock(&locki[i2]); if(inode[i2] == 0) { b2 = (i2*2)%26; while(1) { pthread_mutex_lock(&lockb[b2]); if(!busy[b2]){ busy[b2] = 1; inode[i2] = b2+1; pthread_mutex_unlock(&lockb[b2]); break; } pthread_mutex_unlock(&lockb[b2]); b2 = (b2+1)%26; } } pthread_mutex_unlock(&locki[i2]); return 0; } void * thread_routine3() { int b3; int tid3 = 3; int i3 = tid3 % 32; pthread_mutex_lock(&locki[i3]); if(inode[i3] == 0) { b3 = (i3*2)%26; while(1) { pthread_mutex_lock(&lockb[b3]); if(!busy[b3]){ busy[b3] = 1; inode[i3] = b3+1; pthread_mutex_unlock(&lockb[b3]); break; } pthread_mutex_unlock(&lockb[b3]); b3 = (b3+1)%26; } } pthread_mutex_unlock(&locki[i3]); return 0; } void * thread_routine4() { int b4; int tid4 = 4; int i4 = tid4 % 32; pthread_mutex_lock(&locki[i4]); if(inode[i4] == 0) { b4 = (i4*2)%26; while(1) { pthread_mutex_lock(&lockb[b4]); if(!busy[b4]){ busy[b4] = 1; inode[i4] = b4+1; pthread_mutex_unlock(&lockb[b4]); break; } pthread_mutex_unlock(&lockb[b4]); b4 = (b4+1)%26; } } pthread_mutex_unlock(&locki[i4]); return 0; } int main () { int i=0; while (i < 32) { pthread_mutex_init(&locki[i], 0); i+=1; } i = 0; while (i < 32) { pthread_mutex_init(&lockb[i], 0); i+=1; } pthread_create(&tids[0], 0, thread_routine1, 0); pthread_create(&tids[1], 0, thread_routine2, 0); pthread_create(&tids[2], 0, thread_routine3, 0); pthread_create(&tids[3], 0, thread_routine4, 0); pthread_join(tids[0], 0); pthread_join(tids[1], 0); pthread_join(tids[2], 0); pthread_join(tids[3], 0); }
0
#include <pthread.h> int stmp = 3; void *refresher_child_common(void *param){ while(1) { pthread_mysleep(60 * 3); } } void refresher_init(){ pthread_t refresher_common ; pthread_create(&refresher_common, 0, refresher_child_common, 0); } void getTime(char *timing){ time_t rawtime; struct tm * timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); strftime(timing, 80, "%Y-%m-%d %H:%I:%S %p", timeinfo); } pthread_mutex_t fakeMutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t fakeCond = PTHREAD_COND_INITIALIZER; void pthread_mysleep(int s){ struct timespec timeToWait; struct timeval now; gettimeofday(&now,0); timeToWait.tv_sec = now.tv_sec + s; timeToWait.tv_nsec = now.tv_usec*1000; pthread_mutex_lock(&fakeMutex); pthread_cond_timedwait(&fakeCond, &fakeMutex, &timeToWait); pthread_mutex_unlock(&fakeMutex); }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *readCANData(void *canData) { char *mqttMessage; struct can_frame *frame = (struct can_frame *) canData; printf("Received data from CAN bus: %s\\n", frame->data); int size = asprintf(&mqttMessage, "ID: %d, Data: %s", frame->can_id, frame->data); if(size == -1) { printf("Malloc failed while construction of MQTT message.\\nCannot publish to MQTT\\n"); pthread_exit(0); } pthread_mutex_lock(&mutex); publishCANMessage(mqttMessage); pthread_mutex_unlock(&mutex); free(mqttMessage); pthread_exit(0); } int startCANListnerLoop(const char *interfaceName) { pthread_t tid; int s; int nbytes; struct sockaddr_can addr; struct can_frame frame; struct ifreq ifr; const char *ifname = interfaceName; if((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) { perror("Error while opening socket: "); return -1; } strncpy(ifr.ifr_name, ifname, strlen(ifname)); ioctl(s, SIOCGIFINDEX, &ifr); addr.can_family = AF_CAN; addr.can_ifindex = ifr.ifr_ifindex; printf("%s at index %d\\n", ifname, ifr.ifr_ifindex); if(bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("Error in socket bind: "); return -1; } while(1) { nbytes = read(s, &frame, sizeof(struct can_frame)); if(nbytes) { pthread_create(&tid, 0, readCANData, (void *)&frame); } } return 0; }
0
#include <pthread.h> int send_pkt( void *args) { struct ether_hdr *eth_header; struct ipv4_hdr *ipv4_header; struct udp_hdr *udp_header; unsigned char *payload_ptr; unsigned long int sentTime, seqNo = 1; int ret, index = 0; double prio; printf("STARTING SENDER\\n"); while(SND_PKT) { for (index = 0; index < NUM_INSTANCES; index++) { Message* pkg; if (BUF_TOKENS > 0) { pthread_mutex_lock(&ts_lock); if (priority_empty(pqueue)) { pthread_mutex_unlock(&ts_lock); continue; } pkg = priority_dequeue(pqueue); pthread_mutex_unlock(&ts_lock); BUF_TOKENS--; NUM_USED[pkg->num_packets]= NUM_USED[pkg->num_packets] + 1; printf("Dequeuing pkt of %d\\n", pkg->num_packets); if (BUF_TOKENS == 0) priority_reset(pqueue); } else { pthread_mutex_lock(&be_lock); if (fifo_empty()) { pthread_mutex_unlock(&be_lock); continue; } fifo_deq(&pkg); pthread_mutex_unlock(&be_lock); } struct rte_mbuf *send_bufs[1]; send_bufs[0] = pkg->buf; ret = rte_eth_tx_burst(TX_PORT_NO, TX_QUEUE_ID, send_bufs, 1); if (unlikely(ret < 1)) { for (index = ret; index < 1; index++) rte_pktmbuf_free(send_bufs[index]); } } } printf("DPDK SENDER: RETURNING ...\\n"); RCV_PKT = 0; return 0; }
1
#include <pthread.h> pthread_mutex_t lock; int needs_init = 1; void set_options() { convert_characters = 1; shrink_lines = 1; remove_empty_alt = 1; option_no_image = 1; option_no_alt = 1; convert_tags = 0; option_links = 0; option_links_inline = 0; option_title = 0; set_iconv_charset("utf-8"); errorlevel = 0; } char* vilistextum(char* text, int extractText) { if(text == 0) return 0; if(needs_init && pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 0; } needs_init = 0; pthread_mutex_lock(&lock); error = 0; set_options(); if(init_multibyte()) { open_files(text); html(extractText); quit(); } char* output = getOutput(strlen(text)); pthread_mutex_unlock(&lock); return output; }
0
#include <pthread.h> const int page_size = 4096; int64_t nr_block = 4096 * 10000; int64_t nr_total_pages = 4096 * 10000 * 8; static pthread_mutex_t *comp_done_lock; static pthread_cond_t *comp_done_cond; struct CompressParam { int start; int done; pthread_mutex_t mutex; pthread_cond_t cond; }; static CompressParam *comp_param; void error(char *msg) { perror(msg); exit(1); } struct thread_info { pthread_t thread_id; int thread_num; }; static void dirty_pages(void *mem_head) { char* var, *multiple_var; int64_t i, j; for (i = 0; i < (nr_block / page_size); ++i) { var = mem_head; var += i * page_size; *var = 'a'; } } static void *thread_start(void *opaque) { CompressParam *param = opaque; int64_t mem_size = nr_total_pages; void *mem_head = malloc(mem_size); if (mem_head == 0) { fprintf(stderr, "mem NULL\\n"); } int block_index = 0; while (1) { pthread_mutex_lock(&param->mutex); while (!param->start) { pthread_cond_wait(&param->cond, &param->mutex); } char *block = (char*)mem_head + block_index * nr_block; fprintf(stderr, "mem NULL 1\\n"); dirty_pages(block); fprintf(stderr, "mem NULL 2\\n"); param->start = 0; pthread_mutex_unlock(&param->mutex); pthread_mutex_lock(comp_done_lock); param->done = 1; pthread_cond_signal(comp_done_cond); pthread_mutex_unlock(comp_done_lock); block_index++; if (block_index == (nr_total_pages / nr_block)) { block_index = 0; } } } static inline void start_dirty_pages(CompressParam *param) { param->done = 0; pthread_mutex_lock(&param->mutex); param->start = 1; pthread_cond_signal(&param->cond); pthread_mutex_unlock(&param->mutex); } static void wait_dirty_pages_done() { int idx, thread_count; thread_count = 4; for (idx = 0; idx < thread_count; idx++) { if (!comp_param[idx].done) { pthread_mutex_lock(comp_done_lock); while (!comp_param[idx].done) { pthread_cond_wait(comp_done_cond, comp_done_lock); } pthread_mutex_unlock(comp_done_lock); } } } int main(int argc, char **argv) { int sockfd; int portno; int clientlen; struct sockaddr_in serveraddr; struct sockaddr_in clientaddr; struct hostent *hostp; char buf[1024]; char *hostaddrp; int optval; int n; if (argc != 2) { fprintf(stderr, "usage: %s <port>\\n", argv[0]); exit(1); } portno = atoi(argv[1]); sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) error("ERROR opening socket"); optval = 1; setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval , sizeof(int)); bzero((char *) &serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); serveraddr.sin_port = htons((unsigned short)portno); if (bind(sockfd, (struct sockaddr *) &serveraddr, sizeof(serveraddr)) < 0) error("ERROR on binding"); int tnum, s; void *res; struct thread_info *tinfo; tinfo = calloc(4, sizeof(struct thread_info)); if (tinfo == 0) fprintf(stderr, "calloc"); comp_param = malloc(sizeof(struct CompressParam) * 4); memset(comp_param, 0, sizeof(struct CompressParam) * 4); comp_done_cond = malloc(sizeof(pthread_cond_t)); memset(comp_done_cond, 0, sizeof(pthread_cond_t)); comp_done_lock = malloc(sizeof(pthread_mutex_t)); memset(comp_done_lock, 0, sizeof(pthread_mutex_t)); pthread_cond_init(comp_done_cond); pthread_mutex_init(comp_done_lock); for (tnum = 0; tnum < 4; tnum++) { tinfo[tnum].thread_num = tnum + 1; comp_param[tnum].done = 1; pthread_mutex_init(&comp_param[tnum].mutex); pthread_cond_init(&comp_param[tnum].cond); s = pthread_create(&tinfo[tnum].thread_id, 0, &thread_start, comp_param + tnum); if (s != 0) fprintf(stderr, "pthread_create"); } clientlen = sizeof(clientaddr); int i, val = 0; struct timeval t1, t2; long elapsed_time; while (1) { val++; n = recvfrom(sockfd, buf, 1024, 0, (struct sockaddr *) &clientaddr, &clientlen); if (n < 0) error("ERROR in recvfrom"); gettimeofday(&t1, 0); for (i = 0; i < 4; ++i) { start_dirty_pages(&comp_param[i]); } wait_dirty_pages_done(); gettimeofday(&t2, 0); elapsed_time= (((t2.tv_sec - t1.tv_sec)*1000000) + t2.tv_usec) - (t1.tv_usec); printf("%ld microseconds (us)\\n", elapsed_time); n = sendto(sockfd, &val, sizeof(val), 0, (struct sockaddr *) &clientaddr, clientlen); } for (tnum = 0; tnum < 4; tnum++) { s = pthread_join(tinfo[tnum].thread_id, &res); if (s != 0) fprintf(stderr, "pthread_join"); } }
1
#include <pthread.h> int total = 0; pthread_mutex_t mutex; void *count_txt(void *t){ long thread_id = (long)t; char c; printf("Here is %lu\\n", pthread_self()); while((c=fgetc(t))!=EOF) { pthread_mutex_lock(&mutex); total++; pthread_mutex_unlock(&mutex); } pthread_exit(0); } int main(int arc, char *argv[]) { int pid,pid_t,i; FILE *fp[2]; char ch; char *para[] = {"./a1","./a2"}; pthread_t threads[2]; int rc; for(i=0;i<2;i++) { if((fp[i]=fopen(para[i],"w+"))==0) { printf("cannot open this file.\\n"); exit(0); } } while((pid=fork())==-1); if(pid==0) { for(i=0;i<2;i++) { fputc(ch,fp[i]); getchar(); } fclose(fp[0]); fclose(fp[1]); exit(1); } wait(0); pthread_mutex_init(&mutex, 0); fseek(fp[0],0,0); fseek(fp[1],0,0); rc = pthread_create(&threads[0],0,count_txt,(void *)fp[0]); rc = pthread_create(&threads[1],0,count_txt,(void *)fp[1]); if (rc) { perror("error"); exit(1); } pthread_join(threads[0],0); pthread_join(threads[1],0); pthread_mutex_destroy(&mutex); printf("a1、a2文件中共有: %d个字符\\n",total); fclose(fp[0]); fclose(fp[1]); while((pid_t=vfork())==-1); if(pid_t==0) { execl("./change",para[0],para[1],0); exit(0); } wait(0); }
0
#include <pthread.h> int mediafirefs_access(const char *path, int mode) { printf("FUNCTION: access. path: %s\\n", path); (void)path; (void)mode; struct mediafirefs_context_private *ctx; ctx = fuse_get_context()->private_data; pthread_mutex_lock(&(ctx->mutex)); fprintf(stderr, "access is a no-op\\n"); pthread_mutex_unlock(&(ctx->mutex)); return 0; }
1
#include <pthread.h> pthread_mutex_t lock; void *hold(void *arg) { pthread_mutex_lock(&lock); usleep(10000); pthread_mutex_unlock(&lock); return arg; } void *wait(void *arg) { pthread_mutex_lock(&lock); pthread_mutex_unlock(&lock); return arg; } int main() { int ret; const int THREAD_COUNT = 50; pthread_t thread[THREAD_COUNT]; ret = pthread_mutex_init(&lock, 0); if (ret) { fprintf(stderr, "pthred_mutex_init, error: %d\\n", ret); return ret; } ret = pthread_create(&thread[0], 0, hold, 0); if (ret) { fprintf(stderr, "pthread_create, error: %d\\n", ret); return ret; } for (int i = 1; i < THREAD_COUNT; i++) { ret = pthread_create(&thread[i], 0, wait, 0); if (ret) { fprintf(stderr, "pthread_create, error: %d\\n", ret); return ret; } } for (int i = 0; i < THREAD_COUNT; i++) { ret = pthread_join(thread[i], 0); if (ret) { fprintf(stderr, "pthread_join, error: %d\\n", ret); return ret; } } ret = pthread_mutex_destroy(&lock); if (ret) { fprintf(stderr, "pthread_mutex_destroy, error: %d\\n", ret); return ret; } return 0; }
0
#include <pthread.h> int nextCustomerNo = 1; int first = 0, last = 0; int waitingCustomerCount = 0; pthread_mutex_t lck; pthread_cond_t custCond[4]; int custNos[4]; pthread_cond_t brbrCond; void WakeUpBarber() { pthread_cond_signal(&brbrCond); } void CustomerWait(int chair) { pthread_cond_wait(&custCond[chair], &lck); } int CheckVacancyAndWait(void) { int chair; int custNo; pthread_mutex_lock(&lck); if (waitingCustomerCount == 4) { pthread_mutex_unlock(&lck); return 0; } else { chair = last; custNo = custNos[chair] = nextCustomerNo++; last = (chair + 1) % 4; waitingCustomerCount++; if (waitingCustomerCount == 1) WakeUpBarber(); CustomerWait(chair); pthread_mutex_unlock(&lck); return custNo; } } int CheckCustomerAndSleep(void) { pthread_mutex_lock(&lck); if (waitingCustomerCount == 0) pthread_cond_wait(&brbrCond, &lck); } void ServiceCustomer() { int custNo; int chair; chair = first; first = (first + 1) % 4; custNo = custNos[chair]; waitingCustomerCount--; pthread_cond_signal(&custCond[chair]); pthread_mutex_unlock(&lck); printf("Barber servicing %d customer\\n",custNo); sleep(3); } void *Barber(void *k) { while (1) { CheckAndSleep(); ServiceCustomer(); } } void * Customer(void) { int custno; while (1) { custno = CheckVacancyAndWait(); if (custno != 0) { printf("Customer %d getting serviced ...\\n",custno); sleep(3); } else { printf("No chair is vacant and customer leaving ...\\n"); sleep((time(0) % 5) + 1); } } } int main(void) { Initialize(); pthread_t brbr, cust[4 +1]; pthread_create(&brbr, 0, Barber, 0); for (int i=0; i<4 +1; i++) pthread_create(&cust[i], 0, *Customer, 0); for ( ; ; ) ; return 0; }
1
#include <pthread.h> pthread_mutex_t number_mutex1; pthread_mutex_t number_mutex2; int globalnumber1 = 10; void thread2(void *arg); void thread1(void *arg); int main(void) { int status; pthread_t thid1,thid2; pthread_mutex_init(& number_mutex1,PTHREAD_MUTEX_TIMED_NP); pthread_mutex_init(& number_mutex2,PTHREAD_MUTEX_TIMED_NP); if(pthread_create(&thid1,0,(void *)thread1,0) != 0){ printf("thid1 create failed\\n"); } if(pthread_create(&thid2,0,(void *)thread2,0) != 0){ printf("thid2 create failed\\n"); } pthread_join(thid1,(void *)&status); pthread_join(thid2,(void *)&status); return 0; } void thread2(void *arg) { int temp=0; sleep(2); pthread_mutex_lock(& number_mutex2); globalnumber1++; temp=globalnumber1; pthread_mutex_unlock(& number_mutex2); printf("i am thread2,my temp=%d\\n",temp); pthread_exit(0); } void thread1(void *arg) { pthread_mutex_lock(& number_mutex1); globalnumber1++; printf("i am thread1,my globalnumber=%d\\n",globalnumber1); sleep(5); pthread_mutex_unlock(& number_mutex1); pthread_exit(0); }
0
#include <pthread.h> long long counter_max; long long counter = 0; pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER; double *sum_res; void printout_the_result(double pi); void *pi_thread(void *arg) { double sum; long long i, beg, end, unit; while (1) { pthread_mutex_lock(&counter_mutex); unit = counter; counter++; pthread_mutex_unlock(&counter_mutex); if (unit>=counter_max) return 0; beg = unit*1000000; end = beg + 1000000; sum = 0.0; for (i=beg+1;i<end;i+=4) sum += 1.0/(double)i - 1.0/(double)(i+2); sum_res[unit] = sum*4.0; } return 0; } int main(int argn, char *arg[]) { pthread_t *tid; double pi; int i, n; if (argn!=3) return printf("Usage: pi <n_threads> <N>\\n"); n = atol(arg[1]); counter_max = atol(arg[2]); printf("\\nN = %lldx1000000\\n", counter_max); sum_res = (double *)malloc(counter_max*sizeof(double)); tid = (pthread_t *)malloc(n*sizeof(pthread_t)); printf("Running %d threads...\\n", n); for (i=0;i<n;i++) pthread_create(tid+i, 0, pi_thread, 0); for (i=0;i<n;i++) pthread_join(tid[i], 0); pi = 0.0; for (i=0;i<counter_max;i++) pi += sum_res[i]; printout_the_result(pi); free(sum_res); free(tid); return 0; } void printout_the_result(double pi) { int sig_figures; char str_correct[32]; char str_wrong[32]; sig_figures = (int)(-log10(fabs((pi-M_PI)/M_PI))); if (sig_figures<0) sig_figures=0; if (sig_figures>30) sig_figures=30; sprintf(str_correct, "%19.17lf", pi); sprintf(str_wrong, "%19.17lf", pi); str_correct[sig_figures+1] = 0; printf("pi = \\033[32;1m%s\\033[0m%s (%d sig-figs)\\n\\n", str_correct, str_wrong+sig_figures+1, sig_figures); }
1
#include <pthread.h> struct data{ int threadID; pthread_cond_t cond; }; pthread_t threads[4]; unsigned long queue_pos = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; sem_t sem; sem_t queue[4 + 1]; int q_size = 0; int q_front = 0; void _queue_push(sem_t *sem) { q_size++; } void _queue_pop() { q_front++; } void smf_wait() { sem_t *sp; pthread_mutex_lock(&mutex); if(sem_trywait(&sem) == 0) pthread_mutex_unlock(&mutex); else { sp = (sem_t *)malloc(sizeof(sem_t)); sem_init(sp, 0, 0); _queue_push(sp); pthread_mutex_unlock(&mutex); sem_wait(sp); sem_destroy(sp); free(sp); } } void smf_sig() { sem_t *sp; pthread_mutex_lock(&mutex); if(q_size == 0) sem_post(&sem); else { _queue_pop(); sem_post(sp); } pthread_mutex_unlock(&mutex); } void * thread_print(void *arg) { struct data *d = (struct data*)arg; printf("Starting thread %d\\n", d->threadID); smf_wait(); printf("Thread ID: %d \\n", d->threadID); return 0; } int main( int argc, const char* argv[] ) { struct data d[4]; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); sem_init(&sem, 0, 4); pthread_mutex_init(&mutex, 0); for(int i = 0; i < 4; ++i) { d[i].threadID = i; if(pthread_create(&threads[i], &attr, thread_print, (void*)&d[i]) != 0) { perror("Cannot create thread"); exit(1); } } for(int i = 0; i < 4; ++i) pthread_join(threads[i], 0); pthread_attr_destroy(&attr); pthread_mutex_destroy(&mutex); sem_destroy(&sem); return 0; }
0
#include <pthread.h> int rc=0,wc=0,val; pthread_mutex_t mutex1,mwrite,mread,rallow; pthread_t tr1,tr2,tw1,tw2; pthread_attr_t tr1attr,tr2attr,tw1attr,tw2attr; void *writer(); void *reader(); int main() { pthread_mutex_init(&mwrite,0); pthread_mutex_init(&mread,0); pthread_mutex_init(&rallow,0); pthread_mutex_init(&mutex1,0); pthread_attr_init(&tw1attr); pthread_attr_init(&tr1attr); pthread_attr_init(&tr2attr); pthread_attr_init(&tw2attr); printf("\\n Writer 1 created"); pthread_create(&tw1,&tw1attr,writer,0); printf("\\n Reader 1 created"); pthread_create(&tr1,&tr1attr,reader,0); printf("\\n Reader 2 created"); pthread_create(&tr2,&tr2attr,reader,0); printf("\\n WRITER 2 created"); pthread_create(&tw2,&tw2attr,writer,0); pthread_join(tw1,0); pthread_join(tr1,0); pthread_join(tr2,0); pthread_join(tw2,0); return 0; } void *writer() { pthread_mutex_lock(&mwrite); wc++; if(wc==1) pthread_mutex_lock(&rallow); pthread_mutex_unlock(&mwrite); pthread_mutex_lock(&mutex1); printf("\\n Enter data in writer %d",wc); scanf("%d",&val); pthread_mutex_unlock(&mutex1); pthread_mutex_lock(&mwrite); wc--; if(wc==0) pthread_mutex_unlock(&rallow); pthread_mutex_unlock(&mwrite); pthread_exit(0); } void *reader() { pthread_mutex_lock(&rallow); pthread_mutex_lock(&mread); rc++; if(rc==1) pthread_mutex_lock(&mutex1); pthread_mutex_unlock(&mread); pthread_mutex_unlock(&rallow); printf("\\n reader %d read data: %d",rc,val); pthread_mutex_lock(&mread); rc--; if(rc==0) pthread_mutex_unlock(&mutex1); pthread_mutex_unlock(&mread); pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t lock_data_init; int data_init() { pthread_mutex_lock(&lock_data_init); if (g_data_info.count == 0) { sem_init(&g_data_info.sem, 0, 0); g_data_info.wqueue = wqueueCreate( DATA_WQUEUE_SIZE); } g_data_info.count++; pthread_mutex_unlock(&lock_data_init); return 1; } int data_destroy() { pthread_mutex_lock(&lock_data_init); if (g_data_info.count == 1) { sem_destroy(&g_data_info.sem); wqueueDestroy(g_data_info.wqueue); } g_data_info.count--; pthread_mutex_unlock(&lock_data_init); return -1; } void *dataThread(void *argv) { void *buf; sem_post(&g_thread_sem); while (1) { sem_wait(&g_data_info.sem); pthread_mutex_lock(&g_data_info.lock); buf = wqueuePop(g_data_info.wqueue); pthread_mutex_unlock(&g_data_info.lock); if (buf == 0) { printf("Error:dataThread\\n"); continue; } if ( *((unsigned short*)buf) == MSG_D2MCE_TERMINAL) { mem_free(buf); break; } else if (*((unsigned short*)buf) == MSG_SM_INIT) { sm_init_reply(buf); } else if (*((unsigned short*)buf) == MSG_SM_READMISS) { sm_readmiss_reply(buf); } else if (*((unsigned short*)buf) == MSG_SM_FETCH) { sm_fetch_reply(buf); } else if (*((unsigned short*)buf) == MSG_SM_WRITEMISS || *((unsigned short*)buf) == MSG_SM_WRITEMISS_NOREPLY) { sm_writemiss_reply(buf); } else if (*((unsigned short*)buf) == MSG_SM_INVALID || *((unsigned short*)buf) == MSG_SM_INVALID_NOREPLY) { sm_invalid_reply(buf); } else if (*((unsigned short*)buf) == MSG_SM_INVALID_OK) { sm_invalid_ok(buf); } else if (*((unsigned short*)buf) == MSG_SM_MULTIREAD) { sm_multiread_reply(buf); } else if (*((unsigned short*)buf) == MSG_SM_MULTIWRITE) { sm_multiwrite_reply(buf); } else if (*((unsigned short*)buf) == MSG_SM_IAMHOME) { sm_sethome_reply(buf); } else if (*((unsigned short*)buf) == MSG_SM_NEWHOME) { sm_newhome_reply(buf); } else if (*((unsigned short*)buf) == MSG_SM_HOME_READY) { sm_homeready_reply(buf); } mem_free(buf); } return 0; } int dataThread_close() { void *buf; buf = mem_malloc(64); ((struct request_header*)buf)->msg_type = MSG_D2MCE_TERMINAL; pthread_mutex_lock(&g_data_info.lock); wqueuePush(g_data_info.wqueue, buf); pthread_mutex_unlock(&g_data_info.lock); sem_post(&g_data_info.sem); return 1; }
0
#include <pthread.h> void thread_list_join_destroy(struct thread_list *list) { struct thread_list_node *current = list->head; while (current) { pthread_join(current->thread, 0); free(current->arg); current->arg = 0; current->thread = 0; current = current->next; } current = list->head; while (list->head) { current = list->head; list->head = current->next; free(current); } list->tail = 0; pthread_mutex_destroy(&list->lock); } int thread_list_add(struct thread_list *list, void *(*fn)(void *), void *arg, size_t arg_sz) { struct thread_list_node *node; int error; if (!(node = malloc(sizeof(struct thread_list_node)))) return errno; if (!(node->arg = malloc(arg_sz))) { free(node); return errno; } memcpy(node->arg, arg, arg_sz); node->arg_sz = arg_sz; pthread_mutex_lock(&list->lock); node->threadnum = list->lastnum + 1; if (list->tail) node->next = list->tail->next; else node->next = 0; error = pthread_create(&node->thread, 0, fn, node->arg); if (error) { free(node->arg); free(node); pthread_mutex_unlock(&list->lock); return error; } if (list->tail) list->tail->next = node; if (!list->head) list->head = node; list->tail = node; list->lastnum++; pthread_mutex_unlock(&list->lock); return 0; } unsigned thread_list_num_of(struct thread_list *list, pthread_t thread) { struct thread_list_node *current; unsigned threadnum = -1; pthread_mutex_lock(&list->lock); current = list->head; while (current) { if (current->thread == thread) threadnum = current->threadnum; current = current->next; } pthread_mutex_unlock(&list->lock); return threadnum; }
1
#include <pthread.h> char* my_name; char* test_name; int num_threads; long long length; int test_argc; void** test_argv; } parsed_args_t; int (*setup)(int, long long, int, void**); int (*execute)(int, int, long long, int, void**); int (*cleanup)(int, long long); char** error_str_ptr; } test_t; parsed_args_t args; test_t test; int ready_thread_count; pthread_mutex_t ready_thread_count_lock; pthread_cond_t start_cvar; pthread_cond_t threads_ready_cvar; int parse_args(int argc, char** argv, parsed_args_t* parsed_args) { if(argc != 4) { return -1; } parsed_args->my_name = argv[0]; parsed_args->test_name = argv[1]; parsed_args->num_threads = atoi(argv[2]); parsed_args->length = strtoll(argv[3], 0, 10); parsed_args->test_argc = 0; parsed_args->test_argv = 0; return 0; } void print_usage(char** argv) { printf("Usage: %s test_name threads length\\n", argv[0]); } int find_test(char* test_name, char* test_path) { char binpath[MAXPATHLEN]; char* dirpath; uint32_t size = sizeof(binpath); int retval; retval = _NSGetExecutablePath(binpath, &size); assert(retval == 0); dirpath = dirname(binpath); snprintf(test_path, MAXPATHLEN, "%s/perfindex-%s.dylib", dirpath, test_name); if(access(test_path, F_OK) == 0) return 0; else return -1; } int load_test(char* path, test_t* test) { void* handle; void* p; handle = dlopen(path, RTLD_NOW | RTLD_LOCAL); if(!handle) { return -1; } p = dlsym(handle, "setup"); test->setup = (int (*)(int, long long, int, void **))p; p = dlsym(handle, "execute"); test->execute = (int (*)(int, int, long long, int, void **))p; if(p == 0) return -1; p = dlsym(handle, "cleanup"); test->cleanup = (int (*)(int, long long))p; p = dlsym(handle, "error_str"); test->error_str_ptr = (char**)p; return 0; } void start_timer(struct timeval *tp) { gettimeofday(tp, 0); } void end_timer(struct timeval *tp) { struct timeval tend; gettimeofday(&tend, 0); if(tend.tv_usec >= tp->tv_usec) { tp->tv_sec = tend.tv_sec - tp->tv_sec; tp->tv_usec = tend.tv_usec - tp->tv_usec; } else { tp->tv_sec = tend.tv_sec - tp->tv_sec - 1; tp->tv_usec = tend.tv_usec - tp->tv_usec + 1000000; } } void print_timer(struct timeval *tp) { printf("%ld.%06d\\n", tp->tv_sec, tp->tv_usec); } static void* thread_setup(void *arg) { int my_index = (int)arg; long long work_size = args.length / args.num_threads; int work_remainder = args.length % args.num_threads; if(work_remainder > my_index) { work_size++; } pthread_mutex_lock(&ready_thread_count_lock); ready_thread_count++; if(ready_thread_count == args.num_threads) pthread_cond_signal(&threads_ready_cvar); pthread_cond_wait(&start_cvar, &ready_thread_count_lock); pthread_mutex_unlock(&ready_thread_count_lock); test.execute(my_index, args.num_threads, work_size, args.test_argc, args.test_argv); return 0; } int main(int argc, char** argv) { int retval; int thread_index; struct timeval timer; pthread_t* threads; int thread_retval; void* thread_retval_ptr = &thread_retval; char test_path[MAXPATHLEN]; retval = parse_args(argc, argv, &args); if(retval) { print_usage(argv); return -1; } retval = find_test(args.test_name, test_path); if(retval) { printf("Unable to find test %s\\n", args.test_name); return -1; } load_test(test_path, &test); if(retval) { printf("Unable to load test %s\\n", args.test_name); return -1; } pthread_cond_init(&threads_ready_cvar, 0); pthread_cond_init(&start_cvar, 0); pthread_mutex_init(&ready_thread_count_lock, 0); ready_thread_count = 0; if(test.setup) { retval = test.setup(args.num_threads, args.length, 0, 0); if(retval == PERFINDEX_FAILURE) { fprintf(stderr, "Test setup failed: %s\\n", *test.error_str_ptr); return -1; } } threads = (pthread_t*)malloc(sizeof(pthread_t)*args.num_threads); for(thread_index = 0; thread_index < args.num_threads; thread_index++) { retval = pthread_create(&threads[thread_index], 0, thread_setup, (void*)(long)thread_index); assert(retval == 0); } pthread_mutex_lock(&ready_thread_count_lock); if(ready_thread_count != args.num_threads) { pthread_cond_wait(&threads_ready_cvar, &ready_thread_count_lock); } pthread_mutex_unlock(&ready_thread_count_lock); start_timer(&timer); pthread_cond_broadcast(&start_cvar); for(thread_index = 0; thread_index < args.num_threads; thread_index++) { pthread_join(threads[thread_index], &thread_retval_ptr); if(**test.error_str_ptr) { printf("Test failed: %s\\n", *test.error_str_ptr); } } end_timer(&timer); if(test.cleanup) retval = test.cleanup(args.num_threads, args.length); if(retval == PERFINDEX_FAILURE) { fprintf(stderr, "Test cleanup failed: %s\\n", *test.error_str_ptr); free(threads); return -1; } print_timer(&timer); free(threads); return 0; }
0
#include <pthread.h> int main(int argc, char* argv[]){ char comando[80]; pthread_mutexattr_t mattr; pthread_mutex_init(&mutex_config, &mattr); pthread_mutex_init(&mutex_tlb, &mattr); pthread_mutex_init(&mutex_cpu, &mattr); pthread_mutex_init(&mutex_swap, &mattr); pthread_mutex_init(&mutex_page_table, &mattr); pthread_mutex_init(&mutex_frames, &mattr); pthread_mutex_init(&mutex_memory, &mattr); LOG = log_create("UMC.log","UMC.c",0,1); if (argc != 2){ log_error(LOG, "No se indicó la ruta del archivo de configuración"); return 1; } else config = get_config(argv[1], LOG); if (string_is_empty(config.IP_SWAP) || string_is_empty(config.PUERTO) || string_is_empty(config.PUERTO_SWAP)) { return 1; } if(create_struct_memory()){ log_error(LOG, "Error al crear espacio de memoria principal"); return 1; }else{ list_cpu = list_create(); } void* arg_server; pthread_attr_t attr; pthread_t server_thread; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_create(&server_thread, &attr, &main_server, arg_server); pthread_attr_destroy(&attr); printf("*******************************************************************\\n"); printf("* Consola UMC Grupo Lajew *\\n"); printf("*******************************************************************\\n"); printf("* Comando ayuda: help *\\n"); printf("*******************************************************************\\n"); do{ printf("UMC-UTN-GrupoLAJEW<>~: "); fgets(comando,80,stdin); if (!strcmp(comando, "retardo\\n")){ char retardo[80] = ""; printf("\\nUMC-UTN-GrupoLAJEW<>~/Retardo: "); fgets(retardo,80,stdin); char* retardo_val = string_substring(retardo, 0, string_length(retardo)-1); if(!string_equals_ignore_case(retardo_val, "0")){ pthread_mutex_lock( &mutex_config ); config.RETARDO = atoi(retardo_val); pthread_mutex_unlock( &mutex_config ); } }else{ } if (!strcmp(comando, "dump -struct\\n")){ printf("\\nUMC-UTN-GrupoLAJEW<>~/Dump-Struct: **Eligió mostrar un reporte de las estructuras de memoria. Elija un PID(0 para mostrar toda la memoria)**"); char pid[80]; printf("\\nUMC-UTN-GrupoLAJEW<>~/Dump-Struct/PID: "); fgets(pid, 80, stdin); int pid_nro = atoi(pid); dump_struct(pid_nro); }else{ if (!strcmp(comando, "dump -content\\n")){ printf("\\nUMC-UTN-GrupoLAJEW<>~/Dump-Content: **Eligió mostrar un reporte del contenido de memoria. Elija un PID(0 para mostrar toda la memoria)**"); char pid[80]; printf("\\nUMC-UTN-GrupoLAJEW<>~/Dump-Content/PID: "); fgets(pid, 80, stdin); int pid_nro = atoi(pid); if(pid_nro != 0){ dump_content(pid_nro); }else{ dump_content_all(); } } } if (!strcmp(comando, "flush -tlb\\n")){ log_info(LOG, "Se requiere realizar un flush de la TLB"); if( config.ENTRADAS_TLB > 0){ clean_tlb(); log_info(LOG, "Flush realizado. TLB limpia!"); printf("TLB limpia!\\n"); }else{ log_info(LOG, "TLB no activa para flush"); printf("TLB no activa\\n"); } }else{ if (!strcmp(comando, "flush -memory\\n")){ log_info(LOG, "Se requiere setear todas las páginas en modificado"); usleep(config.RETARDO * 1000); set_modif_all_pages(); log_info(LOG, "Todas las páginas fueron seteadas como modificadas."); printf("Páginas actualizadas con bit de modificación\\n"); } } if (!strcmp(comando, "help\\n")){ printf("\\n"); printf("**** La consola de éste proceso comprende los siguientes comandos: \\n"); printf(" - retardo: Éste comando modifica el valor en milisegundos del retardo para acceso a memoria \\n"); printf(" - flush -<parametro>: Dependiendo el valor del parámetro se realizan las siguientes acciones: \\n"); printf(" .memory: Éste comando marca todas las páginas presentes en memoria como modificadas \\n"); printf(" Ejemplo: flush -memory \\n"); printf(" .tlb: Éste comando limpia la TLB \\n"); printf(" Ejemplo: flush -tlb \\n"); printf(" - dump -<parametro>: Dependiendo del valor del parámetro se muestra un listado de: \\n"); printf(" .struct: Éste comando muestra un reporte de las estructuras de memoria de uno o todos los procesos\\n"); printf(" .content: Éste comando muestra un reporte del contenido de memoria\\n"); printf(" - exit: Salir\\n"); printf("****\\n"); printf("\\n"); } }while(strcmp(comando, "exit\\n")); destroy_struct_memory(); log_destroy(LOG); printf("LOG destruído"); pthread_exit(0); return 0; }
1
#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; 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; pthread_mutex_unlock(&my); x = x + x + a; pthread_mutex_unlock(&mx); assert(x!=27); return 0; } void *thread2() { x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; return 0; } void *thread3() { pthread_mutex_lock(&my); y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; pthread_mutex_unlock(&my); 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; }
0
#include <pthread.h> struct donut_ring shared_ring; pthread_mutex_t prod [NUMFLAVORS]; pthread_mutex_t cons [NUMFLAVORS]; pthread_cond_t prod_cond [NUMFLAVORS]; pthread_cond_t cons_cond [NUMFLAVORS]; pthread_t thread_id [NUMPRODUCERS+NUMCONSUMERS], sig_wait_id; ushort get_time_microseconds() { struct timeval randtime; gettimeofday(&randtime, (struct timezone *) 0); return randtime.tv_usec; } int main ( int argc, char *argv[] ) { int i, j, k, nsigs; struct timeval randtime, first_time, last_time; int arg_array[NUMPRODUCERS+NUMCONSUMERS]; struct sched_param sched_struct; gettimeofday (&first_time, (struct timezone *) 0 ); for ( i = 0; i < NUMPRODUCERS+NUMCONSUMERS; i++ ) { arg_array [i] = i+1; } for ( i = 0; i < NUMFLAVORS; i++ ) { pthread_mutex_init ( &prod [i], 0 ); pthread_mutex_init ( &cons [i], 0 ); pthread_cond_init ( &prod_cond [i], 0 ); pthread_cond_init ( &cons_cond [i], 0 ); shared_ring.outptr [i] = 0; shared_ring.in_ptr [i] = 0; shared_ring.serial [i] = 1; shared_ring.space_count [i] = NUMSLOTS; shared_ring.donut_count [i] = 0; } for ( i = 0; i < NUMCONSUMERS; i++) { if ( pthread_create ( &thread_id [i], 0, consumer, ( void * )&arg_array [i]) != 0 ){ printf ( "pthread_create failed" ); exit ( 3 ); } } for ( ; i < NUMPRODUCERS+NUMCONSUMERS; i++ ) { if ( pthread_create ( &thread_id [i], 0, producer, ( void * )&arg_array [i]) != 0 ){ printf ( "pthread_create failed" ); exit ( 3 ); } } for ( i = 0; i < NUMCONSUMERS; i++ ) pthread_join ( thread_id [i], 0 ); gettimeofday (&last_time, ( struct timezone * ) 0 ); if ( ( i = last_time.tv_sec - first_time.tv_sec) == 0 ) j = last_time.tv_usec - first_time.tv_usec; else{ if ( last_time.tv_usec - first_time.tv_usec < 0 ) { i--; j = 1000000 + ( last_time.tv_usec - first_time.tv_usec ); } else { j = last_time.tv_usec - first_time.tv_usec; } } printf ( "\\n\\nElapsed consumer time is %d sec and %d usec\\n", i, j ); printf ( "\\n\\n ALL CONSUMERS FINISHED, KILLING PROCESS\\n\\n" ); exit ( 0 ); } void *producer ( void *arg ) { int i, j, k,id; int donut_flavor_count,donut_flavor_buffer; unsigned short xsub [3]; struct timeval randtime; id = *( int * ) arg; gettimeofday ( &randtime, ( struct timezone * ) 0 ); xsub [0] = ( ushort ) randtime.tv_usec; xsub [1] = ( ushort ) ( randtime.tv_usec >> 16 ); xsub [2] = ( ushort ) ( pthread_self ); while ( 1 ){ j = nrand48 ( xsub ) & 3; pthread_mutex_lock ( &prod [j] ); while ( shared_ring.space_count [j] == 0 ){ pthread_cond_wait ( &prod_cond [j], &prod [j] ); } shared_ring.flavor[j][shared_ring.in_ptr[j]] = shared_ring.serial[j]; shared_ring.space_count[j]--; shared_ring.serial[j]++; shared_ring.in_ptr[j] = ((shared_ring.in_ptr[j]+1) % NUMSLOTS); pthread_mutex_unlock ( &prod [j] ); pthread_mutex_lock ( &cons[j] ); shared_ring.donut_count[j]++; pthread_mutex_unlock ( &cons [j] ); pthread_cond_signal(&cons_cond[j]); } return 0; } void *consumer ( void *arg ){ int i, j, k, m, id; int donuts,out_ptr; int output_array[NUMFLAVORS][12]; FILE *fp; char fname[64]; pid_t consumerpid; int doz_id; int dozen_count=1; id = *( int * ) arg; time_t t; char buf[80]; struct tm *ts; for(i = 0; i < NUMFLAVORS; i++){ for(j = 0; j < 12; j++){ output_array[i][j]=0; } } sprintf(fname,"Consumer_%d",id); if((consumerpid = getpid()) == -1){ printf("\\nError! Could not retrieve Consumer PID"); return 0; } unsigned short xsub [3]; struct timeval randtime; gettimeofday ( &randtime, ( struct timezone * ) 0 ); xsub [0] = ( ushort ) randtime.tv_usec; xsub [1] = ( ushort ) ( randtime.tv_usec >> 16 ); xsub [2] = ( ushort ) ( pthread_self ); while(dozen_count <= (NUMDOZENS+1)){ for(m = 0; m < 12; m++){ j = nrand48( xsub ) & 3; pthread_mutex_lock ( &cons[j] ); while(shared_ring.donut_count[j]==0){ pthread_cond_wait ( &cons_cond [j], &cons [j] ); } out_ptr=shared_ring.outptr[j]; donuts = shared_ring.flavor[j][out_ptr]; output_array[j][m] = donuts; shared_ring.outptr[j] = ((shared_ring.outptr[j] + 1) % NUMSLOTS); shared_ring.donut_count[j]--; pthread_mutex_unlock ( &cons[j] ); pthread_mutex_lock ( &prod[j] ); shared_ring.space_count[j]++; pthread_mutex_unlock ( &prod[j] ); pthread_cond_signal(&prod_cond[j]); } if(dozen_count<(NUMDOZENS+1)) { fp = fopen(fname,"a"); t = time(0); ts = localtime(&t); strftime(buf, sizeof(buf), " %H:%M:%S ", ts); fprintf( fp, "\\n"); consumerpid, buf, get_time_microseconds(), dozen_count); fprintf( fp, "\\n"); fprintf( fp, "%15s %15s %15s %15s \\n", "PLAIN", "JELLY", "COCONUT", "HONEY-DIP\\n"); fprintf( fp, "\\n"); for(k = 0; k < 12; k++){ fprintf(fp," "); for(j=0;j<NUMFLAVORS;j++) { if(output_array[j][k]!=0) { fprintf(fp,"%11d",output_array[j][k]); } else { fprintf(fp,"%15s"," "); } } fprintf(fp,"\\n"); } fprintf( fp, " \\n"); fprintf( fp, " =========================================================\\n"); fprintf( fp, "\\n\\n"); for(k=0; k< NUMFLAVORS; k++) for(j=0; j< 12; j++) output_array[k][j] = 0; fclose(fp); } dozen_count++; } pthread_exit(0); }
1
#include <pthread.h> int Math_Pow(int base, int exp); int first_time_init = 1; void* space_ptr; int header_size; int mem_available; pthread_mutex_t mutex; int Mem_Init(int sizeOfRegion){ pthread_mutex_init(&mutex, 0); if(first_time_init == 0){ fprintf(stderr,"Error:mem.c: Init mroe than once\\n"); return -1; } if(sizeOfRegion <= 0){ fprintf(stderr,"Error:mem.c: Requested block size is not positive\\n"); return -1; } int page_size; int pad_size; int fd; int alloc_size; page_size = getpagesize(); pad_size = sizeOfRegion % page_size; if(pad_size !=0) pad_size = page_size - pad_size; alloc_size = sizeOfRegion + pad_size; fd = open ("/dev/zero", O_RDWR); if(fd == -1){ fprintf(stderr,"Cannot opne /dev/zero\\n"); return -1; } space_ptr = mmap(0,alloc_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); if(space_ptr == MAP_FAILED){ fprintf(stderr,"Map failed\\n"); return -1; } int seg_number = alloc_size / 16; header_size = seg_number/8; unsigned char* tmp = space_ptr; int i; for(i=0;i<header_size;i++){ *(tmp+i) = 0x00; } int num_block_for_header = header_size / 16; int num_char_for_header = num_block_for_header/8; for(i=0;i<num_char_for_header;i++){ *(tmp+i) = 0xFF; } int num_char_offset_for_header = num_block_for_header%8; unsigned char *current_seg = tmp+i; for(i=0; i<num_char_offset_for_header; i++){ *current_seg = (*current_seg) | (0x80 >> i); } first_time_init = 0; close(fd); mem_available = alloc_size - header_size; return 0; } void* Mem_Alloc(int size){ if(size <=0) return 0; pthread_mutex_lock(&mutex); int i; for(i=0; i<header_size;i++){ unsigned char *current_seg = (unsigned char*)space_ptr + i; if((*current_seg) != 0xFF){ int j; for(j=0; j<8; j++){ unsigned char current = (*current_seg) << j; if((current & 0x80) == 0){ *current_seg = ((*current_seg) | (0x80 >> j)); mem_available -= 16; pthread_mutex_unlock(&mutex); return ((char*)space_ptr + (i*8+j)*16); } } } } pthread_mutex_unlock(&mutex); return 0; } int Mem_Free(void *ptr){ pthread_mutex_lock(&mutex); if(ptr == 0){ pthread_mutex_unlock(&mutex); return -1; } if(((((char*)ptr - (char*)space_ptr)) % 16) != 0){ pthread_mutex_unlock(&mutex); return -1; } int index = (((char*)ptr - (char*)space_ptr)) / 16; int sub_index_i = index / 8; int sub_index_j = index % 8; unsigned char *current_seg = (unsigned char*)space_ptr + sub_index_i; *current_seg = (*current_seg) & ( Math_Pow(2,8) -1 - Math_Pow(2,8-sub_index_j+1)); mem_available += 16; pthread_mutex_unlock(&mutex); return 0; } int Math_Pow(int base, int exp){ if(exp < 0){ printf("Not Supported\\n"); return -1; } int result = 1; int i; for(i=0;i<exp;i++) result *= exp; return result; } int Mem_Available(){ return mem_available; } void Mem_Dump() { printf("Not Supported\\n"); return; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t condvar; int shared = 0; void *consumer_fun(void *); void *producer_fun(void *); int main(void){ pthread_t consumer; pthread_t producer; pthread_mutex_init(&mutex, 0); pthread_cond_init(&condvar, 0); pthread_create(&consumer, 0, consumer_fun, 0); pthread_create(&producer, 0, producer_fun, 0); pthread_join(consumer, 0); pthread_join(producer, 0); pthread_cond_destroy(&condvar); pthread_mutex_destroy(&mutex); return 0; } void *producer_fun(void *ptr){ int number = 0; int i = 0; printf("Producer thread starting.\\n"); srandom((unsigned int)time(0)); for (i=0; i<1000; i++){ number = random() % 5 + 1; pthread_mutex_lock(&mutex); while(shared != 0){ pthread_cond_wait(&condvar, &mutex); } shared = number; printf("Producer storing the number %d, on loop %d. \\n", shared, i); pthread_cond_signal(&condvar); pthread_mutex_unlock(&mutex); } pthread_exit(0); } void *consumer_fun(void *ptr){ int i = 0; printf("Consumer thread starting.\\n"); for (i=0; i<1000; i++){ pthread_mutex_lock(&mutex); while (shared == 0){ pthread_cond_wait(&condvar, &mutex); } printf("Consumer retrieving the number %d, on loop %d.\\n", shared, i); shared = 0; pthread_cond_signal(&condvar); pthread_mutex_unlock(&mutex); } pthread_exit(0); }
1
#include <pthread.h> double counter=0; double counterSup100 = 0; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; double serialFunc(){ counter++; return counter; } void *multiplyMatCst(void *arg){ int i,j; double *M; M = (double *) arg; for (i=0;i<5000;i++){ for (j=0;j<5000;j++){ M[i*5000 +j] = M[i*5000 +j]*10.0; pthread_mutex_lock(&lock); if(M[i*5000 +j]>100) { counterSup100++; } pthread_mutex_unlock(&lock); } } return 0; } double wallclock(){ struct timeval tv; double t; gettimeofday(&tv, 0); t = (double)tv.tv_sec; t += ((double)tv.tv_usec)/1000000.0; return t; } int main(int argc, char *argv[]){ double tstart, tend; pthread_t mytask_thread[15]; double *matArray[15]; int i,j,k; printf("Initializing the matrices\\n"); tstart = wallclock(); for (k=0;k<15;k++){ matArray[k] = (double *) malloc (5000*5000*sizeof(double)); for (i=0;i<5000;i++){ for(j=0;j<5000;j++){ matArray[k][i*5000 +j] = serialFunc(); } } } tend = wallclock(); printf("Execution time serial part %f sec.\\n", tend - tstart); for (k=0;k<15;k++){ } tstart = wallclock(); for (k=0;k<15;k++){ if(pthread_create(&(mytask_thread[k]), 0, multiplyMatCst, matArray[k])) { fprintf(stderr, "Error creating thread\\n"); return 1; } } for (k=0;k<15;k++){ if(pthread_join(mytask_thread[k], 0)) { fprintf(stderr, "Error joining thread\\n"); return 2; } } tend = wallclock(); printf("Execution time parallel part %f sec.\\n", tend - tstart); for (k=0;k<15;k++){ } for (k=0;k<15;k++){ free(matArray[k]); } return 0; }
0
#include <pthread.h> struct mythread_t { pthread_t id; int index; int M, N, Q; int P; float **a, **b, **c; }; pthread_mutex_t mutex; void read_matrix(char* fname, float*** a, float** sa, int* m, int* n) { FILE* finptr; int i, sz; finptr = fopen(fname, "r"); if(!finptr) { perror("ERROR: can't open matrix file\\n"); exit(1); } if(fread(m, sizeof(int), 1, finptr) != 1 || fread(n, sizeof(int), 1, finptr) != 1) { perror("Error reading matrix file"); exit(1); } sz = (*m)*(*n); *sa = (float*)malloc(sz*sizeof(float)); if(fread(*sa, sizeof(float), sz, finptr) != sz) { perror("Error reading matrix file"); exit(1); } *a = (float**)malloc((*m)*sizeof(float*)); for(i=0; i<*m; i++) (*a)[i] = &(*sa)[i*(*n)]; fclose(finptr); } void write_matrix(char* fname, float* sa, int m, int n, int id, int p) { FILE* foutptr; int i; float* ptr; foutptr = fopen(fname, "w"); if(!foutptr) { perror("ERROR: can't open matrix file\\n"); exit(1); } if(fwrite(&m, sizeof(int), 1, foutptr) != 1 || fwrite(&n, sizeof(int), 1, foutptr) != 1) { perror("Error reading matrix file"); exit(1); } ptr = sa; for(i=0; i<m; i++) { if(fwrite(ptr, sizeof(float), n, foutptr) != n) { perror("Error writing matrix file"); exit(1); } ptr += n; } fclose(foutptr); } void write_matrix2(char* fname, float* sa, int m, int n, int id, int p) { FILE* foutptr; int i; float* ptr; foutptr = fopen(fname, "w"); if(!foutptr) { perror("ERROR: can't open matrix file\\n"); exit(1); } if(fwrite(&m, sizeof(int), 1, foutptr) != 1 || fwrite(&n, sizeof(int), 1, foutptr) != 1) { perror("Error reading matrix file"); exit(1); } ptr = sa + n*p; for(i=id; i<m; i+=p) { if(fwrite(ptr, sizeof(float), n, foutptr) != n) { perror("Error writing matrix file"); exit(1); } ptr += n*p; } fclose(foutptr); } void block_matmul(int index, int p, int m, int n, int q, float** a, float** b, float** c) { int i, j, k; for(i=index; i<m; i+=p){ for(j=0; j<q; j++) for(k=0; k<n; k++) c[i][j] += a[i][k]*b[k][j]; } } void dumb_matmul(float** a, float** b, float** c, int M,int N, int Q) { block_matmul(0, 1, M, N, Q, a, b, c); } int main (int argc, char * argv[]) { int m, n, q; float *sa, *sb, *sc; float **a, **b, **c; int i, j; int id; int p; pthread_mutex_init(&mutex, 0); if(argc != 4) { printf("Usage: %s fileA fileB fileC\\n", argv[0]); return 1; } read_matrix(argv[1], &a, &sa, &i, &j); m = i; n = j; read_matrix(argv[2], &b, &sb, &i, &j); q = j; if(n != i) { printf("ERROR: matrix A and B incompatible\\n"); return 6; } sc = (float*)malloc(m*q*sizeof(float)); memset(sc, 0, m*q*sizeof(float)); c = (float**)malloc(m*sizeof(float*)); for(i=0; i<m; i++) c[i] = &sc[i*q]; MPI_Init (&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &id); MPI_Comm_size(MPI_COMM_WORLD, &p); if(p == 1) dumb_matmul(a, b, c, m, n, q); else { if(p>m) p = m; struct mythread_t *t, *k; t = k = (struct mythread_t*) malloc(sizeof(struct mythread_t)); printf("MPI rank %d of %d\\n", id, p); k->M = m; k->N = n; k->Q = q, k->P = p; k->a = a; k->b = b; k->c = c, k->index = id; block_matmul(k->index, k->P, k->M, k->N, k->Q, k->a, k->b, k->c); free(k); } pthread_mutex_lock(&mutex); write_matrix2(argv[3], sc, m, q, id, p); pthread_mutex_unlock(&mutex); MPI_Finalize(); pthread_mutex_destroy(&mutex); free(a); free(b); free(c); free(sa); free(sb); free(sc); return 0; }
1
#include <pthread.h> struct msg { struct msg *next; int num; }; struct msg *head; struct msg *mp; pthread_cond_t has_product = PTHREAD_COND_INITIALIZER; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void *consumer(void *p) { for (;;) { pthread_mutex_lock(&lock); while (head == 0) { pthread_cond_wait(&has_product, &lock); } mp = head; head = mp->next; pthread_mutex_unlock(&lock); printf("-Consume ---%d\\n", mp->num); free(mp); mp = 0; sleep(rand() % 5); } } void *producer(void *p) { for (;;) { mp = malloc(sizeof(struct msg)); mp->num = rand() % 1000 + 1; printf("-Produce ---%d\\n", mp->num); pthread_mutex_lock(&lock); mp->next = head; head = mp; pthread_mutex_unlock(&lock); pthread_cond_signal(&has_product); sleep(rand() % 5); } } int main(int argc, char *argv[]) { pthread_t pid, cid; srand(time(0)); pthread_create(&pid, 0, producer, 0); pthread_create(&cid, 0, consumer, 0); pthread_join(pid, 0); pthread_join(cid, 0); return 0; }
0
#include <pthread.h> int bx_wd_show(struct bx_wd *bx_wdp) { fprintf(stderr,"Worker Thread Data Structure: bx_wdp=%p, next=%p, prev=%p, flags=0x%016x\\n", bx_wdp, bx_wdp->bx_wd_next, bx_wdp->bx_wd_prev, bx_wdp->bx_wd_flags); fprintf(stderr,"Worker Thread Data Structure: bx_wdp=%p, my_worker_thread_number=%d, fd=%d\\n", bx_wdp, bx_wdp->bx_wd_my_worker_thread_number, bx_wdp->bx_wd_fd); fprintf(stderr,"Worker Thread Data Structure: bx_wdp=%p, bufhdrp=%p, next_buffer_queue=%d, my_queue=%p\\n", bx_wdp, bx_wdp->bx_wd_bufhdrp, bx_wdp->bx_wd_next_buffer_queue, bx_wdp->bx_wd_my_queue); return(0); } int bx_wd_queue_show(struct bx_wd_queue *qp) { struct bx_wd *bx_wdp; fprintf(stderr,"\\n"); fprintf(stderr,"Worker Thread Data Structure QUEUE: qp=%p, name='%s', counter=%d, flags=0x%08x\\n", qp, qp->q_name, qp->q_counter, qp->q_flags); fprintf(stderr,"Worker Thread Data Structure QUEUE: qp=%p, first=%p, last=%p\\n\\n", qp, qp->q_first, qp->q_last); bx_wdp = qp->q_first; while (bx_wdp) { bx_wd_show(bx_wdp); bx_wdp = bx_wdp->bx_wd_next; } return(0); } int bx_wd_queue_init(struct bx_wd_queue *qp, char *q_name) { int status; qp->q_name = q_name; qp->q_counter = 0; qp->q_flags = 0; qp->q_first = 0; qp->q_last = 0; status = pthread_mutex_init(&qp->q_mutex, 0); if (status) { perror("Error initializing Worker Thread Data Structure queue mutex"); return(-1); } status = pthread_cond_init(&qp->q_conditional, 0); if (status) { perror("Error initializing Worker Thread Data Structure queue conditional variable"); return(-1); } return(0); } int bx_wd_enqueue(struct bx_wd *bx_wdp, struct bx_wd_queue *qp) { struct bx_wd *tmp; int status; pthread_mutex_lock(&qp->q_mutex); if (qp->q_first == 0) { qp->q_first = bx_wdp; qp->q_last = qp->q_first; qp->q_counter++; bx_wdp->bx_wd_prev = 0; bx_wdp->bx_wd_next = 0; } else { tmp = qp->q_last; tmp->bx_wd_next = bx_wdp; bx_wdp->bx_wd_prev = tmp; bx_wdp->bx_wd_next = 0; qp->q_counter++; qp->q_last = bx_wdp; } if (qp->q_flags & BX_WD_WAITING) { status = pthread_cond_broadcast(&qp->q_conditional); if ((status != 0) && (status != PTHREAD_BARRIER_SERIAL_THREAD)) { fprintf(stderr,"bx_wd_enqueue: ERROR: pthread_cond_broadcast failed: status is %d, errno is %d\\n", status, errno); perror("Reason"); } } pthread_mutex_unlock(&qp->q_mutex); return(0); } struct bx_wd * bx_wd_dequeue(struct bx_wd_queue *qp) { struct bx_wd *bx_wdp; pthread_mutex_lock(&qp->q_mutex); qp->q_flags |= BX_WD_WAITING; while (qp->q_counter == 0) { pthread_cond_wait(&qp->q_conditional, &qp->q_mutex); } qp->q_flags &= ~BX_WD_WAITING; bx_wdp = qp->q_first; qp->q_first = bx_wdp->bx_wd_next; if (qp->q_first == 0) { qp->q_last = 0; } else { qp->q_first->bx_wd_prev = 0; } qp->q_counter--; pthread_mutex_unlock(&qp->q_mutex); return(bx_wdp); }
1
#include <pthread.h> int n=0; pthread_mutex_t mylock=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t qready=PTHREAD_COND_INITIALIZER; void * thread_func(void *arg) { int param=(int)arg; char c='A'+param; int ret,i=0; for (; i < 10; i++) { pthread_mutex_lock(&mylock); while (param != n) { ret = pthread_cond_wait(&qready, &mylock); if (ret == 0) { } else { } } printf("%c ",c); n=(n+1)%3; pthread_mutex_unlock(&mylock); pthread_cond_broadcast(&qready); } return (void *)0; } int main(int argc, char** argv) { int i=0,err; pthread_t tid[3]; void *tret; for(;i<3;i++) { err=pthread_create(&tid[i],0,thread_func,(void *)i); if(err!=0) { printf("thread_create error:%s\\n",strerror(err)); exit(-1); } } for (i = 0; i < 3; i++) { err = pthread_join(tid[i], &tret); if (err != 0) { printf("can not join with thread %d:%s\\n", i,strerror(err)); exit(-1); } } printf("\\n"); return 0; }
0
#include <pthread.h> int sum_of_number = 0; sem_t write_res_number; sem_t read_res_number; struct recycle_buffer { int buffer[4]; int head, tail; }re_buf; pthread_mutex_t buffer_mutex = PTHREAD_MUTEX_INITIALIZER; static void *producer(void *arg){ int i; for(i=0; i<=8; i++){ sem_wait(&write_res_number); pthread_mutex_lock(&buffer_mutex); re_buf.buffer[re_buf.tail] = i; re_buf.tail = (re_buf.tail + 1)%4; printf("producer %d write %d.\\n", (unsigned int)pthread_self(), i); pthread_mutex_unlock(&buffer_mutex); sem_post(&read_res_number); } return 0; } static void *consumer(void *arg) { int i, num; for(i=0; i<=8; i++){ sem_wait(&read_res_number); pthread_mutex_lock(&buffer_mutex); num = re_buf.buffer[re_buf.head]; re_buf.head = (re_buf.head +1)%4; printf("consumer %d read %d.\\n", (unsigned int)pthread_self(),num); pthread_mutex_unlock(&buffer_mutex); sum_of_number += num; sem_post(&write_res_number); } return 0; } int main(int argc, char* argv[]) { pthread_t p_tid; pthread_t c_tid; int i; re_buf.head = 0; re_buf.tail = 0; for(i=0; i<4; i++) re_buf.buffer[i] = 0; sem_init(&write_res_number, 0, 4); sem_init(&read_res_number, 0, 0); pthread_create(&p_tid, 0, producer, 0); pthread_create(&c_tid, 0, consumer, 0); pthread_join(p_tid, 0); pthread_join(c_tid, 0); printf("The sun of number is: %d\\n", sum_of_number); exit(0); }
1
#include <pthread.h> state situation[MAXTH]; pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition[MAXTH]; int philosopherCount; void test(int i) { if(situation[(i + 1) % philosopherCount]!=EATING && situation[(i +philosopherCount - 1 ) % philosopherCount]!=EATING && situation[i]==HUNGRY) { situation[i]=EATING; pthread_cond_signal(&condition[i]); } } void dp_init(int N) { if(N<5 || N>20) { perror("You have entered out-of-limit number."); return; } philosopherCount=N; int i=0; for(i=0;i<N;i++) { situation[i]=THINKING; pthread_cond_init(&condition[i], 0); } } void dp_get_forks(int i) { pthread_mutex_lock(&mutex); situation[i]=HUNGRY; test(i); if(situation[i]!=EATING) { pthread_cond_wait(&condition[i], &mutex); } pthread_mutex_unlock(&mutex); } void dp_put_forks(int i) { pthread_mutex_lock(&mutex); situation[i]=THINKING; test((i + 1) % philosopherCount); test((i +philosopherCount - 1 ) % philosopherCount); pthread_mutex_unlock(&mutex); }
0
#include <pthread.h> int GlobalCounter = 0, NewNumber = 0;; pthread_mutex_t mutexsum; void *Func1(void *threadid) { int taskId; taskId = (int)threadid; pthread_mutex_lock (&mutexsum); printf("\\n\\nThread 1: Enter New Number To be added the Counter (0: Terminate the process)\\n"); scanf("%d",&NewNumber); GlobalCounter += NewNumber; printf("taskId: %d ,\\tThread 1: GlobalCounter is %d\\n", taskId,GlobalCounter); pthread_mutex_unlock (&mutexsum); pthread_exit(0); } void *Func234(void *threadid) { int taskId; taskId = (int)threadid; int TID = pthread_self(); while (GlobalCounter == 0); pthread_mutex_lock (&mutexsum); while(GlobalCounter > 0) { GlobalCounter--; printf("taskId: %d ,\\tThread ID: %d ,\\t GlobalCounter is %d\\n", taskId,TID, GlobalCounter); sleep(1); } pthread_mutex_unlock (&mutexsum); pthread_exit(0); } void main(int argc, char *argv[]) { pthread_t threads[4]; pthread_attr_t attr; void *status; int rc, t; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); t = 0; printf("Creating thread : %d\\n",t); pthread_create(&threads[t], &attr, Func1, (void *)t); t = 1; printf("Creating thread : %d\\n",t); pthread_create(&threads[t], &attr, Func234, (void *)t); t = 2; printf("Creating thread : %d\\n",t); pthread_create(&threads[t], &attr, Func234, (void *)t); t = 3; printf("Creating thread : %d\\n",t); pthread_create(&threads[t], &attr, Func234, (void *)t); pthread_attr_destroy(&attr); for(t=0;t<4;t++) pthread_join(threads[t], &status); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; void * child1(void *arg) { pthread_cleanup_push(pthread_mutex_unlock,&mutex); while(1){ printf("thread 1 get running \\n"); printf("thread 1 pthread_mutex_lock returns %d\\n", pthread_mutex_lock(&mutex)); pthread_cond_wait(&cond,&mutex); printf("thread 1 condition applied\\n"); pthread_mutex_unlock(&mutex); sleep(5); } pthread_cleanup_pop(0); } void *child2(void *arg) { while(1){ sleep(3); printf("thread 2 get running.\\n"); printf("thread 2 pthread_mutex_lock returns %d\\n", pthread_mutex_lock(&mutex)); pthread_cond_wait(&cond,&mutex); printf("thread 2 condition applied\\n"); pthread_mutex_unlock(&mutex); sleep(1); } } int main(void) { int tid1,tid2; printf("hello, condition variable test\\n"); pthread_mutex_init(&mutex,0); pthread_cond_init(&cond,0); pthread_create(&tid1,0,child1,0); pthread_create(&tid2,0,child2,0); do{ sleep(2); pthread_cancel(tid1); sleep(2); pthread_cond_signal(&cond); }while(1); sleep(100); pthread_exit(0); }
0
#include <pthread.h> void * th_f(void *arg); char * read_line(int fd); char * process_line(char *src); pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER; int main(int argc, char *argv[]) { pthread_t ntid; int status; int fd; fd = open (argv[1] , O_RDONLY); if ( 0 > fd ) { perror("File opening Failed\\n"); exit(1); } status=pthread_create(&ntid,0,th_f,(void *)fd); if (status != 0) { printf("Error in Creating Thread\\n"); exit(status); } th_f(fd); } void * th_f(void *arg) { char * lptr; while (1) { pthread_mutex_lock(&mymutex); lptr = read_line ( (int)arg); pthread_mutex_unlock(&mymutex); if (0 == lptr) { pthread_exit(0); } printf("%u %s\\n",pthread_self(), process_line(lptr)); write(1, lptr, strlen(lptr)); free(lptr); } } char * read_line(int fd) { char *buffer; int ret, index=0; buffer = (char *)malloc(120); if (0 == buffer) { printf("Memory allocation failed\\n"); exit(1); } memset( buffer, '\\0', 120); while((ret=read(fd, buffer + index, 1))>0) { if ('\\n' == *(buffer + index)) { index++; *(buffer + index) = '\\0'; return buffer; } index ++; } return 0; } char * process_line(char *src) { int index; for (index = 0; src[index]; index++) src[index] = toupper(src[index]); src[index] = 0; return src; }
1
#include <pthread.h> pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER; char log_path[4096]; char log_filename[4096 + 255]; int log_has_configed = 0; int log_fd; void closelog() { fsync(log_fd); close(log_fd); } void rename_logfile(const char *fname) { time_t now = time(0); struct tm *r = localtime(&now); char postfix[100]; char newname[4096 + 255]; snprintf(postfix, 99, "%4d%02d%02d%02d%02d%02d", r->tm_year + 1900, r->tm_mon + 1, r->tm_mday, r->tm_hour, r->tm_min, r->tm_sec); snprintf(newname, 4096 + 255 - 1, "%s.%s", fname, postfix); rename(fname, newname); } void log_init(const char *file, const char *function, const int line, char *path, char *name) { pthread_mutex_lock(&log_lock); if (log_has_configed == 1) goto out; log_has_configed = 1; strncpy(log_path, path, 4096 - 1); log_path[4096 - 1] = '\\0'; if (strlen(log_path) != strlen(path)) { err_quit(file, function, line, "路径长度过长(超过4095)。"); } if (access(log_path, R_OK | W_OK | X_OK) != 0) { err_sys(file, function, line, "日志路径权限检查出错"); } strncpy(log_filename, log_path, 4096 + 255 - 1); if (log_path[strlen(log_path) - 1] == '/') { strncat(log_filename, name, 4096 + 255 - 1 - strlen(log_filename)); } else { strncat(log_filename, "/", 4096 + 255 - 1 - 1); strncat(log_filename, name, 4096 + 255 - 1 - strlen(log_filename)); } log_filename[4096 + 255 - 1] = '\\0'; open: log_fd = open(log_filename, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (log_fd == -1) { if (errno == EEXIST) { rename_logfile(log_filename); goto open; } err_sys(file, function, line, "无法创建日志文件"); } atexit(closelog); const char init_msg[] = "======== log system init ========\\n"; write(log_fd, init_msg, strlen(init_msg)); out: pthread_mutex_unlock(&log_lock); } void log_info(const char *file, const char *function, const int line, char *fmt, ...) { pthread_mutex_lock(&log_lock); char msgbuf[8192]; char tmp[8192]; va_list ap; __builtin_va_start((ap)); vsnprintf(tmp, 8192 - 2, fmt, ap); ; snprintf(msgbuf, 8192 - 2, "[File: %s][Function: %s][Line: %d][INFO] ", file, function, line); strncat(msgbuf, tmp, 8192 - 2 - strlen(msgbuf)); if (msgbuf[strlen(msgbuf) - 1] != '\\n') { strcat(msgbuf, "\\n"); } msgbuf[8192 - 1] = '\\0'; write(log_fd, msgbuf, strlen(msgbuf)); pthread_mutex_unlock(&log_lock); } void log_debug(const char *file, const char *function, const int line, char *fmt, ...) { pthread_mutex_lock(&log_lock); char msgbuf[8192]; char tmp[8192]; va_list ap; __builtin_va_start((ap)); vsnprintf(tmp, 8192 - 2, fmt, ap); ; snprintf(msgbuf, 8192 - 2, "[File: %s][Function: %s][Line: %d][DEBUG] ", file, function, line); strncat(msgbuf, tmp, 8192 - 2 - strlen(msgbuf)); if (msgbuf[strlen(msgbuf) - 1] != '\\n') { strcat(msgbuf, "\\n"); } msgbuf[8192 - 1] = '\\0'; write(log_fd, msgbuf, strlen(msgbuf)); pthread_mutex_unlock(&log_lock); }
0
#include <pthread.h> extern int make_detach_thread(void *(*fn)(void *), void *arg); struct to_info { void (*to_fn)(void *); void *to_arg; struct timespec to_wait; }; void clock_gettime(int id, struct timespec *tsp) { struct timeval tv; gettimeofday(&tv, 0); tsp->tv_sec = tv.tv_sec; tsp->tv_nsec = tv.tv_usec * 1000; } void *timeout_helper(void *arg) { struct to_info *tip; tip = (struct to_info *)arg; nanosleep((&tip->to_wait), (0)); (*tip->to_fn)(tip->to_arg); free(arg); return(0); } void timeout(const struct timespec *when, void (*func)(void *), void *arg) { struct timespec now; struct to_info *tip; int err; clock_gettime(0, &now); if ((when->tv_sec > now.tv_sec) || (when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) { tip = malloc(sizeof(struct to_info)); if (tip != 0) { tip->to_fn = func; tip->to_arg = arg; tip->to_wait.tv_sec = when->tv_sec - now.tv_sec; if (when->tv_nsec >= now.tv_nsec) { tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec; } else { tip->to_wait.tv_sec--; tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec; } err = make_detach_thread(timeout_helper, (void *)tip); if (err == 0) return; else free(tip); } } (*func)(arg); } pthread_mutexattr_t attr; pthread_mutex_t mutex; void retry(void *arg) { pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); } int main(void) { int err, condition, arg; struct timespec when; if ((err = pthread_mutexattr_init(&attr)) != 0) err_exit(err, "pthread_mutexattr_init failed"); if ((err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) != 0) err_exit(err, "can't set recursive type"); if ((err = pthread_mutex_init(&mutex, &attr)) != 0) err_exit(err, "can't create recursive mutex"); pthread_mutex_lock(&mutex); if (condition) { clock_gettime(0, &when); when.tv_sec += 10; timeout(&when, retry, (void *)((unsigned long)arg)); } pthread_mutex_unlock(&mutex); exit(0); }
1
#include <pthread.h> static pthread_mutex_t fff0r_mutex = PTHREAD_MUTEX_INITIALIZER; void fff0r_lock(void) { pthread_mutex_lock(&fff0r_mutex); } void fff0r_unlock(void) { pthread_mutex_unlock(&fff0r_mutex); }
0
#include <pthread.h> int i, numfull, produce, consume, numbuf, numtrd; int *buffer; pthread_cond_t empty; pthread_cond_t fill; pthread_mutex_t mutex; pthread_t *t; void* consumer(); void server_init(int argc, char* argv[]) { if (argc != 4) { fprintf(stderr, "Usage: %s server" " [portnum] [threads] [buffers]\\n", argv[0]); exit(1); } if (atoi(argv[2]) <= 0) { perror("number of threads not positive"); exit(1); } if (atoi(argv[3]) <= 0) { perror("number of buffers not positive"); exit(1); } numbuf = atoi(argv[3]); buffer = malloc(sizeof(uint)*numbuf); for (i = 0; i < numbuf; i++) buffer[i] = -1; numfull = 0; produce = 0; consume = 0; numtrd = atoi(argv[2]); t = (pthread_t *)malloc(sizeof(pthread_t)*numtrd); if (pthread_cond_init(&empty, 0) != 0) exit(1); if (pthread_cond_init(&fill, 0) != 0) exit(1); if (pthread_mutex_init(&mutex, 0) != 0) exit(1); for (i = 0; i < numtrd; i++) { if (pthread_create(&t[i], 0, consumer, 0) != 0) { printf("pthread_create goes wrong\\n"); exit(1); } } } void *consumer() { int fd1 = 0; while (1) { pthread_mutex_lock(&mutex); while (numfull == 0) { pthread_cond_wait(&fill, &mutex); } fd1 = buffer[consume]; buffer[consume] = -1; consume = (consume+1)%numbuf; numfull -= 1; pthread_cond_signal(&empty); pthread_mutex_unlock(&mutex); requestHandle(fd1); } } void server_dispatch(int connfd) { int fd = connfd; pthread_mutex_lock(&mutex); while (numfull == numbuf) { pthread_cond_wait(&empty, &mutex); } buffer[produce] = fd; produce = (produce+1)%numbuf; numfull += 1; pthread_cond_signal(&fill); pthread_mutex_unlock(&mutex); }
1
#include <pthread.h> struct list_elem* next; char* data; }list_elem; struct list_elem* first; int size; }head_list_elem; pthread_mutex_t global_mutex; head_list_elem* cont_allocate(){ head_list_elem* head = 0; head = (head_list_elem*)malloc( sizeof (head_list_elem)); assert ( head ); head->size = 0; head->first = 0; return head; } void cont_free ( head_list_elem* root ){ list_elem* cur = root->first; list_elem* tmp = 0; free(root); while ( cur ){ tmp = cur->next; free(cur); cur = tmp; } } void cont_add_first ( head_list_elem* root, char* str ){ list_elem* tmp = 0; list_elem* newElement = 0; tmp = root->first; if ( 0 == tmp ){ pthread_mutex_lock(&global_mutex); newElement = (list_elem*)malloc(sizeof(list_elem)); (root->size)++; newElement->next = 0; newElement->data = str; root->first = newElement; pthread_mutex_unlock(&global_mutex); return; } pthread_mutex_lock(&global_mutex); newElement = (list_elem*)malloc(sizeof(list_elem)); (root->size)++; newElement->next = (root->first); newElement->data = str; root->first = newElement; pthread_mutex_unlock(&global_mutex); return; } void swap ( list_elem* a, list_elem* b){ void* tmp = a->data; a->data = b->data; b->data = tmp; } void cont_print ( head_list_elem* root ){ pthread_mutex_lock(&global_mutex); list_elem* cur = root->first; printf("________________________________\\n"); while ( cur ){ printf ( "%s\\n", cur->data ); cur = cur->next; } printf("________________________________\\n"); pthread_mutex_unlock(&global_mutex); } void* cont_sort(void* root) { assert( root ); while (1) { list_elem* list = ((head_list_elem*)root)->first; list_elem* iteri = 0; sleep(5); pthread_mutex_lock(&global_mutex); for (iteri = list; iteri; iteri = iteri->next) { list_elem* iterj = 0; for (iterj = iteri->next; iterj; iterj = iterj->next) { if (0 < strcmp(iteri->data, iterj->data)) { swap(iteri, iterj); } } } pthread_mutex_unlock(&global_mutex); cont_print(root); } return 0; } int main(int argc, char* argv[]){ char* cur = 0; head_list_elem* root = 0; pthread_t sort_thread; pthread_mutex_init(&global_mutex, 0); root = cont_allocate(); pthread_create(&sort_thread, 0, cont_sort, (void*)(root)); while (1){ cur = (char*)calloc( (80), sizeof(char)); assert(cur); fgets(cur, (80), stdin); if ('\\n' == cur[strlen(cur) - 1]) { cur[strlen(cur) - 1] = 0; } if (0 == strlen(cur)) { cont_print(root); continue; } cont_add_first(root, cur); } pthread_cancel(sort_thread); pthread_join(sort_thread, 0); pthread_mutex_destroy(&global_mutex); cont_free(root); return 0; }
0
#include <pthread.h> extern int done_creating_requests; static void cleanup_free_mutex(void* a_mutex) { pthread_mutex_t* p_mutex = (pthread_mutex_t*)a_mutex; if (p_mutex) pthread_mutex_unlock(p_mutex); } static void handle_request(struct request* a_request, int thread_id) { if (a_request) { int i; for (i = 0; i<100000; i++) ; } } void* handle_requests_loop(void* thread_params) { int rc; struct request* a_request; struct handler_thread_params *data; data = (struct handler_thread_params*)thread_params; assert(data); printf("Starting thread '%d'\\n", data->thread_id); fflush(stdout); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0); pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, 0); pthread_cleanup_push(cleanup_free_mutex, (void*)data->request_mutex); rc = pthread_mutex_lock(data->request_mutex); while (1) { int num_requests = get_requests_number(data->requests); if (num_requests > 0) { a_request = get_request(data->requests); if (a_request) { handle_request(a_request, data->thread_id); free(a_request); } } else { if (done_creating_requests) { pthread_mutex_unlock(data->request_mutex); printf("thread '%d' exiting\\n", data->thread_id); fflush(stdout); pthread_exit(0); } rc = pthread_cond_wait(data->got_request, data->request_mutex); } } pthread_cleanup_pop(0); }
1
#include <pthread.h> sem_t suma_total; int total = 0; int vect1[100000000]; int vect2[100000000]; pthread_mutex_t lock; struct parametros_hilo { int min; int max; int suma_temp; }; void prodVect(void* parametros) { struct parametros_hilo* params = (struct parametros_hilo*) parametros; int tmp_suma = 0; for (int i = params->min; i < params->max; ++i) { tmp_suma += vect1[i] * vect2[i]; } pthread_mutex_lock(&lock); total += tmp_suma; pthread_mutex_unlock(&lock); printf("total:%d\\n", total); } int main(int argc, char const *argv[]) { int num; int num1; FILE *mi_archivo1; FILE *mi_archivo2; int numHilos = atoi(argv[3]); pthread_t hilos_ids[numHilos]; mi_archivo1 = fopen(argv[1], "r"); mi_archivo2 = fopen(argv[2], "r"); int i = 0; while (fscanf(mi_archivo1, "%d", &num) > 0) { fscanf(mi_archivo2, "%d", &num1); printf("%d\\n", num ); vect1[i] = num; vect2[i] = num1; i++; } printf("--------- Fin Vector 1 ---------\\n"); char choice[80]; do { int porcion = 100000000 / numHilos; struct parametros_hilo paramHilo[numHilos]; for (int i = 0; i < numHilos; ++i) { paramHilo[i].min = i * porcion; paramHilo[i].max = (i + 1) * porcion; } struct timeval begin, end; gettimeofday(&begin, 0); for (int i = 0; i < numHilos; ++i) { pthread_create(&hilos_ids[i], 0, (void *)prodVect, &paramHilo[i]); } for (int i = 0; i < numHilos; ++i) { pthread_join(hilos_ids[i], 0); } printf("El producto vectorial entre los dos vectores de %d numeros es: %d\\n", 100000000, total); gettimeofday(&end, 0); double elapsed = (end.tv_sec - begin.tv_sec) + ((end.tv_usec - begin.tv_usec) / 1000000.0); printf("Tiempo Transcurrido: %f segundos.\\n", elapsed); printf("Volver a ejecutar? s/n\\n"); scanf("%s", choice); if (strcmp (choice, "n") == 0) { break; } total = 0; getchar(); } while (1); return 0; }
0
#include <pthread.h> const unsigned int NUM_PRINTS = 5; const unsigned int NUM_THREADS = 8; static char BufferA[65536]; static int CountA[128]; int EndofBuffer = 0; pthread_mutex_t lock; pthread_mutex_t lock2; void cleanBuffer(int *buf) { int i; for (i = 0; i < 128; i++) { buf[i] = 0; } } void *thread_func(void *data) { int CountLocal[128]; int start, end,i; cleanBuffer(CountLocal); pthread_mutex_lock(&lock); start = EndofBuffer; end= EndofBuffer +65536/NUM_THREADS; EndofBuffer = end; pthread_mutex_unlock(&lock); for( start;start < end;start++) { i = (int)BufferA[start]; CountLocal[i]++; } pthread_mutex_lock(&lock2); for (i = 0; i < 128; i++) { CountA[i]= CountA[i]+CountLocal[i]; } pthread_mutex_unlock(&lock2); } int main(int argc, char **argv) { int k = 0; int bytes_read; FILE *outfile; pthread_t threads[NUM_THREADS]; cleanBuffer(CountA); if (argc <= 2) { printf("no argument \\n"); exit(1); } int fd = open(argv[1], O_RDONLY); if (fd < 0) { printf("Unable to open file %s\\n", argv[1]); exit(1); } outfile = fopen(argv[2], "w"); printf(" with %i NUM_THREADS\\n",NUM_THREADS); do { bytes_read = read(fd, BufferA, 65536); if (bytes_read <= 0) { if (bytes_read < 0) { printf(" having a error when reading file %s \\n", argv[1]); exit(1); } } else { unsigned long i; EndofBuffer = 0; for (i = 0; i < NUM_THREADS; i++) { pthread_create(&threads[i], 0, thread_func, (void *) (i + 1)); } unsigned int j; for (j = 0; j < NUM_THREADS; j++) { pthread_join(threads[j], 0); } } } while (bytes_read != 0); for (k = 0; k < 128; k++) { fprintf(outfile, " %i occurrences of Ox%x\\n", CountA[k], k); } return 0; }
1
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top=0; static unsigned int arr[(5)]; 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==(5)) { printf("stack overflow\\n"); return (-1); } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (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<(5); i++) { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint()%(5); if ((push(arr,tmp)==(-1))) error(); pthread_mutex_unlock(&m); } } void *t2(void *arg) { int i; for( i=0; i<(5); i++) { pthread_mutex_lock(&m); if (top>0) { 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> const int MAX_KEY = 100000000; struct list_node_s { int data; struct list_node_s* next; }; struct list_node_s* head = 0; int num_hilos; int total_ops; double porcentaje_insertar; double porcentaje_busqueda; double porcentaje_borrado; pthread_rwlock_t rwlock; pthread_mutex_t count_mutex; int member_count = 0, insert_count = 0, delete_count = 0; void Usage(char* prog_name); void Get_input(int* inserts_in_main_p); void* Thread_work(void* rank); int Insert(int value); void Print(void); int Member(int value); int Delete(int value); void Free_list(void); int Is_empty(void); int main(int argc, char* argv[]) { long i; int key, success, attempts; pthread_t* thread_handles; int inserts_in_main; unsigned seed = 1; double inicio, fin; if (argc != 2) Usage(argv[0]); num_hilos = strtol(argv[1],0,10); Get_input(&inserts_in_main); i = attempts = 0; while ( i < inserts_in_main && attempts < 2*inserts_in_main ) { key = my_rand(&seed) % MAX_KEY; success = Insert(key); attempts++; if (success) i++; } printf("%ld keys insertadas\\n", i); thread_handles = malloc(num_hilos*sizeof(pthread_t)); pthread_mutex_init(&count_mutex, 0); pthread_rwlock_init(&rwlock, 0); GET_TIME(inicio); for (i = 0; i < num_hilos; i++) pthread_create(&thread_handles[i], 0, Thread_work, (void*) i); for (i = 0; i < num_hilos; i++) pthread_join(thread_handles[i], 0); GET_TIME(fin); printf("Tiempo de ejecución = %e segundos\\n", fin - inicio); printf("Total operaciones = %d\\n", total_ops); printf("Operaciones miembro = %d\\n", member_count); printf("Operaciones insertar = %d\\n", insert_count); printf("Operaciones borrado = %d\\n", delete_count); Free_list(); pthread_rwlock_destroy(&rwlock); pthread_mutex_destroy(&count_mutex); free(thread_handles); return 0; } void Usage(char* prog_name) { fprintf(stderr, "usage: %s <num_hilos>\\n", prog_name); exit(0); } void Get_input(int* inserts_in_main_p) { printf("Número de claves a insertar:\\n"); scanf("%d", inserts_in_main_p); printf("Número total de operaciones:\\n"); scanf("%d", &total_ops); printf("Porcentaje de operaciones de búsqueda:\\n"); scanf("%lf", &porcentaje_busqueda); printf("Porcentaje de operaciones de inserción:\\n"); scanf("%lf", &porcentaje_insertar); porcentaje_borrado = 1.0 - (porcentaje_busqueda + porcentaje_insertar); } int Insert(int value) { struct list_node_s* curr = head; struct list_node_s* pred = 0; struct list_node_s* temp; int rv = 1; while (curr != 0 && curr->data < value) { pred = curr; curr = curr->next; } if (curr == 0 || curr->data > value) { temp = malloc(sizeof(struct list_node_s)); temp->data = value; temp->next = curr; if (pred == 0) head = temp; else pred->next = temp; } else rv = 0; return rv; } void Print(void) { struct list_node_s* temp; printf("lista = "); temp = head; while (temp != (struct list_node_s*) 0) { printf("%d ", temp->data); temp = temp->next; } printf("\\n"); } int Member(int value) { struct list_node_s* temp; temp = head; while (temp != 0 && temp->data < value) temp = temp->next; if (temp == 0 || temp->data > value) { return 0; } else { return 1; } } int Delete(int value) { struct list_node_s* curr = head; struct list_node_s* pred = 0; int rv = 1; while (curr != 0 && curr->data < value) { pred = curr; curr = curr->next; } if (curr != 0 && curr->data == value) { if (pred == 0) { head = curr->next; free(curr); } else { pred->next = curr->next; free(curr); } } else rv = 0; return rv; } void Free_list(void) { struct list_node_s* current; struct list_node_s* following; if (Is_empty()) return; current = head; following = current->next; while (following != 0) { free(current); current = following; following = current->next; } free(current); } int Is_empty(void) { if (head == 0) return 1; else return 0; } void* Thread_work(void* rank) { long my_rank = (long) rank; int i, val; double which_op; unsigned seed = my_rank + 1; int my_member_count = 0, my_insert_count=0, my_delete_count=0; int ops_per_thread = total_ops/num_hilos; for (i = 0; i < ops_per_thread; i++) { which_op = my_drand(&seed); val = my_rand(&seed) % MAX_KEY; if (which_op < porcentaje_busqueda) { pthread_rwlock_rdlock(&rwlock); Member(val); pthread_rwlock_unlock(&rwlock); my_member_count++; } else if (which_op < porcentaje_busqueda + porcentaje_insertar) { pthread_rwlock_wrlock(&rwlock); Insert(val); pthread_rwlock_unlock(&rwlock); my_insert_count++; } else { pthread_rwlock_wrlock(&rwlock); Delete(val); pthread_rwlock_unlock(&rwlock); my_delete_count++; } } pthread_mutex_lock(&count_mutex); member_count += my_member_count; insert_count += my_insert_count; delete_count += my_delete_count; pthread_mutex_unlock(&count_mutex); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; void *thread_1(void *arg) { pthread_mutex_lock(&mutex); DPRINTF(stdout,"Thread 1 locked the mutex\\n"); pthread_exit(0); return 0; } void *thread_2(void *arg) { int rc = 0; pthread_t self = pthread_self(); int policy = SCHED_FIFO; struct sched_param param; memset(&param, 0, sizeof(param)); param.sched_priority = sched_get_priority_min(policy); rc = pthread_setschedparam(self, policy, &param); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_setschedparam: %d %s", rc, strerror(rc)); exit(UNRESOLVED); } if (pthread_mutex_lock(&mutex) != EOWNERDEAD) { EPRINTF("FAIL: pthread_mutex_lock didn't return EOWNERDEAD"); exit(FAIL); } DPRINTF(stdout,"Thread 2 lock the mutex and return EOWNERDEAD\\n"); pthread_mutex_unlock(&mutex); if (pthread_mutex_lock(&mutex) != ENOTRECOVERABLE) { EPRINTF("FAIL: The mutex did not transit to ENOTRECOVERABLE" "state when unlocked in Sun compatibility mode"); pthread_mutex_unlock(&mutex); exit(FAIL); } pthread_exit(0); return 0; } int main() { pthread_mutexattr_t attr; pthread_t threads[2]; pthread_attr_t threadattr; int rc; rc = pthread_mutexattr_init(&attr); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_mutexattr_init %d %s", rc, strerror(rc)); return UNRESOLVED; } rc = pthread_mutexattr_setrobust_np(&attr, PTHREAD_MUTEX_ROBUST_SUN_NP); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_mutexattr_setrobust_np %d %s", rc, strerror(rc)); return UNRESOLVED; } rc = pthread_mutex_init(&mutex, &attr); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_mutex_init %d %s", rc, strerror(rc)); return UNRESOLVED; } rc = pthread_attr_init(&threadattr); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_attr_init %d %s", rc, strerror(rc)); return UNRESOLVED; } rc = pthread_create(&threads[0], &threadattr, thread_1, 0); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_create %d %s", rc, strerror(rc)); return UNRESOLVED; } pthread_join(threads[0], 0); DPRINTF(stdout,"Thread 1 exit without unlock...\\n"); rc = pthread_create(&threads[1], &threadattr, thread_2, 0); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_create %d %s", rc, strerror(rc)); return UNRESOLVED; } pthread_join(threads[1], 0); DPRINTF(stdout,"Thread 2 exit... \\n"); DPRINTF(stdout,"PASS: Test PASSED\\n"); return PASS; }
0
#include <pthread.h> int error; static pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; void * thr_fn1(void * arg) { struct timespec tout; struct tm *tmp; char buf[64]; clock_gettime(CLOCK_REALTIME, &tout); tmp = localtime(&tout.tv_sec); strftime(buf, sizeof(buf), "%r", tmp);; tout.tv_sec += 5; error = pthread_mutex_timedlock(&mutex1, &tout); clock_gettime(CLOCK_REALTIME, &tout); tmp = localtime(&tout.tv_sec); strftime(buf, sizeof(buf), "%r", tmp);; if (error) { printf("Thread 1: can’t lock mutex1: %s\\n", strerror(error)); } else { printf("Thread 1: mutex1 locked!\\n"); } int i; for(i = 0 ; i < 0xFFFF ; i++); clock_gettime(CLOCK_REALTIME, &tout); tmp = localtime(&tout.tv_sec); strftime(buf, sizeof(buf), "%r", tmp);; tout.tv_sec += 5; error = pthread_mutex_timedlock(&mutex2, &tout); clock_gettime(CLOCK_REALTIME, &tout); tmp = localtime(&tout.tv_sec); strftime(buf, sizeof(buf), "%r", tmp);; if (error) { printf("Thread 1: can’t lock mutex2: %s\\n", strerror(error)); } else { printf("Thread 1: mutex2 locked!\\n"); } pthread_mutex_unlock(&mutex1); pthread_mutex_unlock(&mutex2); pthread_exit((void *)2); } void * thr_fn2(void * arg) { struct timespec tout; struct tm *tmp; char buf[64]; clock_gettime(CLOCK_REALTIME, &tout); tmp = localtime(&tout.tv_sec); strftime(buf, sizeof(buf), "%r", tmp);; tout.tv_sec += 5; error = pthread_mutex_timedlock(&mutex2, &tout); clock_gettime(CLOCK_REALTIME, &tout); tmp = localtime(&tout.tv_sec); strftime(buf, sizeof(buf), "%r", tmp);; if (error) { printf("Thread 2: can’t lock mutex2: %s\\n", strerror(error)); } else { printf("Thread 2: mutex2 locked!\\n"); } int i; for(i = 0 ; i < 0xFFFF ; i++); clock_gettime(CLOCK_REALTIME, &tout); tmp = localtime(&tout.tv_sec); strftime(buf, sizeof(buf), "%r", tmp);; tout.tv_sec += 10; error = pthread_mutex_timedlock(&mutex1, &tout); clock_gettime(CLOCK_REALTIME, &tout); tmp = localtime(&tout.tv_sec); strftime(buf, sizeof(buf), "%r", tmp);; if (error) { printf("Thread 2: can’t lock mutex1: %s\\n", strerror(error)); } else { printf("Thread 2: mutex1 locked!\\n"); } pthread_mutex_unlock(&mutex1); pthread_mutex_unlock(&mutex2); pthread_exit((void *)2); } int main() { pthread_t tid1, tid2; void *tret; error = pthread_create(&tid1, 0, thr_fn1, (void *)1); if (error) do { errno = error; perror("can’t create thread 1"); exit(1); } while (0); error = pthread_create(&tid2, 0, thr_fn2, (void *)1); if (error) do { errno = error; perror("can’t create thread 2"); exit(1); } while (0); error = pthread_join(tid1, &tret); if (error) do { errno = error; perror("can’t join with thread 1"); exit(1); } while (0); printf("thread 1: exit code %ld\\n", (long)tret); error = pthread_join(tid2, &tret); if (error) do { errno = error; perror("can’t join with thread 2"); exit(1); } while (0); printf("thread 2: exit code %ld\\n", (long)tret); exit(0); }
1
#include <pthread.h> int busCounter = 0; pthread_mutex_t busCounterLock = PTHREAD_MUTEX_INITIALIZER; int lightDir = 0; pthread_mutex_t lightDirLock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t lightDirNorth = PTHREAD_COND_INITIALIZER; pthread_cond_t lightDirSouth = PTHREAD_COND_INITIALIZER; int bussesPassed = 0; pthread_mutex_t bussesPassedLock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t bussesPassedCond = PTHREAD_COND_INITIALIZER; void depart(int direction) { pthread_mutex_lock(&busCounterLock); pthread_mutex_lock(&bussesPassedLock); printf("Bus leaving pass in direction: %i\\n", direction); busCounter--; bussesPassed++; if( busCounter == 0 && bussesPassed >= 1 ) { printf("Last bus left the pass, signalling busses waiting to leave pass to wake\\n"); pthread_mutex_unlock(&busCounterLock); pthread_mutex_unlock(&bussesPassedLock); pthread_cond_broadcast(&bussesPassedCond); } if(bussesPassed >= 1) { while(busCounter > 0) { printf("Time to change the light, but there are still %i busses in the pass, waiting for it to clear.\\n", busCounter); pthread_mutex_unlock(&busCounterLock); pthread_mutex_unlock(&bussesPassedLock); pthread_cond_wait(&bussesPassedCond, &bussesPassedLock); pthread_mutex_lock(&busCounterLock); } pthread_mutex_lock(&lightDirLock); if(direction == 0) { lightDir = 1; printf("Lights switched!\\n"); pthread_mutex_unlock(&lightDirLock); pthread_cond_broadcast(&lightDirSouth); } else { lightDir = 0; printf("Lights switched!\\n"); pthread_mutex_unlock(&lightDirLock); pthread_cond_broadcast(&lightDirNorth); } } pthread_mutex_unlock(&busCounterLock); pthread_mutex_unlock(&bussesPassedLock); } void approach(int direction) { printf("Bus approaching passage going in direction: %i.\\n", direction); pthread_mutex_lock(&lightDirLock); if(lightDir == direction) { pthread_mutex_lock(&bussesPassedLock); if(bussesPassed >= 1) { printf("Max number of busses passed, i better wait, so other side can pass!\\n"); pthread_mutex_unlock(&lightDirLock); if(direction == 0) { pthread_cond_wait(&lightDirNorth, &lightDirLock); printf("DRIVIN AGAIN!\\n"); } else { pthread_cond_wait(&lightDirSouth, &lightDirLock); printf("DRIVIN AGAIN!\\n"); } pthread_mutex_lock(&lightDirLock); } pthread_mutex_unlock(&bussesPassedLock); pthread_mutex_lock(&busCounterLock); busCounter++; printf("Light is green, bus entering going in direction: %i\\n", direction); pthread_mutex_unlock(&busCounterLock); } else { printf("Light is red!\\n"); pthread_mutex_lock(&busCounterLock); if (busCounter > 0) { pthread_mutex_unlock(&busCounterLock); printf("Waiting for light to go green.\\n"); if(direction == 0) { pthread_cond_wait(&lightDirNorth, &lightDirLock); } else { pthread_cond_wait(&lightDirSouth, &lightDirLock); } printf("Done waiting. Light is green. Bus entering pass going in direction: %i. \\n", direction); pthread_mutex_lock(&busCounterLock); busCounter++; pthread_mutex_unlock(&busCounterLock); } else { printf("Light is red, but pass is free! Switching light to green\\n"); lightDir = direction; printf("Bus entering pass going in direction: %i\\n", direction); busCounter++; pthread_mutex_unlock(&busCounterLock); } } pthread_mutex_unlock(&lightDirLock); } void busTrip(int direction) { approach(direction); sleep(1); depart(direction); } int main() { int bus1_return, bus2_return, bus3_return, bus4_return; pthread_t bus1, bus2, bus3, bus4; bus1_return = pthread_create(&bus1, 0, (void *) &busTrip, (int *) 0); printf("Bus going north thread created with status: %i\\n", bus1_return); bus2_return = pthread_create(&bus2, 0, (void *) &busTrip, (int *) 1); printf("Bus going south thread created with status: %i\\n", bus2_return); bus3_return = pthread_create(&bus3, 0, (void *) &busTrip, (int *) 1); printf("Bus going south thread created with status: %i\\n", bus3_return); bus4_return = pthread_create(&bus4, 0, (void *) &busTrip, (int *) 0); printf("Bus going north thread created with status: %i\\n", bus4_return); pthread_exit(0); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int contador=0; void *funcionConflictiva(void *argumentos){ pthread_mutex_lock(&mutex); contador++; pthread_mutex_unlock(&mutex); pthread_exit(0); } int main(int argc,char *argv[]){ int i; int cantidadHebras = atoi(argv[1]); pthread_t *arr_thread = (pthread_t*)malloc(sizeof(pthread_t)*cantidadHebras); for(i=0;i<cantidadHebras;i++){ pthread_create(&arr_thread[i],0,&funcionConflictiva,0); } for(i=0;i<cantidadHebras;i++){ pthread_join(arr_thread[i],0); } printf("El valor de contador es: %i\\n",contador); return 0; }
1
#include <pthread.h> int total_size = 0; pthread_mutex_t memory_mutex = PTHREAD_MUTEX_INITIALIZER; void *first = 0; void *last = 0; void free_mem(void* to_delete) { unsigned long *addr; unsigned long *temp; pthread_mutex_lock(&memory_mutex); temp = addr = (unsigned long *)last; *addr = (unsigned int)to_delete; last = to_delete; addr = (unsigned long *)to_delete; *addr = 0; if(first == 0) first = last; pthread_mutex_unlock(&memory_mutex); } int init_mem(int size) { char *temp; unsigned long *addr; char *end; size_t length; pthread_mutex_lock(&memory_mutex); first = (void*)malloc(5*4096); if(first == 0) return -1; temp = (char *) first; end = first + 5*4096; length = 2 * size; total_size = size; while( ( end - temp ) > length ) { addr = (unsigned long*) temp; *addr = (unsigned long)(temp+size); temp += size; } last = (void*)temp; addr = (unsigned long*)temp; *addr = 0; pthread_mutex_unlock(&memory_mutex); return 0; } void *get_memory(void) { unsigned long *addr; unsigned long addr2; if(first == 0) { if(init_mem(total_size)==-1) return(0); } pthread_mutex_lock(&memory_mutex); addr = (unsigned long *)first; addr2 = *addr; first = (void*)addr2; if(first == 0) last = 0; pthread_mutex_unlock(&memory_mutex); return(addr); }
0
#include <pthread.h> pthread_t threads[100]; int seats = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; sem_t customers; sem_t barber; void *barberBob(void *threadid){ int haircuts = 100 -1; while(haircuts > 0){ sem_wait(&customers); pthread_mutex_lock(&mutex); seats++; sem_post(&barber); haircuts--; printf("cutting some hair, waiting on next customer\\n"); pthread_mutex_unlock(&mutex); printf("\\n Barber Thread: haircuts = %d, chairs left = %d \\n",haircuts,seats); } printf("Closing shop, bye!\\n"); pthread_exit(0); } void *customer(void *threadid) { int haircuts = 1; while(haircuts > 0){ pthread_mutex_lock(&mutex); if(seats > 0){ seats--; printf("taking a seat, waiting on barber\\n"); sem_post(&customers); haircuts--; sleep(1); pthread_mutex_unlock(&mutex); sem_wait(&barber); printf("getting a haircut %d \\n", (int)threadid); } else{ pthread_mutex_unlock(&mutex); printf("\\n Customer Thread:%d couldn't get a haircut, seats = %d\\n",(int)threadid, seats); sleep(1); } } pthread_exit(0); } int main(int argc, char *argv[]) { if(argc < 2 || argc > 3){ printf("Wrong number of arguments: Usage > barber.exe x \\n"); } seats = atoi(argv[1]); printf("number of chairs %d \\n", seats); sem_init(&customers,0,0); sem_init(&barber,0,0); int t; for(t=0;t<100;t++){ printf("Creating thread %d\\n", t); if(t == 0){ pthread_create(&threads[t], 0, barberBob, (void *)t); } else{ pthread_create(&threads[t], 0, customer, (void *)t); } } for(t = 0; t < 100; t++) pthread_join(threads[t],0); pthread_exit(0); }
1
#include <pthread.h> void thread_function(); pthread_mutex_t mutex1 = PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP; volatile long long counter = 0; volatile int flag = 0; long think_spin, lock_spin; int main(int argc, char *argv[]) { pthread_t thread_id[2000]; int i, n; struct timeval tv; long long t1, t2, c1, c2; double throughput; if (argc != 4) { fprintf(stderr, "Usage: %s <num_threads> " "<think_spin_count> <lock_spin_count>\\n", argv[0]); exit(-1); } n = atoi(argv[1]); think_spin = atoi(argv[2]); lock_spin = atoi(argv[3]); assert(n <= 2000); for (i = 0; i < n; i++) { pthread_create(&thread_id[i], 0, (void*)&thread_function, 0); } sleep(1); c1 = counter; gettimeofday(&tv, 0); t1 = (1000000L * tv.tv_sec) + tv.tv_usec; sleep(10); c2 = counter; gettimeofday(&tv, 0); t2 = (1000000L * tv.tv_sec) + tv.tv_usec ; flag = 1; for (i = 0; i < n; i++) { pthread_join( thread_id[i], 0); } throughput = (((double) (c2 - c1)) * 1000000) / ((double) (t2 - t1)); printf("Clients:%d Throughput:%f\\n", n, throughput); return 0; } void thread_function() { long long i; while (!flag) { for (i = 0; i < think_spin; i++); pthread_mutex_lock(&mutex1); for (i = 0; i < lock_spin; i++); counter++; pthread_mutex_unlock(&mutex1); } pthread_exit(0); }
0
#include <pthread.h> int n, goY = 0, goZ = 0; pthread_cond_t fimX = PTHREAD_COND_INITIALIZER, fimZ = PTHREAD_COND_INITIALIZER; pthread_mutex_t the_mutex = PTHREAD_MUTEX_INITIALIZER; void X(void *argp){ pthread_mutex_lock(&the_mutex); n = n * 16; printf("X : %i\\n", n); pthread_cond_signal(&fimX); goZ = 1; pthread_mutex_unlock(&the_mutex); pthread_exit(0); } void Y(void *argp){ pthread_mutex_lock(&the_mutex); while( !goY ) pthread_cond_wait(&fimZ, &the_mutex); n = n / 7; printf("Y : %i\\n", n); pthread_mutex_unlock(&the_mutex); pthread_exit(0); } void Z(void *argp){ pthread_mutex_lock(&the_mutex); while( !goZ ) pthread_cond_wait(&fimX, &the_mutex); n = n + 40; printf("Z : %i\\n", n); pthread_cond_signal(&fimZ); goY = 1; pthread_mutex_unlock(&the_mutex); pthread_exit(0); } int main(void){ pthread_t t1, t2, t3; int rc; n = 1; rc = pthread_create(&t1, 0, (void *) X, 0); assert(rc == 0); rc = pthread_create(&t2, 0, (void *) Y, 0); assert(rc == 0); rc = pthread_create(&t3, 0, (void *) Z, 0); assert(rc == 0); rc = pthread_join(t1, 0); assert(rc == 0); rc = pthread_join(t2, 0); assert(rc == 0); rc = pthread_join(t3, 0); assert(rc == 0); printf("n = %d\\n", n); return 0; }
1
#include <pthread.h> struct foo { int f_count; pthread_mutex_t f_lock; }; struct foo * foo_alloc(void); void foo_add(struct foo *fp); void foo_release(struct foo *fp); void *thread_func1(void *arg); void *thread_func2(void *arg); int main() { pthread_t pid1, pid2; int err; void *pret; struct foo *fobj; fobj = foo_alloc(); err = pthread_create(&pid1, 0, thread_func1, (void *)fobj); if (err != 0) { perror("pthread_create error"); exit(-1); } err = pthread_create(&pid2, 0, thread_func2, (void *)fobj); if (err != 0) { perror("pthread_create error"); exit(-1); } pthread_join(pid1, &pret); printf("thread 1 exit code is: %d\\n", (int)pret); pthread_join(pid2, &pret); printf("thread 2 exit code is: %d\\n", (int)pret); exit(0); } struct foo * foo_alloc(void) { struct foo *fobj; fobj = (struct foo *)malloc(sizeof(struct foo)); if (0 != fobj) { fobj->f_count = 0; if (pthread_mutex_init(&fobj->f_lock, 0) != 0) { free(fobj); return 0; } } return fobj; } void foo_add(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; printf("f_count = %d\\n", fp->f_count); pthread_mutex_unlock(&fp->f_lock); } void foo_release(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count--; printf("f_count = %d\\n", fp->f_count); if (fp->f_count == 0) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { pthread_mutex_unlock(&fp->f_lock); } } void * thread_func1(void *arg) { struct foo *fp = (struct foo *)arg; printf("thread 1 start.\\n"); foo_release(fp); printf("thread 1 exit.\\n"); pthread_exit((void *)1); } void * thread_func2(void *arg) { struct foo *fp = (struct foo *)arg; printf("thread 2 start.\\n"); foo_add(fp); foo_add(fp); printf("thread 2 exit.\\n"); pthread_exit((void *)2); }
0