text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> char** theArray; pthread_mutex_t mutex; int aSize = 100; int usr_port; void* ServerEcho(void *args); int main(int argc, char * argv []){ printf("creating mutex \\n"); pthread_mutex_init(&mutex,0); int n = atoi(argv[2]); usr_port = atoi(argv[1]); if( (n==10)||(n==100)||(n==1000)||(n==10000) ){ aSize=n; } theArray=malloc(aSize*sizeof(char*)); for (int i=0; i<aSize;i++){ theArray[i]=malloc(100*sizeof(char)); sprintf(theArray[i], "%s%d%s", "String ", i, ": the initial value" ); } struct sockaddr_in sock_var; int serverFileDescriptor=socket(AF_INET,SOCK_STREAM,0); int clientFileDescriptor; pthread_t* thread_handles; thread_handles = malloc(1000*sizeof(pthread_t)); sock_var.sin_addr.s_addr=inet_addr("127.0.0.1"); sock_var.sin_port=usr_port; sock_var.sin_family=AF_INET; if(bind(serverFileDescriptor,(struct sockaddr*)&sock_var,sizeof(sock_var))>=0) { printf("socket has been created \\n"); listen(serverFileDescriptor,2000); while(1){ for(int i=0;i<1000;i++){ clientFileDescriptor=accept(serverFileDescriptor,0,0); printf("Connected to client %d \\n",clientFileDescriptor); pthread_create(&thread_handles[i],0,ServerEcho,(void*)clientFileDescriptor); } for(int i = 0;i<1000;i++){ pthread_join(thread_handles[i],0); } free(thread_handles); pthread_mutex_destroy(&mutex); printf("All threads have joined. Checking Array \\n"); for(int i=0;i<aSize;i++){ printf("%s\\n",theArray[i]); } for (int i=0; i<aSize;i++){ free(theArray[i]); } free(theArray); } } else{ printf("socket creation failed \\n"); return 1; } return 0; } void* ServerEcho(void* args){ long clientFileDescriptor = (long) args; char buff[100]; read(clientFileDescriptor,buff,100); int pos; char operation; int CSerror; sscanf(buff, "%d %c", &pos,&operation); printf(" Server thread received position %d and operation %c from %ld \\n",pos,operation,clientFileDescriptor); if(operation=='r'){ char msg[100]; pthread_mutex_lock(&mutex); CSerror=snprintf(msg,100, "%s", theArray[pos] ); pthread_mutex_unlock(&mutex); if(CSerror<0){ printf("ERROR: could not read from position: %d \\n", pos); sprintf(msg, "%s %d","Error writing to pos: ", pos ); } write(clientFileDescriptor,msg,100); close(clientFileDescriptor); } else if(operation=='w'){ char msg[100]; snprintf(msg,100, "%s%d%s","String ", pos, " has been modified by a write request \\n" ); pthread_mutex_lock(&mutex); CSerror=snprintf(theArray[pos],100,"%s",msg); pthread_mutex_unlock(&mutex); if(CSerror<0){ printf("ERROR: could not write to array \\n"); sprintf(msg, "%s %d","Error writing to pos: ", pos ); } write(clientFileDescriptor,msg,100); close(clientFileDescriptor); } else{ printf("ERROR: could not communicate with client %ld \\n",clientFileDescriptor); } return 0; }
1
#include <pthread.h> volatile int *signalArray; struct timeval *readTimeStamp,*detectTimeStamp; int N,NTHREADS,alarm_seconds; volatile int readSum,detectedSum,changedSignal; pthread_mutex_t changedSignal_mtx; void exitfunc(int sig) { int i,usecRead,usecDetect,detectionSpeed; int inTimeDetections = 0; struct timeval tv; for(i=0;i<detectedSum;i++) { usecRead = readTimeStamp[i].tv_usec; usecDetect = detectTimeStamp[i].tv_usec; detectionSpeed = usecDetect-usecRead; if (detectionSpeed <= 1) { inTimeDetections++; } } char buf[200]; snprintf(buf, sizeof(buf), "Results/Statistics-%d-%d.txt",NTHREADS,alarm_seconds); FILE *f = fopen(buf, "a"); if (f == 0) { printf("Error opening file!\\n"); exit(1); } fprintf(f,"%d,%d,%d,%.2f,%.2f\\n",N,readSum,detectedSum,((float)detectedSum/(float)readSum)*100 ,((float)inTimeDetections/(float)detectedSum)*100); fclose(f); fflush(stdout); printf("%d-%d-%d\\n",N,NTHREADS,alarm_seconds); _exit(0); } void *SensorSignalReader (void *args); void *ChangeDetector (void *args); int main(int argc, char **argv) { if (argc != 4) { printf("Usage: %s N NTHREADS s\\n" " where\\n" " N : number of signals to monitor\\n" " NTHREADS : number of threads\\n" " s : number of seconds to run\\n" , argv[0]); return (1); } N = atoi(argv[1]); NTHREADS = atoi(argv[2]); alarm_seconds = atoi(argv[3]); int i,rc; signal(SIGALRM, exitfunc); alarm(alarm_seconds); signalArray = (int *) malloc(N*sizeof(int)); detectTimeStamp = (struct timeval *) malloc(NTHREADS*10*alarm_seconds*sizeof(struct timeval)); readTimeStamp = (struct timeval *) malloc(NTHREADS*10*alarm_seconds*sizeof(struct timeval)); for (i=0; i<N; i++) { signalArray[i] = 0; } pthread_t sigGen; pthread_t sigDet; pthread_mutex_init(&changedSignal_mtx,0); readSum = 0; detectedSum = 0; changedSignal = -1; for(i=0;i<NTHREADS;i++) { rc = pthread_create (&sigDet, 0, ChangeDetector, 0); assert(rc == 0); } pthread_create (&sigGen, 0, SensorSignalReader, 0); pthread_join (sigDet, 0); return 0; } void *SensorSignalReader (void *arg) { struct timeval tv; srand(time(0)); while (1) { int t = rand() % 10 + 1; usleep(t*100000); int r = rand() % N; signalArray[r] ^= 1; if (signalArray[r]) { gettimeofday(&tv, 0); changedSignal = r; readTimeStamp[readSum] = tv; readSum++; } } } void *ChangeDetector (void *arg) { struct timeval tv; while (1) { pthread_mutex_lock(&changedSignal_mtx); while (changedSignal == -1) {} gettimeofday(&tv, 0); changedSignal = -1; pthread_mutex_unlock(&changedSignal_mtx); detectTimeStamp[detectedSum] = tv; detectedSum++; } }
0
#include <pthread.h> void* pass(void*); double timer(); int token; pthread_mutex_t mtx; pthread_cond_t cnd; }lock; int ID; int rounds; lock* left; lock* right; }args; int main(int argc, char* argv[]){ int p; int r; double start; double end; p = (argc > 1) ? atoi(argv[1]) : 100; r = (argc > 2) ? atoi(argv[2]) : 10000; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); long i; pthread_t threads[p]; args* thread_args[p]; lock* locks[p]; for(i=0;i<p;i++){ locks[i] = malloc(sizeof(lock)); thread_args[i] = malloc(sizeof(args)); } for(i=0;i<p;i++){ thread_args[i]->rounds = r; thread_args[i]->ID = i; thread_args[i]->left = locks[i]; thread_args[i]->right = locks[(i+1)%p]; locks[i]->token = 0; pthread_mutex_init(&locks[i]->mtx,0); } for(i=0;i<p;i++) pthread_create(&threads[i],&attr,pass,(void*)thread_args[i]); start = timer(); locks[0]->token = 3; pthread_cond_signal(&locks[0]->cnd); for(i=0;i<p;i++) pthread_join(threads[i],0); for(i=0;i<p;i++){ free(locks[i]); free(thread_args[i]); } end = timer(); printf("%g sec\\n",end-start); return 0; } void *pass(void *a){ args* t = (args*)a; int token; while(t->rounds > 0){ pthread_mutex_lock(&t->left->mtx); while(t->left->token == 0) pthread_cond_wait(&t->left->cnd,&t->left->mtx); token = t->left->token; t->left->token = 0; pthread_mutex_unlock(&t->left->mtx); pthread_mutex_lock(&t->right->mtx); t->right->token = token; pthread_cond_signal(&t->right->cnd); pthread_mutex_unlock(&t->right->mtx); t->rounds--; } } double timer() { static bool initialized = 0; static struct timeval start; struct timeval end; if( !initialized ) { gettimeofday( &start, 0 ); initialized = 1; } gettimeofday( &end, 0 ); return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec); }
1
#include <pthread.h> pthread_mutex_t lock; long counter[256]; void *thread_counting(void *ptr) { int fd; int i; int ending; char buffer[16384]; char *filename = (char*) ptr; pthread_mutex_lock(&lock); for(i=0;i<257;i++) { counter[i] = 0L; } fd = open(filename, O_RDONLY); if (fd < 0) { printf("Error reading File errno=%d file=%s\\n", errno, filename); exit(1); } while (1) { ssize_t size_read = read(fd, buffer, 16384); if (size_read == 0 ) { break; } for(i=0; i<size_read; i++) { unsigned char c = buffer[i]; counter[c]++; } } printf("---------------------------------------------------------------\\n"); printf("Filename: %s\\n", filename); printf("---------------------------------------------------------------\\n"); for(i=0; i<256; i++) { long val = counter[i]; if (! (i & 007)) { printf("\\n"); fflush(stdout); } if ((i & 0177) < 32 || i == 127) { printf("\\\\%03o: %10ld ", i, val); } else { printf("%4c: %10ld ", (char) i, val); } } printf("\\n\\n"); pthread_mutex_unlock(&lock); } int main(int argc, char *argv[]) { if(argc <= 1) { printf("Dateinamen als Parameter angeben. Beispiel: ./uebung datei.txt\\n"); exit(1); } int zaehler; int retcode; pthread_t thread[argc-1]; if (pthread_mutex_init(&lock, 0) != 0) { printf("Mutex init failed\\n"); exit(3); } printf("Starte Prozesse!\\n"); for(zaehler=1;zaehler<argc;zaehler++) { printf("Starte Thread %d\\n", zaehler); retcode = pthread_create(&thread[zaehler], 0, thread_counting, argv[zaehler]); if(retcode < 0) { printf("Error reading from pipe retcode=%d errno=%d thread=%d\\n", retcode, errno, zaehler); exit(3); } } for(zaehler=1;zaehler<argc;zaehler++) { pthread_join(thread[zaehler], 0); printf("Joining Thread %d\\n", zaehler); } pthread_mutex_destroy(&lock); }
0
#include <pthread.h> pthread_t philosopher[5]; pthread_mutex_t forks[5]; unsigned int randr (unsigned int min, unsigned int max) { double scaled = (double)rand()/32767; return scaled*(max - min + 1) + min; } void *func(void *id){ long n = (long)id; while(1){ printf("\\nPhilosopher %ld is thinking ",n); sleep(randr(1,4)); if((double)rand()/32767 < 0.5){ pthread_mutex_lock(&forks[n]); pthread_mutex_lock(&forks[(n+1)%5]); } else{ pthread_mutex_lock(&forks[(n+1)%5]); pthread_mutex_lock(&forks[n]); } printf("\\nPhilosopher %ld is eating ",n); sleep(randr(1,4)); pthread_mutex_unlock(&forks[n]); pthread_mutex_unlock(&forks[(n+1)%5]); printf("\\nPhilosopher %ld Finished eating ",n); } } int main(){ long i,k; void *msg; srand(time(0)); for(i=1;i<=5;i++) { k=pthread_mutex_init(&forks[i],0); if(k==-1) { printf("\\n Mutex initialization failed"); exit(1); } } for(i=1;i<=5;i++){ k=pthread_create(&philosopher[i],0,(void *)func,(void *)i); if(k!=0){ printf("\\n Thread creation error \\n"); exit(1); } } for(i=1;i<=5;i++){ k=pthread_join(philosopher[i],&msg); if(k!=0){ printf("\\n Thread join failed \\n"); exit(1); } } for(i=1;i<=5;i++){ k=pthread_mutex_destroy(&forks[i]); if(k!=0){ printf("\\n Mutex Destroyed \\n"); exit(1); } } return 0; }
1
#include <pthread.h> int g_positions[3] = {0}; pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t g_cond = PTHREAD_COND_INITIALIZER; void* foo(void* p_param) { int t_index = (intptr_t) p_param; while(g_positions[t_index] < 4) { if(t_index == 0) { pthread_mutex_lock(&g_mutex); g_positions[t_index]++; fprintf(stdout, "Activity (%d) start work on %d\\n", t_index, g_positions[t_index]); pthread_mutex_unlock(&g_mutex); sleep(1); fprintf(stdout, "Activity (%d) end work on %d\\n", t_index, g_positions[t_index]); pthread_cond_broadcast(&g_cond); } else { pthread_mutex_lock(&g_mutex); while(!g_positions[t_index] >= g_positions[t_index - 1]) pthread_cond_wait(&g_cond, &g_mutex); g_positions[t_index]++; fprintf(stdout, "Activity (%d) start work on %d\\n", t_index, g_positions[t_index]); pthread_mutex_unlock(&g_mutex); sleep(1); fprintf(stdout, "Activity (%d) end work on %d\\n", t_index, g_positions[t_index]); pthread_cond_broadcast(&g_cond); } } pthread_exit(0); } int main() { pthread_t t_threads[3]; for(int t_index = 0; t_index < 3; t_index++) pthread_create(&t_threads[t_index], 0, foo, (void*) (intptr_t) t_index); for(int t_index = 0; t_index < 3; t_index++) pthread_join(t_threads[t_index], 0); return 0; }
0
#include <pthread.h> sem_t semaforo; pthread_mutex_t mutex; void *body(void *arg) { int i, j; char * mychar = (char*) arg; for (j=0; j<10; j++) { pthread_mutex_lock(&mutex); for (i=0; i<1000000; i++); for (i=0; i<4; i++) { fprintf(stderr, mychar); } pthread_mutex_unlock(&mutex); } return 0; } int main() { pthread_t t1,t2,t3; pthread_attr_t myattr; int err; sem_init(&semaforo, 0, 1); pthread_mutexattr_t mymutexattr; pthread_mutexattr_init(&mymutexattr); pthread_mutex_init(&mutex, &mymutexattr); pthread_mutexattr_destroy(&mymutexattr); pthread_attr_init(&myattr); err = pthread_create(&t1, &myattr, body, (void *)"."); err = pthread_create(&t3, &myattr, body, (void *)"o"); pthread_attr_destroy(&myattr); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); sem_destroy(&semaforo); printf("\\n"); return 0; }
1
#include <pthread.h> int fd; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void analyse_port_info(unsigned int msg_data) { info.data = msg_data; if (PORT != data_id) return; if (PLUG_IN == data_info) { printf("PORT change: port%d plugged in\\n", data_no); } else if (PLUG_OUT == data_info) { printf("PORT change: port%d plugged out\\n", data_no); } } void psu_signal_fun(int signum) { unsigned int *info_arr; int i, ret; unsigned long msg_num; printf("signal handle fun\\n"); pthread_mutex_lock(&mutex); ret = ioctl(fd, READ_PORT_INFO, &msg_num); if (ret < 0){ printf("ioctrl failed\\n"); return; } if (ret == 0 && msg_num > 0) { info_arr = malloc(msg_num * sizeof(unsigned int)); if (!info_arr) { printf("No memory\\n"); return; } ret = read(fd, info_arr, sizeof(unsigned int) * msg_num); if (ret < 0) { printf("msg_num is not correct\\n"); return; } else if (ret != msg_num) printf("info msg num left %d\\n", ret); printf("MSG num : %ld\\n", msg_num); for (i = 0; i < msg_num; ++i) { analyse_port_info(info_arr[i]); } } free(info_arr); pthread_mutex_unlock(&mutex); } int main(int argc, char **argv) { unsigned char key_val; int ret, Oflags, num; time_t timep; struct sigaction act; sigset_t mask; unsigned long msg_num; fd = open("/dev/swctrl_port", O_RDWR); if (fd < 0) { printf("can't open %s\\n", PORT_DEVICE_NAME); return -1; } else printf("%s open success\\n", PORT_DEVICE_NAME); fcntl(fd, F_SETOWN, getpid()); Oflags = fcntl(fd, F_GETFL); fcntl(fd, F_SETFL, Oflags | FASYNC); pthread_mutex_init(&mutex, 0); ret = ioctl(fd, READ_INIT_SYNC, &msg_num); if (0 == ret) { if (READ_SYNC_ACK == msg_num) printf("init sync success\\n"); else { printf(" init sync failed\\n"); return -1; } } else printf("ioctrl failed\\n"); signal(SIGIO, psu_signal_fun); while (1) { sleep(100); printf("wake up!\\n"); } return 0; }
0
#include <pthread.h> static long hits_to_circle_area = 0; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; { long number_of_points; long thread_id; } pthread_input_t; void* number_of_hits( void* input ) { pthread_input_t* pt_input = ( pthread_input_t* )input; double x, y; long i; int rand_seed_x = time( 0 ) + pt_input->thread_id; int rand_seed_y = time( 0 ) + pt_input->thread_id + 1; for ( i = 0; i < pt_input->number_of_points; i++ ) { x = ( double )rand_r( &rand_seed_x ) / ( double )32767; y = ( double )rand_r( &rand_seed_y ) / ( double )32767; pthread_mutex_lock( &mutex ); if ( ( x * x + y * y ) <= 1 ) { hits_to_circle_area++; } pthread_mutex_unlock( &mutex ); } return 0; } int main( int argc, const char* argv[] ) { long number_of_points = 1000; long number_of_threads = 4; if ( argc != 3 ) { printf( "Usage: ./pi_mutex-pthread-cc <number_of_points> <number_of_threads>\\n" " using default values (1000, 4).\\n" ); } else { number_of_points = atol( argv[ 1 ] ); number_of_threads = atol( argv[ 2 ] ); } long points_per_thread = number_of_points / number_of_threads; pthread_input_t pthread_input[ number_of_threads ]; long i; double pi; clock_t timer; pthread_t threads[ number_of_threads ]; pthread_mutex_init( &mutex, 0 ); for ( i = 0; i < number_of_threads; i++ ) { pthread_input[ i ].number_of_points = points_per_thread; pthread_input[ i ].thread_id = i; } if ( number_of_points % number_of_threads != 0 ) { pthread_input[ number_of_threads - 1 ].number_of_points = points_per_thread + number_of_points % number_of_threads; } timer = clock(); for ( i = 0; i < number_of_threads; i++ ) { pthread_create( &threads[ i ], 0, number_of_hits, ( void* )&pthread_input[ i ] ); } for ( i = 0; i < number_of_threads; i++ ) { pthread_join( threads[ i ], 0 ); } pi = ( double )4.0 * hits_to_circle_area / number_of_points; timer = clock() - timer; printf( "Approximate value of pi with %lu iterations is: %g\\n", number_of_points, pi ); printf( "Difference between exact and computed values is: %g\\n", pi - 3.14159265358979323846 ); printf( "Error: %f%%\\n", ( float )( fabs( ( pi - 3.14159265358979323846 ) / ( 3.14159265358979323846 ) ) * 100 ) ); printf( "Computation time: %fs\\n", ( ( float )timer ) / CLOCKS_PER_SEC ); pthread_mutex_destroy( &mutex ); return 0; }
1
#include <pthread.h> static struct log * stat_log; static pthread_mutex_t stat_lock = PTHREAD_MUTEX_INITIALIZER; int ccnfstat_init(char * filename) { stat_log = malloc(sizeof(struct log)); char log_name[256]; snprintf(log_name, 256, "ccnf_stats_%u", g_nodeId); if (log_init(log_name, filename, stat_log, LOG_OVERWRITE | LOG_NORMAL)) return -1; return 0; } void ccnfstat_rcvd_interest(struct ccnf_interest_pkt * interest) { if (!interest) return; int bytes = MIN_INTEREST_PKT_SIZE + interest->name->len; pthread_mutex_lock(&stat_lock); log_print(stat_log, "EVENT INTEREST_RCVD %d", bytes); pthread_mutex_unlock(&stat_lock); } void ccnfstat_sent_interest(struct ccnf_interest_pkt * interest) { if (!interest) return; int bytes = MIN_INTEREST_PKT_SIZE + interest->name->len; pthread_mutex_lock(&stat_lock); log_print(stat_log, "EVENT INTEREST_SENT %d", bytes); pthread_mutex_unlock(&stat_lock); } void ccnfstat_rcvd_data(struct ccnf_data_pkt * data) { if (!data) return; int bytes = MIN_DATA_PKT_SIZE + data->name->len + data->payload_len; pthread_mutex_lock(&stat_lock); log_print(stat_log, "EVENT DATA_RCVD %d", bytes); pthread_mutex_unlock(&stat_lock); } void ccnfstat_rcvd_data_unsolicited(struct ccnf_data_pkt * data) { if (!data) return; int bytes = MIN_DATA_PKT_SIZE + data->name->len + data->payload_len; pthread_mutex_lock(&stat_lock); log_print(stat_log, "EVENT UNSOLICITED_RCVD %d", bytes); pthread_mutex_unlock(&stat_lock); } void ccnfstat_sent_data(struct content_obj * content) { if (!content) return; int bytes = MIN_DATA_PKT_SIZE + content->name->len + content->size; pthread_mutex_lock(&stat_lock); log_print(stat_log, "EVENT DATA_SENT %d", bytes); pthread_mutex_unlock(&stat_lock); }
0
#include <pthread.h> int main(int argc, char *argv[]) { int err; struct timespec tout; struct tm *tmp = 0; char buf[64] = ""; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&lock); printf("mutex is locked\\n"); clock_gettime(CLOCK_REALTIME, &tout); tmp = localtime(&tout.tv_sec); strftime(buf, sizeof(buf), "%r", tmp); printf("current time is %s\\n", buf); tout.tv_sec += 10; err = pthread_mutex_timedlock(&lock, &tout); clock_gettime(CLOCK_REALTIME, &tout); tmp = localtime(&tout.tv_sec); strftime(buf, sizeof(buf), "%r", tmp); printf("the time is now %s\\n", buf); if (err == 0) { printf("mutex locked again\\n"); } else { printf("can't lock mutex again: %s\\n", strerror(err)); } pthread_mutex_unlock(&lock); return 0; }
1
#include <pthread.h> unsigned int led_speed; pthread_mutex_t lock; static void *LEDMod(void *dummy) { unsigned int led_period; int tmp; tmp = open("/sys/class/leds/led-ds23/brightness", O_WRONLY); if (tmp < 0) exit(1); while (1) { pthread_mutex_lock(&lock); led_period = (10 - led_speed) * 16000; pthread_mutex_unlock(&lock); write(tmp, "1", 2); usleep(led_period); write(tmp, "0", 2); usleep(led_period); } } int main(int argc, char **argv) { pthread_t pth; struct input_event ev; int tmp; int key_code; int size = sizeof(ev); printf("Hello World!\\n"); led_speed = 5; tmp = open("/sys/class/leds/led-ds23/trigger", O_WRONLY); if (tmp < 0) return 1; if (write(tmp, "default-on", 10) != 10) { printf("Error writing trigger"); return 1; } close(tmp); printf("Configured LED for use\\n"); pthread_mutex_init(&lock, 0); pthread_create(&pth, 0, LEDMod, "Blinking LED..."); tmp = open("/dev/input/event0", O_RDONLY); if (tmp < 0) { printf("\\nOpen " "/dev/input/event0" " failed!\\n"); return 1; } while (1) { if (read(tmp, &ev, size) < size) { printf("\\nReading from " "/dev/input/event0" " failed!\\n"); return 1; } if (ev.value == 1 && ev.type == 1) { key_code = ev.code; if (key_code == KEY_DOWN) { pthread_mutex_lock(&lock); if (led_speed > 0) led_speed -= 1; else led_speed = 9; pthread_mutex_unlock(&lock); } else if (key_code == KEY_UP) { pthread_mutex_lock(&lock); if (led_speed < 9) led_speed += 1; else led_speed = 0; pthread_mutex_unlock(&lock); } printf("Speed: %i\\n", led_speed); usleep(1000); } } return 0; }
0
#include <pthread.h> void* producer(void*); void* consumer(void*); struct Context{ pthread_cond_t* cond; pthread_mutex_t* mutex; char holder; int error; }; int main(){ volatile struct Context context; context.cond = (pthread_cond_t*)malloc(sizeof(pthread_cond_t)); context.mutex = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t)); context.error = 0; pthread_cond_init(context.cond, 0); pthread_mutex_init(context.mutex, 0); pthread_t prod; pthread_t cons; puts("Creating first thread"); if(pthread_create(&prod, 0, producer, (void*)&context) != 0){ puts("Could not create producer thread"); pthread_mutex_destroy(context.mutex); pthread_cond_destroy(context.cond); return(1); } puts("Creating second thread"); if(pthread_create(&cons, 0, consumer, (void*)&context) != 0){ puts("Could not create consumer thread"); pthread_mutex_lock(context.mutex); context.error = 1; pthread_mutex_unlock(context.mutex); pthread_cond_signal(context.cond); pthread_join(prod, 0); pthread_mutex_destroy(context.mutex); pthread_cond_destroy(context.cond);; return(1); } pthread_join(prod, 0); pthread_join(cons, 0); pthread_mutex_destroy(context.mutex); pthread_cond_destroy(context.cond); free(context.cond); free(context.mutex); return(0); } void* producer(void* _context){ puts("in producer"); struct Context* context = (struct Context*)_context; char data[] = "Some data to send to the consumer\\n"; pthread_mutex_lock(context->mutex); int i; for(i = 0; i < sizeof(data); i++){ if(!context->error){ context->holder = data[i]; pthread_cond_signal(context->cond); pthread_cond_wait(context->cond, context->mutex); }else{ pthread_mutex_unlock(context->mutex); return 0; } } pthread_cond_signal(context->cond); pthread_mutex_unlock(context->mutex); return 0; } void* consumer(void* _context){ puts("in consumer"); struct Context* context = (struct Context*)_context; printf("Recieving data: "); pthread_mutex_lock(context->mutex); while(context->holder != '\\0'){ if(!context->error){ putc((unsigned int)context->holder, stdout); pthread_cond_signal(context->cond); pthread_cond_wait(context->cond, context->mutex); }else{ pthread_cond_signal(context->cond); pthread_mutex_unlock(context->mutex); return 0; } } pthread_cond_signal(context->cond); pthread_mutex_unlock(context->mutex); return 0; }
1
#include <pthread.h> void *consumidor(int *v); void quitaritem(int* v); void * productor(int *v); void poneritem(int* v); void imprimir(int *v,char *c); int vacio=5,lleno=0; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t si_vacio = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t si_lleno= PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t esperar_hilos= PTHREAD_MUTEX_INITIALIZER; int main(){ int *v; int i; srand(time(0)); v=(int*)malloc(5*sizeof(int)); pthread_t hilos[20],hilofinal; pthread_mutex_lock (&esperar_hilos); pthread_mutex_lock (&si_vacio); for(i=0;i<20;i++){ printf("Hilo %d\\n",i); if(rand()%2==0)pthread_create(&hilos[i],0,(void*)consumidor,v); else pthread_create(&hilos[i],0,(void*)productor,v); } pthread_mutex_unlock(&esperar_hilos); pthread_mutex_lock (&esperar_hilos); for(i=0;i<20;i++) pthread_join(hilos[i],0); pthread_mutex_unlock(&esperar_hilos); pthread_mutex_destroy(&mutex); pthread_mutex_destroy(&si_lleno); pthread_mutex_destroy(&si_vacio); pthread_mutex_destroy(&esperar_hilos); } void *consumidor(int *v){ if(vacio==4||vacio==5) pthread_mutex_lock (&si_vacio); pthread_mutex_lock (&mutex); quitaritem(v); if(lleno==4)pthread_mutex_unlock (&si_lleno); imprimir(v,"consumidor"); pthread_mutex_unlock (&mutex); } void quitaritem(int* v){ int i=0; while((v[i]!=0)&&(i<5)) i++; printf("soy consumidor y quite el valor %d\\n" ,i-1); v[i-1]=0; vacio++; lleno--; printf("Consumidor: lleno:%d, vacio:%d\\n",lleno,vacio); } void * productor(int *v){ if(lleno==4||lleno==5) pthread_mutex_lock (&si_lleno); pthread_mutex_lock (&mutex); poneritem(v); if (vacio==4)pthread_mutex_unlock (&si_vacio); imprimir(v,"productor"); pthread_mutex_unlock (&mutex); } void poneritem(int* v){ int i=0,k; while(v[i]!=0) i++; printf("Soy productor y puse en el valor %d\\n",i); v[i]=rand()%5+1; lleno++; vacio--; printf("Productor: lleno:%d, vacio:%d\\n",lleno,vacio); } void imprimir(int *v,char *c){ int i; printf("El %s \\n",c); for(i=0;i<5;i++){ printf("v[%d]=%d\\n",i,v[i]); } }
0
#include <pthread.h> unsigned int counter = 0; unsigned int result = 0; pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t result_mutex = PTHREAD_MUTEX_INITIALIZER; void* chain( void* ); void main() { setvbuf(stdout, 0, _IONBF, 0); int i; pthread_t thr[4]; for ( i= 0; i < 4; i++ ) { if( pthread_create( &thr[i], 0, &chain, 0 )) { printf("Could not create thread %d.\\n", i); exit(-1); } } for(i = 0; i < 4; i++) { if(pthread_join(thr[i], 0)) { printf("Could not join thread %d.\\n", i); exit(-1); } } printf("\\nResult: %d\\n", result); } void* chain( void *callsign ) { unsigned int next, i; unsigned int this; for ( ;; ) { pthread_mutex_lock(&counter_mutex); if( ++counter >= 10000000 ) { pthread_mutex_unlock(&counter_mutex); return; } else this = counter; if( counter % 100000 == 99999 ) { printf("."); } pthread_mutex_unlock(&counter_mutex); for ( ;; ) { next = 0; while( this > 0 ) { i = this % 10; next = next + ( i * i ); this = this / 10; } if(next == 1) { break; } else if(next == 89) { pthread_mutex_lock(&result_mutex); result++; pthread_mutex_unlock(&result_mutex); break; } this = next; } } }
1
#include <pthread.h> int *washedcars; int *machine; double *timeWash; int *flag; pthread_mutex_t mutex; pthread_cond_t IsMachine; struct timeval startT, nowT; int RunThread(void* id) { int ID=(int)id; struct timeval Wasingtime; pthread_mutex_lock(&mutex); if(*machine<=0) pthread_cond_wait(&IsMachine,&mutex); *machine-=1; pthread_mutex_unlock(&mutex); gettimeofday(&Wasingtime, 0); printf("Im: %d Enter to wash in time: %lf\\n", ID, GetTime(startT, UpdateTime(nowT))); usleep((int)(pow(10, 6) * nextTime(1.0 / 3.0)*-1)); printf("Im: %d Finish wash in time: %lf\\n", ID, GetTime(startT, UpdateTime(nowT))); pthread_mutex_lock(&mutex); *timeWash += GetTime(Wasingtime, UpdateTime(nowT)); *washedcars += 1; *machine+=1; pthread_cond_signal(&IsMachine); pthread_mutex_unlock(&mutex); pthread_exit(0); } void UserStop(){ signal(SIGINT,UserStop); *flag=1;} int main() { int t=1; int N, run ; float avgC ; void *status; pthread_t *Cars; pthread_attr_t attr; printf("enter num of wash station(1-5):\\nnum of run time program(in seconds)\\nnum of avg arrival car to station:\\n"); scanf("%d%d%f", &N,&run,&avgC); washedcars=(int *)calloc(1,sizeof(int)); machine=(int *)calloc(1,sizeof(int)); timeWash=(double *)calloc(1,sizeof(double)); flag=(int*)calloc(1,sizeof(int)); Cars=(pthread_t *)calloc(1,sizeof(pthread_t)); *machine=N; pthread_mutex_init(&mutex, 0); pthread_cond_init(&IsMachine,0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); gettimeofday(&startT, 0); while ( GetTime(startT, UpdateTime(nowT))<=run && *flag==0) { signal(SIGINT,UserStop); pthread_create(&Cars[t],&attr,RunThread,(void*)t); printf("FFF%d",*flag); printf("\\nIm: %d {{Enterd to Queue}} in time: %lf\\n", t, GetTime(startT, UpdateTime(nowT))); t++; usleep((int)(pow(10,6)*nextTime(1.0/avgC))*-1); } printf("\\n--------------------------After Time Ended-------------------------------\\n\\n"); int i; for (i = t-1; i >=1; i--) { pthread_join(Cars[i],&status); } printf("\\n\\n{///////////End program////////////}\\n"); printf("car washed--> [%d], in Total run Time: %lf(s)\\n", *washedcars, GetTime(startT, UpdateTime(nowT))); printf("avg wash time: %lf(s)\\n", *timeWash / (*washedcars)); free(washedcars); free(machine); free(timeWash); pthread_attr_destroy(&attr); pthread_mutex_destroy(&mutex); pthread_exit(0); return 0; }
0
#include <pthread.h> pthread_mutex_t apopen_mutex = PTHREAD_MUTEX_INITIALIZER; struct popen_list_item { struct popen_list_item *next; FILE *f; pid_t pid; }; static struct popen_list_item *popen_list ; FILE *apopen(const char *command, const char *modes) { FILE *fp; struct popen_list_item *pi; struct popen_list_item *po; int pipe_fd[2]; int parent_fd; int child_fd; int child_writing; pid_t pid; child_writing = 0; if (modes[0] != 'w') { ++child_writing; if (modes[0] != 'r') { goto RET_NULL; } } if (!(pi = malloc(sizeof(struct popen_list_item)))) { goto RET_NULL; } if (pipe(pipe_fd)) { goto FREE_PI; } child_fd = pipe_fd[child_writing]; parent_fd = pipe_fd[1-child_writing]; if (!(fp = fdopen(parent_fd, modes))) { close(parent_fd); close(child_fd); goto FREE_PI; } pthread_mutex_lock(&apopen_mutex); if ((pid = fork()) == 0) { close(parent_fd); if (child_fd != child_writing) { dup2(child_fd, child_writing); close(child_fd); } printf("settting pg\\n"); if ( setpgid(0, 0) ) { printf("setpgid failed: %s\\n", strerror(errno)); } for (po = popen_list ; po ; po = po->next) { close(fileno(po->f)); } execl("/bin/sh", "sh", "-c", command, (char *)0); _exit(127); } close(child_fd); if (pid > 0) { if (0) syslog(LOG_DEBUG, "putting %i into the child list\\n", pid); pi->pid = pid; pi->f = fp; pi->next = popen_list; popen_list = pi; pthread_mutex_unlock(&apopen_mutex); return fp; } pthread_mutex_unlock(&apopen_mutex); fclose(fp); FREE_PI: free(pi); RET_NULL: return 0; } int apclose(FILE *stream) { struct popen_list_item *p; int stat; pid_t pid; pthread_mutex_lock(&apopen_mutex); if ((p = popen_list) != 0) { if (p->f == stream) { popen_list = p->next; } else { struct popen_list_item *t; do { t = p; if (!(p = t->next)) { break; } if (p->f == stream) { t->next = p->next; break; } } while (1); } } if (p) { pid = p->pid; free(p); fclose(stream); do { if (waitpid(pid, &stat, 0) >= 0) { pthread_mutex_unlock(&apopen_mutex); if (0) syslog(LOG_DEBUG, "removed %i from the child list\\n", pid); return stat; } if (errno != EINTR) { break; } } while (1); } pthread_mutex_unlock(&apopen_mutex); if (0) syslog(LOG_DEBUG, "something was wrong\\n"); return -1; } void apopen_shutdown(void) { pthread_mutex_lock(&apopen_mutex); struct popen_list_item *cursor = popen_list; while ( cursor ) { if (0) syslog(LOG_DEBUG, "about to kill %i\\n", cursor->pid); if ( kill( -(cursor->pid), SIGKILL) ) { if (0) syslog(LOG_DEBUG, "kill(%i, SIGKILL) failed: %s\\n", cursor->pid, strerror(errno)); } cursor = cursor->next; } if (0) syslog(LOG_DEBUG, "all processes got their kill\\n"); cursor = popen_list; while ( cursor ) { if (0) syslog(LOG_DEBUG, "waiting %i\\n", cursor->pid); if ( waitpid(cursor->pid, 0, 0) == -1 ) { if (0) syslog(LOG_DEBUG, "waitpid for %i failed: %s\\n", cursor->pid, strerror(errno)); } cursor = cursor->next; } pthread_mutex_unlock(&apopen_mutex); }
1
#include <pthread.h> double red[10000] = {100.0, 0.0}; double blk[10000] = {100.0, 0.0}; pthread_t ids[10000]; int sizep[10000]; int nprocs; struct ARGS { int beg, end, t, id; } sp[10000]; pthread_mutex_t *mut; void *slave(void *p) { int i, ii, ini, fim, ticks, id, cnt = 0; ini = ((struct ARGS *)p)->beg; fim = ((struct ARGS *)p)->end; ticks = ((struct ARGS *)p)->t; id = ((struct ARGS *)p)->id; printf("%d %d %d %d\\n", ini, fim, ticks, id); for (ii = 0; ii < ticks; ii++) { if (id > 0) { pthread_mutex_lock(&mut[id-1]); blk[ini] = (red[ini-1] + red[ini+1])/2.0; cnt++; pthread_mutex_unlock(&mut[id-1]); } else { blk[ini] = (red[ini-1] + red[ini+1])/2.0; cnt++; } for (i = ini+1; i < fim-1; i++) { blk[i] = (red[i-1] + red[i+1])/2.0; cnt++; } if (id < nprocs-1) { pthread_mutex_lock(&mut[id+1]); blk[ini] = (red[fim-2] + red[fim])/2.0; cnt++; pthread_mutex_unlock(&mut[id+1]); } else { blk[fim-1] = (red[fim-2] + red[fim])/2.0; cnt++; } if (id > 0) { pthread_mutex_lock(&mut[id-1]); red[ini] = (blk[ini-1] + blk[ini+1])/2.0; cnt++; pthread_mutex_unlock(&mut[id-1]); } else { red[ini] = (blk[ini-1] + blk[ini+1])/2.0; cnt++; } for (i = ini+1; i < fim-1; i++) { red[i] = (blk[i-1] + blk[i+1])/2.0; cnt++; } if (id < nprocs-1) { pthread_mutex_lock(&mut[id+1]); red[ini] = (blk[fim-2] + blk[fim])/2.0; cnt++; pthread_mutex_unlock(&mut[id+1]); } else { red[fim-1] = (blk[fim-2] + blk[fim])/2.0; cnt++; } } return 0; } int main(int argc, char **argv) { int i; void *retval; nprocs = argc > 1 ? atoi(argv[1]) : 1; if (nprocs < 1) nprocs = 1; else if (nprocs >= 10000) nprocs = 10000; mut = malloc(nprocs * sizeof(*mut)); for (i = 0; i < nprocs; i++) { pthread_mutex_init(&mut[i], 0); sizep[i] = (10000 -2)/nprocs; if (i < (10000 -2) % nprocs) sizep[i]++; printf("THR %d :: %d\\n", i, sizep[i]); } sizep[nprocs] = 10000; sp[0].beg = 1; sp[0].end = sizep[0] + 1; sp[0].t = 10000 * 10; sp[i].id = 0; pthread_create(&ids[0], 0, slave, (void *) &sp[0]); for (i = 1; i < nprocs; i++) { sp[i].beg = sp[i-1].end; sp[i].end = sp[i-1].beg + sizep[i]; sp[i].t = 10000 * 10; sp[i].id = i; pthread_create(&ids[i], 0, slave, (void *) &sp[i]); } for (i = 0; i < nprocs; i++) if (pthread_join(ids[i], &retval)) { fprintf(stderr, "%d: thread falhou\\n", i); return 1; } for (i = 0; i < 10; i++) { printf(" %7.3f", red[i]); } printf("\\n"); return 0; }
0
#include <pthread.h> struct mpd_connection *conn; pthread_mutex_t mpd_mutex; pthread_t mpd_fred; long ts_stop = 0; int easympd_internal_debug; static int handle_error(struct mpd_connection *c) { assert(mpd_connection_get_error(c) != MPD_ERROR_SUCCESS); fprintf(stderr, "%s\\n", mpd_connection_get_error_message(c)); mpd_connection_free(c); return 1; } void easympd_volume(int volume) { if(easympd_internal_debug) printf("Setting MPD volume to %d.\\n",volume); pthread_mutex_lock (&mpd_mutex); mpd_run_set_volume(conn, volume); pthread_mutex_unlock (&mpd_mutex); } long get_ts() { time_t result = time(0); return (long)result; } static void *status_fred(void* val) { while(1) { sleep(1); long ts_current = get_ts(); long timeleft = ts_stop - ts_current; struct mpd_status * status; struct mpd_song *song; const struct mpd_audio_format *audio_format; pthread_mutex_lock (&mpd_mutex); status = mpd_run_status(conn); if (status == 0) { handle_error(conn); } else if(easympd_internal_debug) { printf("StatusCheck at %ld ... Volume: %i ... Seconds left: %ld\\n", ts_current, mpd_status_get_volume(status),timeleft); } if(timeleft < 0) { mpd_run_stop(conn); } pthread_mutex_unlock (&mpd_mutex); } } void easympd_change(const char * earl) { pthread_mutex_lock (&mpd_mutex); mpd_run_clear(conn); mpd_run_add_id_to(conn,earl,0); mpd_run_play_pos(conn,0); pthread_mutex_unlock (&mpd_mutex); } void easympd_play(int seconds) { pthread_mutex_lock (&mpd_mutex); ts_stop = get_ts() + seconds; mpd_run_play(conn); pthread_mutex_unlock (&mpd_mutex); } int easympd_setup(int debug) { easympd_internal_debug = debug; pthread_mutex_init (&mpd_mutex, 0); int rc = 1; while(rc != MPD_ERROR_SUCCESS) { conn = mpd_connection_new("localhost", 0, 60000); rc = mpd_connection_get_error(conn); if (mpd_connection_get_error(conn) != MPD_ERROR_SUCCESS) { printf("Failed to connect to MPD (%d). Retrying in a sec.",rc); sleep(1); } } rc = pthread_create( &mpd_fred, 0, &status_fred, 0 ); if( rc != 0 ) { printf("Cannot start status and keepalive thread.\\n"); return 1; } return 0; }
1
#include <pthread.h> static pthread_mutex_t gAllocMutex; int MSGBUF_SYS_init (void) { pthread_mutex_init (&gAllocMutex, 0); return 0; } void * MSGBUF_SYS_malloc ( size_t xSize ) { void * pData; pthread_mutex_lock (&gAllocMutex); pData = malloc (xSize); pthread_mutex_unlock (&gAllocMutex); return pData; } void MSGBUF_SYS_free ( void * pxData ) { pthread_mutex_lock (&gAllocMutex); free (pxData); pthread_mutex_unlock (&gAllocMutex); } int MSGBUF_SYS_terminate (void) { pthread_mutex_destroy (&gAllocMutex); return 0; }
0
#include <pthread.h> static int sPowerStatefd; static const char *pwr_state_mem = "mem"; static const char *pwr_state_on = "on"; static pthread_t tinasuspend_thread; static pthread_mutex_t tinasuspend_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t tinasuspend_cond = PTHREAD_COND_INITIALIZER; static bool wait_for_tinasuspend; static enum { EARLYSUSPEND_ON, EARLYSUSPEND_MEM, } tinasuspend_state = EARLYSUSPEND_ON; extern void (*wakeup_func)(bool success); int tinasuspend_set_state(unsigned int state) { if(state != EARLYSUSPEND_ON && state != EARLYSUSPEND_MEM) return -1; if (wait_for_tinasuspend) { pthread_mutex_lock(&tinasuspend_mutex); tinasuspend_state = state; pthread_cond_signal(&tinasuspend_cond); pthread_mutex_unlock(&tinasuspend_mutex); } return 0; } int tinasuspend_wait_resume(void) { if (wait_for_tinasuspend) { pthread_mutex_lock(&tinasuspend_mutex); while(tinasuspend_state == EARLYSUSPEND_MEM) pthread_cond_wait(&tinasuspend_cond, &tinasuspend_mutex); pthread_mutex_unlock(&tinasuspend_mutex); } return 0; } static void *tinasuspend_thread_func(void *arg) { int ret; bool success; while (1) { pthread_mutex_lock(&tinasuspend_mutex); while(tinasuspend_state == EARLYSUSPEND_ON) { pthread_cond_wait(&tinasuspend_cond, &tinasuspend_mutex); } pthread_mutex_unlock(&tinasuspend_mutex); TLOGI("prepare standy!\\n"); TLOGV("%s: write %s to %s\\n", __func__, pwr_state_mem, SYS_POWER_STATE); ret = TEMP_FAILURE_RETRY(write(sPowerStatefd, pwr_state_mem, strlen(pwr_state_mem))); if (ret < 0) { success = 0; } TLOGI("sleep 2s, wait for enter standby\\n", ret); sleep(2); pthread_mutex_lock(&tinasuspend_mutex); tinasuspend_state = EARLYSUSPEND_ON; pthread_cond_signal(&tinasuspend_cond); pthread_mutex_unlock(&tinasuspend_mutex); ret = TEMP_FAILURE_RETRY(write(sPowerStatefd, pwr_state_on, strlen(pwr_state_on))); TLOGI("resume, perform wakeup function!\\n"); void (*func)(bool success) = wakeup_func; if (func != 0) { (*func)(success); } } } static int autosuspend_tinasuspend_enable(void) { char buf[80]; int ret; TLOGV("autosuspend_tinasuspend_enable\\n"); ret = write(sPowerStatefd, pwr_state_on, strlen(pwr_state_on)); if (ret < 0) { strerror_r(errno, buf, sizeof(buf)); TLOGE("Error writing to %s: %s\\n", "/sys/power/state", buf); } if (wait_for_tinasuspend) { pthread_mutex_lock(&tinasuspend_mutex); while (tinasuspend_state != EARLYSUSPEND_ON) { pthread_cond_wait(&tinasuspend_cond, &tinasuspend_mutex); } pthread_mutex_unlock(&tinasuspend_mutex); } TLOGV("autosuspend_tinasuspend_enable done\\n"); return 0; err: return ret; } static int autosuspend_tinasuspend_disable(void) { char buf[80]; int ret; TLOGV("autosuspend_tinasuspend_disable\\n"); ret = TEMP_FAILURE_RETRY(write(sPowerStatefd, pwr_state_on, strlen(pwr_state_on))); if (ret < 0) { strerror_r(errno, buf, sizeof(buf)); TLOGE("Error writing to %s: %s\\n", "/sys/power/state", buf); } if (wait_for_tinasuspend) { pthread_mutex_lock(&tinasuspend_mutex); while (tinasuspend_state != EARLYSUSPEND_ON) { pthread_cond_wait(&tinasuspend_cond, &tinasuspend_mutex); } pthread_mutex_unlock(&tinasuspend_mutex); } TLOGV("autosuspend_tinasuspend_disable done\\n"); return 0; err: return ret; } struct autosuspend_ops autosuspend_tinasuspend_ops = { .enable = autosuspend_tinasuspend_enable, .disable = autosuspend_tinasuspend_disable, }; struct autosuspend_ops *autosuspend_tinasuspend_init(void) { char buf[80]; int ret; sPowerStatefd = TEMP_FAILURE_RETRY(open("/sys/power/state", O_RDWR)); if (sPowerStatefd < 0) { strerror_r(errno, buf, sizeof(buf)); TLOGW("Error opening %s: %s\\n", "/sys/power/state", buf); return 0; } ret = TEMP_FAILURE_RETRY(write(sPowerStatefd, "on", 2)); if (ret < 0) { strerror_r(errno, buf, sizeof(buf)); TLOGW("Error writing 'on' to %s: %s\\n", "/sys/power/state", buf); goto err_write; } TLOGI("Selected tina suspend\\n"); ret = pthread_create(&tinasuspend_thread, 0, tinasuspend_thread_func, 0); if (ret) { strerror_r(errno, buf, sizeof(buf)); TLOGE("Error creating thread: %s\\n", buf); goto err_write; } wait_for_tinasuspend = 1; return &autosuspend_tinasuspend_ops; err_write: close(sPowerStatefd); return 0; }
1
#include <pthread.h> double red[200]; pthread_mutex_t lock; pthread_t threads[200]; struct RedEnvelo { double money; int num; }re; struct Person { int id; double m; int flag; }per[200]; void CreatRedenve(double m,int n) { pthread_mutex_lock(&lock); re.money = m; re.num = n; pthread_mutex_unlock(&lock); printf("红包已放入!\\n"); } void* DistrubuteRedenve(void *j) { srand((int)time(0)); double m =((struct RedEnvelo*)j)->money; int n =((struct RedEnvelo*)j)->num; double restmoney = m; int restnum = n; double redmax = m / n * 2; for(int i=0; i < n-1; i++) { red[i] = (rand() % (int)(redmax * 100) + 1) / 100.0; restmoney -= red[i]; redmax = restmoney / (n - i - 1) * 2; } red[n-1] = restmoney; return (void*)2; } void* Getrede(void* j) { int i = *(int*)j; pthread_mutex_lock(&lock); if(per[i].flag == 0) { printf("第%d个人拿走的金额是:%.2lf\\n",i+1,red[i]); re.money = re.money - red[i]; re.num = re.num - 1; printf("剩余金额:%.2lf 剩余红包个数:%d\\n",re.money,re.num); per[i].id = i; per[i].m = red[i]; per[i].flag =1; } pthread_mutex_unlock(&lock); return (void*)1; } int main() { struct RedEnvelo* p; p = &re; pthread_mutex_init(&lock,0); pthread_t t; double money = 0; int num = 0; printf("请输入红包金额:\\n"); scanf("%lf",&money); printf("请输入红包个数:\\n"); scanf("%d",&num); CreatRedenve(money,num); memset(per,0,sizeof(struct Person)*(num)); pthread_create(&t,0,DistrubuteRedenve,p); pthread_join(t,0); for(int i=0; i < num; i++) { pthread_create(&threads[i],0,Getrede,(void*)&i); pthread_join(threads[i],0); } pthread_mutex_destroy(&lock); return 0; }
0
#include <pthread.h> int memory[(2*960+1)]; int next_alloc_idx = 1; pthread_mutex_t m; int top; int index_malloc(){ int curr_alloc_idx = -1; pthread_mutex_lock(&m); if(next_alloc_idx+2-1 > (2*960+1)){ pthread_mutex_unlock(&m); curr_alloc_idx = 0; }else{ curr_alloc_idx = next_alloc_idx; next_alloc_idx += 2; pthread_mutex_unlock(&m); } return curr_alloc_idx; } void EBStack_init(){ top = 0; } int isEmpty() { if(top == 0) return 1; else return 0; } int push(int d) { int oldTop = -1, newTop = -1, casret = -1; newTop = index_malloc(); if(newTop == 0){ return 0; }else{ memory[newTop+0] = d; while (1) { oldTop = top; memory[newTop+1] = oldTop; if(__sync_bool_compare_and_swap(&top,oldTop,newTop)){ return 1; } } } } void __VERIFIER_atomic_assert(int r) { __atomic_begin(); assert(!(!r || !isEmpty())); __atomic_end(); } void push_loop(){ int r = -1; int arg = __nondet_int(); while(1){ r = push(arg); __VERIFIER_atomic_assert(r); } } pthread_mutex_t m2; int state = 0; void* thr1(void* arg) { pthread_mutex_lock(&m2); switch(state) { case 0: EBStack_init(); state = 1; case 1: pthread_mutex_unlock(&m2); push_loop(); break; } return 0; } int main() { pthread_t t1,t2; pthread_create(&t1, 0, thr1, 0); pthread_create(&t2, 0, thr1, 0); return 0; }
1
#include <pthread.h> struct _image_t { int width; int height; image_t *next; unsigned char data[1]; }; static inline unsigned int get_pixel (image_t *img, int x, int y) { return (unsigned int) img->data[(img->width * y) + x]; } static inline void set_pixel (image_t *img, int x, int y, unsigned int v) { img->data[(img->width * y) + x] = (unsigned char) (v < 255 ? v : 255); } static inline unsigned int add_pixel (const int kw, int x, int y, int p_x, int p_y, int pixel) { int d_x = x - p_x; int d_y = y - p_y; unsigned int d = (d_x * d_x) + (d_y * d_y); if (d == 0) return pixel * kw; else return (pixel * kw) / d; } static void blur_image (const int kw, image_t *in, image_t *out) { int width = in->width < out->width ? in->width : out->width; int height = in->height < out->height ? in->height : out->height; int y; for (y = 0; y < height; ++y) { int x; for (x = 0; x < width; ++x) { unsigned int sum = 0; unsigned int c = 0; int i, j; for (j = 0; j < kw; ++j) { int p_y = y + j - (kw >> 1); if (p_y < 0 || p_y >= height) continue; for (i = 0; i < kw; ++i) { int p_x = x + i - (kw >> 1); if (p_x < 0 || p_x >= width) continue; unsigned int p = get_pixel (in, p_x, p_y); sum += add_pixel (kw, x, y, p_x, p_y, p); c++; } } set_pixel (out, x, y, sum / c); } } } static image_t *image_alloc (int width, int height) { image_t *img = (image_t *) malloc ( sizeof (image_t) + (width * height) ); img->width = width; img->height = height; img->next = 0; return img; } static void image_free (image_t *img) { free (img); } static pthread_mutex_t lock; static pthread_cond_t want_work; static pthread_cond_t work_available; static pthread_cond_t worker_terminated; static volatile int complete = 0; static volatile int workers = 0; static image_t *volatile next_image = 0; static void *element (void *p) { for (;;) { image_t *img = 0; pthread_mutex_lock (&lock); while (!complete && next_image == 0) { pthread_cond_signal (&want_work); pthread_cond_wait (&work_available, &lock); } img = next_image; if (img == 0) { break; } else { next_image = img->next; } pthread_mutex_unlock (&lock); { image_t *buf = image_alloc (img->width, img->height); blur_image (9, img, buf); image_free (img); image_free (buf); } } workers--; pthread_cond_signal (&worker_terminated); pthread_mutex_unlock (&lock); return 0; } static void server (int frames, int elements, int queuing) { int width = 512, height = 512; int i; fprintf (stdout, "start\\n"); fflush (stdout); for (i = 0; i < frames; ++i) { image_t *img = image_alloc (width, height); memset (img->data, 128, width * height); pthread_mutex_lock (&lock); if (next_image != 0) { if (queuing) { img->next = next_image; } else { pthread_cond_wait (&want_work, &lock); } } next_image = img; pthread_cond_signal (&work_available); pthread_mutex_unlock (&lock); } pthread_mutex_lock (&lock); while (next_image != 0) pthread_cond_wait (&want_work, &lock); complete = 1; pthread_cond_broadcast (&work_available); while (workers > 0) pthread_cond_wait (&worker_terminated, &lock); pthread_mutex_unlock (&lock); fprintf (stdout, "end\\n"); fflush (stdout); } static void proc_main (int frames, int elements, int queuing) { int i; pthread_mutex_init (&lock, 0); pthread_cond_init (&want_work, 0); pthread_cond_init (&work_available, 0); pthread_cond_init (&worker_terminated, 0); workers = elements; for (i = 0; i < elements; ++i) { pthread_t thread; pthread_create (&thread, 0, element, 0); } server (frames, elements, queuing); } int main (int argc, char *argv[]) { int elements = 1; int frames = 64; int queuing = 0; if (argc >= 2) frames = atoi (argv[1]); if (argc >= 3) elements = atoi (argv[2]); if (argc >= 4) queuing = atoi (argv[3]); proc_main (frames, elements, queuing); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; void unlock(void *p) { printf(" call the cleanup to unlock\\n"); } void *thread_func1(void *p) { pthread_cleanup_push(unlock,0); pthread_mutex_lock(&mutex); long int i=0; sleep(1); while(i<1000000) { i++; (*(long int*)p)++; } pthread_exit((void*)i); pthread_mutex_unlock(&mutex); pthread_cleanup_pop(0); } void *thread_func2(void *p) { long int i=0; while(i<1000000) { i++; pthread_mutex_lock(&mutex); (*(long int*)p)++; pthread_mutex_unlock(&mutex); } pthread_exit((void*)i); } int main() { pthread_t thid1,thid2; long int ret1=0,ret2=0; long int *p=(long int *)malloc(sizeof(long int)); pthread_mutexattr_t mutexattr; pthread_mutexattr_init(&mutexattr); pthread_mutexattr_settype(&mutexattr,PTHREAD_MUTEX_TIMED_NP); pthread_mutex_init(&mutex,&mutexattr); pthread_create(&thid1,0,thread_func1,p); pthread_create(&thid2,0,thread_func2,p); pthread_cancel(thid1); pthread_join(thid1,(void**)&ret1); printf("the first child thread return value is %ld\\n",ret1); pthread_join(thid2,(void**)&ret2); printf("the second child thread return value is %ld\\n",ret2); pthread_mutex_destroy(&mutex); printf("the sum=%ld\\n",*p); }
1
#include <pthread.h> void usync_queue_init(struct usync_queue *q) { pthread_mutex_init(&q->qlist_mutex, 0); pthread_cond_init(&q->qlist_cond, 0); ulist_head_init(&q->qlist); ulist_head_init(&q->accum_list); q->active = 1; } inline void usync_queue_push_list_(struct usync_queue *q, struct ulist_head *h) { pthread_mutex_lock(&q->qlist_mutex); ulist_append_list(&q->qlist, h); pthread_cond_signal(&q->qlist_cond); pthread_mutex_unlock(&q->qlist_mutex); } void usync_queue_accum(struct usync_queue *q, struct ulist_node *n) { ulist_add_tail(&q->accum_list, n); } void usync_queue_push_accum(struct usync_queue *q) { usync_queue_push_list_(q, &q->accum_list); } void usync_queue_push_list(struct usync_queue *q, struct ulist_head *h) { usync_queue_push_list_(q, h); } void usync_queue_push_node(struct usync_queue *q, struct ulist_node *n) { pthread_mutex_lock(&q->qlist_mutex); ulist_add_tail(&q->qlist, n); pthread_cond_signal(&q->qlist_cond); pthread_mutex_unlock(&q->qlist_mutex); } const void *usync_queue_pop_(struct usync_queue *q, size_t off) { const void *p; pthread_mutex_lock(&q->qlist_mutex); while (q->active && ulist_empty(&q->qlist)) { pthread_cond_wait(&q->qlist_cond, &q->qlist_mutex); } p = (q->active) ? ulist_pop_(&q->qlist, off) : 0; pthread_mutex_unlock(&q->qlist_mutex); return p; } int usync_queue_pull_list(struct usync_queue *q, struct ulist_head *h) { int err = 0; pthread_mutex_lock(&q->qlist_mutex); while (q->active && ulist_empty(&q->qlist)) { pthread_cond_wait(&q->qlist_cond, &q->qlist_mutex); } if (q->active) ulist_append_list(h, &q->qlist); else err = -1; pthread_mutex_unlock(&q->qlist_mutex); return err; } void usync_queue_shutdown(struct usync_queue *q) { pthread_mutex_lock(&q->qlist_mutex); while (!ulist_empty(&q->qlist)) { pthread_mutex_unlock(&q->qlist_mutex); sched_yield(); pthread_mutex_lock(&q->qlist_mutex); } q->active = 0; pthread_cond_signal(&q->qlist_cond); pthread_mutex_unlock(&q->qlist_mutex); }
0
#include <pthread.h> pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; pthread_t thr[(10)]; int pass[(10)] = {0}; void* thread_func(void *arg) { size_t index = (size_t)arg; pass[index] = 1; pthread_mutex_lock(&mut); pthread_mutex_unlock(&mut); return 0; } void DetachPin(unsigned int num) { assert(0); } int main () { int check = 0; size_t i = 0; pthread_mutex_lock(&mut); for (i = 0; i < (10); ++i) { pthread_create(&thr[i], 0, thread_func, (void*)i); } while (!check) { check = 1; for (i = 0; i < (10); ++i) { check &= pass[i]; } sched_yield(); } sleep(1); DetachPin((10)+1); pthread_mutex_unlock(&mut); for (i = 0; i < (10); ++i) { pthread_join(thr[i], 0); } return 0; }
1
#include <pthread.h> int buff[100]; int i=0; int produrre=100000; pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condizione=PTHREAD_COND_INITIALIZER; void *produttori(void *arg){ int indice =*(int*)arg; while(i<produrre){ pthread_mutex_lock(&mutex); buff[i]=rand()%15; i++; pthread_mutex_unlock(&mutex); } printf("ueue\\n"); pthread_exit(0); } void *consuma(void *arg){ pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); pthread_exit(0); } int main(int argc, char const *argv[]) { int n = atoi(argv[1]); pthread_t threads[n]; for (int i = 0; i < n;i++) { int *indice= malloc(sizeof(int)); *indice=i; pthread_create(&threads[i],0,produttori,indice); } pthread_create(&threads[n],0,consuma,0); for (i=0;i<=n;i++){ pthread_join(threads[i],0); } return 0; }
0
#include <pthread.h> void Emove_player(){ int f=0; float x=0, y=0, z=0; pthread_mutex_lock(&Tlock_input); x = EGinput.v_move_rel[0]; y = EGinput.v_move_rel[2]; z = EGinput.v_move_rel[1]; if(EGplayer.look[0]>90) EGplayer.look[0]=90; if(EGplayer.look[0]<-90)EGplayer.look[0]=-90; if(EGinput.PressedKeys[SDLK_w]){ EGinput.v_move_rel[0]-=sin(EGplayer.look[1]*M_PI/180); EGinput.v_move_rel[2]+=cos(EGplayer.look[1]*M_PI/180); f++; } if(EGinput.PressedKeys[SDLK_s]){ EGinput.v_move_rel[0]+=sin(EGplayer.look[1]*M_PI/180)*0.9; EGinput.v_move_rel[2]-=cos(EGplayer.look[1]*M_PI/180)/0.9; f++; } if(EGinput.PressedKeys[SDLK_a]){ EGinput.v_move_rel[0]+=(cos(EGplayer.look[1]*M_PI/180)*0.75); EGinput.v_move_rel[2]+=(sin(EGplayer.look[1]*M_PI/180)*0.75); f++; } if(EGinput.PressedKeys[SDLK_d]){ EGinput.v_move_rel[0]-=(cos(EGplayer.look[1]*M_PI/180)*0.75); EGinput.v_move_rel[2]-=(sin(EGplayer.look[1]*M_PI/180)*0.75); f++; } if(f==2){ EGinput.v_move_rel[0]*=0.8; EGinput.v_move_rel[2]*=0.8; } if(EGplayer.jump > 1){ if(EGplayer.jump==19){ EPlayEnvironmentSound(SND_JUMP, 1); } EGinput.v_move_rel[1]-=4; EGplayer.jump--; } if(EGinput.PressedKeys[SDLK_LCTRL]&& EGplayer.jump==0){ EGplayer.height=PLAYER_HEIGHT*0.6; } if(((EGinput.v_move_rel[0]+EGinput.v_move_rel[2])>0.001)||((EGinput.v_move_rel[0]+EGinput.v_move_rel[2])<-0.001)){ if(EGplayer.jump==0){ if(!EGinput.PressedKeys[SDLK_LCTRL]){ if(EGinput.PressedKeys[SDLK_LSHIFT]){ EGplayer.move_speed = 2*DEFAULT_MOVESPEED; EPlayEnvironmentSound(SND_RUN, 0); } else { EGplayer.move_speed = DEFAULT_MOVESPEED; EPlayEnvironmentSound(SND_WALK, 0); } } else { EGplayer.move_speed = DEFAULT_MOVESPEED*0.5; EPlayEnvironmentSound(SND_WALK, 0); } } else { if(!EGinput.PressedKeys[SDLK_LSHIFT]){ EGplayer.move_speed=DEFAULT_MOVESPEED; } else { EGplayer.move_speed=DEFAULT_MOVESPEED*1.5; } } } if(EGinput.mouse_left){ } else if(EGinput.mouse_right){ EPlayEnvironmentSound(SND_SETBLOCK, 1); } if(EGinput.v_move_rel[0] != x) player_new_xpos(&EGinput.v_move_rel); if(EGinput.v_move_rel[2] != y) player_new_xpos(&EGinput.v_move_rel+2); if(EGinput.v_move_rel[1] != z) player_new_xpos(&EGinput.v_move_rel+1); pthread_mutex_unlock(&Tlock_input); }
1
#include <pthread.h> pthread_mutex_t lock_flag; int flag = 1; int num = 1; int ret; int fd1; int fd2; int fd3; int fd4; char buff1[1024]={0}; char buff2[1024]={0}; char buff3[1024]={0}; char buff4[1024]={0}; void *handler1(void *arg) { ret = write(fd1,"A.",2); int i = 0; while(1) { if(i >= 20) { sleep(1); ret = read(fd1,buff1,1023); printf("%s\\n",buff1); printf("fd1 give over\\n"); break; } pthread_mutex_lock(&lock_flag); if(flag == 1) { flag = 2; if(num == 1) { ret = write(fd1,"1",1); num = 2; i++; } if(num == 2) { ret = write(fd1,"2",1); num =3; i++; } if(num == 3) { ret = write(fd1,"3",1); num =4; i++; } if(num == 4) { ret = write(fd1,"4",1); num =1; i++; } } pthread_mutex_unlock(&lock_flag); } } void *handler2(void *arg) { ret = write(fd2,"B.",2); int i = 0; while(1) { if(i >= 20) { sleep(1); ret = read(fd2,buff2,1023); printf("%s\\n",buff2); printf("fd2 give over\\n"); break; } pthread_mutex_lock(&lock_flag); if(flag == 2) { flag = 3; if(num == 1) { ret = write(fd2,"2",1); num = 2; i++; } if(num == 2) { ret = write(fd2,"3",1); num =3; i++; } if(num == 3) { ret = write(fd2,"4",1); num =4; i++; } if(num == 4) { ret = write(fd2,"1",1); num =1; i++; } } pthread_mutex_unlock(&lock_flag); } } void *handler3(void *arg) { ret = write(fd3,"C.",2); int i = 0; while(1) { if(i >= 20) { sleep(1); ret = read(fd3,buff3,1023); printf("%s\\n",buff3); printf("fd3 give over\\n"); break; } pthread_mutex_lock(&lock_flag); if(flag == 3) { flag = 4; if(num == 1) { ret = write(fd3,"3",1); num = 2; i++; } if(num == 2) { ret = write(fd3,"4",1); num =3; i++; } if(num == 3) { ret = write(fd3,"1",1); num =4; i++; } if(num == 4) { ret = write(fd3,"2",1); num =1; i++; } } pthread_mutex_unlock(&lock_flag); } } void *handler4(void *arg) { ret = write(fd4,"D.",2); int i = 0; while(1) { if(i >= 20) { sleep(1); ret = read(fd4,buff4,1023); printf("%s\\n",buff4); printf("fd4 give over\\n"); break; } pthread_mutex_lock(&lock_flag); if(flag == 4) { flag = 1; if(num == 1) { ret = write(fd4,"4",1); num = 2; i++; } if(num == 2) { ret = write(fd4,"1",1); num =3; i++; } if(num == 3) { ret = write(fd4,"2",1); num =4; i++; } if(num == 4) { ret = write(fd4,"3",1); num =1; i++; } } pthread_mutex_unlock(&lock_flag); } } int main() { pthread_t pid1; pthread_t pid2; pthread_t pid3; pthread_t pid4; fd1 = open("A.txt",O_RDWR |O_APPEND | O_TRUNC | O_CREAT,0640); fd2 = open("B.txt",O_RDWR |O_APPEND | O_TRUNC | O_CREAT,0640); fd3 = open("C.txt",O_RDWR |O_APPEND | O_TRUNC | O_CREAT,0640); fd4 = open("D.txt",O_RDWR |O_APPEND | O_TRUNC | O_CREAT,0640); pthread_mutex_init(&lock_flag,0); ret =pthread_create(&pid1,0,handler1,0); if(ret < 0) { perror("pthread create"); return -1; } ret =pthread_create(&pid2,0,handler2,0); if(ret < 0) { perror("pthread create"); return -1; } ret =pthread_create(&pid3,0,handler3,0); if(ret < 0) { perror("pthread create"); return -1; } ret =pthread_create(&pid4,0,handler4,0); if(ret < 0) { perror("pthread create"); return -1; } pthread_join(pid1,0); pthread_join(pid2,0); pthread_join(pid3,0); pthread_join(pid4,0); close(fd1); close(fd2); close(fd3); close(fd4); return 0; }
0
#include <pthread.h> static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static unsigned int seed0; static unsigned int seed1; static int have_init = 0; static int read_dev_random (void *buffer, size_t buffer_size) { int fd; ssize_t status = 0; char *buffer_position; size_t yet_to_read; fd = open ("/dev/urandom", O_RDONLY); if (fd < 0) { perror ("open"); return (-1); } buffer_position = (char *) buffer; yet_to_read = buffer_size; while (yet_to_read > 0) { status = read (fd, (void *) buffer_position, yet_to_read); if (status < 0) { if (errno == EINTR) continue; fprintf (stderr, "read_dev_random: read failed.\\n"); break; } buffer_position += status; yet_to_read -= (size_t) status; } close (fd); if (status < 0) return (-1); return (0); } static void do_init (void) { if (have_init) return; read_dev_random (&seed0, sizeof (seed0)); read_dev_random (&seed1, sizeof (seed1)); have_init = 1; } int sn_random_init (void) { have_init = 0; do_init (); return (0); } int sn_random (void) { int r0; int r1; pthread_mutex_lock (&lock); do_init (); r0 = rand_r (&seed0); r1 = rand_r (&seed1); pthread_mutex_unlock (&lock); return (r0 ^ r1); } int sn_true_random (void) { int ret = 0; int status; status = read_dev_random (&ret, sizeof (ret)); if (status != 0) return (sn_random ()); return (ret); } int sn_bounded_random (int min, int max) { int range; int rand; if (min == max) return (min); else if (min > max) { range = min; min = max; max = range; } range = 1 + max - min; rand = min + (int) (((double) range) * (((double) sn_random ()) / (((double) 32767) + 1.0))); assert (rand >= min); assert (rand <= max); return (rand); } double sn_double_random (void) { return (((double) sn_random ()) / (((double) 32767) + 1.0)); }
1
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo{ int f_count; pthread_mutex_t f_lock; struct foo *f_next; int f_id; }; struct foo *foo_alloc(int id){ struct foo *fp; int idx; if((fp=malloc(sizeof(struct foo)))!=0){ fp->f_count=1; fp->f_id=id; if(pthread_mutex_init(&fp->f_lock,0)!=0){ free(fp); return(0); } idx=(((unsigned long)id)%29); pthread_mutex_lock(&hashlock); fh[idx]=fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return(fp); } void foo_hold(struct foo *fp){ pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } struct foo *foo_find(int id){ struct foo *fp; int idx; idx=(((unsigned long)id)%29); printf("foo_find idx=%d\\n",idx); pthread_mutex_lock(&hashlock); for(fp=fh[idx];fp!=0;fp=fp->f_next){ printf("foo_find id=%d,fp_count=%d\\n",id,fp->f_count); if(fp->f_id==id){ printf("last find id=%d\\n",id); foo_hold(fp); break; } } pthread_mutex_unlock(&hashlock); return(fp); } void foo_rele(struct foo *fp){ struct foo *tfp; int idx; pthread_mutex_lock(&fp->f_lock); if(fp->f_count==1){ printf("f_count=1\\n"); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&fp->f_lock); if(fp->f_count!=1){ fp->f_count--; pthread_mutex_unlock(&fp->f_lock); pthread_mutex_unlock(&hashlock); return; } idx=(((unsigned long)fp->f_id)%29); tfp=fh[idx]; if(tfp==fp){ fh[idx]==fp->f_next; }else{ while(tfp->f_next!=fp) tfp=tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); }else{ fp->f_count--; pthread_mutex_unlock(&fp->f_lock); } } int main(void){ struct foo *fo; struct foo *fo2; struct foo *fo_find; int a=12; fo=foo_alloc(a); printf("f_count=%d,f_id=%d\\n",fo->f_count,fo->f_id); foo_hold(fo); printf("f_count=%d,f_id=%d\\n",fo->f_count,fo->f_id); foo_rele(fo); printf("f_count=%d,f_id=%d\\n",fo->f_count,fo->f_id); fo_find=foo_find(1); printf("foo_find f_count=%d,f_id=%d\\n",fo_find->f_count,fo_find->f_id); printf("----\\n"); int b=13; fo2=foo_alloc(b); printf("f_count=%d,f_id=%d\\n",fo2->f_count,fo2->f_id); exit(0); }
0
#include <pthread.h> pthread_t threadArray[10]; static pthread_mutex_t lock; void* feldThread(void* arg) { int i; for (i = 0; i < 10; i++) { if (pthread_equal(threadArray[i], pthread_self())) { pthread_mutex_lock(&lock); struct Position ps = gibStartPosition(i); do { char tmp = Feld[ps.Y][ps.X]; struct Position newPS = gibNeuePosition(ps); Feld[newPS.Y][newPS.X] = tmp; usleep(200000); } while( !((EingabeZeichen == 'b') || (EingabeZeichen == 'B')) ); pthread_mutex_unlock(&lock); } } pthread_exit(0); } void* anzeigeThread(void *arg) { pthread_mutex_lock(&lock); do { anzeigen(); usleep(30000); } while( !((EingabeZeichen == 'b') || (EingabeZeichen == 'B')) ); pthread_mutex_unlock(&lock); pthread_exit(0); } int main(void) { init(); int i; for (i = 0; i < 10; i++) { pthread_create(&threadArray[i], 0, &feldThread, 0); } pthread_t aThread; pthread_create(&aThread, 0, anzeigeThread, 0); do { scanf(" %c", &EingabeZeichen); } while( !((EingabeZeichen == 'b') || (EingabeZeichen == 'B')) ); for (i = 0; i < 10; i++) { pthread_join(threadArray[i], 0); } pthread_exit(0); return 0; }
1
#include <pthread.h> pthread_t thread_ids[8]; pthread_mutex_t twos_mutex, threes_mutex, fives_mutex; int twos, threes, fives; void *f(void *arg) { while(1) { pthread_mutex_lock(&twos_mutex); pthread_mutex_lock(&threes_mutex); pthread_mutex_lock(&fives_mutex); bool done = (twos >= 3 && threes >= 3 && fives >= 3); pthread_mutex_unlock(&fives_mutex); pthread_mutex_unlock(&threes_mutex); pthread_mutex_unlock(&twos_mutex); if(done) { printf("Thread finished.\\n"); return 0; } int a = rand() % 6; int b = rand() % 10; int c = rand() % 10; printf("Generated =====> %d%d%d\\n", a, b, c); if(a == 2 || b == 2 || c == 2) { pthread_mutex_lock(&twos_mutex); twos++; printf("Got another 2\\n"); pthread_mutex_unlock(&twos_mutex); } if(a == 3 || b == 3 || c == 3) { pthread_mutex_lock(&threes_mutex); threes++; printf("Got another 3\\n"); pthread_mutex_unlock(&threes_mutex); } if(a == 5 || b == 5 || c == 5) { pthread_mutex_lock(&fives_mutex); fives++; printf("Got another 5\\n"); pthread_mutex_unlock(&fives_mutex); } } return 0; } int main() { srand((unsigned)time(0)); pthread_mutex_init(&twos_mutex, 0); pthread_mutex_init(&threes_mutex, 0); pthread_mutex_init(&fives_mutex, 0); for(int i=0; i<7; i++) pthread_create(&thread_ids[i], 0, f, 0); for(int i=0; i<7; i++) pthread_join(thread_ids[i], 0); printf("twos: %d\\n", twos); printf("threes: %d\\n", threes); printf("fives: %d\\n", fives); return 0; }
0
#include <pthread.h> void * serverthread(void * parm); pthread_mutex_t mut; int visits = 0; main (int argc, char *argv[]) { struct hostent *ptrh; struct protoent *ptrp; struct sockaddr_in sad; struct sockaddr_in cad; int sd, sd2; int port; int alen; pthread_t tid; pthread_mutex_init(&mut, 0); memset((char *)&sad,0,sizeof(sad)); sad.sin_family = AF_INET; sad.sin_addr.s_addr = INADDR_ANY; if (argc > 1) { port = atoi (argv[1]); } else { port = 6969; } if (port > 0) sad.sin_port = htons((u_short)port); else { fprintf (stderr, "bad port number %s/n",argv[1]); exit (1); } if ( ((int)(ptrp = getprotobyname("tcp"))) == 0) { fprintf(stderr, "cannot map \\"tcp\\" to protocol number"); exit (1); } sd = socket (PF_INET, SOCK_STREAM, ptrp->p_proto); if (sd < 0) { fprintf(stderr, "socket creation failed\\n"); exit(1); } if (bind(sd, (struct sockaddr *)&sad, sizeof (sad)) < 0) { fprintf(stderr,"bind failed\\n"); exit(1); } if (listen(sd, 6) < 0) { fprintf(stderr,"listen failed\\n"); exit(1); } alen = sizeof(cad); fprintf( stderr, "Server up and running.\\n"); while (1) { printf("SERVER: Waiting for contact ...\\n"); if ( (sd2=accept(sd, (struct sockaddr *)&cad, &alen)) < 0) { fprintf(stderr, "accept failed\\n"); exit (1); } pthread_create(&tid, 0, serverthread, (void *) sd2 ); } close(sd); } void * serverthread(void * parm) { int tsd, tvisits; char buf[100]; tsd = (int) parm; pthread_mutex_lock(&mut); tvisits = ++visits; pthread_mutex_unlock(&mut); sprintf(buf,"This server has been contacted %d time%s\\n", tvisits, tvisits==1?".":"s."); printf("SERVER thread: %s", buf); send(tsd,buf,strlen(buf),0); close(tsd); pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex; char *word; int count; struct dict *next; } dict_t; dict_t *d; char * make_word( char *word ) { return strcpy( malloc( strlen( word )+1 ), word ); } dict_t * make_dict(char *word) { dict_t *nd = (dict_t *) malloc( sizeof(dict_t) ); nd->word = make_word( word ); nd->count = 1; nd->next = 0; return nd; } dict_t * insert_word( dict_t *d, char *word ) { dict_t *nd; dict_t *pd = 0; dict_t *di = d; while(di && ( strcmp(word, di->word ) >= 0) ) { if( strcmp( word, di->word ) == 0 ) { di->count++; return d; } pd = di; di = di->next; } nd = make_dict(word); nd->next = di; if (pd) { pd->next = nd; return d; } return nd; } void print_dict(dict_t *d) { while (d) { printf("[%d] %s\\n", d->count, d->word); d = d->next; } } int get_word( char *buf, int n, FILE *infile) { int inword = 0; int c; while( (c = fgetc(infile)) != EOF ) { if (inword && !isalpha(c)) { buf[inword] = '\\0'; return 1; } if (isalpha(c)) { buf[inword++] = c; } } return 0; } void * words(void * args){ FILE * infile = (FILE *) args; char wordbuf[5000]; while(get_word( wordbuf, 5000, infile ) ) { pthread_mutex_lock(&mutex); d = insert_word(d, wordbuf); pthread_mutex_unlock(&mutex); } } int main( int argc, char *argv[] ) { if(pthread_mutex_init(&mutex,0)!=0){ printf("OOPS ,UNABLE TO CREATE THE MUTEX LOCK\\n"); return 1; } d = 0; FILE *infile = stdin; if (argc >= 2) { infile = fopen(argv[1],"r"); } if( !infile ) { printf("Unable to open %s\\n",argv[1]); exit( 1 ); } pthread_t thread[4]; pthread_create(&thread[0],0,words,infile); pthread_join(thread[0], 0); pthread_create(&thread[1],0,words,infile); pthread_join(thread[1], 0); pthread_create(&thread[2],0,words,infile); pthread_join(thread[2], 0); pthread_create(&thread[3],0,words,infile); pthread_join(thread[3], 0); print_dict(d); pthread_mutex_destroy(&mutex); fclose( infile ); }
0
#include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; char global[2000] = ""; void * ThreadOne(void * a) { char character[3]; FILE *fp; fp = fopen("data1.txt", "r"); if (fp == 0) { printf("Can't open input file data1.txt!"); exit(1); } while (fscanf(fp, "%s", character) == 1) { pthread_mutex_lock(&lock); printf("Thread 1 just locked!!!\\n"); if (strlen(global) == 0) { strcpy(global, character); printf("Thread 1 just cpy'd:\\t%s\\n", character); } else if ((strlen(global) % 2) == 0){ strcat(global, character); printf("Thread 1 just cat'd:\\t%s\\n", character); } else { int count = 0; while ((strlen(global) % 2) != 0 && count < 100){ pthread_mutex_unlock(&lock); printf("Thread 1 is waiting for thread 2...\\n"); pthread_mutex_lock(&lock); count++; } printf("Thread 1 is done waiting for thread 2...\\n"); strcat(global, character); } pthread_mutex_unlock(&lock); printf("Thread 1 just unlocked!\\n"); } fclose(fp); return 0; } void * ThreadTwo(void * a) { char character[3]; char temp[3]; FILE *fp; fp = fopen("data2.txt", "r"); if (fp == 0) { printf("Can't open input file data2.txt!"); exit(1); } while (fscanf(fp, "%s", character) == 1) { pthread_mutex_lock(&lock); printf("Thread 2 just locked!!!\\n"); if (strlen(global) == 0) { while (strlen(global) == 0){ pthread_mutex_unlock(&lock); printf("Thread 2 is waiting for thread 1...\\n"); pthread_mutex_lock(&lock); } printf("Thread 2 is done waiting for thread 1...\\n"); strcat(global, character); printf("Thread 2 just cat'd:\\t%s\\n", character); } else{ strcat(global, character); printf("Thread 2 just cat'd:\\t%s\\n", character); } pthread_mutex_unlock(&lock); printf("Thread 2 just unlocked!\\n"); } fclose(fp); return 0; } int main(int argc, char * argv[]) { pthread_t tid1, tid2; if (pthread_mutex_init(&lock, 0) != 0) { printf("\\nMutex initiation failed!\\n"); return 1; } if(pthread_create(&tid1, 0, ThreadOne, 0)) { printf("\\n ERROR creating thread 1"); exit(1); } if(pthread_create(&tid2, 0, ThreadTwo, 0)) { printf("\\n ERROR creating thread 2"); exit(1); } if(pthread_join(tid1, 0)) { printf("\\n ERROR joining thread"); exit(1); } if(pthread_join(tid2, 0)) { printf("\\n ERROR joining thread"); exit(1); } printf("\\nThe decoded message is:\\n\\n%s\\n\\n", global); pthread_mutex_destroy(&lock); pthread_exit(0); }
1
#include <pthread.h> int g_SOMA_tam, g_SOMA_nThreads, g_SOMA_maiorIndice=0; float **g_SOMA_A; double *g_SOMA_somasColunas, g_SOMA_maiorElemento=0; pthread_mutex_t g_SOMA_maiorIndice_mutex, g_SOMA_maiorElemento_mutex; void *thread_soma_coluna(void* arg){ int i, j, index = *( (int*) arg); for(j=index; j<g_SOMA_tam; j+=g_SOMA_nThreads){ g_SOMA_somasColunas[j] = 0; for(i=0; i<g_SOMA_tam; i++){ g_SOMA_somasColunas[j] += g_SOMA_A[i][j]; } pthread_mutex_lock(&g_SOMA_maiorElemento_mutex); pthread_mutex_lock(&g_SOMA_maiorIndice_mutex); if(g_SOMA_maiorElemento< g_SOMA_somasColunas[j]){ g_SOMA_maiorElemento = g_SOMA_somasColunas[j]; g_SOMA_maiorIndice = j; } pthread_mutex_unlock(&g_SOMA_maiorElemento_mutex); pthread_mutex_unlock(&g_SOMA_maiorIndice_mutex); } pthread_exit(0); } int colunaMaiorSomaTotal(int tam, int nThreads, float **matriz){ g_SOMA_somasColunas = (double*) malloc(tam*sizeof(double)); g_SOMA_nThreads = nThreads; g_SOMA_tam = tam; g_SOMA_A = matriz; int j; pthread_t *tid_sistema; int *tid_somaColunas; tid_sistema = (pthread_t *) malloc(sizeof(pthread_t) * g_SOMA_nThreads); if(tid_sistema==0) { printf("--ERRO: malloc()\\n"); exit(-1); } tid_somaColunas = (int *) malloc(sizeof(int) * g_SOMA_nThreads); if(tid_somaColunas==0) { printf("--ERRO: malloc()\\n"); exit(-1); } for(j=0; j<g_SOMA_nThreads; j++){ tid_somaColunas[j] = j; if (pthread_create(&tid_sistema[j], 0, thread_soma_coluna, (void*) &tid_somaColunas[j])) { printf("--ERRO: pthread_create()\\n"); exit(-1); } } for(j=0; j<g_SOMA_nThreads; j++) { if (pthread_join(tid_sistema[j], 0)) { printf("--ERRO: pthread_join()\\n"); exit(-1); } } free(tid_sistema); free(tid_somaColunas); free(g_SOMA_somasColunas); return g_SOMA_maiorIndice; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condizione=PTHREAD_COND_INITIALIZER; int contatore=0; int limite=0; void *somma(void *param){ int i=0; int a,b,c=0; while(i<1000 && contatore <=limite){ pthread_mutex_lock(&mutex); a=rand()%10; b=rand()%10; c=a+b; printf("%d\\n",c); i++; contatore++; pthread_mutex_unlock(&mutex); } if (contatore <=limite){ printf("Sono qui"); pthread_mutex_lock(&mutex); pthread_cond_signal(&condizione); pthread_mutex_unlock(&mutex); } pthread_exit(0); } void *notifica(void*param){ pthread_mutex_lock(&mutex); while(contatore <=limite){ pthread_cond_wait(&condizione,&mutex); } pthread_mutex_unlock(&mutex); printf("Messaggio arrivato\\n" ); pthread_exit(0); } int main(int argc,char *argv[]){ pthread_t thread[3]; if(argc <2){ printf("Error"); exit(1); } limite = atoi(argv[1]); int i=0; for (i=0;i<3;i++){ pthread_create(&thread[i],0,somma,0); } pthread_create(&thread[3],0,notifica,0); for (i=0;i<=3;i++){ pthread_join(thread[i],0); } return 0; }
1
#include <pthread.h> float hole= 0; int flag= 0; pthread_mutex_t lock_hole; void delay(){ int aux2; for (aux2= 600000; aux2 > 0; aux2--); return; } void delay2(){ int aux2; for (aux2= 100000; aux2 > 0; aux2--); return; } double get(){ int aux1; pthread_mutex_lock(&lock_hole); aux1= hole; pthread_mutex_unlock(&lock_hole); return aux1; } double inc(){ int aux1; pthread_mutex_lock(&lock_hole); for (aux1=0;aux1<10;aux1++) { hole= hole + 0.100000000; delay2(); } pthread_mutex_unlock(&lock_hole); return hole; } void* producer(int* name){ int aux1, aux2, aux3, count; for (aux1 = 0; aux1 < 20; aux1++) { printf("Producer inc: %.3f\\n", inc()); } pthread_exit(0); } void* consumer(int* name){ int aux1, aux2, aux3; for (aux1 = 0; aux1 < 10; aux1++) { printf("Consumer got: %.3f\\n", get()); delay(); } pthread_exit(0); } void main(){ pthread_t simpleThread1, simpleThread2; int status, aux1, priority; int pro1 = 0; int pro2 = 1; pthread_mutex_init(&lock_hole, 0); pthread_setconcurrency(100); printf("Concurrency %d\\n", pthread_getconcurrency()); pthread_create(&simpleThread1, 0, producer, (void*) &pro1); pthread_create(&simpleThread2, 0, consumer, (void*) 0); pthread_join(simpleThread1, 0); pthread_join(simpleThread2, 0); }
0
#include <pthread.h> pthread_mutex_t mymutex=PTHREAD_MUTEX_INITIALIZER; int balance=1000; void deposit(void *ptr) { int i; for(i=1;i<=50;i++) { pthread_mutex_lock(&mymutex); balance=balance+50; printf("\\nBALANCE AFTER %d DEPOSIT:\\t%d\\n",i,balance); pthread_mutex_unlock(&mymutex); sleep(2); } pthread_exit(0); } int main() { pthread_t mythread; int i; if(pthread_create(&mythread,0,(void*)&deposit,0)) { perror("Error in creating thread"); exit(1); } for(i=1;i<=20;i++) { pthread_mutex_lock(&mymutex); balance=balance-20; printf("\\nBALANCE AFTER %d WITHDRAWAL:\\t%d\\n",i,balance); pthread_mutex_unlock(&mymutex); sleep(1); } if(pthread_join(mythread,0)) { perror("Error in joining the threads"); exit(1); } printf("\\n\\n\\nFINAL BALANCE :\\t%d",balance); printf("\\nmain thread exiting\\n"); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int minD = 1000; long formula(long n){ return n*(3*n-1)/2; } int is_pentagonal(long s){ unsigned delta = sqrt(1+24*s); if( delta*delta == (1+24*s) && (1+ delta)%6 == 0) return 1; return 0; } void *look_for_min(void *threadid){ long tid; tid = (long) threadid; long start, end; long j, k; start = tid*100000000/16 + 1; end = start + 100000000/16 -1; for(j=start; j<end; j++){ long sum = 0, differences = 0; for(k=j+1; k<100000000; k++){ sum = formula(j) + formula(k); differences = formula(k) - formula(j); if(is_pentagonal(sum) && is_pentagonal(differences)) if(sum - differences <= minD){ pthread_mutex_lock(&mutex1); minD = sum - differences; pthread_mutex_unlock(&mutex1); } } } printf("%d\\n", minD); pthread_exit(0); } int main(int argc, char *argv[]){ pthread_t threads[16]; int rc; long t; for(t=0; t<16; t++){ rc = pthread_create(&threads[t], 0, look_for_min, (void *)t); if(rc) printf("Error; return code from pthread_create() is %d\\n", rc); } for(t=0; t<16; t++){ pthread_join(threads[t], 0); } printf("final mini D is: %d\\n", minD); pthread_exit(0); return 0; }
0
#include <pthread.h> pthread_mutex_t chopstick[5]; void pickup(int me) { if((me%5) == 0) { pthread_mutex_lock(&chopstick[(((me)+1)%5)]); pthread_mutex_lock(&chopstick[me]); } else { pthread_mutex_lock(&chopstick[me]); pthread_mutex_lock(&chopstick[(((me)+1)%5)]); } } void drop(int me) { pthread_mutex_unlock(&chopstick[me]); pthread_mutex_unlock(&chopstick[(((me)+1)%5)]); } void *philosophy(void *arg) { int me = (int)arg; while(1) { printf("%d is thinking...\\n", me); usleep(rand()%10); pickup(me); printf("%d is eating...\\n", me); usleep(rand()%10); drop(me); } } int main() { pthread_t tid[5]; int i, p[5]; srand(time(0)); for(i = 0; i < 5; i++) pthread_mutex_init(&chopstick[i], 0); for(i = 0; i < 5; i++) p[i] = i; for(i = 0; i < 5 -1; i++) pthread_create(&tid[i], 0, philosophy, (void *)p[i]); philosophy((void*)(5 -1)); for(i = 0; i < 5 -1; i++) pthread_join(tid[i], 0); for(i = 0; i < 5; i++) pthread_mutex_destroy(&chopstick[i]); return 0; }
1
#include <pthread.h> const char * c_getenv(const char *variable) { return getenv(variable); } bool c_setenv(const char *variable, const char *value, bool overwrite) { return setenv(variable, value, overwrite) == 0; } void c_unsetenv(const char *variable) { unsetenv(variable); } char * c_win32_getlocale(void) { return 0; } bool c_path_is_absolute(const char *filename) { c_return_val_if_fail(filename != 0, 0); return (*filename == '/'); } static pthread_mutex_t pw_lock = PTHREAD_MUTEX_INITIALIZER; static const char *home_dir; static const char *user_name; static void get_pw_data(void) { if (user_name != 0) return; pthread_mutex_lock(&pw_lock); if (user_name != 0) { pthread_mutex_unlock(&pw_lock); return; } if (home_dir == 0) home_dir = c_getenv("HOME"); if (user_name == 0) { user_name = c_getenv("USER"); if (user_name == 0) user_name = "somebody"; } pthread_mutex_unlock(&pw_lock); } const char * c_get_home_dir(void) { get_pw_data(); return home_dir; } const char * c_get_user_name(void) { get_pw_data(); return user_name; } static const char *tmp_dir; static pthread_mutex_t tmp_lock = PTHREAD_MUTEX_INITIALIZER; const char * c_get_tmp_dir(void) { if (tmp_dir == 0) { pthread_mutex_lock(&tmp_lock); if (tmp_dir == 0) { tmp_dir = c_getenv("TMPDIR"); if (tmp_dir == 0) { tmp_dir = c_getenv("TMP"); if (tmp_dir == 0) { tmp_dir = c_getenv("TEMP"); if (tmp_dir == 0) tmp_dir = "/tmp"; } } } pthread_mutex_unlock(&tmp_lock); } return tmp_dir; }
0
#include <pthread.h> int ocupacion=0; pthread_mutex_t m; pthread_cond_t barbero_durmiendo; pthread_cond_t corte_pelo; void CortarElPelo() { printf("Estoy cortando el pelo....ocupacion=%d\\n",ocupacion); sleep(3); printf("He terminado de cortar el pelo!!!\\n"); } void * barbero () { while(1) { pthread_mutex_lock(&m); while(ocupacion==0 ) { printf("Soy el barbero y duermo\\n"); pthread_cond_wait(&barbero_durmiendo,&m); } CortarElPelo(); ocupacion--; pthread_cond_signal(&corte_pelo); pthread_mutex_unlock(&m); } pthread_exit(0); } void * cliente(void * p) { int n_cliente; n_cliente=(int)p; pthread_mutex_lock(&m); if(ocupacion != 4) { ocupacion++; printf("Soy el cliente %d y acabo de llegar. Ocupacion=%d\\n",n_cliente,ocupacion); pthread_cond_signal(&barbero_durmiendo); pthread_cond_wait(&corte_pelo,&m); } else { printf("Soy el cliente %d y no hay sillas. Me voy!!\\n", n_cliente); } pthread_mutex_unlock(&m); pthread_exit(0); } int main() { int num; pthread_t t_barbero; pthread_t * p_cliente; int contador=0; pthread_mutex_init(&m,0); pthread_cond_init(&barbero_durmiendo,0); pthread_cond_init(&corte_pelo,0); pthread_create(&t_barbero,0,barbero,0); srand(time(0)); while(1) { num=rand()%2; if(num==0) { contador++; p_cliente=malloc(sizeof(pthread_t)); pthread_create(p_cliente,0,cliente,(void*)&contador); } else { sleep(2); } } pthread_mutex_destroy(&m); }
1
#include <pthread.h> volatile int arg; volatile int res; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t c1 = PTHREAD_COND_INITIALIZER, c2 = PTHREAD_COND_INITIALIZER; void * thread_routine(void *dummy) { while(1) { pthread_mutex_lock(&mutex); if(arg < 0) pthread_cond_wait(&c1, &mutex); res = arg; arg = -1; pthread_mutex_unlock(&mutex); pthread_cond_signal(&c2); } } int main() { pthread_t thread; int rc; int i, j, s; arg = -1; res = 0; rc = pthread_create(&thread, 0, thread_routine, 0); if(rc != 0) abort(); for(i = 0; i < 100; i++) { s = 0; for(j = 0; j < 10000; j++) { pthread_mutex_lock(&mutex); res = -1; arg = j; pthread_mutex_unlock(&mutex); pthread_cond_signal(&c1); pthread_mutex_lock(&mutex); if(res < 0) pthread_cond_wait(&c2, &mutex); s += res; arg = -1; pthread_mutex_unlock(&mutex); } } printf("%d\\n", s); return 0; }
0
#include <pthread.h> void *thread_function (void *arg); pthread_mutex_t x_mutex; int x; int test_ready = 0; int main () { int res; pthread_t threads[4]; int i; pthread_mutex_init (&x_mutex, 0); for (i = 0; i < 4; ++i) { res = pthread_create (&threads[i], 0, thread_function, (void *) (intptr_t) i); if (res != 0) { fprintf (stderr, "error in thread %d create\\n", i); abort (); } } for (i = 0; i < 4; ++i) { res = pthread_join (threads[i], 0); if (res != 0) { fprintf (stderr, "error in thread %d join\\n", i); abort (); } } exit (0); } void thread_started () { } void * thread_function (void *arg) { int i; thread_started (); while (! test_ready) usleep (1); for (i = 0; i < 10; ++i) { pthread_mutex_lock (&x_mutex); printf ("Thread %ld changing x %d -> %d\\n", (long) arg, x, x + 1); ++x; usleep (1); pthread_mutex_unlock (&x_mutex); } pthread_exit (0); }
1
#include <pthread.h> void handler(int); void *threadroutine(void *); pthread_mutex_t mt; pthread_cond_t cv; void handler(int sig) { return; } void * threadroutine(void *arg) { sigset_t set; sigemptyset(&set); sigaddset(&set, SIGALRM); pthread_sigmask(SIG_UNBLOCK, &set, 0); pthread_mutex_lock(&mt); pthread_cond_wait(&cv, &mt); pthread_mutex_unlock(&mt); return 0; } int main(void) { pthread_t th; sigset_t set; struct sigaction act; printf("Testing CV teardown under spurious wakeups.\\n"); sigfillset(&set); pthread_sigmask(SIG_BLOCK, &set, 0); act.sa_handler = handler; sigemptyset(&act.sa_mask); act.sa_flags = 0; sigaction(SIGALRM, &act, 0); pthread_mutex_init(&mt, 0); pthread_cond_init(&cv, 0); pthread_create(&th, 0, threadroutine, 0); alarm(1); pthread_join(th, 0); pthread_cond_destroy(&cv); pthread_mutex_destroy(&mt); printf("Passed.\\n"); return 0; }
0
#include <pthread.h> char *num_str[] = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "twenty one", "twenty two", "twenty three", "twenty four", "twenty five", "twenty six", "twenty seven", "twenty eight", "twenty nine", "thirty" }; int dequeue_count = 0; int enqueue_count = 0; struct entry { struct entry *next; void *data; }; struct list { struct entry *head; struct entry **tail; pthread_mutex_t lock; int size; }; struct list *list_init(void) { struct list *list; list = malloc(sizeof *list); if (list == 0) return (0); list->head = 0; list->tail = &list->head; list->lock = PTHREAD_MUTEX_INITIALIZER; list->size = 0; return (list); } int list_enqueue(struct list *list, void *data) { struct entry *e; e = malloc(sizeof *e); if (e == 0) return (1); e->next = 0; e->data = data; pthread_mutex_lock(&list->lock); *list->tail = e; list->tail = &e->next; list->size++; pthread_mutex_unlock(&list->lock); return (0); } struct entry *list_dequeue(struct list *list) { struct entry *e; pthread_mutex_lock(&list->lock); if (list->head == 0) { pthread_mutex_unlock(&list->lock); return(0); } e = list->head; list->head = e->next; list->size--; if (list->head == 0) list->tail = &list->head; pthread_mutex_unlock(&list->lock); return (e); } struct entry *list_traverse (struct list *list, int (*func)(void *, void *), void *user) { struct entry **prev, *n, *next; if (list == 0) return (0); prev = &list->head; for (n = list->head; n != 0; n = next) { next = n->next; switch (func(n->data, user)) { case 0: prev = &n->next; break; case 1: *prev = next; if (next == 0) list->tail = prev; return (n); case -1: default: return (0); } } return (0); } int print_entry(void *e, void *u) { printf("%s\\n", (char *)e); return (0); } int delete_entry(void *e, void *u) { char *c1 = e, *c2 = u; return (!strcmp(c1, c2)); } void *put_thirty_entries(void *arg) { int i = 0; struct list *list = (struct list *)arg; for (i = 0; i < 30; i++) { enqueue_count++; list_enqueue(list, strdup(num_str[i])); printf("Enqueue %d回目 : %s\\n", enqueue_count, num_str[i]); } } void *get_ten_entries(void *arg) { struct list *list = (struct list *)arg; struct entry *entry; int i = 0; for (i = 0; i < 10; i++) { entry = list_dequeue(list); dequeue_count++; printf("Dequeue %d回目 : %s\\n", dequeue_count, (char *)entry->data); free(entry->data); free(entry); } } int main() { struct list *list; struct entry *entry; pthread_t put_thirty_entries1, put_thirty_entries2; pthread_t get_ten_entries1, get_ten_entries2, get_ten_entries3, get_ten_entries4, get_ten_entries5, get_ten_entries6; list = list_init(); pthread_create(&put_thirty_entries1, 0, put_thirty_entries, (void *)(list)); pthread_create(&get_ten_entries1, 0, get_ten_entries, (void *)(list)); pthread_create(&get_ten_entries2, 0, get_ten_entries, (void *)(list)); pthread_create(&get_ten_entries3, 0, get_ten_entries, (void *)(list)); pthread_create(&get_ten_entries4, 0, get_ten_entries, (void *)(list)); pthread_create(&get_ten_entries5, 0, get_ten_entries, (void *)(list)); pthread_create(&put_thirty_entries2, 0, put_thirty_entries, (void *)(list)); pthread_create(&get_ten_entries6, 0, get_ten_entries, (void *)(list)); pthread_join(put_thirty_entries1, 0); pthread_join(get_ten_entries1, 0); pthread_join(get_ten_entries2, 0); pthread_join(get_ten_entries3, 0); pthread_join(get_ten_entries4, 0); pthread_join(get_ten_entries5, 0); pthread_join(put_thirty_entries2, 0); pthread_join(get_ten_entries6, 0); list_traverse(list, print_entry, 0); return (0); }
1
#include <pthread.h> int clientCount = 0; int byteCount = 0; pthread_mutex_t lock; struct serverParm{ int connectionfd; int clientNO; }; static int callback(void *data, int argc, char **argv, char **azColName) { int *fileDesc; fileDesc = (int *) data; int i; for (i = 0; i < argc; i++) { byteCount += write(*fileDesc, azColName[i], strlen(azColName[i])); byteCount += write(*fileDesc, " = ", 3); byteCount += write(*fileDesc, argv[i], strlen(argv[i])); byteCount += write(*fileDesc, "\\n", 1); } byteCount += write(*fileDesc, "\\n", 1); return 0; } void sqlHandler(char cmd[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char sql[1025]; int *fileDesc; fileDesc = (int *) malloc(sizeof(fileDesc)); *fileDesc = open("result.txt", O_APPEND | O_WRONLY); rc = sqlite3_open("book.db", &db); if (rc) { fprintf(stderr, "Can't open database\\n", sqlite3_errmsg(db)); exit(0); } else { } strcpy(sql, cmd); printf("Statement: %s\\n", sql); rc = sqlite3_exec(db, sql, callback, (void*)fileDesc, &zErrMsg); if (rc != SQLITE_OK) { fprintf(stderr, "SQL error: %s\\n", zErrMsg); byteCount += write(*fileDesc, "SQL error: ", 11); byteCount += write(*fileDesc, zErrMsg, strlen(zErrMsg)); byteCount += write(*fileDesc, "\\n", 1); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Operation done successfully\\n"); } sqlite3_close(db); close(*fileDesc); free(fileDesc); } void *threadFunction(void *parmPtr){ char cmd[1025]; int cmdLen; char result[4096]; int readfd; int writefd; pthread_t tid; tid = pthread_self(); time_t curtime; struct tm *timestamp; char timeHeading[100]; printf("Connection established: %d\\n", ((struct serverParm *) parmPtr)->connectionfd); clientCount++; ((struct serverParm *) parmPtr)->clientNO = clientCount; while((cmdLen = recv(((struct serverParm *) parmPtr)->connectionfd, cmd, 1025, 0)) > 0){ pthread_mutex_lock(&lock); if(strcmp(cmd, "exit") == 0){ close(((struct serverParm *) parmPtr)->connectionfd); free(((struct serverParm *) parmPtr)); clientCount--; pthread_mutex_unlock(&lock); pthread_exit(0); } curtime = time(0); timestamp = localtime(&curtime); strftime(timeHeading, sizeof(timeHeading), "%c", timestamp); writefd = open("result.txt", O_CREAT | O_TRUNC | O_WRONLY, 0644); byteCount += write(writefd, timeHeading, strlen(timeHeading)); byteCount += write(writefd, " Thread ID: ", 12); close(writefd); FILE *file; file = fopen("result.txt", "a"); byteCount += fprintf(file, "%lu (0x%lx)\\n", (unsigned long)tid, (unsigned long)tid); fclose(file); FILE *logfile; logfile = fopen("a4p1ServerLog.txt", "a"); fclose(logfile); sqlHandler(cmd); recv(((struct serverParm *) parmPtr)->connectionfd, cmd, 1025, 0); readfd = open("result.txt", O_RDONLY); read(readfd, result, byteCount); send(((struct serverParm *) parmPtr)->connectionfd, result, strlen(result), 0); memset(&result, 0, sizeof(result)); send(((struct serverParm *) parmPtr)->connectionfd, result, 4096, 0); byteCount = 0; pthread_mutex_unlock(&lock); } close(((struct serverParm *) parmPtr)->connectionfd); free(((struct serverParm *) parmPtr)); clientCount--; pthread_exit(0); } int main(){ int listenSocket, acceptSocket, n; struct sockaddr_in cliAddr, servAddr; pthread_t threadID; struct serverParm *parmPtr; if(pthread_mutex_init(&lock, 0) != 0){ perror("Failed to initialize mutex"); exit(1); } listenSocket = socket(AF_INET, SOCK_STREAM, 0); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = htonl(INADDR_ANY); servAddr.sin_port = htons(6000); bind(listenSocket, (struct sockaddr *)&servAddr, sizeof(servAddr)); listen(listenSocket, 5); printf("Starts listening...\\n"); while(1){ acceptSocket = accept(listenSocket, 0, 0); printf("Client accepted!!! Assigning thread to serve client\\n"); parmPtr = (struct serverParm *) malloc(sizeof(struct serverParm)); parmPtr->connectionfd = acceptSocket; if(pthread_create(&threadID, 0, threadFunction, (void *)parmPtr) != 0){ perror("Failed to create thread"); close(acceptSocket); close(listenSocket); exit(1); } printf("Server ready for another client\\n"); } close(listenSocket); }
0
#include <pthread.h> struct student { int id; int age; int name; }stu; int i; pthread_mutex_t mutex; void *thread_fun1(void *arg) { while(1) { pthread_mutex_lock(&mutex); stu.id = i; stu.age = i; stu.name = i; i++; if(stu.id !=stu.age ||stu.id!=stu.name||stu.age!=stu.name ) { printf("%d,%d,%d\\n",stu.id,stu.age,stu.name); break; } pthread_mutex_unlock(&mutex); } return (void *)0; } void *thread_fun2(void *arg) { while(1) { pthread_mutex_lock(&mutex); stu.id = i; stu.age = i; stu.name = i; if(stu.id !=stu.age ||stu.id!=stu.name||stu.age!=stu.name ) { printf("%d,%d,%d\\n",stu.id,stu.age,stu.name); break; } i++; pthread_mutex_unlock(&mutex); } return (void *)0; } int main() { pthread_t tid1,tid2; int err; err = pthread_mutex_init(&mutex,0); if(err!=0) { printf("init mutex failed\\n"); return; } err= pthread_create(&tid1,0,thread_fun1,0); if(err!=0) { printf("create new thread failed\\n"); return; } err= pthread_create(&tid2,0,thread_fun2,0); if(err!=0) { printf("create new thread failed\\n"); return; } pthread_join(tid1,0); pthread_join(tid2,0); return 0; }
1
#include <pthread.h> static int led_isOn = CONTROL_UNKNOWN; static int led_green_isOn = CONTROL_UNKNOWN; static int led_red_isOn = CONTROL_UNKNOWN; static int nChargingFull = CONTROL_UNKNOWN; static int nChargingRemoved = CONTROL_UNKNOWN; void turn_led_on() { if (led_isOn == CONTROL_ON) return; led_isOn = CONTROL_ON; property_set("sys.ipo.ledon", "1"); } void turn_led_off() { if (led_isOn == CONTROL_OFF) return; led_isOn = CONTROL_OFF; property_set("sys.ipo.ledon", "0"); } void start_red_led(int skew) { if (led_red_isOn == CONTROL_ON) return; led_red_isOn = CONTROL_ON; if (skew > 255) skew = 255; else if (skew < 0) skew = 0; set_int_value("/sys/class/leds/red/brightness", skew); } void stop_red_led() { if (led_red_isOn == CONTROL_OFF) return; led_red_isOn = CONTROL_OFF; set_int_value("/sys/class/leds/red/brightness", 0); } void start_green_led(int skew) { if (led_green_isOn == CONTROL_ON) return; led_green_isOn = CONTROL_ON; if (skew > 255) skew = 255; else if (skew < 0) skew = 0; set_int_value("/sys/class/leds/green/brightness", skew); } void stop_green_led() { if (led_green_isOn == CONTROL_OFF) return; led_green_isOn = CONTROL_OFF; set_int_value("/sys/class/leds/green/brightness", 0); } int lights_chgfull() { SXLOGI("lights_chgfull"); pthread_mutex_lock(&mutex); nChargingFull = CONTROL_ON; nChargingRemoved = CONTROL_OFF; stop_red_led(); start_green_led(255); turn_led_on(); pthread_mutex_unlock(&mutex); return 0; } int lights_chgon() { SXLOGI("lights_chgon"); pthread_mutex_lock(&mutex); nChargingFull = CONTROL_OFF; nChargingRemoved = CONTROL_OFF; stop_green_led(); start_red_led(255); turn_led_on(); pthread_mutex_unlock(&mutex); return 0; } int lights_chgexit() { SXLOGI("lights_chgexit"); pthread_mutex_lock(&mutex); nChargingFull = CONTROL_OFF; nChargingRemoved = CONTROL_ON; stop_green_led(); stop_red_led(); turn_led_off(); pthread_mutex_unlock(&mutex); return 0; }
0
#include <pthread.h> static int *buffer; static int size; static int num_producers; static int cindex; static int pindex; pthread_t thread; int id; } thread_data; struct thread_data *producers; struct thread_data *consumers; static sem_t spaces; static sem_t items; static pthread_mutex_t mutex; static int producer_count; static int consumer_count; static void *producer(void *context) { thread_data *producers = (thread_data*)context; int output = producers->id; while (1) { sem_wait(&spaces); pthread_mutex_lock(&mutex); if (producer_count > 0) { buffer[pindex] = output; pindex = (pindex + 1) % size; output += num_producers; producer_count--; } pthread_mutex_unlock(&mutex); if (producer_count == 0) { sem_post(&spaces); pthread_exit(0); } } } static void *consumer(void *context) { thread_data *consumers = (thread_data*)context; int input = -1; while (1) { sem_wait(&items); pthread_mutex_lock(&mutex); if (consumer_count > 0) { input = buffer[cindex]; cindex = (cindex + 1) % size; float input_sqrt = sqrt(input); if ((input_sqrt - (int)input_sqrt) == 0) { printf("%d %d %d\\n", consumers->id, input, (int)input_sqrt); } consumer_count--; sem_post(&spaces); } pthread_mutex_unlock(&mutex); if (consumer_count == 0) { sem_post(&items); pthread_exit(0); } } } void pc_run(int N, int B, int P, int C) { buffer = malloc(B*sizeof(int)); size = B; cindex = 0; pindex = 0; num_producers = P; producers = malloc(P*sizeof(thread_data)); consumers = malloc(C*sizeof(thread_data)); producer_count = N; consumer_count = N; pthread_mutex_init(&mutex, 0); sem_init(&spaces, 0, B); sem_init(&items, 0, 0); for (int i = 0; i < P; i++) { producers[i].id = i; pthread_create(&producers[i].thread, 0, producer, &producers[i]); } for (int i = 0; i < C; i++) { consumers[i].id = i; pthread_create(&consumers[i].thread, 0, consumer, &consumers[i]); } for (int i = 0; i < P; i++) { pthread_join(producers[i].thread, 0); } for (int i = 0; i < C; i++) { pthread_join(consumers[i].thread, 0); } } void pc_clean() { free(buffer); free(producers); free(consumers); pthread_mutex_destroy(&mutex); sem_destroy(&spaces); sem_destroy(&items); }
1
#include <pthread.h> int shared_x = 0; int resource_counter = 0; int waiting_readers = 0; int NUM_READS = 5; int NUM_WRITES = 5; int NUM_READERS = 10; int NUM_WRITERS = 3; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t c_read = PTHREAD_COND_INITIALIZER; pthread_cond_t c_write = PTHREAD_COND_INITIALIZER; void *reader(void *param); void *writer(void *param); int main(int argc, char* argv[]){ pthread_t rt[NUM_READERS]; pthread_t wt[NUM_WRITERS]; int i=0; int reader_thread_num[NUM_READERS]; int writer_thread_num[NUM_WRITERS]; for(i=0; i<NUM_READERS; i++){ reader_thread_num[i] = i; if(pthread_create(&rt[i], 0, reader, (void*)&reader_thread_num[i]) != 0) { fprintf(stderr, "Unable to create reader thread\\n"); exit(1); } } for(i=0; i<NUM_WRITERS; i++){ writer_thread_num[i] = i; if(pthread_create(&wt[i], 0, writer, (void*)&writer_thread_num[i]) != 0) { fprintf(stderr, "Unable to create writer thread\\n"); exit(1); } } for(i=0; i<NUM_READERS; i++){ pthread_join(rt[i], 0); } for(i=0; i<NUM_WRITERS; i++){ pthread_join(wt[i], 0); } printf("Parent process quiting\\n"); return 0; } void *writer(void *param){ int *i = (int *)param; int num = 0; for(num=0; num<NUM_READS; num++){ usleep(1000 * (random() % (NUM_READERS + NUM_WRITERS))); pthread_mutex_lock(&m); while(resource_counter != 0) pthread_cond_wait(&c_write, &m); resource_counter = -1; pthread_mutex_unlock(&m); printf("Writer[%d] writes value %d\\n", *i, ++shared_x); fflush(stdout); pthread_mutex_lock(&m); resource_counter = 0; if(waiting_readers > 0) pthread_cond_broadcast(&c_read); else pthread_cond_signal(&c_write); pthread_mutex_unlock(&m); } pthread_exit(0); } void *reader(void *param){ int *i = (int*)param; int num = 0; for(num=0; num<NUM_WRITES; num++){ usleep(1000 * (random() % (NUM_READERS + NUM_WRITERS))); pthread_mutex_lock(&m); waiting_readers ++; while(resource_counter == -1) pthread_cond_wait(&c_read, &m); resource_counter++; waiting_readers--; pthread_mutex_unlock(&m); printf ("Reader[%d] reads value %d\\n", *i, shared_x); fflush(stdout); pthread_mutex_lock(&m); resource_counter--; if(resource_counter == 0) pthread_cond_signal(&c_write); pthread_mutex_unlock(&m); } pthread_exit(0); }
0
#include <pthread.h> int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *idp) { int j,i; double result=0.0; int *my_id = idp; for (i=0; i < 8; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 10) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %d, count = %d Threshold reached.\\n", *my_id, count); } printf("inc_count(): thread %d, count = %d, unlocking mutex\\n", *my_id, count); pthread_mutex_unlock(&count_mutex); for (j=0; j < 10000; j++) result = result + (double)random(); } pthread_exit(0); } void *watch_count(void *idp) { int *my_id = idp; printf("Starting watch_count(): thread %d\\n", *my_id); pthread_mutex_lock(&count_mutex); if (count < 10) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %d Condition signal received.\\n", *my_id); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int i, rc; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[2], &attr, watch_count, (void *)&thread_ids[2]); pthread_create(&threads[0], &attr, inc_count, (void *)&thread_ids[0]); pthread_create(&threads[1], &attr, inc_count, (void *)&thread_ids[1]); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Done.\\n", 3); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit (0); }
1
#include <pthread.h> pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t writer_condition = PTHREAD_COND_INITIALIZER; pthread_cond_t reader_condition = PTHREAD_COND_INITIALIZER; int waitingReaders = 0; int resource_counter = 0; int variable = 0; void *writer(void *param); void *reader(void *param); int main(int argc, char *argv[]) { pthread_t tid1[5], tid2[5]; int i; int tNum[5]; for (i = 0; i < 5; i++) { tNum[i] = i; if (pthread_create(&tid1[i], 0, writer, &tNum[i]) != 0) { fprintf(stderr, "Unable to create writer thread\\n"); exit(1); } } for (i = 0; i < 5; i++) { if (pthread_create(&tid2[i], 0, reader, &tNum[i]) != 0) { fprintf(stderr, "Unable to create reader thread\\n"); exit(1); } } for (i = 0; i < 5; i++) { pthread_join(tid1[i], 0); } for (i = 0; i < 5; i++) { pthread_join(tid2[i], 0); } printf("Parent quitting\\n"); return 0; } void *writer(void *param) { int id = *((int*)param); int i; for (i = 0; i < 10; i++) { usleep(1000 * (random() % 5 + id)); pthread_mutex_lock(&m); while (resource_counter != 0) { pthread_cond_wait(&writer_condition, &m); } resource_counter = -1; pthread_mutex_unlock(&m); variable++; printf("Writer %d is accessing on iteration %d: %d\\n", id, i, variable); printf("Number of readers: %d\\n", resource_counter); fflush(stdout); pthread_mutex_lock(&m); resource_counter = 0; if (waitingReaders > 0) { pthread_cond_broadcast(&reader_condition); } else { pthread_cond_signal(&writer_condition); } pthread_mutex_unlock(&m); } printf("Writer %d finished\\n", id); fflush(stdout); return 0; } void *reader(void *param) { int id = *((int*)param); int i; for (i = 0; i < 10; i++) { usleep(1000 * (random() % 5 + 5)); pthread_mutex_lock(&m); waitingReaders++; while (resource_counter == -1) { pthread_cond_wait(&reader_condition, &m); } waitingReaders--; resource_counter++; pthread_mutex_unlock(&m); printf("Reader %d is accessing on iteration %d: %d\\n", id, i, variable); printf("Number of readers: %d\\n", resource_counter); fflush(stdout); pthread_mutex_lock(&m); resource_counter--; if (resource_counter == 0) { pthread_cond_signal(&writer_condition); } pthread_mutex_unlock(&m); } printf("Reader %d finished\\n", id); fflush(stdout); return 0; }
0
#include <pthread.h> pthread_t dipendenti[10]; pthread_t cuoco; { int primi_piatti_consumati; sem_t primo_piatto, secondo_piatto, seconda_fase, posto_libero; pthread_mutex_t lock; } Mensa; Mensa mensa; void * cuoco_thread(void * t) { unsigned int tempo_di_preparazione; for(int i=0; i < 10; i++) { sem_wait(&mensa.posto_libero); tempo_di_preparazione = rand() % 2; printf("[Cuoco] Preparo un nuovo primo piatto\\n"); sleep(tempo_di_preparazione); sem_post(&mensa.primo_piatto); } sem_wait(&mensa.seconda_fase); for(int i=0; i < 10; i++) { sem_wait(&mensa.posto_libero); tempo_di_preparazione = rand() % 2; printf("[Cuoco] Preparo un nuovo secondo piatto\\n"); sleep(tempo_di_preparazione); sem_post(&mensa.secondo_piatto); } printf("[Cuoco] finito!\\n"); pthread_exit(0); } void * dipendente_thread(void * t) { unsigned int tempo_di_consumazione; int tid = (int)(intptr_t) t; sem_wait(&mensa.primo_piatto); tempo_di_consumazione = rand() % 3; printf("[Dipendente %d] consumo primo piatto\\n", tid); sleep(tempo_di_consumazione); pthread_mutex_lock(&mensa.lock); mensa.primi_piatti_consumati++; printf("[Dipendente %d] finito primo piatto\\n", tid); sem_post(&mensa.posto_libero); if(mensa.primi_piatti_consumati == 10) { printf("[Dipendente %d] sono l'ultimo a finire il primo piatto! Si dia il via ai secondi piatti!\\n", tid); sem_post(&mensa.seconda_fase); } pthread_mutex_unlock(&mensa.lock); sem_wait(&mensa.secondo_piatto); printf("[Dipendente %d] consumo secondo piatto\\n", tid); sleep(tempo_di_consumazione); sem_post(&mensa.posto_libero); printf("[Dipendente %d] grazie del pranzo\\n", tid); return 0; } void init(Mensa *m) { sem_init(&m->posto_libero, 0, 6); sem_init(&m->primo_piatto, 0, 0); sem_init(&m->seconda_fase, 0, 0); sem_init(&m->secondo_piatto, 0, 0); pthread_mutex_init(&m->lock, 0); } int main(int argc, char * argv[]) { printf("Programma mensa avviato\\n"); int result; void * status; init(&mensa); for(int i=0; i < 10; i++) { result = pthread_create(&dipendenti[i], 0, dipendente_thread, (void *)(intptr_t) i); if(result) { perror("Errore nella creazione dei dipendenti\\n"); exit(-1); } } pthread_create(&cuoco, 0, cuoco_thread, 0); for(int i=0; i < 10; i++) { result = pthread_join(dipendenti[i], &status); if(result) { perror("Errore nella join\\n"); exit(-1); } } pthread_join(cuoco, &status); return 0; }
1
#include <pthread.h> int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i<10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %ld, count = %d Threshold reached.\\n", my_id, count); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while (count<12) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); } count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char *argv[]) { int i, rc; long t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *)t2); pthread_create(&threads[2], &attr, inc_count, (void *)t3); for (i=0; i<3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Done.\\n", 3); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
0
#include <pthread.h> struct mymesg { long mtype; char mtext[512 + 1]; }; struct threadinfo { int qid; int fd; int len; pthread_mutex_t mutex; pthread_cond_t ready; struct mymesg m; }; void* helper (void* arg) { int n; struct threadinfo* tip = arg; for (;;) { memset (&tip->m, 0, sizeof (struct mymsg)); if ( (n = msgrcv (tip->qid, &tip->m, 512, 0, MSG_NOERROR)) < 0) { err_sys ("msgrcv error"); } tip->len = n; pthread_mutex_lock (&tip->mutex); if (write (tip->fd, "a", sizeof (char)) < 0) { err_sys ("write error"); } pthread_cond_wait (&tip->ready, &tip->mutex); pthread_mutex_unlock (&tip->mutex); } } int main() { char c; int i, n, err; int fd[2]; int qid[3]; struct pollfd pfd[3]; struct threadinfo ti[3]; pthread_t tid[3]; for (i = 0; i < 3; i++) { if ( (qid[i] = msgget ( (0x123 + i), IPC_CREAT | 0666)) < 0) { err_sys ("msgget error"); } printf ("queue ID %d is %d\\n", i, qid[i]); if (socketpair (AF_UNIX, SOCK_DGRAM, 0, fd) < 0) { err_sys ("socketpair error"); } pfd[i].fd = fd[0]; pfd[i].events = POLLIN; ti[i].qid = qid[i]; ti[i].fd = fd[1]; if (pthread_cond_init (&ti[i].ready, 0) != 0) { err_sys ("pthread_cond_init error"); } if (pthread_mutex_init (&ti[i].mutex, 0) != 0) { err_sys ("pthread_mutex_init error"); } if ( (err = pthread_create (&tid[i], 0, helper, &ti[i])) != 0) { err_exit (err, "pthread_create error"); } } for (;;) { if (poll (pfd, 3, -1) < 0) { err_sys ("poll error"); } for (i = 0; i < 3; i++) { if (pfd[i].revents & POLLIN) { if ( (n = read (pfd[i].fd, &c, sizeof (char))) < 0) { err_sys ("read error"); } ti[i].m.mtext[ti[i].len] = 0; printf ("queue id %d, message %s\\n", qid[i], ti[i].m.mtext); pthread_mutex_lock (&ti[i].mutex); pthread_cond_signal (&ti[i].ready); pthread_mutex_unlock (&ti[i].mutex); } } } exit (0); }
1
#include <pthread.h> pthread_mutex_t mutexvar=PTHREAD_MUTEX_INITIALIZER; int Matrix_rows,Matrix_cols,Vector_size; double **Matrix,*Vector,*Result_matrix; void * mul(void *l) { int j; double sum=0; int a=(int)l; for(j=0;j<Vector_size;j++) sum=sum+(Matrix[a][j]*Vector[j]); pthread_mutex_lock(&mutexvar); Result_matrix[a]=sum; pthread_mutex_unlock(&mutexvar); return 0; } int main(int argc,char *argv[]) { int i,j,r; struct timeval start,end; double Time_taken; if(argc<3) { printf("provide matrix and vector sizes"); exit(0); } Matrix_rows=atoi(argv[1]); Matrix_cols=atoi(argv[2]); Vector_size=atoi(argv[3]); printf("matrix n vector size %d %d %d",Matrix_rows,Matrix_cols,Vector_size); Matrix=(double **)malloc(sizeof(double *)*Matrix_rows); if(Matrix==0) { printf("memory not available"); exit(0); } for(i=0;i<Matrix_rows;i++) { Matrix[i]=(double * )malloc(sizeof(double )*Matrix_cols); } for(i=0;i<Matrix_rows;i++) { for(j=0;j<Matrix_cols;j++) { Matrix[i][j]=rand()/100; } } Vector=(double *)malloc(sizeof(double)*Vector_size); if(Vector==0) { printf("memory not available"); exit(0); } for(i=0;i<Vector_size;i++) { Vector[i]=rand()/100; } Result_matrix=(double *)malloc(sizeof(double)*Matrix_rows); if(Result_matrix==0) { printf("memory not available"); exit(0); } gettimeofday(&start,0); pthread_t thread[Matrix_rows]; for(i=0;i<Matrix_rows;i++) { r=pthread_create(&thread[i],0,mul,(void *)i); if(r) { printf("thread creation failed"); exit(0); } } for(i=0;i<Matrix_rows;i++) { r=pthread_join(thread[i],0); if(r) { printf("thread joining failed"); exit(0); } } gettimeofday(&end,0); if(end.tv_usec<start.tv_usec) { end.tv_usec=end.tv_sec+1000000; end.tv_sec=end.tv_sec-1; } end.tv_usec=end.tv_usec-start.tv_usec; end.tv_sec=end.tv_sec-start.tv_sec; Time_taken=(double)end.tv_usec/1000000; Time_taken=Time_taken+(double )end.tv_sec; printf("no of operations : %d\\n",2*Matrix_rows*Vector_size); printf("Time taken : %f\\n",Time_taken); printf("performance in Mflops is : %f\\n",(2*Matrix_rows*Vector_size)/(Time_taken*1000000)); }
0
#include <pthread.h> static void fail( char const *message ) { fprintf( stderr, "%s\\n", message ); exit( 1 ); } int *numList; int numCount = 0; int total = 0; sem_t s; int numWorked = 0; int finished = 0; pthread_mutex_t mon = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t workWait = PTHREAD_COND_INITIALIZER; void readNumbers() { int val; while ( scanf( "%d", &val ) == 1 ) { if ( numCount >= 20000 ) fail( "Too many numbers" ); numList[ numCount++ ] = val; pthread_cond_signal( &workWait); } finished = 1; pthread_cond_broadcast( &workWait); } int gcd( int a, int b ) { while ( b != 0 ) { int c = a % b; a = b; b = c; } return a; } void *consumer( void *param ) { while (!finished || (numWorked != numCount)) { pthread_mutex_lock( &mon ); while( numWorked == numCount ){ if(finished){ pthread_mutex_unlock( &mon ); return 0; } pthread_cond_wait( &workWait, &mon); } numWorked++; int currCount = numWorked - 1; for ( int i = currCount - 1; i >= 0; i-- ) { if ( gcd ( numList[i], numList[ currCount] ) == 1 ) { sem_wait(&s); total++; sem_post(&s); } } pthread_mutex_unlock( &mon); } return 0; } int main( int argc, char *argv[] ) { int workers = 4; if ( argc != 2 || sscanf( argv[ 1 ], "%d", &workers ) != 1 || workers < 1 ) fail( "usage: pairs <workers>" ); numList = (int *) malloc( 20000 * sizeof( int ) ); pthread_t consumers[ workers ]; sem_init(&s, 0, 1 ); for ( int i = 0; i < workers; i++ ) { if ( pthread_create( &consumers[i], 0, consumer, 0 ) != 0 ) fail( "Unable to create consumer thread" ); } readNumbers(); for ( int i = 0; i < workers; i++ ) { pthread_join( consumers[i], 0 ); } printf( "Total: %d\\n", total ); return 0; }
1
#include <pthread.h> int * subset; int N; int len; int start; int end; int * counter; pthread_mutex_t * mutex_o; }Task; int countsumOf(int * set, int len, int index) { if(len > (pow(2, len) - 1)) { printf("This program cannot handle more than %f length of set", (pow(2, len) - 1)); } int sum = 0; int i; for(i = 0; i < len; i ++) { if(((index >> i) & 0x0001) == 1) { sum += set[i]; } } return sum; } void * countSubsets(void * Thread) { Task * thtask = (Task *)Thread; if(thtask != 0){ int i; for(i = thtask -> start; i <= thtask -> end; i++) { if(countsumOf(thtask -> subset, thtask -> len, i) == thtask -> N) { pthread_mutex_lock(thtask -> mutex_o); *(thtask -> counter) += 1; pthread_mutex_unlock(thtask -> mutex_o); } } return (void *)thtask; } return 0; } void assignTasks(Task * Thread, int Thread_n, int * set, int N, int len, int numThread, int * counter, pthread_mutex_t * mutex_o) { int task_size = pow(2,len) / numThread; Thread -> subset = set; Thread -> N = N; Thread -> len = len; Thread -> start = task_size * (Thread_n); if(!(Thread_n == numThread - 1)) Thread -> end = Thread -> start + task_size - 1; else Thread -> end = (int)pow(2,len) - 1; if(Thread_n == 0) Thread -> start = 1; Thread -> counter = counter; Thread -> mutex_o = mutex_o; } int subsetSum(int * intset, int length, int N, int numThread) { int counter = 0; pthread_mutex_t mutex_o = PTHREAD_MUTEX_INITIALIZER; pthread_t p_threads[numThread]; int thread_id[numThread]; int i,j; j = 0; Task * thTasks[numThread]; for(i = 0; i < numThread; i++) { thTasks[i] = malloc(sizeof(Task)); assignTasks(thTasks[i], i,intset, N,length, numThread, &counter, &mutex_o); } while(j < numThread) { thread_id[j] = pthread_create(&p_threads[j], 0, countSubsets, (void *)thTasks[j]); j++; } for(i = 0; i < numThread; i++) { pthread_join(p_threads[i], 0); } pthread_mutex_destroy(&mutex_o); for(i = 0; i < numThread; i++) { free(thTasks[i]); } return counter; }
0
#include <pthread.h> int quit,sum; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t waitloc =PTHREAD_COND_INITIALIZER; void *thr_fn(void *arg) { int j = 0; printf("thr_fn\\n"); if (j==0){ printf("the init j success\\n"); while(j<101){ pthread_mutex_lock(&lock); sum += j; pthread_mutex_unlock(&lock); j++; } pthread_mutex_lock(&lock); printf("the sum:%d\\n", sum); pthread_mutex_unlock(&lock); } pthread_exit((void *)0); } int main(int argc, char **argv) { int i,err,num =0; pthread_t tid[i]; pthread_attr_t attr; err = pthread_attr_init(&attr); if (err) return(err); err = pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); if (err==0){ for (int i = 0; i < 5; ++i) { err = pthread_create(&tid[i],&attr,thr_fn,(void *)&num); if (err) { printf("craete err\\n"); } } }else printf("set pthread detach failed\\n"); pthread_attr_destroy(&attr); sleep(1); for (int i = 5; i >0; --i) { printf("wait the thread:%d\\n", i); err = pthread_join(tid[i],(void *)&err); if (!err) { printf("wait success thread :%d\\n",i); } } return 0; }
1
#include <pthread.h> struct process_mufi { char * name; int line; int (*func) (void *); void * arg; int priority; int started; double init; struct process_mufi * next; }; static ProcessMUFI head; static int init = 0; static int running = 0; static pthread_mutex_t head_lock; static pthread_mutex_t file_lock; static pthread_t *threads_ids; static long threads; static double *end_time; static FILE *log; static int context_changes; static int output_info; static int output_line; void mufi_exec(char *name, int line, double remaining, int (*func) (void *), void *arg) { ProcessMUFI tmp, novo; if (init) pthread_mutex_lock(&head_lock); tmp = head; if (line >= 0 && output_info == 100) { fprintf(stderr, " NEW '%s' (%d)\\n", name, line); } else if (output_info == 99) { fprintf(stderr, "%.3f\\t NEW '%s'\\n", time2(), name); } while (tmp != 0 && tmp->next != 0) tmp = tmp->next; novo = malloc2(sizeof(struct process_mufi)); novo->name = name; novo->line = line; novo->func = func; novo->arg = arg; novo->next = 0; novo->priority = 1; novo->started = 0; novo->init = time2(); if (head == 0) head = novo; else tmp->next = novo; if (init) pthread_mutex_unlock(&head_lock); } static void * escalona (void * n) { ProcessMUFI atual, tmp; int *number; int flag; int return_value; double tf; number = (int *)n; while (1) { pthread_mutex_lock(&head_lock); if (head != 0) { atual = head; head = head->next; running++; end_time[*number] = time2() + atual->priority * 0.5; pthread_mutex_unlock(&head_lock); if (atual->line >= 0 && output_info == 100) { fprintf(stderr, "%d) IN '%s' (%d)\\n", *number, atual->name, atual->line); } else if (output_info == 99) { if (atual->started == 0) { fprintf(stderr, "%.3f\\t %3d > START '%s'\\n", time2(), *number, atual->name); } else { fprintf(stderr, "%.3f\\t %3d > IN '%s'\\n", time2(), *number, atual->name); } } atual->started = 1; return_value = atual->func(atual->arg); pthread_mutex_lock(&head_lock); if (return_value == 1) { tmp = head; atual->next = 0; atual->priority += 1; while (tmp != 0 && tmp->next != 0) tmp = tmp->next; if (head == 0) head = atual; else tmp->next = atual; context_changes++; } else { if (atual->line >= 0) { tf = time2(); pthread_mutex_lock(&file_lock); fprintf(log, "%s %.5f %.5f\\n", atual->name, tf, tf-atual->init); output_line++; pthread_mutex_unlock(&file_lock); } } running--; pthread_mutex_unlock(&head_lock); if (atual->line >= 0 && output_info == 100) { if (return_value == 1) { fprintf(stderr, "%d) OUT '%s'\\n", *number, atual->name); } else { fprintf(stderr, "%d) END '%s' (%d)\\n", *number, atual->name, output_line-1); } } else if (output_info == 99) { if (return_value == 1) { fprintf(stderr, "%.3f\\t %3d > OUT '%s'\\n", time2(), *number, atual->name); } else { fprintf(stderr, "%.3f\\t %3d > END '%s'\\n", time2(), *number, atual->name); } } } else { flag = running == 0 && head == 0; pthread_mutex_unlock(&head_lock); if (flag) { if (output_info == 99) fprintf(stderr, "%.3f\\t %3d > OFF\\n", time2(), *number); return 0; } sleep2 (0.05); } } } void mufi_init(char *log_file, int output) { int i; int *cpu_n; threads = sysconf(_SC_NPROCESSORS_ONLN); log = fopen(log_file, "w"); output_info = output; output_line = 0; threads_ids = malloc2(sizeof(pthread_t) * threads); cpu_n = malloc2(sizeof(int) * threads); end_time = malloc2(sizeof(double) * threads); context_changes = 0; if (pthread_mutex_init(&head_lock, 0) != 0 && pthread_mutex_init(&file_lock, 0) != 0) { fprintf(stderr, "Erro ao criar mutex!\\n"); } else { init = 1; for (i = 0; i < threads; ++i) { cpu_n[i] = i; pthread_create(&threads_ids[i], 0, escalona, &cpu_n[i]); } for (i = 0; i < threads; ++i) { pthread_join(threads_ids[i], 0); } pthread_mutex_destroy(&head_lock); pthread_mutex_destroy(&file_lock); } if (output_info == 100) fprintf(stderr, " MC %d\\n", context_changes); fprintf(log, "%d\\n", context_changes); fclose(log); } int mufi_run() { int i; pthread_t my_id; my_id = pthread_self(); for (i = 0; i < threads; ++i) { if (my_id == threads_ids[i]) { if (end_time[i] <= time2() && running == threads) return 1; } } return 0; }
0
#include <pthread.h> int nitems; struct{ pthread_mutex_t mutex; int buff[ 100000]; int nput; int nval; } shared = { PTHREAD_MUTEX_INITIALIZER }; void *produce( void*), *consume( void*), consume_wait( int i); int main( int argc, char** argv) { int i, nthreads, count[ 100]; pthread_t tid_produce[ 100], tid_consume; nitems = (atoi( argv[1]) > 100000? 100000: atoi( argv[1])); nthreads = (atoi( argv[2]) > 100? 100: atoi( argv[2])); pthread_setconcurrency( nthreads + 1); for ( int 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 ( int i = 0; i < nthreads; i++){ pthread_join( tid_produce[i], 0); printf("count[ %d] = %d\\n", i, count[i]); } pthread_join( tid_consume, 0); return 0; } void * produce( void *arg) { while( 1){ 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) { while(1){ pthread_mutex_lock( &shared.mutex); if( i < shared.nput){ pthread_mutex_unlock( &shared.mutex); return; } pthread_mutex_unlock( &shared.mutex); } } void * consume( void *arg) { for( int i = 0; i < nitems; i++){ consume_wait( i); if( shared.buff[i] != i) printf( "buff[%d] = %d\\n", i, shared.buff[i]); } return 0; }
1
#include <pthread.h> pthread_mutex_t print_region = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t crit_region = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t *mutex_p; pthread_cond_t *cond_p; char *philosophers; int n; int all_together; void print(){ pthread_mutex_lock(&print_region); int i=0; printf("%c", philosophers[i]); for(i=1;i<n;i++) printf(" %c", philosophers[i]); printf("\\n"); pthread_mutex_unlock(&print_region); } int left(int philosopher){ if(philosopher==0){ return n-1; } else return philosopher-1; } int right(int philosopher){ if(philosopher==n-1){ return 0; } else return philosopher+1; } void test(int philosopher){ if (philosophers[philosopher] == 'H' && philosophers[left(philosopher)] != 'E' && philosophers[right(philosopher)] != 'E') { philosophers[philosopher] = 'E'; print(); pthread_cond_broadcast(&(cond_p[philosopher])); } } void *philosopher(void *args){ while(all_together); int index; index = *(int *)args; while(1){ switch(philosophers[index]){ case 'T': sleep((rand()%10)+1); philosophers[index] = 'H'; print(); break; case 'E': sleep((rand()%10)+1); pthread_mutex_lock(&crit_region); philosophers[index] = 'T'; print(); test(left(index)); test(right(index)); pthread_mutex_unlock(&crit_region); break; case 'H': pthread_mutex_lock(&crit_region); test(index); pthread_mutex_unlock(&crit_region); if(philosophers[index]!='E'){ pthread_mutex_lock(&(mutex_p[index])); pthread_cond_wait(&(cond_p[index]), &(mutex_p[index])); } break; } } } int main(int argn, char *argv[]){ if(argn==1){ printf("Missing paramenters\\n"); exit(1); } int i; sscanf(argv[1], "%d", &n); pthread_t th[n]; srand(time(0)); cond_p = calloc(n, sizeof(pthread_cond_t)); for(i=0;i<n;i++) pthread_cond_init(&(cond_p[i]), 0); mutex_p = calloc(n, sizeof(pthread_mutex_t)); for(i=0;i<n;i++) pthread_mutex_init(&(mutex_p[i]), 0); philosophers = calloc(n, sizeof(philosophers)); for(i=0;i<n;i++) philosophers[i] = 'H'; all_together=1; for(i=0;i<n;i++) {int *_i = calloc(1, sizeof(int)); *_i = i; pthread_create(&(th[n]), 0, philosopher, _i);} all_together=0; print(); while(1); }
0
#include <pthread.h> pthread_mutex_t toggleMutex; char* fileName = "invalid"; int num_threads = 4; int num_threads_merge = -1; char *pbuf; ssize_t numRead; char *addr; size_t len = 0; FILE *fileIn; int fileNum; char *thread_offset; long num_records_per_thread; int increment_offset; struct stat sb; long t; int rc; pthread_t thread[512]; pthread_attr_t attr; char* calc_offset(long t) { if(t == 0) { return addr; } else { char *offset = addr + (t * increment_offset); return offset; } } int compare(const void *a, const void *b) { char keya[8]; strncpy(keya, (char *)a, 8); return strncmp((char *)a, (char *)b, 8); } void merge_threads(long current_t, int iter, long rec_per_threads) { pthread_mutex_lock(&toggleMutex); long target_thread = current_t + pow(2, iter); iter++; pthread_mutex_unlock(&toggleMutex); printf("In thread %ld, iteration number %d\\n", current_t, iter-1); if(current_t % 2 == 0) { printf("TARGET thread: %ld.\\n", target_thread); if(current_t % target_thread == 0) { pthread_join(thread[target_thread], 0); printf("pthread %ld has been merged with pthread %ld.\\n", current_t, target_thread); qsort(calc_offset((long)current_t), rec_per_threads, 63, compare); num_threads_merge = num_threads_merge - 1; printf("Number of threads after merge: %d\\n", num_threads_merge); if(num_threads_merge == 1) { pthread_exit(0); return; } merge_threads(current_t, iter, rec_per_threads*2); } printf("pthread %ld has been merged with pthread %ld.\\n", current_t, target_thread); num_threads_merge = num_threads_merge - 1; printf("Number of threads after merge: %d\\n", num_threads_merge); qsort(calc_offset((long)current_t), rec_per_threads*2, 63, compare); } qsort(calc_offset((long)current_t), rec_per_threads, 63, compare); } void *thread_sort(void *t) { printf("Thread %ld is working\\n", (long)t); merge_threads((long)t, 0, num_records_per_thread); pthread_exit(0); } int main(int argc, char *argv[]) { printf ("Default threads = %d\\n", num_threads); int n; if(argc > 1) { for(n = 1; n < argc; n++) { if(strcmp(argv[n], "-t") == 0) { num_threads = atoi(argv[++n]); num_threads_merge = num_threads; printf("Set num_threads = %d\\n", num_threads); continue; } else if(strcmp(argv[n], "-file") == 0) { fileName = argv[++n]; printf("Set input file\\n"); continue; } else { printf("Input file : %s.\\n", fileName); printf("ThreadCount : %d.\\n", num_threads); } } } else { printf("Usage: \\n\\t-t <num_threads>\\n\\t-file <input_file>\\n"); } pbuf = (char *)malloc(16); if (pbuf == 0) { printf("malloc failed.\\n"); exit(1); } fileNum = open(fileName, O_RDONLY); if(fileNum == -1) { printf("Error opening file."); exit(-1); } printf("File Opened Successfully\\n"); if((fstat(fileNum, &sb)) == -1) { printf("fstat fail"); exit(-1); } int sb_size = sb.st_size; int num_records = sb_size/63; printf("SB SIZE: %d\\n", sb_size); printf("num_records: %d\\n", num_records); addr = (char *)mmap(0, sb_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fileNum, 0); if (addr == MAP_FAILED) { close(fileNum); perror("Error mmapping the file"); exit(1); } printf("Unsorted Addr: \\n%s\\n", addr); num_records_per_thread = num_records/num_threads; printf("Number of Records per Thread = %ld\\n", num_records_per_thread); increment_offset = num_records_per_thread * 63; thread_offset = addr - increment_offset; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(t = 0; t < num_threads; t++) { printf("creating thread %ld\\n", t); rc = pthread_create(&thread[t], &attr, thread_sort, (void *)t); if (rc) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } rc = pthread_join(thread[0], 0); if (rc) { printf("ERROR; return code from pthread_create() for thread %ld is %d\\n", t, rc); } qsort(calc_offset((long)0), num_records, 63, compare); printf("Sort complete.\\n\\n"); printf("Sorted Records: \\n%s\\n", addr); return 0; }
1
#include <pthread.h> struct fifo_s { uint32_t count; void *buffer; ssize_t size; struct fifo_s *next; }; struct fifo_s * fifo_push (struct fifo_s *fifo, char *buffer, ssize_t size) { struct fifo_s *entry; struct fifo_s *last; entry = fifo; while ((entry = entry->next) == 0) { last = entry; last->count++; } entry = calloc (1, sizeof (struct fifo_s)); entry->buffer = malloc (size); if (!entry->buffer) { free (entry); return 0; } memcpy (entry->buffer, buffer, size); entry->size = size; if (last) last->next = entry; else fifo = entry; return fifo; } struct fifo_s * fifo_pull (struct fifo_s *fifo, char **buffer, ssize_t *size) { struct fifo_s *value; value = fifo; if (!value) return 0; *buffer = malloc (value->size); if (!*buffer) { return 0; } memcpy (*buffer, value->buffer, value->size); *size = value->size; fifo = fifo->next; free (value->buffer); value->buffer = 0; value->size = 0; free (value); return fifo; } int fifo_count (struct fifo_s *fifo) { if (!fifo) return 0; return fifo->count; } struct sound_tinyalsa_global_s { int cmd_card; int cmd_device; struct pcm *pcm; struct fifo_s *fifo; pthread_mutex_t mutex; pthread_cond_t cond; pthread_t thread; }; struct sound_tinyalsa_global_s g = { .cmd_card = 0, .cmd_device = 0, .pcm = 0, .fifo = 0 }; void * sound_tinyalsa_thread (void *arg) { struct sound_tinyalsa_global_s *data = (struct sound_tinyalsa_global_s *)arg; char *buffer = 0; ssize_t size = 0; while (1) { pthread_mutex_lock (&data->mutex); while (fifo_count(data->fifo) == 0) pthread_cond_wait (&data->cond, &data->mutex); data->fifo = fifo_pull (data->fifo, &buffer, &size); pthread_mutex_unlock (&data->mutex); pcm_write(data->pcm, buffer, size); } return 0; } int sound_tinyalsa_check(char *line, int len) { if (sscanf(line,"card=%i[^\\n]", &g.cmd_card)) { } else if (sscanf(line,"device=%i[^\\n]", &g.cmd_device)) { } return 0; } static int sound_tinyalsa_open(int channels, int encoding, long rate) { struct pcm_config config; unsigned int period_size = 1024; unsigned int period_count = 4; config.channels = channels; config.rate = rate; config.period_size = period_size; config.period_count = period_count; if (encoding == MPG123_ENC_SIGNED_32) config.format = PCM_FORMAT_S32_LE; else if (encoding == MPG123_ENC_SIGNED_16) config.format = PCM_FORMAT_S16_LE; config.start_threshold = 0; config.stop_threshold = 0; config.silence_threshold = 0; g.pcm = pcm_open(g.cmd_card, g.cmd_device, PCM_OUT, &config); if (g.pcm == 0) return -1; pthread_mutex_init (&g.mutex, 0); pthread_cond_init (&g.cond, 0); pthread_create(&g.thread, 0, sound_tinyalsa_thread, &g); return 0; } static int sound_tinyalsa_write(char *buffer, ssize_t size) { pthread_mutex_lock (&g.mutex); g.fifo = fifo_push (g.fifo, buffer, size); pthread_cond_signal (&g.cond); pthread_mutex_lock (&g.mutex); if (!g.fifo) return -1; return size; } static int sound_tinyalsa_close(void) { return pcm_close(g.pcm); } struct sound_module sound_tinyalsa = { .open = sound_tinyalsa_open, .write = sound_tinyalsa_write, .close = sound_tinyalsa_close, .get_volume = 0, .set_volume = 0, .get_mute = 0, .set_mute = 0, };
0
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cwait = PTHREAD_COND_INITIALIZER; void * thr_fn(void *arg) { int err, signo; for (;;) { err = sigwait(&mask, &signo); if (err != 0) { perror("sigwait failed"); exit(1); } switch (signo) { case SIGINT: printf("\\ninterrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&cwait); return(0); default: printf("Unexpected signal %d\\n", signo); exit(1); } } } int main(void) { int err; sigset_t oldmask; pthread_t tid; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGQUIT); sigaddset(&mask, SIGUSR1); if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) { perror("SIG_BLOCK error"); exit(1); } err = pthread_create( &tid, 0, thr_fn, 0); if (err != 0) { perror("can't create thread"); exit(1); } pthread_mutex_lock(&lock); while (quitflag == 0) pthread_cond_wait(&cwait, &lock); pthread_mutex_unlock(&lock); quitflag = 0; if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) { perror("SIG_SETMASK error"); exit(1); } exit(0); }
1
#include <pthread.h> static pthread_mutex_t forks[5]; static void lfsr_next(uint32_t * state) { uint32_t state_value = *state; uint32_t bit = ((state_value >> 0) ^ (state_value >> 10) ^ (state_value >> 30) ^ (state_value >> 31)) & 1; *state = (state_value >> 1) | (bit << 31); } void * philosopher_thread(void * ptr_id) { int id = *(int *) ptr_id; free(ptr_id); unsigned int rand_state = time(0) + id; lfsr_next(&rand_state); int forkA, forkB; if (id == 5 - 1) { forkA = 0; forkB = id; } else { forkA = id; forkB = id + 1; } for (;;) { printf("%d: Thinking\\n", id); lfsr_next(&rand_state); sleep(1 + (rand_state % 5)); printf("%d: Finished Thinking\\n", id); pthread_mutex_lock(&forks[forkA]); pthread_mutex_lock(&forks[forkB]); printf("%d: Eating\\n", id); lfsr_next(&rand_state); sleep(1 + (rand_state % 5)); pthread_mutex_unlock(&forks[forkA]); pthread_mutex_unlock(&forks[forkB]); } } int main(void) { pthread_t thr; printf("Dining Philosphers (%d philosophers)\\n\\n", 5); for (int i = 0; i < 5; i++) pthread_mutex_init(&forks[i], 0); for (int i = 0; i < 5; i++) { int * id_ptr = malloc(sizeof(int)); *id_ptr = i; pthread_create(&thr, 0, philosopher_thread, id_ptr); } for (;;) pause(); }
0
#include <pthread.h> pthread_t *tab; int val = 0; int valTab = 0; int condition = 0; static int valThread = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_attr_t attr; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void *funcThread(void *arg){ pthread_mutex_lock(&mutex); valThread++; val += (*(int*) arg); printf("Valeur de val : %d\\n",val); if(valThread == valTab){ condition = 1; pthread_cond_signal(&cond); } pthread_mutex_unlock(&mutex); pthread_exit((void*)0); return 0; } void *funcAttente(void *arg){ pthread_mutex_lock(&mutex); while(!condition) pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); printf("Valeur finale : %d\\n",val); pthread_exit((void*)0); } int main(int argc, char *argv[]) { int i = 0; int *pi; int *valeur; if(argc != 2) return 1; valTab = atoi(argv[1]); tab = malloc((valTab+1)*sizeof(pthread_t)); pthread_create(&tab[0],0,funcAttente,0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); for (i =1;i<valTab+1;i++) { pi = malloc(sizeof(int)); *pi = (int) (10*((double)rand())/ 32767) ; pthread_create(&tab[i],&attr,funcThread,pi); } pthread_join(tab[0], 0); }
1
#include <pthread.h> int numMax; int nthreads; int i_global = 0; int soma = 0; pthread_mutex_t mutex; int ehPrimo(long long int n){ int i; if (n <= 1) return 0; if (n == 2) return 1; if (n%2 == 0) return 0; for (i = 3; i < sqrt(n) + 1; i += 2) if(n%i == 0) return 0; return 1; } void *quantidadePrimos (void *args) { int i_local; int aux = 0; pthread_mutex_lock(&mutex); i_local = i_global; i_global++; pthread_mutex_unlock(&mutex); while(i_local <= numMax) { if(ehPrimo(i_local)) aux++; pthread_mutex_lock(&mutex); i_local = i_global; i_global++; pthread_mutex_unlock(&mutex); } soma += aux; pthread_exit(0); return 0; } int main(int argc, char *argv[]) { pthread_t tid_sistema[nthreads]; int t, vetorid[nthreads], numPrimos = 0; double inicio, fim, delta; if(argc < 3) { printf("Entre com os valores: %s <numero de elementos> <numero de threads>\\n", argv[0]); exit(1); } numMax = atoi(argv[1]); nthreads = atoi(argv[2]); GET_TIME(inicio); pthread_mutex_init(&mutex, 0); for(t = 0; t < nthreads; t++) { vetorid[t] = t; if (pthread_create(&tid_sistema[t], 0, quantidadePrimos, (void *) &vetorid[t])) { printf("--ERRO: pthread_create()\\n"); exit(-1); } } for (t = 0; t < nthreads; t++){ if (pthread_join(tid_sistema[t], 0)) { printf("--ERRO: pthread_join() \\n"); exit(-1); } } pthread_mutex_destroy(&mutex); numPrimos = soma; GET_TIME(fim); delta = fim - inicio; printf("Numero total de primos = %d\\n", numPrimos); printf("Tempo total de execucao: %.8lf\\n", delta); pthread_exit(0); return 0; }
0
#include <pthread.h> int **matrice = 0; int rows = 0, cols = 0; int x = 0; int contatore = 0; struct posizione{ int individuato; int riga; int colonna; }; struct posizione *trovati = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void *cerca(void *r){ int riga = *(int *)r; printf("T: %d R: %d\\n", (int)pthread_self(),riga); for(int i = 0; i < cols; i++){ pthread_mutex_lock(&mutex); if( matrice[riga][i] == x ){ contatore++; trovati[0].riga = riga; pthread_cond_signal(&cond); } pthread_mutex_unlock(&mutex); } pthread_exit(0); } void *aspetta(){ pthread_cond_wait(&cond, &mutex); printf("TA: %d\\n",(int)pthread_self()); printf("contatore = %d\\n", contatore); pthread_exit(0); } int main(int argc, char *argv[]){ if(argc < 3){ printf("USAGE: %s <m> <n> <x>\\n", argv[0]); return 1; } rows = atoi(argv[1]); cols = atoi(argv[2]); x = atoi(argv[3]); trovati = malloc(sizeof(struct posizione)); matrice = malloc( rows * sizeof(int *)); for(int row = 0; row < rows; row++){ matrice[row] = malloc(cols * sizeof(int)); for(int col = 0; col < cols; col++){ int valore = 1 + rand() % 5; matrice[row][col] = valore; } } for (int row = 0; row < rows ; row++) { for (int col = 0; col < cols; col++) { printf("%d \\t",matrice[row][col]); } printf("\\n"); } pthread_t *threads = malloc(1+rows * sizeof(pthread_t)); for (int i=0; i < rows; i++) { int *row=malloc(sizeof(int)); *row=i; pthread_create(&threads[i],0,cerca,row); } pthread_create(&threads[rows+1],0,aspetta,0); for (int i=0; i < rows+1; i++) { pthread_join(threads[i],0); } return 0; }
1
#include <pthread.h> static int fd = -1; static bool add_time = 0; static bool initial = 1; static pthread_mutex_t mutex; static char *trace; static int end; static int pos = 0; static bool wrapped = 0; void start_timed_trace() { add_time = 1; } void report(char *format, ...) { if (initial) { initial = 0; trace = (char *)malloc(0x40000000); end = 0x40000000; pthread_mutex_init(&mutex, 0); } pthread_mutex_lock(&mutex); if (pos >= end - 1024) { end = pos; pos = 0; wrapped = 1; } unsigned long long now; if (add_time) { now = Now(); pos += sprintf(&trace[pos], "%llu ", now); } va_list va; __builtin_va_start((va)); pos += vsprintf(&trace[pos], format, va); ; pthread_mutex_unlock(&mutex); } void display() { FILE *f = fopen("trace", "a"); int p, q; if (wrapped) { p = q = pos + 1; while (p < end) { p += printf("%s", &trace[p]); q += fprintf(f, "%s", &trace[q]); } } p = q = 0; while (p < pos) { p += printf("%s", &trace[p]); q += fprintf(f, "%s", &trace[q]); } fclose(f); pos = 0; end = 0x40000000; wrapped = 0; }
0
#include <pthread.h> void ptq_init(struct ptq *ptq, size_t q_size) { ptq->q_size = q_size; ptq->count = ptq->wr = ptq->rd = 0; pthread_mutexattr_t mutex_attr; pthread_mutexattr_init(&mutex_attr); pthread_mutex_init(&ptq->mutex, &mutex_attr); pthread_cond_init(&ptq->cond_full, 0); pthread_cond_init(&ptq->cond_empty, 0); } void ptq_enqueue(struct ptq *ptq, uintptr_t val) { pthread_mutex_lock(&ptq->mutex); while (ptq->count == ptq->q_size) pthread_cond_wait(&ptq->cond_full, &ptq->mutex); ptq->queue[ptq->wr] = val; ptq->wr = (ptq->wr + 1) % ptq->q_size; ptq->count++; if (ptq->count == 1) pthread_cond_signal(&ptq->cond_empty); pthread_mutex_unlock(&ptq->mutex); } void ptq_dequeue(struct ptq *ptq, uintptr_t *val) { pthread_mutex_lock(&ptq->mutex); while (ptq->count == 0) pthread_cond_wait(&ptq->cond_empty, &ptq->mutex); *val = ptq->queue[ptq->rd]; ptq->rd = (ptq->rd + 1) % ptq->q_size; ptq->count--; if (ptq->count == ptq->q_size - 1) pthread_cond_signal(&ptq->cond_full); pthread_mutex_unlock(&ptq->mutex); }
1
#include <pthread.h> unsigned int TEST_REG_RO[4] = { REG_MC34704_GENERAL3, REG_MC34704_FAULTS, REG_MC34704_REG4SET2, REG_MC34704_VGSET2, }; unsigned int TEST_REG_NA[3] = { 0x00, 0x20, 0x60, }; unsigned int TEST_EVNT_NA[1] = { EVENT_NB }; int TEST_VALUE = 0xFFF000; int VT_mc34704_IP_setup(void) { int rv = TFAIL; rv = TPASS; return rv; } int VT_mc34704_IP_cleanup(void) { int rv = TFAIL; rv = TPASS; return rv; } int VT_mc34704_test_IP(void) { int rv = TPASS, fd, i = 0; fd = open(MC34704_DEVICE, O_RDWR); if (fd < 0) { pthread_mutex_lock(&mutex); tst_resm(TFAIL, "Unable to open %s", MC34704_DEVICE); pthread_mutex_unlock(&mutex); return TFAIL; } for (i = 0; i < 4; i++) { if (VT_mc34704_opt (fd, CMD_WRITE, TEST_REG_RO[i], &TEST_VALUE) == TPASS) { pthread_mutex_lock(&mutex); printf ("Driver have wrote to Read Only reg %d\\n", TEST_REG_RO[i]); pthread_mutex_unlock(&mutex); rv = TFAIL; } } for (i = 0; i < 3; i++) { if (VT_mc34704_opt (fd, CMD_WRITE, TEST_REG_NA[i], &TEST_VALUE) == TPASS) { pthread_mutex_lock(&mutex); printf ("Driver have wrote to non avaible reg %d\\n", TEST_REG_NA[i]); pthread_mutex_unlock(&mutex); rv = TFAIL; } } for (i = 0; i < 3; i++) { if (VT_mc34704_opt (fd, CMD_READ, TEST_REG_NA[i], &TEST_VALUE) == TPASS) { pthread_mutex_lock(&mutex); printf ("Driver have read from non avaible reg %d\\n", TEST_REG_NA[i]); pthread_mutex_unlock(&mutex); rv = TFAIL; } } for (i = 0; i < 1; i++) { if (VT_mc34704_opt (fd, CMD_SUB, TEST_EVNT_NA[i], &TEST_VALUE) == TPASS) { pthread_mutex_lock(&mutex); printf ("Driver have subscribed non existing event %d\\n", TEST_EVNT_NA[i]); pthread_mutex_unlock(&mutex); rv = TFAIL; } } if (VT_mc34704_opt(fd, CMD_UNSUB, 2, &TEST_VALUE) == TPASS) { pthread_mutex_lock(&mutex); printf ("Driver have unsubscribed not subscribed event %d\\n", TEST_EVNT_NA[i]); pthread_mutex_unlock(&mutex); rv = TFAIL; } if (close(fd) < 0) { pthread_mutex_lock(&mutex); tst_resm(TFAIL, "Unable to close file descriptor %d", fd); pthread_mutex_unlock(&mutex); return TFAIL; } return rv; }
0
#include <pthread.h> struct threadParameter{ int* nbThreadTotal; int* nbThreadWaitingForSync; int doneCreating; pthread_mutex_t mut; }; void initThreadParameter(struct threadParameter* p){ p->nbThreadTotal=malloc(sizeof(int*)); *(p->nbThreadTotal)=0; p->nbThreadWaitingForSync=malloc(sizeof(int*)); *(p->nbThreadWaitingForSync)=0; p->doneCreating=0; pthread_mutex_init(&(p->mut),0); } void destroyThreadParameter(struct threadParameter* p){ free(p->nbThreadTotal); free(p->nbThreadWaitingForSync); } void* f(void*p){ struct threadParameter* c=(struct threadParameter*)p; while(!c->doneCreating){ sleep(1); } printf("I'm done working, i'm waiting for my slow brothers\\n"); pthread_mutex_lock(&(c->mut)); *(c->nbThreadWaitingForSync)+=1; pthread_mutex_unlock(&(c->mut)); while(*(c->nbThreadWaitingForSync)!=*(c->nbThreadTotal)){ sleep(1); } printf("I'm done working, gonna go sleep\\n"); pthread_exit(0); } int main(){ struct threadParameter* p=malloc(sizeof(struct threadParameter)); initThreadParameter(p); pthread_t idT[10]; for(size_t i=0;i<10;++i){ pthread_mutex_lock(&(p->mut)); if(pthread_create(&idT[i],0,f,(void*)p)){ fprintf(stderr,"failed creating a thread\\n"); return 1; } *(p->nbThreadTotal)+=1; pthread_mutex_unlock(&(p->mut)); } p->doneCreating=1; for(size_t i=0;i<10;++i){ pthread_join(idT[i],0); } destroyThreadParameter(p); free(p); return 0; }
1
#include <pthread.h> pthread_mutex_t chopstick[5]; void pickup(int me) { if (me == 0) { pthread_mutex_lock(&chopstick[((me + 1) % 5)]); pthread_mutex_lock(&chopstick[me]); } else { pthread_mutex_lock(&chopstick[me]); pthread_mutex_lock(&chopstick[((me + 1) % 5)]); } } void putdown(int me) { pthread_mutex_unlock(&chopstick[me]); pthread_mutex_unlock(&chopstick[((me + 1) % 5)]); } void *func(void *arg) { int i = (int)arg; srand(time(0)); while (1) { printf("philosopher %d thinking...\\n", i); usleep(rand() % 10); pickup(i); printf("philosopher %d eating...\\n", i); usleep(rand() % 10); putdown(i); } return 0; } int main(void) { int i; pthread_t tid[5]; for (i = 0; i < 5; i++) { pthread_mutex_init(&chopstick[i], 0); } for (i = 0; i < 5 - 1; i++) { pthread_create(&tid[i], 0, func, (void *)i); } func((void *)i); for (i = 0; i < 5 - 1; i++) { pthread_join(tid[i], 0); } return 0; }
0
#include <pthread.h> int a[20]; int b[20]; int c[20]; int array_index; int global_sum; int counter; pthread_mutex_t mutex; } sem_var_t; sem_var_t shared_variables; void *Producer(void *arg) { int index = (int) arg; while (shared_variables.array_index < 20 && shared_variables.global_sum < 200){ while(shared_variables.counter >= 1 && shared_variables.global_sum < 200); pthread_mutex_lock(&shared_variables.mutex); shared_variables.c[shared_variables.array_index] = shared_variables.a[shared_variables.array_index] + shared_variables.b[shared_variables.array_index]; shared_variables.global_sum += shared_variables.c[shared_variables.array_index]; printf("Producer %d has written c[%d] and updated global sum.\\n", index, shared_variables.array_index); shared_variables.array_index += 1; shared_variables.counter += 1; printf("Number of items available for consumer: %d\\n\\n", shared_variables.counter); pthread_mutex_unlock(&shared_variables.mutex); sleep(1); } return 0; } void *Consumer(void *arg) { int index = (int) arg; int i; for (i = 0; i < 20; i++) { while(shared_variables.counter <= 0 && shared_variables.global_sum < 200); pthread_mutex_lock(&shared_variables.mutex); printf("Consumer %d has read c[%d]= %d.\\n", index, i, shared_variables.c[i]); printf("Consumer %d has read global sum = %d\\n\\n", index, shared_variables.global_sum); shared_variables.counter -= 1; pthread_mutex_unlock(&shared_variables.mutex); sleep(1); if (shared_variables.global_sum >= 200){ printf("Consumer %d has read previously produced c[%d]= %d.\\n", index, i+1, shared_variables.c[i+1]); printf("Consumer %d has read global sum = %d\\n\\n", index, shared_variables.global_sum); break; } } return 0; } int main() { pthread_t idProducer, idConsumer; int index; for(int i = 0; i < 20; i++) { shared_variables.a[i] = i; } for(int i = 0; i < 20; i++) { shared_variables.b[i] = i+1; } for(int i = 0; i < 20; i++) { shared_variables.c[i] = 0; } shared_variables.array_index = 0; shared_variables.global_sum = 0; pthread_mutex_init(&shared_variables.mutex, 0); for (index = 0; index < 2; index++) { pthread_create(&idProducer, 0, Producer, (void*)index); } for(index=0; index<1; index++) { pthread_create(&idConsumer, 0, Consumer, (void*)index); } pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t thread_cond = PTHREAD_COND_INITIALIZER; struct com_data { int a; int b; }; struct com_data mydata; void *do_write(void *data) { mydata.a = 0; mydata.b = 0; while(1) { pthread_mutex_lock(&mutex_lock); mydata.a = random() % 6000; mydata.b = random() % 6000; pthread_cond_signal(&thread_cond); pthread_mutex_unlock(&mutex_lock); sleep(2); } } void *do_read(void *data) { while(1) { pthread_mutex_lock(&mutex_lock); pthread_cond_wait(&thread_cond, &mutex_lock); printf("%d + %d = %d\\n", mydata.a, mydata.b, mydata.a + mydata.b); pthread_mutex_unlock(&mutex_lock); } } int main() { pthread_t p_thread[2]; int thr_id; int status; int a = 1; int b = 2; thr_id = pthread_create(&p_thread[0], 0, do_write, (void *)&a); thr_id = pthread_create(&p_thread[1], 0, do_read, (void *)&b); pthread_join(p_thread[0], (void **) status); pthread_join(p_thread[1], (void **) status); return 0; }
0
#include <pthread.h> void *thread_function(void *arg); pthread_mutex_t work_mutex; struct work_struct{ int readcount; int lastreadby; char work_area[1024]; }; struct work_struct ws; int time_to_exit = 0; int main() { int res; pthread_t a_thread; pthread_t a_thread1; void *thread_result; int thread_ids[] = {1,2}; res = pthread_mutex_init(&work_mutex, 0); if(res != 0){ perror("Mutex Initialization failed"); exit(1); } res = pthread_create(&a_thread, 0, thread_function, &thread_ids[0]); if(res != 0){ perror("Thread creation failed"); exit(1); } res = pthread_create(&a_thread1, 0, thread_function, &thread_ids[1]); if(res != 0){ perror("Thread creation failed"); exit(1); } pthread_mutex_lock(&work_mutex); while(!time_to_exit){ printf("Input some text. Enter 'end' to finish\\n"); fgets(ws.work_area, 1024, stdin); ws.readcount = 0; ws.lastreadby = 0; pthread_mutex_unlock(&work_mutex); while(1){ pthread_mutex_lock(&work_mutex); if(ws.readcount < 2){ pthread_mutex_unlock(&work_mutex); sleep(3); } else{ break; } } } pthread_mutex_unlock(&work_mutex); printf("\\nWaiting for thread to finish...\\n"); res = pthread_join(a_thread, &thread_result); if(res != 0){ perror("Thread join failed"); exit(1); } res = pthread_join(a_thread1, &thread_result); if(res != 0){ perror("Thread join failed"); exit(1); } printf("Thread joined\\n"); pthread_mutex_destroy(&work_mutex); exit(0); } void *thread_function(void *arg) { int myid = *(int *)arg; sleep(1); pthread_mutex_lock(&work_mutex); while(1){ printf("You input %d characters\\n", strlen(ws.work_area) -1); ws.readcount++; ws.lastreadby = myid; if(strncmp("end", ws.work_area, 3) == 0) break; while(ws.lastreadby >= myid){ pthread_mutex_unlock(&work_mutex); printf("Sleeping...%d\\n", myid); sleep(1); pthread_mutex_lock(&work_mutex); } } time_to_exit = 1; pthread_mutex_unlock(&work_mutex); printf("child thread exit\\n"); pthread_exit(0); }
1
#include <pthread.h> int global_value = 0; pthread_mutex_t global_value_mutex; void *writer(void *arg); void *reader(void *arg); int main(int argc, char **argv) { pthread_mutexattr_t mutexattr; pthread_mutexattr_init(&mutexattr); pthread_mutex_init(&global_value_mutex, &mutexattr); pthread_mutexattr_destroy(&mutexattr); pthread_t t1, t2; int rc; rc = pthread_create(&t1, 0, writer, 0); if (rc != 0) { fprintf(stderr, "Failed to create writer thread: %s\\n", strerror(rc)); } rc = pthread_create(&t2, 0, reader, 0); if (rc != 0) { fprintf(stderr, "Failed to create reader thread: %s\\n", strerror(rc)); } pthread_join(t1, 0); pthread_join(t2, 0); pthread_mutex_destroy(&global_value_mutex); pthread_exit((void *) 0); } void *writer(void *arg) { for (;;) { pthread_mutex_lock(&global_value_mutex); global_value++; pthread_mutex_unlock(&global_value_mutex); sleep(1); } pthread_exit((void *) 0); } void *reader(void *arg) { for (;;) { pthread_mutex_lock(&global_value_mutex); fprintf(stdout, "global_value = %d\\n", global_value); pthread_mutex_unlock(&global_value_mutex); sleep(1); } pthread_exit((void *) 0); }
0
#include <pthread.h> int VAGAS = 4; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t baia = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t chefe_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t lotou = PTHREAD_COND_INITIALIZER; pthread_cond_t acorda_chefe = PTHREAD_COND_INITIALIZER; int contador = 0; int contador_servidores = 0; int contador_estagiarios = 0; int chama_chefe = 0; char matriz [20][20]; int baias[5][2]; int baias_ocupadas[5] = {0}; void inicializa_baias(){ baias[0][0] = 5; baias[0][1] = 19; baias[1][0] = 8; baias[1][1] = 19; baias[2][0] = 11; baias[2][1] = 19; baias[3][0] = 14; baias[3][1] = 19; } void sai_da_baia(int num_baia, int i){ int linha = baias[num_baia][0]; int coluna = baias[num_baia][1]; matriz[linha][coluna - 1] = '_'; matriz[linha+1][coluna - 1] = '0' + i; sleep(1); matriz[linha+1][coluna - 1] = '_'; matriz[linha+1][coluna] = '0' + i; sleep(1); matriz[linha+1][coluna] = '_'; } void mostra_que_quer_entrar(){ pthread_mutex_lock(&mutex); contador++; pthread_mutex_unlock(&mutex); } int servidor_trabalha(int i){ pthread_mutex_lock(&baia); int num_baia; for(int k = 0; k <= VAGAS; k++) { if(baias_ocupadas[k] == 0){ baias_ocupadas[k] = 1; num_baia = k; break; } } pthread_mutex_unlock(&baia); int linha_baia = baias[num_baia][0]; int coluna_baia = baias[num_baia][1]; for (int k = 1; k <= linha_baia; k++) { matriz[k-1][i] = '_'; matriz[k][i] = '0' + i; sleep(1); } for (int k = i; k < coluna_baia; k++) { matriz[linha_baia][k-1] = '_'; matriz[linha_baia][k] = '0' + i; sleep(1); } sleep(10); return num_baia; } void servidor_vai_para_casa(int i, int num_baia){ pthread_mutex_lock(&mutex); pthread_mutex_lock(&baia); baias_ocupadas[num_baia] = 0; pthread_mutex_unlock(&baia); pthread_cond_broadcast(&lotou); contador--; pthread_mutex_unlock(&mutex); sai_da_baia(num_baia, i); sleep(5); } void servidor_fica_esperando(int i){ pthread_mutex_lock(&mutex); contador_servidores++; contador--; pthread_mutex_lock(&chefe_mutex); if(!chama_chefe){ sleep(5); chama_chefe = 1; pthread_cond_signal(&acorda_chefe); } pthread_mutex_unlock(&chefe_mutex); while(contador >= VAGAS){ pthread_cond_wait(&lotou, &mutex); } contador_servidores--; pthread_mutex_unlock(&mutex); } void* servidor(void * a){ int i = *((int *) a); while(1){ matriz[1][i]='S'; mostra_que_quer_entrar(); if(contador<=VAGAS){ int baia = servidor_trabalha(i); servidor_vai_para_casa(i, baia); break; }else{ servidor_fica_esperando(i); } } } void* estagiario(void* a){ int i = *((int *) a); while(1){ matriz[0][i]='E'; if(contador <= VAGAS && contador_servidores == 0){ pthread_mutex_lock(&mutex); contador++; pthread_mutex_unlock(&mutex); pthread_mutex_lock(&baia); int num_baia; for(int k = 0; k <= VAGAS; k++) { if(baias_ocupadas[k] == 0){ baias_ocupadas[k] = 1; num_baia = k; break; } } pthread_mutex_unlock(&baia); int linha_baia = baias[num_baia][0]; int coluna_baia = baias[num_baia][1]; for (int k = 1; k <= linha_baia; k++){ matriz[k-1][i] = '_'; matriz[k][i] = '0' + i; sleep(1); } for (int k = i; k < coluna_baia; k++){ matriz[linha_baia][k-1] = '_'; matriz[linha_baia][k] = '0' + i; sleep(1); } sleep(20); pthread_mutex_lock(&mutex); contador--; pthread_mutex_unlock(&mutex); pthread_mutex_lock(&baia); baias_ocupadas[num_baia] = 0; pthread_mutex_unlock(&baia); sai_da_baia(num_baia, i); break; } pthread_mutex_lock(&mutex); while(contador >= VAGAS || contador_servidores > 0){ pthread_cond_wait(&lotou, &mutex); } pthread_mutex_unlock(&mutex); } } void* chefe_vai_ao_almoxarifado(void* a){ int i = *((int *) a); matriz[i][15] = 'C'; pthread_mutex_lock(&chefe_mutex); while(!chama_chefe){ pthread_cond_wait(&acorda_chefe, &chefe_mutex); } pthread_mutex_unlock(&chefe_mutex); sleep(10); pthread_mutex_lock(&baia); matriz[17][19] = 'B'; baias[4][0] = 17; baias[4][1] = 19; baias_ocupadas[5] = 0; VAGAS++; pthread_cond_broadcast(&lotou); pthread_mutex_unlock(&baia); } void preenche_matriz(){ for (int i = 0; i < 20; i++){ for (int j = 0; j < 20; j++){ matriz[i][j]='_'; matriz[5][19]='B'; matriz[8][19]='B'; matriz[11][19]='B'; matriz[14][19]='B'; } } } void* imprime(){ while(1){ for (int i = 0; i < 20; i++){ for (int j = 0; j < 20; j++){ printf("%c",matriz[i][j]); } printf("\\n"); } sleep(1); system("clear"); } } int main(){ pthread_t s[100]; pthread_t e[100]; pthread_t matriz; pthread_t chefe; int i; int *id; preenche_matriz(); inicializa_baias(); id = (int *) malloc(sizeof(int)); *id = i; pthread_create(&chefe, 0, chefe_vai_ao_almoxarifado, (void *) (id)); id = (int *) malloc(sizeof(int)); *id = i; pthread_create(&matriz, 0, imprime, (void *) (id)); for (i = 0; i < 6 ; i++) { id = (int *) malloc(sizeof(int)); *id = i; pthread_create(&s[i], 0, servidor, (void *) (id)); } for (i = 0; i < 3 ; i++) { id = (int *) malloc(sizeof(int)); *id = i; pthread_create(&e[i], 0, estagiario, (void *) (id)); } int num_threads = 6; while(1){ time_t t; srand((unsigned) time(&t)); int random = rand() % 2; if(random == 0){ id = (int *) malloc(sizeof(int)); *id = num_threads; pthread_create(&s[num_threads], 0, servidor, (void *) (id)); }else{ id = (int *) malloc(sizeof(int)); *id = num_threads; pthread_create(&e[num_threads], 0, estagiario, (void *) (id)); } num_threads++; sleep(30); } for (i = 0; i < 6 ; i++) { pthread_join(s[i],0); } for (i = 0; i < 3 ; i++) { pthread_join(e[i],0); } pthread_join(matriz,0); pthread_join(chefe,0); return 0; }
1
#include <pthread.h> void *fun1(void *); void *fun2(void *); struct tag { int shared_data; pthread_mutex_t mutex; pthread_cond_t cond1; pthread_cond_t cond2; } abc = {0,PTHREAD_MUTEX_INITIALIZER,PTHREAD_COND_INITIALIZER,PTHREAD_COND_INITIALIZER}; int main (void) { pthread_t thread1; pthread_t thread2; int status; status = pthread_create (&thread1, 0, fun1, 0); if (status != 0) { exit (1); } status = pthread_create (&thread2, 0, fun2, 0); if (status != 0) { exit (1); } pthread_exit (0); return 0; } void *fun1 (void *t) { while (1) { pthread_mutex_lock (&abc.mutex); if ((abc.shared_data % 2) == 0) { pthread_cond_signal ( &abc.cond2); pthread_cond_wait (&abc.cond1, &abc.mutex); } sleep(1); printf ("odd == %d\\n", abc.shared_data); (abc.shared_data)++; pthread_mutex_unlock (&abc.mutex); } } void *fun2 (void *t) { while (1) { pthread_mutex_lock (&abc.mutex); if ((abc.shared_data % 2) == 1) { pthread_cond_signal ( &abc.cond1); pthread_cond_wait (&abc.cond2, &abc.mutex); } sleep(1); printf ("even == %d\\n", abc.shared_data); (abc.shared_data)++; pthread_mutex_unlock (&abc.mutex); } }
0
#include <pthread.h> enum { SWITCH_ON, SWITCH_OFF, GET_STATUS }; struct command { uint8_t code; unsigned lamp; }; struct switch_answ { uint8_t code; }; struct status_data { unsigned lamps[LAMPS]; }; static struct { unsigned lamps[LAMPS]; pthread_mutex_t mutex; struct tcp_server server; } hlight; static void new_session(struct tcp_client *client, void *data) { struct command cmd; const struct lamp_cfg *lc = configs_get_lamps(); if(!tcp_client_recv(client, (void *)&cmd, sizeof(struct command))) { pthread_mutex_lock(&hlight.mutex); log_local("Fail reading client command", LOG_ERROR); pthread_mutex_unlock(&hlight.mutex); return; } switch (cmd.code) { case SWITCH_ON: { pthread_mutex_lock(&hlight.mutex); digitalWrite(lc->lamps[cmd.lamp], LOW); hlight.lamps[cmd.lamp] = 1; pthread_mutex_unlock(&hlight.mutex); break; } case SWITCH_OFF: { pthread_mutex_lock(&hlight.mutex); digitalWrite(lc->lamps[cmd.lamp], HIGH); hlight.lamps[cmd.lamp] = 0; pthread_mutex_unlock(&hlight.mutex); break; } case GET_STATUS: { struct status_data sdata; pthread_mutex_lock(&hlight.mutex); printf("New status getting:"); for (uint8_t i = 0; i < LAMPS; i++) { sdata.lamps[i] = hlight.lamps[i]; printf("L%hhu=%u ", i, hlight.lamps[i]); } printf("\\n"); pthread_mutex_unlock(&hlight.mutex); if (!tcp_client_send(client, (const void *)&sdata, sizeof(struct status_data))) { pthread_mutex_lock(&hlight.mutex); log_local("Fail receiving status data", LOG_ERROR); pthread_mutex_unlock(&hlight.mutex); return; } break; } } } static void accept_error(void *data) { pthread_mutex_lock(&hlight.mutex); log_local("Fail accepting new client", LOG_ERROR); pthread_mutex_lock(&hlight.mutex); } bool hlight_start(void) { const struct server_cfg *sc = configs_get_server(); const struct lamp_cfg *lc = configs_get_lamps(); puts("Starting home light server..."); pthread_mutex_init(&hlight.mutex, 0); for (size_t i = 0; i < LAMPS; i++) { hlight.lamps[i] = 0; pinMode(lc->lamps[i], OUTPUT); digitalWrite(lc->lamps[i], HIGH); } tcp_server_set_newsession_cb(&hlight.server, new_session, 0); tcp_server_set_accepterr_cb(&hlight.server, accept_error, 0); if (!tcp_server_bind(&hlight.server, sc->port, sc->max_users)) { log_local("Fail starting HomeLight server", LOG_ERROR); return 0; } pthread_mutex_destroy(&hlight.mutex); return 1; }
1
#include <pthread.h> { double *a; double *b; double sum; int veclen; } DOTDATA; DOTDATA dotstr; pthread_t callThd[4]; pthread_mutex_t mutexsum; void *dotprod(void *arg) { int i, start, end, len ; long offset; double mysum, *x, *y; offset = (long)arg; len = dotstr.veclen; start = offset*len; end = start + len; x = dotstr.a; y = dotstr.b; mysum = 0; for (i=start; i<end ; i++) { mysum += (x[i] * y[i]); } pthread_mutex_lock (&mutexsum); dotstr.sum += mysum; printf("Thread %ld did %d to %d: mysum=%f global sum=%f\\n",offset,start,end,mysum,dotstr.sum); pthread_mutex_unlock (&mutexsum); pthread_exit((void*) 0); } int main (int argc, char *argv[]) { long i; double *a, *b; void *status; pthread_attr_t attr; a = (double*) malloc (4*100000*sizeof(double)); b = (double*) malloc (4*100000*sizeof(double)); for (i=0; i<100000*4; i++) { a[i]=1; b[i]=a[i]; } dotstr.veclen = 100000; dotstr.a = a; dotstr.b = b; dotstr.sum=0; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0;i<4;i++) { pthread_create(&callThd[i], &attr, dotprod, (void *)i); } pthread_attr_destroy(&attr); for(i=0;i<4;i++) { pthread_join(callThd[i], &status); } printf ("Sum = %f \\n", dotstr.sum); free (a); free (b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
0
#include <pthread.h> char *sieve; long sieve_size; pthread_mutex_t mutex; long next; long get_next() { long res; pthread_mutex_lock(&mutex); while (sieve[next]) { next++; } res = next; next++; pthread_mutex_unlock(&mutex); return res; } void* sieve_worker(void *thread_id) { long id; long i, j; id = (long) thread_id; for (i = get_next(); i < sqrt(sieve_size); i = get_next()) { if (sieve[i]) { continue; } for (j = 2 * i; j < sieve_size; j += i) { sieve[j] = 1; } } } void sieve_init(long size) { long id; int status; pthread_t threads[2]; pthread_mutex_init(&mutex, 0); next = 2; sieve_size = size + 1; sieve = (char*) malloc(sieve_size); memset(sieve, 0, sieve_size); for (id = 0; id < 2; id++) { status = pthread_create(&threads[id], 0, sieve_worker, (void*) id); if (status) { fprintf(stderr, "error %d in pthread_create\\n", status); } } for (id = 0; id < 2; id++) { pthread_join(threads[id], 0); } } void sieve_free() { free(sieve); } int sieve_is_prime(long n) { return !sieve[n]; } int main() { sieve_init(100); assert(sieve_is_prime(1)); assert(sieve_is_prime(2)); assert(sieve_is_prime(3)); assert(sieve_is_prime(5)); assert(sieve_is_prime(7)); assert(sieve_is_prime(23)); assert(sieve_is_prime(41)); assert(sieve_is_prime(97)); assert(!sieve_is_prime(4)); assert(!sieve_is_prime(6)); assert(!sieve_is_prime(8)); assert(!sieve_is_prime(25)); assert(!sieve_is_prime(100)); return 0; }
1
#include <pthread.h> struct propset { char *str; int row; int delay; int dir; }; pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER; int main(int ac, char *av[]) { int c; pthread_t thrds[10]; struct propset props[10]; void *animate(); int num_msg ; int i; if ( ac == 1 ){ printf("usage: tanimate string ..\\n"); exit(1); } num_msg = setup(ac-1,av+1,props); for(i=0 ; i<num_msg; i++) if ( pthread_create(&thrds[i], 0, animate, &props[i])){ fprintf(stderr,"error creating thread"); endwin(); exit(0); } while(1) { c = getch(); if ( c == 'Q' ) break; if ( c == ' ' ) for(i=0;i<num_msg;i++) props[i].dir = -props[i].dir; if ( c >= '0' && c <= '9' ){ i = c - '0'; if ( i < num_msg ) props[i].dir = -props[i].dir; } } pthread_mutex_lock(&mx); for (i=0; i<num_msg; i++ ) pthread_cancel(thrds[i]); endwin(); return 0; } int setup(int nstrings, char *strings[], struct propset props[]) { int num_msg = ( nstrings > 10 ? 10 : nstrings ); int i; srand(getpid()); for(i=0 ; i<num_msg; i++){ props[i].str = strings[i]; props[i].row = i; props[i].delay = 1+(rand()%15); props[i].dir = ((rand()%2)?1:-1); } initscr(); crmode(); noecho(); clear(); mvprintw(LINES-1,0,"'Q' to quit, '0'..'%d' to bounce",num_msg-1); return num_msg; } void *animate(void *arg) { struct propset *info = arg; int len = strlen(info->str)+2; int col = rand()%(COLS-len-3); while( 1 ) { usleep(info->delay*20000); pthread_mutex_lock(&mx); move( info->row, col ); addch(' '); addstr( info->str ); addch(' '); move(LINES-1,COLS-1); refresh(); pthread_mutex_unlock(&mx); col += info->dir; if ( col <= 0 && info->dir == -1 ) info->dir = 1; else if ( col+len >= COLS && info->dir == 1 ) info->dir = -1; } }
0
#include <pthread.h> int N; int count = 0; pthread_mutex_t mcount = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t minterrupt = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cinterrupt = PTHREAD_COND_INITIALIZER; pthread_cond_t ccreation = PTHREAD_COND_INITIALIZER; pthread_cond_t ctermination = PTHREAD_COND_INITIALIZER; void handler(int signal); void *thread(void*); int main(int argc, char *argv[]) { sigset_t mask; sigfillset(&mask); sigprocmask(SIG_SETMASK, &mask, 0); struct sigaction action; action.sa_handler = &handler; sigaction(SIGINT, &action, 0); N = atoi(argv[1]); pthread_t tid; count += 1; pthread_create(&tid, 0, &thread, 0); pthread_mutex_lock(&mcount); if (count != N) { pthread_cond_wait(&ccreation, &mcount); } pthread_mutex_unlock(&mcount); printf("all descendants created\\n"); printf("please signal me\\n"); sigemptyset(&mask); sigsuspend(&mask); pthread_mutex_lock(&minterrupt); pthread_cond_broadcast(&cinterrupt); pthread_mutex_unlock(&minterrupt); pthread_mutex_lock(&mcount); if (count != 0) { pthread_cond_wait(&ctermination, &mcount); } pthread_mutex_unlock(&mcount); printf("all descendants terminated\\n"); return 0; } void handler(int signal) { return; } void *thread(void *pointer) { printf("thread created\\n"); pthread_mutex_lock(&mcount); if (count != N) { pthread_t tid; pthread_create(&tid, 0, &thread, 0); count++; } else { pthread_cond_signal(&ccreation); } pthread_mutex_unlock(&mcount); pthread_mutex_lock(&minterrupt); pthread_cond_wait(&cinterrupt, &minterrupt); pthread_mutex_unlock(&minterrupt); pthread_mutex_lock(&mcount); count--; printf("thread terminated\\n"); if (count == 0) { pthread_cond_signal(&ctermination); } pthread_mutex_unlock(&mcount); return 0; }
1
#include <pthread.h> volatile long double area = 0.0; pthread_mutex_t piLock; long double intervals; int numThreads; void *computeArea(void *id) { long double x, width, localSum = 0; int i, threadID = *((int*)id); width = 360.0/ intervals; for(i = threadID ; i < intervals; i += numThreads) { x = (i * width); localSum += sin(x); } localSum *= width; pthread_mutex_lock(&piLock); area += localSum; pthread_mutex_unlock(&piLock); printf ("I am thread number :%d My area is %Lf \\n",threadID ,localSum); return 0; } int main(int argc, char **argv) { pthread_t *threads; void *retval; int *threadID; int i; if (argc == 3) { intervals = atoi(argv[1]); numThreads = atoi(argv[2]); threads = malloc(numThreads*sizeof(pthread_t)); threadID = malloc(numThreads*sizeof(int)); pthread_mutex_init(&piLock, 0); for (i = 0; i < numThreads; i++) { threadID[i] = i; pthread_create(&threads[i], 0, computeArea, threadID+i); } for (i = 0; i < numThreads; i++) { pthread_join(threads[i], &retval); } printf("Estimation of the area under the curve is %Lf \\n", area); } else { printf("Usage: ./a.out <numIntervals> <numThreads> \\n"); } return 0; }
0
#include <pthread.h> pthread_cond_t cond; pthread_mutex_t mutex; void* p_func(void* p) { pthread_mutex_lock(&mutex); int ret; printf(" i am child ,this is wait entrance\\n" ); ret=pthread_cond_wait(&cond,&mutex); if(0!=ret) { printf("pthread_cond_wait ret is %d\\n" ,ret); } printf(" i am child thread,i am wake\\n" ); pthread_mutex_unlock(&mutex); pthread_exit( 0); } int main( ) { int ret; ret=pthread_cond_init(&cond,0); if( 0!=ret) { printf("pthread_cond_init ret is %d\\n" ,ret); return -1; } ret=pthread_mutex_init(&mutex,0); if( 0!=ret) { printf("pthread_mutex_init ret is %d\\n" ,ret); return -1; } pthread_t thid; pthread_create( &thid,0,p_func,0); sleep( 1); pthread_mutex_lock(&mutex); printf("i am father thread,i can lock\\n" ); pthread_mutex_unlock( &mutex); pthread_cond_signal( &cond); ret=pthread_join(thid,0); if( 0!=ret) { printf("pthread_join ret is %d\\n" ,ret); return -1; } ret=pthread_cond_destroy(&cond); if( 0!=ret) { printf("pthread_cond_destroy ret is %d\\n" ,ret); return -1; } ret=pthread_mutex_destroy(&mutex); if( 0!=ret) { printf("pthread_mutex_destroy ret is %d\\n" ,ret); return -1; } return 0; }
1
#include <pthread.h> void *find_words(void*); int map_reduce(int number_threads, char *string, struct list *list); int main(void) { char *string; int cur_time, i, j; struct list *list; struct stat *buf; buf = (struct stat *) malloc(sizeof(struct stat)); stat("./Don_Quixote.txt", buf); int fd = open("./Don_Quixote.txt", O_RDONLY); string = (char *)malloc(sizeof(char) * buf->st_size); read(fd, string, buf->st_size); list = (struct list *)malloc(sizeof(struct list)); for(j = 2; j < 4; ++j) { list_init(list); cur_time = clock(); map_reduce(j, string, list); cur_time = clock() - cur_time; printf("%d\\n\\n", cur_time); for(i = 0; i < list->current_length; ++i) free(list->head[i]); list_destroy(list); } free(string); free(list); exit(0); } int is_separator(char *simbol, char *separators) { while(*separators != 0) { if(*simbol == *separators) return 1; ++separators; } return 0; } void *find_words(void *arg) { struct list *list; char *begin, *end; char *new_begin, *new_str; int i, is_unique; void **pointer; pointer = (void **)arg; list = (struct list *)(pointer[0]); begin = (char *)(pointer[1]); end = (char *)(pointer[2]); while(begin != end) { while(begin <= end && is_separator(begin, " ,.?!")) ++begin; if(begin > end) return 0; new_begin = begin; while(new_begin <= end && !is_separator(new_begin, " ,.?!")) ++new_begin; --new_begin; pthread_mutex_lock(list->mutex); is_unique = 0; for(i = 0; i < list->current_length; ++i) { if(strncmp(list->head[i], begin, new_begin - begin + 1) == 0) { is_unique = 1; break; } } if(is_unique == 0) { new_str = (char *)malloc(sizeof(char) * (new_begin - begin + 2)); memcpy(new_str, begin, new_begin - begin + 1); new_str[new_begin - begin + 1] = '\\0'; list_add(list, new_str); } pthread_mutex_unlock(list->mutex); usleep(1000); begin = new_begin + 1; } pthread_exit(0); } int map_reduce(int number_threads, char *string, struct list *list) { int length, delta_length, i, begin_offset, end_offset, cur_pthread; void ***arg; pthread_t *pthreads; pthreads = (pthread_t *)malloc(sizeof(pthread_t)*number_threads); arg = (void ***)malloc(sizeof(void *) * number_threads); length = strlen(string); delta_length = length / number_threads; begin_offset = 0; cur_pthread = 0; for(i = 0; i < number_threads; ++i) { if(i == number_threads - 1) end_offset = length; else { end_offset = delta_length * (i + 1); while(end_offset >= begin_offset && !is_separator(string + end_offset, " ,.?!")) --end_offset; } if(end_offset >= begin_offset) { arg[cur_pthread] = (void **)malloc(sizeof(void *) * 3); arg[cur_pthread][0] = list; arg[cur_pthread][1] = string + begin_offset; arg[cur_pthread][2] = string + end_offset - 1; pthread_create((pthreads + cur_pthread), 0, find_words, (void*)(arg[cur_pthread])); ++cur_pthread; } begin_offset = end_offset; } for(i = 0; i < cur_pthread; ++i) { pthread_join(pthreads[i], 0); free(arg[i]); } free(pthreads); free(arg); return 0; }
0
#include <pthread.h> pthread_mutex_t fork_mutex[5]; pthread_mutex_t eat_mutex; main() { int i; pthread_t diner_thread[5]; int dn[5]; void *diner(); pthread_mutex_init(&eat_mutex, 0); for (i=0;i<5;i++) pthread_mutex_init(&fork_mutex[i], 0); for (i=0;i<5;i++){ dn[i] = i; pthread_create(&diner_thread[i],0,diner,&dn[i]); } for (i=0;i<5;i++) pthread_join(diner_thread[i],0); pthread_exit(0); } void *diner(int *i) { int v; int eating = 0; printf("I'm diner %d\\n",*i); v = *i; while (eating < 5) { printf("%d is thinking\\n", v); sleep( v/2); printf("%d is hungry\\n", v); pthread_mutex_lock(&eat_mutex); pthread_mutex_lock(&fork_mutex[v]); pthread_mutex_lock(&fork_mutex[(v+1)%5]); pthread_mutex_unlock(&eat_mutex); printf("%d is eating\\n", v); eating++; sleep(1); printf("%d is done eating\\n", v); pthread_mutex_unlock(&fork_mutex[v]); pthread_mutex_unlock(&fork_mutex[(v+1)%5]); } pthread_exit(0); }
1
#include <pthread.h> extern int klee_make_symbolic(void* array, size_t size, const char* name); pthread_mutex_t cs0, cs1; int globalX = 0; int globalY = 0; void print_safe() { printf("-------- safe\\n"); } void print_deadlock() { printf("------------- could deadlock\\n"); } void * work0 (void *arg) { pthread_mutex_lock (&cs0); printf("work0: got lock 0\\n"); globalX++; pthread_mutex_lock (&cs1); printf("work0: got lock 1\\n"); globalY++; pthread_mutex_unlock (&cs1); printf("work0: released lock 1\\n"); pthread_mutex_unlock (&cs0); printf("work0: released lock 0\\n"); return 0; } void * work1 (void *arg) { int r; klee_make_symbolic(&r, sizeof(r), "r"); printf("r is now symbolic\\n"); if(r) { pthread_mutex_lock (&cs0); globalX++; pthread_mutex_lock (&cs1); print_safe(); globalY++; } else { pthread_mutex_lock (&cs1); printf("work1: got lock 1\\n"); print_deadlock(); globalX++; pthread_mutex_lock (&cs0); printf("work1: got lock 0\\n"); globalY++; } if(r) { pthread_mutex_unlock (&cs1); print_safe(); pthread_mutex_unlock (&cs0); } else { pthread_mutex_unlock (&cs0); printf("work1: released lock 0\\n"); print_deadlock(); pthread_mutex_unlock (&cs1); printf("work1: released lock 1\\n"); } return 0; } int main (int argc, char *argv[]) { pthread_t t0, t1; int rc; srand(time(0)); if(argc != 1) return 1; pthread_mutex_init (&cs0, 0); pthread_mutex_init (&cs1, 0); printf ("START\\n"); printf("t0 = %u \\n", (unsigned int) t0); rc = pthread_create (&t0, 0, work0, 0); printf("t0 = %u \\n", (unsigned int) t0); rc = pthread_create (&t1, 0, work1, 0); pthread_join(t0, 0); pthread_join(t1, 0); printf ("TOTAL = (%d,%d)\\n", globalX, globalY); printf ("STOP\\n"); return 0; }
0
#include <pthread.h> char buff[30]; pthread_mutex_t mt; void* clnt_handling(void* param) { int str_len; int clnt_sock=*((int*)param); pthread_mutex_lock(&mt); while(1) { str_len=read(clnt_sock,buff,30); if(str_len<=0) break; write(clnt_sock,buff,str_len); } pthread_mutex_unlock(&mt); } int main(int argc,char* argv[]) { int serv_sock,clnt_sock; struct sockaddr_in serv_addr,clnt_addr; int clnt_addr_sz; pthread_t tid; pthread_mutex_init(&mt,0); if(argc!=2) { printf("Usage %s <port>\\n",argv[0]); exit(1); } serv_sock=socket(AF_INET,SOCK_STREAM,0); memset(&serv_addr,0,sizeof(serv_addr)); serv_addr.sin_family=AF_INET; serv_addr.sin_addr.s_addr=htonl(INADDR_ANY); serv_addr.sin_port=htons(atoi(argv[1])); bind(serv_sock,(struct sockaddr*)&serv_addr,sizeof(serv_addr)); listen(serv_sock,5); while(1) { clnt_sock=accept(serv_sock,(struct sockaddr*)&clnt_addr,&clnt_addr_sz); pthread_create(&tid,0,clnt_handling,(void*)&clnt_sock); pthread_detach(tid); } pthread_mutex_destroy(&mt); close(serv_sock); return 0; }
1
#include <pthread.h> char *pbs_locjob_err( int c, char *jobid, char *extend, int *local_errno) { int rc; struct batch_reply *reply; char *ploc = (char *)0; int sock; struct tcp_chan *chan = 0; if ((jobid == (char *)0) || (*jobid == '\\0')) { *local_errno = PBSE_IVALREQ; return(0); } pthread_mutex_lock(connection[c].ch_mutex); sock = connection[c].ch_socket; if ((chan = DIS_tcp_setup(sock)) == 0) { pthread_mutex_unlock(connection[c].ch_mutex); return 0; } else if ((rc = encode_DIS_ReqHdr(chan, PBS_BATCH_LocateJob, pbs_current_user)) || (rc = encode_DIS_JobId(chan, jobid)) || (rc = encode_DIS_ReqExtend(chan, extend))) { connection[c].ch_errtxt = strdup(dis_emsg[rc]); pthread_mutex_unlock(connection[c].ch_mutex); *local_errno = PBSE_PROTOCOL; DIS_tcp_cleanup(chan); return(0); } if (DIS_tcp_wflush(chan)) { pthread_mutex_unlock(connection[c].ch_mutex); *local_errno = PBSE_PROTOCOL; DIS_tcp_cleanup(chan); return(0); } reply = PBSD_rdrpy(local_errno,c); if (reply == 0) { *local_errno = PBSE_PROTOCOL; } else if (reply->brp_choice != BATCH_REPLY_CHOICE_NULL && reply->brp_choice != BATCH_REPLY_CHOICE_Text && reply->brp_choice != BATCH_REPLY_CHOICE_Locate) { fprintf(stderr, "advise: pbs_locjob\\tUnexpected reply choice\\n\\n"); *local_errno = PBSE_PROTOCOL; } else if (connection[c].ch_errno == 0) { ploc = strdup(reply->brp_un.brp_locate); } PBSD_FreeReply(reply); pthread_mutex_unlock(connection[c].ch_mutex); DIS_tcp_cleanup(chan); return(ploc); } char *pbs_locjob( int c, char *jobid, char *extend) { pbs_errno = 0; return(pbs_locjob_err(c, jobid, extend, &pbs_errno)); }
0
#include <pthread.h> void * adder(void *); pthread_mutex_t m; pthread_t tid[2]; int bignum = 0; main( int argc, char *argv[] ) { int i, ret; for (i=0; i<2; i++) { pthread_create(&tid[i], 0, adder, (void *)i); pthread_join(tid[1], 0); } pthread_join(tid[0], 0); printf("main() reporting that all %d threads have terminated\\n", i); printf("I am main! bignum=%d\\n", bignum); } void * adder(void * parm) { int i=0,j=0; pthread_mutex_lock(&m); printf("I am a new thread!\\t %d\\n ",(int *)parm); for(i=0;i<5;i++) { j = bignum; j++; bignum =j; printf("big number = %d in Thread %lx\\n",bignum,pthread_self()); } pthread_mutex_unlock(&m); pthread_exit(0); }
1
#include <pthread.h> int mediafirefs_getattr(const char *path, struct stat *stbuf) { printf("FUNCTION: getattr. path: %s\\n", path); struct mediafirefs_context_private *ctx; int retval; time_t now; ctx = fuse_get_context()->private_data; pthread_mutex_lock(&(ctx->mutex)); now = time(0); if (now - ctx->last_status_check > ctx->interval_status_check) { folder_tree_update(ctx->tree, ctx->conn, 0); ctx->last_status_check = now; } retval = folder_tree_getattr(ctx->tree, ctx->conn, path, stbuf); if (retval != 0 && stringv_mem(ctx->sv_writefiles, path)) { stbuf->st_uid = geteuid(); stbuf->st_gid = getegid(); stbuf->st_ctime = 0; stbuf->st_mtime = 0; stbuf->st_mode = S_IFREG | 0666; stbuf->st_nlink = 1; stbuf->st_atime = 0; stbuf->st_size = 0; retval = 0; } pthread_mutex_unlock(&(ctx->mutex)); return retval; }
0
#include <pthread.h> static pthread_mutex_t dref_mutex = PTHREAD_MUTEX_INITIALIZER; static unsigned long num_open_dirs; static unsigned long num_open_dirs_max; static void dref_lock(void) { if (!global_threaded) return; pthread_mutex_lock(&dref_mutex); } static void dref_unlock(void) { if (!global_threaded) return; pthread_mutex_unlock(&dref_mutex); } struct dref *dref_create(const char *dirname) { struct dref *dref; DIR *dd; dd = opendir(dirname); DBG("opendir(%s)=%p (total=%lu)", dirname, dd, ++num_open_dirs); if (!dd) { num_open_dirs--; return 0; } if (num_open_dirs > num_open_dirs_max) num_open_dirs_max = num_open_dirs; dref = mmalloc(sizeof(struct dref)); dref->dd = dd; dref->dirfd = dirfd(dd); dref->count = 1; return dref; } struct dref *dref_get(struct dref *dref) { if (dref) { dref_lock(); dref->count++; dref_unlock(); } return dref; } void dref_put(struct dref *dref) { if (dref) { dref_lock(); dref->count--; if (dref->count == 0) { num_open_dirs--; DBG("closedir(%p) (total=%lu, max=%lu)", dref->dd, num_open_dirs, num_open_dirs_max); closedir(dref->dd); free(dref); } dref_unlock(); } }
1
#include <pthread.h> int beers = 2000000; pthread_mutex_t beers_lock = PTHREAD_MUTEX_INITIALIZER; void* drink_lots() { int i; pthread_mutex_lock(&beers_lock); for (i = 0; i < 100000; i++) { beers = beers - 1; } pthread_mutex_unlock(&beers_lock); printf("beers = %i\\n", beers); return 0; } int main() { pthread_t threads[20]; int t; printf("%i bottles of beer on the wall\\n%i bottles of beer\\n", beers, beers); for (t = 0; t < 20; t++) { pthread_create(&threads[t], 0, drink_lots, 0); } void* result; for (t = 0; t < 20; t++) { pthread_join(threads[t], &result); } printf("There are now %i bottles of beer on the wall\\n", beers); return 0; }
0