text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> extern void __VERIFIER_error() ; int __VERIFIER_nondet_int(void); void ldv_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error();}; return; } pthread_t t1; pthread_mutex_t mutex; int pdev; void *thread1(void *arg) { pthread_mutex_lock(&mutex); pdev = 6; ldv_assert(pdev==6); pthread_mutex_unlock(&mutex); } int module_init() { pthread_mutex_init(&mutex, 0); pdev = 1; ldv_assert(pdev==1); if(__VERIFIER_nondet_int()) { pthread_create(&t1, 0, thread1, 0); return 0; } pdev = 3; ldv_assert(pdev==3); pthread_mutex_destroy(&mutex); return -1; } void module_exit() { void *status; pthread_join(t1, &status); pthread_mutex_destroy(&mutex); pdev = 5; ldv_assert(pdev==5); } int main(void) { if(module_init()!=0) goto module_exit; module_exit(); module_exit: return 0; }
1
#include <pthread.h> static int sockets[MAX_CONNECTION]; static pthread_mutex_t verrou_connexion = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t verrou_ecriture = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t verrou_deconnexion = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t verrou_stats = PTHREAD_MUTEX_INITIALIZER; static void add_socket(int fd) { int i; pgrs_in(); for (i=0; i<MAX_CONNECTION; i++) { if (sockets[i] == 0) { sockets[i] = fd; break; } } assert(i!=MAX_CONNECTION); pgrs_out(); } static void del_socket(int fd) { int i; pgrs_in(); for (i=0; i<MAX_CONNECTION; i++) { if (sockets[i] == fd) { sockets[i] = 0; break; } } assert(i!=MAX_CONNECTION); pgrs_out(); } static void signal_handler(int sig) { pgrs_in(); pgrs("affichage des statistiques..."); print_stats(); pgrs("...affichage des statistiques"); pgrs_out(); } static void repeater(int sckt) { char buf[MAX_BUFFER]; int nbc, i; struct sigaction sa; const char WELCOME[] = "mtcs : bienvenue\\n"; sa.sa_handler = signal_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; sigaction(SIGSTAT,&sa,(struct sigaction *) 0); pgrs_in(); write(sckt, WELCOME, strlen(WELCOME)); pgrs("enregistrement d'une socket"); pthread_mutex_lock(&verrou_connexion); add_socket(sckt); pthread_mutex_lock(&verrou_stats); update_nb_clients(TRUE); update_max_clients(); pthread_mutex_unlock(&verrou_stats); pthread_mutex_unlock(&verrou_connexion); while (1) { pgrs("attente read"); nbc = read(sckt, buf, MAX_BUFFER); if (nbc <= 0) { pgrs("fin lecture client"); pgrs("desenregistrement d'une socket"); pthread_mutex_lock(&verrou_deconnexion); del_socket(sckt); pthread_mutex_lock(&verrou_stats); update_nb_clients(FALSE); pthread_mutex_unlock(&verrou_stats); pthread_mutex_unlock(&verrou_deconnexion); close(sckt); pgrs_out(); return; } pgrs("boucle ecriture"); pthread_mutex_lock(&verrou_ecriture); for(i=0; i<MAX_CONNECTION; i++) { if (sockets[i]) { write(sockets[i], buf, nbc); } } pthread_mutex_lock(&verrou_stats); update_snt_lines(); update_rcv_lines(); update_max_rcv_lines_by_client(); update_max_snt_lines_to_client(); pthread_mutex_unlock(&verrou_stats); pthread_mutex_unlock(&verrou_ecriture); pgrs("fin boucle ecriture"); } } void *pt_repeater(void *arg) { int n; n = (int) arg; repeater(n); return 0; } int manage_cnct(int fd) { pthread_t t; int status; pgrs_in(); status = pthread_create(&t,0,pt_repeater,(void *) fd); assert(!status); status = pthread_detach(t); assert(!status); pgrs_out(); return 0; }
0
#include <pthread.h> void rpcap_init() { _ports_used = 0; _nb_port_used = 0; _rpcap_port_min = _rpcap_port_max = -1; pthread_mutex_init(&_mutex_port_req, 0); } int rpcap_get_port() { int i; int ret = -1; pthread_mutex_lock(&_mutex_port_req); ret = _rpcap_port_min; do { for (i = 0; i <_nb_port_used; i++) { if (_ports_used[i] == ret) { ++ret; break; } } } while (i != _nb_port_used); ++_nb_port_used; if (_ports_used == 0) { _ports_used = (int *)malloc(sizeof(int)); } else { _ports_used = (int *)realloc(_ports_used, sizeof(int) * _nb_port_used); } _ports_used[_nb_port_used - 1] = ret; pthread_mutex_unlock(&_mutex_port_req); return ret; } void rpcap_free_port(int port) { int i; pthread_mutex_lock(&_mutex_port_req); for (i = 0; i <_nb_port_used; i++) { if (_ports_used[i] == port) { --_nb_port_used; _ports_used[i] = _ports_used[_nb_port_used]; _ports_used = (int *)realloc(_ports_used, sizeof(int) * _nb_port_used); break; } } pthread_mutex_unlock(&_mutex_port_req); } int rpcap_add_ports(int min, int max) { _rpcap_port_min = _rpcap_port_max = -1; if (min > max) { return 1; } if (min < 1 || max < 1) { return 1; } if (min > 65535 || max > 65535) { return 1; } _rpcap_port_min = min; _rpcap_port_max = max; return 0; } struct server_params * rpcap_start_socket(int port) { int success; struct server_params * rpcap_server_params = init_new_server_params(); rpcap_server_params->port = port; rpcap_server_params->server->encrypt = 0; rpcap_server_params->single_connection = 1; rpcap_server_params->server->thread_type = THREAD_TYPE_RPCAP; rpcap_server_params->server->handle_client_data = handle_rpcap_data; rpcap_server_params->server->send_client_data = send_rpcap_data; rpcap_server_params->server->upon_connection_receive = receive_pcap_file_header; rpcap_server_params->identifier = (char *)calloc(1, (strlen(MUTEX_NAME_RPCAP) + 5 + 1) * sizeof(char)); sprintf(rpcap_server_params->identifier, "%s%d", MUTEX_NAME_RPCAP, port); success = create_server_listening(rpcap_server_params, &_stop_threads); if (success == 0) { return rpcap_server_params; } return 0; } void free_global_memory_rpcap_server() { pthread_mutex_destroy(&_mutex_port_req); FREE_AND_NULLIFY(_ports_used); } int receive_pcap_file_header(unsigned char ** data, int * data_length, struct client_params * params) { if (!data || !(*data) || !data_length || !params) { return UPON_CONNECTION_RECEIVE_FAILURE; } if (*data_length < sizeof(struct pcap_file_header)) { return UPON_CONNECTION_RECEIVE_NOT_ENOUGH_DATA; } params->received_packets->pcap_header = (struct pcap_file_header*)malloc(sizeof(struct pcap_file_header)); memcpy(params->received_packets->pcap_header, *data, sizeof(struct pcap_file_header)); remove_bytes_from_buffer(data, data_length, sizeof(struct pcap_file_header), 1); return UPON_CONNECTION_RECEIVE_SUCCESS; }
1
#include <pthread.h> int niter = 100000,i, count=0,total_threads; pthread_mutex_t pthread; void *calculatePiValue(void* rank) { long my_rank = (long) rank; double x,y,z; int sz = niter/total_threads; int start_i = my_rank*sz; int end_i = start_i + sz - 1; pthread_mutex_lock(&pthread); for (i=start_i; i<end_i; ++i) { x = (double)random()/32767; y = (double)random()/32767; z = sqrt((x*x)+(y*y)); if (z<=1) { ++count; } } pthread_mutex_unlock(&pthread); return 0; } int main(int argc, char* argv[]) { long th; pthread_t* thread_handles; printf("Enter the value of N\\n"); scanf("%d", &niter); total_threads = strtol(argv[1], 0, 10); pthread_mutex_init(&pthread, 0); thread_handles = malloc(sizeof(pthread_t)*total_threads); for (th = 0; th < total_threads; th++) pthread_create(&thread_handles[th], 0, calculatePiValue, (void*) th); for (th = 0; th < total_threads; th++) pthread_join(thread_handles[th], 0); double pi = ((double)count/(double)niter)*4.0; printf("Pi: %f\\nNumber of Points inside circle %i\\n", pi, count); return 0; }
0
#include <pthread.h> int **matrix; int max_col = 0; uint64_t time_par; struct thread_data{ int col_pos; int start; int end; }; struct thread_data thread_data_array[4]; pthread_t threads[4]; pthread_mutex_t mutexcomp; void printmatrix(int **matrix); void *findMAX(void *arg); void max_pthread(int **matrix, int col); void Initialize(); void max_sequential(int **matrix); void freealloc(); void Initialize(){ time_par = 0; srand(6); matrix = (int **)malloc(sizeof(int*) * 256); for(int i=0; i<256; i++) matrix[i] = (int *)malloc(sizeof(int)*256); for(int i=0;i<256;i++) for(int j=0;j<256;j++) matrix[i][j] = rand()%1000-500; } void freealloc(){ for(int i=0;i<256;i++) free(matrix[i]); free(matrix); } void printmatrix(int **matrix){ for(int i=0;i<256;i++){ for(int j=0;j<256;j++){ printf("%5.d, ", matrix[i][j]); } printf("\\n"); } printf("\\n"); } void *findMAX(void *arg){ int max_row_pos; int i, j; struct thread_data *my_data; my_data = (struct thread_data *)arg; max_row_pos = my_data->start; j = my_data->col_pos; for(i = my_data->start; i<=my_data->end;i++){ if(abs(matrix[i][j]) > abs(matrix[max_row_pos][j])){ max_row_pos = i; } } pthread_mutex_lock(&mutexcomp); if( abs(matrix[max_row_pos][j]) > abs(matrix[max_col][j]) ){ max_col = max_row_pos; } pthread_mutex_unlock(&mutexcomp); pthread_exit(0); } void max_pthread(int **matrix, int col){ struct timespec start, end; uint64_t consumed_time; int t; int thread_num = 4; void *status; while((256 -col)/thread_num < 2){ thread_num = thread_num-1; } max_col = col; pthread_attr_t attr; pthread_mutex_init(&mutexcomp, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); clock_gettime(CLOCK_MONOTONIC, &start); for(t=0; t<thread_num; t++){ thread_data_array[t].start = col + t*(256 -col)/thread_num; thread_data_array[t].end = thread_data_array[t].start+(256 -col)/thread_num-1; if(t >= thread_num - (256 -col)%thread_num) thread_data_array[t].end = thread_data_array[t].end +1; thread_data_array[t].col_pos = col; int rc = pthread_create(&threads[t], &attr, findMAX, (void*)&thread_data_array[t]); } pthread_attr_destroy(&attr); for(t=0; t<thread_num;t++){ pthread_join(threads[t], &status); } clock_gettime(CLOCK_MONOTONIC, &end); consumed_time= (end.tv_sec - start.tv_sec)*1000000000L +(end.tv_nsec - start.tv_nsec); time_par = consumed_time + time_par; pthread_mutex_destroy(&mutexcomp); if(col != max_col){ for(t=0; t< 256;t++){ int temp = matrix[col][t]; matrix[col][t] = matrix[max_col][t]; matrix[max_col][t] = temp; } } return; } void max_sequential(int **matrix){ struct timespec start, end; uint64_t time_seq; uint64_t total= 0; for(int i=0; i<256; i++){ clock_gettime(CLOCK_MONOTONIC, &start); int max_val = 0; int max_row = -1; for(int j=i; j<256; j++){ if(abs(matrix[j][i])> max_val ){ max_val = abs(matrix[j][i]); max_row = j; } } clock_gettime(CLOCK_MONOTONIC, &end); time_seq = (end.tv_sec - start.tv_sec)*1000000000L + (end.tv_nsec - start.tv_nsec); total += time_seq; int *temp = matrix[max_row]; matrix[max_row] = matrix[i]; matrix[i] = temp; } printf("The sequential time cost is %llu ns.\\n", total); } int main(int argc, char** argv){ printf("Below is sequential algo.\\n"); Initialize(); max_sequential(matrix); freealloc(); printf("Below is parallel algo.\\n"); Initialize(); for(int i = 0; i < 256 -1; i++) max_pthread(matrix, i); freealloc(); printf("The time with pthread is %llu ns. \\n", time_par); return 1 ; }
1
#include <pthread.h> int sd; pthread_mutex_t sendlock; void _dispatch_packet(struct tcp_header*, size_t, uint32_t, uint32_t); int init_tcp_rw() { sd = socket(PF_INET, SOCK_RAW, IPPROTO_TCP); if (sd < 0) { printf("Could not initialize socket\\n"); return 1; } pthread_mutex_init(&sendlock, 0); return 0; } void* socket_read_loop(void* unused ) { void* buffer = malloc(4096); ssize_t amt; struct tcp_header* tcphdr; uint32_t srcaddr_nw; uint32_t destaddr_nw; uint32_t iphdr_len; uint16_t msg_len; while (1) { amt = recv(sd, buffer, 4096, 0); if (amt == -1) { if (errno == EINTR) { printf("Signal\\n"); continue; } else { printf("TCP Loop is terminating\\n"); break; } } else if (amt == 4096) { printf("Packet size is >= 4 KiB; dropping it\\n"); continue; } srcaddr_nw = ((uint32_t*) buffer)[3]; destaddr_nw = ((uint32_t*) buffer)[4]; iphdr_len = (((uint8_t*) buffer)[0] & 0xF) << 2; msg_len = ntohs(((uint16_t*) buffer)[1]); tcphdr = (struct tcp_header*) (((uint8_t*) buffer) + iphdr_len); if (srcaddr_nw != LOCALHOST && get_checksum((struct in_addr*) &srcaddr_nw, (struct in_addr*) &destaddr_nw, tcphdr, msg_len - iphdr_len)) { continue; } _dispatch_packet(tcphdr, msg_len - iphdr_len, srcaddr_nw, destaddr_nw); } free(buffer); return 0; } int transmit_segment(struct tcp_socket* tcpsock, struct tcp_header* tcpseg, size_t seglen) { ssize_t sent = -1; errno = 0; pthread_mutex_lock(&sendlock); sent = sendto(sd, tcpseg, seglen, 0, (struct sockaddr*) &tcpsock->remote_addr, sizeof(tcpsock->remote_addr)); if (sent < 0) { perror("Could not send data"); } pthread_mutex_unlock(&sendlock); return sent; } void send_tcp_msg(struct tcp_socket* tcpsock, uint8_t flags, uint32_t seqnum, uint32_t acknum, void* msgbody, size_t msgbody_len, int retransmit) { uint16_t cksum; size_t len = msgbody_len + sizeof(struct tcp_header); struct tcp_header* tcpseg = malloc(len); if (msgbody_len) { memcpy(tcpseg + 1, msgbody, msgbody_len); } tcpseg->seqnum = htonl(seqnum); tcpseg->acknum = htonl(acknum); tcpseg->winsize = htons(tcpsock->RCV.WND); tcpseg->urgentptr = htons(tcpsock->SND.UP); tcpseg->flags = flags; tcpseg->offset_reserved_NS = 0; tcpseg->srcport = tcpsock->local_addr.sin_port; tcpseg->destport = tcpsock->remote_addr.sin_port; tcpseg->offset_reserved_NS |= (((uint8_t) sizeof(struct tcp_header)) << 2); tcpseg->urgentptr = 0; tcpseg->checksum = 0; cksum = get_checksum(&tcpsock->local_addr.sin_addr, &tcpsock->remote_addr.sin_addr, tcpseg, len); tcpseg->checksum = cksum; transmit_segment(tcpsock, tcpseg, len); if (retransmit) { if (cbuf_write_segment(tcpsock->retrbuf, (uint8_t*) tcpseg, len) < 0) { printf("Retransmit queue is full for socket %d\\n", tcpsock->index); } } free(tcpseg); } void send_tcp_ctl_msg(struct tcp_socket* tcpsock, uint8_t flags, uint32_t seqnum, uint32_t acknum, int retransmit) { send_tcp_msg(tcpsock, flags, seqnum, acknum, 0, 0, retransmit); } void halt_tcp_rw() { pthread_mutex_destroy(&sendlock); close(sd); }
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*100000*sizeof(double)); b = (double*) malloc (4*100000*sizeof(double)); for (i=0; i<100000*4; i++) { a[i]=1; b[i]=a[i]; } dotstr.veclen = 100000; dotstr.a = a; dotstr.b = b; dotstr.sum=0; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0;i<4;i++) { pthread_create(&callThd[i], &attr, dotprod, (void *)i); } pthread_attr_destroy(&attr); for(i=0;i<4;i++) { pthread_join(callThd[i], &status); } printf ("Sum = %f \\n", dotstr.sum); free (a); free (b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
1
#include <pthread.h> char bwc_buffer[BUFFER_LENGTH]; char bwss_buffer[BUFFER_LENGTH]; pthread_t bwss_thread; pthread_t bwc_thread; char *bwss_port; char *bwc_port; int bwc_socket; int bwss_socket; int ready; pthread_mutex_t mutex; pthread_cond_t cond; void *connect_client(void *pcl); void *bwc_connect(void * ptr); void *bwss_connect(void *ptr); void DwriteUDP(int cl, char *buf, int l) { if(l >= 0) { if(write(cl, buf, l) != l) { perror("falló write en el socket"); exit(1); } } fprintf(stderr, "DwriteUDP: %d bytes \\n", l); } int main(int argc, char **argv) { char *bwss_server; if(argc == 1) { bwss_server = "localhost"; bwss_port = "2000"; bwc_port = "2001"; } else if (argc == 2) { bwss_server = argv[1]; bwss_port = "2000"; bwc_port = "2001"; } else if(argc == 4) { bwss_server = argv[1]; bwss_port = argv[2]; bwc_port = argv[3]; } else { fprintf(stderr, "Use: bwcs bwss_server server_port client_port\\n"); return 1; } ready = 0; pthread_mutex_init(&mutex,0); pthread_cond_init(&cond,0); pthread_create(&bwc_thread, 0, bwc_connect, (void *)bwc_port); pthread_create(&bwss_thread, 0, bwss_connect, (void *)bwss_server); pthread_join(bwc_thread, 0); pthread_join(bwss_thread, 0); return 0; } void *bwss_connect(void *ptr) { int bytes, cnt; if((bwss_socket = j_socket_udp_connect((char *)ptr, bwss_port)) < 0) { printf("udp connect failed\\n"); exit(1); } for(bytes=0;; bytes+=cnt) { int size = BUFFER_LENGTH; cnt = read(bwss_socket, bwc_buffer, size); fprintf(stderr, "ReadUDP: %d bytes\\n", cnt); if(cnt <= 0) { break; } Dwrite(bwc_socket, bwc_buffer, cnt); } Dwrite(bwc_socket, bwc_buffer, 0); pthread_mutex_lock(&mutex); ready = 1; Dclose(bwss_socket); pthread_cond_broadcast(&cond); pthread_mutex_unlock(&mutex); fprintf(stderr, "SOCKET UDP CERRADO\\n"); return 0; } void *bwc_connect(void* ptr) { int s, s2; int *p; s = j_socket_tcp_bind((char *) ptr); if(s < 0) { fprintf(stderr, "bind failed\\n"); exit(1); } s2 = j_accept(s); p = (int *)malloc(sizeof(int)); *p = s2; connect_client((void *)p); return 0; } void* connect_client(void *pcl){ int bytes, cnt; bwc_socket = *((int *)pcl); free(pcl); DwriteUDP(bwss_socket, bwss_buffer, 0); for(bytes=0;; bytes+=cnt) { cnt = Dread(bwc_socket, bwss_buffer, BUFFER_LENGTH); if(cnt <= 0) break; DwriteUDP(bwss_socket, bwss_buffer, cnt); } DwriteUDP(bwss_socket, bwss_buffer, 0); pthread_mutex_lock(&mutex); while(!ready) pthread_cond_wait(&cond, &mutex); Dclose(bwc_socket); pthread_mutex_unlock(&mutex); fprintf(stderr, "SOCKET TCP CERRADO\\n"); return 0; }
0
#include <pthread.h> int main(int argc, char* argv[]) { pthread_mutex_t mutex; pthread_mutexattr_t mutexattr; int* x; char* ptr; int rt; int ret; pthread_mutexattr_init(&mutexattr); pthread_mutexattr_setpshared(&mutexattr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&mutex, &mutexattr); rt = fork(); if(rt == 0) { int child_shmid; child_shmid = shm_open("myshared", O_RDWR | O_CREAT, S_IRWXU | S_IRGRP); if(-1 == child_shmid) { perror("shm_open failed in child process!"); exit(-1); } ftruncate(child_shmid, sizeof(int)); ptr = (char*)mmap(0, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, child_shmid, 0); x = (int*)ptr; int i; for(i = 0; i < 10; i++) { ret = pthread_mutex_lock(&mutex); if(ret == 0) { (*x)++; printf("child process++ && x = %d\\n", *x); } pthread_mutex_unlock(&mutex); sleep(1); } } else { int father_shmid; father_shmid = shm_open("myshared", O_RDWR | O_CREAT, S_IRWXU | S_IRGRP); ftruncate(father_shmid, sizeof(int)); ptr = (char*)mmap(0, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, father_shmid, 0); x = (int*)ptr; int i; for(i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); (*x) += 2; printf("father process+2 && x = %d\\n", *x); pthread_mutex_unlock(&mutex); sleep(1); } } shm_unlink("myshared"); munmap(ptr, sizeof(int)); return 0; }
1
#include <pthread.h> double elapsedTimesInThreads[ 16 ]; int threadCounter = 0; pthread_mutex_t mutex; void* threadFunction( void* rank ); int main( void ) { pthread_mutex_init( &mutex, 0 ); pthread_t* threadHandles = ( pthread_t* )malloc( 16 * sizeof( pthread_t ) ); for( long threadIndex = 0; threadIndex < 16; threadIndex++ ) { pthread_create( ( threadHandles + threadIndex ), 0, threadFunction, ( void* )threadIndex ); } for( long threadIndex = 0; threadIndex < 16; threadIndex++ ) { pthread_join( *( threadHandles + threadIndex ), 0 ); } for( long threadIndex = 0; threadIndex < 16; threadIndex++ ) { printf( "thread %ld: %f \\n", threadIndex, elapsedTimesInThreads[ threadIndex ] ); } } void* threadFunction( void* rank ) { long threadRank = ( long ) rank; double startTimeOfThread, finishTimeOfThread; GET_TIME( startTimeOfThread ); pthread_mutex_lock( &mutex ); threadCounter = threadCounter + 1; printf( "thread Rank : %ld \\t Counter: %d \\n", threadRank, threadCounter ); pthread_mutex_unlock( &mutex ); while( threadCounter < 16 ); GET_TIME( finishTimeOfThread ); elapsedTimesInThreads[ threadRank ] = finishTimeOfThread - startTimeOfThread; return 0; }
0
#include <pthread.h> pthread_mutex_t aarrived, barrived; pthread_cond_t lock; int islocked = 0; void main() { pthread_cond_init(&lock, 0); pthread_mutex_init(&aarrived, 0); pthread_mutex_init(&barrived, 0); pthread_t threada, threadb; void *threadAFunction(), *threadBFunction(); pthread_create(&threada, 0, *threadAFunction, 0); pthread_create(&threadb, 0, *threadBFunction, 0); pthread_join(threada, 0); pthread_join(threadb, 0); } void sem_wait(pthread_mutex_t *mutex) { pthread_mutex_lock(mutex); if (islocked != 0) { islocked = pthread_cond_wait(&lock, mutex); } pthread_mutex_unlock(mutex); } void sem_signal(pthread_mutex_t *mutex) { pthread_mutex_unlock(mutex); pthread_cond_signal(&lock); } void *threadAFunction() { puts("a1"); sem_signal(&aarrived); sem_wait(&barrived); puts("a2"); pthread_exit(0); } void *threadBFunction() { puts("b1"); sem_signal(&barrived); sem_wait(&aarrived); puts("b2"); pthread_exit(0); }
1
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long) t; for (i = 0; i < 10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { printf("inc_count(): thread %ld, count = %d Threshold reached. ", my_id, count); pthread_cond_signal(&count_threshold_cv); printf("Just sent signal.\\n"); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long) t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while (count < 12) { printf("watch_count(): thread %ld Count= %d. Going into wait...\\n", my_id, count); pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received. Count= %d\\n", my_id, count); printf("watch_count(): thread %ld Updating the value of count...\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } printf("watch_count(): thread %ld Unlocking mutex.\\n", my_id); pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int i, rc; long t1 = 1, t2 = 2, t3 = 3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init(&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *) t1); pthread_create(&threads[1], &attr, inc_count, (void *) t2); pthread_create(&threads[2], &attr, inc_count, (void *) t3); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf("Main(): Waited and joined with %d threads. Final value of count = %d. Done.\\n", 3, count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
0
#include <pthread.h> static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int var = 1; void *thread_a(void *arg); void *thread_b(void *arg); int main(){ int shmid = shmget(IPC_PRIVATE, sizeof(int), S_IRUSR | S_IWUSR); if (shmid==-1){ perror("Error creating shared memory!\\n"); return 0; } int *pointer = (int *) shmat(shmid, 0, 0); pthread_mutex_lock(&mutex); pthread_t thread_1, thread_2; pthread_create(&thread_1, 0, thread_a, pointer); pthread_create(&thread_2, 0, thread_b, pointer); pthread_join(thread_1, 0); pthread_join(thread_2, 0); printf("Terminating process...\\n"); pthread_mutex_destroy(&mutex); shmctl(shmid, IPC_RMID, 0); pthread_exit(0); return 0; } void *thread_a(void *arg){ int number_father = 5; int response; do{ printf("[Father] Try to guess the number is: %d\\n", number_father); while(var != 1) pthread_cond_wait(&cond, &mutex); *((int *) arg) = number_father; var = 0; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&mutex); while(var != 1) pthread_cond_wait(&cond, &mutex); response = *((int *) arg); if(response == 1) number_father--; else if (response == -1) number_father++; else if(response != 0) perror("Error occured in father!\\n"); }while(response!=0); printf("[Father] The guess number was: %d\\n", number_father); pthread_exit(0); return 0; } void *thread_b(void *arg){ int randn_child = rand() % 10; int response; do{ pthread_mutex_lock(&mutex); while(var != 0) pthread_cond_wait(&cond, &mutex); response = *((int *) arg); if(response > randn_child){ printf("[Child] Wrong! The number is smaller than attempt.\\n"); response = 1; } else if(response < randn_child){ printf("[Child] Wrong! The number is bigger than attempt.\\n"); response = -1; }else{ printf("[Child] Yeeh! The number is equal to attempt.\\n"); response = 0; } *((int *) arg) = response; var = 1; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&mutex); }while(response!=0); pthread_exit(0); 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) err_exit(err, "sigwait failed"); 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) err_exit(err, "SIG_BLOCK error"); err = pthread_create(&tid, 0, thr_fn, 0); if (err != 0) err_exit(err, "can't create thread"); 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) err_sys("SIG_SETMASK error"); exit(0); }
0
#include <pthread.h> int pid_map[(350 -300 +1)]; pthread_mutex_t mutex; int allocate_map(void) { int i; pthread_mutex_init(&mutex,0); pthread_mutex_lock(&mutex); for(i =0;i<(350 -300 +1); i++) pid_map[i] = 0; pthread_mutex_unlock(&mutex); return 1; } int allocate_pid(void) { int result = -1; pthread_mutex_lock(&mutex); int i; for(i=(350 -300); i >= 0; i--) { if(pid_map[i] == 0){ pid_map[i] = 1; result = i + 300; break; } } pthread_mutex_unlock(&mutex); return result; } void release_pid(int pid) { pthread_mutex_lock(&mutex); pid_map[pid - 300] = 0; pthread_mutex_unlock(&mutex); } pthread_mutex_t test_mutex; void *allocator(void *param) { int pid; int i; for(i = 0; i < 10; i++) { sleep((int)(random() % 5)); pthread_mutex_lock(&test_mutex); pid = allocate_pid(); pthread_mutex_unlock(&test_mutex); if(pid !=-1) { printf("PID:%d allocated\\n",pid); sleep((int)(random() % 5)); pthread_mutex_lock(&test_mutex); release_pid(pid); pthread_mutex_unlock(&test_mutex); printf("released %d\\n", pid); } } } int main(void) { int i; pthread_t tids[100]; pthread_mutex_init(&test_mutex, 0); allocate_map(); srand(time(0)); for(i=0;i < 100;i++) { pthread_create(&(tids[i]),0,&allocator,0); } for(i=0;i < 100;i++) pthread_join(tids[i], 0); printf("***DONE***\\n"); return 0; }
1
#include <pthread.h> extern pthread_mutex_t timer_queue_mutex; extern void tsSendPeriodicTau(unsigned char ueId); void *timer_thread_main(void *data) { int i; int j; timer_queue_msg *tqm; while (1) { pthread_mutex_lock(&timer_queue_mutex); for (i = 0; i < TIMER_QUEUE_NUM_MAX; i++) { tqm = tq_get_head_msg(i); for (j = 0; j < tq_get_msg_num(i); j++) { if (tqm[j].timer <= time(0)) { if(tqm[j].callbk != 0) tqm[j].callbk(tqm[j].ueId); tq_display_msg(&(tqm[j])); if (tqm[j].type == TIMER_QUEUE_MSG_TYPE_MAC) tq_del_msg_on_str(tqm[j].type, tqm[j].mac, i); else tq_del_msg_on_str(tqm[j].type, tqm[j].ipv4, i); } else break; } } pthread_mutex_unlock(&timer_queue_mutex); sleep(TIMER_THREAD_WAKEUP_TIME); } }
0
#include <pthread.h> pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex3 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex4 = PTHREAD_MUTEX_INITIALIZER; static int sequence1 = 0; static int sequence2 = 0; int func1() { pthread_mutex_lock(&mutex1); sequence1++ ; printf("thread 1 seq 1++ and now is %d \\n",sequence1); pthread_mutex_unlock(&mutex1); pthread_mutex_lock(&mutex2); sequence2++; printf("thread 1 seq 2++ and now is %d \\n",sequence2); pthread_mutex_unlock(&mutex2); return sequence1; } int func2() { pthread_mutex_lock(&mutex2); sequence2++; printf("thread 2 seq 2++ and now is %d \\n",sequence2); pthread_mutex_unlock(&mutex2); pthread_mutex_lock(&mutex1); sequence1++; printf("thread 2 seq 1++ and now is %d \\n",sequence1); pthread_mutex_unlock(&mutex1); return sequence2; } void* thread1(void* arg) { while (1) { int iRetValue = func1(); if (iRetValue == 100000) { printf("thread 1 finished\\n"); pthread_exit(0); } } } void* thread2(void* arg) { while (1) { int iRetValue = func2(); if (iRetValue == 100000) { printf("thread 2 finished\\n"); pthread_exit(0); } } } void* thread3(void* arg) { while (1) { sleep(1); char szBuf[128]; memset(szBuf, 0, sizeof(szBuf)); strcpy(szBuf, "thread3"); } } void* thread4(void* arg) { while (1) { sleep(1); char szBuf[128]; memset(szBuf, 0, sizeof(szBuf)); strcpy(szBuf, "thread4"); } } int main() { pthread_t tid[4]; if (pthread_create(&tid[0], 0, &thread1, 0) != 0) { _exit(1); } if (pthread_create(&tid[1], 0, &thread2, 0) != 0) { _exit(1); } if (pthread_create(&tid[2], 0, &thread3, 0) != 0) { _exit(1); } if (pthread_create(&tid[3], 0, &thread4, 0) != 0) { _exit(1); } sleep(5); pthread_join(tid[0], 0); pthread_join(tid[1], 0); pthread_join(tid[2], 0); pthread_join(tid[3], 0); pthread_mutex_destroy(&mutex1); pthread_mutex_destroy(&mutex2); pthread_mutex_destroy(&mutex3); pthread_mutex_destroy(&mutex4); return 0; }
1
#include <pthread.h> void event_listener_init(struct event_listener* el) { pthread_mutex_init(&el->lock, 0); el->el_cancel = 0; el->epoll_fd = epoll_create(EPOLL_SIZE); el->ev_num = 0; el->ev_cur = 0; el->ev_reg = 0; el->ac_num = 0; el->ac_cur = 0; el->ac_end = 0; event_storage_init(&el->es); } void event_listener_add(struct event_listener* el, struct event* event) { struct event* ev = event_storage_ins(&el->es, event); if (!ev) return; struct epoll_event ep; int fd = ev->fd; ep.data.ptr = (void*)ev; ep.events = 0; if (ev->op & EV_READ) ep.events |= EPOLLIN; if (ev->op & EV_WRITE) ep.events |= EPOLLOUT; if (ev->op & EV_ONESHOT) ep.events |= EPOLLONESHOT; if (ev->op & EV_POLLET) ep.events |= EPOLLET; if (((ev->op & EV_TIME) == EV_TIME)) { fprintf(stderr, "Hello\\n"); struct itimerspec new; int msec = fd; fd = timerfd_create(CLOCK_MONOTONIC, 0); new.it_value.tv_sec = msec / 1000; new.it_value.tv_nsec = (msec % 1000) * 1000000; new.it_interval.tv_sec = msec / 1000; new.it_interval.tv_nsec = (msec % 1000) * 1000000; timerfd_settime(fd, 0, &new, 0); ev->tmp_fd = fd; } if (((ev->op & EV_SIGNAL) == EV_SIGNAL)) { sigset_t sig; sigemptyset(&sig); sigaddset(&sig, fd); fd = signalfd(-1, &sig, 0); ev->tmp_fd = fd; } pthread_mutex_lock(&el->lock); if (ev->op & EV_ACTION) { el->ac_num++; el->actions[el->ac_end] = ev; el->ac_end = (el->ac_end + 1) % ACTION_SIZE; } epoll_ctl(el->epoll_fd, EPOLL_CTL_ADD, fd, &ep); el->ev_reg++; pthread_mutex_unlock(&el->lock); } void event_listener_del(struct event_listener* el, struct event* ev) { event_storage_del(&el->es, ev); if (((ev->op & EV_TIME) == EV_TIME) || ((ev->op & EV_SIGNAL) == EV_SIGNAL)) { close(ev->tmp_fd); } pthread_mutex_lock(&el->lock); if (!(ev->op & EV_ONESHOT)) epoll_ctl(el->epoll_fd, EPOLL_CTL_DEL, ev->fd, 0); el->ev_reg--; pthread_mutex_unlock(&el->lock); } struct event* event_listener_detach(struct event_listener* el) { struct event* ev = 0; if (el->el_cancel) return 0; do { pthread_mutex_lock(&el->lock); if (el->ac_num > 0) { ev = el->actions[el->ev_cur]; el->ac_num--; el->ac_cur = (el->ac_cur + 1) % ACTION_SIZE; break; } if (el->ev_num == 0) { el->ev_num = epoll_wait(el->epoll_fd, el->events, EVENT_SIZE, 0); el->ev_cur = 0; } if (el->ev_num > 0) { el->ev_num--; el->ev_cur++; ev = (struct event*)(el->events[el->ev_cur - 1].data.ptr); if (((ev->op & EV_SIGNAL) == EV_SIGNAL)) { if (ev->arg && (ev->op & EV_PARM)) read(ev->tmp_fd, (struct signalfd_siginfo*)ev->arg, sizeof(struct signalfd_siginfo)); else { struct signalfd_siginfo fdsi; read(ev->tmp_fd, &fdsi, sizeof(struct signalfd_siginfo)); } } if (((ev->op & EV_TIME) == EV_TIME)) { if (ev->arg && (ev->op & EV_PARM)) read(ev->tmp_fd, (uint64_t*) ev->arg, sizeof(uint64_t)); else { uint64_t tmp; read(ev->tmp_fd, &tmp, sizeof(uint64_t)); } } break; } } while(0); pthread_mutex_unlock(&el->lock); if (ev && ev->prefunc) (*ev->prefunc)(ev->fd, ev->op, ev->arg); return ev; } void event_listener_destroy(struct event_listener* el) { el->el_cancel = 1; pthread_mutex_lock(&el->lock); pthread_mutex_destroy(&el->lock); close(el->epoll_fd); }
0
#include <pthread.h> extern char **environ; static pthread_key_t key; static pthread_once_t once_done = PTHREAD_ONCE_INIT; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void thread_init(void) { pthread_key_create(&key, free); } char *getenv_l(const char *name) { int i, len; char *envbuf; pthread_once(&once_done, thread_init); pthread_mutex_lock(&mutex); envbuf = (char *)pthread_getspecific(key); if (envbuf == 0) { envbuf = malloc(ARG_MAX); if (envbuf == 0) { pthread_mutex_unlock(&mutex); return 0; } pthread_setspecific(key, envbuf); } len = strlen(name); for (i = 0; environ[i] != 0; ++i) { if (strncmp(name, environ[i], len) == 0 && environ[i][len] == '=') { strcpy(envbuf, &environ[i][len+1]); pthread_mutex_unlock(&mutex); return envbuf; } } pthread_mutex_unlock(&mutex); return 0; } void *thr_rtn1(void *arg) { printf("Enter thread 1 .......\\n"); printf("thread 1: getenv_l(USER): %s\\n", getenv_l("USER")); return (void *)0; } void *thr_rtn2(void *arg) { printf("Enter thread 2 .......\\n"); printf("thread 2: getenv_l(USER): %s\\n", getenv_l("USER")); return (void *)0; } int main(void) { pthread_t tid1, tid2; tid1 = pthread_create(&tid1, 0, thr_rtn1, 0); if (tid1 != 0) return 1; tid2 = pthread_create(&tid2, 0, thr_rtn2, 0); if (tid2 != 0) return 1; pthread_exit((void *)0); }
1
#include <pthread.h> static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER; void output_init() { return; } void output( char * string, ... ) { va_list ap; char *ts="[??:??:??]"; struct tm * now; time_t nw; pthread_mutex_lock(&m_trace); nw = time(0); now = localtime(&nw); if (now == 0) printf(ts); else printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec); __builtin_va_start((ap)); vprintf(string, ap); ; pthread_mutex_unlock(&m_trace); } void output_fini() { return; }
0
#include <pthread.h> int i_fd = -1, i_w = -1; pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cnd; void* threadfunc(void *arg) { struct pollfd pf = { .fd = i_fd, .events = POLLIN }; while (1) { pf.revents = 0; if (poll(&pf, 1, 1000) < 0) continue; if (pf.revents & (POLLHUP | POLLERR)) continue; if (pf.revents & POLLIN) break; usleep(5000); } pthread_mutex_lock(&mtx); pthread_cond_signal(&cnd); pthread_mutex_unlock(&mtx); pthread_exit(0); } int main(int argc, char* argv[]) { struct timespec tw; pthread_condattr_t attr; pthread_t thread; int ret; if (argc < 2) return 1; pthread_condattr_init(&attr); pthread_condattr_setclock(&attr, CLOCK_MONOTONIC); ret = pthread_cond_init(&cnd, &attr); pthread_condattr_destroy(&attr); if (ret != 0) return 2; i_fd = inotify_init(); if (i_fd < 0) return 3; i_w = inotify_add_watch(i_fd, argv[1], IN_MODIFY); if (i_w < 0) { close(i_fd); return 4; } ret = pthread_create(&thread, 0, threadfunc, 0); if (ret < 0) goto out; ret = clock_gettime(CLOCK_MONOTONIC, &tw); if (ret < 0) return 5; tw.tv_sec += 3 * 60; ret = pthread_cond_timedwait(&cnd, &mtx, &tw); if (ret == ETIMEDOUT) { pthread_cancel(thread); ret = 4; } else { void *tmp; pthread_join(thread, &tmp); ret = 0; } out: inotify_rm_watch(i_fd, i_w); close(i_fd); return ret; }
1
#include <pthread.h> pthread_t philosophers[5]; pthread_attr_t philosophers_attr[5]; pthread_mutex_t mutex[5]; pthread_cond_t cond_var[5]; pthread_mutex_t printing_mutex; int idx[5] = {0,1,2,3,4}; int forks[5]; void* runner(void *param); void pickup_forks(int philo_num); void return_forks(int philo_num); int nofal() { srand(time(0)); do{for (int i =0; i < 5; i++) forks[i] = 0;}while(0); pthread_mutex_init(&printing_mutex,0); for (int i =0; i < 5; i++) pthread_attr_init(&philosophers_attr[i]); for (int i =0; i < 5; i++) pthread_mutex_init(&mutex[i], 0); for (int i =0; i < 5; i++) pthread_cond_init(&cond_var[i], 0); int i = 0; for(int i =0; i < 5; i++) { printf("creating thread for phil_num %d \\n\\n", i); pthread_create(&philosophers[i],&philosophers_attr[i], &runner, &idx[i]); } for (int i =0; i < 5; i++) pthread_join(philosophers[i],0); return 0; } void* runner(void *param) { int philo_num = *((int*) param); while(1) { int secs_to_slp = (rand()+1)%3; pickup_forks(philo_num); pthread_mutex_lock(&printing_mutex); printf("philo_num %d eating..... \\n", philo_num); pthread_mutex_unlock(&printing_mutex); sleep(secs_to_slp); return_forks(philo_num); pthread_mutex_lock(&printing_mutex); printf("philo_num %d thinking..... \\n", philo_num); pthread_mutex_unlock(&printing_mutex); sleep(secs_to_slp); } } void pickup_forks(int philo_num) { printf("philo_num :%d is thinking about picking up fork %d\\n\\n",philo_num,((philo_num-1+5)%5)); do{ pthread_mutex_lock(&mutex[((philo_num-1+5)%5)]); }while(0); forks[((philo_num-1+5)%5)] = 1; printf("philo_num :%d picked up mutex %d\\n\\n",philo_num,((philo_num-1+5)%5)); printf("philo_num :%d is thinking about picking up fork %d\\n\\n",philo_num,((philo_num+1)%5)); while(pthread_mutex_trylock(&mutex[((philo_num+1)%5)]) !=0) { forks[((philo_num-1+5)%5)] = 0; printf("philo_num :%d put down mutex %d\\n\\n",philo_num,((philo_num-1+5)%5)); do{pthread_cond_wait(&cond_var[((philo_num-1+5)%5)], &mutex[((philo_num-1+5)%5)]); }while(0); } printf("philo_num :%d picked up fork %d\\n\\n",philo_num,((philo_num+1)%5)); printf("philo_num :%d picked up fork %d\\n\\n",philo_num,((philo_num-1+5)%5)); forks[((philo_num-1+5)%5)] = 1; forks[((philo_num+1)%5)] = 1; } void return_forks(int philo_num) { forks[((philo_num+1)%5)] = 0; printf("philo_num :%d put down fork %d\\n\\n",philo_num,((philo_num+1)%5)); do{ pthread_cond_signal(&cond_var[((philo_num+1)%5)]); }while(0); do{ pthread_mutex_unlock(&mutex[((philo_num+1)%5)]); }while(0); forks[((philo_num-1+5)%5)] = 0; printf("philo_num :%d put down fork %d\\n\\n",philo_num,((philo_num-1+5)%5)); do{ pthread_cond_signal(&cond_var[((philo_num-1+5)%5)]); }while(0); do{ pthread_mutex_unlock(&mutex[((philo_num-1+5)%5)]); }while(0); }
0
#include <pthread.h> struct Pattern{ char *url; char *user; char *password; }; static struct Pattern patterns[100]; static int pcount; static int hash_index; static void process_function(); static void process_function_actual(int job_type); static int process_judege(struct Job *job); static void analysis_userpassword_from_job(struct Job *current_job); static void analysis_userpassword_from_http_list(struct Http_List *list); static void analysis_userpassword_from_http(struct Http *http); static void psinit(){ pcount = 0; patterns[pcount].url = "www.renren.com"; patterns[pcount].user = "email"; patterns[pcount].password = "password"; pcount++; patterns[pcount].url = "www.51.com"; patterns[pcount].user = "passport_51_user"; patterns[pcount].password = "passport_51_password"; pcount++; patterns[pcount].url = "www.tianya.cn"; patterns[pcount].user = "vwriter"; patterns[pcount].password = "vpassword"; pcount++; patterns[pcount].url = "www.mop.com"; patterns[pcount].user = "user_name"; patterns[pcount].password = "password"; pcount++; patterns[pcount].url = "mail.sohu.com"; patterns[pcount].user = "username"; patterns[pcount].password = "passwd"; pcount++; } static void analysis_userpassword_from_job(struct Job *current_job){ struct Http_RR *http_rr = current_job->http_rr; if(http_rr == 0) return; analysis_userpassword_from_http_list(http_rr->request_list); analysis_userpassword_from_http_list(http_rr->response_list); } static void analysis_userpassword_from_http_list(struct Http_List *list){ if(list == 0) return; struct Http * point = list->head; while(point != 0){ analysis_userpassword_from_http(point); point = point->next; } } static void analysis_userpassword_from_http(struct Http *http){ struct UPInformation upinfo; int i; int flag; for(i=0; i<pcount; i++){ memset(&upinfo,0,sizeof(upinfo)); int flag = 0; { char *name; struct List_Node *value = (struct List_Node *)malloc(sizeof(struct List_Node)); value->length = 0; value->data = 0; name = patterns[i].user; get_first_value_from_name(http,name,value); if(value->length > 0 && value->data != 0){ memset(upinfo.user,0,sizeof(upinfo.user)); strcpy(upinfo.user,value->data); flag++; } free_list_node(value); free(value); } { char *name; struct List_Node *value = (struct List_Node *)malloc(sizeof(struct List_Node)); value->length = 0; value->data = 0; name = patterns[i].password; get_first_value_from_name(http,name,value); if(value->length > 0 && value->data != 0){ memset(upinfo.password,0,sizeof(upinfo.password)); strcpy(upinfo.password,value->data); flag++; } free_list_node(value); free(value); } if(flag == 2){ memset(upinfo.url,0,sizeof(upinfo.url)); strcpy(upinfo.url,patterns[i].url); sql_factory_add_user_password_record(&upinfo,hash_index); } } } extern void user_password_analysis_init(){ psinit(); register_job(JOB_TYPE_USERANDPASSWORD,process_function,process_judege,CALL_BY_HTTP_ANALYSIS); } static void process_function(){ int job_type = JOB_TYPE_USERANDPASSWORD; while(1){ pthread_mutex_lock(&(job_mutex_for_cond[job_type])); pthread_cond_wait(&(job_cond[job_type]),&(job_mutex_for_cond[job_type])); pthread_mutex_unlock(&(job_mutex_for_cond[job_type])); process_function_actual(job_type); } } static void process_function_actual(int job_type){ struct Job_Queue private_jobs; private_jobs.front = 0; private_jobs.rear = 0; get_jobs(job_type,&private_jobs); struct Job current_job; while(!jobqueue_isEmpty(&private_jobs)){ jobqueue_delete(&private_jobs,&current_job); hash_index = current_job.hash_index; analysis_userpassword_from_job(&current_job); if(current_job.http_rr != 0) free_http_rr(current_job.http_rr); } } static int process_judege(struct Job *job){ return 1; }
1
#include <pthread.h> pthread_mutex_t lock; int array[10]; int n_elementos=0; void * productor(); void * consumidor(); int main(int argc, char ** argv){ srand(time(0)); int i; pthread_mutex_init(&lock, 0); pthread_t pid[2]; for(i=0;i<10;i++){ array[i] = rand()%5; n_elementos++; } pthread_create(&pid[0], 0, (void *) productor, 0); pthread_create(&pid[1], 0, (void *) consumidor, 0); pthread_join(pid[0], 0); pthread_join(pid[1], 0); pthread_exit(0); } void * productor(){ int i, j; pthread_mutex_lock(&lock); for(j=0;j<10;j++){ i = rand() % 5; while(n_elementos==10){ printf("Vector lleno\\n"); pthread_mutex_unlock(&lock); } array[j]=i; n_elementos++; printf("PNum elementos es %d\\n", n_elementos); printf("Producto creado\\n"); } pthread_mutex_unlock(&lock); pthread_exit(0); } void * consumidor(){ int i, j; int dato; pthread_mutex_lock(&lock); for(j=0;j<10; j++){ i = rand() % 5; while(n_elementos==0){ printf("Vector vacio\\n"); pthread_mutex_unlock(&lock); } dato=array[j]; n_elementos--; printf("CNum elementos es %d\\n", n_elementos); printf("Producto consumido %d\\n", dato); } pthread_mutex_unlock(&lock); pthread_exit(0); }
0
#include <pthread.h> char *socket_path = "go.sock"; int socket; char buf[4096]; int len; } msg_t; pthread_cond_t send_c; pthread_cond_t recv_c; pthread_mutex_t m; msg_t *msg; } channel_t; channel_t workers; channel_t reply; } conn_t; conn_t *conn; int socket; } server_t; void ch_init(channel_t * ch) { ch->msg = 0; pthread_mutex_init(&ch->m, 0); pthread_cond_init(&ch->send_c, 0); pthread_cond_init(&ch->recv_c, 0); } void ch_send(channel_t * ch, msg_t * msg) { pthread_mutex_lock(&ch->m); while (0 != ch->msg) { pthread_cond_wait(&ch->send_c, &ch->m); } ch->msg = msg; pthread_cond_signal(&ch->recv_c); pthread_mutex_unlock(&ch->m); } msg_t *ch_recv(channel_t * ch) { msg_t *msg; pthread_mutex_lock(&ch->m); while (0 == ch->msg) { pthread_cond_wait(&ch->recv_c, &ch->m); } msg = ch->msg; ch->msg = 0; pthread_cond_signal(&ch->send_c); pthread_mutex_unlock(&ch->m); return msg; } void *worker(void *arg) { conn_t *conn = (conn_t *) arg; msg_t *msg; while (1) { msg = ch_recv(&conn->workers); do { }while(0); usleep(10); do { }while(0); ch_send(&conn->reply, msg); do { }while(0); } return 0; } void *writer(void *arg) { conn_t *conn = (conn_t *) arg; msg_t *msg; int len; while (1) { msg = ch_recv(&conn->reply); do { }while(0); len = write(msg->socket, msg->buf, msg->len); if (len < 0) { printf("Unable to write to socket\\n"); close(msg->socket); return 0; } else if (len == 0) { printf("Write close EOF\\n"); close(msg->socket); return 0; } free(msg); } return 0; } void *reader(void *arg) { int i; msg_t *msg; server_t *s; conn_t *conn; s = (server_t *) arg; conn = s->conn; do { }while(0); while (1) { msg = (msg_t *) malloc(sizeof(msg_t)); msg->socket = s->socket; msg->len = read(s->socket, msg->buf, sizeof(msg->buf)); if (msg->len < 0) { printf("Unable to read from socket\\n"); close(s->socket); goto out; } else if (msg->len == 0) { printf("Close: EOF\\n"); close(s->socket); goto out; } do { }while(0); ch_send(&conn->workers, msg); do { }while(0); } out: free(arg); return 0; } int main(int argc, char *argv[]) { struct sockaddr_un addr; int fd, client, pid; pthread_t tid; conn_t conn; int i; server_t *s; if (argc > 1) { socket_path = argv[1]; } ch_init(&conn.workers); ch_init(&conn.reply); pthread_create(&tid, 0, writer, &conn); for (i = 0; i < 32; i++) { pthread_create(&tid, 0, worker, &conn); } if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { perror("socket error"); exit(-1); } memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1); unlink(socket_path); if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) { perror("bind error"); exit(-1); } if (listen(fd, 10) == -1) { perror("listen error"); exit(-1); } while (1) { if ((client = accept(fd, 0, 0)) == -1) { perror("accept error"); continue; } s = (server_t *) malloc(sizeof(server_t)); s->conn = &conn; s->socket = client; pthread_create(&tid, 0, reader, s); } return 0; }
1
#include <pthread.h> void man(int *); pthread_mutex_t mutex[6]; int main(){ pthread_t man1, man2, man3, man4, man5; int a = 1, b = 2, c = 3, d = 4, e = 5; pthread_create(&man1, 0, (void *)man, &a); pthread_create(&man2, 0, (void *)man, &b); pthread_create(&man3, 0, (void *)man, &c); pthread_create(&man4, 0, (void *)man, &d); pthread_create(&man5, 0, (void *)man, &e); pthread_join(man1, 0); pthread_join(man2, 0); pthread_join(man3, 0); pthread_join(man4, 0); pthread_join(man5, 0); return 0; } void man(int *n){ int busy; while(1){ printf("man %d is thinking.\\n", *n); sleep(1); pthread_mutex_lock(&mutex[*n]); printf("%d 右锁\\n", *n); if (*n == 5) busy = pthread_mutex_lock(&mutex[1]); else pthread_mutex_lock(&mutex[*n+1]); printf("%d 左锁\\n", *n); printf("man %d is eating.\\n", *n); pthread_mutex_unlock(&mutex[(*n)]); if (*n == 5) pthread_mutex_unlock(&mutex[1]); else pthread_mutex_unlock(&mutex[*n+1]); printf("%d 吃完啦,解右锁\\n", *n); } }
0
#include <pthread.h> static int error(int cod,const char*const msg) { if (cod<0) { perror(msg); exit(1); } return cod; } { pthread_mutex_t guard; volatile unsigned val; } Shared; Shared theShared; static void* increment(void* data) { unsigned long count=(1ul<<20); while(count--) { pthread_mutex_lock(&theShared.guard); ++theShared.val; pthread_mutex_unlock(&theShared.guard); } } static void* decrement(void *data) { Shared* shared=(Shared*)data; unsigned long count=(1ul<<20); while(count--) { pthread_mutex_lock(&theShared.guard); --theShared.val; pthread_mutex_unlock(&theShared.guard); } } static void result() { printf("theShared->val=%d\\n",theShared.val); } static void sequentially() { increment(0); decrement(0); } static void concurrent() { pthread_t inc; pthread_t dec; error(pthread_create(&inc, 0, increment, 0), "inc" ); error(pthread_create(&dec, 0, decrement, 0), "dec" ); pthread_join(inc,0); pthread_join(dec,0); } int main(int argc,char** args) { theShared.val=0; concurrent(); result(); return 0; }
1
#include <pthread.h> void* child_fn ( void* arg ) { pthread_mutex_unlock( (pthread_mutex_t*)arg ); return 0; } void nearly_main ( void ) { pthread_t child; pthread_mutex_t mx1, mx2; int bogus[100], i; for (i = 0; i < 100; i++) bogus[i] = 0xFFFFFFFF; pthread_mutex_init( &mx1, 0 ); pthread_mutex_lock( &mx1 ); pthread_mutex_unlock( &mx1 ); pthread_mutex_unlock( &mx1 ); pthread_mutex_init( &mx2, 0 ); pthread_mutex_lock( &mx2 ); pthread_create( &child, 0, child_fn, (void*)&mx2 ); pthread_join(child, 0 ); pthread_mutex_unlock( (pthread_mutex_t*) &bogus[50] ); } int main ( void ) { nearly_main(); fprintf(stderr, "---------------------\\n" ); nearly_main(); return 0; }
0
#include <pthread.h> static double var_raw_analog_data[7]; static pthread_mutex_t Raw_Analog_Write_Lock = PTHREAD_MUTEX_INITIALIZER; void Init_Raw_Analog(void) { int ii; pthread_mutex_unlock(&Raw_Analog_Write_Lock); for(ii=0; ii < 6;ii++){ var_raw_analog_data[ii]=-1; } } double Get_Raw_Analog(int indexid) { return (var_raw_analog_data[(indexid%6)]); } void Update_Raw_Analog(int rawdata, int indexid) { while(pthread_mutex_lock(&Raw_Analog_Write_Lock) != 0) { usleep(133+(rawdata%13)); } if(rawdata > 0) { var_raw_analog_data[indexid] = (rawdata*(5.0/1024.0)); }else{ var_raw_analog_data[indexid] = 0; } pthread_mutex_unlock(&Raw_Analog_Write_Lock); }
1
#include <pthread.h> int item_in_array[10], item_out_array[100]; int item_in_count = 0, item_out_count = 0; int no = 0; pthread_t ptid, ctid[3], disp_tid; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; sem_t full, empty; void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } void sort() { int i, j; for (i = 0;i < no;i++) { for (j = 0;j < (no - i);j++) { if (item_out_array[j] > item_out_array[j + 1]) { swap(&item_out_array[j], &item_out_array[j + 1]); } } } } void *disp_output(void *var) { int i; while (1) { sort(); for (i = 0;i < no;i++) { printf("[%d]\\n", item_out_array[i]); sleep(3); } } } void add_item(int item) { int i = 0; if (no == 0) { item_out_array[no] = item; } else { item_out_array[--i] = item; } no++; } void *producer(void *var) { int item; while (1) { item = rand(); sem_wait(&empty); pthread_mutex_lock(&mutex); if (item_in_count < 10) { item_in_array[item_in_count] = item; item_in_count++; } pthread_mutex_unlock(&mutex); sem_post(&full); sleep(1); } return 0; } void *consumer(void *var) { int item; while (1) { sem_wait(&full); pthread_mutex_lock(&mutex); if (item_in_count > 0) { add_item(item_in_array[--item_in_count]); } pthread_mutex_unlock(&mutex); sem_post(&empty); sleep(1); } return 0; } int main(int argc, char const *argv[]) { int i; sem_init(&empty, 0, 10); sem_init(&full, 0, 0); pthread_create(&ptid, 0, producer, 0); for (i = 0;i < 3;i++) { pthread_create(&ctid[i], 0, consumer, 0); } pthread_create(&disp_tid, 0, disp_output, 0); pthread_join(ptid, 0); for (i = 0; i < 3;i++) { pthread_join(ctid[i], 0); } pthread_join(disp_tid, 0); return 0; }
0
#include <pthread.h> void* pthTextRW_run(void *argv){ int sock_fd; int flag; int ret; int option; int *retval; char *buff; struct sockaddr_in udpaddr; struct sockaddr_in client; key_path = "./folder/.key"; retval = 0; buff = 0; sock_fd = socket(AF_INET,SOCK_DGRAM,0); if(sock_fd < 0){ pthPrint(); perror("sock_fd create failed: "); exit(1); } flag = fcntl(sock_fd,F_GETFL); ret = setsockopt(sock_fd,SOL_SOCKET,SO_REUSEADDR,&option,sizeof(option)); if(ret < 0){ pthPrint(); perror("sock_fd setsockopt failed: "); exit(1); } memset(&udpaddr,0,sizeof(struct sockaddr_in)); udpaddr.sin_family = AF_INET; udpaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); udpaddr.sin_port = htons(2050); if(bind(sock_fd,(struct sockaddr*)&udpaddr,sizeof(struct sockaddr_in)) < 0){ close(sock_fd); pthPrint(); perror("pthTextRW_run bind failed: "); exit(1); } buff = (char*)malloc(50); if(buff == 0){ pthPrint(); fprintf(stderr,"malloc failed, line: %d\\n",66); close(sock_fd); exit(1); } while(1){ int client_len; client_len = sizeof(client); memset(buff,0,50); ret = recvfrom(sock_fd,buff,50,0,(struct sockaddr*)&client,&client_len); pthread_mutex_lock(&mutex_output); pthPrint(); printf("ret: %d, recv buff: %s\\n",ret,buff); pthread_mutex_unlock(&mutex_output); if(strcmp(buff,"write to .key") == 0){ prime_write(); memset(buff,0,50); strcpy(buff,"write ok"); if(sendto(sock_fd,buff,50,0,(struct sockaddr*)&client,client_len) < strlen(buff)){ pthPrint(); perror("pthTextRW -> main \\"write ok\\" "); } break; } else if(strcmp(buff,"decrypt") == 0){ prime_read(); memset(buff,0,50); strcpy(buff,"read ok"); ret = sendto(sock_fd,buff,50,0,(struct sockaddr *)&client,client_len); if(ret < strlen(buff)){ pthPrint(); perror("pthTextRW -> main \\"primer read ok\\": "); } break; } } end_tag: close(sock_fd); free(buff); buff = 0; retval = (int *)malloc(sizeof(int)); *retval = 1; pthread_exit((void*)retval); } void prime_write(){ FILE *key_p = 0; int i; key_p = fopen(key_path,"w"); if(key_p == 0){ pthPrint(); perror("key path w fopen: "); exit(1); } for (i=0; i<prime_stack_cnt; i++){ if(fwrite(&prime_stack[i],sizeof(int),1,key_p) != 1){ pthPrint(); perror("fwrite: "); exit(1); } } fclose(key_p); } void prime_read(){ FILE *key_p; int i; key_p = fopen(key_path,"r"); i=0; if(key_p == 0){ pthPrint(); perror("key_p r fope: "); exit(1); } while(!feof(key_p)){ fread(&prime_stack[i++],sizeof(int),1,key_p); } fclose(key_p); prime_stack_cnt = i-1; pthread_mutex_lock(&mutex_output); int j; for (j=0; j<i-1; j++){ printf("\\033[0;32m%d\\033[0m ",prime_stack[j]); } puts(""); pthread_mutex_unlock(&mutex_output); } static void pthPrint(){ printf("\\033[0;32m[textRWThread]\\033[0m "); }
1
#include <pthread.h> struct list_head { struct list_head *next ; struct list_head *prev ; }; struct s { int datum ; struct list_head list ; }; struct cache { struct list_head slot[10] ; pthread_mutex_t slots_mutex[10] ; }; struct cache c ; static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list; list->prev = list; } struct s *new(int x) { struct s *p = malloc(sizeof(struct s)); p->datum = x; INIT_LIST_HEAD(&p->list); return p; } static inline void list_add(struct list_head *new, struct list_head *head) { struct list_head *next = head->next; next->prev = new; new->next = next; new->prev = head; head->next = new; } inline static struct list_head *lookup1 (int d) { int hvalue1; struct list_head *p; p = c.slot[hvalue1].next; return p; } inline static struct list_head *lookup2 (int d) { int hvalue2; struct list_head *p; p = c.slot[hvalue2].next; return p; } void *f(void *arg) { struct s *pos ; int j; struct list_head const *p ; struct list_head const *q ; while (j < 10) { pthread_mutex_lock(&c.slots_mutex[j]); p = c.slot[j].next; pos = (struct s *)((char *)p - (size_t)(& ((struct s *)0)->list)); while (& pos->list != & c.slot[j]) { pos->datum++; q = pos->list.next; pos = (struct s *)((char *)q - (size_t)(& ((struct s *)0)->list)); } pthread_mutex_unlock(&c.slots_mutex[j]); j ++; } return 0; } int main() { int x; struct list_head *pp; pthread_t t1, t2; for (int i = 0; i < 10; i++) { INIT_LIST_HEAD(&c.slot[i]); pthread_mutex_init(&c.slots_mutex[i], 0); for (int j = 0; j < 30; j++) list_add(&new(j*i)->list, &c.slot[i]); } if (x) pp = lookup1(7); else pp = lookup2(7); pthread_create(&t1, 0, f, 0); pthread_create(&t2, 0, f, 0); return ((long) pp); }
0
#include <pthread.h> pthread_t tid; pthread_cond_t cond_lock = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex_lock = PTHREAD_MUTEX_INITIALIZER; void *first_thread(void *arg) { printf("%s start to lock the mutex.\\n", __func__); pthread_mutex_lock(&mutex_lock); printf("%s start to wait the cond.\\n", __func__); pthread_cond_wait(&cond_lock, &mutex_lock); printf("%s cond_wait() return.\\n", __func__); } void *second_thread(void *arg) { printf("%s start to lock the mutex.\\n", __func__); pthread_mutex_lock(&mutex_lock); printf("%s mutex_lock return.\\n", __func__); printf("%s cond_signal.\\n", __func__); pthread_cond_signal(&cond_lock); printf("%s cond_signal return.\\n", __func__); pthread_mutex_unlock(&mutex_lock); } int main(int argc, char **argv) { pthread_create(&tid, 0, first_thread, 0); sleep(2); pthread_create(&tid, 0, second_thread, 0); sleep(5); printf(" main() terminate.\\n"); return 0; }
1
#include <pthread.h> struct psuma { uint16_t v1; uint16_t v2; uint32_t res; }; void *suma (void *); void *ver_cone (void *); int leer_mensaje ( int , char * , int ); int cone; pthread_mutex_t m; pthread_cond_t c; int main() { int lon; int sd; int sd_cli; struct sockaddr_in servidor; struct sockaddr_in cliente; pthread_t tid; pthread_t tid_ver; servidor.sin_family = AF_INET; servidor.sin_port = htons (4444); servidor.sin_addr.s_addr = INADDR_ANY; sd = socket (PF_INET, SOCK_STREAM, 0); if ( bind ( sd , (struct sockaddr *) &servidor , sizeof(servidor) ) < 0 ) { perror("Error en bind\\n"); exit (-1); } listen ( sd , 5); cone = 0; pthread_mutex_init ( &m , 0); pthread_cond_init ( &c , 0); pthread_create ( &tid_ver, 0, ver_cone, 0 ); while (1) { lon = sizeof(cliente); sd_cli = accept ( sd , (struct sockaddr *) &cliente , &lon); pthread_mutex_lock (&m); cone++; pthread_cond_signal (&c); pthread_mutex_unlock (&m); pthread_create ( &tid, 0, suma, &sd_cli ); } close (sd); } void *suma ( void *arg ) { int sdc; int n; char buffer[sizeof(struct psuma)]; struct psuma *suma; suma = (struct psuma *) buffer; sdc = *( (int *) arg); n = 1; while ( n != 0) { if ( ( n = leer_mensaje ( sdc , buffer , sizeof(struct psuma) ) ) > 0 ) { suma->res = htonl ( ntohs (suma->v1) + ntohs(suma->v2) ); printf ("Enviando: %d %d %d \\n",ntohs(suma->v1),ntohs(suma->v2),ntohl(suma->res)); send ( sdc , buffer , sizeof(struct psuma) ,0 ); } } close (sdc); pthread_mutex_lock (&m); cone--; pthread_cond_signal (&c); pthread_mutex_unlock (&m); } void *ver_cone (void * arg) { while (1) { pthread_mutex_lock (&m); pthread_cond_wait(&c,&m); printf("Conexiones %d\\n",cone); pthread_mutex_unlock (&m); } } int leer_mensaje ( int socket , char *buffer , int total ) { int bytes, leido; leido = 0; bytes = 1; while ( (leido < total) && (bytes > 0) ) { bytes = recv ( socket , buffer + leido , total - leido , 0 ); leido = leido + bytes; } return (leido); }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int condition; int count; pthread_t thread; int consume( void ){ while ( count < 10 ){ printf( "Consume wait\\n" ); pthread_mutex_lock( &mutex ); while( condition == 0 ) pthread_cond_wait( &cond, &mutex ); printf( "Consumed %d\\n", count ); condition = 0; pthread_cond_signal( &cond ); pthread_mutex_unlock( &mutex ); } return( 0 ); } void* produce( void * arg ){ while ( count < 10 ){ printf( "Produce wait\\n" ); pthread_mutex_lock( &mutex ); while( condition == 1 ) pthread_cond_wait( &cond, &mutex ); count++; printf( "Produced %d\\n", count ); condition = 1; pthread_cond_signal( &cond ); pthread_mutex_unlock( &mutex ); } return( 0 ); } int main( void ){ pthread_create( &thread, 0, &produce, 0 ); return consume(); }
1
#include <pthread.h> struct tramp_heap_page; struct tramp_heap_data { struct tramp_heap_page *prev, *next; unsigned int inuse; unsigned int inuse_mask[((TRAMP_COUNT + (CHAR_BIT * sizeof(int)) - 1) / (CHAR_BIT * sizeof(int)))]; }; struct tramp_heap_page { char code[PAGE_SIZE]; struct tramp_heap_data data ; }; static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static struct tramp_heap_page *cur_page; static struct tramp_heap_page *notfull_page_list; void * __tramp_heap_alloc (uintptr_t fnaddr, uintptr_t chain_value) { struct tramp_heap_page *page; unsigned int index; pthread_mutex_lock (&lock); page = cur_page; if (page == 0) { page = notfull_page_list; if (page != 0) { notfull_page_list = page->data.next; if (page->data.next) { page->data.next->data.prev = 0; page->data.next = 0; } } else page = __tramp_alloc_pair (); } index = page->data.inuse++; cur_page = (index == (TRAMP_COUNT - ((sizeof (struct tramp_heap_data) + TRAMP_SIZE - 1) / TRAMP_SIZE)) - 1 ? 0 : page); { unsigned int iofs, bofs, mask, old; iofs = index / (CHAR_BIT * sizeof(int)); bofs = index % (CHAR_BIT * sizeof(int)); mask = 1u << bofs; old = page->data.inuse_mask[iofs]; if (old & mask) { while (old != ~0u) { if (++iofs == ((TRAMP_COUNT + (CHAR_BIT * sizeof(int)) - 1) / (CHAR_BIT * sizeof(int)))) iofs = 0; old = page->data.inuse_mask[iofs]; } mask = ~old & -~old; bofs = __builtin_ctz (mask); index = iofs * (CHAR_BIT * sizeof(int)) + bofs; } page->data.inuse_mask[iofs] = old | mask; } { void *tramp_code; uintptr_t *tramp_data; unsigned int index; tramp_code = page->code + (index + ((sizeof (struct tramp_heap_data) + TRAMP_SIZE - 1) / TRAMP_SIZE)) * TRAMP_SIZE; tramp_data = tramp_code + PAGE_SIZE; tramp_data[TRAMP_FUNCADDR_FIRST ? 0 : 1] = fnaddr; tramp_data[TRAMP_FUNCADDR_FIRST ? 1 : 0] = chain_value; pthread_mutex_unlock (&lock); return tramp_code; } } void __tramp_heap_free (void *tramp) { struct tramp_heap_page *page; unsigned int index; page = (void *)((uintptr_t)tramp & -PAGE_SIZE); index = ((uintptr_t)tramp & (PAGE_SIZE - 1)) / TRAMP_SIZE; index -= ((sizeof (struct tramp_heap_data) + TRAMP_SIZE - 1) / TRAMP_SIZE); pthread_mutex_lock (&lock); { unsigned int inuse = --page->data.inuse; if (page != cur_page) { if (inuse == (TRAMP_COUNT - ((sizeof (struct tramp_heap_data) + TRAMP_SIZE - 1) / TRAMP_SIZE)) - 1) { struct tramp_heap_page *next = notfull_page_list; page->data.next = next; if (next) next->data.prev = page; notfull_page_list = page; } else if (inuse == 0) { struct tramp_heap_page *next, *prev; next = page->data.next; prev = page->data.prev; if (next) next->data.prev = prev; if (prev) prev->data.next = next; page->data.next = page->data.prev = 0; if (cur_page == 0) cur_page = page; else { __tramp_free_pair (page); goto egress; } } } } { unsigned int iofs, bofs, mask; iofs = index / (CHAR_BIT * sizeof(int)); bofs = index % (CHAR_BIT * sizeof(int)); mask = 1u << bofs; page->data.inuse_mask[iofs] &= ~mask; } egress: pthread_mutex_unlock (&lock); }
0
#include <pthread.h> pthread_mutex_t mutex; void *lowprio(void *null) { int i; printf("\\n %s: \\n",__func__); printf("LOWPRIO : contending for mutex lock \\n"); if(pthread_mutex_lock(&mutex)==0) { printf("LOWPRIO : lock acquired\\n"); printf("LOWPRIO : executing critical op ......\\n"); while(i<40000000) i++; printf("LOWPRIO : Done\\n"); printf("LOWPRIO : Releasing mutex \\n"); } pthread_mutex_unlock(&mutex); pthread_exit(0); } void * highprio(void *null) { printf("HIGHPRIO : contending for mutex lock \\n"); if(pthread_mutex_lock(&mutex)==0) { printf("HIGHPRIO : lock acquired \\n"); printf("HIGHPRIO : executing critical op ......\\n"); printf("HIGHPRIO : Done\\n"); printf("HIGHPRIO : Releasing mutex \\n"); } pthread_mutex_unlock(&mutex); pthread_exit(0); } void * medprio(void *null) { printf("MEDPRIO : contending for muex lock \\n"); } int main (int argc, char *argv[]) { pthread_mutexattr_t attrmutex; int inherit,policy,priority,rc; struct sched_param param; pthread_t tcb1,tcb2,tcb3; pthread_attr_t attr; pthread_attr_init(&attr); pthread_mutexattr_init(&attrmutex); pthread_mutexattr_setprotocol(&attrmutex,PTHREAD_PRIO_INHERIT); pthread_mutex_init(&mutex,&attrmutex); pthread_attr_setinheritsched(&attr,PTHREAD_EXPLICIT_SCHED); param.sched_priority=30; pthread_attr_setschedpolicy(&attr, SCHED_RR); pthread_attr_setschedparam(&attr, &param); pthread_create(&tcb1, &attr, lowprio, 0); param.sched_priority=20; pthread_attr_setschedpolicy(&attr,SCHED_RR); pthread_attr_setschedparam(&attr,&param); pthread_create(&tcb2, &attr, highprio, 0); param.sched_priority=10; pthread_attr_setschedpolicy(&attr,SCHED_RR); pthread_attr_setschedparam(&attr,&param); pthread_create(&tcb3, &attr, medprio, 0); pthread_attr_destroy(&attr); pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER; int shared = 133; void *ta (void *arg) { int local = 17; (void) arg; printf ("ta: running\\n"); if (0) local += shared; if (0) shared = local; pthread_mutex_lock (&m1); if (0) local += shared; if (0) shared = local; pthread_mutex_unlock (&m1); if (0) local += shared; if (0) shared = local; return (void*) (size_t) local; } void *tb (void *arg) { int local = 17; (void) arg; printf ("tb: running\\n"); if (0) local += shared; if (0) shared = local; pthread_mutex_lock (&m1); if (0) local += shared; if (0) shared = local; pthread_mutex_unlock (&m1); if (0) local += shared; if (0) shared = local; return (void*) (size_t) local; } int main() { pthread_t a, b; int local = 17; if (0) local += shared; if (0) shared = local;; pthread_create (&a, 0, ta, 0); if (0) local += shared; if (0) shared = local;; pthread_create (&b, 0, tb, 0); if (0) local += shared; if (0) shared = local;; pthread_join (b, 0); if (0) local += shared; if (0) shared = local;; pthread_join (a, 0); if (0) local += shared; if (0) shared = local;; return local; }
0
#include <pthread.h> int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t count_threshold_cv = PTHREAD_COND_INITIALIZER; void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i<10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %ld, count = %d Threshold reached.\\n" , my_id, count); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); if (count<12) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char *argv[]) { int i, rc; long t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_create(&threads[0], 0, watch_count, (void *)t1); pthread_create(&threads[1], 0, inc_count, (void *)t2); pthread_create(&threads[2], 0, inc_count, (void *)t3); for (i=0; i<3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Done.\\n", 3); pthread_exit(0); }
1
#include <pthread.h> pthread_t tid[3]; pthread_mutex_t m; struct node { int data; struct node *link; }; struct node *header, *ptr, *temp; int count=0; void insert_front(); void insert_end(); void insert_any(); void display(); void delete(); void createthread(); void main() { int choice; int cont = 1; header = (struct node *) malloc(sizeof(struct node)); header->data = 0; header->link = 0; while(cont == 1) { printf("\\n1. Insert at front\\n"); printf("\\n2. Insert at end\\n"); printf("\\n3. Insert at any position\\n"); printf("\\n4. delete linked list\\n"); printf("\\n5. display linked list\\n"); printf("\\n6. create thread\\n"); printf("\\nEnter your choice: "); scanf("%d", &choice); switch(choice) { case 1: insert_front(); break; case 2: insert_end(); break; case 3: insert_any(); break; case 4: delete(); break; case 5: display(); break; case 6: createthread(); break; } printf("\\n\\nDo you want to continue? (1 / 0): "); scanf("%d", &cont); } } void createthread() { for (int i=1; i<3; i++) { pthread_create(&tid[i], 0, delete, (void *)i); } for (int i = 1; i < 3; i++) pthread_join(tid[i], 0); } void insert_front() { int data_value; pthread_mutex_lock(&m); printf("\\nEnter data of the node: "); scanf("%d", &data_value); temp = (struct node *) malloc(sizeof(struct node)); if(count!=0) { temp->data = data_value; temp->link = header; header = temp; } else { temp->data=data_value; temp->link=0; header=temp; count++; } pthread_mutex_unlock(&m); } void insert_end() { int data_value; printf("\\nEnter data of the node: "); scanf("%d", &data_value); temp = (struct node *) malloc(sizeof(struct node)); ptr = header; while(ptr->link != 0) { ptr = ptr->link; } temp->data = data_value; temp->link = ptr->link; ptr->link = temp; } void insert_any() { int data_value, key; printf("\\nEnter data of the node: "); scanf("%d", &data_value); printf("\\nEnter data of the node after which new node is to be inserted: "); scanf("%d", &key); temp = (struct node *) malloc(sizeof(struct node)); ptr = header; while(ptr->link != 0 && ptr->data != key) { ptr = ptr->link; } if(ptr->data == key) { temp->data = data_value; temp->link = ptr->link; ptr->link = temp; } else { printf("\\nValue %d not found\\n",key); } } void delete(void * p) { pthread_mutex_lock(&m); int position = 1; printf("position = %d\\n",position ); temp=header; if (position == 0) { header = temp->link; free(temp); return; } for (int j=0; temp!=0 && j<position-1; j++) temp = temp->link; if (temp == 0 || temp->link == 0) return; struct node *link = temp->link->link; free(temp->link); temp->link = link; pthread_mutex_unlock(&m); } void display() { printf("\\nContents of the linked list are: \\n"); ptr = header; while(ptr != 0) { printf("%d ", ptr->data); ptr = ptr->link; } }
0
#include <pthread.h> int makethread(void *(*fn)(void *), void *arg) { int err; pthread_t tid; pthread_attr_t attr; err = pthread_attr_init(&attr); if (err != 0) return(err); err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); if (err == 0) err = pthread_create(&tid, &attr, fn, arg); pthread_attr_destroy(&attr); return(err); } struct to_info { void (*to_fn)(void *); void *to_arg; struct timespec to_wait; }; void clock_gettime(int id, struct timespec *tsp) { struct timeval tv; gettimeofday(&tv, 0); tsp->tv_sec = tv.tv_sec; tsp->tv_nsec = tv.tv_usec * 1000; } void * timeout_helper(void *arg) { struct to_info *tip; tip = (struct to_info *)arg; nanosleep((&tip->to_wait), (0)); (*tip->to_fn)(tip->to_arg); free(arg); return(0); } void timeout(const struct timespec *when, void (*func)(void *), void *arg) { struct timespec now; struct to_info *tip; int err; clock_gettime(0, &now); if ((when->tv_sec > now.tv_sec) || (when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) { tip = malloc(sizeof(struct to_info)); if (tip != 0) { tip->to_fn = func; tip->to_arg = arg; tip->to_wait.tv_sec = when->tv_sec - now.tv_sec; if (when->tv_nsec >= now.tv_nsec) { tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec; } else { tip->to_wait.tv_sec--; tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec; } err = makethread(timeout_helper, (void *)tip); if (err == 0) return; else free(tip); } } (*func)(arg); } pthread_mutexattr_t attr; pthread_mutex_t mutex; void retry(void *arg) { pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); } int main(void) { int err, condition, arg; struct timespec when; if ((err = pthread_mutexattr_init(&attr)) != 0) err_exit(err, "pthread_mutexattr_init failed"); if ((err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) != 0) err_exit(err, "can't set recursive type"); if ((err = pthread_mutex_init(&mutex, &attr)) != 0) err_exit(err, "can't create recursive mutex"); pthread_mutex_lock(&mutex); if (condition) { clock_gettime(0, &when); when.tv_sec += 10; timeout(&when, retry, (void *)((unsigned long)arg)); } pthread_mutex_unlock(&mutex); exit(0); }
1
#include <pthread.h> struct employee { int number; int id; char first_name[32]; char last_name[32]; char department[32]; int root_number; }; struct employee employees[] = { { 1, 12345678, "astro", "Bluse", "Accounting", 101 }, { 2, 87654321, "Shrek", "Charl", "Programmer", 102 }, }; struct employee employee_of_the_day; void copy_employee(struct employee *from, struct employee *to) { memcpy(to, from, sizeof(struct employee)); } pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void *do_loop(void *data) { int num = *(int *)data; while (1) { pthread_mutex_lock(&lock); copy_employee(&employees[num - 1], &employee_of_the_day); pthread_mutex_unlock(&lock); } } int main(int argc, const char *argv[]) { pthread_t th1, th2; int num1 = 1; int num2 = 2; int i; copy_employee(&employees[0], &employee_of_the_day); if (pthread_create(&th1, 0, do_loop, &num1)) { errx(1, "pthread_create() error.\\n"); } if (pthread_create(&th2, 0, do_loop, &num2)) { errx(1, "pthread_create() error.\\n"); } while (1) { pthread_mutex_lock(&lock); struct employee *p = &employees[employee_of_the_day.number - 1]; if (p->id != employee_of_the_day.id) { printf("mismatching 'id', %d != %d (loop '%d')\\n", employee_of_the_day.id, p->id, i); exit(1); } if (strcmp(p->first_name, employee_of_the_day.first_name)) { printf("mismatching 'first_name', %s != %s (loop '%d')\\n", employee_of_the_day.first_name, p->first_name, i); exit(1); } if (strcmp(p->last_name, employee_of_the_day.last_name)) { printf("mismatching 'last_name', %s != %s (loop '%d')\\n", employee_of_the_day.last_name, p->last_name, i); exit(1); } if (strcmp(p->department, employee_of_the_day.department)) { printf("mismatching 'department', %s != %s (loop '%d')\\n", employee_of_the_day.department, p->department, i); exit(1); } if (p->root_number != employee_of_the_day.root_number) { printf("mismatching 'root_number', %d != %d (loop '%d')\\n", employee_of_the_day.root_number, p->root_number, i); exit(1); } printf("lory, employees contents was always consistent\\n"); pthread_mutex_unlock(&lock); } exit(0); }
0
#include <pthread.h> int * gArray; int globalSum = 0; pthread_mutex_t lock; void * sumArray(void * ip) { int * i = (int *) ip; int threadArraySliceSize = 400 / 8; int startIndex = *i * threadArraySliceSize; int endIndex = (*i + 1) * threadArraySliceSize; int sumSlice = 0; int j; for ( j = startIndex; j < endIndex; j++ ) { sumSlice += gArray[j]; } pthread_mutex_lock(&lock); globalSum += sumSlice; pthread_mutex_unlock(&lock); printf("Hi. I'm thread %d, sumSlice = %d, avg Value = %5.1f\\n", *i, sumSlice, (float) sumSlice / (float) threadArraySliceSize ); pthread_exit(0); } void fillOutArray() { time_t t; srand((unsigned) time(&t)); int i; for ( i=0; i < 400 ; i++) { gArray[i] = rand() % 1000; } } int main() { int i, vals[8]; pthread_t threads[8]; pthread_mutex_init(&lock,0); void * retval; gArray = malloc(400*sizeof(int)); fillOutArray(); for (i = 0; i < 8; i++) { vals[i] = i; int rc = pthread_create(&threads[i], 0, sumArray,(void *) &vals[i]); if (rc) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } for (i = 0; i < 8; i++) { pthread_join(threads[i], &retval); } int correctSum = 0; for (i = 0; i < 400; i++) { correctSum += gArray[i]; } printf("globalSum: %d, correct answer: %d\\n",globalSum,correctSum); free(gArray); pthread_mutex_destroy(&lock); pthread_exit(0); }
1
#include <pthread.h> pthread_cond_t cond_t = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex_t; void emit(void) { for (int i = 0; i < 3; ++i) { printf("sleep %d s\\n", i); sleep(1); } pthread_mutex_lock(&mutex_t); pthread_cond_signal(&cond_t); puts("emmit"); pthread_mutex_unlock(&mutex_t); } void wait_signal(void) { pthread_cond_wait(&cond_t, &mutex_t); puts("emmited"); } int main() { pthread_t emit_t, wait_signal_t; pthread_mutex_init(&mutex_t, 0); pthread_create(&emit_t, 0, (void *) emit, 0); pthread_create(&wait_signal_t, 0, (void *) wait_signal, 0); pthread_join(emit_t, 0); pthread_join(wait_signal_t, 0); return 0; }
0
#include <pthread.h> int ** bigmatrix; int r = 5; int c = 5; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int ready = 0; int ** AllocMatrix(int r, int c) { int ** a; int i; a = (int**) malloc(sizeof(int *) * r); assert(a != 0); for (i = 0; i < r; i++) { a[i] = (int *) malloc(c * sizeof(int)); assert(a[i] != 0); } return a; } void FreeMatrix(int ** a, int r, int c) { int i; for (i=0; i<r; i++) { free(a[i]); } free(a); } void GenMatrix(int ** matrix, const int height, const int width) { int i, j; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { int * mm = matrix[i]; mm[j] = rand() % 10; } } } int AvgElement(int ** matrix, const int height, const int width) { int x=0; int y=0; int ele=0; int i, j; for (i=0; i<height; i++) for (j=0; j<width; j++) { int *mm = matrix[i]; y=mm[j]; x=x+y; ele++; } printf("x=%d ele=%d\\n",x, ele); return x / ele; } void *worker(void *arg) { int *loops = (int *) &arg; int i; for (i=0; i<*loops; i++) { pthread_mutex_lock(&mutex); bigmatrix = AllocMatrix(r,c); GenMatrix(bigmatrix, r, c); ready=1; pthread_cond_signal(&cond); while (ready == 1) pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); FreeMatrix(bigmatrix, r, c); } return 0; } int main (int argc, char * argv[]) { pthread_t p1; printf("main: begin \\n"); int loops = 10000; int i; pthread_create(&p1, 0, worker, loops); for(i=0;i<loops;i++) { pthread_mutex_lock(&mutex); while (ready==0) pthread_cond_wait(&cond, &mutex); int avgele = AvgElement(bigmatrix, r, c); printf("Avg array=%d value=%d\\n",i,avgele); ready=0; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } pthread_join(p1, 0); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void *thread1(void*); void *thread2(void*); void send_num(int); int i = 1; int main(void) { int mk = 0; pthread_t t_a; pthread_t t_b; pthread_create(&t_a, 0, thread2, (void*) 0); sleep(1); pthread_create(&t_b, 0, thread1, (void*) 0); pthread_join(t_a,0); pthread_join(t_b,0); exit(0); } void send_num(int num){ i = num; pthread_mutex_lock(&mutex); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } void *thread1(void *junk) { int mk = 0; for(;mk<=10;mk++) { send_num(mk); } } void *thread2(void *junk) { while(i<10) { pthread_mutex_lock(&mutex); pthread_cond_wait(&cond, &mutex); printf("client : %d\\n", i); pthread_mutex_unlock(&mutex); } }
0
#include <pthread.h> int numT; char * aldodir; char * imagedir; char aldoFileNames[10][15]; long imageID; struct _finddata_t imageData; int *** aldos; int numAldos = 0; int allAldoRows[100]; int allAldoCols[100]; pthread_mutex_t mutex_nextFile = PTHREAD_MUTEX_INITIALIZER; int main( int argc, char * argv[] ) { pthread_t tid[16]; long fileID; struct _finddata_t fileData; FILE * fp; int aldoRows = 0, aldoCols = 0; char inStr[10]; char inChar; char * token; char dump[100]; int i = 0, j = 0, k = 0; double timeTaken; StartTime(); if( argc != 4 ) { printf("Not enough arguments.\\n"); getchar(); } numT = atoi(argv[3]); aldodir = (char *)malloc(sizeof(char)*strlen(argv[1])+1); strcpy(aldodir, argv[1]); imagedir = (char *)malloc(sizeof(char)*strlen(argv[2])+1); strcpy(imagedir, argv[2]); if(_chdir(aldodir)) { printf("Cannot find directory.\\n"); exit(1); } aldos = (int***) malloc(sizeof(int**)*100); fileID = _findfirst("*.txt", &fileData); do { strcpy(aldoFileNames[i], fileData.name); fp = fopen(fileData.name, "r"); fgets(inStr, 10, fp); token = strtok(inStr, " "); aldoRows = atoi(token); token = strtok(0, " "); aldoCols = atoi(token); allAldoRows[i] = aldoRows; allAldoCols[i] = aldoCols; aldos[i] = (int**)malloc(sizeof(int*)*aldoRows); for( j = 0; j < aldoRows; j++ ) { aldos[i][j] = (int*)malloc(sizeof(int)*aldoCols); } for( j = 0; j < aldoRows; j++ ) { for ( k = 0; k < aldoCols; k++ ) { aldos[i][j][k] = fgetc(fp); } fgets(dump, 100, fp); } fclose(fp); i++; } while (_findnext(fileID, &fileData)==0); _findclose(fileID); numAldos = i; if (_chdir(imagedir)) { printf("Cannot open image dir.\\n"); fgetc(stdin); exit(1); } imageID = _findfirst("*.img", &imageData); for( i = 0; i < numT; i++ ) { pthread_create(&tid[i], 0, thread_start, (void *)i); } for ( i=0; i < numT; i++ ) { pthread_join(tid[i], 0); } printf("Threads exit.\\n"); _findclose(imageID); free(aldodir); free(imagedir); timeTaken = EndTime(); printf("Time taken: %.2lf\\nInput any character to exit.\\n", timeTaken); fgetc(stdin); return 0; } void *thread_start(void * index) { int ** myImage; int imgRows = 0, imgCols = 0; int aldoLocaRow, aldoLocaCol, aldoRotation; int i = 0, j = 0; int rotation = 0; int startRow = 0, startCol = 0; int rowMod = 0, colMod = 0; char * myFilename; char dump[100]; char inStr[10]; char * token; FILE * fp; myFilename = (char*)malloc(sizeof(char)*13); while(1) { pthread_mutex_lock(&mutex_nextFile); fp = fopen(imageData.name, "r" ); if (fp == 0) { pthread_mutex_unlock(&mutex_nextFile); pthread_exit(0); } printf("Filename %s T%d\\n", imageData.name, index); if(0!=_findnext(imageID, &imageData)) { pthread_mutex_unlock(&mutex_nextFile); pthread_exit(0); } pthread_mutex_unlock(&mutex_nextFile); fgets(inStr, 10, fp); token = strtok(inStr, " "); imgRows = atoi(token); token = strtok(0, " "); imgCols = atoi(token); myImage = (int**)malloc(sizeof(int*)*imgRows); for( i = 0; i < imgRows; i++ ) { myImage[i] = (int*)malloc(sizeof(int)*imgCols); } for( i = 0; i < imgRows; i++ ) { for ( j = 0; j < imgCols; j++ ) { myImage[i][j] = fgetc(fp); } fgets(dump, 100, fp); } fclose(fp); fp = 0; for( i = 0; i < imgRows; i++ ) { free(myImage[i]); } free(myImage); } pthread_exit(0); return 0; }
1
#include <pthread.h> pthread_t tidTable[1000]; pthread_mutex_t mutex_one; pthread_cond_t cond_one; long index = 0; int iNumThread; void thinking(){ srandom(time(0)); usleep(random()%500); } void pickUpChopsticks(long threadX){ printf("%ld is trying to pick the chopsticks\\n",threadX); pthread_mutex_lock(&mutex_one); printf("%ld get the chopsticks\\n",threadX); while(index != threadX){ printf("%ld give up chopsticks and sleep\\n",threadX); pthread_cond_wait(&cond_one,&mutex_one); printf("%ld wake up and try to get lock again\\n",threadX); } printf("%ld start to use the chopsticks\\n",threadX); } void eating(){ srandom(time(0)); usleep(random()%500); } void putDownChopsticks(long threadX){ printf("%ld eat\\n",threadX); index = (threadX + 1)%iNumThread; pthread_cond_broadcast(&cond_one); printf("%ld signal cond\\n",threadX); pthread_mutex_unlock(&mutex_one); printf("%ld signal release lock\\n",threadX); } void *PhilosopherThread(void *str){ long threadX = (long)str; thinking(); pickUpChopsticks(threadX); eating(); putDownChopsticks(threadX); } void createPhilosophers(int iNumThread){ long i,err; for(i = 0; i< iNumThread; i++){ err = pthread_create(&tidTable[i],0,PhilosopherThread,(void*)i); if(err){ printf("create %ldth thread failed\\n",i); exit(0); } } for(i=0;i<iNumThread;i++){ pthread_join(tidTable[i],0); } printf("N threads have been joined successfully\\n"); } int main(int argc, char *argv[]){ int i; if(argc!=2){ exit(0); }else{ iNumThread = abs(atoi(argv[1])); if(iNumThread > 1000) { printf("iNumThread should be smaller than %d\\n",1000); exit(0); } } printf("Tianyi Liu is creating %d threads\\n", iNumThread); pthread_mutex_init(&mutex_one,0); pthread_cond_init(&cond_one,0); createPhilosophers(iNumThread); return 0; }
0
#include <pthread.h> double a; double b; int n; double approx; pthread_mutex_t mutex; double static NEG_1_TO_POS_1 = 0.66666666666667; double static ZERO_TO_POS_10 = 333.333; double f(double a) { return a * a; } void* trap_loop(void *rank) { int *rank_int_ptr = (int*) rank; int my_rank = *rank_int_ptr; double x_i; double h = (b-a) / n; int step = n / 20; int start = step * my_rank; int end = step * (my_rank + 1) -1; double local_approx = 0; for(int i = start; i < end; i++) { x_i = a + i*h; local_approx = local_approx + f(x_i); } pthread_mutex_lock(&mutex); approx = approx + local_approx; pthread_mutex_unlock(&mutex); return 0; } void trap() { double x_i; double h = (b-a) / n; approx = ( f(a) - f(b) ) / 2.0; pthread_t ids[20]; int ranks[20]; for (int i=0; i < 20; i++) { ranks[i] = i; pthread_create(&ids[i], 0, trap_loop, &ranks[i]); } for (int i=0; i < 20; i++) { pthread_join(ids[i], 0); } approx = h*approx; return; } int main() { pthread_mutex_init(&mutex, 0); a = -1.0; b = 1.0; n = 100000000; timerStart(); trap(); printf("Took %ld ms\\n", timerStop()); printf("a:%f\\t b:%f\\t n:%d\\t actual:%f\\t approximation:%f\\n", a, b, n, NEG_1_TO_POS_1, approx); a = 0.0; b = 10.0; n = 100000000; timerStart(); trap(); printf("Took %ld ms\\n", timerStop()); printf("a:%f\\t b:%f\\t n:%d\\t actual:%f\\t approximation:%f\\n", a, b, n, ZERO_TO_POS_10, approx); return 0; }
1
#include <pthread.h> void clearSampleTableEnt(int i) { sampleTable[i].id = i; sampleTable[i].audioIdx = -1; sampleTable[i].mixIdx = -1; sampleTable[i].playbackState = STOPPED; sampleTable[i].overlay = 0; sampleTable[i].numOverlays = 0; sampleTable[i].loop = FALSE; sampleTable[i].digitalBehavior = 0; return; } void clearSampleTable() { int i; if (AUDIO_INIT_DEBUG) fprintf(stderr, " - Clearing the SAMPLE table.\\n"); for (i = 0; i < MAX_SAMPLE; i++) clearSampleTableEnt(i); return; } int setSampleTable(char filenames[MAX_AUDIO_FILES][MAX_NAME], int sampleMap[]) { int i = 0; if (AUDIO_INIT_DEBUG) fprintf(stderr, "*** SETTING SAMPLE TABLE! ***\\n"); clearSampleTable(); for (i = 0; i < MAX_SAMPLE; i++) { if (sampleMap[i] >= 0) { if (AUDIO_INIT_DEBUG) fprintf(stderr, " - audio.c: setting sample %d to audio file %d\\n", i, sampleMap[i]); sampleTable[i].audioIdx = sampleMap[i]; } } return 1; } int sampleStart(int sampleID) { if (AUDIO_PLAY_DEBUG) fprintf(stderr, " - Sample %d told to START\\n", sampleID); if (sampleID < 0) return -1; if (sampleTable[sampleID].playbackState == PLAYING) { if (AUDIO_PLAY_DEBUG) fprintf(stderr, " - Sample %d already playing, can't start again!\\n", sampleID); return 1; } sampleTable[sampleID].mixIdx = setMixTableFile(sampleTable[sampleID].audioIdx, &sampleTable[sampleID]); sampleTable[sampleID].playbackState = PLAYING; return 1; } int sampleStop(int sampleID) { if (AUDIO_PLAY_DEBUG) fprintf(stderr, " - Sample %d told to STOP\\n", sampleID); pthread_mutex_lock(&mix_lock); mixTable[sampleTable[sampleID].mixIdx].blackSpot = 1; mixTable[sampleTable[sampleID].mixIdx].sampleStop = 1; pthread_mutex_unlock(&mix_lock); return 1; } int sampleRestart(int sampleID) { if (AUDIO_PLAY_DEBUG) fprintf(stderr, " - Sample %d told to RESTART\\n", sampleID); if (sampleTable[sampleID].playbackState == STOPPED) { sampleStart(sampleID); } else { pthread_mutex_lock(&mix_lock); mixTable[sampleTable[sampleID].mixIdx].blackSpot = 1; mixTable[sampleTable[sampleID].mixIdx].sampleStop = 0; pthread_mutex_unlock(&mix_lock); sampleTable[sampleID].mixIdx = setMixTableFile(sampleTable[sampleID].audioIdx, &sampleTable[sampleID]); sampleTable[sampleID].playbackState = PLAYING; } return 1; } int sampleStartLoop(int sampleID) { if (AUDIO_PLAY_DEBUG) fprintf(stderr, " - Sample %d told to START\\n", sampleID); if (sampleID < 0) return -1; if (sampleTable[sampleID].playbackState == PLAYING) { if (AUDIO_PLAY_DEBUG) fprintf(stderr, " - Sample %d already playing, can't start again!\\n", sampleID); return 1; } sampleTable[sampleID].mixIdx = setMixTableFile(sampleTable[sampleID].audioIdx, &sampleTable[sampleID]); sampleTable[sampleID].playbackState = PLAYING; sampleTable[sampleID].loop = TRUE; return 1; } int sampleOverlay(int sampleID) { if (AUDIO_PLAY_DEBUG) fprintf(stderr, " - Sample %d told to play OVERLAID!\\n", sampleID); return 1; } int sampleStopALL() { if (AUDIO_PLAY_DEBUG) fprintf(stderr, " - ALL samples told to STOP"); return 1; } int setPlaybackSound(int idx) { return setMixTableFile(idx, 0); }
0
#include <pthread.h> static pthread_cond_t condvar; static bool child_ready; static pthread_mutex_t lock; static int num_received; static void handler(int sig, siginfo_t *info, void *ucxt) { print("in handler %d\\n", sig); if (sig == 42) { num_received++; if (num_received >= 2) pthread_exit(0); else { sleep(1); } } } static void * thread_routine(void *arg) { int rc; struct sigaction act; act.sa_sigaction = (void (*)(int, siginfo_t *, void *)) handler; rc = sigemptyset(&act.sa_mask); ASSERT_NOERR(rc); act.sa_flags = SA_SIGINFO; rc = sigaction(42, &act, 0); ASSERT_NOERR(rc); pthread_mutex_lock(&lock); child_ready = 1; pthread_cond_signal(&condvar); pthread_mutex_unlock(&lock); while (1) sleep(10); } int main(int argc, char **argv) { pthread_t thread; void *retval; struct timespec sleeptime; pthread_mutex_init(&lock, 0); pthread_cond_init(&condvar, 0); if (pthread_create(&thread, 0, thread_routine, 0) != 0) { perror("failed to create thread"); exit(1); } pthread_mutex_lock(&lock); while (!child_ready) pthread_cond_wait(&condvar, &lock); pthread_mutex_unlock(&lock); print("sending 2 signals\\n"); pthread_kill(thread, 42); pthread_kill(thread, 42); if (pthread_join(thread, &retval) != 0) perror("failed to join thread"); pthread_cond_destroy(&condvar); pthread_mutex_destroy(&lock); print("all done\\n"); return 0; }
1
#include <pthread.h> struct list_node_s { int data; struct list_node_s* next; }; struct list_node_s* head_p = 0; pthread_mutex_t mutex; int noOfOperationsPerThread; int noOfDeletePerThread; int noOfInsertPerThread; int noOfMemberPerThread; int Delete(int value); int Insert(int value); int Member(int value); void initialize(int); int generateRandom(void); void* doOperations(void*); long current_timestamp(void); int main(int arc, char *argv[]) { if (arc != 7) { printf("Invalid number of arguments %d\\n", arc); return -1; } long start, finish, elapsed; pthread_t* threadHandles; int noOfVariables = atoi(argv[1]); int noOfThreads = atoi(argv[6]); noOfOperationsPerThread = atoi(argv[2]) / noOfThreads; noOfMemberPerThread = strtod(argv[3], 0) * noOfOperationsPerThread; noOfInsertPerThread = strtod(argv[4], 0) * noOfOperationsPerThread; noOfDeletePerThread = strtod(argv[5], 0) * noOfOperationsPerThread; threadHandles = (pthread_t*) malloc (noOfThreads * sizeof(pthread_t)); pthread_mutex_init(&mutex, 0); initialize(noOfVariables); long thread; start = current_timestamp(); for (thread = 0; thread < noOfThreads; thread++) { pthread_create(&threadHandles[thread], 0, doOperations, (void*)thread); } for (thread = 0; thread < noOfThreads; thread++) { pthread_join(threadHandles[thread], 0); } finish = current_timestamp(); elapsed = finish - start; printf("%ld", elapsed); return 0; } long current_timestamp() { struct timeval te; gettimeofday(&te, 0); long milliseconds = te.tv_sec*1000LL + te.tv_usec/1000; return milliseconds; } int generateRandom() { int value = rand() % 65536; return value; } void initialize(int noOfVariables) { srand (time(0)); int inserted = 0; int i; for (i = 0; i < noOfVariables; i++) { inserted = Insert(generateRandom()); if (!inserted) { i--; } } } void* doOperations(void* rank) { long start = ((long) rank) * noOfOperationsPerThread; long end = start + noOfOperationsPerThread; long i; for (i = start; i < end; i++) { if (i < start + noOfInsertPerThread) { int value = generateRandom(); pthread_mutex_lock(&mutex); Insert(value); pthread_mutex_unlock(&mutex); } else if (i < start + noOfInsertPerThread + noOfDeletePerThread) { int value = generateRandom(); pthread_mutex_lock(&mutex); Delete(value); pthread_mutex_unlock(&mutex); } else { int value = generateRandom(); pthread_mutex_lock(&mutex); Member(value); pthread_mutex_unlock(&mutex); } } return 0; } int Delete(int value) { struct list_node_s* curr_p = head_p; struct list_node_s* pred_p = 0; while (curr_p != 0 && curr_p->data < value) { pred_p = curr_p; curr_p = curr_p->next; } if (curr_p != 0 && curr_p->data == value) { if (pred_p == 0) { head_p = curr_p->next; free(curr_p); } else { pred_p->next = curr_p->next; free(curr_p); } return 1; } else { return 0; } } int Insert(int value) { struct list_node_s* curr_p = head_p; struct list_node_s* pred_p = 0; struct list_node_s* temp_p; while (curr_p != 0 && curr_p->data < value) { pred_p = curr_p; curr_p = curr_p->next; } if (curr_p == 0 || curr_p->data > value) { temp_p = malloc(sizeof(struct list_node_s)); temp_p->data = value; temp_p->next = curr_p; if (pred_p == 0) head_p = temp_p; else pred_p->next = temp_p; return 1; } else { return 0; } } int Member(int value) { struct list_node_s* curr_p; curr_p = head_p; while (curr_p != 0 && curr_p->data < value) curr_p = curr_p->next; if (curr_p == 0 || curr_p->data > value) { return 0; } else { return 1; } }
0
#include <pthread.h> pthread_mutex_t print_lock; pthread_mutex_t thread_count_lock; int count_threads; int count_finished; pthread_mutex_t count_in_use_lock; int count_in_use; pthread_cond_t cond_cooled_down; int on_cool_down; void print_state() { pthread_mutex_lock(&print_lock); printf("\\n\\n\\n"); printf("threads:\\n"); printf(" total: %d\\n", count_threads); printf(" waiting: %d\\n", count_threads - count_finished - count_in_use); printf(" running: %d\\n", count_in_use); printf(" finished: %d\\n", count_finished); printf("on cool down: %s\\n", on_cool_down ? "yes" : "no"); pthread_mutex_unlock(&print_lock); } void *locker(void *ptr) { pthread_mutex_lock(&count_in_use_lock); count_threads++; while(on_cool_down && count_in_use > 0) pthread_cond_wait(&cond_cooled_down, &count_in_use_lock); count_in_use++; if(count_in_use == 3) on_cool_down = 1; print_state(); pthread_mutex_unlock(&count_in_use_lock); sleep(rand() % 4 + 2); pthread_mutex_lock(&count_in_use_lock); count_finished++; count_in_use--; if(on_cool_down && !count_in_use) { pthread_cond_signal(&cond_cooled_down); on_cool_down = 0; } print_state(); pthread_mutex_unlock(&count_in_use_lock); pthread_exit(0); } int main(int argc, char *argv[]) { if(argc != 1) { printf("usage: ./a.out\\n"); exit(0); } pthread_mutex_init(&print_lock, 0); pthread_mutex_init(&count_in_use_lock, 0); count_in_use = 0; count_threads = 0; count_finished = 0; pthread_cond_init(&cond_cooled_down, 0); on_cool_down = 0; pthread_t t; while(1) { pthread_create(&t, 0, locker, 0); sleep(rand() % 2); } }
1
#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 process_job(struct job *j) { printf("%s Called\\n", __FUNCTION__); return; } void *thread_function(void *args) { while(1) { struct job *next_job; sem_wait(&job_queue_count); printf("%s : Pass sem_wait job_queue_count[%d]\\n", __FUNCTION__, 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; printf("%s : Calling sem_post\\n", __FUNCTION__); sem_post(&job_queue_count); pthread_mutex_unlock(&job_queue_mutex); } int main() { pthread_t thread; initialize_job_queue(); pthread_create(&thread, 0, &thread_function, 0); enqueue_job(); while(1) { enqueue_job(); } return 0; }
0
#include <pthread.h> int q[5]; int qsiz; pthread_mutex_t mq; void queue_init () { pthread_mutex_init (&mq, 0); qsiz = 0; } void queue_insert (int x) { int done = 0; printf ("prod: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz < 5) { done = 1; q[qsiz] = x; qsiz++; } pthread_mutex_unlock (&mq); } } int queue_extract () { int done = 0; int x = -1, i = 0; printf ("consumer: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz > 0) { done = 1; x = q[0]; qsiz--; for (i = 0; i < qsiz; i++) q[i] = q[i+1]; __VERIFIER_assert (qsiz < 5); q[qsiz] = 0; } pthread_mutex_unlock (&mq); } return x; } void swap (int *t, int i, int j) { int aux; aux = t[i]; t[i] = t[j]; t[j] = aux; } int findmaxidx (int *t, int count) { int i, mx; mx = 0; for (i = 1; i < count; i++) { if (t[i] > t[mx]) mx = i; } __VERIFIER_assert (mx >= 0); __VERIFIER_assert (mx < count); t[mx] = -t[mx]; return mx; } int source[3]; int sorted[3]; void producer () { int i, idx; for (i = 0; i < 3; i++) { idx = findmaxidx (source, 3); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 3); queue_insert (idx); } } void consumer () { int i, idx; for (i = 0; i < 3; i++) { idx = queue_extract (); sorted[i] = idx; printf ("m: i %d sorted = %d\\n", i, sorted[i]); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 3); } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; int i; __libc_init_poet (); for (i = 0; i < 3; i++) { source[i] = __VERIFIER_nondet_int(0,20); printf ("m: init i %d source = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); return 0; }
1
#include <pthread.h> static time_t runtime_cache_timeout_secs = 10; struct hybris_prop_value { char *key; char *value; time_t last_update; }; static struct hybris_prop_value * prop_array = 0; static int num_prop = 0; static int num_alloc = 0; static pthread_mutex_t array_mutex = PTHREAD_MUTEX_INITIALIZER; static int prop_qcmp(const void *a, const void *b) { struct hybris_prop_value *aa = (struct hybris_prop_value *)a; struct hybris_prop_value *bb = (struct hybris_prop_value *)b; return strcmp(aa->key, bb->key); } static struct hybris_prop_value *cache_find_internal(const char *key) { struct hybris_prop_value prop_key; prop_key.key = (char*)key; return bsearch(&prop_key, prop_array, num_prop, sizeof(struct hybris_prop_value), prop_qcmp); } static void runtime_cache_init() { num_alloc = 8; prop_array = malloc(num_alloc * sizeof(struct hybris_prop_value)); const char *timeout_str = getenv("HYBRIS_PROPERTY_CACHE_TIMEOUT_SECS"); if (timeout_str) { runtime_cache_timeout_secs = atoi(timeout_str); } } static void runtime_cache_ensure_initialized() { if (!prop_array) { runtime_cache_init(); } } static void runtime_cache_invalidate_entry(struct hybris_prop_value *entry) { free(entry->value); entry->value = 0; } static int runtime_cache_get_impl(const char *key, char *value) { int ret = -ENOENT; struct hybris_prop_value *entry = cache_find_internal(key); if (entry != 0 && entry->value != 0) { struct timespec now; clock_gettime(CLOCK_MONOTONIC_COARSE, &now); time_t delta_secs = now.tv_sec - entry->last_update; if (delta_secs > runtime_cache_timeout_secs) { runtime_cache_invalidate_entry(entry); } else { strcpy(value, entry->value); ret = 0; } } return ret; } static void runtime_cache_insert_impl(const char *key, char *value) { struct timespec now; clock_gettime(CLOCK_MONOTONIC_COARSE, &now); struct hybris_prop_value *entry = cache_find_internal(key); if (entry) { assert(entry->value == 0); entry->value = strdup(value); entry->last_update = now.tv_sec; } else { if (num_alloc == num_prop) { num_alloc = 3 * num_alloc / 2; prop_array = realloc(prop_array, num_alloc * sizeof(struct hybris_prop_value)); } struct hybris_prop_value new_entry = { strdup(key), strdup(value), now.tv_sec }; prop_array[num_prop++] = new_entry; qsort(prop_array, num_prop, sizeof(struct hybris_prop_value), prop_qcmp); } } void runtime_cache_lock() { pthread_mutex_lock(&array_mutex); } void runtime_cache_unlock() { pthread_mutex_unlock(&array_mutex); } void runtime_cache_remove(const char *key) { runtime_cache_ensure_initialized(); struct hybris_prop_value *entry = cache_find_internal(key); if (entry) { runtime_cache_invalidate_entry(entry); } } int runtime_cache_get(const char *key, char *value) { runtime_cache_ensure_initialized(); return runtime_cache_get_impl(key, value); } void runtime_cache_insert(const char *key, char *value) { runtime_cache_ensure_initialized(); runtime_cache_insert_impl(key, value); }
0
#include <pthread.h> struct Vertex { char* string; struct Vertex* next; }; int counter; pthread_cond_t cond_counter; pthread_mutex_t mut_counter; struct Vertex* head; struct Vertex* tail; char is_drop; } Queue; struct Param { char get_or_put; int ID; Queue* queue; }; void mymsginit(Queue *); void mymsqdrop(Queue *); void mymsgdestroy(Queue *); int mymsgput(Queue *, char * msg); int mymsgget(Queue *, char * buf, size_t bufsize); int start_thread(pthread_t* pthread, struct Param* param); void* thread_body(void* raram); struct Param* get_param(char get_or_put, int ID, Queue* queue); int main(int argc, char* argv) { int i; Queue* queue = (Queue*)malloc(sizeof(Queue)); struct Param** params = (struct Param**)malloc(sizeof(struct Param*)*4); pthread_t** pthreads = (pthread_t**)malloc(sizeof(pthread_t*)*4); mymsginit(queue); for(i=0; i<4; ++i){ pthreads[i] = (pthread_t*)malloc(sizeof(pthread_t)); if(i < 2){ params[i] = get_param(1, i, queue); } else { params[i] = get_param(0, i, queue); } start_thread(pthreads[i], params[i]); } for(i = 0; i < 4; ++i){ pthread_join(*pthreads[i], 0); free(params[i]); free(pthreads[i]); } mymsgdestroy(queue); free(params); free(pthreads); } void mymsginit(Queue* queue) { pthread_cond_init(&queue->cond_counter, 0); pthread_mutex_init(&queue->mut_counter, 0); queue->counter = 0; queue->head = 0; queue->tail = 0; queue->is_drop = 0; } void mymsqdrop(Queue *queue) { queue->is_drop = 1; pthread_cond_broadcast(&queue->cond_counter); } void mymsgdestroy(Queue *queue) { int i; struct Vertex* ver = queue->head; struct Vertex* next; for(; ver != 0; ver = next){ next = ver->next; free(ver); } queue->is_drop = 1; queue->head = 0; queue->tail = 0; pthread_cond_destroy(&queue->cond_counter); pthread_mutex_destroy(&queue->mut_counter); } int mymsgput(Queue *queue, char * msg) { struct Vertex* newVertex; int size_str; if(queue->is_drop){ return 0; } if((newVertex = (struct Vertex*)malloc(sizeof(struct Vertex))) == 0 ){ return -1; } newVertex->next = 0; newVertex->string = (char*)malloc(sizeof(char)*80); size_str = strlen(strncpy(newVertex->string, msg, 80)); pthread_mutex_lock(&queue->mut_counter); while(1){ if(queue->is_drop){ pthread_mutex_unlock(&queue->mut_counter); return 0; } if(queue->counter < 10){ break; } pthread_cond_wait(&queue->cond_counter,&queue->mut_counter); } if(queue->head == 0) { queue->tail = newVertex; queue->head = newVertex; } else { queue->tail->next = newVertex; queue->tail = newVertex; } ++(queue->counter); pthread_mutex_unlock(&queue->mut_counter); pthread_cond_broadcast(&queue->cond_counter); return size_str; } int mymsgget(Queue *queue, char * buf, size_t bufsize) { struct Vertex* ver_get; int size; if(queue->is_drop){ return 0; } pthread_mutex_lock(&queue->mut_counter); while(1){ if(queue->is_drop){ pthread_mutex_unlock(&queue->mut_counter); return 0; } if(queue->counter > 0){ break; } pthread_cond_wait(&queue->cond_counter,&queue->mut_counter); } ver_get = queue->head; if(queue->head->next == 0){ if(queue->head->next == 0){ queue->head = 0; queue->tail = 0; } } else { queue->head = queue->head->next; } --(queue->counter); pthread_mutex_unlock(&queue->mut_counter); pthread_cond_broadcast(&queue->cond_counter); size = strlen(strncpy(buf, ver_get->string, bufsize)); free(ver_get); return size; } int start_thread(pthread_t* pthread, struct Param* param) { int code; code = pthread_create(pthread, 0, thread_body, param); if (code!=0) { char buf[256]; strerror_r(code, buf, sizeof buf); fprintf(stderr, " creating thread: %s\\n", buf); return 1; } return 0; } void* thread_body(void* param_) { int i; struct Param* param = (struct Param*)param_; if(param->get_or_put == 1){ for(i=0; i < 10; ++i){ sleep(1); fprintf(stderr, "put i=%d\\n", i); mymsgput(param->queue, "string111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"); } } else if(param->get_or_put == 0){ for(i=0; i < 10; ++i){ size_t bufsize = 10*i; sleep(10); fprintf(stderr, "get i=%d\\n", i); char *buf = (char*)malloc(sizeof(char) * bufsize); mymsgget(param->queue,buf,bufsize); fprintf(stderr, "%s\\n", buf); free(buf); } } else { fprintf(stderr, "error param thread\\n"); } return 0; } struct Param* get_param(char get_or_put, int ID, Queue* queue) { struct Param* param = (struct Param*)malloc(sizeof(struct Param)); param->get_or_put = get_or_put; param->ID = ID; param->queue = queue; return param; }
1
#include <pthread.h> int n = 20; pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER; void *printyou(void *unused) { int c = n; while (c--) { usleep(10000); printf("你"); } return 0; } void *printme(void *unused) { int c = n; while (c--) { usleep(10000); printf("我"); } return 0; } void *printthim(void *unused) { int c = n; while (c--) { usleep(10000); printf("他"); } return 0; } int main(int argc, char *argv[]) { int c = n; pthread_t tid1, tid2, tid3; pthread_mutex_lock(&mylock); pthread_create(&tid1, 0, &printyou, 0); pthread_create(&tid2, 0, &printme, 0); pthread_create(&tid3, 0, &printthim, 0); pthread_mutex_unlock(&mylock); while (c--) { usleep(10000); printf("O"); } pthread_join(tid1, 0); pthread_join(tid2, 0); pthread_join(tid3, 0); return 0; }
0
#include <pthread.h> pthread_t g_thread[2]; pthread_mutex_t g_mutex; __uint64_t g_count; pid_t gettid() { return syscall(SYS_gettid); } void *run_amuck(void *arg) { int i, j; printf("Thread %lu started.\\n", (unsigned long)gettid()); for (i = 0; i < 10000; i++) { pthread_mutex_lock(&g_mutex); for (j = 0; j < 100000; j++) { if (g_count++ == 123456789) printf("Thread %lu wins!\\n", (unsigned long)gettid()); } pthread_mutex_unlock(&g_mutex); } printf("Thread %lu finished!\\n", (unsigned long)gettid()); return (0); } int main(int argc, char *argv[]) { int i, threads = 2; printf("Creating %d threads...\\n", threads); pthread_mutex_init(&g_mutex, 0); for (i = 0; i < threads; i++) pthread_create(&g_thread[i], 0, run_amuck, (void *) i); for (i = 0; i < threads; i++) pthread_join(g_thread[i], 0); printf("Done.\\n"); return (0); }
1
#include <pthread.h> int q[2]; int qsiz; pthread_mutex_t mq; void queue_init () { pthread_mutex_init (&mq, 0); qsiz = 0; } void queue_insert (int x) { int done = 0; printf ("prod: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz < 2) { done = 1; q[qsiz] = x; qsiz++; } pthread_mutex_unlock (&mq); } } int queue_extract () { int done = 0; int x = -1, i = 0; printf ("consumer: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz > 0) { done = 1; x = q[0]; qsiz--; for (i = 0; i < qsiz; i++) q[i] = q[i+1]; __VERIFIER_assert (qsiz < 2); q[qsiz] = 0; } pthread_mutex_unlock (&mq); } return x; } void swap (int *t, int i, int j) { int aux; aux = t[i]; t[i] = t[j]; t[j] = aux; } int findmaxidx (int *t, int count) { int i, mx; mx = 0; for (i = 1; i < count; i++) { if (t[i] > t[mx]) mx = i; } __VERIFIER_assert (mx >= 0); __VERIFIER_assert (mx < count); t[mx] = -t[mx]; return mx; } int source[6]; int sorted[6]; void producer () { int i, idx; for (i = 0; i < 6; i++) { idx = findmaxidx (source, 6); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 6); queue_insert (idx); } } void consumer () { int i, idx; for (i = 0; i < 6; i++) { idx = queue_extract (); sorted[i] = idx; printf ("m: i %d sorted = %d\\n", i, sorted[i]); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 6); } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; int i; __libc_init_poet (); for (i = 0; i < 6; i++) { source[i] = __VERIFIER_nondet_int(0,20); printf ("m: init i %d source = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); return 0; }
0
#include <pthread.h> enum {THINKING,EATING,SLEEPING,SLEEPY,HUNGRY} state[5]; int N=5; sem_t sleepsem; sem_t pick[5]; pthread_mutex_t lock; int duration=300; void take_bed(int i) { int value; state[i]=SLEEPY; sem_wait(&sleepsem); sem_getvalue(&sleepsem,&value); printf("Thread[%d]: Sleepsm value after wait %d\\n",i,value); if(state[i] == SLEEPY){ state[i]=SLEEPING; } } void release_bed(int i) { state[i]=HUNGRY; sem_post(&sleepsem); } void test_forks(int i){ if((state[(i+1) % 5] != EATING) && (state[(i+4) % 5] != EATING) && (state[i] == HUNGRY)){ state[i]=EATING; sem_post(&pick[i]); } } void take_forks(int i) { pthread_mutex_lock(&lock); state[i]=HUNGRY; test_forks(i); pthread_mutex_unlock(&lock); if(state[i] != EATING){ sem_wait(&pick[i]); take_forks(i); } } void release_forks(int i) { state[i]=THINKING; test_forks((i+1) % 5); test_forks((i+4) % 5); } void thinking(int i) { if(state[i] == THINKING){ sleep(rand() % 5 + 1); } } void eating(int i) { if(state[i] == EATING){ sleep(rand() % 5 + 1); } } void sleeping(int i) { if(state[i] == SLEEPING){ sleep(rand() % 5 + 1); } } void *philosopher(void *n) { int i=*(int*)n; while(1) { take_bed(i); sleeping(i); release_bed(i); thinking(i); } } int main(int argc, char *argv[]){ if(argc > 1){ duration=atoi(argv[1]); if(duration <= 0){ printf("Usage: %s <Number of seconds>\\n",argv[0]); exit(1); } } int i, var[N]; pthread_t tid[N]; time_t start=time(0); for(i=0;i<N;i++){ var[i]=i; pthread_create(&tid[i], 0, philosopher, &var[i]); state[i]=THINKING; sem_init(&pick[i],0,0); sem_init(&sleepsem,0,1); } while(1){ if((time(0)-start)>duration){ printf("Elapsed %d seconds, Exiting...\\n",duration); exit(0); } for(i=0;i<N;i++){ if(state[i] == THINKING){ printf("Philosopher %d: thinking\\n",i); } else if(state[i] == EATING){ printf("Philosopher %d: eating\\n",i); } else if(state[i] == SLEEPING){ printf("Philosopher %d: sleeping\\n",i); } else if(state[i] == SLEEPY){ printf("Philosopher %d: waiting to sleep\\n",i); } else if(state[i] == HUNGRY){ printf("Philosopher %d: waiting to eat\\n",i); } } printf("\\n"); sleep(1); } }
1
#include <pthread.h> struct timeval startwtime, endwtime; double seq_time; double *x; double *z; double error; double p; double delta; double temp_add; int repeats; int nodes; int threads; pthread_mutex_t lock= PTHREAD_MUTEX_INITIALIZER; pthread_t *threads_array; int begin; int end; int id; }Thread_job; Thread_job *thread_jobs; int size; int* index; } Connection; Connection *connections; void page_rank(); int main(){ int i, j; printf("Set the number of nodes\\n"); scanf("%d", &nodes); printf("Set the number of threads\\n"); scanf("%d", &threads); repeats=0; char* filename="data.txt"; connections= (Connection *)malloc(nodes*sizeof(Connection)); for(i=0;i<nodes;i++){ connections[i].size=0; connections[i].index=(int*)calloc(0, sizeof(int)); } FILE *f=fopen(filename, "r"); if(f==0){ printf("Error in opening file\\n"); return 1; } char* type= "%d\\t%d\\n"; while(!feof(f)){ if(fscanf(f, type, &j, &i)){ if(j>nodes || i>nodes){ continue; } connections[j].size++; connections[j].index=(int*)realloc(connections[j].index, connections[j].size*sizeof(int)); connections[j].index[connections[j].size-1]= i; } } fclose(f); threads_array= (pthread_t *)malloc(threads*sizeof(pthread_t)); thread_jobs= (Thread_job*)malloc(threads*sizeof(Thread_job)); int nodes_per_thread= ceil((double) nodes/threads); int data_jump=0; for(i=0;i<threads;i++){ thread_jobs[i].id=i; thread_jobs[i].begin=data_jump; data_jump+= nodes_per_thread; if(data_jump>nodes){ thread_jobs[i].end= nodes-1; }else{ thread_jobs[i].end= data_jump; } } gettimeofday (&startwtime, 0); page_rank(); gettimeofday (&endwtime, 0); seq_time = (double)((endwtime.tv_usec - startwtime.tv_usec)/1.0e6 + endwtime.tv_sec - startwtime.tv_sec); printf("Parallel clock time = %f\\n", seq_time); printf("Number of repeats for convergence %d\\n", repeats); f=fopen("x_out.txt", "w"); if (f==0){ printf("Error saving data\\n"); return 2; } for(i=0;i<nodes;i++) fprintf(f,"%f\\n",x[i]); fclose(f); double temp_val=0; for(i=0;i<nodes;i++) temp_val+=x[i]; printf("Total sum of probabilities %f\\n", temp_val); for(i=0;i<nodes;i++){ free(connections[i].index); } free(connections); free(threads_array); free(thread_jobs); free(x); free(z); return 0; } void* copy_data(void* temp_thread_job){ Thread_job *thread_job= (Thread_job*)temp_thread_job; int i; for(i=thread_job->begin;i<thread_job->end;i++){ z[i]=x[i]; x[i]=0; } pthread_exit(0); } void* first_loop(void* temp_thread_job){ Thread_job *thread_job= (Thread_job*)temp_thread_job; int i, j; double temp_val; double temp_add_local=0; for(j=thread_job->begin; j<thread_job->end; j++){ Connection temp= connections[j]; if(temp.size==0){ temp_add_local+=(double)(z[j]/nodes); }else{ temp_val=(double) z[j]/temp.size; for(i=0;i<temp.size;i++){ x[temp.index[i]]+=temp_val; } } } pthread_mutex_lock(&lock); temp_add+=temp_add_local; pthread_mutex_unlock(&lock); pthread_exit(0); } void* second_loop(void* temp_thread_job){ Thread_job *thread_job= (Thread_job*)temp_thread_job; int i; double temp_val; double max=0; for(i=thread_job->begin; i<thread_job->end; i++){ x[i]= p*(x[i]+temp_add) +delta; temp_val=fabs(x[i]-z[i]); if(temp_val>max) max= temp_val; } pthread_mutex_lock(&lock); if(error<max) error=max; pthread_mutex_unlock(&lock); pthread_exit(0); } void page_rank(){ int i, j; p= (double)0.85; delta= (double)(1-p)/nodes; x=(double*)malloc(nodes*sizeof(double)); z=(double*)malloc(nodes*sizeof(double)); for(i=0; i<nodes;i++){ x[i]= (double)1/nodes; } do{ temp_add=0; for(i=0;i<threads;i++) pthread_create(&threads_array[i], 0, &copy_data, (void*)&thread_jobs[i]); for(i=0;i<threads;i++) pthread_join(threads_array[i], 0); for(i=0;i<threads;i++) pthread_create(&threads_array[i], 0, &first_loop, (void*)&thread_jobs[i]); for(i=0;i<threads;i++) pthread_join(threads_array[i], 0); error=0; for(i=0;i<threads;i++) pthread_create(&threads_array[i], 0, &second_loop, (void*)&thread_jobs[i]); for(i=0;i<threads;i++) pthread_join(threads_array[i], 0); repeats++; }while(error>0.0001); }
0
#include <pthread.h> pthread_mutex_t the_mutex; pthread_cond_t condc, condp; int buffer = 0; void* producer(void *ptr) { int i; for (i = 1; i <= 10000000000; i++) { pthread_mutex_lock(&the_mutex); while (buffer != 0) pthread_cond_wait(&condp, &the_mutex); buffer = i; pthread_cond_signal(&condc); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } void* consumer(void *ptr) { int i; for (i = 1; i <= 10000000000; i++) { pthread_mutex_lock(&the_mutex); while (buffer == 0) pthread_cond_wait(&condc, &the_mutex); buffer = 0; pthread_cond_signal(&condp); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } int main(int argc, char **argv) { pthread_t pro, con; pthread_mutex_init(&the_mutex, 0); pthread_cond_init(&condc, 0); pthread_cond_init(&condp, 0); pthread_create(&con, 0, consumer, 0); pthread_create(&pro, 0, producer, 0); pthread_join(&con, 0); pthread_join(&pro, 0); pthread_mutex_destroy(&the_mutex); pthread_cond_destroy(&condc); pthread_cond_destroy(&condp); }
1
#include <pthread.h> int queue[10]; int front =-1; int tail=0; int pro_num=0; int left_num=10; pthread_mutex_t mymutex; pthread_cond_t produce,consumer; static void* pro_func(void*); static void* con_func(void*); int main(int argc,char *argv[]) { srand(getpid()); pthread_t tid1,tid2; pthread_mutex_init(&mymutex,0); pthread_cond_init(&produce,0); pthread_cond_init(&consumer,0); int p1=atoi(argv[1]); int p2=atoi(argv[2]); while(p1) { pthread_create(&tid1,0,pro_func,0); p1--; } while(p2) { pthread_create(&tid2,0,con_func,0); p2--; } pthread_join(tid1,0); pthread_join(tid2,0); pthread_mutex_destroy(&mymutex); pthread_cond_destroy(&produce); pthread_cond_destroy(&consumer); return 0; } void* pro_func(void *arg) { while(1) { pthread_mutex_lock(&mymutex); while(left_num==0) pthread_cond_wait(&produce,&mymutex); pro_num++; left_num--; queue[tail]=rand()%100; printf("producer: tail:%d pro_num:%d\\n",queue[tail],pro_num); tail++; if(pro_num==1) pthread_cond_broadcast(&consumer); pthread_mutex_unlock(&mymutex); sleep(rand()%5+1); } } void* con_func(void *arg) { while(1) { pthread_mutex_lock(&mymutex); while(pro_num==0) pthread_cond_wait(&consumer,&mymutex); pro_num--; left_num++; printf("consumer: tail:%d pro_num: %d\\n",queue[tail-1],pro_num); tail--; if(left_num==1) pthread_cond_broadcast(&produce); pthread_mutex_unlock(&mymutex); sleep(rand()%5+1); } }
0
#include <pthread.h> pthread_mutex_t tenedor[5]; void pensar(int i){ printf("Filosofo %d pensando...\\n",i); usleep(random() % 50000); } void comer(int i){ printf("Filosofo %d comiendo...\\n",i); usleep(random() % 50000); } void tomar_tenedores_zurdo(int i) { pthread_mutex_lock(&(tenedor[(i+1)%5])); sleep(1); pthread_mutex_lock(&(tenedor[i])); } void tomar_tenedores(int i) { pthread_mutex_lock(&(tenedor[i])); sleep(1); pthread_mutex_lock(&(tenedor[(i+1)%5])); } void dejar_tenedores(int i) { pthread_mutex_unlock(&(tenedor[i])); pthread_mutex_unlock(&(tenedor[(i+1)%5])); } void diestro() { for (;;) { tomar_tenedores(omp_get_thread_num()); comer(omp_get_thread_num()); dejar_tenedores(omp_get_thread_num()); pensar(omp_get_thread_num()); } } void zurdo() { for (;;) { tomar_tenedores_zurdo(omp_get_thread_num()); comer(omp_get_thread_num()); dejar_tenedores(omp_get_thread_num()); pensar(omp_get_thread_num()); } } int main () { omp_set_num_threads(5); { { zurdo(); } diestro(); } return 0; }
1
#include <pthread.h> int q[2]; int qsiz; pthread_mutex_t mq; void queue_init () { pthread_mutex_init (&mq, 0); qsiz = 0; } void queue_insert (int x) { int done = 0; printf ("prod: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz < 2) { done = 1; q[qsiz] = x; qsiz++; } pthread_mutex_unlock (&mq); } } int queue_extract () { int done = 0; int x = -1, i = 0; printf ("consumer: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz > 0) { done = 1; x = q[0]; qsiz--; for (i = 0; i < qsiz; i++) q[i] = q[i+1]; __VERIFIER_assert (qsiz < 2); q[qsiz] = 0; } pthread_mutex_unlock (&mq); } return x; } void swap (int *t, int i, int j) { int aux; aux = t[i]; t[i] = t[j]; t[j] = aux; } int findmaxidx (int *t, int count) { int i, mx; mx = 0; for (i = 1; i < count; i++) { if (t[i] > t[mx]) mx = i; } __VERIFIER_assert (mx >= 0); __VERIFIER_assert (mx < count); t[mx] = -t[mx]; return mx; } int source[3]; int sorted[3]; void producer () { int i, idx; for (i = 0; i < 3; i++) { idx = findmaxidx (source, 3); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 3); queue_insert (idx); } } void consumer () { int i, idx; for (i = 0; i < 3; i++) { idx = queue_extract (); sorted[i] = idx; printf ("m: i %d sorted = %d\\n", i, sorted[i]); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 3); } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; int i; __libc_init_poet (); for (i = 0; i < 3; i++) { source[i] = __VERIFIER_nondet_int(0,20); printf ("m: init i %d source = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); return 0; }
0
#include <pthread.h> struct Params { long startPos; long endPos; }; pthread_mutex_t readFlag; pthread_mutex_t writeFlag; pthread_mutex_t copyFlag; pthread_mutex_t changeFlag; char *progName, *inFile, *outFile; volatile unsigned short int threadCount = 0; unsigned short int threadLimit; int fd1, fd2; void *copy(void *); void copyAccessRights (char* , char* ); int getFileSize (char filePath[PATH_MAX]) { struct stat fileInfo; stat(filePath, &fileInfo); return fileInfo.st_size; } int main(int argc, char **argv) { pthread_mutex_init(&readFlag, 0); pthread_mutex_init(&writeFlag, 0); pthread_mutex_init(&copyFlag, 0); pthread_mutex_init(&changeFlag, 0); progName = basename(argv[0]); if (argc != 4) { fprintf(stderr, "%s: Nevernoe kolichestvo argumentov (path1 path2 N)\\n", progName); return 1; } threadLimit = atoi(argv[3]); threadLimit--; if (threadLimit <= 0) { fprintf(stderr, "%s: Nevernoe kolichestvo potokov (N)\\n", progName); return 1; } inFile = (char *) malloc(strlen(argv[1]) * sizeof(char)); strcpy(inFile, argv[1]); outFile = (char *) malloc(strlen(argv[2]) * sizeof(char)); strcpy(outFile, argv[2]); struct stat fileInfo; stat(inFile, &fileInfo); int flags = O_RDONLY; fd1 = open64(inFile, flags, fileInfo.st_mode); if (fd1 == -1) { fprintf(stderr, "%s : %s : %s\\n", progName, strerror(errno), inFile); return 1; } unsigned long size, partSize; size = getFileSize(inFile); FILE *fDest; fDest = fopen(outFile, "w+"); fseek(fDest, size - 1, 1); fprintf(fDest,"!"); fclose(fDest); copyAccessRights (inFile, outFile); flags = O_RDWR | O_CREAT; fd2 = open64(outFile, flags, fileInfo.st_mode); partSize = size / threadLimit; printf("%s: Size: %lu byte\\t PartSize: %lu byte\\n", progName, size, partSize); int i; params *p; pthread_t tid; for(i = 0; i < threadLimit; i++) { p = (params *)malloc(sizeof(params)); p->startPos = partSize * i; p->endPos = partSize * (i + 1) + (size % threadLimit); if((i + 1) == threadLimit) p->endPos = size; pthread_attr_t threadAttr; int result = pthread_attr_init(&threadAttr); if (result != 0) { fprintf(stderr, "%s : Oshibka v atributah sozdaniya potoka\\n", progName); exit(1); } result = pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED); if (result != 0) { fprintf(stderr, "%s : Oshibka v atributah sozdaniya potoka\\n", progName); exit(1); } result = pthread_create(&tid, &threadAttr, copy, (void *)p); if (result != 0) { } } sleep(1); while (threadCount) { usleep(20); } close(fd1); close(fd2); return 0; } void *copy(void *param) { params p = *((params *)param); pthread_mutex_lock(&changeFlag); threadCount++; pthread_mutex_unlock(&changeFlag); unsigned long size = p.endPos - p.startPos; unsigned long currPos = p.startPos; char buf[1024]; int readCount = 0; FILE *fSrc, *fDest; while (size != 0) { if(size > 1024) { readCount = 1024; size -= 1024; } else { readCount = size; size = 0; } printf("%d\\t%lu\\t%lu\\r\\n", syscall(SYS_gettid), currPos, readCount); memset(buf,0, 1024); pthread_mutex_lock(&readFlag); lseek64(fd1, currPos, 0); read(fd1, buf, readCount); pthread_mutex_unlock(&readFlag); pthread_mutex_lock(&writeFlag); lseek64(fd2, currPos, 0); write(fd2, buf, readCount); pthread_mutex_unlock(&writeFlag); currPos += readCount; } pthread_mutex_lock(&changeFlag); threadCount--; pthread_mutex_unlock(&changeFlag); free(param); return 0; } void copyAccessRights (char* inFilePath, char* outFilePath) { struct stat fileInfo; stat(inFilePath, &fileInfo); chmod(outFilePath, fileInfo.st_mode); }
1
#include <pthread.h> int Graph[101][101]; int dist[101][101]; pthread_mutex_t mutex,wrt; int readCount; int n; void * handle_i(void *args) { int i = ((int *)(args))[0]; int k = ((int *)(args))[1]; int j,dist_i_k,dist_k_j,dist_i_j; for(j=1;j<=n;++j) { pthread_mutex_lock(&mutex); readCount++; if(readCount == 1) { pthread_mutex_lock(&wrt); } pthread_mutex_unlock(&mutex); dist_i_k = dist[i][k]; dist_k_j = dist[k][j]; dist_i_j = dist[i][j]; pthread_mutex_lock(&mutex); readCount--; if(readCount == 0) { pthread_mutex_unlock(&wrt); } pthread_mutex_unlock(&mutex); if(dist_i_k+dist_k_j<dist_i_j) { pthread_mutex_lock(&wrt); dist[i][j] = dist_i_k+dist_k_j; pthread_mutex_unlock(&wrt); } } } int main() { int i,j,k,m,u,v,w; pthread_t threads[101]; int arg[101][2]; scanf("%d%d",&n,&m); for(i=1;i<=n;++i) { for(j=1;j<=n;++j) { Graph[i][j] = 0; } } for(i=0;i<m;++i) { scanf("%d%d%d",&u,&v,&w); Graph[u][v] = w; Graph[v][u] = w; } for(i=1;i<=n;++i) { for(j=1;j<=n;++j) { if(i == j) dist[i][j] = 0; else if(Graph[i][j] == 0) { dist[i][j] = 100000000; } else{ dist[i][j] = Graph[i][j]; } } } printf("\\nInitial dist Matrix\\n"); printf("------------------\\n\\n"); for(i=1;i<=n;++i) { for(j=1;j<=n;++j) { if(dist[i][j] == 100000000) { printf("INF\\t"); } else printf("%d\\t",dist[i][j]); } printf("\\n"); } for(k=1;k<=n;++k) { pthread_mutex_init(&mutex,0); pthread_mutex_init(&wrt,0); readCount = 0; for(i=1;i<=n;++i) { arg[i][0] = i; arg[i][1] = k; if(pthread_create(&threads[i],0,handle_i,&(arg[i]))) { printf("Error Creating Thread\\n"); } } for(i=1;i<=n;++i) { if(pthread_join(threads[i],0)) { printf("Error Joining Thread\\n"); } } pthread_mutex_destroy(&mutex); pthread_mutex_destroy(&wrt); } printf("\\nFinal dist Matrix\\n"); printf("------------------\\n"); for(i=1;i<=n;++i) { for(j=1;j<=n;++j) { if(dist[i][j] == 100000000) { printf("INF\\t"); } else printf("%d\\t",dist[i][j]); } printf("\\n"); } return 0; }
0
#include <pthread.h> struct Buffer { char *buf; int in; int out; int count; int size; pthread_cond_t empty; pthread_cond_t full; pthread_mutex_t m; }; void put(struct Buffer *b, char c) { pthread_mutex_lock(&b->m); printf("put\\n"); while (b->count==b->size) { printf("waitput\\n"); pthread_cond_wait(&b->full, &b->m); } b->buf[b->in] = c; b->in = ((b->in)+1)%(b->size); ++(b->count); pthread_cond_signal(&b->empty); pthread_mutex_unlock(&b->m); } char get(struct Buffer *b) { pthread_mutex_lock(&b->m); printf("get\\n"); while (b->count==0) { printf("waitget\\n"); pthread_cond_wait(&b->empty, &b->m); } char c = b->buf[b->out]; b->buf[b->out] = '\\0'; b->out = ((b->out)+1)%(b->size); --(b->count); pthread_cond_signal(&b->full); pthread_mutex_unlock(&b->m); return c; } void initBuffer(struct Buffer *b, int size) { b->in = 0; b->out = 0; b->count = 0; b->size = size; pthread_mutex_init(&b->m, 0); pthread_cond_init(&b->empty, 0); pthread_cond_init(&b->full, 0); b->buf = (char*)malloc(sizeof(char) * size); if (b->buf == 0) exit(-1); }; void destroyBuffer(struct Buffer* b) { free(b->buf); }; void *producerFunc(void *param) { struct Buffer* b = (struct Buffer*)param; int i; for (i = 0; i < (100); ++i) { char c = (char)(26 * (rand() / (32767 + 1.0))) + 97; put(b, c); usleep( getRandSleepTime()*2 ); } }; int getRandSleepTime() { return rand() % 100000; } void *consumerFunc(void *param) { struct Buffer* b = (struct Buffer*)param; int i; for (i = 0; i < (100); ++i) { printf("%c\\n", get(b)); usleep( getRandSleepTime()); }; }; int main(int argc, char **argv) { pthread_t producer, consumer; srand(time(0)); struct Buffer b; initBuffer(&b, 10); pthread_create( &producer, 0, producerFunc, &b ); pthread_create( &consumer, 0, consumerFunc, &b ); pthread_join( producer, 0 ); pthread_join( consumer, 0 ); destroyBuffer(&b); return 0; }
1
#include <pthread.h> int voti[2]; char film[2][40]; char vincitore[40]; int pareri; pthread_mutex_t m; } sondaggio; sem_t mb; sem_t sb; int arrivati; } barriera; pthread_mutex_t mf; char vincitore[40]; } film_stream; sondaggio S; barriera B; film_stream F; void init(sondaggio *s, barriera *b) { int i; for(i=0;i<2; i++) { printf("Qual è il nome del film numero %d ?", i+1); gets(s->film[i]); s->voti[i]=0; } s->pareri=0; pthread_mutex_init(&s->m, 0); sem_init(&b->mb,0,1); sem_init(&b->sb,0,0); b->arrivati=0; } void esprimi_pareri(sondaggio *s, int th) { int i, voto; pthread_mutex_lock(&s->m); printf("\\n\\n COMPILAZIONE QUESTIONARIO per lo Spettatore %d:\\n", th); for(i=0;i<2; i++) { printf("voto del film %s [0,.. 10]? ", s->film[i]); scanf("%d", &voto); s->voti[i]+=voto; } s->pareri++; printf("FINE QUESTIONARIO per lo spettatore %d\\n RISULTATI PARZIALI SONDAGGIO:\\n", th); for(i=0;i<2;i++) printf("Valutazione media film %s: %f\\n", s->film[i], (float)(s->voti[i])/s->pareri); pthread_mutex_unlock (&s->m); } film_stream winner(sondaggio *s) { int i_max, t; float max, media=0; film_stream result; printf("\\n\\n--- R I S U L T A T I ---\\n"); i_max=0; max=0; for(t=0; t<2;t++) { media=(float) s->voti[t]/s->pareri; printf("Valutazione media del film n.%d (%s): %f\\n", t+1, s->film[t], media); if (media>max) { max=media; i_max=t; } } printf("\\n\\n IL FILM VINCITORE E': %s, con voto %f !\\n", s->film[i_max], max); strcpy(s->vincitore, s->film[i_max]); strcpy(result.vincitore, s->film[i_max]); pthread_mutex_init(&result.mf, 0); return result; } void sync_barriera(barriera *b, sondaggio *s) { sem_wait(&b->mb); b->arrivati++; if (b->arrivati==3) { F=winner(s); sem_post(&b->sb); } sem_post(&b->mb); sem_wait(&b->sb); sem_post(&b->sb); return; } void *spettatore(void *t) { long tid, result=0; tid = (int)t; esprimi_pareri(&S, tid); sync_barriera(&B, &S); printf("Spettatore %ld vede il film vincitore: %s\\n",tid, F.vincitore); pthread_exit((void*) result); } int main (int argc, char *argv[]) { pthread_t thread[3]; int rc; long t; void *status; init(&S, &B); for(t=0; t<3; t++) { rc = pthread_create(&thread[t], 0, spettatore, (void *)t); if (rc) { printf("ERRORE: %d\\n", rc); exit(-1); } } for(t=0; t<3; t++) { rc = pthread_join(thread[t], &status); if (rc) printf("ERRORE join thread %ld codice %d\\n", t, rc); } return 0; }
0
#include <pthread.h> int buffer[1024]; int count=0; pthread_mutex_t mutex1; pthread_mutex_t mutex2; pthread_mutex_t mutex3; void *threadFun1(void *arg) { int i; while(1) { pthread_mutex_lock(&mutex1); printf("Thread 1\\n"); count++; if((count%2)==1) { pthread_mutex_unlock(&mutex3); } else { pthread_mutex_unlock(&mutex2); } } } void *threadFun2(void *arg) { int i; while(1) { pthread_mutex_lock(&mutex2); printf("Thread 2:%d\\n",count); pthread_mutex_unlock(&mutex1); } } void *threadFun3(void *arg) { int i; while(1) { pthread_mutex_lock(&mutex3); printf("Thread 3:%d\\n",count); pthread_mutex_unlock(&mutex1); } } int main() { pthread_t tid[3]; int ret=0; int i; int t_value[3]; void *(*threadFun[])(void*) = {threadFun1, threadFun2,threadFun3}; ret = pthread_mutex_init(&mutex1,0); if(ret!=0) { fprintf(stderr, "pthread mutex init error:%s", strerror(ret)); return 1; } ret = pthread_mutex_init(&mutex2,0); if(ret!=0) { fprintf(stderr, "pthread mutex init error:%s", strerror(ret)); return 1; } pthread_mutex_lock(&mutex2); ret = pthread_mutex_init(&mutex3,0); if(ret!=0) { fprintf(stderr, "pthread mutex init error:%s", strerror(ret)); return 1; } pthread_mutex_lock(&mutex3); printf("Main thread before pthread create\\n"); for(i=0; i<3; i++) { t_value[i]=i; ret=pthread_create( &(tid[i]), 0, threadFun[i], (void*)&(t_value[i])); if(ret!=0) { fprintf(stderr, "pthread create error:%s", strerror(ret)); return 1; } } printf("Main thread after pthread create\\n"); for(i=0; i<3; i++) { ret = pthread_join(tid[i],0); if(ret!=0) { fprintf(stderr, "pthread join error:%s", strerror(ret)); return 2; } } ret = pthread_mutex_destroy(&mutex1); if(ret!=0) { fprintf(stderr, "pthread mutex destroy error:%s", strerror(ret)); return 1; } ret = pthread_mutex_destroy(&mutex2); if(ret!=0) { fprintf(stderr, "pthread mutex destroy error:%s", strerror(ret)); return 1; } ret = pthread_mutex_destroy(&mutex3); if(ret!=0) { fprintf(stderr, "pthread mutex destroy error:%s", strerror(ret)); return 1; } printf("All threads are over!\\n"); return 0; }
1
#include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int glo_val1 = 1, glo_val2 = 2; void *ssu_thread1(void *arg); void *ssu_thread2(void *arg); int main(void) { pthread_t tid1, tid2; pthread_create(&tid1, 0, ssu_thread1, 0); pthread_create(&tid2, 0, ssu_thread2, 0); pthread_join(tid1, 0); pthread_join(tid2, 0); pthread_mutex_destroy(&lock); pthread_cond_destroy(&cond); exit(0); } void *ssu_thread1(void *arg) { sleep(1); glo_val1 = 2; glo_val2 = 1; if(glo_val1 > glo_val2) pthread_cond_broadcast(&cond); printf("ssu_thread1 end\\n"); return 0; } void *ssu_thread2(void *arg) { struct timespec timeout; struct timeval now; pthread_mutex_lock(&lock); gettimeofday(&now, 0); timeout.tv_sec = now.tv_sec + 5; timeout.tv_nsec = now.tv_usec * 1000; if(glo_val1 <= glo_val2) { printf("ssu_thread2 sleep\\n"); if(pthread_cond_timedwait(&cond, &lock, &timeout) == ETIMEDOUT) printf("timeout\\n"); else printf("glo_val1 = %d, glo_val2 = %d\\n", glo_val1, glo_val2); } pthread_mutex_unlock(&lock); printf("ssu_thread2 end\\n"); return 0; }
0
#include <pthread.h> struct timeval search_start; struct timeval search_target_end; unsigned int white_time_left; unsigned int white_time_inc; unsigned int black_time_left; unsigned int black_time_inc; bool think_infinite; bool v_is_thinking; bool stop_status; pthread_mutex_t lock; void set_infinite_think(bool s) { think_infinite = s; } void start_search_clock(bool is_white) { gettimeofday(&search_start, 0); unsigned int t_inc = is_white ? white_time_inc : black_time_inc; unsigned int t_left = is_white ? white_time_left : black_time_left; unsigned int longest_allowed_search = t_inc + (t_left / 30); longest_allowed_search = longest_allowed_search < t_left/2 ? longest_allowed_search : t_left/2; unsigned int target_usec = 1000 * (longest_allowed_search % 1000); unsigned int target_sec = 0; target_usec += search_start.tv_usec; if (target_usec > 1000000) { target_usec %= 1000000; target_sec += 1; } target_sec += longest_allowed_search / 1000; target_sec += search_start.tv_sec; search_target_end.tv_sec = target_sec; search_target_end.tv_usec = target_usec; } bool should_continue_greater_depth( clock_t last_search_ticks) { return !should_stop(); } bool should_stop_on_time() { if (think_infinite) return 0; struct timeval current_time; gettimeofday(&current_time, 0); if (current_time.tv_sec < search_target_end.tv_sec) return 0; if (current_time.tv_sec == search_target_end.tv_sec) if(current_time.tv_usec < search_target_end.tv_usec) return 0; return 1; } void init_manage_time() { pthread_mutex_init(&lock, 0); pthread_mutex_lock(&lock); v_is_thinking = 0; pthread_mutex_unlock(&lock); } void cleanup_manage_time() { pthread_mutex_destroy(&lock); } void set_to_stop(bool should_stop) { pthread_mutex_lock(&lock); stop_status = should_stop; pthread_mutex_unlock(&lock); } void set_is_thinking(bool s) { pthread_mutex_lock(&lock); v_is_thinking = s; pthread_mutex_unlock(&lock); } bool is_thinking() { bool thinking_status; pthread_mutex_lock(&lock); thinking_status = v_is_thinking; pthread_mutex_unlock(&lock); return thinking_status; } bool should_stop() { return should_stop_gui_request() || should_stop_on_time(); } bool should_stop_gui_request() { bool status; pthread_mutex_lock(&lock); status = stop_status; pthread_mutex_unlock(&lock); return status; } void set_white_time_left(unsigned int w_time_left) { white_time_left = w_time_left; } void set_black_time_left(unsigned int b_time_left) { black_time_left = b_time_left; } void set_white_time_inc(unsigned int w_time_inc) { white_time_inc = w_time_inc; } void set_black_time_inc(unsigned int b_time_inc) { black_time_inc = b_time_inc; }
1
#include <pthread.h> pthread_t stu_thread[2]; pthread_mutex_t mutex_lock; pthread_cond_t cond_ready; int number = 0; void * studentA() { int i = 0; for(i = 0; i < 5; i++) { pthread_mutex_lock(&mutex_lock); number++; printf("studentA has finished the work one time\\n"); pthread_mutex_unlock(&mutex_lock); sleep(1); } if(5 <= number) { printf("studentA has finished all works!!!\\n"); pthread_cond_signal(&cond_ready); } pthread_exit(0); } void * studentB() { pthread_mutex_lock(&mutex_lock); if(5 >= number) { pthread_cond_wait(&cond_ready, &mutex_lock); } number = 0; printf("studentB has finished his work!!!\\n"); pthread_mutex_unlock(&mutex_lock); pthread_exit(0); } int main() { pthread_mutex_init(&mutex_lock, 0); pthread_cond_init(&cond_ready, 0); pthread_create(&stu_thread[0], 0, studentA, 0); pthread_create(&stu_thread[1], 0, studentB, 0); pthread_join(stu_thread[0], 0); pthread_join(stu_thread[1], 0); return 0; }
0
#include <pthread.h> pthread_t pthreads[4]; pthread_mutex_t locks[4]; char *topics[3] = {"life","death","world hunger"}; void *philosopher(void *arg){ int philonum = *((int *)arg); int left_fork; int right_fork; left_fork=philonum; if(philonum==4 -1) right_fork = 0; else right_fork = philonum+1; while(1){ sleep(rand()%3); sleep(rand()%10); pthread_mutex_lock(&locks[left_fork]); pthread_mutex_lock(&locks[right_fork]); sleep(rand()%10); pthread_mutex_unlock(&locks[left_fork]); pthread_mutex_unlock(&locks[right_fork]); } } int main(int argc, char *argv[]) { int i; int philonums[4]; for(i=0;i<4;i++){ philonums[i]=i; pthread_mutex_init(&locks[i],0); pthread_create(&pthreads[i],0,philosopher,&philonums[i]); } for(i=0;i<4;i++){ pthread_join(pthreads[i],0); } return 0; }
1
#include <pthread.h> void *countWords(void *); int wordCount = 0; pthread_mutex_t mutex; char data[81920]; struct bufferPartition { int start; int end; }; int main(int argc, char *argv[]) { clock_t t1,t2; int bytesRead = 1; struct bufferPartition partitions[1]; pthread_t tid[1]; int i,totalBytes; int offset=0; pthread_attr_t attr; pthread_attr_init(&attr); pthread_mutex_init(&mutex,0); if (argc != 2) { fprintf(stderr,"Error, wrong number of arguments\\n"); return(1); } int fd1 = open(argv[1],O_RDONLY); if (fd1 == -1) { fprintf(stderr,"Error opening of file\\n"); return(1); } while(bytesRead > 0) { bytesRead = read(fd1,data,81920); totalBytes = totalBytes + bytesRead; } if (bytesRead == -1) { fprintf(stderr,"Error reading file\\n"); return(1); } else close(fd1); int partitionSizes[1]; int bufferBytes = 0; for (i=0; i < 1;i++) { partitionSizes[i] = totalBytes/1; } for (i = 0; i < totalBytes % 1;i++) { partitionSizes[i] += 1; } t1 = clock(); for(int i = 0; i < 1; i++) { if(i == 0) { partitions[i].start = 0; } else { partitions[i].start = (partitions[i - 1].end) + 1; } partitions[i].end = partitions[i].start + (partitionSizes[i]); while(isalnum(data[partitions[i].end])) { (partitions[i].end)++; } pthread_create(&tid[i], &attr, countWords, &partitions[i]); } for(int i = 0; i < 1; i++) { pthread_join(tid[i], 0); } t2 = clock(); printf("Elapsed: %.4f\\n", (t2 - t1) / (double) CLOCKS_PER_SEC); printf("Running with %d threads,\\n", 1); printf("The file contains %d words.\\n", wordCount); pthread_exit(0); return 0; } void* countWords(void* arg) { struct bufferPartition *currentPart = arg; pthread_mutex_lock(&mutex); if(isalnum(data[currentPart->start])) { wordCount++; } for(int i = (currentPart->start) + 1; i < (currentPart->end) - 1; i++) { int j = i + 1; if(!isalnum(data[i]) && isalnum(data[j])) { wordCount++; } } pthread_mutex_unlock(&mutex); return 0; }
0
#include <pthread.h> void *producer(void *param); void *consumer(void *param); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; sem_t buf_full; sem_t buf_empty; sem_t complete; int times; int con_count; int num_consumed = 0; int buffer[1]; void *produce (void *param) { unsigned int seed = 55555; int i = 0; while (i < times) { sem_wait(&buf_empty); int num = rand_r(&seed) % 101; buffer[0] = num; printf("Producer: produced %d!\\n", num); int q; for (q = 0; q < con_count; q++) { sem_post(&buf_full); } i++; } return 0; } void *consume (void *param) { long thread_num = (long) param; int val; int i = 0; while (i < times) { sem_wait(&buf_full); pthread_mutex_lock(&mutex); val = buffer[0]; num_consumed++; if (num_consumed == con_count) { printf("Consumer: I am thread %ld, and I have just read in the value: %d.\\n---\\n", thread_num, val); int k; for (k = 1; k < num_consumed; k++) { sem_post(&complete); } sem_post(&buf_empty); num_consumed = 0; pthread_mutex_unlock(&mutex); } else { printf("Consumer: I am thread %ld, and I have just read in the value: %d.\\n", thread_num, val); pthread_mutex_unlock(&mutex); sem_wait(&complete); } i++; } return 0; } int main (int argc, char **argv) { if (argc == 3) { times = atoi(argv[1]); con_count = atoi(argv[2]); } else { times = 4; con_count = 4; } buffer[0] = 0; sem_init(&buf_empty, 0, 1); sem_init(&buf_full, 0, 0); sem_init(&complete, 0, 0); long i; pthread_t producer_thread; pthread_t consumer_threads[con_count]; printf("%d consumer threads, producing %d times.\\n", con_count, times); for (i = 0; i < con_count; i++) { (void) pthread_create(&consumer_threads[i], 0, consume, (void*) i); } (void) pthread_create(&producer_thread, 0, produce, 0); (void) pthread_join(producer_thread, 0); for (i = 0; i < con_count; i++) { (void) pthread_join(consumer_threads[i], 0); } sem_destroy(&buf_empty); sem_destroy(&buf_full); sem_destroy(&complete); printf("all done!\\n"); return 0; }
1
#include <pthread.h> int prod_pos; int cons_pos; sem_t full; sem_t empty; pthread_mutex_t mutex; int buff_filled; char **buffer; } prod_cons_t; void *insere_buffer(prod_cons_t *prod_cons) { do { char *buffer = (char *)malloc(1024*sizeof(char)); scanf (" %[^\\n]", buffer); printf("Inserindo\\n"); sem_wait(&prod_cons->empty); pthread_mutex_lock(&prod_cons->mutex); prod_cons->buffer[prod_cons->prod_pos] = buffer; prod_cons->prod_pos = (prod_cons->prod_pos + 1) % 32; prod_cons->buff_filled++; pthread_mutex_unlock(&prod_cons->mutex); sem_post(&prod_cons->full); } while(1); pthread_exit((void*)0); } void *retira_buffer(prod_cons_t *prod_cons) { char *buff; do { sem_wait(&prod_cons->full); pthread_mutex_lock(&prod_cons->mutex); buff = prod_cons->buffer[prod_cons->cons_pos]; printf("Rettirou = %s\\n", buff); prod_cons->buffer[prod_cons->cons_pos] = 0; prod_cons->cons_pos = (prod_cons->cons_pos + 1) % 32; prod_cons->buff_filled--; pthread_mutex_unlock(&prod_cons->mutex); sem_post(&prod_cons->empty); } while(1); pthread_exit((void*)1); } prod_cons_t *cria_prod_cons(void) { prod_cons_t *prod_cons = (prod_cons_t *) malloc(sizeof(prod_cons_t)); prod_cons->prod_pos = 0; prod_cons->cons_pos = 0; sem_init(&(prod_cons->full), 0, 0); sem_init(&(prod_cons->empty), 0, 32); pthread_mutex_init(&(prod_cons->mutex), 0); prod_cons->buff_filled = 0; prod_cons->buffer = (char **)malloc(32*sizeof(char*)); return prod_cons; } int main() { int *res; prod_cons_t *prod_cons = cria_prod_cons(); pthread_t prod, cons; pthread_create(&prod, 0, (void *)&insere_buffer, (void*)prod_cons); pthread_create(&cons, 0, (void*)&retira_buffer, (void*)prod_cons); pthread_join(prod, (void*)&res); pthread_join(cons, (void*)&res); return 0; }
0
#include <pthread.h> int MYTHREADS = 2; double sumArray[8]; int count = 0; int n = 1048576; int nArray[1048576]; struct params { pthread_mutex_t mutex; pthread_cond_t done; int id; }; void* threadWork(void* arg) { int id; pthread_mutex_lock(&(*(params_t*)(arg)).mutex); id = (*(params_t*)(arg)).id; while (count < n ) { count = count + 1; nArray[count] = count; } pthread_mutex_unlock(&(*(params_t*)(arg)).mutex); pthread_cond_signal (&(*(params_t*)(arg)).done); int j; for ( j = 0; j < MYTHREADS; j++) { if (id == j) { int locMin = floor((double)n * (((double)id) / (double)MYTHREADS)); int locMax = floor((double)n * (((double)id + 1) / (double)MYTHREADS)); while (locMin < locMax) { locMin++; sumArray[id] = sumArray[id] + nArray[locMin]; } } } } int main() { struct timespec start, finish; clock_gettime(CLOCK_MONOTONIC, &start); double finalSum; pthread_t threads[MYTHREADS]; params_t params; pthread_mutex_init (&params.mutex , 0); pthread_cond_init (&params.done, 0); pthread_mutex_lock (&params.mutex); int i; for (i = 0; i < MYTHREADS; i++) { params.id = i; pthread_create(&threads[i], 0, threadWork, &params); pthread_cond_wait (&params.done, &params.mutex); } for (i = 0; i < MYTHREADS; i++) { pthread_join(threads[i], 0); } pthread_mutex_destroy (&params.mutex); pthread_cond_destroy (&params.done); for (i = 0; i < MYTHREADS ; i++) { finalSum = sumArray[i] + finalSum; } printf("\\n\\n%d array sum: %lf\\n", count, finalSum); clock_gettime(CLOCK_MONOTONIC, &finish); elapsed = (finish.tv_sec - start.tv_sec); elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0; printf(" %f", elapsed); return 0; }
1
#include <pthread.h> pthread_attr_t attr; pthread_t threads[25]; pthread_mutex_t threads_lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t wait_lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t rand_lock = PTHREAD_MUTEX_INITIALIZER; sem_t death_lock; pthread_mutex_t count_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t wait_cv = PTHREAD_COND_INITIALIZER; int answer; void delay(int a, int b) { sleep(b); } void count_tries(int i) { static int count = 0; static int old_count = 0; static int max_count = 0; static pthread_mutex_t count_lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&count_lock); count += i; if (i == -1) { printf("Total attempt count: %d\\n", max_count); } pthread_mutex_unlock(&count_lock); } void cleanup_count(void *arg) { int *ip = (int *)arg; int i = *ip; pthread_t tid = pthread_self(); count_tries(i); printf("thread $%d: exited (or cancelled) on it's %d try.\\n", (int)tid, i); } void cleanup_lock(void *arg) { pthread_t tid = pthread_self(); free(arg); pthread_mutex_unlock(&rand_lock); } void *search(void *arg) { char *p; unsigned int seed; int i = 0, j, err, guess, target = (int)arg; pthread_t tid = pthread_self(); seed = (unsigned int) tid; pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, 0); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0); pthread_cleanup_push(cleanup_count, (void *)&i); while (1) { ++i; pthread_mutex_lock(&rand_lock); p = (char *) malloc(10); pthread_cleanup_push(cleanup_lock, (void *)p); guess = rand_r(&seed); delay(0, 10); pthread_testcancel(); pthread_cleanup_pop(0); free(p); pthread_mutex_unlock(&rand_lock); delay(0, 10); } pthread_cleanup_pop(0); return 0; } int main(int argc, char *argv[]) { return 0; }
0
#include <pthread.h> pthread_cond_t cv_suspend; pthread_mutex_t mx_suspend; pthread_t thr_sleepy; void* thread_sleepy(void*); int main() { pthread_condattr_t attr_cv_suspend; pthread_condattr_init(&attr_cv_suspend); pthread_condattr_setpshared(&attr_cv_suspend, PTHREAD_PROCESS_SHARED); pthread_cond_init(&cv_suspend, &attr_cv_suspend); pthread_mutexattr_t attr_mx_suspend; pthread_mutexattr_init(&attr_mx_suspend); pthread_mutexattr_setpshared(&attr_mx_suspend, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&mx_suspend, &attr_mx_suspend); if(0 != pthread_create(&thr_sleepy, 0, thread_sleepy, 0)){ perror("MAIN: pthread_create failed"); exit(1); } puts("MAIN: thread created!"); sleep(1); puts("MAIN: now resuming the suspended thread, again"); pthread_cond_signal(&cv_suspend); sleep(1); puts("MAIN: cleaning up conditional variable stuff"); pthread_cond_destroy(&cv_suspend); pthread_mutex_destroy(&mx_suspend); pthread_mutexattr_destroy(&attr_mx_suspend); pthread_condattr_destroy(&attr_cv_suspend); puts("READY."); exit(0); } void* thread_sleepy(void* arg) { puts("THREAD: this is the dummy thread"); puts("THREAD: suspends..."); pthread_mutex_lock(&mx_suspend); pthread_cond_wait(&cv_suspend, &mx_suspend); pthread_mutex_unlock(&mx_suspend); puts("THREAD: ...awakes"); puts("THREAD: exits"); pthread_exit(0); }
1
#include <pthread.h> struct servent_data _servent_data; void setservent(int f) { pthread_mutex_lock(&_servent_mutex); setservent_r(f, &_servent_data); pthread_mutex_unlock(&_servent_mutex); } void endservent(void) { pthread_mutex_lock(&_servent_mutex); endservent_r(&_servent_data); pthread_mutex_unlock(&_servent_mutex); } struct servent * getservent(void) { struct servent *s; pthread_mutex_lock(&_servent_mutex); s = getservent_r(&_servent_data.serv, &_servent_data); pthread_mutex_unlock(&_servent_mutex); return (s); }
0
#include <pthread.h> char pass[4 +1]; char *senha_passada_arg; char *senha_compartilhada[50]; int buffer[50]; int inicio = 0, final = 0, cont = 0; pthread_mutex_t bloqueio; pthread_cond_t nao_vazio, nao_cheio; void calcula_hash_senha(const char *senha, char *hash); void incrementa_senha(char *senha); void testa_senha(const char *hash_alvo, const char *senha); void* consumidor(void *v); void* produtor(void *v); int main(int argc, char *argv[]) { int i; if (argc != 2) { printf("Uso: %s <hash>", argv[0]); return 1; } for (i = 0; i < 50; i++) { senha_compartilhada[i] = 0; } senha_passada_arg = argv[1]; for (i = 0; i < 4; i++) { pass[i] = 'a'; } pass[4] = '\\0'; pthread_t thr_produtor; pthread_t thr_consumidor1,thr_consumidor2,thr_consumidor3,thr_consumidor4; pthread_mutex_init(&bloqueio, 0); pthread_cond_init(&nao_cheio, 0); pthread_cond_init(&nao_vazio, 0); for (i = 0; i < 50; i++) buffer[i] = 0; pthread_create(&thr_produtor, 0, produtor, 0); pthread_create(&thr_consumidor1, 0, consumidor, 0); pthread_create(&thr_consumidor2, 0, consumidor, 0); pthread_create(&thr_consumidor3, 0, consumidor, 0); pthread_create(&thr_consumidor4, 0, consumidor, 0); pthread_join(thr_produtor, 0); pthread_join(thr_consumidor1, 0); pthread_join(thr_consumidor2, 0); pthread_join(thr_consumidor3, 0); pthread_join(thr_consumidor4, 0); return 0; } void testa_senha(const char *hash_alvo, const char *senha) { char hash_calculado[256 + 1]; calcula_hash_senha(senha, hash_calculado); if (!strcmp(hash_alvo, hash_calculado)) { printf("Achou! %s\\n", senha); exit(0); } } void incrementa_senha(char *senha) { int i; i = 4 - 1; while (i >= 0) { if (senha[i] != 'z') { senha[i]++; i = -2; } else { senha[i] = 'a'; i--; } } if (i == -1) { printf("Não achou!\\n"); exit(1); } } void calcula_hash_senha(const char *senha, char *hash) { struct crypt_data data; data.initialized = 0; strcpy(hash, crypt_r(senha, "aa", &data)); } void* produtor(void *v) { int aux; while(1) { pthread_mutex_lock(&bloqueio); while (cont == 50) { pthread_cond_wait(&nao_cheio, &bloqueio); } senha_compartilhada[final] = pass; buffer[final] = final; incrementa_senha(pass); final = (final + 1) % 50; aux = cont; cont = aux + 1; pthread_cond_signal(&nao_vazio); pthread_mutex_unlock(&bloqueio); } printf("Produção encerrada.\\n"); return 0; } void* consumidor(void *v) { int aux; char senha[4 +1]; while(1) { pthread_mutex_lock(&bloqueio); while (cont == 0) { pthread_cond_wait(&nao_vazio, &bloqueio); } strcpy(senha, senha_compartilhada[inicio]); inicio = (inicio + 1) % 50; aux = buffer[inicio]; aux = cont; cont = aux - 1; pthread_cond_signal(&nao_cheio); pthread_mutex_unlock(&bloqueio); testa_senha(senha_passada_arg, senha); } printf("Consumo encerrado.\\n"); return 0; }
1
#include <pthread.h>extern void __VERIFIER_error() ; void __VERIFIER_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error();}; return; } char *v; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; void *thread1(void * arg) { v = malloc(sizeof(char)); return 0; } void *thread2(void *arg) { pthread_mutex_lock (&m); v[0] = 'X'; pthread_mutex_unlock (&m); return 0; } void *thread3(void *arg) { pthread_mutex_lock (&m); v[0] = 'Y'; pthread_mutex_unlock (&m); return 0; } void *thread0(void *arg) { pthread_t t1, t2, t3, t4, t5; pthread_create(&t1, 0, thread1, 0); pthread_join(t1, 0); pthread_create(&t2, 0, thread2, 0); pthread_create(&t3, 0, thread3, 0); pthread_create(&t4, 0, thread2, 0); pthread_create(&t5, 0, thread2, 0); pthread_join(t2, 0); pthread_join(t3, 0); pthread_join(t4, 0); pthread_join(t5, 0); return 0; } int main(void) { pthread_t t; pthread_create(&t, 0, thread0, 0); pthread_join(t, 0); __VERIFIER_assert(v[0] == 'X'); return 0; }
0
#include <pthread.h> const int MAX_THREADS = 1024; void* Thread_sum(void* rank); void Get_args(int argc, char* argv[]); void Usage(char* prog_name); double Serial_pi(long long n); long thread_count; long long n; double sum, sum_serial; pthread_mutex_t mutex; int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; double start, finish, elapsed; Get_args(argc, argv); thread_handles = malloc(thread_count * sizeof(pthread_t) ); pthread_mutex_init(&mutex, 0); sum = 0.0; GET_TIME(start); for(thread = 0; thread < thread_count; thread++) { pthread_create(&thread_handles[thread], 0, Thread_sum, (void*) thread); } for(thread = 0; thread < thread_count; thread++) { pthread_join(thread_handles[thread], 0); } GET_TIME(finish); sum = sum * 4; printf("\\nPthread pi estimation: %.12lf\\n", sum); elapsed = finish - start; printf("The code to be timed took %e seconds\\n", elapsed); GET_TIME(start); sum_serial = Serial_pi(n); GET_TIME(finish); printf("\\nSerial pi estimation: %.12lf\\n", sum_serial); elapsed = finish - start; printf("The code to be timed took %e seconds\\n\\n", elapsed); pthread_mutex_destroy(&mutex); free(thread_handles); return 0; } void* Thread_sum(void* rank) { long my_rank = (long) rank; long long i; double factor = 1.0; long long my_n = n / thread_count; long long my_first_i = my_n * my_rank; long long my_last_i = my_first_i + my_n; if(my_first_i % 2 == 0) { factor = 1.0; } else { factor = -1.0; } for (i = my_first_i; i < my_last_i; i++, factor = -factor) { pthread_mutex_lock(&mutex); sum += factor / (2 * i + 1); pthread_mutex_unlock(&mutex); } return 0; } double Serial_pi(long long n) { double sum = 0.0; long long i; double factor = 1.0; for (i = 0; i < n; i++, factor = -factor) { sum += factor / (2 * i + 1); } return 4.0 * sum; } void Get_args(int argc, char* argv[]) { if (argc != 3) { Usage(argv[0]); } thread_count = strtol(argv[1], 0, 10); if (thread_count <= 0 || thread_count > MAX_THREADS) { Usage(argv[0]); } n = strtoll(argv[2], 0, 10); if (n <= 0) { Usage(argv[0]); } } void Usage(char* prog_name) { fprintf(stderr, "usage: %s <number of threads> <n>\\n", prog_name); fprintf(stderr, " n is the number of terms and should be >= 1\\n"); fprintf(stderr, " n should be evenly divisible by the number of threads\\n"); exit(0); }
1
#include <pthread.h> extern int makethread(void *(*)(void *), void *); struct to_info { void (*to_fn)(void *); void *to_arg; struct timespec to_wait; }; void * timeout_helper(void *arg) { struct to_info *tip; tip = (struct to_info *)arg; nanosleep(&tip->to_wait, 0); (*tip->to_fn)(tip->to_arg); return(0); } void timeout(const struct timespec *when, void (*func)(void *), void *arg) { struct timespec now; struct timeval tv; struct to_info *tip; int err; gettimeofday(&tv, 0); now.tv_sec = tv.tv_sec; now.tv_nsec = tv.tv_usec * 1000; if ((when->tv_sec > now.tv_sec) || (when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) { tip = malloc(sizeof(struct to_info)); if (tip != null) { tip->to_fn = func; tip->to_arg = arg; tip->to_wait.tv_sec = when->tv_sec - now.tv_sec; if (when->tv_nsec >= now.tv_nsec) { tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec; } else { tip->to_wait.tv_sec--; tip->to_wait.tv_nsec = 1000000000 - not.tv_nsec + when->tv_nsec; } err = makethread(timeout_helper, (void *)tip); if (err == 0) return; } } (*func)(arg); } pthread_mutexattr_t attr; pthread_mutex_t mutex; void retry(void *arg) { pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); }
0
#include <pthread.h> struct thread_data { int thread_id; int my_turn_num[100]; }; pthread_t threads[2 - 1]; struct thread_data thread_data_array[2]; int cur_t = 0; pthread_cond_t condition[2 - 1]; pthread_mutex_t mutex[2 - 1]; pthread_attr_t attr; int ready[2 -1]; void *Get_times(void *threadarg) { int taskid, i, child, rc; struct thread_data *my_data; my_data = (struct thread_data *) threadarg; taskid = my_data->thread_id; printf ("Thread %d starting\\n", taskid); rc = BIND (1); if (rc) { printf( "Client error from BIND is %d, errno is %d\\n", rc, errno ); perror( "client" ); } printf ("Thread %d running on CPU %d\\n", taskid, GETCPU()); if ((child = taskid - 1) >= 0) { pthread_mutex_init( &mutex[child], 0 ); pthread_cond_init( &condition[child], 0 ); pthread_mutex_lock( &mutex[child] ); ready[child] = 0; thread_data_array[child].thread_id = child; printf("Creating thread %d\\n", child); rc = pthread_create(&threads[child], &attr, Get_times, (void *) &thread_data_array[child]); if (rc) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } while( !ready[child] ) { pthread_cond_wait( &condition[child], &mutex[child] ); } } if (taskid < 2 - 1) { pthread_mutex_lock( &mutex[taskid] ); pthread_cond_signal( &condition[taskid] ); ready[taskid] = 1; pthread_mutex_unlock( &mutex[taskid] ); } for (i = 0; i < 100; i++) { sched_yield(); my_data->my_turn_num[i] = cur_t++; } printf ("Thread %d running on CPU %d\\n", taskid, GETCPU()); if (taskid == 0) pthread_exit(0); pthread_mutex_unlock( &mutex[child] ); pthread_mutex_destroy( &mutex[child] ); pthread_cond_destroy( &condition[child] ); if (taskid == 2 - 1) return 0; pthread_exit(0); return (0); } int main() { int t, i; int this_turn, last_turn; int turn_error = 0; struct thread_data *cur_data; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); thread_data_array[2 - 1].thread_id = 2 - 1; printf("Starting thread %d\\n", 2 - 1); Get_times ((void *) &thread_data_array[2 - 1]); while (cur_t < 2 * 100) ; pthread_attr_destroy(&attr); printf("Checking results\\n"); for (t = 0; t < 2; t++) { cur_data = &thread_data_array[t]; last_turn = cur_data->my_turn_num[0]; if (last_turn != t) { printf ("START UP ERROR: thread %d; first turn: %d\\n", t, last_turn); } for (i = 1; i < 100; i++) { this_turn = cur_data->my_turn_num[i]; if (this_turn != last_turn + 2) { printf ("TURN ERROR: thread: %d; time: %d; turn: %d; last turn: %d\\n", t, i, this_turn, last_turn); turn_error = 1; } last_turn = this_turn; } } if (!turn_error) { printf ("Processor yielded as expected\\n"); } return turn_error; }
1
#include <pthread.h> static char s_msgbuf[256]; pthread_mutex_t s_msgbufMutex = PTHREAD_MUTEX_INITIALIZER; void print_msg(enum LoggerLevel level, const char* prefix, const void* buf, int len) { if (LogIsEnabled(level)) { char* p = s_msgbuf; int bufLeft = sizeof(s_msgbuf) - 1; int printLen = (len <= 32) ? len : 32; pthread_mutex_lock(&s_msgbufMutex); int i; for(i=0; i<printLen && bufLeft > 0; i++) { int n = snprintf(p, bufLeft, " %02x", ((const uint8_t *)buf)[i]); if(n > 0) { p += n; bufLeft -= n; } else { break; } } logger_log(level, "msg_utils.c", 41, "%s: %s%s", prefix, s_msgbuf, (printLen < len ? "..." : "") ); pthread_mutex_unlock(&s_msgbufMutex); } } uint64_t get_currenttime_in_ms() { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (((uint64_t)ts.tv_sec) * 1000 + ts.tv_nsec / 1000000); } bool is_timeout(uint64_t last_time_in_ms, uint64_t now_time_in_ms, uint64_t timeout_val_in_ms) { uint64_t end_time = last_time_in_ms + timeout_val_in_ms; if(end_time >= last_time_in_ms) { return end_time <= now_time_in_ms; } else { return now_time_in_ms < last_time_in_ms && end_time <= now_time_in_ms; } } void sleep_in_ms(long ms) { struct timespec ts; ts.tv_sec = ms/1000; ts.tv_nsec = (ms%1000) * 1000 * 1000; while (nanosleep (&ts, &ts) == -1); }
0
#include <pthread.h> int element[(20)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int __VERIFIER_nondet_int(void); int stored_elements[(20)]; _Bool enqueue_flag, dequeue_flag; QType queue; int init(QType *q) { q->head=0; q->tail=0; q->amount=0; } int empty(QType * q) { if (q->head == q->tail) { printf("queue is empty\\n"); return (-1); } else return 0; } int full(QType * q) { if (q->amount == (20)) { printf("queue is full\\n"); return (-2); } else return 0; } int enqueue(QType *q, int x) { q->element[q->tail] = x; q->amount++; if (q->tail == (20)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (20)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); if (enqueue_flag) { for(i=0; i<(20); i++) { value = __VERIFIER_nondet_int(); enqueue(&queue,value); stored_elements[i]=value; } enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); return 0; } void *t2(void *arg) { int i; pthread_mutex_lock(&m); if (dequeue_flag) { for(i=0; i<(20); i++) { if (empty(&queue)!=(-1)) if (!(dequeue(&queue)==stored_elements[i])) { ERROR: goto ERROR; } } dequeue_flag=(0); enqueue_flag=(1); } pthread_mutex_unlock(&m); return 0; } int main(void) { pthread_t id1, id2; enqueue_flag=(1); dequeue_flag=(0); init(&queue); if (!(empty(&queue)==(-1))) { ERROR: goto ERROR; } pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, &queue); pthread_create(&id2, 0, t2, &queue); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#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() { 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, &thread_func, &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; }
0
#include <pthread.h> int done; pthread_cond_t *multiple; pthread_mutex_t *print_lock; int print; int simulations; int inside_circ; pthread_mutex_t *inside_circ_lock; int total_sims_done; pthread_mutex_t *total_sims_done_lock; pthread_mutex_t *rand_lock; void *print_pi(void *arg) { while(!done) { pthread_mutex_lock (print_lock); while(!print) { pthread_cond_wait (multiple, print_lock); } pthread_mutex_lock (total_sims_done_lock); double pi = 4 * ((double)inside_circ / total_sims_done); printf ("Pi = %f after %i simulations with %i hits\\n", pi, total_sims_done, inside_circ); print = 0; pthread_mutex_unlock (total_sims_done_lock); pthread_mutex_unlock (print_lock); } pthread_exit(0); } void *simulator (void * arg) { while(!done) { double x = ((double) rand() / (double) 32767); double y = ((double) rand() / (double) 32767); double magnitude = sqrt(pow (x - 0.5, 2) + pow (y - 0.5, 2)); pthread_mutex_lock (total_sims_done_lock); if (magnitude <= 0.5) { pthread_mutex_lock (inside_circ_lock); inside_circ++; pthread_mutex_unlock (inside_circ_lock); } total_sims_done++; if (total_sims_done % 1000000 == 0) { pthread_mutex_lock(print_lock); print = 1; pthread_cond_broadcast(multiple); pthread_mutex_unlock(print_lock); } if (total_sims_done == simulations) { done = 1; print = 1; pthread_cond_broadcast(multiple); } pthread_mutex_unlock (total_sims_done_lock); } pthread_exit(0); } int main(int argc, char *argv[]) { int n_threads; sscanf (argv[1], "%d", &n_threads); sscanf (argv[2], "%i", &simulations); done = 0; inside_circ = 0; total_sims_done = 0; print = 0; multiple = (pthread_cond_t *) malloc (sizeof (pthread_cond_t)); pthread_cond_init (multiple, 0); print_lock = (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t)); pthread_mutex_init (print_lock, 0); inside_circ_lock = (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t)); pthread_mutex_init (inside_circ_lock, 0); total_sims_done_lock = (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t)); pthread_mutex_init (total_sims_done_lock, 0); rand_lock = (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t)); pthread_mutex_init (rand_lock, 0); srand((567342)); pthread_t *print_thread = (pthread_t *) malloc (sizeof(pthread_t *)); if(pthread_create (print_thread, 0, print_pi, 0)) { fprintf(stderr, "Error creating print thread"); exit(-1); } pthread_t **tid = (pthread_t **) malloc (sizeof(pthread_t *) * n_threads); int i; for(i = 0; i < n_threads; i++) { tid[i] = (pthread_t *) malloc(sizeof(pthread_t *)); if(pthread_create (tid[i], 0, simulator, 0)) { fprintf(stderr, "Error creating thread %d.\\n", i); exit(-1); } } if(pthread_join(*print_thread, 0)) { fprintf(stderr, "Error joining with print thread"); exit(-1); } for(i = 0; i < n_threads; i ++) { if(pthread_join(*tid[i], 0)) { fprintf(stderr, "Error joining with thread %d.", i); exit(-1); } } free (print_thread); for (i = 0; i < n_threads; i++) { free (tid[i]); } free (tid); exit (0); }
1
#include <pthread.h> struct node { long tid; int primenumber; struct node *next; }*head,*var; int number=0; char filename[20]; int isLooked[100000000]; FILE *file; void createList(long td,int n){ struct node *temp; temp=head; var=(struct node *)malloc(sizeof (struct node)); var->tid=td; var->primenumber=n; if(head==0){ head=var; head->next=0; } else{ while(temp->next!=0){ temp=temp->next; } var->next=0; temp->next=var; } } void display(){ var=head; file = fopen(filename,"w"); if(var==0){ printf("List is Empty\\n"); } else{ while(var!=0){ printf("Thread %ld\\tPrime number:%d",var->tid,var->primenumber); fprintf(file,"Thread %ld\\tPrime number:%d\\n",var->tid,var->primenumber); var=var->next; printf("\\n"); } printf("\\n"); } fclose(file); } pthread_mutex_t lockx; void *primeNumbers(void *t){ int i,j; pthread_mutex_lock(&lockx); for(i=2;i<number;i++){ if(isLooked[i]==0){ createList((long)t,i); for(j=i;i*j<number;j++){ if(isLooked[i*j]==0){ isLooked[i*j]=1; } } isLooked[i]=1; usleep(1); } pthread_mutex_unlock(&lockx); } pthread_exit(0); } int main( int argc, char *argv[]){ if( argc == 5 && strstr(argv[1],"-n") && strstr(argv[3],"-o") ){ strcpy(filename,argv[4]); number=atoi(argv[2]); int numbthread=2; pthread_t threads2[numbthread]; int rc; long t; void *status; int x; for(x=0;x<number;x++){ isLooked[x]=0; } for(t=0;t<numbthread;t++){ if ((rc = pthread_create(&threads2[t], 0, primeNumbers, (void *)t))) { fprintf(stderr, "error: pthread_create, rc: %d\\n", rc); return 1; } } int i; for (i = 0; i < numbthread; ++i){ pthread_join(threads2[i], &status); } pthread_mutex_destroy(&lockx); } else if( argc == 7 && strstr(argv[1],"-n") && strstr(argv[3],"-t") && strstr(argv[5],"-o")) { number=atoi(argv[2]); int numbOfThreads=atoi(argv[4]); strcpy(filename,argv[6]); pthread_t threads[numbOfThreads]; int rc; long t; void *status; int x; for(x=0;x<number;x++){ isLooked[x]=0; } for(t=0;t<numbOfThreads;t++){ if ((rc = pthread_create(&threads[t], 0, primeNumbers, (void *)t))) { fprintf(stderr, "error: pthread_create, rc: %d\\n", rc); return 1; } } int i; for (i = 0; i < numbOfThreads; ++i){ pthread_join(threads[i], &status); } pthread_mutex_destroy(&lockx); } else { printf("Invalid arguments.\\n"); } display(); return 0; }
0
#include <pthread.h> pthread_cond_t is_zero; pthread_mutex_t mutex; int shared_data = 5; void *thread_function (void *arg) { pthread_mutex_lock(&mutex) ; while ( shared_data > 0) { --shared_data ; printf("Thread - Decreasing shared_data... Value:%d\\n",shared_data); sleep(1); } pthread_mutex_unlock(&mutex); printf("Thread, loop finished...\\n"); sleep(3); printf("Sending signal to main() thread....shared_data = 0 !!!\\n"); pthread_cond_signal (&is_zero); return 0; } int main (void) { pthread_t thread_ID1; void *exit_status; pthread_cond_init (&is_zero , 0) ; pthread_mutex_init (&mutex , 0) ; pthread_create (&thread_ID1 ,0, thread_function , 0) ; pthread_mutex_lock(&mutex ); printf("Main thread locking the mutex...\\n"); while ( shared_data != 0) { printf("I am the Main thread, shared_data is != 0. I am to sleep and unlock the mutex...\\n"); pthread_cond_wait (&is_zero, &mutex) ; } printf("Main awake - Value of shared_data: %d!!!\\n", shared_data); pthread_mutex_unlock(&mutex) ; pthread_join( thread_ID1 , 0) ; pthread_mutex_destroy(&mutex) ; pthread_cond_destroy (&is_zero) ; exit(0); }
1
#include <pthread.h> static pthread_key_t key; static pthread_once_t init_done = PTHREAD_ONCE_INIT; pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER; extern char **environ; static void thread_init(void) { pthread_key_create(&key, free); } char *getenv_r(const char *name) { int i, len; char *envbuf; pthread_once(&init_done, thread_init); pthread_mutex_lock(&env_mutex); envbuf = (char *)pthread_getspecific(key); if (envbuf == 0) { envbuf = malloc(4096); if (envbuf == 0) { pthread_mutex_unlock(&env_mutex); return 0; } pthread_setspecific(key, envbuf); } len = strlen(name); for (i = 0; environ[i] != 0; i++) { if ((strncmp(name, environ[i], len) == 0) && environ[i][len] == '=') { strncpy(envbuf, &environ[i][len+1], 4096 -1); pthread_mutex_unlock(&env_mutex); return envbuf; } } pthread_mutex_unlock(&env_mutex); return 0; } void *thd(void *arg) { printf("SHELL = %s\\n", getenv_r("SHELL")); printf("TERM_PROGRAM = %s\\n", getenv_r("TERM_PROGRAM")); printf("MANPATH = %s\\n", getenv_r("MANPATH")); printf("TERM = %s\\n", getenv_r("TERM")); printf("PWD = %s\\n", getenv_r("PWD")); pthread_exit((void *)0); } int main(void) { int err; pthread_t tid1, tid2; pthread_attr_t thd_attr; err = pthread_attr_init(&thd_attr); if (err != 0) return err; err = pthread_attr_setdetachstate(&thd_attr, PTHREAD_CREATE_DETACHED); if (err != 0) return err; err = pthread_create(&tid1, &thd_attr, thd, 0); if (err != 0) return err; err = pthread_create(&tid2, &thd_attr, thd, 0); if (err != 0) return err; pthread_attr_destroy(&thd_attr); pthread_key_delete(key); sleep(1); return 0; }
0
#include <pthread.h> struct Bloom* createBloom(int size_memory){ struct Bloom* bfilter = (struct Bloom*)malloc(sizeof(struct Bloom)); bfilter-> bit = (uint64_t*)malloc(sizeof(uint64_t)*size_memory); bfilter->mutexArr = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t)*size_memory); pthread_mutexattr_t Attr; pthread_mutexattr_init(&Attr); pthread_mutexattr_settype(&Attr, PTHREAD_MUTEX_RECURSIVE); int i; for(i=0;i<size_memory;i++) { bfilter-> bit[i] = 0; pthread_mutex_init(&(bfilter->mutexArr[i]), &Attr); } return bfilter; } void getLocks(int a[], struct Bloom* b){ int i,j,d; for(i =1; i<NUM_OF_HASH;i++){ d = a[i]/64; pthread_mutex_lock(&(b->mutexArr[d])); } } void releaseLocks(int a[], struct Bloom* b){ int i,j,d; for(i =0; i<NUM_OF_HASH;i++){ d = a[i]/64; pthread_mutex_unlock(&(b->mutexArr[d])); } } void insertHash(int a[], struct Bloom* b){ uint64_t i,m,d,k = 1; getLocks(a,b); for(i =0; i<NUM_OF_HASH;i++){ d = a[i]/64; m = a[i]%64; k = (1<<m); if((b->bit[d] & k) > 0) continue; else b->bit[d] = (b->bit[d] | k); } releaseLocks(a,b); } int findHash(int a[], struct Bloom* b){ uint64_t i,j =1, d,m, k =1; for(i =0; i<NUM_OF_HASH;i++){ d = a[i]/64; m = a[i]%64; k = 1<<m; if((b->bit[d]&k) > 0) continue; else j= 0; } return j; }
1
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i = 0; i < 10; ++i) { pthread_mutex_lock(&count_mutex); ++count; if (count == 12) { printf("inc_count(): thread %ld, count = %d Treshold reached. ", my_id, count); pthread_cond_signal(&count_threshold_cv); printf("Just send signal.\\n"); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while (count < 12) { printf("watch_count(): thread %ld Count= %d. Going into wait...\\n", my_id, count); pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received. Count= %d\\n", my_id, count); } printf("watch_count(): thread %ld Updating the value of count...\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); printf("watch_count(): thread %ld Unlocking mutex.\\n", my_id); pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int i; long threads_ids[3] = {1, 2, 3}; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init(&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)threads_ids[0]); pthread_create(&threads[1], &attr, inc_count, (void *)threads_ids[1]); pthread_create(&threads[2], &attr, inc_count, (void *)threads_ids[2]); for (i = 0; i < 3; ++i) { pthread_join(threads[i], 0); } printf("Main(): Waited and joined with %d threads. Final value of count = %d. Done.\\n", 3, count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
0
#include <pthread.h> int ncount; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* do_loop(void *data) { int i; for (i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); printf("loop1 : %d\\n", ncount); ncount ++; if(i == 10) return; pthread_mutex_unlock(&mutex); sleep(1); } } void* do_loop2(void *data) { int i; for (i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); printf("loop2 : %d\\n", ncount);ncount ++; pthread_mutex_unlock(&mutex); sleep(1); } } int main() { int thr_id; pthread_t p_thread[2]; int status; int a = 1; ncount = 0; thr_id = pthread_create(&p_thread[0], 0, do_loop, (void*)&a); sleep(1); thr_id = pthread_create(&p_thread[1], 0, do_loop2, (void*)&a); pthread_join(p_thread[0], (void *) &status); pthread_join(p_thread[1], (void *) &status); status = pthread_mutex_destroy(&mutex); printf("code = %d", status); printf("programing is end\\n"); return 0; }
1
#include <pthread.h> int file_idx; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; char **args; int N; void clean(int signal); void *convert_file(void *file_name); int main (int argc, char ** argv) { struct sigaction action; action.sa_handler = &clean; sigaction(SIGINT, &action, 0); N = argc - 1; args = argv + 1; pthread_t *tid; tid = (pthread_t *)malloc(sizeof(pthread_t) * N); int i; file_idx = 0; for (i = 0; i < 5; i++) { if (pthread_create(&(tid[i]), 0, convert_file, (void *) &i) != 0) { perror("pthread create"); kill(getpid(), SIGINT); } } for (i = 0; i < 5; i++) { if (pthread_join(tid[i], 0) != 0) { perror("pthread join"); kill(getpid(), SIGINT); } } printf("Finished\\n"); clean(SIGINT); return 0; } void *convert_file(void *idx) { if (*((int *)idx) >= N) { printf("Waste at %d\\n", *((int *)idx)); return 0; } while(1) { pthread_mutex_lock(&mutex); if (file_idx >= N) { pthread_mutex_unlock(&mutex); pthread_exit((void *) 0); } char *file = args[file_idx]; FILE *fp1, *fp2; char *src_fname; char *dest_fname; int c = 1; asprintf(&src_fname, "input/%s", file); printf("Open %s\\n", src_fname); fp1 = fopen (src_fname, "r"); asprintf(&dest_fname, "out/%s.UPPER.txt", file); printf("Write to %s\\n", dest_fname); fp2 = fopen (dest_fname, "w+"); if (fp1 == 0) { perror ( "fopen 1"); exit (1); } if (fp2 == 0) { perror("fopen 2"); } file_idx += 1; pthread_mutex_unlock(&mutex); while (c != EOF) { c = fgetc(fp1); if (c != EOF) fputc(toupper(c), fp2); } fclose (fp1); fclose (fp2); free(dest_fname); free(src_fname); } } void clean(int signal) { }
0
#include <pthread.h> struct Settings { int output_result; unsigned long long N; int M; }; struct Settings read_settings(int argc, char** argv) { struct Settings settings; if (argc < 3) { printf("wrong arguments count\\n"); exit(-1); } if (strcmp(argv[1], "-p") == 0) { settings.output_result = 1; settings.N = strtoll(argv[2], 0, 10); settings.M = strtoll(argv[3], 0, 10); } else { settings.output_result = 0; settings.N = strtoll(argv[1], 0, 10); settings.M = strtoll(argv[2], 0, 10); } return settings; } int m; char* primes; unsigned long long next_prime; unsigned long long n; unsigned long long sqrt_n; pthread_mutex_t next_prime_lock; void* thread_function(void* arg) { unsigned long long i; unsigned long long j; while (1) { pthread_mutex_lock(&next_prime_lock); while (!primes[next_prime] && next_prime <= sqrt_n) next_prime++; if (next_prime > sqrt_n) { pthread_mutex_unlock(&next_prime_lock); return 0; } i = next_prime; next_prime++; pthread_mutex_unlock(&next_prime_lock); if (primes[i]) { for (j = i * i; j < n; j += i) { primes[j] = 0; } } } } pthread_t* start_threads(int count) { int i; pthread_t* threads = (pthread_t*)malloc(count * sizeof(pthread_t)); for (i = 0; i < count; i++) { pthread_create(threads + i, 0, thread_function, 0); } return threads; } void join_threads(int count, pthread_t* threads) { int i; for (i = 0; i < count; i++) { pthread_join(threads[i], 0); } free(threads); } char* eratosthenes_sieve() { sqrt_n = (unsigned long long)sqrt((double)n); primes = (char*)malloc(n + 1); memset(primes, 0x01, n + 1); primes[0] = 0; primes[1] = 0; next_prime = 2; pthread_mutex_init(&next_prime_lock, 0); pthread_t* threads = start_threads(m); join_threads(m, threads); pthread_mutex_destroy(&next_prime_lock); return primes; } int main(int argc, char** argv) { unsigned long long i; struct Settings settings = read_settings(argc, argv); n = settings.N; m = settings.M; char* primes = eratosthenes_sieve(); if (settings.output_result) { for (i = 2; i < settings.N; i++) { if (primes[i]) { printf("%llu\\n", i); } } } free(primes); return 0; }
1
#include <pthread.h> pthread_mutex_t alarm_mutex; volatile int spawnflag; void uplink_alarm_handle(int sig) { pthread_mutex_lock(&alarm_mutex); spawnflag++; pthread_mutex_unlock(&alarm_mutex); } void uplink_alarm_init(unsigned long delta) { spawnflag = 0; pthread_mutex_init(&alarm_mutex, 0); signal(SIGALRM, uplink_alarm_handle); ualarm(delta, delta); } inline int uplink_wait_for_alarm(void) { while (spawnflag==0) { usleep(100); } pthread_mutex_lock(&alarm_mutex); spawnflag--; pthread_mutex_unlock(&alarm_mutex); return spawnflag; }
0