text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> int ny,nl,n; int flagy[10000]={0},flagl[10000]={0}; sem_t buf_limit,seml,semy; sem_t sl; sem_t sy; int nwaity=0,nwaitl=0; void *Yenter(void *ii); void *Lenter(void *ii); pthread_mutex_t mutex; int main() { printf("Number of Yorks:"); scanf("%d",&ny); printf("\\nNumber of Lanncasters:"); scanf("%d",&nl); printf("\\nInn size:"); scanf("%d",&n); printf("\\n"); pthread_t y[ny],l[nl]; sem_init(&buf_limit,0,n); sem_init(&seml,0,0); sem_init(&semy,0,0); int i,a[ny],b[nl]; for(i=0;i<ny;i++) { a[i]=i; } for(i=0;i<nl;i++) { b[i]=i; } for(i=0;i<ny;i++) { pthread_create(&y[i],0,&Yenter,&a[i]); } for(i=0;i<nl;i++) { pthread_create(&l[i],0,&Lenter,&b[i]); } printf("threads created\\n"); for(i=0;i<ny;i++) { pthread_join(y[i],0); } for(i=0;i<nl;i++) { pthread_join(l[i],0); } return 0; } void *Yenter(void *ii) { int i = *((int *)ii); pthread_mutex_lock(&mutex); int f; for(f=0;f<nl;f++) { if(flagl[f]==1) break; } if(f!=nl) { printf("York %d waiting\\n",i+1); nwaity++; sem_wait(&seml); pthread_mutex_unlock(&mutex); } else { flagy[i]=1; pthread_mutex_unlock(&mutex); } sem_wait(&buf_limit); pthread_mutex_lock(&mutex); printf("York %d entered the Inn\\n",i+1); flagy[i]=1; pthread_mutex_unlock(&mutex); sleep(2); pthread_mutex_lock(&mutex); printf("York %d left the Inn\\n",i+1); flagy[i]=0; sem_post(&buf_limit); for(f=0;f<ny;f++) { if(flagy[f]==1) break; } if(f==ny) { int o; for(o=0;o<nwaitl;o++) { sem_post(&semy); } nwaitl=0; } pthread_mutex_unlock(&mutex); } void *Lenter(void *ii) { int i = *((int *)ii); pthread_mutex_lock(&mutex); int f; for(f=0;f<ny;f++) { if(flagy[f]==1) break; } if(f!=ny) { printf("Lanncaster %d waiting\\n",i+1); nwaitl++; pthread_mutex_unlock(&mutex); sem_wait(&semy); pthread_mutex_unlock(&mutex); } else { flagl[i]=1; pthread_mutex_unlock(&mutex); } sem_wait(&buf_limit); pthread_mutex_lock(&mutex); printf("Lanncaster %d entered the Inn\\n",i+1); flagl[i]=1; pthread_mutex_unlock(&mutex); sleep(2); pthread_mutex_lock(&mutex); printf("Lanncaster %d left the Inn\\n",i+1); flagl[i]=0; sem_post(&buf_limit); for(f=0;f<nl;f++) { if(flagl[f]==1) break; } if(f==nl) { sem_post(&seml); int o; for(o=0;o<nwaity;o++) { sem_post(&seml); } nwaity=0; } pthread_mutex_unlock(&mutex); }
1
#include <pthread.h> void PL_wifi_signal_thread() { int goterr = 0; char ap_addr_outcome[255]; char signal_indicator[2]; uint8_t connection_test; uint8_t signal_level; FILE * f; PL_debug("PL_wifi_signal_thread: starting"); while(1) { signal_level = 0; system("/usr/sbin/iris-wifi-signal-level.sh"); f = fopen("/tmp/wifi.signal.level", "r"); if(f==0) signal_level = 0; else { fscanf(f, "%d", &signal_level); fclose(f); } if(signal_level > 4) signal_level = 0; pthread_mutex_lock(&G_display_lock); switch (signal_level) { case 0: my_spi_WEH001602_def_char(6,0x0010001000100010); break; case 1: my_spi_WEH001602_def_char(6,0x0018001000100010); break; case 2: my_spi_WEH001602_def_char(6,0x0018001C00100010); break; case 3: my_spi_WEH001602_def_char(6,0x0018001C001E0010); break; case 4: my_spi_WEH001602_def_char(6,0x0018001C001E001F); break; } pthread_mutex_unlock(&G_display_lock); sprintf(signal_indicator,"\\x6\\0"); if(G_global_mode == GLOBAL_MODE_NORMAL) { pthread_mutex_lock(&G_display_lock); my_spi_WEH001602_out_text_at_col(BOTTOM_ROW, 0, &signal_indicator); pthread_mutex_unlock(&G_display_lock); } sleep(6); } }
0
#include <pthread.h> const char * getexecname(void) { static char execname[PATH_MAX + 1] = ""; static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; char *ptr = 0; ssize_t rc; pthread_mutex_lock(&mtx); if (strlen(execname) == 0) { rc = readlink("/proc/self/exe", execname, sizeof (execname) - 1); if (rc == -1) { execname[0] = '\\0'; } else { execname[rc] = '\\0'; ptr = execname; } } else { ptr = execname; } pthread_mutex_unlock(&mtx); return (ptr); }
1
#include <pthread.h> char str1[9999999]; long n = 5242880, lc, buffer_size; struct timeval t; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; long timediff(clock_t t1, clock_t t2) { long elapsed; elapsed = ((double)t2 - t1) / CLOCKS_PER_SEC * 1000000 ; return elapsed; } double genavg(double a[]) { int s; double sum=0; double avg; for(s = 0; s < 10000; s++) { sum+=a[s]; } avg= sum/10000; return avg; } void mkdata(long n) { printf("Constructing the file...\\n"); int i; for (i = 0; i < n; ++i) { str1[i]= (char)((rand()% 10)+97); } } void *seqread() { char temp[n]; long m; pthread_mutex_lock( &mutex1 ); for(m = 0; m < lc; m += buffer_size) memcpy(temp, str1, buffer_size); pthread_mutex_unlock( &mutex1 ); } void *seqwrite() { char str3[n]; long q; pthread_mutex_lock( &mutex1 ); for(q = 0; q < lc; q += buffer_size) strncpy(str3, str1, buffer_size); pthread_mutex_unlock( &mutex1 ); } void *randread() { long w, v; char temp[n]; pthread_mutex_lock( &mutex1 ); for (w = 0; w < lc; w += buffer_size) { v = rand()% 200; memcpy(&temp[v], &str1[v], buffer_size); } pthread_mutex_unlock( &mutex1 ); } void *randwrite() { long e, g; char str3[n]; pthread_mutex_lock( &mutex1 ); for (e = 0;e < lc; e += buffer_size) { g = rand()% 200; strncpy(&str3[g], &str1[g], buffer_size); } pthread_mutex_unlock( &mutex1 ); } void latency(long buffer_size1, long buffer_size) { long r; char str5[n]; clock_t t1,t2; double elapsed[10000]; double tt; for(r=0; r<10000; r+=1) { t1= clock(); memcpy(&str5[r], &str1[r] , buffer_size); t2= clock(); elapsed[r] = timediff(t1, t2); } tt= genavg(elapsed); printf("Latency: %lf ns\\n", tt); } int main() { int threadct, i, j, k, l, p, o, u, y,q; double s_t, e_t, t_t, tt; float ca1[40], ca2[40], ca3[40], ca4[40]; printf("Enter the number of threads you want to create:"); scanf("%d",&threadct); pthread_t threads[threadct]; printf("\\nEnter the size(1 byte/1024 bytes/1048576 bytes:"); scanf("%ld",&buffer_size); mkdata(n); lc = n/threadct; gettimeofday(&t, 0); s_t = t.tv_sec+(t.tv_usec/1000000.0); for( i=0;i<threadct;i++) { pthread_create(&threads[i],0, &seqread, 0); } for(p =0; p < threadct; p++) { pthread_join(threads[p], 0); } gettimeofday(&t, 0); e_t = t.tv_sec+(t.tv_usec/1000000.0); t_t = e_t - s_t; printf("Time elapsed using threads: %lf Sec\\n", t_t); printf("Throughput for seq read = %lf \\n", (n/t_t)/(1024*1024)); sleep(1); gettimeofday(&t, 0); s_t = t.tv_sec+(t.tv_usec/1000000.0); for(j = 0; j < threadct; j++) { pthread_create(&threads[j],0, &seqwrite, 0); } for(o =0; o < threadct; o++) { pthread_join(threads[o], 0); } gettimeofday(&t, 0); e_t = t.tv_sec+(t.tv_usec/1000000.0); t_t = e_t - s_t; printf("Time elapsed using threads: %lf Sec\\n", t_t); ca2[q]=(n/t_t)/(1024*1024); printf("Throughput for seq write = %lf \\n",(n/t_t)/(1024*1024)); sleep(1); gettimeofday(&t, 0); s_t = t.tv_sec+(t.tv_usec/1000000.0); for(k = 0; k < threadct; k++) { pthread_create(&threads[k],0, &randread, 0); } for(u =0; u < threadct; u++) { pthread_join(threads[u], 0); } gettimeofday(&t, 0); e_t = t.tv_sec+(t.tv_usec/1000000.0); t_t = e_t - s_t; printf("Time elapsed using threads: %lf Sec\\n", t_t); ca3[q]=(n/t_t)/(1024*1024); printf("Throughput for rand read = %lf \\n", (n/t_t)/(1024*1024)); sleep(1); gettimeofday(&t, 0); s_t = t.tv_sec+(t.tv_usec/1000000.0); for(l = 0; l < threadct; l++) { pthread_create(&threads[l],0, &randwrite, 0); } for(y =0; y < threadct; y++) { pthread_join(threads[y], 0); } gettimeofday(&t, 0); e_t = t.tv_sec+(t.tv_usec/1000000.0); t_t = e_t - s_t; printf("Time elapsed using threads: %lf Sec\\n", t_t); ca4[q]=(n/t_t)/(1024*1024); printf("Throughput for rand write =%lf \\n",(n/t_t)/(1024*1024)); sleep(1); printf("Ending...\\n"); latency(buffer_size,buffer_size); return 0; }
0
#include <pthread.h> double counter = 0; pthread_mutex_t lock; void* counting(void *); int main(void) { pthread_t tid[200]; int i=0; if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } for( i=0; i<200; i++){ pthread_create (&tid[i], 0, &counting, 0); } for( i=0; i< 200; i++){ pthread_join(tid[i], 0); } pthread_mutex_destroy(&lock); printf("\\nCounter must be in: %d\\n", 1000*200); printf("\\nCounter value is: %.0f\\n\\n", counter); return 0; } void* counting(void * unused) { int i=0; pthread_mutex_lock(&lock); for(i=0; i<1000; i++) counter++; pthread_mutex_unlock(&lock); return 0; }
1
#include <pthread.h> int totalSlots; int levels; int parkingSpaces; int** parking; FILE *file; int identifierMax=0; pthread_cond_t parkingFull = PTHREAD_COND_INITIALIZER; pthread_cond_t leaveSpace = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutexin = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexout = PTHREAD_MUTEX_INITIALIZER; void *assignSpace(void *threadid){ pthread_mutex_lock(&mutexin); if(totalSlots <= 0){ printf("Parking full. Thread %d will wait\\n",threadid); pthread_cond_wait(&leaveSpace, &mutexin); } totalSlots--; if ((fprintf(file,"[%d] in the parking, %d vacancies\\n", threadid, totalSlots))<0) { perror("write error"); } int i,j, ib,jb,k, counter = 0; for( i = 0; i < levels; i++){ for( j = 0; j < parkingSpaces; j++){ if(parking[i][j] == 0){ printf("Level %d. Position %d is free. Thread %d is taking it...",i,j,threadid); parking[i][j]=1; printf("TAKEN \\n"); ib=i; jb=j; for(k = 0 ; k < parkingSpaces; k++) if(parking[i][k] == 0) counter++; if ((fprintf(file,"[%d] arrives at level %d, %d free spaces on the level\\n", threadid, i, counter))<0) { perror("write error"); } j=parkingSpaces;i=levels; } } } pthread_mutex_unlock(&mutexin); pthread_mutex_lock(&mutexout); sleep(random()%10); counter=0; parking[ib][jb]=0; for(k = 0 ; k < parkingSpaces; k++) if(parking[ib][k] == 0) counter++; if ((fprintf(file,"[%d] leaves level %d, %d free spaces on the level\\n",threadid, ib, counter))<0) { perror("write error"); } totalSlots++; printf("%d leaves parking, %d vacancies\\n",threadid, totalSlots); if ((fprintf(file,"[%d] leaves the parking, %d vacancies\\n", threadid, totalSlots))<0) { perror("write error"); } pthread_cond_signal(&leaveSpace); pthread_mutex_unlock(&mutexout); pthread_exit(0); } int main (int argc, char *argv[]){ if (argc != 4){ printf("Sorry, at least three parameters, number of levels, number of spaces" " and file name are required to run the program. \\n You wrote %d parameters" "\\nExiting... ", argc); exit(1); } printf("Assigning levels..."); levels = atoi(argv[1]); printf("DONE\\n"); printf("Assigning parking spaces per level..."); parkingSpaces = atoi(argv[2]); printf("DONE\\n"); totalSlots = levels * parkingSpaces; printf("Initializing parking spots..."); int i; parking = malloc(levels*sizeof(int *)); if(parking == 0){ perror("out of memory\\n"); exit(1); } for( i = 0; i < levels; i++){ parking[i] = malloc(parkingSpaces*sizeof(int)); if(parking[i] == 0){ perror("out of memory\\n"); exit(1); } } printf("DONE\\n"); printf("The parking has %d total slots. All of them are empty\\n",totalSlots); printf("Creating output file..."); const char *textfilename = argv[3]; if ((file = fopen(textfilename,"a+")) == 0) { perror("Error when creating text file"); return 1; } printf("DONE\\n"); int nrOfCars; int t, rc; int stillCarsIn = 1; pthread_t threads[1000]; while(stillCarsIn){ printf("How many cars are trying to enter the parking?\\n"); scanf("%d",&nrOfCars); if(nrOfCars < 0){ printf("Sorry, you cannot have a negative number of cars. Exiting..."); fclose(file); exit(1); } if(nrOfCars == 0){ printf("Wait until the cars exit the parking...\\n"); while(totalSlots != levels * parkingSpaces); printf("All the cars are out. Parking is empty.\\n"); printf("Exiting..."); fclose(file); exit(1); } if(nrOfCars > 0){ for(t=0;t < nrOfCars;t++){ printf("Creating thread for car %d\\n", identifierMax+t); rc = pthread_create(&threads[t], 0, assignSpace, (void *)identifierMax+t); if (rc){ printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } identifierMax=nrOfCars; } } return 0; }
0
#include <pthread.h> pthread_mutex_t mut0 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mut1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t inutil = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int nom_incr; void sigint_handler(int s) { pthread_mutex_destroy(&mut0); pthread_mutex_destroy(&mut1); exit(0); } void* incr(void* arg) { int* var=((int*)arg); nom_incr++; int nom=nom_incr; while(1) { pthread_cond_wait(&cond, &inutil); sleep(rand()%2+1); pthread_mutex_lock(&mut0); printf("incr%d : \\t before x=%d\\n", nom, *var); (*var)++; printf("\\t\\t after x=%d\\n", *var); pthread_mutex_unlock(&mut0); pthread_mutex_unlock(&mut1); } } void* reset(void* arg) { int* var=(int*)arg; while(1) { pthread_mutex_lock(&mut1); if(*var>=5) { printf("RESET : \\t before x=%d\\n", *var); *var=0; printf("\\t\\t after x=%d\\n", *var); } pthread_cond_signal(&cond); } } int main(void) { srand(time(0)); struct sigaction sa; sa.sa_handler=sigint_handler; sa.sa_flags=SA_RESTART; sigemptyset(&sa.sa_mask); sigaction(SIGINT, &sa, 0); pthread_t th0, th1, th2, th3; int var=0; nom_incr=0; int ptid1=pthread_create(&th0, 0, incr, &var); int ptid2=pthread_create(&th1, 0, incr, &var); int ptid3=pthread_create(&th2, 0, incr, &var); int ptid4=pthread_create(&th3, 0, reset, &var); pthread_join(th0, 0); exit(0); }
1
#include <pthread.h> static void read_quicktime(frame, number) unsigned char *frame[]; long number; { int i, j; int r, g, b; int y, u, v; double cr, cg, cb, cu, cv; char name[128]; unsigned char *yp, *up, *vp; static unsigned char *u444, *v444, *u422, *v422; static double coef[7][3] = { {0.2125,0.7154,0.0721}, {0.299, 0.587, 0.114}, {0.299, 0.587, 0.114}, {0.30, 0.59, 0.11}, {0.299, 0.587, 0.114}, {0.299, 0.587, 0.114}, {0.212, 0.701, 0.087}}; static long rtoy_tab[256], gtoy_tab[256], btoy_tab[256]; static long rtou_tab[256], gtou_tab[256], btou_tab[256]; static long rtov_tab[256], gtov_tab[256], btov_tab[256]; static int need_tables = 1; int colormodel; long real_number; i = matrix_coefficients; if(i > 8) i = 3; cr = coef[i - 1][0]; cg = coef[i - 1][1]; cb = coef[i - 1][2]; cu = 0.5 / (1.0 - cb); cv = 0.5 / (1.0 - cr); if(chroma_format == CHROMA444) { u444 = frame[1]; v444 = frame[2]; } else { if (!u444) { if (!(u444 = (unsigned char *)malloc(width*height))) error("malloc failed"); if (!(v444 = (unsigned char *)malloc(width*height))) error("malloc failed"); if (chroma_format==CHROMA420) { if (!(u422 = (unsigned char *)malloc((width>>1)*height))) error("malloc failed"); if (!(v422 = (unsigned char *)malloc((width>>1)*height))) error("malloc failed"); } } } if(need_tables) { for(i = 0; i < 256; i++) { rtoy_tab[i] = (long)( 0.2990 * 65536 * i); rtou_tab[i] = (long)(-0.1687 * 65536 * i); rtov_tab[i] = (long)( 0.5000 * 65536 * i); gtoy_tab[i] = (long)( 0.5870 * 65536 * i); gtou_tab[i] = (long)(-0.3320 * 65536 * i); gtov_tab[i] = (long)(-0.4187 * 65536 * i); btoy_tab[i] = (long)( 0.1140 * 65536 * i); btou_tab[i] = (long)( 0.5000 * 65536 * i); btov_tab[i] = (long)(-0.0813 * 65536 * i); } need_tables = 0; } real_number = (long)((double)quicktime_frame_rate(qt_file, 0) / frame_rate * number + 0.5); quicktime_set_video_position(qt_file, real_number, 0); quicktime_set_row_span(qt_file, width); quicktime_set_window(qt_file, 0, 0, horizontal_size, vertical_size, horizontal_size, vertical_size); quicktime_set_cmodel(qt_file, (chroma_format == 1) ? BC_YUV420P : BC_YUV422P); quicktime_decode_video(qt_file, frame, 0); } static void read_mpeg(long number, unsigned char *frame[]) { int i; char name[128]; long real_number; real_number = (long)((double)mpeg3_frame_rate(mpeg_file, 0) / frame_rate * number + 0.5); while(mpeg3_get_frame(mpeg_file, 0) <= real_number) mpeg3_read_yuvframe(mpeg_file, frame[0], frame[1], frame[2], 0, 0, horizontal_size, vertical_size, 0); if(mpeg3_end_of_video(mpeg_file, 0)) frames_scaled = 1; } static void read_stdin(long number, unsigned char *frame[]) { int chroma_denominator = 1; unsigned char data[5]; if(chroma_format == 1) chroma_denominator = 2; fread(data, 4, 1, stdin_fd); if(data[0] == 0xff && data[1] == 0xff && data[2] == 0xff && data[3] == 0xff) { frames_scaled = 0; return; } fread(frame[0], width * height, 1, stdin_fd); fread(frame[1], width / 2 * height / chroma_denominator, 1, stdin_fd); fread(frame[2], width / 2 * height / chroma_denominator, 1, stdin_fd); } static void read_buffers(long number, unsigned char *frame[]) { int chroma_denominator = 1; unsigned char data[5]; if(chroma_format == 1) chroma_denominator = 2; pthread_mutex_lock(&input_lock); if(input_buffer_end) { frames_scaled = 0; pthread_mutex_unlock(&copy_lock); pthread_mutex_unlock(&output_lock); return; } memcpy(frame[0], input_buffer_y, width * height); memcpy(frame[1], input_buffer_u, width / 2 * height / chroma_denominator); memcpy(frame[2], input_buffer_v, width / 2 * height / chroma_denominator); pthread_mutex_unlock(&copy_lock); pthread_mutex_unlock(&output_lock); } void readframe(int frame_num, uint8_t *frame[]) { int n; n = frame_num % (2 * READ_LOOK_AHEAD); frame[0] = frame_buffers[n][0]; frame[1] = frame_buffers[n][1]; frame[2] = frame_buffers[n][2]; switch (inputtype) { case T_QUICKTIME: read_quicktime(frame, frame_num); break; case T_MPEG: read_mpeg(frame_num, frame); break; case T_STDIN: read_stdin(frame_num, frame); break; case T_BUFFERS: read_buffers(frame_num, frame); break; default: break; } }
0
#include <pthread.h> struct connection ** connection_tbl = 0; struct connection *last_connection; pthread_mutex_t mutex; int init_connection_tbl_status = 0; fpos_t pos; char str_status[6][7] = {"NEW", "SEND", "RECV", "CONNECT" , "LISTEN", "FIN"}; void init_connection_tbl() { if(!init_connection_tbl_status) { connection_tbl = calloc(1, sizeof(struct connection *)); connection_tbl[0] = calloc(1, sizeof(struct connection)); connection_tbl[0]->next = 0; last_connection = connection_tbl[0]; if(!connection_tbl) { printf("Error init_connection_tbl"); return; } printf("Memory Loction of table %p\\n", connection_tbl); printf("Memory Loction of init record %p\\n", connection_tbl[0]); init_connection_tbl_status = 1; printf("Size of connection : %lu %lu\\n", sizeof(struct connection), sizeof(size_t)); printf("------------------------------\\n"); printf("Initialized Connection Manager\\n"); printf("------------------------------\\n\\n\\n"); } } void add_connection(int sockfd, int app_guid){ struct connection *record; record = calloc(1, sizeof(struct connection)); last_connection->next = record; if(!record) { printf("Error add_connection"); return; } printf("Memory Loction is %p\\n", record); record->sockfd = sockfd; record->parent_sockfd = 0; record->app_guid = app_guid; record->policy_guid = 0; record->status = NEW; record->next = 0; update_last_connection(record); } void add_child_connection(int sockfd, int new_sockfd){ struct connection *record; record = calloc(1, sizeof(struct connection)); last_connection->next = record; if(!record) { printf("Error add_connection"); return; } printf("Memory Loction is %p\\n", record); record->sockfd = new_sockfd; record->parent_sockfd = sockfd; record->app_guid = 31; record->policy_guid = 0; record->status = NEW; record->next = 0; update_last_connection(record); } int update_connection_bind(int sockfd, const void *addr, int addrlen){ struct connection *node = connection_tbl[0]->next; while(node->next != 0) { if (node->sockfd == sockfd) { node->addr = addr; node->addrlen = addrlen; return 0; } node = node->next; } return 1; } int update_connection_status(int sockfd, enum connection_status status){ struct connection *node = connection_tbl[0]->next; while(node->next != 0) { if (node->sockfd == sockfd) { node->status = status; return 0; } node = node->next; } return 1; } void print_connections() { struct connection *node = connection_tbl[0]->next; FILE *file = fopen("connections.out","w"); fflush(file); if (fgetpos(file,&pos) == -1) { fprintf(file,"Unable to refresh screen\\n"); fclose(file); } fprintf(file,"------------------------\\n"); fprintf(file,"Printing Connection Info\\n"); fprintf(file,"------------------------\\n"); fprintf(file,"Connection: FD \\t STAT \\t APPID \\n"); while(node->next != 0) { fprintf(file,"Connection: %d \\t %s \\t %d \\n", node->sockfd, convert_status(node->status), node->app_guid); node = node->next; } fprintf(file, "------------------------\\n"); if (fsetpos(file,&pos) == -1) { fprintf(file,"Unable to refresh screen\\n"); fclose(file); } fclose(file); } char * convert_status(enum connection_status status) { return str_status[status]; } void update_last_connection(struct connection *record) { pthread_mutex_lock( &mutex ); last_connection = record; pthread_mutex_unlock( &mutex ); }
1
#include <pthread.h> void pthread_huidiao(void) { } void lizhi1_huidiao_init(struct pthread_huidiao_1 *p) { p->clocktime=0; p->flag_appact=0; p->funpthread_hui=pthread_huidiao; pthread_mutex_init(&p->all,0); p->funpthread_hui=lizhi1_huidiao_f1; } void lizhi1_huidiao_destroy(struct pthread_huidiao_1*p) { p->clocktime=0; p->flag_appact=0; p->funpthread_hui=pthread_huidiao; pthread_mutex_destroy(&p->all); } void lizhi1_huidiao_start(struct pthread_huidiao_1* p) { int ret; ret=pthread_create(&p->poll_thread,0,lizhi1_huidiao_pthr_1,p); if (ret!=0) { printf("creat pthread error!\\n"); } } void lizhi1_huidiao_shutdown(struct pthread_huidiao_1* p) { p->flag_appact=1; } void lizhi1_huidiao_lock(struct pthread_huidiao_1*p) { pthread_mutex_lock(&p->all); } void lizhi1_huidiao_unlock(struct pthread_huidiao_1*p) { pthread_mutex_unlock(&p->all); } void lizhi1_huidiao_join(struct pthread_huidiao_1*p) { pthread_join(p->poll_thread,0); } void lizhi1_huidiao_f1(void) { printf("huidiao chengong!\\n"); } void * lizhi1_huidiao_pthr_1(void * p) { struct pthread_huidiao_1 *a; a=(struct pthread_huidiao_1 *)p; do { lizhi1_huidiao_lock(a); a->clocktime++; lizhi1_huidiao_unlock(a); Sleep(1000); a->funpthread_hui(); } while (a->flag_appact==0); return 0; } void lizhi1_huidiao_test() { struct pthread_huidiao_1 pth_clk; lizhi1_huidiao_init(&pth_clk); lizhi1_huidiao_start(&pth_clk); lizhi1_huidiao_join(&pth_clk); lizhi1_huidiao_destroy(&pth_clk); }
0
#include <pthread.h> pthread_mutex_t lock; int i = 0 ; void* thd_handle(void* arg) { int *pval = (int *)arg; int cnt = 10 ; while(cnt > 0) { pthread_mutex_lock(&lock); printf("thread %d lock\\n", *pval); i ++ ; pthread_mutex_unlock(&lock); printf("thread %d unlock\\n", *pval); sleep(1); cnt -- ; } pthread_exit((void*)0); } int main(int argc, char* argv[]) { pthread_t thd1 ; pthread_t thd2 ; int cnt = 100000000 ; int val1 = 1; int val2 = 2; pthread_create(&thd1, 0, thd_handle, (void*)&val1); pthread_create(&thd2, 0, thd_handle, (void*)&val2); pthread_join(thd1,0 ); pthread_join(thd2,0 ); printf("i : %d\\n", i); pthread_mutex_destroy(&lock); return 0 ; }
1
#include <pthread.h> static pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER; void lock_mutex(void) { pthread_mutex_lock(&mx); } void unlock_mutex(void) { pthread_mutex_unlock(&mx); } void myClear(void) { pthread_mutex_lock(&mx); clear(); pthread_mutex_unlock(&mx); } void myFlash(void) { pthread_mutex_lock(&mx); flash(); pthread_mutex_unlock(&mx); } void setup(void) { atexit((void *)endwin); initscr(); crmode(); noecho(); clear(); curs_set(0); timeout(0); } bool print_str(const char *str, const int row, const int col, const int len) { int ofst; if ((row < 0) || (row >= LINES) || (col + len < 0) || (col >= COLS)) { return 0; } else if (col < 0) { ofst = -col; pthread_mutex_lock(&mx); move(row, 0); printw("%s", str + ofst); refresh(); pthread_mutex_unlock(&mx); return 1; } else if (col + len >= COLS) { ofst = COLS - col; pthread_mutex_lock(&mx); move(row, col); printw("%.*s", ofst, str); refresh(); pthread_mutex_unlock(&mx); return 1; } else { pthread_mutex_lock(&mx); move(row, col); printw("%s", str); refresh(); pthread_mutex_unlock(&mx); return 1; } } int get_input(void) { char c = -1; pthread_mutex_lock(&mx); c = getch(); pthread_mutex_unlock(&mx); return c; } char get_char(int row, int col) { char x; pthread_mutex_lock(&mx); move(row, col); x = inch(); pthread_mutex_unlock(&mx); return x; } int get_columns(void) { return COLS; } int get_rows(void) { return LINES; }
0
#include <pthread.h> void* thread_function(void* arg); pthread_mutex_t work_mutex; char work_area[4]; int time_to_exit = 0; int main() { int res; pthread_t a_thread; void* thread_result; res = pthread_mutex_init(&work_mutex, 0); if(res){ perror("Mutex initialization failed.\\n"); exit(1); } res = pthread_create(&a_thread, 0, thread_function, 0); if(res){ perror("Thread creation failed.\\n"); exit(1); } pthread_mutex_lock(&work_mutex); printf("Input some text. Enter 'end' to finish.\\n"); while(!time_to_exit){ fgets(work_area, 4, stdin); pthread_mutex_unlock(&work_mutex); while(1){ pthread_mutex_lock(&work_mutex); if(work_area[0] == '\\0'){ printf("Okay no input means work_area[0] = '\\0' "); exit(0); } if(work_area[0] != '\\0'){ pthread_mutex_unlock(&work_mutex); sleep(1); } else break; } } pthread_mutex_unlock(&work_mutex); printf("\\nWaiting for thread to finish. . .\\n"); res = pthread_join(a_thread, &thread_result); if(res){ perror("Thread join failed.\\n"); exit(1); } pthread_mutex_destroy(&work_mutex); exit(0); } void* thread_function(void* arg) { sleep(20); pthread_mutex_lock(&work_mutex); while(strncmp(work_area, "end", 3) != 0){ printf("You input %d charcters.\\n",(int)(strlen(work_area) - 1)); work_area[0] = '\\0'; pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); while(work_area[0] != '\\0'){ pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); } } time_to_exit = 1; work_area[0] = '\\0'; pthread_mutex_unlock(&work_mutex); pthread_exit(0); }
1
#include <pthread.h> int init_disk_controller(struct dctrl *dc) { int rc; pthread_mutex_init(&dc->dc_mutex, 0); pthread_cond_init (&dc->dc_io_req, 0); rc = pthread_create(&dc->dc_thread, 0, disk_controller, dc); if (rc) return -1; return 0; } int close_disk_controller(struct dctrl *dc) { pthread_kill(dc->dc_thread, SIGTERM); pthread_join(dc->dc_thread, &dc->dc_status); pthread_exit(0); } static void dcontroller_terminate(int param) { return; } static void *disk_controller(void *a_dc) { signal(SIGTERM, dcontroller_terminate); struct dctrl *dc = (struct dctrl *)a_dc; while (1) { pthread_mutex_lock(&dc->dc_mutex); dc->dc_bio->bi_ops = &biops; struct bio_operations *io = dc->dc_bio->bi_ops; pthread_cond_wait( &dc->dc_io_req, &dc->dc_mutex); switch(dc->dc_bio->bi_type) { case BI_read: (io->read_block)(dc->dc_bio); break; case BI_write: (io->write_block)(dc->dc_bio); break; } raise_intr(__NR_disk_irq); pthread_mutex_unlock(&dc->dc_mutex); } pthread_exit(0); }
0
#include <pthread.h> struct timeval t0; struct timeval t1; static unsigned len = 2000000; pthread_t tid[16]; pthread_mutex_t full_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t left_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t right_mutex = PTHREAD_MUTEX_INITIALIZER; int v; struct p * left; struct p * right; pthread_mutex_t mutex; } p; struct p *tree; struct p * newNode(int value, struct p * parent) { struct p * node = (struct p*)malloc(sizeof(struct p)); node->v = value; node->left = 0; node->right = 0; return(node); } struct p * find(int v, struct p * somewhere) { if (somewhere == 0) { return 0; } else if (v == somewhere->v) { return somewhere; } else if (v < somewhere->v) { find(v, somewhere->left); } else { find(v, somewhere->right); } } struct p * add(int v, struct p * somewhere, struct p * parent) { if (somewhere == 0) { return(newNode(v,parent)); } else if (v <= somewhere->v) { somewhere->left = add(v, somewhere->left, somewhere); } else { somewhere->right = add(v, somewhere->right, somewhere); } return(somewhere); } struct p * addRoot(int v, struct p * somewhere, struct p * parent) { if (somewhere == 0) { return(newNode(v,parent)); } else if (v <= somewhere->v) { pthread_mutex_lock(&left_mutex); somewhere->left = add(v, somewhere->left, somewhere); pthread_mutex_unlock(&left_mutex); } else { pthread_mutex_lock(&right_mutex); somewhere->right = add(v, somewhere->right, somewhere); pthread_mutex_unlock(&right_mutex); } return(somewhere); } struct p * add2(int v, struct p * somewhere, struct p * parent) { if (somewhere == 0) { pthread_mutex_unlock(&parent->mutex); return(newNode(v,parent)); } else { pthread_mutex_lock(&somewhere->mutex); if (somewhere != parent) pthread_mutex_unlock(&parent->mutex); if (v <= somewhere->v) { somewhere->left = add2(v, somewhere->left, somewhere); } else { somewhere->right = add2(v, somewhere->right, somewhere); } } return(somewhere); } struct p * add_if_not_present(int v, struct p * somewhere, struct p * parent) { if (somewhere == 0) { return(newNode(v,parent)); } else if (v == somewhere->v) { return 0; } else { if (v <= somewhere->v) { somewhere->left = add(v, somewhere->left, somewhere); } else { somewhere->right = add(v, somewhere->right, somewhere); } } return(somewhere); } struct p * add_if_not_present2(int v, struct p * somewhere, struct p * parent) { if (somewhere == 0) { pthread_mutex_unlock(&parent->mutex); return(newNode(v,parent)); } else if (v == somewhere->v) { pthread_mutex_unlock(&parent->mutex); return 0; } else { pthread_mutex_lock(&somewhere->mutex); if (somewhere != parent) pthread_mutex_unlock(&parent->mutex); if (v <= somewhere->v) { somewhere->left = add_if_not_present2(v, somewhere->left, somewhere); } else { somewhere->right = add_if_not_present2(v, somewhere->right, somewhere); } } return(somewhere); } int size(struct p * somewhere) { int c = 1; if (somewhere == 0) { return 0; } else { c += size(somewhere->left); c += size(somewhere->right); return c; } } int checkIntegrity(struct p * somewhere, int index, int nodeCount) { if (somewhere == 0) { return(1); } else if (index >= nodeCount) { return(0); } return(checkIntegrity(somewhere->left, 2*index + 1, nodeCount) && checkIntegrity(somewhere->right, 2*index + 2, nodeCount)); } void *baseline() { int i; for(i = 0; i<len;i++) { pthread_mutex_lock(&full_mutex); add(random(),tree,tree); add_if_not_present(random(),tree,tree); pthread_mutex_unlock(&full_mutex); } } void *better() { int i; for(i = 0; i<len; i++) { addRoot(random(),tree,tree); add_if_not_present(random(),tree,tree); } } void curFunc() { int i; int err; for(i = 0; i < 16; i++) { err = pthread_create(&(tid[i]), 0, &better, 0); }; for(i = 0; i < 16; i++) { pthread_join(tid[i],0); }; }; int main() { tree = (p *) malloc(len*sizeof(p)); tree->v = random(); gettimeofday(&t0,0); curFunc(); gettimeofday(&t1,0); double elapsed = (t1.tv_sec-t0.tv_sec)*1000000 + t1.tv_usec-t0.tv_usec; printf("time: %f\\n", elapsed/ 1000000 ); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; int message_available; char** messages; void* Send_msg(void* rank); int main(void) { pthread_t* thread_handles; long thread; long thread_count = 2; message_available = 0; messages = malloc(1 * sizeof(char *)); pthread_mutex_init(&mutex, 0); thread_handles = malloc (thread_count * sizeof ( pthread_t) ); for (thread = 0; thread < thread_count; thread++) { pthread_create(&thread_handles[thread], 0, Send_msg, (void*) thread); } for (thread = 0; thread < thread_count; thread++) { pthread_join(thread_handles[thread], 0); } free(messages); free(thread_handles); return 0; } void* Send_msg(void* rank) { long my_rank = (long) rank; char* my_msg = malloc(1024 * sizeof (char)); while (1) { pthread_mutex_lock(&mutex); if (my_rank == 0) { if (message_available) { printf("Consumer Thread %ld > %s\\n", my_rank, messages[my_rank]); pthread_mutex_unlock(&mutex); break; } } else { sprintf(my_msg, "Hello to Consumer thread %d from Producer thread %ld", 0, my_rank); messages[0] = my_msg; message_available = 1; pthread_mutex_unlock(&mutex); break; } pthread_mutex_unlock(&mutex); } return 0; }
0
#include <pthread.h> int nb_philo; int nb_Grain_De_Riz = 8; int * baguettes_prises; int doitPrioriser; int aPrioriser; int * toursSansManger; pthread_mutex_t * mutexs; pthread_mutex_t global; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; struct philo { int identifiant; }; int mod(int a, int b) { int r = a % b; return r < 0 ? r + b : r; } void initialisation(){ pthread_mutex_init(&global, 0); baguettes_prises = malloc(nb_philo*sizeof(int)); toursSansManger = malloc(nb_philo*sizeof(int)); mutexs = malloc(nb_philo*sizeof(pthread_mutex_t)); srand (time (0)); aPrioriser = -1; doitPrioriser = 0; for(int i = 0; i<nb_philo;i++){ baguettes_prises[i] = 0; toursSansManger[i] = 0; pthread_mutex_init(&mutexs[i], 0); } } void parler(int id){ printf("Le philosophe %d philosophe ! :)\\n",id); } void prendre_baguettes(int id){ pthread_mutex_lock(&global); while( baguettes_prises[id] || baguettes_prises[(id+1)%nb_philo] || (doitPrioriser && (mod(id-1,nb_philo)== aPrioriser || (id+1%nb_philo)== aPrioriser )) ){ pthread_cond_wait(&cond,&global); if(!doitPrioriser && ++toursSansManger[id] == 2){ doitPrioriser = 1; aPrioriser = id; printf("Famine detectee le philosophe %d a faim: remedions a cela !\\n",id); } pthread_cond_signal(&cond); } toursSansManger[id] =0; if(id == aPrioriser){ doitPrioriser =0; aPrioriser = -1; } printf("Le philosophe %d prend les baguettes %d et %d\\n",id, id,(id+1)%nb_philo); pthread_mutex_lock(&mutexs[id]); pthread_mutex_lock(&mutexs[(id+1)%nb_philo]); baguettes_prises[id] = 1; baguettes_prises[(id+1)%nb_philo] = 1; pthread_mutex_unlock(&global); } void manger(int id){ printf("Le philosophe %d mange ! Avec les baguettes %d et %d\\n", id, id, (id+1)%nb_philo); } void rendre_baguettes(int id){ pthread_mutex_lock(&global); pthread_mutex_unlock(&mutexs[id]); pthread_mutex_unlock(&mutexs[(id+1)%nb_philo]); baguettes_prises[id] = 0; baguettes_prises[(id+1)%nb_philo] = 0; printf("Le philosophe %d a rendu les baguettes %d et %d\\n", id, id, (id+1)%nb_philo); pthread_mutex_unlock(&global); pthread_cond_signal(&cond); } void philosophe(void * args){ struct philo* info = (struct philo*) args; int identifiant = info->identifiant; for (int i=0;i<nb_Grain_De_Riz ; i++){ parler(identifiant); prendre_baguettes(identifiant); manger(identifiant); rendre_baguettes(identifiant); } } int main (int argc, char **argv){ if(argc != 2){ printf("Utilisation : ./version1 <nb_philosophes>\\n"); return 1; } nb_philo = atoi(argv[1]); initialisation(); struct philo* philo; pthread_t *tids = malloc (nb_philo * sizeof(pthread_t)); for(int i = 0; i < nb_philo; i++){ philo = (struct philo *) malloc(sizeof(struct philo)); philo->identifiant = i; pthread_create(&tids[i], 0, (void*)philosophe, philo); } for(int j = 0;j< nb_philo;j++) pthread_join(tids[j],0); return 0; }
1
#include <pthread.h> pthread_t threads[2]; int rr_max_priority; int count = 0; pthread_mutex_t count_mutex1, count_mutex2; pthread_cond_t count_threshold_cv1, count_threshold_cv2; volatile unsigned long long total_cost; volatile unsigned long long start1, end1; volatile unsigned long long start2, end2; void * lowest(void *arg) { move_thread_to_core(2); set_resource_limit(); get_thread_info(pthread_self()); int i; for (i = 0; i < MAX_CV_TIMES; i++) { pthread_mutex_lock(&count_mutex1); count++; start1 = rdtsc(); pthread_cond_signal(&count_threshold_cv1); pthread_mutex_unlock(&count_mutex1); pthread_mutex_lock(&count_mutex2); pthread_cond_wait(&count_threshold_cv2, &count_mutex2); end2 = rdtsc(); total_cost += end1-start1+end2-start2; count++; pthread_mutex_unlock(&count_mutex2); } usleep(10); pthread_exit(0); } void * highest(void *arg) { move_thread_to_core(1); set_resource_limit(); get_thread_info(pthread_self()); int i; for (i = 0; i < MAX_CV_TIMES; i++) { pthread_mutex_lock(&count_mutex1); pthread_cond_wait(&count_threshold_cv1, &count_mutex1); end1 = rdtsc(); count++; pthread_mutex_unlock(&count_mutex1); pthread_mutex_lock(&count_mutex2); count++; start2 = rdtsc(); pthread_cond_signal(&count_threshold_cv2); pthread_mutex_unlock(&count_mutex2); } usleep(10); pthread_exit(0); } int main(int argc, char *argv[]) { int prio_low, prio_high; struct sched_param param_low, param_high; pthread_attr_t attr_obj_low, attr_obj_high; int ret; move_self_to_core(1); printf("PID %d\\n", getpid()); prio_low = sched_get_priority_max(SCHED_RR) - 80; prio_high = sched_get_priority_max(SCHED_RR) - 1; param_low.sched_priority = prio_low; param_high.sched_priority = prio_high; ret = pthread_attr_init(&attr_obj_low); if (ret) assert(0); ret = pthread_attr_init(&attr_obj_high); if (ret) assert(0); ret = pthread_attr_setinheritsched(&attr_obj_low, PTHREAD_EXPLICIT_SCHED); if (ret) assert(0); ret = pthread_attr_setinheritsched(&attr_obj_high, PTHREAD_EXPLICIT_SCHED); if (ret) assert(0); ret = pthread_attr_setschedpolicy(&attr_obj_low, SCHED_RR); if (ret) assert(0); ret = pthread_attr_setschedpolicy(&attr_obj_high, SCHED_RR); if (ret) assert(0); ret = pthread_attr_setschedparam(&attr_obj_low, &param_low); if (ret) assert(0); ret = pthread_attr_setschedparam(&attr_obj_high, &param_high); if (ret) assert(0); ret = pthread_attr_getschedparam(&attr_obj_low, &param_low); if (ret) assert(0); ret = pthread_attr_getschedparam(&attr_obj_high, &param_high); if (ret) assert(0); printf("obj1: thread priority : %d\\n",param_low.sched_priority); printf("obj2: thread priority : %d\\n",param_high.sched_priority); ret = pthread_create(&threads[1], &attr_obj_high, (void *)highest,0); if (ret) assert(0); sleep(1); ret = pthread_create(&threads[0], &attr_obj_low, (void *)lowest,0); if (ret) assert(0); sleep(1); pthread_mutex_init(&count_mutex1, 0); pthread_mutex_init(&count_mutex2, 0); pthread_cond_init (&count_threshold_cv1, 0); pthread_cond_init (&count_threshold_cv2, 0); printf("cv cost: %llu (%d times)\\n", (total_cost/MAX_CV_TIMES) >> 1, MAX_CV_TIMES); int i; for (i = 0; i < 2; i++) { pthread_join(threads[i], 0); } return 0; }
0
#include <pthread.h> pthread_cond_t notFull, notEmpty; pthread_mutex_t mutex; int buffer[10]; int head = 0, tail = 0, size = 0; int counter_producers = 0, counter_consumers = 0; void* producer(void *arg) { int product; srand(time(0)); while (counter_producers < 50) { pthread_mutex_lock(&mutex); while (size == 10 && counter_producers < 50) pthread_cond_wait(&notFull, &mutex); if (counter_producers < 50) { product = -100 + rand() % 200; buffer[head] = product; head = (head + 1) % 10; size++; counter_producers++; printf("Produced %d. number = %d\\n", counter_producers, product); pthread_cond_signal(&notEmpty); } pthread_mutex_unlock(&mutex); } return 0; } void* consumer(void *arg) { int product; while (counter_consumers < 50) { pthread_mutex_lock(&mutex); while (size == 0 && counter_consumers < 50) pthread_cond_wait(&notEmpty, &mutex); if (counter_consumers < 50) { product = buffer[tail]; tail = (tail + 1) % 10; size--; counter_consumers++; printf("Consumed %d. number = %d\\n", counter_consumers, product); pthread_cond_signal(&notFull); } pthread_mutex_unlock(&mutex); } return 0; } int main(int argc, char* argv[]) { int i, rc; pthread_t producers[2]; pthread_t consumers[6]; pthread_attr_t attribute; pthread_mutex_init(&mutex, 0); pthread_cond_init(&notFull, 0); pthread_cond_init(&notEmpty, 0); pthread_attr_init(&attribute); pthread_attr_setdetachstate(&attribute, PTHREAD_CREATE_JOINABLE); for (i = 0; i < 2; i++) { rc = pthread_create(&producers[i], &attribute, producer, (void *)i); if (rc) { printf("GRESKA! Povratni kod iz pthread_create() je: %d", rc); exit(1); } } for (i = 0; i < 6; i++) { rc = pthread_create(&consumers[i], &attribute, consumer, (void *)0); if (rc) { printf("GRESKA! Povratni kod iz pthread_create() je: %d", rc); exit(1); } } for (i = 0; i < 2; i++) { rc = pthread_join(producers[i], 0); if (rc) { printf("GRESKA! Povratni kod iz pthread_join() je: %d", rc); exit(1); } } for (i = 0; i < 6; i++) { rc = pthread_join(consumers[i], 0); if (rc) { printf("GRESKA! Povratni kod iz pthread_join() je: %d", rc); exit(1); } } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&notFull); pthread_cond_destroy(&notEmpty); pthread_attr_destroy(&attribute); return 0; }
1
#include <pthread.h> static int last = -1; static int shared = 0; static pthread_mutex_t a1; static pthread_mutex_t a2; static pthread_mutex_t a3; static pthread_mutex_t a4; static pthread_mutex_t a5; static pthread_mutex_t a6; static pthread_mutex_t a7; static pthread_mutex_t a8; static pthread_mutex_t *p1; static pthread_mutex_t *p2; static pthread_mutex_t *p3; static pthread_mutex_t *p4; static pthread_mutex_t *p5; static pthread_mutex_t *p6; static pthread_mutex_t *p7; static pthread_mutex_t *p8; void * w1 (void *x) { pthread_mutex_lock (p1); for (int i = 0; i < 3; ++i) { last = 1; shared = 1; } pthread_mutex_unlock (p1); return 0; } void * w2 (void *x) { pthread_mutex_lock (p2); for (int i = 0; i < 3; ++i) { last = 2; shared = 2; } pthread_mutex_unlock (p2); return 0; } int main () { if (__nondet_bool()) { p1 = &a1; p2 = &a1; pthread_mutex_init (&a1, 0); } else { p1 = &a2; p2 = &a2; pthread_mutex_init (&a2, 0); } pthread_t t1; pthread_t t2; pthread_t t3; pthread_t t4; pthread_t t5; pthread_t t6; pthread_t t7; pthread_t t8; pthread_create (&t1, 0, w1, 0); pthread_create (&t2, 0, w2, 0); pthread_join (t1, 0); pthread_join (t2, 0); assert (last == shared); return 0; }
0
#include <pthread.h> struct wait4context { struct nodeID* node; struct cloud_helper_context *cloud; struct timeval *tout; int *user_fds; pthread_mutex_t wait_mutex; pthread_cond_t wait_cond; int status; int source; }; static void* wait4data_wrapper(void *ctx) { struct wait4context *wait4ctx; struct timeval tout; int status; wait4ctx = (struct wait4context *) ctx; tout = *wait4ctx->tout; status = wait4data(wait4ctx->node, &tout, wait4ctx->user_fds); if (status == 1){ pthread_mutex_lock(&wait4ctx->wait_mutex); wait4ctx->source = DATA_SOURCE_NET; wait4ctx->status = status; pthread_cond_signal(&wait4ctx->wait_cond); pthread_mutex_unlock(&wait4ctx->wait_mutex); } pthread_exit(0); } static void* wait4cloud_wrapper(void *ctx) { struct wait4context *wait4ctx; struct timeval tout; int status; wait4ctx = (struct wait4context *) ctx; tout = *wait4ctx->tout; status = wait4cloud(wait4ctx->cloud, &tout); if (status == 1 || status == -1) { pthread_mutex_lock(&wait4ctx->wait_mutex); wait4ctx->source = DATA_SOURCE_CLOUD; wait4ctx->status = status; pthread_cond_signal(&wait4ctx->wait_cond); pthread_mutex_unlock(&wait4ctx->wait_mutex); } pthread_exit(0); } int wait4any_threaded(struct nodeID *n, struct cloud_helper_context *cloud, struct timeval *tout, int *user_fds, int *data_source) { pthread_attr_t attr; pthread_t wait4data_thread; pthread_t wait4cloud_thread; struct wait4context *wait4ctx; struct timespec timeout; struct timeval now; int err; int result; wait4ctx = malloc(sizeof(struct wait4context)); if (wait4ctx == 0) return -1; wait4ctx->node = n; wait4ctx->cloud = cloud; wait4ctx->tout = tout; wait4ctx->user_fds = user_fds; pthread_mutex_init(&wait4ctx->wait_mutex, 0); pthread_cond_init (&wait4ctx->wait_cond, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_lock(&wait4ctx->wait_mutex); pthread_create(&wait4data_thread, &attr, wait4data_wrapper, (void *)wait4ctx); pthread_create(&wait4cloud_thread, &attr, wait4cloud_wrapper, (void *)wait4ctx); gettimeofday(&now, 0); timeout.tv_sec = now.tv_sec + tout->tv_sec; timeout.tv_nsec = now.tv_usec * 1000 + tout->tv_usec * 1000; err = pthread_cond_timedwait(&wait4ctx->wait_cond, &wait4ctx->wait_mutex, &timeout); if (err == 0) { *data_source = wait4ctx->source; result = 1; } else if(err == ETIMEDOUT){ *data_source = DATA_SOURCE_NONE; result = 0; } pthread_cancel(wait4data_thread); pthread_cancel(wait4cloud_thread); pthread_cond_destroy(&wait4ctx->wait_cond); pthread_mutex_unlock(&wait4ctx->wait_mutex); pthread_mutex_destroy(&wait4ctx->wait_mutex); return result; } int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; return x->tv_sec < y->tv_sec; } int wait4any_polling(struct nodeID *n, struct cloud_helper_context *cloud, struct timeval *tout, struct timeval *step_tout, int *user_fds, int *data_source) { struct timeval timeout; struct timeval *step_time; uint8_t turn; int status; timeout = *tout; if (step_tout == 0) { step_time = malloc(sizeof(struct timeval)); step_time->tv_sec = 0; step_time->tv_usec = 100000; } else { step_time = step_tout; } turn = DATA_SOURCE_NET; while (turn != DATA_SOURCE_NONE) { if (turn == DATA_SOURCE_NET) status = wait4data(n, step_time, user_fds); else status = wait4cloud(cloud, step_time); if (status == 1){ *data_source = turn; free(step_time); return 1; } else { turn = (turn == DATA_SOURCE_NET)? DATA_SOURCE_CLOUD:DATA_SOURCE_NET; if (step_tout == 0) { step_time->tv_sec = 0; step_time->tv_usec = 100000; } else { *step_time = *step_tout; } if (timeval_subtract(&timeout, &timeout, step_time) < 0) turn = DATA_SOURCE_NONE; } } free(step_time); *data_source = DATA_SOURCE_NONE; return 0; }
1
#include <pthread.h> int tid; double stuff; } thread_data_t; double shared_x; pthread_mutex_t lock_x; void *thr_func(void *arg) { thread_data_t *data = (thread_data_t *)arg; printf("hello from thr_func, thread id: %d\\n", data->tid); pthread_mutex_lock(&lock_x); shared_x += data->stuff; printf("x = %f\\n", shared_x); pthread_mutex_unlock(&lock_x); pthread_exit(0); } int main(int argc, char **argv) { pthread_t thr[5]; int i, rc; thread_data_t thr_data[5]; shared_x = 0; pthread_mutex_init(&lock_x, 0); for (i = 0; i < 5; ++i) { thr_data[i].tid = i; thr_data[i].stuff = (i + 1) * 5; if ((rc = pthread_create(&thr[i], 0, thr_func, &thr_data[i]))) { fprintf(stderr, "error: pthread_create, rc: %d\\n", rc); return 1; } } for (i = 0; i < 5; ++i) { pthread_join(thr[i], 0); } return 0; }
0
#include <pthread.h> pthread_t workers[PTHREAD_NUM]; int connPool[PTHREAD_NUM]; int workerInit() { printf("start\\n"); int i; pthread_attr_t attr; pthread_attr_init(&attr); printf("num:%d\\n", PTHREAD_NUM); for (i = 0; i < PTHREAD_NUM; i++) { int arg = i; pthread_cond_init(&pcPool[i].cond, 0); pthread_mutex_init(&pcPool[i].mtx, 0); if (pthread_create(&workers[i], 0, workerStartup, &arg) != 0) { crdsErr("pthread startup failure"); } PthreadFdPool[i] = 0; } } void *workerStartup(void *arg) { int index = *(int *)arg; struct timespec outtime; struct timeval now; struct epoll_event event; int epfd = epoll_create(MAX_EVENT); pthread_mutex_lock(&pcPool[index].mtx); while (1) { gettimeofday(&now, 0); outtime.tv_sec = now.tv_sec + 2; outtime.tv_nsec = 0; pthread_cond_timedwait(&pcPool[index].cond, &pcPool[index].mtx, &outtime); if (PthreadFdPool[index] != 0) { } if (strlen(pthreadMsg[index]) > 0) { printf("%s\\n", pthreadMsg[index]); } } pthread_mutex_unlock(&pcPool[index].mtx); } void *listenStartup(void *arg) { listenServerStartup(); } int workerCleanup() { }
1
#include <pthread.h> static void* reader_thread(void* param) { struct lastline* ll = (struct lastline*)param; char buf[512]; while (1) { if (fgets(buf, sizeof(buf), ll->file) == 0) { pthread_mutex_lock(&ll->mutex); ll->eof = 1; if (ll->stopping) free(ll); pthread_mutex_unlock(&ll->mutex); return 0; } buf[sizeof(buf)-1] = '\\0'; pthread_mutex_lock(&ll->mutex); if (ll->stopping) { free(ll); return 0; } strcpy(ll->buf, buf); pthread_mutex_unlock(&ll->mutex); } } struct lastline* lastline_start(FILE* file) { struct lastline* ll = (struct lastline*)malloc(sizeof(struct lastline)); if (ll == 0) goto exit; pthread_mutex_init(&ll->mutex, 0); ll->stopping = 0; ll->eof = 0; ll->buf[0] = '\\0'; ll->file = file; pthread_t reader; if (pthread_create(&reader, 0, &reader_thread, ll) != 0) goto free; pthread_detach(reader); return ll; free: free(ll); exit: return 0; } void lastline_stop(struct lastline* ll) { pthread_mutex_lock(&ll->mutex); if (ll->eof) { free(ll); return; } ll->stopping = 1; pthread_mutex_unlock(&ll->mutex); } void lastline_get(struct lastline* ll, char* buf, int n) { pthread_mutex_lock(&ll->mutex); strncpy(buf, ll->buf, n); pthread_mutex_unlock(&ll->mutex); } int lastline_eof(struct lastline* ll) { pthread_mutex_lock(&ll->mutex); int r = ll->eof; pthread_mutex_unlock(&ll->mutex); return r; }
0
#include <pthread.h> int count, commit; pthread_t DPW_recv_f_t, DPW_recv_m_t[NUM_M], DPW_recv_b_t, DPW_send_b_t; pthread_mutex_t save_mutex; struct log_data *list; static struct timespec DPW_DA_begin_time; void *DPW_recv_f_task(void *arg); void *DPW_recv_m_task(void *arg); void *DPW_recv_b_task(void *arg); void *DPW_send_b_task(void *arg); int main(int argc, char **argv) { int i, tmp_m[NUM_M]; int accepted = 0; if (argc != 2) { printf("Usage: %s type\\n", argv[0]); exit(1); } me = DPW_initialize_cluster(argv[1]); count = 0; commit = 0; list = (struct log_data *) malloc(BUFFER_SIZE * sizeof (struct log_data)); pthread_mutex_init(&save_mutex, 0); if (NTU_listen_unit() < 0) ERROR("listen_unit"); INFO("Start %s", get_name(me)); for (i=F0; i<me; i++){ NTU_connect_unit(i); } NTU_connect_unit(B); while (pthread_create(&DPW_recv_b_t, 0, DPW_recv_b_task, 0) < 0) { WARN("pthread_create DPW_recv_b_t"); } while (pthread_create(&DPW_recv_f_t, 0, DPW_recv_f_task, 0) < 0) { WARN("pthread_create DPW_recv_f_t"); } for (i = 0; i < NUM_M; i++) { tmp_m[i] = i; while (pthread_create(&DPW_recv_m_t[i], 0, DPW_recv_m_task, (void *) &tmp_m[i]) < 0) { WARN("pthread_create DPW_recv_m_t[%d]", i); } } while (pthread_create(&DPW_send_b_t, 0, DPW_send_b_task, 0) < 0) { WARN("pthread_create DPW_send_b_t"); } while (1) { accepted = NTU_accept_unit(); } return 0; } void *DPW_recv_f_task(void *arg) { int protocol; while (1) { if (get_status(F0) == DEAD) continue; if (NTU_recv_unit(F0, &protocol, sizeof (int)) < 0) { continue; } INFO("Recv F that M%d was broken", protocol - 3); } pthread_exit(0); } void *DPW_recv_m_task(void *arg) { int M = M0 + *((int *) arg); struct DPW_result rslt; int index, pre_index; struct timespec start_time, end_time; static int max_diff = 0; int tmp, start; while (1) { if (get_status(M) == DEAD) continue; if (NTU_recv_unit(M, &rslt, DPW_result_size) < 0) continue; INFO("Recv %s id=[%d] count=[%d] hash=[%d] str=[%s]", get_name(M), rslt.id, rslt.count, rslt.hash, rslt.str); tmp = (int) count - (int) rslt.id * 2; if (tmp < 0) tmp = -tmp; if (tmp > max_diff) max_diff = tmp; if (rslt.id < commit) continue; if (rslt.id < 1) clock_gettime(CLOCK_REALTIME, &DPW_DA_begin_time); clock_gettime(CLOCK_REALTIME, &start_time); pthread_mutex_lock(&save_mutex); index = rslt.id % BUFFER_SIZE; pre_index = (rslt.id) - 1; while (rslt.id > 0 && list[pre_index % BUFFER_SIZE].flag == 0) { INFO("Miss data %d", pre_index); pre_index--; if (pre_index < 0) break; } if (pre_index != rslt.id - 1) { pre_index++; start = pre_index; INFO("Ask to resend"); tmp = 1; if (NTU_send_unit(M, &tmp, sizeof (int)) < 0) { } if (NTU_send_unit(M, &start, sizeof (int)) < 0) { } pre_index = (rslt.id) - 1; if (NTU_send_unit(M, &pre_index, sizeof (int)) < 0) { } } if (list[index].flag == 1 && list[index].t.id != rslt.id) { list[index].flag = 0; } if (list[index].flag == 0 || list[index].flag == 2) { list[index].flag = 1; list[index].t = rslt; list[index].u = M; if (NTU_send_unit(B, &rslt, DPW_result_size) < 0) { } else DEBUG("Send B id=[%d] count=[%d] hash=[%d] str=[%s]", rslt.id, rslt.count, rslt.hash, rslt.str); } else { list[index].flag = 2; if (strcmp(rslt.str, list[index].t.str) != 0 || rslt.hash != list[index].t.hash || rslt.count != list[index].t.count) { INFO("Task %d is different", rslt.id); } else { commit++; INFO("Task %d is commited, commit=[%d]", rslt.id, commit); } } clock_gettime(CLOCK_REALTIME, &end_time); DA_data_analysis(rslt.id, start_time, end_time, DPW_DA_begin_time); fflush(stdout); count++; pthread_mutex_unlock(&save_mutex); } pthread_exit(0); } void *DPW_recv_b_task(void *arg) { int protocol, i; while (1) { if (get_status(B) == DEAD) continue; if (NTU_recv_unit(B, &protocol, sizeof (int)) < 0) { continue; } INFO("Recv B that F was broken"); protocol = 2; for (i = 0; i < NUM_M; i++) { if (NTU_send_unit(M0 + i, &protocol, sizeof (int)) < 0) { } } } pthread_exit(0); } void *DPW_send_b_task(void *arg) { struct DPW_result rslt; while (1) { rslt.id = -1; if (NTU_send_unit(B, &rslt, DPW_result_size) < 0); sleep(1); } pthread_exit(0); }
1
#include <pthread.h> sem_t suma_total; int total = 0; int vect1[1000000]; int vect2[1000000]; pthread_mutex_t lock; struct parametros_hilo{ int min; int max; int suma_temp; }; void prodVect(void* parametros){ struct parametros_hilo* params = (struct parametros_hilo*) parametros; int tmp_suma = 0; for (int i = params->min; i < params->max; ++i) { tmp_suma += vect1[i]*vect2[i]; } pthread_mutex_lock(&lock); total += tmp_suma; pthread_mutex_unlock(&lock); printf("total:%d\\n",total); } int main(int argc, char const *argv[]) { int num; int num1; FILE *mi_archivo1; FILE *mi_archivo2; int numHilos = atoi(argv[3]); pthread_t hilos_ids[numHilos]; mi_archivo1 = fopen(argv[1],"r"); mi_archivo2 = fopen(argv[2],"r"); int i = 0; while(fscanf(mi_archivo1,"%d",&num)>0){ printf("%d\\n", num ); vect1[i] = num; i++; } printf("--------- Fin Vector 1 ---------\\n"); i=0; while(fscanf(mi_archivo2,"%d",&num1)>0){ printf("%d\\n", num1 ); vect2[i] = num1; i++; } printf("--------- Fin Vector 1 ---------\\n"); int porcion = 1000000/numHilos; struct parametros_hilo paramHilo[numHilos]; for (int i = 0; i < numHilos; ++i) { paramHilo[i].min = i*porcion; paramHilo[i].max = (i+1)*porcion; } for (int i = 0; i < numHilos; ++i) { pthread_create(&hilos_ids[i], 0, (void *)prodVect, &paramHilo[i]); } for (int i = 0; i < numHilos; ++i) { pthread_join(hilos_ids[i], 0); } printf("El producto vectorial entre los dos vectores de %d numeros es: %d\\n",1000000,total); return 0; }
0
#include <pthread.h> char ch; int y; int x; }Char; Char chars[20]; int end=0; int good=0; int loss=0; pthread_mutex_t m; void clrscr(){ int i,j; for(i=0;i<LINES;i++){ for(j=0;j<COLS;j++){ if(!end) mvaddch(i,j,' '); else return; } } refresh(); } void * thdShow(void *p){ int i; for(;;){ if(end) return 0; clrscr(); for(i=0;i<sizeof(chars)/sizeof(chars[0]);i++){ if(chars[i].y>=LINES) { pthread_mutex_lock(&m); chars[i].ch='A'+rand()%26; chars[i].y=0; loss++; pthread_mutex_unlock(&m); } if(isupper(chars[i].ch)){ attron(COLOR_PAIR(2)); mvaddch(chars[i].y,chars[i].x-1,' '); mvaddch(chars[i].y,chars[i].x,chars[i].ch); mvaddch(chars[i].y,chars[i].x+1,' '); attroff(COLOR_PAIR(2)); pthread_mutex_lock(&m); chars[i].y++; pthread_mutex_unlock(&m); }else if(chars[i].ch=='*'){ attron(COLOR_PAIR(3)); mvaddch(chars[i].y,chars[i].x-1,'*'); mvaddch(chars[i].y,chars[i].x,chars[i].ch); mvaddch(chars[i].y,chars[i].x+1,'*'); attroff(COLOR_PAIR(3)); pthread_mutex_lock(&m); chars[i].ch='A'+rand()%26; chars[i].y=0; good++; pthread_mutex_unlock(&m); } } mvaddch(LINES-1,COLS/2,' '); refresh(); sleep(1); } } void * thdGet(void *p){ char ch; for(;;){ if(end) return 0; ch=getch(); int i; for(i=0;i<sizeof(chars)/sizeof(chars[0]);i++){ if(toupper(ch)==chars[i].ch){ pthread_mutex_lock(&m); chars[i].ch='*'; pthread_mutex_unlock(&m); break; } } } } void func(int sig){ char buf[20]; mvhline(LINES/2-3,20,'=',COLS-40); sprintf(buf,"Get: %d",good); mvaddstr(LINES/2-1,(COLS-strlen(buf))/2-1,buf); sprintf(buf,"Loss: %d",loss); mvaddstr(LINES/2+1,(COLS-strlen(buf))/2-1,buf); mvhline(LINES/2+3,20,'=',COLS-40); refresh(); end=1; sleep(2); pthread_mutex_destroy(&m); endwin(); exit(0); } int main(){ initscr(); signal(SIGINT,func); start_color(); init_pair(1,COLOR_RED,COLOR_BLACK); init_pair(3,COLOR_YELLOW,COLOR_RED); init_pair(2,COLOR_RED,COLOR_YELLOW); int i; pthread_mutex_init(&m,0); srand(time(0)); for(i=0;i<sizeof(chars)/sizeof(chars[0]);i++){ chars[i].ch='A'+rand()%26; chars[i].y=0; chars[i].x=3*i+15; } pthread_t thd_show,thd_get; pthread_create(&thd_show,0,thdShow,0); pthread_create(&thd_get,0,thdGet,0); pthread_join(thd_show,0); pthread_join(thd_get,0); return 0; }
1
#include <pthread.h> int v[3]; pthread_mutex_t mtx; void* incVars(void *arg) { int i; for(i = 0 ; i < 5 ; ++ i) { int x = rand(); pthread_mutex_lock(&mtx); printf("Thread %lld generated %d\\n", (long long)pthread_self(), x); printf("So the values are: %d %d %d\\n", x % 2, x % 3, x % 5); pthread_mutex_unlock(&mtx); if(x % 2 == 0) { pthread_mutex_lock(&mtx); ++ v[0]; pthread_mutex_unlock(&mtx); } if(x % 3 == 0) { pthread_mutex_lock(&mtx); ++ v[1]; pthread_mutex_unlock(&mtx); } if(x % 5 == 0) { pthread_mutex_lock(&mtx); ++ v[2]; pthread_mutex_unlock(&mtx); } } return 0; } int main() { srand(time(0)); pthread_t t[4]; int i; pthread_mutex_init(&mtx, 0); for(i = 0 ; i < 4 ; ++ i) { pthread_create(&t[i], 0, incVars, 0); } for(i = 0 ; i < 4 ; ++ i) { pthread_join(t[i], 0); } for(i = 0 ; i < 3 ; ++ i) { printf("%d ", v[i]); } printf("\\n"); pthread_mutex_destroy(&mtx); return 0; }
0
#include <pthread.h> pthread_mutex_t mutexes[4]; pthread_cond_t conditionVars[4]; int permits[4]; pthread_t tids[4]; int data = 0; void * Philosopher(void * arg){ int i; i = (int)arg; pthread_mutex_lock(&mutexes[i%4]); while (permits[i%4] == 0) { pthread_cond_wait(&conditionVars[i%4],&mutexes[i%4]); } permits[i%4] = 0; pthread_mutex_unlock(&mutexes[i%4]); pthread_mutex_lock(&mutexes[(i+1)%4]); while (permits[(i+1)%4] == 0) { pthread_cond_wait(&conditionVars[(i+1)%4],&mutexes[(i+1)%4]); } permits[(i+1)%4] = 0; pthread_mutex_unlock(&mutexes[(i+1)%4]); printf("philosopher %d thinks \\n",i); fflush(stdout); pthread_mutex_lock(&mutexes[(i+1)%4]); permits[(i+1)%4] = 1; pthread_cond_signal(&conditionVars[(i+1)%4]); pthread_mutex_unlock(&mutexes[(i+1)%4]); pthread_mutex_lock(&mutexes[i%4]); permits[i%4] = 1; pthread_cond_signal(&conditionVars[i%4]); pthread_mutex_unlock(&mutexes[i%4]); return 0; } void * OddPhilosopher(void * arg){ int i; i = (int)arg; pthread_mutex_lock(&mutexes[(i+1)%4]); while (permits[(i+1)%4] == 0) { pthread_cond_wait(&conditionVars[(i+1)%4],&mutexes[(i+1)%4]); } permits[(i+1)%4] = 0; pthread_mutex_unlock(&mutexes[(i+1)%4]); pthread_mutex_lock(&mutexes[i%4]); while (permits[i%4] == 0) { pthread_cond_wait(&conditionVars[i%4],&mutexes[i%4]); } permits[i%4] = 0; pthread_mutex_unlock(&mutexes[i%4]); printf("philosopher %d thinks\\n",i); fflush(stdout); pthread_mutex_lock(&mutexes[i%4]); permits[i%4] = 1; pthread_cond_signal(&conditionVars[i%4]); pthread_mutex_unlock(&mutexes[i%4]); pthread_mutex_lock(&mutexes[(i+1)%4]); permits[(i+1)%4] = 1; pthread_cond_signal(&conditionVars[(i+1)%4]); pthread_mutex_unlock(&mutexes[(i+1)%4]); return 0; } int main(){ int i; for (i = 0; i < 4; i++) pthread_mutex_init(&mutexes[i], 0); for (i = 0; i < 4; i++) pthread_cond_init(&conditionVars[i], 0); for (i = 0; i < 4; i++) permits[i] = 1; for (i = 0; i < 4 -1; i++){ pthread_create(&tids[i], 0, Philosopher, (void*)(i) ); } pthread_create(&tids[4 -1], 0, OddPhilosopher, (void*)(4 -1) ); for (i = 0; i < 4; i++){ pthread_join(tids[i], 0); } for (i = 0; i < 4; i++){ pthread_mutex_destroy(&mutexes[i]); } for (i = 0; i < 4; i++){ pthread_cond_destroy(&conditionVars[i]); } return 0; }
1
#include <pthread.h> int var = 0; int var2 = 100000; pthread_mutex_t mutex_1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex_2 = PTHREAD_MUTEX_INITIALIZER; void* sumar(); void* restar(); int main(){ pthread_t suma; pthread_t resta; pthread_create(&suma,0,sumar,0); pthread_create(&resta,0,restar,0); pthread_join(suma,0); pthread_join(resta,0); printf("El valor de var es: %d \\n",var); printf("El valor de resta es: %d \\n",var2); return 0; } void* sumar(){ int i; int temp; for (i=0;i<100000;++i){ pthread_mutex_lock(&mutex_1); temp = var; var += 3; pthread_mutex_lock(&mutex_2); var2 = var2 + 1; pthread_mutex_unlock(&mutex_2); pthread_mutex_unlock(&mutex_1); } pthread_exit(0); } void* restar(){ int i; int temp; for (i=0;i<100000;++i){ pthread_mutex_lock(&mutex_1); temp = var; var -= 3; pthread_mutex_lock(&mutex_2); var2 = var2 - 1; pthread_mutex_unlock(&mutex_2); pthread_mutex_unlock(&mutex_1); } pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t the_mutex; pthread_t threads[10]; static void* greeter(); static void* greeter() { int i; for (i = 0; i < 15; i++) { pthread_mutex_lock(&the_mutex); printf("hello "); printf("world!\\n"); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } int main(int argc, char **argv) { int i; pthread_mutex_init(&the_mutex, 0); for (i = 0; i < 10; ++i) pthread_create(&threads[i], 0, greeter, 0); for (i = 0; i < 10; ++i) pthread_join(threads[i], 0); pthread_mutex_destroy(&the_mutex); return 0; }
1
#include <pthread.h> static int iTThreads = 2; static int iRThreads = 1; static int data1Value = 0; static int data2Value = 0; pthread_mutex_t *data1Lock; pthread_mutex_t *data2Lock; void lock(pthread_mutex_t *); void unlock(pthread_mutex_t *); void *funcA(void *param) { pthread_mutex_lock(data1Lock); data1Value = 1; pthread_mutex_unlock(data1Lock); pthread_mutex_lock(data2Lock); data2Value = data1Value + 1; pthread_mutex_unlock(data2Lock); return 0; } void *funcB(void *param) { int t1 = -1; int t2 = -1; pthread_mutex_lock(data1Lock); if (data1Value == 0) { pthread_mutex_unlock(data1Lock); return 0; } t1 = data1Value; pthread_mutex_unlock(data1Lock); pthread_mutex_lock(data2Lock); t2 = data2Value; pthread_mutex_unlock(data2Lock); if (t2 != (t1 + 1)) { fprintf(stderr, "Bug found!\\n"); ERROR: goto ERROR; ; } return 0; } int main(int argc, char *argv[]) { int i,err; if (argc != 1) { if (argc != 3) { fprintf(stderr, "./twostage <param1> <param2>\\n"); exit(-1); } else { sscanf(argv[1], "%d", &iTThreads); sscanf(argv[2], "%d", &iRThreads); } } data1Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t)); data2Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t)); if (0 != (err = pthread_mutex_init(data1Lock, 0))) { fprintf(stderr, "pthread_mutex_init error: %d\\n", err); exit(-1); } if (0 != (err = pthread_mutex_init(data2Lock, 0))) { fprintf(stderr, "pthread_mutex_init error: %d\\n", err); exit(-1); } pthread_t tPool[iTThreads]; pthread_t rPool[iRThreads]; for (i = 0; i < iTThreads; i++) { if (0 != (err = pthread_create(&tPool[i], 0, &funcA, 0))) { fprintf(stderr, "Error [%d] found creating 2stage thread.\\n", err); exit(-1); } } for (i = 0; i < iRThreads; i++) { if (0 != (err = pthread_create(&rPool[i], 0, &funcB, 0))) { fprintf(stderr, "Error [%d] found creating read thread.\\n", err); exit(-1); } } for (i = 0; i < iTThreads; i++) { if (0 != (err = pthread_join(tPool[i], 0))) { fprintf(stderr, "pthread join error: %d\\n", err); exit(-1); } } for (i = 0; i < iRThreads; i++) { if (0 != (err = pthread_join(rPool[i], 0))) { fprintf(stderr, "pthread join error: %d\\n", err); exit(-1); } } return 0; } void lock(pthread_mutex_t *lock) { int err; if (0 != (err = pthread_mutex_lock(lock))) { fprintf(stderr, "Got error %d from pthread_mutex_lock.\\n", err); exit(-1); } } void unlock(pthread_mutex_t *lock) { int err; if (0 != (err = pthread_mutex_unlock(lock))) { fprintf(stderr, "Got error %d from pthread_mutex_unlock.\\n", err); exit(-1); } }
0
#include <pthread.h> char w[8192][8192]; char neww[8192][8192]; int w_X, w_Y; static int count; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static int fin; struct thd_info { pthread_t tid; int beg_idx; int num_cells; }; void init1(int X, int Y) { int i, j; w_X = X, w_Y = Y; for (i=0; i<w_X;i++) for (j=0; j<w_Y; j++) w[j][i] = 0; for (i=0; i<w_X; i++) w[0][i] = 1; for (i=0; i<w_Y; i++) w[i][0] = 1; } void test_init2() { int i, j; w_X = 4; w_Y = 6; for (i=0; i<w_X;i++) for (j=0; j<w_Y; j++) w[j][i] = 0; w[0][3] = 1; w[1][3] = 1; w[2][1] = 1; w[3][0] = w[3][1] = w[3][2] = w[4][1] = w[5][1] = 1; } void print_world() { int i, j; for (i=0; i<w_Y; i++) { for (j=0; j<w_X; j++) { printf("%d", (int)w[i][j]); } printf("\\n"); } } int neighborcount(int x, int y) { int ncount = 0; if ((x<0) || (x >=w_X)) { printf("neighborncount: (%d %d) out of bound (0..%d, 0..%d).\\n", x,y, w_X, w_Y); exit(0); } if ((y<0) || (y >=w_Y)) { printf("neighborncount: (%d %d) out of bound (0..%d, 0..%d).\\n", x,y, w_X, w_Y); exit(0); } if (x==0) { if (y == 0) { ncount = w[y][x+1] + w[y+1][x] + w[y+1][x+1]; } else if (y == w_Y-1) { ncount = w[y][x+1] + w[y-1][x] + w[y-1][x+1]; } else { ncount = w[y-1][x] + w[y+1][x] + w[y-1][x+1] + w[y][x+1] + w[y+1][x+1]; } } else if (x == w_X -1) { if (y == 0) { ncount = w[y][x-1] + w[y+1][x-1] + w[y+1][x]; } else if (y == w_Y-1) { ncount = w[y][x-1] + w[y-1][x] + w[y-1][x-1]; } else { ncount = w[y-1][x] + w[y+1][x] + w[y-1][x-1] + w[y][x-1] + w[y+1][x-1]; } } else { if (y == 0) { ncount = w[y][x-1] + w[y][x+1] + w[y+1][x-1] + w[y+1][x] + w[y+1][x+1]; } else if (y == w_Y-1) { ncount = w[y][x-1] + w[y][x+1] + w[y-1][x-1] + w[y-1][x] + w[y-1][x+1]; } else { ncount = w[y-1][x-1] + w[y][x-1] + w[y+1][x-1] + w[y-1][x] + w[y+1][x] + w[y-1][x+1] + w[y][x+1] + w[y+1][x+1]; } } return ncount; } void *update_table(void *arg) { struct thd_info my = *((struct thd_info *)arg); int i, x, y, c, loc_count = 0; x = my.beg_idx % w_X; y = my.beg_idx / w_X; for (i = 0; i < my.num_cells; ++i) { c = neighborcount(x, y); if (c <= 1) neww[y][x] = 0; else if (c >=4) neww[y][x] = 0; else if (c == 3) neww[y][x] = 1; else neww[y][x] = w[y][x]; ++x; if (x == w_X) { x = 0; ++y; } } pthread_mutex_lock(&mutex); ++fin; pthread_mutex_unlock(&mutex); while(1) { pthread_mutex_lock(&mutex); if (fin == 8) break; pthread_mutex_unlock(&mutex); } pthread_mutex_unlock(&mutex); x = my.beg_idx % w_X; y = my.beg_idx / w_X; for (i = 0; i < my.num_cells; ++i) { w[y][x] = neww[y][x]; loc_count += (w[y][x] == 1); ++x; if (x == w_X) { x = 0; ++y; } } pthread_mutex_lock(&mutex); count += loc_count; pthread_mutex_unlock(&mutex); return 0; } int main(int argc, char *argv[]) { int x, y; int iter = 0; int c; int init_count; int start_cell; int cells_per_thd; int extra_cells; struct thd_info thd_data[8]; if (argc == 1) { printf("Usage: ./a.out w_X w_Y\\n"); exit(0); } else if (argc == 2) test_init2(); else init1(atoi(argv[1]), atoi(argv[2])); c = 0; for (x=0; x<w_X; x++) { for (y=0; y<w_Y; y++) { if (w[y][x] == 1) c++; } } init_count = c; count = init_count; printf("initial world, population count: %d\\n", c); if (0 > 10) print_world(); cells_per_thd = (w_X * w_Y) / 8; extra_cells = (w_X * w_Y) % 8; for (iter = 0; (iter < 200) && (count <50*init_count) && (count > init_count / 50); iter ++) { fin = start_cell = count = 0; for (x=0; x < 8; x++) { thd_data[x].beg_idx = start_cell; thd_data[x].num_cells = cells_per_thd; if (x < extra_cells) { ++start_cell; ++(thd_data[x].num_cells); } pthread_create(&(thd_data[x].tid), 0, &update_table, &thd_data[x]); start_cell += cells_per_thd; } for (x=0; x < 8; x++) pthread_join(thd_data[x].tid, 0); printf("iter = %d, population count = %d\\n", iter, count); if (0 > 10) print_world(); } { FILE *fd; if ((fd = fopen("final_world000.txt", "w")) != 0) { for (x=0; x<w_X; x++) { for (y=0; y<w_Y; y++) { fprintf(fd, "%d", (int)w[y][x]); } fprintf(fd, "\\n"); } } else { printf("Can't open file final_world000.txt\\n"); exit(1); } } return 0; }
1
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER; void* thr_fn(void* arg) { int err, signo; for (; ;) { err = sigwait(&mask, &signo); if (err != 0) { printf("sign wait error\\n"); } switch (signo) { case SIGINT: printf("\\ninterrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&waitloc); 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); if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) { printf("ptread_sigmask error\\n"); } err = pthread_create(&tid, 0, thr_fn, 0); if (err != 0) { printf("pthread_create error\\n"); } pthread_mutex_lock(&lock); while (quitflag == 0) { pthread_cond_wait(&waitloc, &lock); } pthread_mutex_unlock(&lock); quitflag = 0; if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) { printf("sigprocmask error\\n"); } exit(0); }
0
#include <pthread.h> int data[10],dosignal=0; int nval=0,ndata=0; bool ready; pthread_mutex_t mutex; pthread_cond_t cond; void* producer() { for(;;) { pthread_mutex_lock(&mutex); if(nval > 10) { printf("Buffer is full\\n"); pthread_mutex_unlock(&mutex); return 0; } data[nval]=ndata; nval++; ndata++; ready++; dosignal =1; pthread_mutex_unlock(&mutex); if(dosignal == 1) pthread_cond_signal(&cond); sleep(1); } } void* consumer() { for(;;) { pthread_mutex_lock(&mutex); while(ready ==0) pthread_cond_wait(&cond,&mutex); printf("value[%d] = %d\\n",nval,ndata); ready--; if(nval >10) { return 0; pthread_mutex_unlock(&mutex); } pthread_mutex_unlock(&mutex); } } int main(void) { pthread_t prod,cons; pthread_create(&prod,0,&producer,0); printf("producer generated\\n"); sleep(1); pthread_create(&cons,0,&consumer,0); printf("Consumer generated\\n"); pthread_join(prod,0); pthread_join(cons,0); return 0; }
1
#include <pthread.h> void monitor_leave(struct cart_t* cart) { int i; int j; int signalling; pthread_mutex_lock(&gl_monLock); fprintf(stderr, "[Cart]\\tCart %i from direction %c leaves intersection\\n", cart->num, cart->dir); signalling = 0; for (i = 0; i < 4 && gl_checkOrder[i] != cart->dir; i++); for (j = (i + 1) % 4; j != i && !signalling; j = (j + 1) % 4) { if (q_cartIsWaiting(gl_checkOrder[j])) { signalling = 1; gl_direction = gl_checkOrder[j]; } } if (!signalling) { if (q_cartIsWaiting(gl_direction)) signalling = 1; else gl_direction = '\\0'; } if (signalling) { fprintf(stderr, "[Thread]\\tThread for %c signalling thread for %c\\n", cart->dir, gl_direction); switch (gl_direction) { case Q_NORTH: pthread_cond_signal(&gl_northCond); break; case Q_SOUTH: pthread_cond_signal(&gl_southCond); break; case Q_EAST: pthread_cond_signal(&gl_eastCond); break; case Q_WEST: pthread_cond_signal(&gl_westCond); break; } } pthread_mutex_unlock(&gl_monLock); }
0
#include <pthread.h> int s = 0; pthread_mutex_t mutex; void F() { pthread_mutex_lock(&mutex); s++; pthread_mutex_unlock(&mutex); } void G() { pthread_mutex_lock(&mutex); F(); pthread_mutex_unlock(&mutex); } void *ExecutaTarefa (void *threadid) { int i; int tid = (int) threadid; printf("Thread : %d esta executando...\\n", (int) tid); for (i=0; i<10000000; i++) { G(); } printf("Thread : %d terminou!\\n", (int) tid); pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t tid[2]; int t; pthread_mutexattr_t mutexAttr; if (pthread_mutexattr_init(&mutexAttr)) { printf("--ERRO: pthread_mutexattr_init()\\n"); exit(-1); } if (pthread_mutexattr_settype(&mutexAttr, PTHREAD_MUTEX_RECURSIVE)) { printf("--ERRO: pthread_mutexattr_settype()\\n"); exit(-1); } if (pthread_mutex_init(&mutex, &mutexAttr)) { printf("--ERRO: pthread_mutex_init()\\n"); exit(-1); } for(t=0; t<2; t++) { printf("--Cria a thread %d\\n", t); if (pthread_create(&tid[t], 0, ExecutaTarefa, (void *)t)) { printf("--ERRO: pthread_create()\\n"); exit(-1); } } for (t=0; t<2; t++) { if (pthread_join(tid[t], 0)) { printf("--ERRO: pthread_join() \\n"); exit(-1); } } printf("Valor de s = %d\\n", s); pthread_exit(0); }
1
#include <pthread.h> double balance; pthread_mutex_t mutex; } account; account joint; const char* delimiter_character_line; const char* delimiter_character_col; void read_balance(char *c_id) { printf("Customer %s reads balance:%lf\\n", c_id, joint.balance); fflush(stdout); } void deposit(char *c_id, double amount) { joint.balance += amount; printf("Customer %s deposited amount:%lf\\n", c_id, amount); fflush(stdout); } void withdraw(char *c_id, double amount) { if(joint.balance >= amount) { joint.balance -= amount; printf("Customer %s withdrawed amount:%lf\\n", c_id, amount); } fflush(stdout); } void *customer(void *arg) { int index = (intptr_t)arg; char *f_name = malloc(sizeof(char) * 10); sprintf(f_name, "%d", index); f_name = strcat(f_name, ".txt"); FILE *fc; fc = fopen(f_name, "r"); char line[1024]; char *c_id; int flag = 0; char *instruction, *value; while(fgets(line, 1024, fc)) { char *token_for_line = (char *)strtok(line, delimiter_character_line); if (!flag) { c_id = strdup(token_for_line); flag = 1; continue; } char *line_ptr = strdup(token_for_line); char *token_for_column = (char *)strtok(line_ptr, delimiter_character_col); instruction = strdup(token_for_column); token_for_column = (char *)strtok(0, delimiter_character_col); value = strdup(token_for_column); if(!strcmp(instruction, "Read")) { pthread_mutex_lock(&joint.mutex); read_balance(c_id); pthread_mutex_unlock(&joint.mutex); } else if(!strcmp(instruction, "Deposit")) { pthread_mutex_lock(&joint.mutex); deposit(c_id, atof(value)); pthread_mutex_unlock(&joint.mutex); } else if(!strcmp(instruction, "Withdraw")) { pthread_mutex_lock(&joint.mutex); withdraw(c_id, atof(value)); pthread_mutex_unlock(&joint.mutex); } sleep(1); } fclose(fc); } int main() { joint.balance = 0; delimiter_character_col = " "; delimiter_character_line = "\\n"; pthread_t customer_thread; int index; pthread_mutex_init(&joint.mutex, 0); for (index = 1; index <= 3; index++) { pthread_create(&customer_thread, 0, customer, (void *)(intptr_t)index); } pthread_exit(0); return 0; }
0
#include <pthread.h> unsigned int gSharedValue = 100; pthread_mutex_t gSharedMemoryLock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t readPhase = PTHREAD_COND_INITIALIZER; pthread_cond_t writePhase = PTHREAD_COND_INITIALIZER; int waitingReaders = 0; int activeReaders = 0; int main(int argc, char** argv){ int readerNum[4]; int writerNum[4]; pthread_t readerThreadIDs[4]; pthread_t writerThreadIDs[4]; int i = 0; srandom((unsigned int)time(0)); for (i = 0; i < 4; i++){ readerNum[i] = i; pthread_create(&readerThreadIDs[i], 0, readerMain, &readerNum[i]); } for (i = 0; i < 4; i++){ writerNum[i] = i; pthread_create(&writerThreadIDs[i], 0, writerMain, &writerNum[i]); } for (i = 0; i < 4; i++){ pthread_join(readerThreadIDs[i], 0); } for (i = 0; i < 4; i++){ pthread_join(writerThreadIDs[i], 0); } return 0; } void* readerMain(void* threadArgument){ int id = *((int*)threadArgument); int numReaders = 0; int i = 0; for (i = 0;i < 4; i++){ usleep(1000 * (random()%4 + 4)); pthread_mutex_lock(&gSharedMemoryLock); waitingReaders++; while (activeReaders == -1) pthread_cond_wait(&readPhase, &gSharedMemoryLock); waitingReaders--; numReaders = ++activeReaders; pthread_mutex_unlock(&gSharedMemoryLock); fprintf(stdout, "[r%d] reading %u [active readers:%2d][waiting readers:%2d]\\n", id, gSharedValue, numReaders, waitingReaders); pthread_mutex_lock(&gSharedMemoryLock); activeReaders--; if (activeReaders == 0) pthread_cond_signal(&writePhase); pthread_mutex_unlock(&gSharedMemoryLock); } pthread_exit(0); } void* writerMain(void* threadArgument){ int id = *((int*)threadArgument); int numReaders = 0; int i = 0; for (i = 0; i < 4; i++){ usleep(1000 * (random()%4 + 4)); pthread_mutex_lock(&gSharedMemoryLock); while (activeReaders != 0) pthread_cond_wait(&writePhase, &gSharedMemoryLock); activeReaders = -1; numReaders = activeReaders; pthread_mutex_unlock(&gSharedMemoryLock); fprintf(stdout, "[w%d] writing %u* [active readers:%2d][waiting readers:%2d]\\n", id, ++gSharedValue, numReaders, waitingReaders); pthread_mutex_lock(&gSharedMemoryLock); activeReaders = 0; if (waitingReaders > 0) pthread_cond_broadcast(&readPhase); else pthread_cond_signal(&writePhase); pthread_mutex_unlock(&gSharedMemoryLock); } pthread_exit(0); }
1
#include <pthread.h> volatile int nShared = 0; pthread_mutex_t verrou; pthread_cond_t condEmpty; void* decr(void* ptr) { char* msg = (char*) ptr; int count = 10000; while(count>0) { pthread_mutex_lock(&verrou); while(nShared<=0) { pthread_cond_wait(&condEmpty, &verrou); printf("%s waits nShared become non-zero (%d)\\n", msg, nShared); } nShared--; pthread_mutex_unlock(&verrou); count--; printf("%s decreased 1 to %d\\n", msg, nShared); } return 0; } void* incr(void* ptr) { char* msg = (char*) ptr; int count = 10000; while(count>0) { pthread_mutex_lock(&verrou); nShared++; pthread_cond_broadcast(&condEmpty); pthread_mutex_unlock(&verrou); count--; printf("%s increased 1 to %d\\n", msg, nShared); } return 0; } double time_diff(struct timeval x , struct timeval y) { double x_ms , y_ms , diff; x_ms = (double)x.tv_sec*1000000 + (double)x.tv_usec; y_ms = (double)y.tv_sec*1000000 + (double)y.tv_usec; diff = (double)y_ms - (double)x_ms; return diff; } int main (int argc, char* argv[]) { struct timeval before , after; gettimeofday(&before , 0); pthread_t t1, t2; char* pName1 = "Thread 1"; char* pName2 = "Thread 2"; pthread_cond_init(&condEmpty, 0); pthread_mutex_init(&verrou, 0); int rc1 = pthread_create(&t1, 0, incr, (void*)pName1 ); int rc2 = pthread_create(&t2, 0, decr, (void*)pName2 ); pthread_join(t1, 0); pthread_join(t2, 0); gettimeofday(&after , 0); printf("Final result=%d. Time=%f\\n", nShared, time_diff(before, after)); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; struct timespec timeout; int use_timeout; void *run(void *arg) { int retcode; printf("in child: sleeping\\n"); sleep(2); if (use_timeout) { retcode = pthread_mutex_timedlock(&mutex, &timeout); } else { retcode = pthread_mutex_lock(&mutex); } handle_thread_error(retcode, "child failed (timed)lock", PROCESS_EXIT); printf("child got mutex\\n"); sleep(5); printf("child releases mutex\\n"); pthread_mutex_unlock(&mutex); printf("child released mutex\\n"); sleep(10); printf("child exiting\\n"); return 0; } void usage(char *argv0, char *msg) { printf("%s\\n\\n", msg); printf("Usage:\\n\\n%s\\n lock mutexes without lock\\n\\n%s -t <number>\\n lock mutexes with timout after given number of seconds\\n", argv0, argv0); exit(1); } int main(int argc, char *argv[]) { int retcode; if (is_help_requested(argc, argv)) { usage(argv[0], ""); } use_timeout = (argc >= 2 && strcmp(argv[1], "-t") == 0); time_t tv_sec = (time_t) 200; long tv_nsec = (long) 0; if (use_timeout && argc >= 3) { int t = atoi(argv[2]); tv_sec = (time_t) t; } struct timespec timeout = get_future(tv_sec, tv_nsec); pthread_t thread; pthread_create(&thread, 0, run, 0); printf("in parent: setting up\\n"); pthread_mutexattr_t mutex_attr; pthread_mutexattr_init(&mutex_attr); pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&mutex, &mutex_attr); sleep(2); printf("in parent: getting mutex\\n"); if (use_timeout) { retcode = pthread_mutex_timedlock(&mutex, &timeout); } else { retcode = pthread_mutex_lock(&mutex); } handle_thread_error(retcode, "parent failed (timed)lock", PROCESS_EXIT); printf("parent got mutex\\n"); sleep(5); printf("parent releases mutex\\n"); pthread_mutex_unlock(&mutex); printf("parent released mutex\\n"); printf("parent waiting for child to terminate\\n"); pthread_join(thread, 0); pthread_mutex_destroy(&mutex); pthread_mutexattr_destroy(&mutex_attr); printf("done\\n"); exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex, mutex2, mutex3; time_t init_time; int cnt, cnt2; void espera_activa( int tiempo) { time_t t; t = time(0) + tiempo; while(time(0) < t); } int get_the_time(){ return (time(0) - init_time); } void *tareaA( void * args) { printf("%d::A::voy a dormir\\n", get_the_time()); sleep(3); printf("%d::A::me despierto y pillo mutex\\n", get_the_time()); pthread_mutex_lock(&mutex); printf("%d::A::incremento valor\\n", get_the_time()); ++cnt; printf("%d::A::desbloqueo mutex\\n", get_the_time()); pthread_mutex_unlock(&mutex); printf("%d::A::FINISH\\n", get_the_time()); } void *tareaM( void * args) { printf("\\t%d::M::me voy a dormir\\n", get_the_time()); sleep(2); printf("\\t%d::M::me despierto y pillo mutex2\\n", get_the_time()); pthread_mutex_lock(&mutex2); printf("\\t%d::M::pillo mutex3\\n", get_the_time()); pthread_mutex_lock(&mutex3); printf("\\t%d::M::incremento variable cnt2\\n", get_the_time()); ++cnt2; printf("\\t%d::M::libero mutex3\\n", get_the_time()); pthread_mutex_unlock(&mutex3); printf("\\t%d::M::libero mutex2\\n", get_the_time()); pthread_mutex_unlock(&mutex2); printf("\\t%d::M::FINSIH\\n", get_the_time()); } void *tareaB( void * args) { printf("\\t\\t%d::B::me voy a dormir\\n", get_the_time()); sleep(1); printf("\\t\\t%d::B::me despierto y pillo mutex3\\n", get_the_time()); pthread_mutex_lock(&mutex3); printf("\\t\\t%d::B::espera activa\\n", get_the_time()); espera_activa(3); printf("\\t\\t%d::B::pillo mutex2\\n", get_the_time()); pthread_mutex_lock(&mutex2); printf("\\t\\t%d::B::incremento cnt2\\n", get_the_time()); ++cnt2; printf("\\t\\t%d::B::suelto mutex2\\n", get_the_time()); pthread_mutex_unlock(&mutex2); printf("\\t\\t%d::B::suelto mutex3\\n", get_the_time()); pthread_mutex_unlock(&mutex3); printf("\\t\\t%d::B::FINISH\\n", get_the_time()); } int main() { pthread_t hebraA, hebraM, hebraB; pthread_attr_t attr; pthread_mutexattr_t attrM, attrM2, attrM3; struct sched_param prio; time( &init_time); cnt = 0; cnt2 = 0; printf("===DEBUG MODO \\"ON\\"===\\nEXEC_TIME::THREAD_TAG::VERBOSE_INFO\\n\\n"); pthread_mutexattr_init(&attrM); pthread_mutexattr_init(&attrM2); pthread_mutexattr_init(&attrM3); if( pthread_mutexattr_setprotocol(&attrM, PTHREAD_PRIO_PROTECT) != 0) { printf("ERROR en __set_protocol\\n"); exit(-1); } if( pthread_mutexattr_setprioceiling(&attrM, 3) != 0){ printf("ERROR en __setprioceiling\\n"); } if( pthread_mutexattr_setprotocol(&attrM2, PTHREAD_PRIO_PROTECT) != 0) { printf("ERROR en __set_protocol\\n"); exit(-1); } if( pthread_mutexattr_setprioceiling(&attrM2, 2) != 0){ printf("ERROR en __setprioceiling\\n"); } if( pthread_mutexattr_setprotocol(&attrM3, PTHREAD_PRIO_PROTECT) != 0) { printf("ERROR en __set_protocol\\n"); exit(-1); } if( pthread_mutexattr_setprioceiling(&attrM3, 2) != 0){ printf("ERROR en __setprioceiling\\n"); } pthread_mutex_init(&mutex, &attrM); pthread_mutex_init(&mutex2, &attrM2); pthread_mutex_init(&mutex3, &attrM3); if( pthread_attr_init( &attr) != 0) { printf("ERROR en __attr_init\\n"); exit(-1); } if( pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED) != 0){ printf("ERROR __setinheritsched\\n"); exit(-1); } if( pthread_attr_setschedpolicy( &attr, SCHED_FIFO) != 0) { printf("ERROR __setschedpolicy\\n"); exit(-1); } int error; prio.sched_priority = 1; if( pthread_attr_setschedparam(&attr, &prio) != 0) { printf("ERROR __attr_setschedparam %d\\n", error); exit(-1); } if( (error=pthread_create(&hebraB, &attr, tareaB, 0)) != 0) { printf("ERROR __pthread_create \\ttipo: %d\\n", error); exit(-1); } prio.sched_priority = 2; if( pthread_attr_setschedparam(&attr, &prio) != 0) { printf("ERROR __attr_setschedparam\\n"); exit(-1); } if( pthread_create(&hebraM, &attr, tareaM, 0) != 0) { printf("ERROR __pthread_create\\n"); exit(-1); } prio.sched_priority = 3; if( pthread_attr_setschedparam(&attr, &prio) != 0) { printf("ERROR __attr_setschedparam\\n"); exit(-1); } if( pthread_create(&hebraA, &attr, tareaA, 0) != 0) { printf("ERROR __pthread_create\\n"); exit(-1); } pthread_join(hebraA, 0); pthread_join(hebraM, 0); pthread_join(hebraB, 0); return 0; }
0
#include <pthread.h> struct job { struct job *next; }; struct job* job_queue; pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER; sem_t job_queue_count; void *initialize_job_queue() { job_queue = 0; sem_init(&job_queue_count, 0, 0); } void *thread_function(void *arg) { while(1) { struct job *next_job; sem_wait(&job_queue_count); pthread_mutex_lock(&job_queue_mutex); next_job = job_queue; job_queue = job_queue->next; pthread_mutex_unlock(&job_queue_mutex); process_job(next_job); free(next_job); } return 0; } void enqueue_job( ) { struct job *new_job; new_job = (struct job*)malloc(sizeof(struct job)); pthread_mutex_lock(&job_queue_mutex); new_job ->next = job_queue; job_queue = new_job; sem_post(&job_queue_count); pthread_mutex_unlock(&job_queue_mutex); }
1
#include <pthread.h> char buf[1024]; pthread_mutex_t g_mutex; pthread_cond_t g_cond; void *input_buffer(void *arg) { int index = 0; while(1) { pthread_mutex_lock(&g_mutex); sprintf(buf, "%d number", index); printf("[%s][%d] >\\n", __func__, index++); pthread_cond_signal(&g_cond); pthread_mutex_unlock(&g_mutex); if(strncmp(buf,"quit",4) == 0) break; sleep(1); } pthread_exit(0); } void *output_buffer(void *arg) { int index = 0; while(1) { pthread_mutex_lock(&g_mutex); pthread_cond_wait(&g_cond, &g_mutex); printf("[%s][%d] %s.\\n", __func__, index++, buf); pthread_mutex_unlock(&g_mutex); if(strncmp(buf,"quit",4) == 0) break; } pthread_exit(0); } int main() { int res; pthread_t tid[2]; int *pvalue; int a = 100; pthread_mutex_init(&g_mutex, 0); pthread_cond_init(&g_cond, 0); res = pthread_create(&tid[0],0,input_buffer,(void *)&a); if(res != 0){ perror("Fail to pthread create"); exit(1); } res = pthread_create(&tid[1],0,output_buffer,0); if(res != 0){ perror("Fail to pthread create"); exit(1); } pthread_join(tid[0],0); pthread_join(tid[1],(void *)&pvalue); pthread_mutex_destroy(&g_mutex); pthread_cond_destroy(&g_cond); exit(1); }
0
#include <pthread.h> pthread_t *tab; int valeur = 0; int val_thread_max = 0; int val_thread_courant = 0; int condition =0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void *funcThread(void *arg){ pthread_mutex_lock(&mutex); val_thread_courant++; valeur += (int) (10*((double)rand())/ 32767); printf("Valeur de val : %d\\n",valeur); if(val_thread_courant == val_thread_max){ 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",valeur); pthread_exit((void*)0); return 0; } int main(int argc, char *argv[]) { int i = 0; int *pi; int *valeur; if(argc != 2) return 1; val_thread_max = atoi(argv[1]); tab = malloc((atoi(argv[1])+1)*sizeof(pthread_t)); pthread_create(&tab[0],0,funcAttente,(void *)0); for (i =1;i<atoi(argv[1])+1;i++) { pi = malloc(sizeof(int)); *pi = i; pthread_create(&tab[i],0,funcThread,pi); } for (i =1;i<atoi(argv[1])+1;i++) { if(pthread_join(tab[i],(void**)&valeur) !=0){ printf("pthread_join\\n"); exit(1); } } }
1
#include <pthread.h> pthread_mutex_t lock; pthread_mutex_t lock2; int value; int value2; sem_t sem; void *functionWithCriticalSection(int* v2) { pthread_mutex_lock(&(lock)); pthread_mutex_lock(&(lock2)); value = value2 + *v2; value2 = value; pthread_mutex_unlock(&(lock2)); pthread_mutex_unlock(&(lock)); sem_post(&sem); } void *otherFunctionWithCriticalSection(int* v2) { if (v2 != 0) { pthread_mutex_lock(&(lock)); pthread_mutex_lock(&(lock2)); value = value2 + 1; value2 = value; pthread_mutex_unlock(&(lock2)); pthread_mutex_unlock(&(lock)); } sem_post(&sem); } void *thirdFunctionWithCriticalSection(int* v2) { pthread_mutex_lock(&(lock)); value = value + 1; pthread_mutex_unlock(&(lock)); sem_post(&sem); } int main() { sem_init(&sem, 0, 0); value = 0; value2 = 0; int v2 = 2; pthread_mutex_init(&(lock), 0); pthread_mutex_init(&(lock2), 0); pthread_t thread1; pthread_t thread2; pthread_create (&thread1,0,functionWithCriticalSection,&v2); pthread_create (&thread2,0,otherFunctionWithCriticalSection,&v2); sem_wait(&sem); sem_wait(&sem); pthread_create (&thread1,0,thirdFunctionWithCriticalSection,&v2); pthread_create (&thread2,0,thirdFunctionWithCriticalSection,&v2); sem_wait(&sem); sem_wait(&sem); pthread_mutex_destroy(&(lock)); pthread_mutex_destroy(&(lock2)); sem_destroy(&sem); printf("%d\\n", value); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t notFull; pthread_cond_t notEmpty; int cnt; int first, last; int buf[1]; } buffer; int tot = 0; buffer buf = { .first = 0, .last = 1 -1, .cnt = 0 }; void store(int item, buffer *pb){ pb->buf[(pb->first)+(pb->cnt)%1] = item; pb->cnt = (pb->cnt)+1; } int retrieve(buffer *pb){ int item = pb->buf[pb->first]; pb->cnt = (pb->cnt)-1; pb->first = ((pb->first)+1)%1; pb->last = ((pb->last)+1)%1; return item; } void* producer(void * v){ int j; for (j=0; j<100; j++){ pthread_mutex_lock(&buf.mutex); while (buf.cnt == 1){ pthread_cond_wait(&buf.notFull, &buf.mutex); } store(j, &buf); pthread_cond_signal(&buf.notEmpty); pthread_mutex_unlock(&buf.mutex); printf ("producer produce %d\\n", j); usleep(rand()%11); } } void* consumer(void * v){ int j=0; while (j< 100 -1){ pthread_mutex_lock(&buf.mutex); while (buf.cnt==0){ pthread_cond_wait(&buf.notEmpty, &buf.mutex); } j = retrieve(&buf); pthread_cond_signal(&buf.notFull); pthread_mutex_unlock(&buf.mutex); tot = tot + j; usleep(rand()%11); } } int main(int argc, char **argv){ pthread_t th[4]; int i; while (1){ pthread_mutex_init(&buf.mutex, 0); pthread_cond_init (&buf.notEmpty, 0); pthread_cond_init (&buf.notFull, 0); for (i = 0; i < 4/2; i++){ pthread_create(&th[i], 0, consumer, 0); } for (i = 4/2; i < 4; i++){ pthread_create(&th[i], 0, producer, 0); } for (i = 0; i < 4; i++){ pthread_join(th[i], 0); } printf ("valeur théorique de tot = %d\\n", ((100*(100 -1))/2)*4/2); printf ("valeur réelle de tot = %d\\n", tot); tot = 0; sleep(3); } return 0; }
1
#include <pthread.h> struct dane { int start; int koniec; }; struct wynik_programu { int primes[500]; int curr_p; pthread_mutex_t m; }wynik; void *f( void *i ) { struct dane *dana = i; int start = dana->start; int koniec = dana->koniec; int j, k; for ( j = start; j < koniec; j++) { for( k = 2; k <= j; k++) { if( j % k == 0 ) break; } if ( k == j ) { pthread_mutex_lock(&wynik.m); wynik.primes[wynik.curr_p] = j; wynik.curr_p++; pthread_mutex_unlock(&wynik.m); } } } int main() { int liczba_watkow = 10; int liczba_ostatnia = 500; pthread_t w[10]; struct dane struktura[10]; wynik.curr_p = 0; pthread_mutex_init(&wynik.m, 0); for (int i = 0; i < liczba_watkow; i++) { struktura[i].start = i * liczba_ostatnia / liczba_watkow; struktura[i].koniec = (i + 1) * liczba_ostatnia / liczba_watkow; } for (int i = 0; i < liczba_watkow; i++) { pthread_create( &w[i], 0, f, &struktura[i] ); } for (int i = 0; i < liczba_watkow; i++) { pthread_join (w[i], 0); } for (int i = 0; i < wynik.curr_p; i++) { printf( "Liczba pierwsza %d: %d \\n", i, wynik.primes[i]); } printf( "Liczba liczb pierwszych: %d \\n", wynik.curr_p); pthread_mutex_destroy(&wynik.m); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; void * thread_body(void * param) { int i; pthread_mutex_lock(&mutex); pthread_cond_signal(&cond); for (i = 0; i < 10; ++i) { pthread_cond_wait(&cond, &mutex); printf("Child : %d\\n", i); pthread_cond_signal(&cond); } pthread_mutex_unlock(&mutex); return 0; } int main(int argc, char *argv[]) { pthread_t thread; pthread_mutexattr_t attr; pthread_cond_init(&cond, 0); pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); pthread_mutex_init(&mutex, &attr); int code; int i; code = pthread_create(&thread, 0, thread_body, 0); if (code!=0) { char buf[256]; strerror_r(code, buf, sizeof buf); fprintf(stderr, "%s: creating thread: %s\\n", argv[0], buf); exit(1); } pthread_mutex_lock(&mutex); for (i = 0; i < 10; ++i) { pthread_cond_wait(&cond, &mutex); printf("Parent %d\\n", i); pthread_cond_signal(&cond); } pthread_mutex_unlock(&mutex); pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> pthread_mutex_t locki[32]; int inode[32]; pthread_mutex_t lockb[26]; int busy[26]; void* thread(void* arg) { int i = (*(int*)arg) % 32; pthread_mutex_lock(locki + i); if (inode[i] == 0) { int b = (i * 2) % 26; while (1) { pthread_mutex_lock(lockb + b); if (!busy[b]) { busy[b] = 1; inode[i] = b + 1; pthread_mutex_unlock(lockb + b); break; } pthread_mutex_unlock(lockb + b); b = (b + 1) % 26; } } pthread_mutex_unlock(locki + i); pthread_exit(0); } void initialize_inodes() { for (int i = 0; i < 32; ++i) { pthread_mutex_init(locki + i, 0); } } void initialize_blocks() { for (int i = 0; i < 26; ++i) { pthread_mutex_init(lockb + i, 0); } } int main() { initialize_inodes(); initialize_blocks(); pthread_t threads[14]; int tids[14]; for (int i = 0; i < 14; ++i) { tids[i] = i; pthread_create(threads + i, 0, thread, tids + i); } for (int i = 0; i < 14; ++i) { pthread_join(threads[i], 0); } return 0; }
0
#include <pthread.h> struct group { pthread_mutex_t a; pthread_mutex_t b; int v; }; struct group * g ; void functionA(); void functionB(); void * init_fun(); pthread_mutexattr_t mutexAttribute; pid_t get_tid () { return syscall(SYS_gettid); } int main() { int rc1, rc2; pthread_t thread1, thread2; printf("Program started\\n"); g = (struct group * )malloc(sizeof(struct group)); int status = pthread_mutexattr_init (&mutexAttribute); if (status != 0) { } status = pthread_mutexattr_settype(&mutexAttribute, PTHREAD_MUTEX_RECURSIVE_NP); if (status != 0) { } status = pthread_mutex_init(& g->a, &mutexAttribute); if (status != 0) { } status = pthread_mutex_init(& g->b, &mutexAttribute); if (status != 0) { } if( (rc1=pthread_create( &thread1, 0, &init_fun, 0)) ) { printf("Thread creation failed: %d\\n", rc1); } if( (rc2=pthread_create( &thread2, 0, &init_fun, 0)) ) { printf("Thread creation failed: %d\\n", rc2); } pthread_join( thread1, 0); pthread_join( thread2, 0); exit(0); } int lock(pthread_mutex_t * l) { return pthread_mutex_lock(l); } int unlock(pthread_mutex_t * l) { return pthread_mutex_unlock(l); } void *init_fun() { void (* foo)(); int id = get_tid(); if (id % 4 == 0) { printf("Thread %d: functionA\\n", id); foo = &functionA; } else { printf("Thread %d: functionB\\n", id); foo = &functionB; } foo(); return 0; } void functionA() { pthread_mutex_t * k; pthread_mutex_t * l; k = & g->a; l = & g->b; lock( k ); usleep(5000); lock( l ); g->v ++; unlock( l ); unlock( k ); return ; } void functionB() { pthread_mutex_lock( & g->b ); usleep(5000); pthread_mutex_lock( & g->a ); g->v ++; pthread_mutex_unlock( & g->a ); pthread_mutex_unlock( & g->b ); return; }
1
#include <pthread.h> pthread_cond_t prod = PTHREAD_COND_INITIALIZER, cons = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutexP = PTHREAD_MUTEX_INITIALIZER, mutexC = PTHREAD_MUTEX_INITIALIZER; int prod_pos = 0, cons_pos = 0, stock = 0, dataProd = 0, buffer[25]; void * producer (void * arg); void * consumer (void * arg); int main (int argc, char * argv[]) { pthread_t producerThread[5], consumerThread[7]; int i = 0, * idC = 0, * idP = 0; srand (time(0)); for (i = 0; i < 5; i++) { idP = (int *) malloc (sizeof (int)); *idP = i; if (pthread_create (&producerThread[i], 0, producer, (void *) idP)) { printf ("Falha ao criar producerThread numero %d!!\\n", i); return -1; } } for (i = 0; i < 7; i++) { idC = (int *) malloc (sizeof (int)); *idC = i; if (pthread_create (&consumerThread[i], 0, consumer, (void *) idC)) { printf ("Falha ao criar consumerThread numero %d!!\\n", i); return -1; } } pthread_join (consumerThread[0], 0); pthread_join (producerThread[0], 0); return 0; } void * producer (void * arg) { int i = *((int *) arg); while (1) { printf ("Produtor %d: vou produzir um item\\n", i); sleep (2); pthread_mutex_lock (&mutexP); dataProd = rand()%1000 + 1; while (stock == 25) { printf ("Produtor %d: vou esperar espaco no buffer\\n", i); pthread_cond_wait (&prod, &mutexP); } printf ("Produtor %d: Produzindo item...\\n", i); sleep (3); printf ("Produtor %d: vou inserir item %d na posicao %d\\n", i, dataProd, prod_pos); buffer[prod_pos] = dataProd; prod_pos = (prod_pos + 1)%25; stock++; printf ("Dados em estoque: %d\\n\\n", stock); if (stock == 1) pthread_cond_signal (&cons); pthread_mutex_unlock (&mutexP); } pthread_exit (0); } void * consumer (void * arg) { int i = *((int *) arg); int removed = 0; while (1) { pthread_mutex_lock (&mutexC); while (stock == 0) { printf ("Consumidor %d: vou esperar por itens\\n", i); pthread_cond_wait (&cons, &mutexC); } removed = buffer[cons_pos]; printf ("Consumidor %d:\\nDado removido da posicao %d: %d\\n", i, cons_pos, removed); cons_pos = (cons_pos + 1)%25; stock--; printf ("Dados em estoque: %d\\n\\n", stock); if (stock == (25 - 5)) pthread_cond_broadcast (&prod); pthread_mutex_unlock (&mutexC); printf ("Consumidor %d: Consumindo dado: %d\\n", i, removed); sleep (20); } pthread_exit (0); }
0
#include <pthread.h> double *b; double *a; double sum; int veclen; } DOTDATA; DOTDATA dotstr; pthread_t callThr[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 sym = " "%f\\n",offset, start, end, mysum, dotstr.sum ); pthread_mutex_unlock (&mutexsum); pthread_exit((void*) 0) ; } int main() { 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 < 4*100000; 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(&callThr[i], &attr, dotprod, (void*)i); } pthread_attr_destroy(&attr); for(i=0; i<4; i++) { pthread_join(callThr[i], &status); } printf("Sum = %f \\n", dotstr.sum); free(a); free(b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
1
#include <pthread.h> int value, wakeups; Mutex *mutex; Cond *cond; } Semaphore; void *check_malloc(unsigned n) { void *res = malloc(n); assert(res != 0); return res; } Mutex *make_mutex(void) { Mutex *ret = check_malloc(sizeof (Mutex)); pthread_mutex_init(ret, 0); return ret; } Cond *make_cond() { Cond *ret = check_malloc(sizeof (Cond)); pthread_cond_init(ret, 0); return 0; } Semaphore *make_semaphore(int value) { Semaphore *S = check_malloc(sizeof (Semaphore)); S->value = value; S->wakeups = 0; S->mutex = make_mutex(); S->cond = make_cond(); return S; } void sem_wait(Semaphore *s) { pthread_mutex_lock(s->mutex); --s->value; if(s->value < 0) { do pthread_cond_wait(s->cond, s->mutex); while(s->wakeups < 1); s->wakeups--; } pthread_mutex_unlock(s->mutex); } void sem_signal(Semaphore *s) { pthread_mutex_lock(s->mutex); ++s->value; if(s->value <= 0) { ++s->wakeups; pthread_cond_signal(s->cond); } pthread_mutex_unlock(s->mutex); } void *f(void *a) { int id =*(int*)a; for(;;) { sleep(random()%5); sem_wait(5); printf("%d dentro \\n",id); sleep(random()%5); sem_signal(5); printf("%d fuera \\n",id); } return 0; } int main() { pthread_t t[10]; int args [10], i; Semaphore *s = make_semaphore(1); for(i = 0; i < 10; i++) { pthread_create(&t[i],0,f,&arg[i]); } pthread_join(t[0], 0); return 0; }
0
#include <pthread.h> void *agent(); void *tobacco(); void *match(); void *paper(); pthread_mutex_t s_lock, s_agent, s_tobacco,s_paper, s_match; void main(){ pthread_t agent_thread, paper_thread, tobacco_thread, match_thread; int a, b, c, d; pthread_mutex_init(&s_lock, 0); pthread_mutex_init(&s_match, 0); pthread_mutex_init(&s_agent, 0); pthread_mutex_init(&s_paper, 0); pthread_mutex_init(&s_tobacco, 0); pthread_mutex_lock(&s_match); pthread_mutex_lock(&s_agent); pthread_mutex_lock(&s_paper); pthread_mutex_lock(&s_tobacco); a = pthread_create( &agent_thread, 0, &agent,0); if(a) { fprintf(stderr,"Error - pthread_create() return code: %d\\n",a); exit(1); } b = pthread_create( &paper_thread, 0, &paper,0); if(b) { fprintf(stderr,"Error - pthread_create() return code: %d\\n",b); exit(1); } c = pthread_create( &tobacco_thread, 0, &tobacco,0); if(c) { fprintf(stderr,"Error - pthread_create() return code: %d\\n",c); exit(1); } d = pthread_create( &match_thread, 0, &match, 0); if(d) { fprintf(stderr,"Error - pthread_create() return code: %d\\n",d); exit(1); } pthread_join( agent_thread, 0); pthread_join( paper_thread, 0); pthread_join( tobacco_thread, 0); pthread_join( match_thread, 0); pthread_mutex_destroy(&s_lock); pthread_mutex_destroy(&s_match); pthread_mutex_destroy(&s_agent); pthread_mutex_destroy(&s_paper); pthread_mutex_destroy(&s_tobacco); exit(0); } void *agent(){ int n = 10; while(n>0){ n--; pthread_mutex_lock(&s_lock); int randnum = rand()%3+1; printf("agent round %d, random number is %d \\n", 10 -n,randnum); if (randnum == 1){ printf("Put tobacco on table\\n"); printf("Put paper on table\\n"); pthread_mutex_unlock(&s_match); } else if(randnum == 2){ printf("Put tobacco on table\\n"); printf("Put match on table\\n"); pthread_mutex_unlock(&s_paper); } else{ printf(" Put match on table\\n"); printf("Put paper on table\\n"); pthread_mutex_unlock(&s_tobacco); } pthread_mutex_unlock(&s_lock); pthread_mutex_lock(&s_agent); } } void *tobacco(){ int n = 10; while(n>0){ n--; pthread_mutex_lock(&s_tobacco ); pthread_mutex_lock(&s_lock ); printf("Pick up match\\n"); printf("Pick up paper\\n"); pthread_mutex_unlock(&s_agent ); pthread_mutex_unlock(&s_lock ); printf("Smoke (but don't inhale)\\n"); } } void *match(){ int n = 10; while(n>0){ n--; pthread_mutex_lock(&s_match ); pthread_mutex_lock(&s_lock ); printf("Pick up tobacco\\n"); printf("Pick up paper\\n"); pthread_mutex_unlock(&s_agent ); pthread_mutex_unlock(&s_lock ); printf("Smoke (but don't inhale)\\n"); } } void *paper(){ int n = 10; while(n>0){ n--; pthread_mutex_lock(&s_paper ); pthread_mutex_lock(&s_lock ); printf("Pick up match\\n"); printf("Pick up tobacco\\n"); pthread_mutex_unlock(&s_agent ); pthread_mutex_unlock(&s_lock ); printf("Smoke (but don't inhale)\\n"); } }
1
#include <pthread.h>extern void __VERIFIER_error() ; int block; int busy; int inode; pthread_mutex_t m_inode; pthread_mutex_t m_busy; void *allocator(){ pthread_mutex_lock(&m_inode); if(inode == 0){ pthread_mutex_lock(&m_busy); busy = 1; pthread_mutex_unlock(&m_busy); inode = 1; } block = 1; if (!(block == 1)) ERROR: __VERIFIER_error();; pthread_mutex_unlock(&m_inode); return 0; } void *de_allocator(){ pthread_mutex_lock(&m_busy); if(busy == 0){ block = 0; if (!(block == 0)) ERROR: __VERIFIER_error();; } pthread_mutex_unlock(&m_busy); return ((void *)0); } int main() { pthread_t t1, t2; __VERIFIER_assume(inode == busy); pthread_mutex_init(&m_inode, 0); pthread_mutex_init(&m_busy, 0); pthread_create(&t1, 0, allocator, 0); pthread_create(&t2, 0, de_allocator, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_mutex_destroy(&m_inode); pthread_mutex_destroy(&m_busy); return 0; }
0
#include <pthread.h> void slowstop(); void slowstop() { SerCmdGotoEncSync(CNT_LATD, motc.declinazione, 2, 5); SerCmdGotoEncSync(CNT_AR, motc.ascRetta, 10, 5); SerCmdGotoEncSync(CNT_PREC, motc.precessione, 10, 5); } int plazero(void) { lock(); pSharedData->PlaMode = MODE_ZERO; pSharedData->PlaSubMode = AZZERAMENTO; pSharedData->bZeroDone = FALSE; unlock(); pthread_mutex_lock(&mutex_ser); motc.bSearchZeroDecl = motc.bSearchZeroAscR = motc.bSearchZeroPrec = TRUE; pthread_mutex_unlock(&mutex_ser); if (!SerCmdZeroEncSync(CNT_LATD, 5, 15)) { lock(); pSharedData->bNAKlat = TRUE; pSharedData->idError = ERR_PLAZERO_ZEROENC; unlock(); } if (!SerCmdZeroEncSync(CNT_AR, 150, 15)) { lock(); pSharedData->bNAKascr = TRUE; pSharedData->idError = ERR_PLAZERO_ZEROENC; unlock(); } if (!SerCmdZeroEncSync(CNT_PREC, 150, 15)) { lock(); pSharedData->bNAKprec = TRUE; pSharedData->idError = ERR_PLAZERO_ZEROENC; unlock(); } if (pSharedData->idError) { slowstop(); return -1; } while (motc.bSearchZeroDecl || motc.bSearchZeroAscR || motc.bSearchZeroPrec) { sleep_ms(50); updateData(); if (pSharedData->bAbort) { lock(); pSharedData->bAbort = FALSE; pSharedData->bSuspend = FALSE; pSharedData->idError = ERR_ABORTED; unlock(); slowstop(); return -1; } } pthread_mutex_lock(&mutex_ser); motc.bSearchZeroDecl = motc.bSearchZeroAscR = motc.bSearchZeroPrec = TRUE; pthread_mutex_unlock(&mutex_ser); if (!SerCmdZeroEncSync(CNT_LATD, 1, 15)) { lock(); pSharedData->bNAKlat = TRUE; pSharedData->idError = ERR_PLAZERO_ZEROENC2; unlock(); } if (!SerCmdZeroEncSync(CNT_AR, 50, 15)) { lock(); pSharedData->bNAKascr = TRUE; pSharedData->idError = ERR_PLAZERO_ZEROENC2; unlock(); } if (!SerCmdZeroEncSync(CNT_PREC, 50, 15)) { lock(); pSharedData->bNAKprec = TRUE; pSharedData->idError = ERR_PLAZERO_ZEROENC2; unlock(); } if (pSharedData->idError) { slowstop(); return -1; } while (motc.bSearchZeroDecl || motc.bSearchZeroAscR || motc.bSearchZeroPrec) { sleep_ms(50); if (pSharedData->bAbort) { lock(); pSharedData->bAbort = FALSE; pSharedData->bSuspend = FALSE; pSharedData->idError = ERR_ABORTED; unlock(); slowstop(); return -1; } updateData(); } lock(); pSharedData->ar_now = AR_OFFSET; pSharedData->latitude_now = LATD_OFFSET; pSharedData->prec_now = PREC_OFFSET; pSharedData->prec_now_year = pSharedData->prec_now*72.22 + 2000; CalcTime(pSharedData->ar_now, pSharedData->sun_ar, &pSharedData->time_hour, &pSharedData->time_min); unlock(); pthread_mutex_lock(&mutex_ser); pSharedData->bZeroDone = TRUE; motc.ascRettaOffset = 0; pthread_mutex_unlock(&mutex_ser); return 0; }
1
#include <pthread.h> pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; { int f_count; pthread_mutex_t f_lock; int f_id; struct foo *f_next; }foo; foo *fh[29]; foo *foo_alloc(int id) { foo *fp = 0; int idx = 0; if ((fp = (foo *)malloc(sizeof(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); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return (fp); } void foo_hold(foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } foo * foo_find(int id) { foo *fp = 0; pthread_mutex_lock(&hashlock); for(fp = fh[(((unsigned long)id)%29)]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { foo_hold(fp); break; } } pthread_mutex_unlock(&hashlock); return (fp); } void foo_rele(foo *fp) { foo *tfp = 0; int idx = 0; pthread_mutex_lock(&fp->f_lock); if (fp->f_count == 1) { 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); } }
0
#include <pthread.h> void *thread_function(void *arg); pthread_mutex_t work_mutex; char work_area[1024]; int time_to_exit = 0; int main() { int res; pthread_t a_thread; void *thread_result; res = pthread_mutex_init(&work_mutex, 0); if(res != 0){ perror("Mutex initialization failed"); exit(1); } res = pthread_create(&a_thread, 0, thread_function, 0); if(res != 0){ perror("Thread creation failed"); exit(1); } pthread_mutex_lock(&work_mutex); printf("Input some text. Enter 'end' to finish\\n"); while(!time_to_exit){ fgets(work_area, 1024, stdin); pthread_mutex_unlock(&work_mutex); while(1){ pthread_mutex_lock(&work_mutex); if(work_area[0] != '\\0'){ pthread_mutex_unlock(&work_mutex); sleep(1); } 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); } printf("Thread joined\\n"); pthread_mutex_destroy(&work_mutex); exit(0); } void *thread_function(void *arg) { sleep(1); pthread_mutex_lock(&work_mutex); while(strncmp("end", work_area, 3) != 0){ printf("You input %lu characters\\n", strlen(work_area) - 1); work_area[0] = '\\0'; pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); while(work_area[0] == '\\0'){ pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); } } printf("time to exit"); time_to_exit = 1; work_area[0] = '\\0'; pthread_mutex_unlock(&work_mutex); pthread_exit(0); }
1
#include <pthread.h> void *piggy(void *arg); void *read_thread(void *ptr); FILE*file; int num; }ph; ph _p1, _p2, _p3, _p4, _p5; pthread_mutex_t mutex; FILE*hw10; int process=0; int main(void) { pthread_mutex_init(&mutex, 0); FILE*file; int end=0; file = fopen("test.txt", "r"); file = fopen("test.txt", "r"); file = fopen("test.txt", "r"); file = fopen("test.txt", "r"); file = fopen("test.txt", "r"); _p1.file = file; _p2.file = file; _p3.file = file; _p4.file = file; _p5.file = file; _p1.num = 0; _p2.num = 1; _p3.num = 2; _p4.num = 3; _p5.num = 4; pthread_t pig1, pig2, pig3, pig4, pig5; pthread_create(&pig1, 0, (void*)&piggy, (void*)&_p1); pthread_detach(&pig1); pthread_create(&pig2, 0, (void*)&piggy, (void*)&_p2); pthread_detach(&pig2); pthread_create(&pig3, 0, (void*)&piggy, (void*)&_p3); pthread_detach(&pig3); pthread_create(&pig4, 0, (void*)&piggy, (void*)&_p4); pthread_detach(&pig4); pthread_create(&pig5, 0, (void*)&piggy, (void*)&_p5); pthread_detach(&pig5); pthread_exit(&end); fclose(file); fclose(file2); fclose(file3); fclose(file4); fclose(file5); return 0; } void *piggy(void *arg){ ph *point; point=((ph*)(arg)); int c; time_t t; srand((unsigned) time(&t)); int r = rand() % 10; int i; pthread_mutex_lock(&mutex); if(process%5!=point->num) { } else { pthread_mutex_unlock(&mutex); hw10 = fopen("hw10.out", "a"); for (i = 1; i < r; i++) { c=fgetc(point->file); printf("Num:%d %c\\n",point->num, c); fputc(c, hw10); } fclose(hw10); process++; } pthread_mutex_unlock(&mutex); }
0
#include <pthread.h> { int id; int seed; int meter; } parameters; pthread_mutex_t mutex_lock; sem_t students_sem; sem_t ta_sem; int waiting_students; int seat[2]; void *doTA(); void *doStudent(); int main(int argc, char *argv[]){ printf("CS149 Sleeping TA from Yehia Qtaish\\n"); sem_init(&students_sem, 0, 0); sem_init(&ta_sem, 0, 1); pthread_mutex_init(&mutex_lock, 0); pthread_attr_t attr; pthread_attr_init(&attr); pthread_t tid[4]; pthread_t tid0; parameters data[4]; waiting_students = 0; pthread_create(&tid0,&attr,doTA,0); int k; for(k=0; k<4; k++) { data[k].id = k+1; pthread_create(&tid[k],&attr,doStudent,&data[k]); } for (k=1; k<=4; k++) { pthread_join(tid[k],0); } pthread_cancel(tid0); } void *doTA(void *data) { int seed = -1; while (1) { sem_wait(&students_sem); while (waiting_students > 0) { sem_post(&ta_sem); pthread_mutex_lock(&mutex_lock); int sid = seat[0]; for (int i=1; i<waiting_students; i++) seat[i-1]=seat[i]; waiting_students--; pthread_mutex_unlock(&mutex_lock); int w = (rand_r(&seed) % 3) + 1; sleep(w); } } } void *doStudent(void *param) { parameters *data = (parameters *) param; data->seed = data->id; data->meter = 2; while (data->meter > 0) { int w = (rand_r(&data->seed) % 3) + 1; printf("\\tStudent %d programming for %d seconds\\n", data->id, w); pthread_mutex_lock(&mutex_lock); if (waiting_students == 0) { sem_wait(&ta_sem); printf("Student %d receiving help\\n", data->id); data->meter--; sem_post(&students_sem); } else if (waiting_students < 2) { seat[waiting_students++] = data->id; } else { printf("\\t\\t\\tStudent %d will try later\\n", data->id); } pthread_mutex_unlock(&mutex_lock); } pthread_exit(0); }
1
#include <pthread.h> void add_oxygen_atom_to_air(void); void * active_carbon_atoms(void *); pthread_mutex_t lock; int oxygen_atoms = 0; int co2_count; int O_inAir = 0; void add_carbon_dioxyde(void) { co2_count ++; } void * generate_oxygen(void * dummy) { int i; for(i=0; i < 10*2; i++) { oxygen_atoms ++; add_oxygen_atom_to_air(); usleep(rand() % 21); } pthread_exit(0); } void add_oxygen_atom_to_air() { pthread_mutex_lock(&lock); O_inAir++; pthread_mutex_unlock(&lock); } void * activate_carbon_atoms() { int type; pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &type); while(1) { pthread_mutex_lock(&lock); if(O_inAir == 2) { add_carbon_dioxyde(); O_inAir-=2; } pthread_mutex_unlock(&lock); } pthread_exit(0); } int main() { pthread_t carbon_threads[20]; int i; for(i=0; i<20; i++) { assert(!pthread_create(&carbon_threads[i], 0, activate_carbon_atoms, 0)); } pthread_t oxygen_thread; assert(!pthread_create(&oxygen_thread, 0, generate_oxygen, 0)); void * dummy; pthread_join(oxygen_thread, &dummy); usleep(100); printf("You code %s\\n", co2_count == 10 ? "Works. Good stuff. Run agin to make sure" : "Does not work. Back to design"); pthread_mutex_destroy(&lock); for(i=0; i<20; i++) pthread_cancel(carbon_threads[i]); pthread_exit(0); return 0; }
0
#include <pthread.h> pthread_mutex_t g_tLock = PTHREAD_MUTEX_INITIALIZER;; pthread_mutex_t g_tLockCVar = PTHREAD_MUTEX_INITIALIZER;; pthread_cond_t g_Cond = PTHREAD_COND_INITIALIZER; static int g_charNumArray[7]={0,0,0,0,0,0,0}; static int g_numChars=0; static char g_myChar=EOF; static char g_myCharString[7]={0,0,0,0,0,0,0}; void * showEyeC(void *p) { int i=0; if ( p ) i = (int) p; printf("start loop with %d \\r\\n",i); while (1) { if (i%2) { pthread_mutex_lock(&g_tLock); printf("%d/ nc = %d",i,g_numChars); } else { pthread_mutex_lock(&g_tLock); printf("\\\\%d nc = %d",i,g_numChars); } pthread_mutex_unlock(&g_tLock); fflush(stdout); printf("\\r \\r"); i++; } return 0; } void * Spell(void *p) { int bSearching=1; while (bSearching) { pthread_mutex_lock(&g_tLockCVar); while (g_myChar!='c' && g_myChar!='a' && g_myChar!='r' && g_myChar!='c' && g_myChar!='m' && g_myChar!='g' ) { pthread_cond_wait(&g_Cond, &g_tLockCVar); } switch (g_myChar) { case 'c': g_myCharString[0]=g_myChar; g_myCharString[3]=g_myChar; g_charNumArray[0]=(g_numChars-1); g_charNumArray[3]=(g_numChars-1); break; case 'a': g_myCharString[1]=g_myChar; g_charNumArray[1]=(g_numChars-1); break; case 'r': g_myCharString[2]=g_myChar; g_charNumArray[2]=(g_numChars-1); break; case 'm': g_myCharString[4]=g_myChar; g_charNumArray[4]=(g_numChars-1); break; case 'g': g_myCharString[5]=g_myChar; g_charNumArray[5]=(g_numChars-1); break; default: break; } pthread_mutex_unlock(&g_tLockCVar); if (!strncmp(g_myCharString,"carcmg",6)) { bSearching=0; } } return 0; } int rotateBits(unsigned short int byte) { int rotatedByte=0; int temp=0,i=0,shift_start=7; printf("rotate 0x%2X\\n",byte); temp = byte&0x1; rotatedByte |= rotatedByte|(temp<<shift_start); for (i=1;i<=3;i++) { shift_start-=2; temp = byte&(1<<i); rotatedByte |= temp<<(shift_start); } shift_start=7; for (i=7;i>=4;i--) { temp = byte&(1<<i); rotatedByte |= temp>>(shift_start); shift_start-=2; } return rotatedByte; } int main (int argc, char * argv[]) { FILE *fp=0; FILE *fp2=0; pthread_t myThreadVar; pthread_t myThreadVar2; if (argc<3) { printf("threads123 - usage : infilename outfilename 1 (to enable debug prints)\\n"); return 0; } printf("opening file %s\\n", argv[1]); fp = fopen(argv[1],"r"); printf("opening file %s\\n", argv[2]); fp2 = fopen(argv[2],"a+"); if (fp && fp2) { printf("success opening files %s and %s\\n", argv[1],argv[2]); if (argv[3] != 0) { pthread_create(&myThreadVar,0,showEyeC,atoi(argv[3])); pthread_create(&myThreadVar2,0,Spell,0); } do { g_myChar = fgetc(fp); if (g_myChar!=EOF) { fputc(g_myChar,fp2); if (g_myChar=='\\n') { fputs("\\r",fp2); } pthread_mutex_lock(&g_tLockCVar); if (g_myChar=='c' || g_myChar=='a' || g_myChar=='r' || g_myChar=='c' || g_myChar=='m' || g_myChar=='g' ) { pthread_cond_signal(&g_Cond); } pthread_mutex_unlock(&g_tLockCVar); pthread_mutex_lock(&g_tLock); g_numChars ++; pthread_mutex_unlock(&g_tLock); } } while (g_myChar!=EOF); fclose(fp); fclose(fp2); } else if ( !fp ) { printf("failed to open file %s\\n", argv[1]); return 0; } else if ( !fp2 ) { printf("failed to open file %s\\n", argv[2]); return 0; } if ( argv[3] != 0 ) { pthread_cancel(myThreadVar); pthread_cancel(myThreadVar2); printf("\\nThreads terminated\\n"); } printf("\\r\\r done with %s. numChars = %d. string = %s\\n", argv[1],g_numChars,g_myCharString); printf("rotated byte = 0x%2X\\n",rotateBits(atoi(argv[3]))); return 1; }
1
#include <pthread.h> pthread_mutex_t mutex1; pthread_mutex_t mutex2; void *thread_A (void *arg) { int random_time; while (1) { srand(time(0)); random_time = rand() % 10; printf("[%s]Sleeping for %d seconds\\n", __FUNCTION__, random_time); sleep(random_time); printf("[%s]Trying to acquire mutex1 (holding none)\\n", __FUNCTION__); pthread_mutex_lock(&mutex1); printf("[%s]Acquired mutex1\\n", __FUNCTION__); random_time = rand() % 10; printf("[%s]Sleeping for %d seconds\\n", __FUNCTION__, random_time); sleep(random_time); printf("[%s]Trying to acquire mutex2 (holding mutex1) \\n", __FUNCTION__); pthread_mutex_lock(&mutex2); printf("[%s]Acquired mutex2\\n\\n", __FUNCTION__); pthread_mutex_unlock(&mutex2); pthread_mutex_unlock(&mutex1); } return 0; } void *thread_B (void *arg) { int random_time; while (1) { srand(time(0)); random_time = rand() % 10; printf("[%s]Sleeping for %d seconds\\n", __FUNCTION__, random_time); sleep(random_time); printf("[%s]Trying to acquire mutex1 (holding none) \\n", __FUNCTION__); pthread_mutex_lock(&mutex1); printf("[%s]Acquired mutex1\\n\\n", __FUNCTION__); random_time = rand() % 10; printf("[%s]Sleeping for %d seconds\\n", __FUNCTION__, random_time); sleep(random_time); printf("[%s]Trying to acquire mutex2 (holding mutex1)\\n", __FUNCTION__); pthread_mutex_lock(&mutex2); printf("[%s]Acquired mutex2\\n", __FUNCTION__); pthread_mutex_unlock(&mutex2); pthread_mutex_unlock(&mutex1); } return 0; } int main () { pthread_t threads[2]; int i; pthread_mutex_init(&mutex1, 0); pthread_mutex_init(&mutex2, 0); for(i=0; i < 2; i++) { if(i%2 == 0) pthread_create(&threads[i], 0, thread_A, 0); else pthread_create(&threads[i], 0, thread_B, 0); } for(i=0; i < 2; i++) pthread_join(threads[i], 0); pthread_mutex_destroy(&mutex1); pthread_mutex_destroy(&mutex2); return 0; }
0
#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*1000*sizeof(double)); b = (double*) malloc (4*1000*sizeof(double)); for (i=0; i<1000*4; i++) { a[i]=1; b[i]=a[i]; } dotstr.veclen = 1000; 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); }
1
#include <pthread.h> int *a, *b; long sum=0; pthread_mutex_t lock; { int counter; int finished; pthread_mutex_t block; pthread_cond_t bcond; } my_barrier_t; my_barrier_t my_barrier; void my_barrier_create(my_barrier_t* barrier,int NUM) { barrier->counter = NUM; barrier->finished = 0; pthread_mutex_init(&barrier->block,0); pthread_cond_init(&barrier->bcond,0); } void my_barrier_wait(my_barrier_t* barrier) { pthread_mutex_lock(&barrier->block); if(--barrier->counter == 0) { barrier->finished = 1; pthread_cond_broadcast(&barrier->bcond); } else { while(!barrier->finished) { pthread_cond_wait(&barrier->bcond,&barrier->block); } } pthread_mutex_unlock(&barrier->block); } void my_barrier_destroy(my_barrier_t* barrier) { pthread_mutex_destroy(&barrier->block); pthread_cond_destroy(&barrier->bcond); } void *dotprod(void *arg) { int i, start, end, offset, len; long tid = (long)arg; long my_sum = 0; double my_part; offset = tid; len = 100000; start = offset*len; end = start + len; printf("thread: %ld starting. start=%d end=%d\\n",tid,start,end-1); for (i=start; i<end ; i++){ pthread_mutex_lock(&lock); my_sum += (a[i] * b[i]); sum += (a[i] * b[i]); pthread_mutex_unlock(&lock); } printf("thread: %ld proceeding to barrier \\n",tid); my_barrier_wait(&my_barrier); my_part = 100*my_sum / sum; printf("thread: %ld done. My part of the Global sum is = %.1lf %% \\n",tid,my_part); pthread_exit((void*) 0); } void init_pthread_variables(){ pthread_mutex_init(&lock,0); my_barrier_create(&my_barrier, 8); } int main (int argc, char *argv[]) { long i; void *status; pthread_t threads[8]; pthread_attr_t attr; a = (int*) malloc (8*100000*sizeof(int)); b = (int*) malloc (8*100000*sizeof(int)); for (i=0; i<100000*8; i++){ a[i]= b[i]=1; } init_pthread_variables(); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0; i<8; i++) pthread_create(&threads[i], &attr, dotprod, (void *)i); pthread_attr_destroy(&attr); for(i=0; i<8; i++) pthread_join(threads[i], &status); printf ("Final Global Sum=%li\\n",sum); free (a); free (b); pthread_exit(0); my_barrier_destroy(&my_barrier); }
0
#include <pthread.h> int G_CHUNK_SIZE; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; large_uint G_current_start; large_uint G_subset_count; int G_terminated_flag; large_uint G_steps; void increment_step() { pthread_mutex_lock(&mutex); G_steps++; pthread_mutex_unlock(&mutex); } struct solution { large_int* subset; int size; }; large_uint get_next_start() { pthread_mutex_lock(&mutex); large_uint start = G_current_start; G_current_start = start + G_CHUNK_SIZE; pthread_mutex_unlock(&mutex); return start; } void print_set(large_int* set, int size, FILE* out) { int i; fprintf(out, "{"); for (i = 0; i < size; i++) { if (i > 0) { fprintf(out, ", "); } fprintf(out, "%lld", set[i]); } fprintf(out, "}\\n"); } large_int* generate_subset(large_int* set, large_uint elements, int* subset_size) { large_uint max_elements = round(log(elements) / log(2)) + 1; large_int* subset = malloc(sizeof(large_int) * max_elements); int i; int current_index = 0; for (i = 0; i < max_elements; i++) { large_uint val = (elements >> i) & 1; if (val == 1) { subset[current_index] = set[i]; current_index++; } } *subset_size = current_index; return subset; } large_int calculate_set_sum(large_int* set, int size) { large_int sum = 0; int i; for (i = 0; i < size; i++) { sum += set[i]; } return sum; } void* find_zero_subset(void* data) { large_int* set = (large_int*) data; while (G_terminated_flag == 0) { large_uint start = get_next_start(); large_uint i; for (i = start; i < start + G_CHUNK_SIZE; i++) { if (i >= G_subset_count) { return 0; } int size; large_int* subset = generate_subset(set, i, &size); large_int sum = calculate_set_sum(subset, size); if (sum == 0) { struct solution* sol = (struct solution*) malloc(sizeof(struct solution)); sol->subset = subset; sol->size = size; printf("Solution found!\\n"); pthread_mutex_lock(&mutex); G_terminated_flag = 1; pthread_mutex_unlock(&mutex); return ((void*) sol); } free(subset); } } return 0; } large_int* generate_set(unsigned int set_size, large_int range) { int i; large_int* set = malloc(sizeof(large_int) * set_size); for (i = 0; i < set_size; i++) { double val = (((double) pcg32_boundedrand(range)) / (range / 2.0)) - 1; large_int value = val * range; set[i] = value; } return set; } void test_multithread(FILE* file, int num_threads, int set_size, large_int range, int chunk_size) { G_CHUNK_SIZE = chunk_size; pthread_t threads[num_threads]; clock_t start = clock(); large_int* set = generate_set(set_size, range); G_subset_count = round(pow(2, set_size)); G_current_start = 1; G_terminated_flag = 0; G_steps = 0; int i; for (i = 0; i < num_threads; i++) { pthread_create(&threads[i], 0, find_zero_subset, (void*) set); } struct solution* sol = 0; for (i = 0; i < num_threads; i++) { void* ret; pthread_join(threads[i], &ret); if (ret != 0) { printf("Thread %d found a solution!\\n", i); sol = ret; } else { printf("Thread %d was not able to find a solution.\\n", i); } } clock_t end = clock(); double delta = (((double) (end - start)) / CLOCKS_PER_SEC); printf("%.5f\\n", delta); printf("Joined with result %x and %d executions\\n", sol, G_steps); if (sol != 0) { print_set(sol->subset, sol->size, stdout); free(sol); } fprintf(file, "%d,%d,%d,%.6f\\n", G_CHUNK_SIZE, num_threads, set_size, delta); fflush(file); } int main(int argc, char** argv) { int rounds = atoi(argv[0]); unsigned int seed = 1478456124; FILE* file = fopen("out_multi_seeded_final_t.csv", "w"); fprintf(file, "chunk,threads,setsize,time\\n"); int ch, th, k, it; for (th = 0; th < 2; th++) { for (ch = 2; ch < 3; ch++) { pcg32_srandom(seed, 54u); for (k = 0; k < 13; k++) { for (it = 0; it < 30; it++) { int chunk = round(pow(10, (ch + 1))); int num_threads = (th + 1) * 2; int set_size = (k + 1) * 4; large_int range = round(pow(2, set_size / 2)); printf("k = %d, it = %d\\n", k, it); test_multithread(file, num_threads, set_size, range, chunk); } } } } return 0; }
1
#include <pthread.h> pthread_mutex_t dir_mutex; int dir_mutex_enabled = 1; int compat_init(void) { if(pthread_mutex_init(&dir_mutex, 0) < 0) return -1; return 0; } void compat_lock_enable(void) { dir_mutex_enabled = 1; } void compat_lock_disable(void) { dir_mutex_enabled = 0; } void dir_mutex_lock(int dfd) { if(dir_mutex_enabled) pthread_mutex_lock(&dir_mutex); if(fchdir(dfd) < 0) { perror("fchdir"); fprintf(stderr, "tup error: Failed to fchdir in a compat wrapper function.\\n"); exit(1); } } void dir_mutex_unlock(void) { if(dir_mutex_enabled) pthread_mutex_unlock(&dir_mutex); }
0
#include <pthread.h> int count = 0; pthread_mutex_t countMutex; pthread_cond_t countThreshold; void *incrementCount(void *tid) { int i; long threadID = (long)tid; while (count != 10) { pthread_mutex_lock(&countMutex); count++; printf ("\\nIncrement-thread %ld: Count incremented to %d.", threadID, count); if (count == 10) { printf("\\nIncrement-thread %ld: Threshold value reached!", threadID); pthread_cond_signal(&countThreshold); printf("\\nIncrement-thread %ld: Watch-count thread has been signalled.", threadID); } pthread_mutex_unlock(&countMutex); sleep(1); } pthread_exit(0); } void *watchCount(void *tid) { long threadID = (long)tid; pthread_mutex_lock(&countMutex); while (count < 10) { pthread_cond_wait(&countThreshold, &countMutex); printf("\\n\\nWatch-count thread %ld: Condition signal received. Count= %d", threadID,count); } printf("\\nWatch-count thread %ld: Unlocking mutex.\\n", threadID); pthread_mutex_unlock(&countMutex); pthread_exit(0); } int main() { int i; int t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&countMutex, 0); pthread_cond_init (&countThreshold, 0); printf("\\n\\nThreshold value = %d\\n", 10); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watchCount, (void *)t1); pthread_create(&threads[1], &attr, incrementCount, (void *)t2); pthread_create(&threads[2], &attr, incrementCount, (void *)t3); for (i=0; i<3; i++) pthread_join(threads[i], 0); printf("\\n\\nJoined all 3 threads.\\nFinal value of shared variable = %d\\n\\n", count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&countMutex); pthread_cond_destroy(&countThreshold); pthread_exit (0); }
1
#include <pthread.h> void *functionC(); pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int counter = 0; main() { int rc1, rc2; pthread_t thread1, thread2; if( (rc1=pthread_create( &thread1, 0, &functionC, 0)) ) { printf("Thread creation failed: %d\\n", rc1); } if( (rc2=pthread_create( &thread2, 0, &functionC, 0)) ) { printf("Thread creation failed: %d\\n", rc2); } pthread_join( thread1, 0); pthread_join( thread2, 0); exit(0); } void *functionC() { pthread_mutex_lock( &mutex1 ); counter++; printf("Counter value: %d\\n",counter); pthread_mutex_unlock( &mutex1 ); }
0
#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(void) { struct foo * fp = (struct foo *)malloc(sizeof(struct foo)); if (fp != 0) { fp -> f_count = 1; if (pthread_mutex_init(&fp -> f_lock, 0) != 0) { free(fp); return(0); } idx = (((unsigned long)fp) % 29); pthread_mutex_lock(&hashlock); fp -> f_next = fh[idx]; fh[idx] = fp -> f_next; 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 = 0; int idx; idx = (((unsigned long)id) % 29); pthread_mutex_lock(&hashlock); for (fp = fh[idx]; fp != 0; fp = fp -> f_next) { if (fp -> f_id == 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) { 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); } idx = (((unsigned long)fp) % 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); } }
1
#include <pthread.h> pthread_mutex_t lock; int chunk_size,nRows,nCols,padding,nThread; int seek=0,fd; pthread_t *t; int thread_block; int *MatrixA,*MatrixB,*MatrixC; void fillMatrix(char *name) { FILE *fp=fopen(name,"w+"); if(fp==0) { perror("Error in opening file"); exit(1); } int i,j; padding=nRows%(chunk_size/4); if(padding!=0) padding=chunk_size/4-padding; for(i=0;i<nRows;i++) { for(j=0;j<nCols;j++) { int x=2,nwrite; nwrite=fwrite(&x,sizeof(int),1,fp); assert(nwrite==1); } for(j=0;j<padding;j++) { int x=0,nwrite; nwrite=fwrite(&x,sizeof(int),1,fp); assert(nwrite==1); } } fclose(fp); } void printMatrix(char *name) { FILE *fp=fopen(name,"r"); if(fp==0) { perror("Error in Opening File"); exit(1); } int i,j; int val,nread; for(i=0;i<nRows;i++) { for(j=0;j<nCols;j++) { nread=fread(&val,sizeof(int),1,fp); assert(nread==1); printf("%d ",val); } for(j=0;j<padding;j++) { nread=fread(&val,sizeof(int),1,fp); assert(nread==1); printf("%d ",val); } printf("\\n"); } fclose(fp); } int chunk_by_chunk_multiply() { size_t i,j,k; int sum; sum=0; for(j=0;j<chunk_size/4;j++) { sum+=MatrixA[j]*MatrixB[j]; } return sum; } int* map_matrix_chunk(char * name,int mode,int rowindex,int colindex) { int fd; if(mode==1) fd=open(name,O_RDONLY); else if(mode==2) fd=open(name,O_RDWR); if(fd==-1) { perror("File not Opened "); exit(1); } int cur_position =rowindex*nRows*4+colindex*chunk_size; lseek(fd,cur_position,0); int *map_addr=0; if(mode==1) map_addr=mmap(0,chunk_size,PROT_READ,MAP_SHARED,fd,0); else if(mode==2) map_addr=mmap(0,chunk_size,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); if(map_addr==MAP_FAILED) { perror("MMAP Error"); exit(1); } close(fd); return map_addr; } int* map_matrix_chunk2(char * name,int mode,int rowindex,int colindex) { int fd; if(mode==1) fd=open(name,O_RDONLY); else if(mode==2) fd=open(name,O_RDWR); if(fd==-1) { perror("File not Opened "); exit(1); } int cur_position =rowindex*4+colindex*chunk_size; lseek(fd,cur_position,0); int *map_addr=0; if(mode==1) map_addr=mmap(0,chunk_size,PROT_READ,MAP_SHARED,fd,0); else if(mode==2) map_addr=mmap(0,chunk_size,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); if(map_addr==MAP_FAILED) { perror("MMAP Error"); exit(1); } close(fd); return map_addr; } void * dowork(void *arg) { int i,j,k,index; int tid=*(int*)arg; int start,end; start=tid*thread_block; end=(tid+1)*thread_block-1; for(i=start;i<=end;i++) { pthread_mutex_lock(&lock); for(j=0;j<(nCols);j++) { if(j%(chunk_size/4)==0) { MatrixC=map_matrix_chunk2("./MatrixC",2,i,j%(chunk_size/4)); memset(MatrixC,0,chunk_size); index=0; } for(k=0;k<(nCols*4/chunk_size);k++) { MatrixA=map_matrix_chunk2("./MatrixA",1,i,k); MatrixB=map_matrix_chunk("./MatrixB",1,j,k); MatrixC[index]+=chunk_by_chunk_multiply(k); munmap(MatrixB,chunk_size); munmap(MatrixA,chunk_size); } index++; if((j+1)%(chunk_size/4)==0) { int loc=0,w,buf=0; for(loc=0;loc<chunk_size/4;loc++) { buf=MatrixC[loc]; w=write(fd,&buf,4); } munmap(MatrixC,chunk_size); } } pthread_mutex_unlock(&lock); } } void map_Matrix() { int i,j,k,index; fd=open("./MatrixC",O_RDWR); if(fd==-1) { perror("File not opened "); exit(1); } for(i=0;i<nThread;i++) { int *x=(int*)malloc(4); *x=i; pthread_create(&t[i],0,dowork,x); } for(i=0;i<nThread;i++) pthread_join(t[i],0); close(fd); } int main(int argc,char **argv) { pthread_mutex_init(&lock,0); if(argc==4) { nRows=atoi(argv[1]);chunk_size=atoi(argv[2]); nThread=atoi(argv[3]); if(chunk_size&(chunk_size-1)!=0) { printf("\\n Chunk_Size should be Power of 2\\n"); exit(1); } } else if(argc==2) { nRows=atoi(argv[1]); nThread=16; printf("\\nWe assuming chunk size as 4096 and nThread as 16\\n");chunk_size=4096; } else if(argc==1) { printf("\\n We assuming array size as 8192 and Chunk Size as 4096 and nThread as 16\\n"); nRows=8192; chunk_size=4096; nThread=16; } nCols=nRows; fillMatrix("./MatrixA"); printf("\\n\\n Matrix A is......\\n\\n"); fillMatrix("./MatrixB"); printf("\\n\\n Matrix B is ...........\\n\\n"); fillMatrix("./MatrixC"); printf("\\n\\n Matric C.....\\n\\n"); nRows=nRows; nCols=nRows+padding; thread_block=nRows/nThread; t=(pthread_t *)malloc(sizeof(pthread_t)*nThread); struct timeval tv_start,tv_end; gettimeofday(&tv_start,0); map_Matrix(); gettimeofday(&tv_end,0); nCols=nCols-padding; padding=0; printf("\\n\\n-----------------------------------------------------------------------------------------------\\n\\n"); printf("\\n \\n time taken is %f sec \\n",(double)((tv_end.tv_sec-tv_start.tv_sec)+((tv_end.tv_usec-tv_start.tv_usec)/1000000))); return 0; }
0
#include <pthread.h> char *message = "HELLO B78! WELCOME TO THE CHAT EDGE. START CHATTING WITH YOUR FRIENDS.\\n welcome :"; pthread_mutex_t mutex; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; struct sockaddr_in sock_addr, sock_addr2; int len; int sd, fd[500], count = 0, file_d; pthread_t tid[500], tids; int shm_d; char *str, *buff, *identity; char *name; void init_name() { name = malloc (2024 * 2); bzero(name, 2024*2); strcpy(name + (15 * 145), "Sandeep"); strcpy(name + (15 * 160), "Manikandan"); strcpy(name + (15 * 175), "Sekhar"); strcpy(name + (15 * 169), "Satha"); strcpy(name + (15 * 148), "Amit"); strcpy(name + (15 * 174), "Mritunjaya"); strcpy(name + (15 * 171), "pratima"); strcpy(name + (15 * 177), "jayesh"); strcpy(name + (15 * 164), "swapnil"); strcpy(name + (15 * 109), "balajiii"); strcpy(name + (15 * 146), "shilpa "); strcpy(name + (15 * 248), "basha"); strcpy(name + (15 * 91), "abbas"); strcpy(name + (15 * 120), "poonam"); strcpy(name + (15 * 218), "deeppo"); strcpy(name + (15 * 90), "rustam"); strcpy(name + (15 * 163), "hardik"); strcpy(name + (15 * 104), "rk"); strcpy(name + (15 * 172), "ninja"); strcpy(name + (15 * 230), "santosh"); strcpy(name + (15 * 249), "jyoti"); strcpy(name + (15 * 131), "Elangovan"); strcpy(name + (15 * 196), "Dileep"); strcpy(name + (15 * 184), "Shilpa H"); strcpy(name + (15 * 84), "Naresh"); strcpy(name + (15 * 110), "Dharmesh"); strcpy(name + (15 * 13), "Shiva"); strcpy(name + (15 * 187), "Jitender"); strcpy(name + (15 * 147), "Sony"); strcpy(name + (15 * 129), "yogi"); strcpy(name + (15 * 132), "mahan"); strcpy(name + (15 * 170), "sai Aanand"); strcpy(name + (15 * 173), "poorna"); strcpy(name + (15 * 130), "praveen"); strcpy(name + (15 * 124), "jeevana"); strcpy(name + (15 * 114), "chiru"); strcpy(name + (15 * 134), "sabarish"); strcpy(name + (15 * 123), "Rahul"); } char *iptoname(int ip) { char *tmp = name + (15 * ip); if (*tmp == 0) { return 0; } return tmp; } void *serve (void *fdp) { FILE *fp = 0; printf("inside serve\\n"); int i = 16; char *tmp = malloc (2024); char *str_tmp = malloc (2024); bzero(tmp, 2024); bzero(str_tmp, 2024); int ip; char ip_str[4]; strcpy(ip_str, (identity + (16 * (count-1)) + (strlen(identity + (16 * (count-1))) - 3))); ip = atoi(ip_str); printf("ip = %d ipstr = %s\\n", ip, ip_str); if (iptoname(ip) == 0) { strcpy(tmp, identity + (16 * (count-1))); } else { strcpy(tmp, iptoname(ip)); } while (i--) { if (tmp[i] == 0) tmp[i] = ' '; } write (*(int *)fdp, message, strlen(message)); write (*(int *)fdp, tmp, strlen(tmp)); write (*(int *)fdp, "\\n\\n",1); strcat(tmp, ": "); printf("connected %s\\n", tmp); while (1) { read (*(int *)fdp, tmp + 16 + 2, 2024); if (*(tmp + 16 + 2) == 0) break; pthread_mutex_lock(&mutex); pthread_cond_signal(&cond); strcpy(buff, tmp); pthread_mutex_unlock(&mutex); *(tmp + 16 + 2) = 0; } close (*(int *)fdp); } void *sendall(void *p) { int i; while (1) { pthread_cond_wait(&cond, &mutex); if (write(file_d, buff, strlen(buff)) == -1) { perror("write"); } for (i = 0; i < count; i++) { write (fd[i], buff, strlen(buff) + 1); } pthread_mutex_unlock(&mutex); } } int main () { str = malloc(1024); buff = malloc(1024); identity = malloc(2024); init_name(); file_d = open("/home/sandeep/chat.log", O_APPEND | O_CREAT | O_RDWR, 0666); perror("open"); bzero(identity, 2024); pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond, 0); sd = socket (AF_INET, SOCK_STREAM, 0); if (sd < 0) { perror ("socket"); exit (1); } sock_addr.sin_family = AF_INET; sock_addr.sin_port = htons(2000); sock_addr.sin_addr.s_addr = inet_addr("0.0.0.0"); if (bind(sd, (struct sockaddr *)&sock_addr, sizeof(sock_addr)) == -1) { perror ("bind"); exit (1); } if (listen(sd, 500) == -1) { perror ("listen"); exit (1); } len = sizeof (sock_addr2); if (pthread_create (&tids, 0, sendall, 0)) { printf("pthread_create fails\\n"); } while (1) { fd[count] = accept (sd, (struct sockaddr *)&sock_addr2, &len); strcpy(identity + (16 * count), (char *)inet_ntoa(sock_addr2.sin_addr)); perror ("accept"); if (pthread_create (&tid[count], 0, serve, (void *)&fd[count])) { printf("pthread_create fails\\n"); } count++; } }
1
#include <pthread.h> int counter=0; void thread1(void *arg); void thread2(void *arg); pthread_mutexattr_t attr; pthread_mutex_t mutex; int err = 0; int main(int argc, char *argv[]) { pthread_t id1,id2; if(err = pthread_mutexattr_init(&attr) != 0){ printf("init attr failed!\\n"); exit(1); } if(err = pthread_mutex_init(&mutex,&attr) != 0){ printf("init mutex failed!\\n"); exit(1); } pthread_create(&id1,0,(void *)thread1, 0); pthread_create(&id2,0,(void *)thread2, 0); pthread_join(id1,0); pthread_join(id2,0); printf("最后的counter值为%d\\n",counter); exit(0); } void thread1(void *arg) { int i,val; for(i=1;i<=5;i++){ pthread_mutex_lock(&mutex); val=++counter; printf("第1个线程:第%d次循环,第1次引用counter=%d\\n",i,counter); usleep(300); printf("第1个线程:第%d次循环,第2次引用counter=%d\\n",i,counter); counter=val; pthread_mutex_unlock(&mutex); } } void thread2(void *arg) { int i,val; for(i=1;i<=5;i++){ pthread_mutex_lock(&mutex); val=++counter; usleep(100); printf("第2个线程:第%d次循环,counter=%d\\n",i,counter); counter=val; pthread_mutex_unlock(&mutex); } }
0
#include <pthread.h> pthread_mutex_t table; pthread_cond_t self; struct resource { int tob, mat, pap, agent; } * res; void putdown(int type); void pickup(int id); void * agent(void * args) { int a,b=0; printf("Agent started !\\n"); while(b <10){ a = rand()%3; putdown(a); sleep(1); b++; } } void * smoker(void * args) { int id = *(int *)args; printf("smoker %d started\\n", id); while(1){ pickup(id); sleep(1); } } int main() { res = (struct resource *)malloc(sizeof(struct resource)); res->agent=1; res->mat=0; res->pap=0; res->tob=0; pthread_t p1, smk[3]; int i; int smk_id[]= {1,2,3}; pthread_mutex_init(&table, 0); pthread_cond_init(&self, 0); pthread_create(&p1, 0, &agent, 0); for(i=0; i<3; i++) pthread_create(&smk[i], 0, &smoker, &smk_id[i]); pthread_join(p1, 0); for (i = 0; i < 3; ++i){ pthread_join(smk[i], 0); } return 0; } void putdown(int type){ pthread_mutex_lock(&table); while(res->agent != 1){ pthread_cond_wait(&self, &table); } switch(type){ case 0: res->tob=1; printf("agent put matches and paper on table\\n"); break; case 1: res->mat=1; printf("agent put matches and paper on table\\n"); break; case 2: res->pap=1; printf("agent put matches and paper on table\\n"); break; default: break; } pthread_cond_broadcast(&self); pthread_mutex_unlock(&table); } void pickup(int id){ pthread_mutex_lock(&table); switch(id){ case 1: while(res->tob!=1){ pthread_cond_wait(&self, &table); } res->tob=0; res->agent=1; printf("smoker %d took tobacco and smoking\\n", id); break; case 2: while(res->mat!=1){ pthread_cond_wait(&self, &table); } res->mat = 0; res->agent=1; printf("smoker %d took matches and smoking\\n", id); break; case 3: while(res->pap!=1){ pthread_cond_wait(&self, &table); } res->pap = 0; res->agent = 1; printf("smoker %d took paper and smoking\\n", id); break; default: break; } pthread_cond_broadcast(&self); pthread_mutex_unlock(&table); }
1
#include <pthread.h> volatile int shared_counter = 0; pthread_t people[100]; pthread_mutex_t lock; void* returnToChair() { pthread_mutex_lock(&lock); for(int i=0; i<1000;i++) { shared_counter++; } pthread_mutex_unlock(&lock); return 0; } int main(void) { if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } clock_t begin, end; double individual_time_spent; double total_time_spent = 0.0; double average_time_spent; int threadReturn; for (int j = 0; j < 10; j++) { printf("\\n> Run - %d\\n", (j+1)); begin = clock(); int i = 0; while(i < 100) { threadReturn = pthread_create(&(people[i]), 0, &returnToChair, 0); if (threadReturn != 0) printf("\\ncan't create thread :[%s]", strerror(threadReturn)); else i++; } end = clock(); individual_time_spent = (double)(end - begin) / CLOCKS_PER_SEC; total_time_spent += individual_time_spent; printf(" --- Time: %f\\n", individual_time_spent); printf(" --- Counter: %d\\n", shared_counter); shared_counter = 0; } pthread_mutex_destroy(&lock); average_time_spent = total_time_spent/10; printf("\\nTotal Time Taken: %f\\n", total_time_spent); printf("Average Time for each run: %f\\n", average_time_spent); return 0; }
0
#include <pthread.h> struct arg_set { char * fname; int count; }; struct arg_set * mailbox; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t flag = PTHREAD_COND_INITIALIZER; main(int ac, char *av[]) { pthread_t t1, t2; struct arg_set args1, args2; void * count_words(void *); int reports_in = 0; int total_words = 0; if(ac != 3) { printf("usage: %s file1 file2\\n", av[0]); exit(1); } pthread_mutex_lock(&lock); args1.fname = av[1]; args1.count = 0; pthread_create(&t1, 0, count_words, (void *) &args1); args2.fname = av[2]; args2.count = 0; pthread_create(&t2, 0, count_words, (void *) &args2); while(reports_in < 2) { printf("MAIN: waiting for flag to go up\\n"); pthread_cond_wait(&flag, &lock); printf("MAIN: wow! flat was raised, i have the lock\\n"); printf("%7d: %s\\n", mailbox->count, mailbox->fname); total_words += mailbox->count; if (mailbox == &args1) pthread_join(t1, 0); if (mailbox == &args2) pthread_join(t2, 0); mailbox = 0; pthread_cond_signal(&flag); reports_in++; } printf("%d: total words\\n", total_words); } void * count_words(void * a) { struct arg_set * args = a; FILE *fp; int c, prevc = '\\0'; if ( (fp=fopen(args->fname,"r")) != 0 ) { while( (c=getc(fp)) != EOF ) { if ( !isalnum(c) && isalnum(prevc) ) args->count++; prevc = c; } fclose(fp); } else { perror(args->fname); } printf("COUNT: waiting to get lock\\n"); pthread_mutex_lock(&lock); printf("COUNT: have lock, storing data\\n"); if (mailbox != 0) pthread_cond_wait(&flag, &lock); mailbox = args; printf("COUNT: raising flag\\n"); pthread_cond_signal(&flag); printf("COUNT: unlocking box\\n"); pthread_mutex_unlock(&lock); return 0; }
1
#include <pthread.h> static FILE *logger = 0; static pthread_mutex_t lock; static const char* logFilePath = 0; void initializeC(const char* _logFilePath) { if (pthread_mutex_init(&lock, 0) != 0) { printf("%s[%d] mutex initialization failed.", __FUNCTION__, 21); assert(0); } logger = fopen(_logFilePath, "a"); if (!logger) { printf("%s[%d] logger initialization failed.", __FUNCTION__, 28); assert(0); } logFilePath = _logFilePath; } void logMessageC(char *message) { pthread_mutex_lock(&lock); fprintf(logger,"%s\\n", message); fflush(logger); pthread_mutex_unlock(&lock); } int clearLogFileC() { pthread_mutex_lock(&lock); logger = freopen(logFilePath, "w", logger); if (!logger) { printf("%s[%d] logger clearing failed.", __FUNCTION__, 54); assert(0); } pthread_mutex_unlock(&lock); return 1; } const char * timeC() { time_t t = time(0); struct tm *tm = localtime(&t); char *s = asctime(tm); s[strlen(s) - 1] = '\\0'; return s; }
0
#include <pthread.h> struct range { int begin; int end; }; int *array = 0; int N = 0; pthread_mutex_t queue_mutex; pthread_cond_t queue_cond; int completed = 0; pthread_mutex_t completed_mutex; bool is_completed() { pthread_mutex_lock(&completed_mutex); bool res = (completed == N); pthread_mutex_unlock(&completed_mutex); return res; } void report_completed(int num) { pthread_mutex_lock(&completed_mutex); completed += num; pthread_mutex_unlock(&completed_mutex); } void swap(int a, int b) { if (a == b) return; int tmp = array[a]; array[a] = array[b]; array[b] = tmp; } void bubble_sort(int low, int high) { if (low > high) return; int i, j; for (i = low; i <= high; i++) for (j = i+1; j <= high; j++) if (array[i] > array[j]) swap(i, j); report_completed(high-low+1); } int partition(int low, int high) { int pivot = array[low], middle = low, i; swap(low, high); for(i=low; i<high; i++) { if(array[i] < pivot) { swap(i, middle); middle++; } } swap(high, middle); report_completed(1); return(middle); } void submit(int low, int high) { struct range *r = (struct range*) malloc(sizeof(struct range)); r->begin = low; r->end = high; pthread_mutex_lock(&queue_mutex); enqueue(r); pthread_cond_signal(&queue_cond); ; pthread_mutex_unlock(&queue_mutex); } void quicksort(int low, int high) { if (high - low < 10) { bubble_sort(low, high); return; } int middle = partition(low, high); submit(low, middle-1); quicksort(middle+1, high); } void worker(long rank) { struct timeval now; struct timespec timeout; struct range *r = 0; while (!is_completed()) { ; pthread_mutex_lock(&queue_mutex); while (empty()) { ; gettimeofday(&now, 0); timeout.tv_sec = now.tv_sec; timeout.tv_nsec = now.tv_usec * 1000 + 300000000; pthread_cond_timedwait(&queue_cond, &queue_mutex, &timeout); if (is_completed()) { break; } } r = dequeue(); pthread_mutex_unlock(&queue_mutex); if (r != 0) { quicksort(r->begin, r->end); ; free(r); } } ; } void* child_proc(void *ip) { worker((long)ip); return 0; } int main(int argc, char **argv) { int i, j; int num_threads; char ans; pthread_t *thread_id = 0; if((argc != 2) && (argc != 3)) { printf("Usage: qsort_queue N [num_threads]\\n"); exit(0); } N = atoi(argv[1]); if(N < 2) { printf("N must be greater than 2\\n"); exit(0); } if(argc == 2) { num_threads = 1; } else { num_threads = atoi(argv[2]); if(num_threads < 1) { printf("num_threads must be greater than 1\\n"); exit(0); } } printf("Quicksort with %d threads (queue version), array_size = %d\\n", num_threads, N); pthread_mutex_init(&queue_mutex, 0); pthread_cond_init(&queue_cond, 0); pthread_mutex_init(&completed_mutex, 0); if(num_threads > 1) { thread_id = (pthread_t*)malloc((num_threads-1)*sizeof(pthread_t)); if (thread_id == 0) { printf("Lack of memory when creating threads\\n"); goto QUIT_POINT; } for(i=1;i<num_threads;i++) { pthread_create(&thread_id[i-1],0,child_proc,(void*)i); ; } } array = (int *) malloc(sizeof(int) * N); if (array == 0) { printf("Lack of memory when allocating data buffer\\n"); goto QUIT_POINT; } for (i=0; i<N; i++) array[i] = i+1; srand(time(0)); for (i=0; i<N; i++) { j = (rand()*1./32767)*(N-1); swap(i, j); } submit(0, N-1); worker (0); if(num_threads > 1) { for(i=1;i<num_threads;i++) { pthread_join(thread_id[i-1],0); } } QUIT_POINT: if (thread_id != 0) { free(thread_id); thread_id = 0; } if (array != 0) { free(array); array = 0; } return 0; }
1
#include <pthread.h> sem_t semA, semB; int max_kapacita; int kapacita = 0; int pocet_kobyl; pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; void * spravca(void * param) { while(1) { pthread_mutex_lock(&mut); kapacita = max_kapacita; printf("Spravca naplnil valov\\n"); int z; for (z = 0; z < max_kapacita; z++) sem_post(&semB); pthread_mutex_unlock(&mut); sem_wait(&semA); sleep(1); } } void * kobyla(void * param) { while(1) { sem_wait(&semB); sleep(1); pthread_mutex_lock(&mut); if (kapacita == 0) continue; kapacita--; printf("kobyla %d zozrala jedlo, kapacita ostava : %d\\n",param,kapacita); if (kapacita == 0) { printf("Posledna kobyla %d zaerdzala\\n",param); sem_post(&semA); } pthread_mutex_unlock(&mut); sched_yield(); } } main(int argc, char *argv[]) { pocet_kobyl = atoi(argv[1]); max_kapacita = atoi(argv[2]); sem_init(&semA, 0, 0); sem_init(&semB, 0, 0); pthread_mutex_init(&mut,0); pthread_t tid; pthread_t zvierata[pocet_kobyl]; pthread_create(&tid, 0, spravca, 0); int i; for (i = 1; i <= pocet_kobyl; i++) { pthread_create(&zvierata[i], 0, kobyla, (void *)i); } for (i = 1; i <= pocet_kobyl; i++) pthread_join(zvierata[i], 0); pthread_join(tid,0); pthread_mutex_destroy(&mut); return 0; }
0
#include <pthread.h> int thread_no; int *data; pthread_mutex_t *mutex; } thread_arg_t; void thread_func(void *arg) { thread_arg_t *targ = (thread_arg_t *)arg; int i, result; for (i = 0; i < 10; i++) { pthread_mutex_lock(targ->mutex); result = targ->data[i] + 1; sched_yield(); targ->data[i] = result; pthread_mutex_unlock(targ->mutex); } } int main(void) { pthread_t handle[2]; thread_arg_t targ[2]; int data[10]; int i; pthread_mutex_t mutex; for (i = 0; i < 10; i++) data[i] = 0; pthread_mutex_init(&mutex, 0); for (i = 0; i < 2; i++) { targ[i].thread_no = i; targ[i].data = data; targ[i].mutex = &mutex; pthread_create(&handle[i], 0, (void *)thread_func, (void *)&targ[i]); } for (i = 0 ; i < 2; i++) { pthread_join(handle[i], 0); } pthread_mutex_destroy(&mutex); for (i = 0; i < 10; i++) printf("data%d : %d\\n", i, data[i]); return 0; }
1
#include <pthread.h> pthread_mutex_t counter_lock; pthread_cond_t counter_nonzero; int counter = 0; int estatus = -1; void *decrement_counter(void *argv) { printf("counter decrement: %d\\n", counter); pthread_mutex_lock(&counter_lock); while(counter == 0) { pthread_cond_wait(&counter_nonzero, &counter_lock); } printf("counter--before:%d\\n", counter); counter--; printf("counter--after:%d\\n", counter); pthread_mutex_unlock(&counter_lock); return &estatus; } void *increment_counter(void *argv) { printf("counter(increment): %d\\n", counter); pthread_mutex_lock(&counter_lock); if(counter == 0) { pthread_cond_signal(&counter_nonzero); } printf("counter--before:%d\\n", counter); counter++; printf("counter--after:%d\\n", counter); pthread_mutex_unlock(&counter_lock); return &estatus; } int main(void) { printf("counter: %d\\n", counter); pthread_t ptd1, ptd2; int ret; pthread_mutex_init(&counter_lock, 0); pthread_cond_init(&counter_nonzero, 0 ); ret = pthread_create(&ptd1, 0, decrement_counter, 0); if(ret) { printf("create thread fail\\n"); return 1; } ret = pthread_create(&ptd2, 0, increment_counter, 0); if(ret) { printf("create thread fail\\n"); return 2; } int counter = 0; while(counter != 10) { printf("counter(main): %d\\n", counter); sleep(1); counter++; } return 0; }
0
#include <pthread.h> static pthread_mutex_t baguette[3]; void error(int err, char *msg) { fprintf(stderr,"%s a retourné %d message d'erreur : %s\\n",msg,err,strerror(errno)); exit(1); } void mange(int id) { printf("Philosophe [%d] mange\\n",id); for(int i=0;i< rand(); i++) { } } void* philosophe ( void* arg ) { int *id=(int *) arg; int left = *id; int right = (left + 1) % 3; while(1) { if(left<right) { pthread_mutex_lock(&baguette[left]); pthread_mutex_lock(&baguette[right]); } else { pthread_mutex_lock(&baguette[right]); pthread_mutex_lock(&baguette[left]); } mange(*id); pthread_mutex_unlock(&baguette[left]); pthread_mutex_unlock(&baguette[right]); } return (0); } int main ( int argc, char *argv[]) { int i; int id[3]; int err; pthread_t phil[3]; srand(getpid()); for (i = 0; i < 3; i++) id[i]=i; for (i = 0; i < 3; i++) { err=pthread_mutex_init( &baguette[i], 0); if(err!=0) error(err,"pthread_mutex_init"); } for (i = 0; i < 3; i++) { err=pthread_create(&phil[i], 0, philosophe, (void*)&(id[i]) ); if(err!=0) error(err,"pthread_create"); } for (i = 0; i < 3; i++) { pthread_join(phil[i], 0); if(err!=0) error(err,"pthread_join"); } for (i = 0; i < 3; i++) { pthread_mutex_destroy(&baguette[i]); if(err!=0) error(err,"pthread_mutex_destroy"); } return (0); }
1
#include <pthread.h> void runner(void *dir); int carNum=0; int car=0; int WestC=0,EastC=0,NorthC=0,SouthC=0; pthread_mutex_t n_mutex, s_mutex, w_mutex, e_mutex, cnter_mutex; sem_t queueNorth, queueSouth, queueWest, queueEast; pthread_cond_t firstNorth, firstSouth, firstEast, firstWest; void *runnerWest(void *carNum); void *runnerEast(void *carNum); void *runnerNorth(void *carNum); void *runnerSouth(void *carNum); void *detectDeadLock(void *argv); int main(int argc, char* argv[]) { pthread_t tid[500]; pthread_t manager; int carNo[500]; if(argc!=2) { printf("parameter error!\\n"); exit(0); } int i=0; for(i=0;argv[1][i]!='\\0';i++) car++; carNum=car; pthread_mutex_init(&n_mutex,0); pthread_mutex_init(&s_mutex,0); pthread_mutex_init(&w_mutex,0); pthread_mutex_init(&e_mutex,0); pthread_mutex_init(&cnter_mutex,0); sem_init(&queueNorth,0,1); sem_init(&queueSouth,0,1); sem_init(&queueWest,0,1); sem_init(&queueEast,0,1); pthread_cond_init(&firstNorth,0); pthread_cond_init(&firstSouth,0); pthread_cond_init(&firstEast,0); pthread_create(&manager,0,detectDeadLock,0); for(i=0;argv[1][i]!='\\0';i++){ carNo[i]=i+1; if(argv[1][i]=='w') pthread_create(&tid[i],0,runnerWest,(void*)&carNo[i]); else if(argv[1][i]=='e') pthread_create(&tid[i],0,runnerEast,(void*)&carNo[i]); else if(argv[1][i]=='n') pthread_create(&tid[i],0,runnerNorth,(void*)&carNo[i]); else if(argv[1][i]=='s') pthread_create(&tid[i],0,runnerSouth,(void*)&carNo[i]); else{ printf("wrong parameter:%c\\n",argv[1][i]); exit(0); } } for(i=0;i<carNum;i++) pthread_join(tid[i],0); car=0; pthread_join(manager,0); printf("end of the program\\n"); return 0; } void *runnerWest(void *carNum) { int no = *(int *)carNum; sem_wait(&queueWest); pthread_mutex_lock(&cnter_mutex); WestC++; pthread_mutex_unlock(&cnter_mutex); printf("car %d from west arrives at crossing\\n",no); sleep(1); pthread_mutex_lock(&s_mutex); pthread_mutex_lock(&cnter_mutex); if(SouthC>0) { pthread_mutex_unlock(&cnter_mutex); pthread_cond_wait(&firstWest,&s_mutex); } else pthread_mutex_unlock(&cnter_mutex); pthread_mutex_lock(&w_mutex); pthread_mutex_unlock(&s_mutex); pthread_mutex_unlock(&w_mutex); printf("car %d from west leaving crossing\\n",no); pthread_mutex_lock(&cnter_mutex); WestC--; pthread_mutex_unlock(&cnter_mutex); pthread_cond_signal(&firstNorth); sem_post(&queueWest); } void *runnerEast(void *carNum) { int no= *(int *)carNum; sem_wait(&queueEast); pthread_mutex_lock(&cnter_mutex); EastC++; pthread_mutex_unlock(&cnter_mutex); printf("car %d from east arrives at crossing\\n",no); sleep(1); pthread_mutex_lock(&n_mutex); pthread_mutex_lock(&cnter_mutex); if(NorthC>0) { pthread_mutex_unlock(&cnter_mutex); pthread_cond_wait(&firstNorth,&n_mutex); } else pthread_mutex_unlock(&cnter_mutex); pthread_mutex_lock(&e_mutex); pthread_mutex_unlock(&n_mutex); pthread_mutex_unlock(&e_mutex); printf("car %d from east leaving crossing\\n",no); pthread_mutex_lock(&cnter_mutex); EastC--; pthread_mutex_unlock(&cnter_mutex); pthread_cond_signal(&firstSouth); sem_post(&queueEast); } void *runnerNorth(void *carNum) { int no= *(int *)carNum; sem_wait(&queueNorth); pthread_mutex_lock(&cnter_mutex); NorthC++; pthread_mutex_unlock(&cnter_mutex); printf("car %d from north arrives at crossing\\n",no); sleep(1); pthread_mutex_lock(&w_mutex); pthread_mutex_lock(&cnter_mutex); if(WestC>0){ pthread_mutex_unlock(&cnter_mutex); pthread_cond_wait(&firstNorth,&w_mutex); } else pthread_mutex_unlock(&cnter_mutex); pthread_mutex_lock(&n_mutex); pthread_mutex_unlock(&w_mutex); pthread_mutex_unlock(&n_mutex); printf("car %d from north leaving crossing\\n",no); pthread_mutex_lock(&cnter_mutex); NorthC--; pthread_mutex_unlock(&cnter_mutex); pthread_cond_signal(&firstEast); sem_post(&queueNorth); } void *runnerSouth(void *carNum) { int no= *(int *)carNum; sem_wait(&queueSouth); pthread_mutex_lock(&cnter_mutex); SouthC++; pthread_mutex_unlock(&cnter_mutex); printf("car %d from south arrives at crossing\\n",no); sleep(1); pthread_mutex_lock(&e_mutex); pthread_mutex_lock(&cnter_mutex); if(EastC>0){ pthread_mutex_unlock(&cnter_mutex); pthread_cond_wait(&firstSouth,&e_mutex); } else pthread_mutex_unlock(&cnter_mutex); pthread_mutex_lock(&s_mutex); pthread_mutex_unlock(&e_mutex); pthread_mutex_unlock(&s_mutex); printf("car %d from south leaving crossing\\n",no); pthread_mutex_lock(&cnter_mutex); SouthC--; pthread_mutex_unlock(&cnter_mutex); pthread_cond_signal(&firstWest); sem_post(&queueSouth); } void *detectDeadLock(void *argv) { while(car){ pthread_mutex_lock(&cnter_mutex); if(WestC!=0&&EastC!=0&&NorthC!=0&&SouthC!=0){ printf("Deadlock Detected!Signalling north to go\\n"); pthread_cond_signal(&firstNorth); } pthread_mutex_unlock(&cnter_mutex); sleep(4); } }
0
#include <pthread.h> pthread_mutex_t phdmutex; pthread_cond_t condSell, condSupply; void *fSellTickets(void *arg) { int *tick = (int *)arg; int tmp; int sum = 0; while(1) { pthread_mutex_lock(&phdmutex); while(*tick == 0) { pthread_cond_signal(&condSupply); pthread_cond_wait(&condSell, &phdmutex); } tmp = *tick; --tmp; *tick = tmp; ++sum; printf("%u sold a ticket, %d, left %d\\n", pthread_self(), sum, *tick); pthread_mutex_unlock(&phdmutex); sleep(1); } pthread_mutex_unlock(&phdmutex); return (void *)sum; } void *fSupplyTickets(void *arg) { int *tick = (int *)arg; while(1) { pthread_mutex_lock(&phdmutex); if(*tick > 0) pthread_cond_wait(&condSupply, &phdmutex); *tick = rand() % 30 + 1; printf("add %d tickets\\n", *tick); pthread_mutex_unlock(&phdmutex); pthread_cond_broadcast(&condSell); } return 0; } int main(int argc, char *argv[]) { int numTickets, numSell; pthread_t pthdSupply; numTickets = atoi(argv[2]); numSell = atoi(argv[1]); int totle = numTickets; pthread_mutex_init(&phdmutex, 0); pthread_cond_init(&condSell, 0); pthread_cond_init(&condSupply, 0); pthread_t *pthdSell = (pthread_t *)calloc(numSell, sizeof(pthread_t)); int *selledTickets = (int *)calloc(numTickets, sizeof(int)); int i, sum; for(i = 0;i < numSell;i++) { pthread_create(pthdSell + i, 0, fSellTickets, &numTickets); } pthread_create(&pthdSupply, 0, fSupplyTickets, &numTickets); for(i = 0;i < numSell;i++) { pthread_join(pthdSell[i], (void *)(selledTickets + i)); } for(sum = 0, i = 0;i < numSell;i++) { sum += selledTickets[i]; } pthread_mutex_destroy(&phdmutex); pthread_cond_destroy(&condSell); pthread_cond_destroy(&condSupply); printf("sell: %d, totle: %d, current: %d\\n", sum, totle, numTickets); return 0; }
1
#include <pthread.h> void init(int decimation, int pixel_buffer_size) { if (rp_Init() != RP_OK) { perror("Red Pitaya API init failed!"); exit(1); } init_control(decimation); init_tcp(pixel_buffer_size); } void end(){ end_control(); end_tcp(); rp_Release(); } void routine(int16_t* buffer, int buffer_size, char* pixel_buffer, int pixel_buffer_size){ int i = 0; int j = 0; for(j = 0; j < buffer_size; j++) buffer[j] = 160; while(i < 10) { pixel_buffer = calcul_pixel(buffer, buffer_size, i, pixel_buffer, pixel_buffer_size); pthread_mutex_lock(&mutex); sprintf(data_to_send, "%s", pixel_buffer); pthread_cond_signal(&new_data); pthread_mutex_unlock(&mutex); i++; } }
0
#include <pthread.h> pthread_mutex_t reading_room_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t num_readers_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t readers = PTHREAD_COND_INITIALIZER; pthread_cond_t writers = PTHREAD_COND_INITIALIZER; int num_readers = 0; int reading_room_taken = 0; void *reader(void *args) { int i = (int) args; sleep(i % 500); pthread_mutex_lock(&reading_room_mutex); if (!reading_room_taken) { reading_room_taken = 1; pthread_cond_broadcast(&readers); } else { pthread_cond_wait(&readers, &reading_room_mutex); } pthread_mutex_lock(&num_readers_mutex); num_readers++; if(num_readers == 1) { reading_room_taken = 1; pthread_cond_broadcast(&readers); } pthread_mutex_unlock(&num_readers_mutex); pthread_mutex_unlock(&reading_room_mutex); printf("start reading %d\\n", i); sleep(1); printf("finish reading %d\\n", i); pthread_mutex_lock(&num_readers_mutex); num_readers--; if (num_readers == 0) { pthread_mutex_lock(&reading_room_mutex); reading_room_taken = 0; pthread_mutex_unlock(&reading_room_mutex); pthread_cond_signal(&writers); } pthread_mutex_unlock(&num_readers_mutex); return (void *)0; } void *writer(void *args) { int i = (int) args; sleep(i % 10); pthread_mutex_lock(&reading_room_mutex); if (!reading_room_taken) { reading_room_taken = 1; } else { pthread_cond_wait(&writers, &reading_room_mutex); } reading_room_taken = 1; pthread_mutex_unlock(&reading_room_mutex); printf("start writing %d \\n", i); sleep(1); printf("finish writing %d \\n", i); pthread_mutex_lock(&reading_room_mutex); reading_room_taken = 0; pthread_mutex_unlock(&reading_room_mutex); pthread_cond_signal(&readers); return (void *)0; } int main() { pthread_t threads[10100]; int i; for(i = 0; i <= 100; i++) { pthread_create(&threads[i], 0, writer, (void *)i); } for(i = 0; i <= 10000; i++) { pthread_create(&threads[i+100], 0, reader, (void *)i); } for(i = 0; i <= 10100; i++) { pthread_join(threads[i], 0); } return 0; }
1
#include <pthread.h> int svalue; sem_t sread, sthreads, sbuff; pthread_mutex_t lock; char* buffer[BUFFER_SIZE]; void initBuffer() { int i; for(i=0; i<BUFFER_SIZE; i++){ buffer[i]="empty"; } } void printBuffer() { int i; for(i=0; i<BUFFER_SIZE; i++) { printf("i: %d, buffer[i]: %s\\n", i, buffer[i]); } } void fillBuffer(char* file){ int i; char* copy = (char*)malloc(sizeof(file)); strcpy(copy, file); for(i = 0; i < BUFFER_SIZE; i++){ if(strcmp("empty", buffer[i])==0){ buffer[i] = copy; sem_getvalue(&sbuff, &svalue); sem_post(&sread); return; } } } char* getBuffer(){ int i; char* result; for(i = 0; i < BUFFER_SIZE; i++){ if(strcmp("SO2014-0.txt", buffer[i])==0 || strcmp("SO2014-1.txt", buffer[i])==0 || strcmp("SO2014-2.txt", buffer[i])==0 || strcmp("SO2014-3.txt", buffer[i])==0 || strcmp("SO2014-4.txt", buffer[i])==0){ result = buffer[i]; buffer[i] = "empty"; sem_post(&sbuff); pthread_mutex_unlock(&lock); return result; } } return "empty"; } int reader(){ int i, fd; int aux = NUMBER_OF_LINES*POSITION_OF_NEWLINE; int lineCounter=0; char currentChar; char* buf = (char*)malloc(sizeof(char)*(aux+1)); sem_wait(&sthreads); sem_post(&sthreads); sem_wait(&sread); char* file = getBuffer(); if((fd = open(file, O_RDONLY)) < 0){ perror("Cannot open file"); reader(); } if(flock(fd, LOCK_SH) < 0){ perror("Failed to lock file"); reader(); } if((read(fd, buf, aux)) < 0){ perror("Failed to read file"); reader(); } if(validLetter(buf[0])){ for(i=0; lineCounter < NUMBER_OF_LINES; i++){ if(i%POSITION_OF_NEWLINE != NUMBER_OF_LETTERS){ if(buf[i]!=buf[0]) { printf("FAILED\\n"); reader(); } }else{ if(buf[i] != '\\n') { printf("FAILED\\n"); reader(); } lineCounter++; } } if(!read(fd, buf, aux)){ if(flock(fd, LOCK_UN) < 0){ perror("Failed to unlock file"); reader(); } if((close(fd))< 0){ perror("Failed to close file"); reader(); } printf("SUCCESS, file: %s\\n", file); reader(); }else{ printf("FAILED\\n"); reader(); } }else{ printf("FAILED\\n"); reader(); } } void* reader_wrapper(void* ptr){ return(void*) reader((char*) ptr); } int main(int argc, char* argv[]){ int i; int result[NUMBER_OF_THREADS]; int stillReading = 1; char* input; pthread_t tid[NUMBER_OF_THREADS]; sem_init(&sthreads, 0, 0); sem_init(&sread, 0,0); sem_init(&sbuff, 0, BUFFER_SIZE); if(pthread_mutex_init(&lock, 0) != 0){ perror("mutex init failed"); exit(-1); } initBuffer(); for(i = 0; i < NUMBER_OF_THREADS; i++){ if(pthread_create(&tid[i], 0, reader_wrapper, 0) !=0){ perror("failed to create thread"); exit(-1); }else{ printf("created thread: %ld\\n", tid[i]); } } sem_post(&sthreads); while(1){ input = (char*)malloc(sizeof(char)*12); scanf("%s", input); if(strcmp("SO2014-0.txt", input)==0 || strcmp("SO2014-1.txt", input)==0 || strcmp("SO2014-2.txt", input)==0 || strcmp("SO2014-3.txt", input)==0 || strcmp("SO2014-4.txt", input)==0){ sem_wait(&sbuff); fillBuffer(input); } free(input); } for(i = 0; i < NUMBER_OF_THREADS; i++){ if(pthread_join(tid[i], (void**)&result[i]) !=0){ perror("failed to join thread"); exit(-1); }else{ printf("joined thread: %ld and retuned:%d\\n", tid[i], result[i]); } } pthread_mutex_destroy(&lock); exit(0); }
0
#include <pthread.h> static struct { int portnumber; char hostname[1020]; } q[256]; static volatile int ihead = 0; static volatile int itail = 0; static volatile int _ufdb_httpsq_n_queued = 0; static pthread_mutex_t httpsq_lock = UFDB_STATIC_MUTEX_INIT; static pthread_cond_t empty = PTHREAD_COND_INITIALIZER; int ufdbHttpsQueueRequest( char * hostname, int portnumber ) { int i; int rv; rv = pthread_mutex_lock( &httpsq_lock ); for (i = ihead; i != itail; i = (i+1) % 256) { if (strcmp( hostname, q[i].hostname ) == 0 && q[i].portnumber == portnumber) { rv = pthread_mutex_unlock( &httpsq_lock ); return UFDB_API_REQ_QUEUED; } } if (_ufdb_httpsq_n_queued < 256) { q[itail].portnumber = portnumber; strcpy( q[itail].hostname, hostname ); _ufdb_httpsq_n_queued++; itail = (itail + 1) % 256; rv = pthread_mutex_unlock( &httpsq_lock ); pthread_cond_broadcast( &empty ); } else { ufdbLogError( "HTTPS/SSL security detection queue is full. %s:%d is not checked now", hostname, portnumber ); rv = pthread_mutex_unlock( &httpsq_lock ); return UFDB_API_ERR_FULL; } return UFDB_API_OK; } void ufdbGetHttpsRequest( char * hostname, int * portnumber ) { int rv; allover: rv = pthread_mutex_lock( &httpsq_lock ); while (1) { if (_ufdb_httpsq_n_queued > 0) { _ufdb_httpsq_n_queued--; *portnumber = q[ihead].portnumber; strcpy( hostname, q[ihead].hostname ); ihead = (ihead + 1) % 256; pthread_mutex_unlock( &httpsq_lock ); return; } else { pthread_cond_wait( &empty, &httpsq_lock ); rv = pthread_mutex_unlock( &httpsq_lock ); usleep( ((unsigned long) pthread_self()) % 1025 + 201 ); goto allover; } } } int UFDBhttpsVerificationQueued( void ) { return _ufdb_httpsq_n_queued; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t entra = PTHREAD_COND_INITIALIZER; pthread_cond_t sale = PTHREAD_COND_INITIALIZER; void * entra_persona(void *); void * sale_persona(void *); int in = 0, out = 0, count = 0, entradas = 0, salidas = 0; int buffer[50]; int main(int argc, char **argv){ pthread_t hilos[25 +25]; int resultado, i, nh; nh = 25 + 25; for (i = 0; i<25; ++i){ resultado = pthread_create(&hilos[i], 0, entra_persona, (void *) i); if (resultado) printf("Error al crear el hilo de entrar_persona.\\n"); } for (i = 0; i < 25; ++i){ resultado = pthread_create(&hilos[25 +i], 0, sale_persona, (void *)i); if (resultado) printf("Error al crear el hilo sale_persona.\\n"); } for (i = 0; i < 25 +25; ++i){ resultado = pthread_join(hilos[i], 0); if (resultado) printf("Error al adjuntar el hilo %d.\\n", i); } pthread_exit(0); return 0; } void *entra_persona(void * arg){ int i, items[100]; int id = (int) arg; printf("+++ El usuario %d entra al sitio Web\\n", id); for (i = 0; i < 100; ++i){ pthread_mutex_lock(&mutex); sleep(rand()%3); if (count < 50){ buffer[in] = items[i]; printf("+++ Ingresó una persona a la sala %d\\n", id); ++in; in %= 50; ++count; ++entradas; if (count == 1) pthread_cond_broadcast(&sale); } else { printf("------------El sitio web esta en espera de resultados de la sala %d ------------\\n", id); pthread_cond_wait(&entra, &mutex); printf("------------El sitio web ya esta disponible para nuevas compras de la sala------------\\n"); } pthread_mutex_unlock(&mutex); } pthread_exit(0); } void *sale_persona(void * arg){ int i; int id = (int) arg; printf("--- Termina la funcion en la sala número %d\\n", id); for (i = 0; i < 100; ++i){ sleep(rand()%3); pthread_mutex_lock(&mutex); if (count > 0){ printf("--- Salió una persona por la sala %d \\n", id); ++out; out %= 50; --count; ++salidas; if (count == (50 -1)) pthread_cond_broadcast(&entra); } else { printf("------------Sitio Web resolviendo peticion de la sala %d para nuevas compras------------\\n", id); pthread_cond_wait(&sale, &mutex); printf("------------Sitio Web resolvio la peticion de la sala %d, lista para nuevas compras------------\\n", id); } pthread_mutex_unlock(&mutex); } pthread_exit(0); }
0
#include <pthread.h> void *anti_syn_flood_check(void *I_do_not_use_this_var ) { int n; struct timeval begin; int count; gettimeofday(&begin,0); for (n=count=0 ; n < e->max_tab_size ; n++) if (e->msg_tab[n].c_syn_tv_sec && (begin.tv_sec - e->msg_tab[n].c_syn_tv_sec) > GARBAGE_RETENTION_TIME) { pthread_mutex_lock(&gl_lock_garbage); memset(&(e->msg_tab[n]),0,sizeof(t_msg)); pthread_mutex_unlock(&gl_lock_garbage); count++; } e->stat_tcpflood_dest_entries += count; if (IS_VERBOSE) send_log(LOG_DEBUG, "[0] Start anti synflood collecting at %d : check %d entry, found %d to destroy (elasped time = %ds)\\n", begin.tv_sec,e->max_tab_size, count, e->synflood_ret_time); if (count * 100 / e->max_tab_size >= 80) send_log(LOG_WARNING, "[46] You reach more than 80% of the max size of your tcp connection buffer. Maybe you should restart with option -a\\n"); return I_do_not_use_this_var; }
1
#include <pthread.h> int knockCount; int idCount; pthread_mutex_t gateLock; pthread_mutex_t threadLock[50]; pthread_mutex_t idLock; pthread_t gateThread; pthread_t waitingThreads[50]; void knockKnock() { pthread_mutex_lock(&gateLock); knockCount++; pthread_mutex_unlock(&gateLock); } int getID() { pthread_mutex_lock(&idLock); idCount++; pthread_mutex_unlock(&idLock); return idCount; } void *threadFunc() { int i = getID(); knockKnock(); printf("Thread %d waiting on gate.\\n", i); pthread_mutex_lock(&threadLock[i]); printf("Thread %d finished.\\n", i); pthread_mutex_unlock(&threadLock[i]); pthread_exit(0); } void *gateWait() { int i; for(i=0; i<50; i++) { pthread_mutex_lock(&threadLock[i]); } while(knockCount < 50); printf("%s\\n", "Unlocked the gate."); for(i=0; i<50; i++) { pthread_mutex_unlock(&threadLock[i]); } pthread_exit(0); } void waitOnThreads() { pthread_join(gateThread, 0); int i; for(i=0; i<50; i++) { pthread_join(waitingThreads[i], 0); } return; } int tearDown() { assert(pthread_mutex_destroy(&gateLock) == 0); assert(pthread_mutex_destroy(&idLock) == 0); int i; for(i=0; i<50; i++) { assert(pthread_mutex_destroy(&threadLock[i]) == 0); } return 0; } int main(int argc, char const *argv[]) { int i; pthread_mutex_init(&gateLock, 0); pthread_mutex_init(&idLock, 0); knockCount = 0; idCount = -1; for(i=0; i<50; i++) { pthread_mutex_init(&threadLock[i], 0); } pthread_create(&gateThread, 0, gateWait, 0); for(i=0; i<50; i++) { pthread_create(&waitingThreads[i], 0, threadFunc, 0); } waitOnThreads(); return tearDown(); }
0
#include <pthread.h> static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER; void output_init() { return; } void output( char * string, ... ) { va_list ap; char *ts="[??:??:??]"; struct tm * now; time_t nw; pthread_mutex_lock(&m_trace); nw = time(0); now = localtime(&nw); if (now == 0) printf(ts); else printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec); __builtin_va_start((ap)); vprintf(string, ap); ; pthread_mutex_unlock(&m_trace); } void output_fini() { return; }
1
#include <pthread.h> void generate(int n); void Read(int n); void *func1(void *arg); void *func2(void *arg); void *func3(void *arg); void calculate(); void resultToFile(); int A[1000]; int B[20][1000]; int prefix_sum[20][1000]={0}; pthread_t tids[20][1000]; pthread_mutex_t mutex; int n; struct S { int i ; int j ; }; int main() { printf("THE ARRAY'S SCALE IS: "); scanf("%d",&n); generate(n); Read(n); clock_t start = clock(); calculate(); resultToFile(); clock_t finish = clock(); printf("COST TIME %.20f SEC\\n",(double)(finish-start)/CLOCKS_PER_SEC); return 0; } void calculate() { int h,i,j,k,l,flag; for(i=1;i<=n;i++) { struct S *s; s = (struct S *)malloc(sizeof(struct S)); s->i = i; if( pthread_create(&tids[0][i],0,func1,s) ) { perror("Fail to create thread!"); exit(1); } } for(j=1;j<=n;j++) pthread_join(tids[0][j],0); printf("A[i]: "); for(j=1;j<=n;j++) printf("%d ",A[j]); printf("\\nAFTER COPY, B EQUALS A:"); for(j=1;j<=n;j++) printf("%d ",B[0][j]); printf("\\n"); for(h=1;h<=log2(n);h++) { for(j=1;j<=n/pow(2,h);j++) { struct S *s; s = (struct S*)malloc(sizeof(struct S)); s->i = h; s->j = j; if( pthread_create(&tids[h][j],0,func2,s) ) { perror("sth is wrong"); exit(1); } } for(j=1;j<=n/pow(2,h);j++) pthread_join(tids[h][j],0); } printf("SUM FORWARD:\\n"); for(h=0;h<=log2(n);h++) { for(l=1;l<=2*h+1;l++) printf(" _ "); for(j=1;j<=n/pow(2,h);j++) { printf("%d",B[h][j]); for(l=1;l<=1+h;l++) printf(" _ "); } printf("\\n"); } for(h=log2(n);h>=0;h--) { for(j=1;j<=n/pow(2,h);j++) { struct S *s; s = (struct S*)malloc(sizeof(struct S)); s->i = h; s->j = j; if( pthread_create(&tids[h][j],0,func3,s) ) { perror("sth is wrong"); exit(1); } } for(j=1;j<=n/pow(2,h);j++) pthread_join(tids[h][j],0); } printf("SUM BACKWARD:\\n"); for(h=log2(n);h>=0;h--) { for(l=1;l<=2*h+1;l++) printf(" _ "); for(j=1;j<=n/pow(2,h);j++) { printf("%d ",prefix_sum[h][j]); for(l=1;l<=h;l++) printf(" _ "); } printf("\\n"); } } void resultToFile() { int i; FILE *file ; file = fopen("/home/ly/parallel/1/prefixSumResult.txt","wt"); for(i=1;i<=n;i++) { fprintf(file,"%-6d",prefix_sum[0][i]); } } void *func1(void *arg) { int i; struct S *p; p = (struct S*)arg; i = p->i; pthread_mutex_lock(&mutex); B[0][i]=A[i]; pthread_mutex_unlock(&mutex); pthread_exit(0); } void *func2(void *args) { int h , j; struct S *p; p = (struct S*)args; h = p->i; j = p->j; pthread_mutex_lock(&mutex); B[h][j]=B[h-1][2*j-1]+B[h-1][2*j]; pthread_mutex_unlock(&mutex); pthread_exit(0); } void *func3(void *arg) { int h,j; struct S *p; p = (struct S*)arg; h = p->i; j = p->j; pthread_mutex_lock(&mutex); if(j==1) prefix_sum[h][1] = B[h][1]; else if (j%2==0) prefix_sum[h][j] = prefix_sum[h+1][j/2] ; else prefix_sum[h][j] = prefix_sum[h+1][(j-1)/2] + B[h][j] ; pthread_mutex_unlock(&mutex); pthread_exit(0); } void generate(int n) { FILE *file1; if( (file1=fopen("/home/ly/parallel/1/arrayA.txt","wt") )==0 ) { perror("fopen"); exit(1); } int i,j; srand( (unsigned)time(0) ); for( i = 1 ; i <= n ;i++) fprintf(file1,"%-8d",rand()%99); fprintf(file1,"\\n"); fclose(file1); } void Read(int n) { FILE *file1; if( (file1=fopen("/home/ly/parallel/1/arrayA.txt","rt") )==0 ) { perror("fopen"); exit(1); } int i,j; srand( (unsigned)time(0) ); for( i = 1 ; i <= n ;i++) fscanf(file1,"%d",&A[i]); fclose(file1); }
0
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top = 0; static unsigned int arr[5]; pthread_mutex_t m; _Bool flag = 0; void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { top == 0 ? 1 : 0; } int push(unsigned int *stack, int x) { if (top == 5) { printf("stack overflow\\n"); return -1; } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (top == 0) { printf("stack underflow\\n"); return -2; } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for (i = 0; i < 5; i++) { __CPROVER_assume(((5 - i) >= 0) && (i >= 0)); { __CPROVER_assume(((5 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint() % 5; if (push(arr, tmp) == (-1)) error(); pthread_mutex_unlock(&m); } } } } void *t2(void *arg) { int i; for (i = 0; i < 5; i++) { __CPROVER_assume(((5 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); if (top > 0) { if (pop(arr) == (-2)) error(); } pthread_mutex_unlock(&m); } } } int main(void) { pthread_t id1; pthread_t id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> int buf_1=0; int buf_2=0; pthread_mutex_t l1; pthread_mutex_t l2; void *prod1() { int aux=0; while(1){ pthread_mutex_lock(l1); if(buf_1 < 6){ aux=buf_1; buf_1=aux+1; aux=0; } pthread_mutex_unlock(l1); } } void *prod2() { int aux=0; while(1){ pthread_mutex_lock(l2); if(buf_2 < 6){ aux=buf_2; buf_2=aux+1; aux=0; } pthread_mutex_unlock(l2); } } void *cons() { int aux=0; while(1){ pthread_mutex_lock(l1); if(buf_1 > 0){ aux=buf_1; buf_1=aux-1; } pthread_mutex_unlock(l1); pthread_mutex_lock(l2); if(buf_2 > 0){ aux=buf_2; buf_2=aux-1; } pthread_mutex_unlock(l2); } } int main() { pthread_t id1; pthread_t id2; pthread_t id3; pthread_mutex_init(l1, 0); pthread_mutex_init(l2, 0); pthread_create(id1, 0, prod1, 0); pthread_create(id2, 0, prod2, 0); pthread_create(id3, 0, cons, 0); pthread_join(id1, 0); pthread_join(id2, 0); pthread_join(id3, 0); }
0
#include <pthread.h> void *print(void *m); struct data { pthread_mutex_t mainlock; pthread_mutex_t childlock; pthread_mutex_t thirdlock; }; int main () { int rt; pthread_t tid; pthread_attr_t attr; struct data d; struct data *dPtr = &d; rt = pthread_mutex_init(&(d.mainlock), 0); if(rt != 0) { perror("Couldn't make pthread init"); } else { printf("Main thread: pthread init successful\\n"); } rt = pthread_mutex_init(&(d.childlock), 0); rt = pthread_mutex_init(&(d.thirdlock), 0); rt = pthread_mutex_lock(&(d.mainlock)); if(rt != 0) { perror("Main: Couldn't make lock main thread"); } else { printf("Main thread: pthread lock successful\\n"); } rt = pthread_mutex_lock(&(d.childlock)); rt = pthread_create(&tid, 0, print, dPtr); printf("pthread create code: %d\\n", rt); printf("Parent: I'm the first\\n"); sleep(3); rt = pthread_mutex_unlock(&(d.mainlock)); rt = pthread_mutex_lock(&(d.thirdlock)); rt = pthread_mutex_lock(&(d.childlock)); pthread_mutex_unlock(&(d.childlock)); printf("Child is unlock now\\n"); printf("User typed enter\\n"); sleep(3); rt = pthread_mutex_unlock(&(d.thirdlock)); rt =pthread_mutex_lock(&(d.mainlock)); pthread_mutex_unlock(&(d.mainlock)); printf("Child is done, program is done\\n"); rt = pthread_mutex_destroy(&(d.mainlock)); printf("Destroy main_lock code: %d\\n", rt); rt = pthread_mutex_destroy(&(d.childlock)); printf("Destroy child_lock code: %d\\n", rt); rt = pthread_mutex_destroy(&(d.thirdlock)); printf("Destroy third_lock code: %d\\n", rt); pthread_join(tid, 0); pthread_exit(0); return 0; } void *print(void *m) { int rt; struct data *dataPtr = m; rt = pthread_mutex_lock(&dataPtr->mainlock); printf("Child: I'm the second\\n"); sleep(3); rt = pthread_mutex_unlock(&dataPtr->childlock); rt = pthread_mutex_lock(&dataPtr->thirdlock); pthread_mutex_unlock(&dataPtr->thirdlock); printf("Child is exiting now\\n"); sleep(3); rt = pthread_mutex_unlock(&dataPtr->mainlock); return 0; }
1
#include <pthread.h> void matrixMultiply(void* params); void matrixLoad(int rc, int**mat, FILE* fr1); int matSize(char *line); int rc; int num_thrd; pthread_mutex_t lock; struct matrixMultParam{ int** matrix1; int** matrix2; int** solution; int slice; }; int main(int argc,char *argv[]) { pthread_t* thread; num_thrd = atoi(argv[4]); FILE *fr1,*fr2,*fw; int **mat1, **mat2, **solution; int rc1, rc2; int toStdOut=1; char line[10000]; if (argc!=5) { toStdOut=0; } fr1=fopen(argv[1],"r"); if (fr1==0) { printf("Cannot open %s. Program terminated...",argv[1]); exit(1); } fr2=fopen(argv[2],"r"); if (fr2==0) { printf("Cannot open %s. Program terminated...",argv[2]); exit(1); } fgets(line,10000,fr1); rc1=matSize(line); fgets(line,10000,fr2); rc2 = matSize(line); if (rc1 == rc2) { rc = rc1; mat1=(int **)malloc(sizeof(int *)*rc); mat2=(int **)malloc(sizeof(int *)*rc); solution=(int **)malloc(sizeof(int *)*rc); int i; for(i=0; i<rc1; ++i) { mat1[i] = malloc(rc1*sizeof(int)); } for(i=0; i<rc1; ++i) { mat2[i] = malloc(rc1*sizeof(int)); } for(i=0; i<rc1; ++i) { solution[i] = malloc(rc1*sizeof(int)); } matrixLoad(rc1, mat1, fr1); matrixLoad(rc1,mat2,fr2); pthread_mutex_init(&lock,0); struct matrixMultParam params; params.matrix1= mat1; params.matrix2= mat2; params.solution = solution; thread = (pthread_t*)malloc(num_thrd*sizeof(pthread_t)); for(int i = 1; i < num_thrd; i++){ pthread_mutex_lock(&lock); params.slice = i; if(pthread_create(&thread[i], 0, matrixMultiply, (void*)(&params)) !=0){ printf("couldn't create thread"); free(thread); exit(1); } } pthread_mutex_lock(&lock); params.slice = 0; matrixMultiply((void*)&params); pthread_mutex_destroy(&lock); if(num_thrd == 0) printf("not a valid number of threads"); for(int i=1; i <num_thrd; ++i){ pthread_join(thread[i],0); } fclose(fr1); fclose(fr2); } else { printf("Program terminated. Both matrices need to be the same size"); exit(1); } if (toStdOut==1) { fw=fopen(argv[3],"w"); if (fw==0) { printf("File not created. Program terminated..."); exit(1); } int i,k; for( i = 0; i < rc1;++i) { for(k = 0; k<rc1; ++k) { fprintf(fw,"%d ", solution[k][i]); } fprintf(fw,"\\n"); } fclose(fw); } else { int i,k; for(i = 0; i < rc1;++i) { for(k = 0; k<rc1; ++k) { printf("%d ", solution[k][i]); } printf("\\n"); } } return 0; } int matSize(char *line) { int count=0; char delimeters[] = " "; char *token = strtok(line, delimeters); while((strcmp(token, "\\n") != 0) && token != 0) { count++; token =strtok(0, delimeters); } return count; } void matrixMultiply(void* params) { struct matrixMultParam matrices = *(struct matrixMultParam*)params; int s = (int)matrices.slice; pthread_mutex_unlock(&lock); int from = (s*rc)/num_thrd; int to = ((s+1)*rc)/num_thrd; for(int i =from; i < to;++i) { for(int j=0;j<rc; ++j){ matrices.solution[i][j] = 0; for(int k=0; k<rc; ++k){ matrices.solution[i][j] += matrices.matrix1[i][k]*matrices.matrix2[k][j]; } } } } void matrixLoad(int rc, int **mat, FILE* fr1) { int val,i,k; rewind(fr1); for( i=0; i< rc; ++i) { for( k=0; k<rc; ++k) { fscanf(fr1,"%i", &val); mat[k][i] = val; } } }
0
#include <pthread.h> struct protoent *getprotobyname(const char *name) { char *buf = _proto_buf(); if (!buf) return 0; return getprotobyname_r(name, (struct protoent *) buf, buf + sizeof(struct protoent), PROTO_BUFSIZE); } struct protoent *getprotobyname_r(const char *name, struct protoent *result, char *buf, int bufsize) { char **alias; pthread_mutex_lock(&proto_iterate_lock); setprotoent(0); while ((result = getprotoent_r(result, buf, bufsize)) != 0) { if (strcmp(result->p_name, name) == 0) break; for (alias = result->p_aliases; *alias != 0; alias++) { if (strcmp(*alias, name) == 0) break; } } pthread_mutex_unlock(&proto_iterate_lock); return result; }
1
#include <pthread.h> void * (*process)(void *arg); void * arg; struct worker* next; }CThread_worker; pthread_mutex_t queue_lock; pthread_cond_t queue_ready; CThread_worker *queue_head; int shutdown; pthread_t * threadid; int max_thread_num; int cur_queue_size; }CThread_pool; int pool_add_worker(PROCESS,void*); void *thread_routine(void * arg); static CThread_pool *pool=0; void pool_init(int max_threads){ assert(max_threads>1); pool=(CThread_pool*)malloc(sizeof(CThread_pool)); pthread_mutex_init(&pool->queue_lock,0); pthread_cond_init(&pool->queue_ready,0); pool->queue_head=0; pool->shutdown=0; pool->max_thread_num=max_threads; pool->cur_queue_size=0; pool->threadid=(pthread_t*)malloc(sizeof(pthread_t)*max_threads); for(int i=0;i<max_threads;i++){ pthread_create(pool->threadid+i,0,thread_routine,0); } } int pool_add_worker(PROCESS process,void* arg){ assert(process!=0); CThread_worker *newworker=(CThread_worker*)malloc(sizeof(CThread_worker)); newworker->process=process; newworker->arg=arg; newworker->next=0; pthread_mutex_lock(&(pool->queue_lock)); CThread_worker *member=pool->queue_head; if(member!=0){ while(member->next!=0){ member=member->next; } member->next=newworker; }else{ pool->queue_head=newworker; } assert(pool->queue_head!=0); pool->cur_queue_size++; pthread_mutex_unlock(&pool->queue_lock); pthread_cond_signal(&pool->queue_ready); return 0; } int pool_destroy(){ if(pool->shutdown){return -1;} pool->shutdown=1; pthread_cond_broadcast(&pool->queue_ready); for(int i=0;i<pool->max_thread_num;i++){ pthread_join(pool->threadid[i],0); } free(pool->threadid); CThread_worker* head =0; while(pool->queue_head){ head=pool->queue_head; pool->queue_head=pool->queue_head->next; free(head); } pthread_mutex_destroy(&pool->queue_lock); pthread_cond_destroy(&pool->queue_ready); free(pool); pool=0; return 0; } void * thread_routine(void* arg){ printf("starting processing thread 0x%x\\n",pthread_self()); while(1){ pthread_mutex_lock(&pool->queue_lock); while(pool->cur_queue_size==0&&!pool->shutdown){ printf("thread 0x%x is wating\\n",pthread_self()); pthread_cond_wait(&pool->queue_ready,&pool->queue_lock); } if(pool->shutdown){ pthread_mutex_unlock(&pool->queue_lock); printf("thread 0x%x will exit\\n",pthread_self()); pthread_exit(0); } printf("thread 0x%x is starting to work\\n",pthread_self()); assert(pool->cur_queue_size!=0); assert(pool->queue_head!=0); pool->cur_queue_size--; CThread_worker* worker=pool->queue_head; pool->queue_head=pool->queue_head->next; pthread_mutex_unlock(&pool->queue_lock); (*(worker->process))(worker->arg); free(worker); worker=0; } pthread_exit(0); } void * myprocess(void* arg){ printf("threadid is 0x%x ,working on task %d\\n", pthread_self(),*(int*)arg); sleep(2); return 0; } void main(){ pool_init(5); int num[10]={0}; for(int i=0;i<10;i++){ num[i]=i; pool_add_worker(myprocess,&num[i]); } sleep(10); pool_destroy(); return 0; }
0