text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> struct check_farmer* create_check_farmer(FILE* p_file) { int root_directory_offset = 0, data_cluster_offset = 0, i; struct check_farmer* tmp = malloc(sizeof (struct check_farmer)); tmp->p_boot_record = malloc(sizeof (struct boot_record)); fread(tmp->p_boot_record, sizeof (struct boot_record), 1, p_file); tmp->fat_item = malloc(tmp->p_boot_record->cluster_count * sizeof (unsigned int)); tmp->file_lock = malloc(sizeof (pthread_mutex_t)); pthread_mutex_init(tmp->file_lock, 0); tmp->file_count_lock = malloc(sizeof (pthread_mutex_t)); pthread_mutex_init(tmp->file_count_lock, 0); tmp->result_lock = malloc(sizeof (pthread_mutex_t)); pthread_mutex_init(tmp->result_lock, 0); for (i = 0; i < tmp->p_boot_record->fat_copies; i++) { fread(tmp->fat_item, sizeof (unsigned int), tmp->p_boot_record->cluster_count, p_file); } root_directory_offset = ftell(p_file); data_cluster_offset = root_directory_offset + tmp->p_boot_record->root_directory_max_entries_count * sizeof (struct root_directory); tmp->file_system = p_file; tmp->root_directory_offset = root_directory_offset; tmp->data_cluster_offset = data_cluster_offset; tmp->cur_file = 0; return tmp; } int delete_check_farmer(struct check_farmer* p_ch_f) { free(p_ch_f->fat_item); free(p_ch_f->p_boot_record); pthread_mutex_destroy(p_ch_f->file_lock); free(p_ch_f->file_lock); pthread_mutex_destroy(p_ch_f->file_count_lock); free(p_ch_f->file_count_lock); pthread_mutex_destroy(p_ch_f->result_lock); free(p_ch_f->result_lock); fclose(p_ch_f->file_system); free(p_ch_f); return 1; } struct check_worker* create_check_worker(struct check_farmer* p_ch_f, int w_id) { struct check_worker* tmp = malloc(sizeof (struct check_worker)); tmp->p_root_directory = (struct root_directory *) malloc(sizeof (struct root_directory)); tmp->p_cluster = malloc(sizeof (char) * p_ch_f->p_boot_record->cluster_size); tmp->worker_id = w_id; tmp->ch_f = p_ch_f; tmp->file_seq_num = 0; return tmp; } int delete_check_worker(struct check_worker* p_ch_w) { free(p_ch_w->p_root_directory); free(p_ch_w->p_cluster); free(p_ch_w); return 1; } int check_farmer_load_next_file(struct check_farmer* ch_f, struct root_directory* rd) { pthread_mutex_lock(ch_f->file_count_lock); int cur_file = ch_f->cur_file; if (cur_file >= ch_f->p_boot_record->root_directory_max_entries_count) { pthread_mutex_unlock(ch_f->file_count_lock); return 0; } ch_f->cur_file = cur_file + 1; pthread_mutex_unlock(ch_f->file_count_lock); pthread_mutex_lock(ch_f->file_lock); int file_offset = ch_f->root_directory_offset + cur_file * sizeof (struct root_directory); fseek(ch_f->file_system, file_offset, 0); fread(rd, sizeof (struct root_directory), 1, ch_f->file_system); pthread_mutex_unlock(ch_f->file_lock); return 1; } int check_farmer_load_next_cluster(struct check_worker* p_ch_w, struct check_farmer* p_ch_f) { long cluster_offset; cluster_offset = p_ch_f->data_cluster_offset + p_ch_w->next_cluster * sizeof (char) * p_ch_f->p_boot_record->cluster_size; pthread_mutex_lock(p_ch_f->file_lock); fseek(p_ch_f->file_system, cluster_offset, 0); fread(p_ch_w->p_cluster, sizeof (char) * p_ch_f->p_boot_record->cluster_size, 1, p_ch_f->file_system); pthread_mutex_unlock(p_ch_f->file_lock); if (p_ch_w->next_cluster == 65533 || p_ch_w->next_cluster == 65534 || p_ch_w->next_cluster > p_ch_f->p_boot_record->cluster_count) { return 0; } return p_ch_w-> next_cluster = p_ch_f->fat_item[p_ch_w->next_cluster]; } void *check_worker_run(struct check_worker* p_ch_w) { unsigned int total_length, current_clusters, expected_clusters, loop_check = 65535; unsigned int res[3]; res[0] = res[1] = 0; while (check_farmer_load_next_file(p_ch_w->ch_f, p_ch_w->p_root_directory)) { p_ch_w->file_seq_num++; current_clusters = 0; expected_clusters = p_ch_w->p_root_directory->file_size / p_ch_w->ch_f->p_boot_record->cluster_size + 1; p_ch_w->next_cluster = p_ch_w->p_root_directory->first_cluster; check_farmer_load_next_cluster(p_ch_w, p_ch_w->ch_f); do { if(current_clusters > expected_clusters){ if(loop_check == 65535){ loop_check = p_ch_w->next_cluster; } else if (loop_check == p_ch_w->next_cluster){ fprintf(stderr, "File %s with starting cluster %04d leads to a loop!",p_ch_w->p_root_directory->file_name, p_ch_w->p_root_directory->first_cluster); break; } } if (p_ch_w->next_cluster != 65534) { current_clusters++; } else { total_length = current_clusters * p_ch_w->ch_f->p_boot_record->cluster_size + strlen(p_ch_w->p_cluster); break; } } while (check_farmer_load_next_cluster(p_ch_w, p_ch_w->ch_f)); if(p_ch_w->next_cluster == 65533){ fprintf(stderr, "File %s ended with a bad cluster and wasnt checked",p_ch_w->p_root_directory->file_name); res[2]++; continue; } if (total_length == p_ch_w->p_root_directory->file_size) { res[0]++; } else { res[1]++; } } pthread_mutex_lock(p_ch_w->ch_f->result_lock); p_ch_w->ch_f->results[0] += res[0]; p_ch_w->ch_f->results[1] += res[1]; p_ch_w->ch_f->results[2] += res[2]; pthread_mutex_unlock(p_ch_w->ch_f->result_lock); }
1
#include <pthread.h> static char board[3][3] = { {'1','2','3'}, {'4','5','6'}, {'7','8','9'} }; int troca = 0; static int nextPlayer = 0; static int numPlays = 0; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void currentBoard(char *buffer) { pthread_mutex_lock(&mutex); snprintf(buffer, MAX_BUFFER_LEN, "\\n\\n %c | %c | %c\\n---+---+---\\n %c | %c | %c\\n---+---+---\\n %c | %c | %c\\n ", board[0][0], board[0][1], board[0][2], board[1][0], board[1][1], board[1][2], board[2][0], board[2][1], board[2][2]); pthread_mutex_unlock(&mutex); } void trocaSimbolos2(){ int line, row; if(!troca) troca = 1; else troca = 0; for(line = 0; line <= 2; line ++){ for(row = 0; row <= 2; row++){ if(board[line][row] == 'X'){ board[line][row] = 'O'; }else{ if(board[line][row] == 'O'){ board[line][row] = 'X'; } } } } } int play(int row, int column, int player) { if (!(row >=0 && row <3 && column >= 0 && column < 3)) { return 1; } pthread_mutex_lock(&mutex); if (board[row][column] > '9') { pthread_mutex_unlock(&mutex); return 2; } if (player != nextPlayer) { pthread_mutex_unlock(&mutex); return 3; } if (numPlays == 9) { pthread_mutex_unlock(&mutex); return 4; } if(troca) board[row][column] = (player == 1) ? 'O' : 'X'; else board[row][column] = (player == 1) ? 'X' : 'O'; nextPlayer = (nextPlayer + 1) % 2; numPlays ++; pthread_mutex_unlock(&mutex); return 0; } int checkWinner() { int line; int result = -1; pthread_mutex_lock(&mutex); if((board[0][0] == board[1][1] && board[0][0] == board[2][2]) || (board[0][2] == board[1][1] && board[0][2] == board[2][0])) { if (board[1][1]=='X') result = 1; else result = 0; } else { for(line = 0; line <= 2; line ++) { if((board[line][0] == board[line][1] && board[line][0] == board[line][2])) { if (board[line][0]=='X') result = 1; else result = 0; break; } if ((board[0][line] == board[1][line] && board[0][line] == board[2][line])) { if (board[0][line]=='X') result = 1; else result = 0; break; } } } if (result == -1 && numPlays == 9) { result = 2; } pthread_mutex_unlock (&mutex); return result; }
0
#include <pthread.h> int a[1000]; int num_iter; struct Array{ long leftone; long rightone; }; void merge(int left, int right) { int mid=(left+right)/2; int L[mid-left+1]; int R[right-mid]; int i,j,k; num_iter++; for(i=0;i<(mid-left+1);i++) L[i]=a[i+left]; for(i=0;i<(right-mid);i++) R[i]=a[mid+1+i]; i=0;j=0;k=left; while (i<(mid-left+1) && j<(right-mid)) { if(L[i]<=R[j]) a[k++]=L[i++]; else a[k++]=R[j++]; } while (i<(mid-left+1)) a[k++]=L[i++]; while (j<(right-mid)) a[k++]=R[j++]; } void* mergesort(void *threadarg) { int left,right; int mid; int err; pthread_t thread[3]; pthread_mutex_t lock; struct Array thd0,thd1,thd2; struct Array *mainthd; mainthd=(struct Array *)threadarg; left = mainthd->leftone; right=mainthd->rightone; mid= (left+right)/2; if(pthread_mutex_init(&lock,0)){printf("Mutex init failed"); exit(0);} if(left<right){ num_iter++; pthread_mutex_lock(&lock); thd0.leftone=left; thd0.rightone=mid; err=pthread_create(&(thread[0]),0,mergesort,(void *)&thd0); if(err) {printf("Error initializing thread"); exit(0);} pthread_mutex_unlock(&lock); pthread_mutex_lock(&lock); thd1.leftone=mid+1; thd1.rightone=right; err=pthread_create(&(thread[1]),0,mergesort,(void *)&thd1); if(err) {printf("Error initializing thread"); exit(0);} pthread_mutex_unlock(&lock); pthread_join(thread[0],0); pthread_join(thread[1],0); merge(left,right); pthread_exit(0); } } void randgen() { long i; srand(time(0)); for(i=0;i<1000;i++) a[i]=rand()%(100000) +1 ; } void main() { long i; clock_t start,end; randgen(); struct Array mainone; mainone.leftone=0; mainone.rightone=1000; start=time(0); mergesort((void *) &mainone); end=time(0); num_iter++; printf("\\nNUmber_iter=%d\\n",num_iter); printf("random number for check=%d\\n",rand()); printf("Time reqd= %f\\n",difftime(end,start)); }
1
#include <pthread.h> extern pthread_mutex_t __sfp_mutex; extern pthread_cond_t __sfp_cond; extern int __sfp_state; FILE *fopen(const char *file, const char *mode) { register FILE *fp; register int f; int flags, oflags; if ((flags = __sflags(mode, &oflags)) == 0) return (0); if ((f = open(file, oflags, 0666)) < 0) { return (0); } pthread_once(&__sdidinit, __sinit); pthread_mutex_lock(&__sfp_mutex); while (__sfp_state) { pthread_cond_wait(&__sfp_cond, &__sfp_mutex); } if (fp = __sfp()) { fp->_file = f; fp->_flags = flags; if (oflags & O_APPEND) (void) __sseek((void *)fp, (fpos_t)0, 2); } pthread_mutex_unlock(&__sfp_mutex); return (fp); }
0
#include <pthread.h> FILE *flog; int semaforo; struct sembuf entro, salgo; int sock; struct sockaddr_in6 servaddr; struct ipv6_mreq ipv6mreq; pthread_t thread[10]; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; { int cada; int durante; char texto[100]; }MENSAJE; MENSAJE mensaje[20]; void leave(int); void *createThread(void*); int main(int arguments, char **argv) { int i=0,j=0; int port; char ifaz[4]; char multicast[10]; char buffer[100]; char *ptr; FILE *f; char texto[30] ="\\nFin de transmisión...\\n"; semaforo = semget(IPC_PRIVATE, 1, IPC_CREAT | 0600); if(semctl(semaforo, 0, SETVAL,1)==-1) { perror("Error SETVAL semaforo\\n"); exit(1); } entro.sem_num=0; entro.sem_op=1; entro.sem_flg=0; salgo.sem_num=0; salgo.sem_op=-1; salgo.sem_flg=0; signal(SIGINT,&leave); switch (fork()) { case -1: syslog(LOG_ERR, "Error Daemond\\n"); exit(1); break; case 0: break; default: return 0; } if (arguments==2) { port=7090; strcpy(ifaz,"eth0"); strcpy(multicast,"ff02::0084"); printf("\\n\\nSocket con argumentos por defecto\\n"); printf("\\n\\n\\nMulticas:%s\\nInterfaz: %s\\nPuerto:%d\\n",multicast,ifaz,port); } else if(arguments==5) { strcpy(multicast,argv[2]); strcpy(ifaz, argv[3]); port=atoi(argv[4]); printf("\\n\\n Argumentos del socket:\\n"); printf("\\n\\n\\nMulticas:%s\\nInterfaz: %s\\nPuerto:%d\\n",multicast,ifaz,port); }else printf("\\n\\n Argumentos: 'Fichero.txt' [Opcionales]: multicas, interfaz, puerto\\n\\n"); f=fopen(argv[1], "r"); flog=fopen("socketMulticas.log", "w"); if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) { syslog(LOG_ERR, "\\n\\nERROR EN LA CREACION DEL SOCKET\\n"); exit (-1); } bzero(&servaddr, sizeof(servaddr)); servaddr.sin6_family = AF_INET6; servaddr.sin6_port = htons(port); inet_pton(AF_INET6,multicast,&servaddr.sin6_addr); ipv6mreq.ipv6mr_interface=if_nametoindex(ifaz); if(setsockopt(sock,IPPROTO_IPV6,IPV6_MULTICAST_IF,&ipv6mreq,sizeof(ipv6mreq))<0) { syslog(LOG_ERR, "\\n\\ERROR SETSOCKOPT\\n\\n"); exit(1); } while (fgets(buffer, 100, f)) { ptr=buffer; ptr=strtok(buffer,separador); strcpy(mensaje[i].texto, ptr); ptr=strtok(0,separador); mensaje[i].cada=atoi(ptr); ptr=strtok(0,separador); mensaje[i].durante=atoi(ptr); if(pthread_create(&thread[i], 0, createThread, &mensaje[i])){ syslog(LOG_ERR, "ERROR AL CREAR THREAD\\n"); exit(1); } if (i>=20) { syslog(LOG_ERR,"Demasiadas lineas para leer(limite de threads 20)\\n\\n"); exit(1); } i++; } if (sendto(sock, texto, sizeof(texto), 0, (struct sockaddr*)&servaddr, sizeof(servaddr))<0) syslog(LOG_ERR, "Error sen socket\\n"); for (j=0; j<i; i++) { pthread_join(thread[j], 0); } fclose(f); close(sock); return 0; } void leave(int signal) { int t; char texto[30] ="\\nEl Socket se ha cerrado\\n"; if (sendto(sock, texto, sizeof(texto), 0, (struct sockaddr*)&servaddr, sizeof(servaddr))<0) syslog(LOG_ERR, "Error sen socket\\n"); for (t=0; t<10; t++) { pthread_cancel(thread[t]); } if (semctl(semaforo, 0, IPC_RMID)==-1) { syslog(LOG_ERR, "Error liberar semaforos\\n"); } close(sock); exit(0); } void *createThread(void *msg) { int i; time_t tEnvio, tRecp; MENSAJE *m = (MENSAJE *)msg; pthread_mutex_lock( &mutex1 ); tEnvio=time(0); do { if (sendto(sock, m->texto, sizeof(m->texto), 0, (struct sockaddr*)&servaddr, sizeof(servaddr))<0) syslog(LOG_ERR, "Error al mandar mensaje"); else syslog(LOG_INFO, "Mensaje: %s\\n",m->texto); sleep(m->cada); tRecp=time(0); } while ((tRecp-tEnvio)<m->durante); pthread_mutex_unlock( &mutex1 ); return 0; }
1
#include <pthread.h> int mediafirefs_symlink(const char *target, const char *linkpath) { printf("FUNCTION: symlink. target: %s, linkpath: %s\\n", target, linkpath); (void)target; (void)linkpath; struct mediafirefs_context_private *ctx; ctx = fuse_get_context()->private_data; pthread_mutex_lock(&(ctx->mutex)); fprintf(stderr, "symlink not implemented\\n"); pthread_mutex_unlock(&(ctx->mutex)); return -ENOSYS; }
0
#include <pthread.h> int pbs_rerunjob_err( int c, char *jobid, char *extend, int *local_errno) { int rc; struct batch_reply *reply; int sock; struct tcp_chan *chan = 0; if ((jobid == (char *)0) || (*jobid == '\\0')) return (PBSE_IVALREQ); pthread_mutex_lock(connection[c].ch_mutex); sock = connection[c].ch_socket; if ((chan = DIS_tcp_setup(sock)) == 0) { pthread_mutex_unlock(connection[c].ch_mutex); rc = PBSE_PROTOCOL; return rc; } else if ((rc = encode_DIS_ReqHdr(chan, PBS_BATCH_Rerun, pbs_current_user)) || (rc = encode_DIS_JobId(chan, jobid)) || (rc = encode_DIS_ReqExtend(chan, extend))) { connection[c].ch_errtxt = strdup(dis_emsg[rc]); pthread_mutex_unlock(connection[c].ch_mutex); DIS_tcp_cleanup(chan); return (PBSE_PROTOCOL); } if (DIS_tcp_wflush(chan)) { pthread_mutex_unlock(connection[c].ch_mutex); DIS_tcp_cleanup(chan); return (PBSE_PROTOCOL); } reply = PBSD_rdrpy(local_errno, c); PBSD_FreeReply(reply); rc = connection[c].ch_errno; pthread_mutex_unlock(connection[c].ch_mutex); DIS_tcp_cleanup(chan); return(rc); } int pbs_rerunjob( int c, char *jobid, char *extend) { pbs_errno = 0; return(pbs_rerunjob_err(c, jobid, extend, &pbs_errno)); }
1
#include <pthread.h> int buffer[5]; sem_t s_empty, s_full; pthread_mutex_t mutex; int count, flag, front, end; void sig_handler(int sig) { if(sig == SIGINT) { printf("\\nReceieved SIGINT\\n"); flag = 1; } } int insert_item(int buffer_item) { if(count < 5) { buffer[end] = buffer_item; count++; if(end == 5 -1) end = 0; else end++; return 0; } else { printf("Buffer full, cannot produce\\n"); return -1; } } int remove_item(int *buffer_item) { if(count > 0) { *buffer_item = buffer[front]; count--; if(front == 5 -1) front = 0; else front++; return 0; } else { printf("Buffer empty, cannot consume\\n"); return -1; } } void *producer(void *param) { int buffer_item; while(1) { signal(SIGINT, sig_handler); usleep(rand()%1000000+1); buffer_item = rand()%20+1; sem_wait(&s_empty); pthread_mutex_lock(&mutex); if(insert_item(buffer_item)) fprintf(stderr, "Error inserting item\\n"); else printf("Producer produced %d\\n", buffer_item); pthread_mutex_unlock(&mutex); sem_post(&s_full); if(flag) break; } } void *consumer(void *param) { int buffer_item; while(1) { signal(SIGINT, sig_handler); usleep(rand()%1000000+1); sem_wait(&s_full); pthread_mutex_lock(&mutex); if(remove_item(&buffer_item)) fprintf(stderr, "Error removing item\\n"); else printf("Consumer consumed %d\\n", buffer_item); pthread_mutex_unlock(&mutex); sem_post(&s_empty); if(flag) break; } } int main(int argc, char *argv[]) { if(argc != 4) { fprintf(stderr, "error: invalid number of arguments\\n"); exit(1); } if(atoi(argv[1]) < 0) { fprintf(stderr, "%d must be >= 0\\n", atoi(argv[1])); exit(1); } int sleept = atoi(argv[1]); int ptotal = atoi(argv[2]); int ctotal = atoi(argv[3]); sleep(sleept); printf("\\nFinished!\\n"); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; void* another( void* arg ) { printf( "in child thread, lock the mutex\\n" ); pthread_mutex_lock( &mutex ); sleep( 5 ); pthread_mutex_unlock( &mutex ); } void prepare() { pthread_mutex_lock( &mutex ); } void infork() { pthread_mutex_unlock( &mutex ); } int main() { pthread_mutex_init( &mutex, 0 ); pthread_t id; pthread_create( &id, 0, another, 0 ); sleep( 1 ); int pid = fork(); if( pid < 0 ) { pthread_join( id, 0 ); pthread_mutex_destroy( &mutex ); return 1; } else if( pid == 0 ) { printf( "I anm in the child, want to get the lock\\n" ); pthread_mutex_lock( &mutex ); printf( "I can not run to here, oop...\\n" ); pthread_mutex_unlock( &mutex ); exit( 0 ); } else { pthread_mutex_unlock( &mutex ); wait( 0 ); } pthread_join( id, 0 ); pthread_mutex_destroy( &mutex ); return 0; }
1
#include <pthread.h> void (*cxa_func)(void*); uint32_t type; uint32_t dso_type; uint32_t dso_scope; void* arg; void* dso; } cxxabi_atexit; uint32_t size; uint32_t nelem; cxxabi_atexit* list; } cxxabi_atexit_list; extern void* __dso_handle; static cxxabi_atexit_list _list; static pthread_mutex_t _mtx = PTHREAD_MUTEX_INITIALIZER; static uint32_t _registered = 0; static uint32_t _initialized = 0; static int __register_with_atexit(const cxxabi_atexit* cxa); static int __init_cxxabi_list(cxxabi_atexit** list); static int __resize_cxxabi_list(const cxxabi_atexit* oldlist, uint32_t nelem, cxxabi_atexit** newlist, uint32_t newsize); void __cxa_atexit_callback(void); static void __do_cleanup(void); int __init_cxxabi_list(cxxabi_atexit** list) { cxxabi_atexit* __p = (cxxabi_atexit *) malloc (64 * sizeof(cxxabi_atexit)); if (__p == 0) return -1; *list = __p; return 0; } int __resize_cxxabi_list(const cxxabi_atexit* oldlist, uint32_t nelem, cxxabi_atexit** newlist, uint32_t newsize) { register cxxabi_atexit* __p = (cxxabi_atexit *) malloc (newsize * sizeof(cxxabi_atexit)); if (__p == 0) return -1; const cxxabi_atexit* __l = oldlist; for (uint32_t i = 0; i < nelem; ++i) *(__p + i) = *(__l + i); *newlist = __p; return 0; } int __register_with_atexit(const cxxabi_atexit* cxa) { int ret = 0; if (cxa == 0) return -1; pthread_mutex_lock(&_mtx); if (_initialized == 0) { _list.nelem = 0; ret = __init_cxxabi_list(&_list.list); if (ret == -1) { pthread_mutex_unlock(&_mtx); return ret; } _list.size = 64; _initialized = 1; } if (_list.nelem == _list.size) { uint32_t newsize = _list.size * 2; cxxabi_atexit* __p; ret = __resize_cxxabi_list(_list.list, _list.nelem, &__p, newsize); if (ret == -1) { free (_list.list); _list.list = 0; _list.size = 0; _list.nelem = 0; pthread_mutex_unlock(&_mtx); return ret; } _list.list = __p; _list.size = newsize; } if (_registered == 0) { ret = atexit(__cxa_atexit_callback); _registered = (ret == 0); } if (_registered != 1) { free (_list.list); _list.list = 0; _list.size = 0; _list.nelem = 0; pthread_mutex_unlock(&_mtx); return ret; } register cxxabi_atexit* __p = _list.list + _list.nelem; *__p = *cxa; ++_list.nelem; pthread_mutex_unlock(&_mtx); return ret; } void __cxa_atexit_callback(void) { cxxabi_atexit* __e = _list.list + (_list.nelem - 1); cxxabi_atexit* __p = __e; if (__p == 0) return; for (int i = _list.nelem; i > 0; --i) { if ((__p->type == 0) && (__p->dso_scope == 4)) { __p->type = 1; __p->cxa_func(__p->arg); } --__p; } __p = __e; for (int i = _list.nelem; i > 0; --i) { if ((__p->type == 0) && (__p->dso_scope == 8)) { __p->type = 1; __p->cxa_func(__p->arg); } --__p; } } int __cxa_atexit(void (*destructor)(void*), void* arg, void* dso) { cxxabi_atexit cxa; cxa.type = 0; cxa.dso_type = 1; cxa.dso_scope = 8; cxa.cxa_func = destructor; cxa.arg = arg; cxa.dso = dso; return __register_with_atexit(&cxa); } int __cxa_finalize(void* dso) { uint32_t i; pthread_mutex_lock(&_mtx); if (_initialized == 0) { pthread_mutex_unlock(&_mtx); return -1; } cxxabi_atexit* __p = _list.list; pthread_mutex_unlock(&_mtx); if (__p == 0) return -1; if (dso == 0) { __p = _list.list + (_list.nelem - 1); pthread_mutex_lock(&_mtx); for (i = _list.nelem; i > 0; --i) { if (__p->type == 1) { --__p; continue; } uint32_t __type = __p->type; __p->type = 1; pthread_mutex_unlock(&_mtx); if (__type == 0) __p->cxa_func(__p->arg); --__p; pthread_mutex_lock(&_mtx); } pthread_mutex_unlock(&_mtx); } else { i = 0; do { if (__p->dso == dso) { pthread_mutex_lock(&_mtx); uint32_t __type = __p->type; __p->type = 1; pthread_mutex_unlock(&_mtx); if (__type == 0) __p->cxa_func(__p->arg); } ++__p; ++i; } while (i < _list.nelem); } return 0; } void __do_cleanup(void) { __cxa_finalize(__dso_handle); }
0
#include <pthread.h> void SayiUret(); void *Siralama(void *parametre); void *Birlesme(void *parametre); void ThreadYarat(); void DosyayaYaz(); pthread_mutex_t lock; int liste[1000]; int sonuc[1000]; FILE *dosya; { int baslangic; int bitis; } parametreler; int main (int argc, const char * argv[]) { dosya = fopen("dizileriGoster.txt", "w+"); if(dosya == 0) { printf("dizileriGoster.txt açılamadı..\\n"); exit(1); } SayiUret(); ThreadYarat(); DosyayaYaz(); return 0; } void SayiUret() { int rnd; int flag; int i, j; printf("***RANDOM DİZİ***\\n"); fprintf(dosya,"%s","****RANDOM DİZİ***"); fputc('\\n',dosya); for(i = 0; i < 1000; i++) { do { flag = 1; rnd = rand() % (1000) + 1; for (j = 0; j < i && flag == 1; j++) { if (liste[j] == rnd) { flag = 0; } } } while (flag != 1); liste[i] = rnd; printf("%d.sayi : %d\\t",i+1,liste[i]); if(i % 10 == 0) printf("\\n"); fprintf(dosya,"%d %s %d" ,i+1,".eleman:",liste[i]); fputc('\\n',dosya); } } void ThreadYarat() { int i; if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex başlatılamadı\\n"); exit(0); } pthread_t threadler[3]; parametreler *veri = (parametreler *) malloc (sizeof(parametreler)); veri->baslangic = 0; veri->bitis = (1000/2) - 1; pthread_create(&threadler[0], 0, Siralama, veri); parametreler *veri2 = (parametreler *) malloc (sizeof(parametreler)); veri2->baslangic = (1000/2); veri2->bitis = 1000 - 1; pthread_create(&threadler[1], 0, Siralama, veri2); for (i = 0; i < 3 -1; i++) { pthread_join(threadler[i], 0); } pthread_mutex_destroy(&lock); parametreler *veri3 = (parametreler *) malloc(sizeof(parametreler)); veri3->baslangic = 0; veri3->bitis = 1000; pthread_create(&threadler[2], 0, Birlesme, veri3); pthread_join(threadler[2], 0); } void *Siralama(void *parametre) { parametreler *p = (parametreler *)parametre; int ilk = p->baslangic; int son = p->bitis+1; int z; fprintf(dosya,"%s","****SIRALANMAMIŞ ELEMANLAR***"); fputc('\\n',dosya); for(z = ilk; z < son; z++){ fprintf(dosya,"%d %s %d" ,z+1,".eleman:",liste[z]); fputc('\\n',dosya); } printf("\\n"); int i,j,t,k; pthread_mutex_lock(&lock); for(i=ilk; i< son; i++) { for(j=ilk; j< son-1; j++) { if(liste[j] > liste[j+1]) { t = liste[j]; liste[j] = liste[j+1]; liste[j+1] = t; } } } pthread_mutex_unlock(&lock); fprintf(dosya,"%s","****SIRALANMIŞ ELEMANLAR***"); fputc('\\n',dosya); for(k = ilk; k< son; k++){ fprintf(dosya,"%d %s %d" ,k+1,".eleman:",liste[k]); fputc('\\n',dosya); } int x; for(x=ilk; x<son; x++) { sonuc[x] = liste[x]; } printf("\\n"); return 0; } void *Birlesme(void *parametre) { parametreler *p = (parametreler *)parametre; int ilk = p->baslangic; int son = p->bitis-1; int i,j,t; for(i=ilk; i< son; i++) { for(j=ilk; j< son-i; j++) { if(sonuc[j] > sonuc[j+1]) { t = sonuc[j]; sonuc[j] = sonuc[j+1]; sonuc[j+1] = t; } } } int d; pthread_exit(0); } void DosyayaYaz() { int i = 0; FILE *fp ; fp = fopen("son.txt","w+"); fprintf(fp,"%s","****SIRALANMIŞ ELEMANLAR***"); fputc('\\n',fp); for(i = 0; i<1000; i++) { fprintf(fp,"%d %s %d" ,i+1,".eleman:",sonuc[i]); fputc('\\n',fp); } fclose(fp); }
1
#include <pthread.h> pthread_mutex_t barrier; pthread_cond_t go; int numWorkers; int numArrived = 0; pthread_mutex_t result_lock; int value; int row; int column; } point_value; int sum; point_value max; point_value min; }matrix_result; matrix_result result = {0, {-1,0,0}, {100,0,0} }; double read_timer() { static bool initialized = 0; static struct timeval start; struct timeval end; if( !initialized ) { gettimeofday( &start, 0 ); initialized = 1; } gettimeofday( &end, 0 ); return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec); } double start_time, end_time; int size, stripSize; int matrix[10000][10000]; void *Worker(void *); int main(int argc, char *argv[]) { int i, j; long l; pthread_attr_t attr; pthread_t workerid[10]; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); pthread_mutex_init(&result_lock, 0); size = (argc > 1)? atoi(argv[1]) : 10000; numWorkers = (argc > 2)? atoi(argv[2]) : 10; if (size > 10000) size = 10000; if (numWorkers > 10) numWorkers = 10; stripSize = size/numWorkers; for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { matrix[i][j] = rand()%99; } } start_time = read_timer(); for (l = 0; l < numWorkers; l++) pthread_create(&workerid[l], &attr, Worker, (void *) l); for (l = 0; l < numWorkers; l++) pthread_join(workerid[l], 0); end_time = read_timer(); printf("The total is %d\\n", result.sum); printf("The maximum value is %d and its matrix position is [%d] [%d]\\n", result.max.value, result.max.column, result.max.row); printf("The minimum value is %d and its matrix position is [%d] [%d]\\n", result.min.value, result.min.column, result.min.row); printf("The execution time is %g sec\\n", end_time - start_time); pthread_exit(0); } void *Worker(void *arg) { long myid = (long) arg; int total, i, j, first, last; first = myid*stripSize; last = (myid == numWorkers - 1) ? (size - 1) : (first + stripSize - 1); point_value max_point = {-1, 0, 0 }; point_value min_point = {100, 0, 0 }; total = 0; for (i = first; i <= last; i++){ for (j = 0; j < size; j++){ total += matrix[i][j]; if(max_point.value < matrix[i][j]){ max_point.value = matrix[i][j]; max_point.column = j; max_point.row = i; } if(min_point.value > matrix[i][j]){ min_point.value = matrix[i][j]; min_point.column = j; min_point.row = i; } } } pthread_mutex_lock(&result_lock); result.sum += total; if(result.max.value < max_point.value){ result.max.value = max_point.value; result.max.column = max_point.column; result.max.row = max_point.row; } if(result.min.value > min_point.value){ result.min.value = min_point.value; result.min.column = min_point.column; result.min.row = min_point.row; } pthread_mutex_unlock(&result_lock); }
0
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; int f_id; struct foo *f_next; }; struct foo * foo_alloc(int id) { struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->f_id = id; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return(0); } idx = (((unsigned long)id)%29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&hashlock); fp->f_count++; pthread_mutex_unlock(&hashlock); } struct foo * foo_find(int id) { struct foo *fp; pthread_mutex_lock(&hashlock); for (fp = fh[(((unsigned long)id)%29)]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { fp->f_count++; break; } } pthread_mutex_unlock(&hashlock); return(fp); } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&hashlock); if (--fp->f_count == 0) { idx = (((unsigned long)fp->f_id)%29); tfp = fh[idx]; if (tfp == fp) { fh[idx] = fp->f_next; } else { while (tfp->f_next != fp) while (tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { pthread_mutex_unlock(&hashlock); } }
1
#include <pthread.h> void* run (void *arg); int main(int argc, char *argv[]) { pthread_mutex_t m; pthread_mutex_init(&m, 0); pthread_mutex_lock(&m); pthread_t h; pthread_create(&h, 0, run, &m); printf("[MAIN]Esperando que termine la ejecucion el hilo disparado\\n"); pthread_join(h, 0); printf("Esto nunca se ejecutara\\n"); pthread_mutex_unlock(&m); pthread_mutex_destroy(&m); return 0; } void* run (void *arg) { pthread_mutex_t *m = (pthread_mutex_t*) arg; pthread_mutex_lock(m); printf("[HILO SECUNDARIO]Tengo el mutex\\n"); pthread_mutex_unlock(m); return 0; }
0
#include <pthread.h> struct id_cache_entry { generic_id_t id; char name[32]; }; struct id_cache { unsigned int num; struct id_cache_entry entries[]; }; static pthread_mutex_t id_cache_mutex = PTHREAD_MUTEX_INITIALIZER; static struct id_cache *id_cache_uid; static struct id_cache *id_cache_gid; static void cache_lock(void) { if (!global_threaded) return; pthread_mutex_lock(&id_cache_mutex); } static void cache_unlock(void) { if (!global_threaded) return; pthread_mutex_unlock(&id_cache_mutex); } static bool strncpy_id_cache_entry(char *dest, struct id_cache *cache, generic_id_t id, size_t len) { unsigned int i; bool hit = 0; cache_lock(); if (cache) { for (i = 0; i < cache->num; i++) { if (cache->entries[i].id == id) { strncpy(dest, cache->entries[i].name, len); hit = 1; break; } } } cache_unlock(); return hit; } static void add_id_cache_entry(struct id_cache **cache_ptr, generic_id_t id, char *name) { struct id_cache *cache; unsigned int cache_num; size_t new_size; struct id_cache *new_cache; cache_lock(); cache = *cache_ptr; cache_num = cache ? cache->num : 0; new_size = sizeof(struct id_cache) + sizeof(struct id_cache_entry) * (cache_num + 1); new_cache = mrealloc(cache, new_size); if (cache_num == 0) new_cache->num = 0; new_cache->entries[cache_num].id = id; strncpy(new_cache->entries[cache_num].name, name, 32); new_cache->num++; *cache_ptr = new_cache; cache_unlock(); } void uid_to_name(uid_t uid, char *name, size_t len) { struct passwd pwd, *pwd_ptr; char buffer[PWD_BUFFER_SIZE], *result; if (strncpy_id_cache_entry(name, id_cache_uid, uid, len)) return; getpwuid_r(uid, &pwd, buffer, PWD_BUFFER_SIZE, &pwd_ptr); if (!pwd_ptr || !pwd_ptr->pw_name) return; result = pwd_ptr->pw_name; add_id_cache_entry(&id_cache_uid, uid, result); strncpy(name, result, len); } void gid_to_name(gid_t gid, char *name, size_t len) { struct group grp, *grp_ptr; char buffer[GRP_BUFFER_SIZE], *result; if (strncpy_id_cache_entry(name, id_cache_gid, gid, len)) return; getgrgid_r(gid, &grp, buffer, GRP_BUFFER_SIZE, &grp_ptr); if (!grp_ptr || !grp_ptr->gr_name) return; result = grp_ptr->gr_name; add_id_cache_entry(&id_cache_gid, gid, result); strncpy(name, result, len); } void idcache_cleanup(void) { free(id_cache_uid); free(id_cache_gid); }
1
#include <pthread.h> int thread_count; double total_integral; pthread_mutex_t mutex; long int nx; long int ny; void* Thread_sum(void* rank); double f1(double x, double y); double f2(double x, double y); int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; clock_t stime, etime; double Ttime, Ttime2; struct timeval t1, t2; scanf("%d", &thread_count); scanf("%ld %ld", &nx, &ny); stime = clock(); gettimeofday(&t1, 0); pthread_mutex_init(&mutex, 0); thread_handles = malloc (thread_count*sizeof(pthread_t)); for (thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], 0, Thread_sum, (void*) thread); for (thread = 0; thread < thread_count; thread++) pthread_join(thread_handles[thread], 0); pthread_mutex_destroy(&mutex); free(thread_handles); etime = clock(); gettimeofday(&t2, 0); Ttime = (double) (etime-stime)/CLOCKS_PER_SEC; if (t2.tv_usec > t1.tv_usec) Ttime2 = (double) ((t2.tv_sec - t2.tv_sec)*1000000 + t2.tv_usec - t1.tv_usec)/1000000; else Ttime2 = (double) ((t2.tv_sec - t2.tv_sec)*1000000 + t1.tv_usec - t2.tv_usec)/1000000; printf("Integral: %f\\t Elements: %ld\\nThreads: %d\\t", total_integral, nx*ny, thread_count); printf("CPU Time: %.10lf\\t Clock_time: %.10lf\\n", Ttime, Ttime2); return 0; } double f1 (double x, double y) { double val; val = 5*(x*x + y*y); return val; } double f2 (double x, double y) { double val; val = 6 - 7*x*x - y*y; return val; } void* Thread_sum(void* rank) { long my_rank = (long) rank; double x, y; int i,j; long long my_nx = nx/thread_count; long long my_first_nx = my_nx*my_rank; long long my_last_nx = my_first_nx + my_nx; double xmin = -1; double xmax = 1; double ymin = -2; double ymax = 2; double hx = (xmax - xmin)/nx; double hy = (ymax - ymin)/ny; double integral = 0; for (i = my_first_nx; i <= my_last_nx; i++) { x = xmin + i*hx; for (j = 0; j < ny; j++) { y = ymin + j*hy; if ( f1(x,y) > f2(x,y)) {} else integral = integral + (f2(x,y) - f1(x,y))*hx*hy; } } pthread_mutex_lock (&mutex); total_integral += integral; pthread_mutex_unlock(&mutex); return 0; }
0
#include <pthread.h> struct thread_args { int allocation_size; int array_size; int thread_count; }; struct timespec timer_start() { struct timespec start_time; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_time); return start_time; } long timer_end(struct timespec start_time) { struct timespec end_time; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_time); long diffInNanos = (round(end_time.tv_nsec/ 1.0e6) - round(start_time.tv_nsec/ 1.0e6)); return diffInNanos; } int MAX_SIZE = 1024 * 1024; int MAX_ALLOCATION_ARRAY_SIZE = 500; char TEST_OUT_FILE[] = "result.out"; int MAX_THREADS = 500; FILE *result_file; pthread_mutex_t result_file_mutex = PTHREAD_MUTEX_INITIALIZER; void * nice_thread_run(void *args) { int allocation_size, array_size, thread_count; allocation_size = ((struct thread_args *)args)->allocation_size; array_size = ((struct thread_args *)args)->array_size; thread_count = ((struct thread_args *)args)->thread_count; int i = 0; void **test_arr; long time_elapsed_ms; struct timespec starttime = timer_start(); test_arr = malloc1(array_size * sizeof(void*)); for(i = 0; i < array_size; i++) { test_arr[i] = malloc1(allocation_size); if(0 == test_arr) { break; } } time_elapsed_ms = timer_end(starttime); for(i = 0; i < array_size; i++) { if(0 != test_arr[i]) { free1(test_arr[i]); } } free1(test_arr); pthread_mutex_lock(&result_file_mutex); fprintf(result_file, "%d\\t%d\\t%d\\t%ld\\n", thread_count, allocation_size, array_size, time_elapsed_ms); pthread_mutex_unlock(&result_file_mutex); return 0; } int main() { result_file = fopen(TEST_OUT_FILE, "w+"); int thread_count = 50; int i = 0; pthread_t tid[10000]; int array_size = 1; int allocation_size = 8; struct thread_args arg; while (thread_count <= MAX_THREADS) { printf(" Thread count, n = %d \\n", thread_count); while(allocation_size < MAX_SIZE) { array_size = 1; while (array_size < MAX_ALLOCATION_ARRAY_SIZE) { arg.allocation_size = allocation_size; arg.array_size = array_size; arg.thread_count = thread_count; for(i = 0; i < thread_count; i++) { pthread_create(&tid[i], 0, nice_thread_run, (void *)&arg); } for(i = 0; i < thread_count; i++) { pthread_join(tid[i], 0); } array_size *= 10; } allocation_size *= 2; } allocation_size = 8; thread_count += 50; } fclose(result_file); return 0; }
1
#include <pthread.h> int count = 0; int thread_ids[3] = {0, 1, 2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold; 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); printf("inc_count(): thread %ld, count = %d Threshold reached.\\n", my_id, count); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long) t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while(count < 12) { pthread_cond_wait(&count_threshold, &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; 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, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *) t2); pthread_create(&threads[2], &attr, inc_count, (void *) t3); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf("Main(): Waited on %d threads. Done.\\n", 3); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold); pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t barrier; pthread_cond_t go; int numWorkers; int numArrived = 0; void Barrier() { pthread_mutex_lock(&barrier); numArrived++; if (numArrived == numWorkers) { numArrived = 0; pthread_cond_broadcast(&go); } else pthread_cond_wait(&go, &barrier); pthread_mutex_unlock(&barrier); } double read_timer() { static bool initialized = 0; static struct timeval start; struct timeval end; if( !initialized ) { gettimeofday( &start, 0 ); initialized = 1; } gettimeofday( &end, 0 ); return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec); } double start_time, end_time; int size, stripSize; int sums[10]; int maxs[10]; int mins[10]; int maxis[10]; int maxjs[10]; int minis[10]; int minjs[10]; int matrix[10000][10000]; void *Worker(void *); int main(int argc, char *argv[]) { int i, j; long l; pthread_attr_t attr; pthread_t workerid[10]; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); pthread_mutex_init(&barrier, 0); pthread_cond_init(&go, 0); size = (argc > 1)? atoi(argv[1]) : 10000; numWorkers = (argc > 2)? atoi(argv[2]) : 10; if (size > 10000) size = 10000; if (numWorkers > 10) numWorkers = 10; stripSize = size/numWorkers; for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { matrix[i][j] = rand()%99; } } start_time = read_timer(); for (l = 0; l < numWorkers; l++) pthread_create(&workerid[l], &attr, Worker, (void *) l); pthread_exit(0); } void *Worker(void *arg) { long myid = (long) arg; int total, i, j, first, last; int min, max, mini, minj, maxi, maxj; first = myid*stripSize; last = (myid == numWorkers - 1) ? (size - 1) : (first + stripSize - 1); total = 0; max = 0; min = 32767; for (i = first; i <= last; i++){ for (j = 0; j < size; j++){ total += matrix[i][j]; if(matrix[i][j] > max){ max = matrix[i][j]; maxi = i; maxj = j; } if(matrix[i][j] < min){ min = matrix[i][j]; mini = i; minj = j; } } } sums[myid] = total; maxs[myid] = max; mins[myid] = min; maxis[myid] = maxi; maxjs[myid] = maxj; minis[myid] = mini; minjs[myid] = minj; Barrier(); if (myid == 0) { total = 0; max = 0; min = 32767; for (i = 0; i < numWorkers; i++){ total += sums[i]; if(maxs[i] > max){max = maxs[i]; maxi = maxis[i]; maxj = maxjs[i];} if(mins[i] < min){min = mins[i]; mini = minis[i]; minj = minjs[i];} } end_time = read_timer(); printf("The total is %d\\n", total); printf("Maximal element is [%d, %d] = %d\\n", maxi, maxj, max); printf("Minimum element is [%d, %d] = %d\\n", mini, minj, min); printf("The execution time is %g sec\\n", end_time - start_time); } }
1
#include <pthread.h> void *find_jpg(void *path){ char *file, *file_ext, file_path[1000]; DIR *inDir; struct dirent *inDirent; inDir = opendir(path); if (!inDir) { fprintf(stderr, "Error while searching for jpg files: invalid file path.\\n"); fprintf(stderr, " Unable to open directory at %s\\n", (char *) path); pthread_exit(0); } while ( (inDirent = readdir(inDir)) ) { file = inDirent->d_name; file_ext = strrchr(file, '.'); if (!strcmp(file, ".") || !strcmp(file, "..") || !strcmp(file, ".DS_Store") || !file_ext) { continue; } if (!strcmp(file_ext, ".jpg")) { strcpy(file_path, path); strcat(file_path, "/"); strcat(file_path, file); pthread_mutex_lock(&html_mutex); generate_html(file_path); pthread_mutex_unlock(&html_mutex); } } closedir(inDir); pthread_exit(0); }
0
#include <pthread.h> bool queue_init(struct _queue *queue, size_t bufsize) { bool ret; memset(queue, 0, sizeof(struct _queue)); ret = pthread_mutex_init(&queue->put_lock, 0) == 0; if (!ret) { goto queue_init_err0; } ret = pthread_mutex_init(&queue->get_lock, 0) == 0; if (!ret) { goto queue_init_err1; } printf("50"); queue->size = bufsize; queue->buffer = (uint8_t*)malloc( queue->size); ret = queue->buffer != 0; if (!ret) { goto queue_init_err2; } queue_init_err2: pthread_mutex_destroy(&queue->get_lock); queue_init_err1: pthread_mutex_destroy(&queue->put_lock); queue_init_err0: return ret; } void queue_deinit(struct _queue *queue) { pthread_mutex_lock(&queue->get_lock); pthread_mutex_lock(&queue->put_lock); free(queue->buffer); queue->size = 0; queue->buffer = 0; queue->get = queue->put = 0; queue->get_parity = queue->put_parity = 0; pthread_mutex_unlock(&queue->put_lock); pthread_mutex_unlock(&queue->get_lock); pthread_mutex_destroy(&queue->put_lock); pthread_mutex_destroy(&queue->get_lock); return; } size_t queue_get(struct _queue *queue, char *buf, size_t size) { int block, read = 0; pthread_mutex_lock(&queue->get_lock); while (read < size) { int bufleft = queue_space(queue, QUEUE_SPACE_GET); if (bufleft == 0) break; block = queue->size - queue->get; if (block > bufleft) block = bufleft; if (block > size - read) block = size - read; block = (((block) < ((((bufleft) < (size - read)) ? (bufleft) : (size - read)))) ? (block) : ((((bufleft) < (size - read)) ? (bufleft) : (size - read)))); memcpy(buf + read, queue->buffer + queue->get, block); queue->get = queue->get + block; if (queue->get >= queue->size) { queue->get = 0; queue->get_parity = ~queue->get_parity; } read = read + block; } pthread_mutex_unlock(&queue->get_lock); return read; } size_t queue_put(struct _queue *queue, char *buf, size_t size) { int block, read = 0; pthread_mutex_lock(&queue->put_lock); while (read < size) { int bufleft = queue_space(queue, QUEUE_SPACE_PUT); if (bufleft == 0) break; block = queue->size - queue->put; if (block > bufleft) block = bufleft; if (block > size - read) block = size - read; memcpy(queue->buffer + queue->put, buf + read, block); queue->put = queue->put + block; if (queue->put >= queue->size) { queue->put = 0; queue->put_parity = ~queue->put_parity; } read = read + block; } pthread_mutex_unlock(&queue->put_lock); return read; } size_t queue_space(struct _queue *queue, int way) { int buf; if (way == QUEUE_SPACE_GET) { buf = queue->put - queue->get; } else if (way == QUEUE_SPACE_PUT) { buf = queue->get - queue->put; } else { return -1; } if (buf < 0) { return buf + queue->size; } else if (buf == 0) { if (queue->put_parity == queue->get_parity) { return (way == QUEUE_SPACE_GET) ? 0 : queue->size; } else { return (way == QUEUE_SPACE_GET) ? queue->size : 0; } } else { return buf; } } size_t queue_flush(struct _queue *queue) { pthread_mutex_lock(&queue->get_lock); pthread_mutex_lock(&queue->put_lock); size_t ret = queue_space(queue, QUEUE_SPACE_GET); queue->get = queue->put; queue->get_parity = queue->put_parity; pthread_mutex_unlock(&queue->put_lock); pthread_mutex_unlock(&queue->get_lock); return ret; }
1
#include <pthread.h> int sum = 0; pthread_mutex_t lock; void count(int *arg){ int i; for(i = 0; i<*arg; i++){ pthread_mutex_lock(&lock); sum++; pthread_mutex_unlock(&lock); } } int main(int argc, char **argv){ int error, i; int numcounters = 10; int limit = 100; pthread_t tid[100]; if(argc == 1){ printf("usage: goodcount numcounters limit\\n"); exit(1); } if(argc == 2){ numcounters = atoi(argv[1]); } if(argc == 3){ numcounters = atoi(argv[1]); limit = atoi(argv[2]); } printf("numcounters = %d, limit = %d\\n", numcounters, limit); pthread_setconcurrency(numcounters); pthread_mutex_init(&lock, 0); for(i = 1; i<=numcounters; i++){ error = pthread_create(&tid[i], 0, (void *(*)(void *))count, &limit); } for(i = 1; i<=numcounters; i++){ error = pthread_join(tid[i], 0); } printf("Counters finished with count = %d\\n", sum); printf("Count should be %d X %d = %d\\n", numcounters, limit, numcounters*limit); return 0; }
0
#include <pthread.h> void interrupt2() { fprintf(stdout, "Token thread exiting\\n"); return; } void *handler2() { struct sigaction act; sigset_t sig; act.sa_handler = interrupt2; sigaction(SIGUSR2, &act, 0); sigemptyset(&sig); sigaddset(&sig, SIGUSR2); pthread_sigmask(SIG_UNBLOCK, &sig, 0); return 0; } void * tokbucketFunc(void * arg) { long int timestamp, start_time; double time; int cnt = 0; Packet *packet; sigset_t sig; char msg[5] = "token"; sigemptyset(&sig); sigaddset(&sig, SIGINT); pthread_sigmask(SIG_BLOCK, &sig, 0); handler2(); start_time = emulationTime; while(1){ cnt++; if(Param.r > 10000000){ Param.r = 10000000; } if(sigHit){ goto thread_exit; } timestamp = Param.r - (getTime() - start_time); if(timestamp <= 0){ fprintf(stdout, "timestamp value is going negative, ignoring sleep\\n"); }else{ usleep(timestamp); } start_time = getTime(); if(sigHit){ goto thread_exit; } pthread_mutex_lock(&mutex); Stat.tok++; if(tokList.num_members < Param.B){ pushToken(); fprintf(stdout,"%012.3lfms: token t%d arrives, token bucket now has %d tokens\\n", relativeTimeinDouble(getTime()), cnt, tokList.num_members); } else{ fprintf(stdout,"%012.3lfms: token t%d arrives, dropped\\n", relativeTimeinDouble(getTime()), cnt); Stat.tok_drop++; } if(!checkQueueEmpty(1)){ packet = firstQueue(1); if(checkToken(packet->P)){ removeTokens(packet->P); packet = popQueue(1); time = (double)(getTime() - packet->Q1)/1000.0; Stat.Q1 = Stat.Q1 + time; fprintf(stdout,"%012.3lfms: p%d leaves Q1, time in Q1 = %lfms,\\n %20s bucket now has %d tokens\\n", relativeTimeinDouble(getTime()), packet->val, time, msg, tokList.num_members); pushQueue(2, packet); processedPacket++; packet->Q2 = getTime(); fprintf(stdout,"%012.3lfms: p%d enters Q2\\n", relativeTimeinDouble(getTime()), packet->val); if(!wakeupServer() && sigHit){ pthread_exit(0); return 0; } }else { pthread_mutex_unlock(&mutex); } }else{ pthread_mutex_unlock(&mutex); } if(processedPacket == Param.packet_num){ removeQueue(1); removeTokens(0); pthread_exit(0); return 0; } } thread_exit: pthread_mutex_lock(&mutex); packetCount = 0; removeTokens(0); pthread_cond_broadcast(&processQueue); pthread_mutex_unlock(&mutex); pthread_exit(0); return 0; }
1
#include <pthread.h> struct android_handlerthread { pthread_t tid; pthread_mutex_t lock; pthread_cond_t cond; struct android_looper *looper; struct android_handler *handler; }; static void *run(void * data) { int ret; struct android_handlerthread *thread = data; pthread_mutex_lock(&thread->lock); thread->looper = ngli_android_looper_new(); if (!thread->looper) goto fail; ret = ngli_android_looper_prepare(thread->looper); if (ret < 0) goto fail; thread->handler = ngli_android_handler_new(); if (!thread->handler) goto fail; pthread_cond_signal(&thread->cond); pthread_mutex_unlock(&thread->lock); ngli_android_looper_loop(thread->looper); ngli_android_handler_free(&thread->handler); ngli_android_looper_free(&thread->looper); return 0; fail: ngli_android_handler_free(&thread->handler); ngli_android_looper_free(&thread->looper); pthread_cond_signal(&thread->cond); pthread_mutex_unlock(&thread->lock); return 0; } struct android_handlerthread *ngli_android_handlerthread_new(void) { struct android_handlerthread *thread = calloc(1, sizeof(*thread)); if (!thread) return 0; pthread_mutex_init(&thread->lock, 0); pthread_cond_init(&thread->cond, 0); pthread_mutex_lock(&thread->lock); if (pthread_create(&thread->tid, 0, run, thread)) { pthread_mutex_unlock(&thread->lock); pthread_mutex_destroy(&thread->lock); pthread_cond_destroy(&thread->cond); free(thread); return 0; } pthread_cond_wait(&thread->cond, &thread->lock); pthread_mutex_unlock(&thread->lock); if (!thread->handler) { ngli_android_handlerthread_free(&thread); return 0; } return thread; } void *ngli_android_handlerthread_get_native_handler(struct android_handlerthread *thread) { if (!thread) return 0; return ngli_android_handler_get_native_handler(thread->handler); } void ngli_android_handlerthread_free(struct android_handlerthread **threadp) { struct android_handlerthread *thread = *threadp; if (!thread) return; ngli_android_looper_quit(thread->looper); pthread_join(thread->tid, 0); pthread_mutex_destroy(&thread->lock); pthread_cond_destroy(&thread->cond); free(*threadp); *threadp = 0; }
0
#include <pthread.h> struct Node* left; struct Node* right; int value; } Node; struct Node* left; struct Node* right; pthread_mutex_t m; } Queue; void push_left(Queue* q, int val) { Node* new_left = (Node*)calloc(1, sizeof (Node)); new_left->value = val; pthread_mutex_lock(&q->m); Node* old_left = q->left; q->left = new_left; if (!old_left) { q->right = new_left; } else { new_left->right = old_left; old_left->left = new_left; } pthread_mutex_unlock(&q->m); } int pop_right(Queue* q) { pthread_mutex_lock(&q->m); Node* old_right = q->right; if (!old_right) { pthread_mutex_unlock(&q->m); return -1; } Node* new_right = old_right->left; if (new_right) new_right->right = 0; q->right = new_right; int v = old_right->value; pthread_mutex_unlock(&q->m); free(old_right); return v; } void for_all(Queue* q, void* data, void (*callback)(void*, int)) { Node* e = 0; pthread_mutex_lock(&q->m); for (e = q->left; e != q->right; e=e->right) { callback(data, e->value); } callback(data, e->value); pthread_mutex_unlock(&q->m); } void printall(void* prefix, int val) { printf("%s: %d\\n", prefix, val); } void lockup(void* data, int val) { Queue* q = (Queue*)data; push_left(q, 42); } int main(void) { Queue* q = (Queue*)calloc(1, sizeof (Queue)); pthread_mutex_init(&q->m, 0); int n = 10; for (int i = 0; i < n; i++) { push_left(q, i); } for_all(q, &"Run 1", printall); for_all(q, q, (void (*)(void*, int))&push_left); for_all(q, &"Run 2", printall); do { int res = pop_right(q); if (res == -1) break; printf("Popped: %d\\n", res); } while (1); pthread_mutex_destroy(&q->m); free(q); pthread_exit(0); return 0; }
1
#include <pthread.h> struct job{ double data; struct job* next; }; struct job* job_queue; sem_t job_queue_count; pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER; void* thread_callback_enqueue(void *arg) { unsigned int thread_id = *((unsigned int*)arg); struct job* new_job = 0; pthread_mutex_lock(&job_queue_mutex); new_job = (struct job*)calloc(1,sizeof(struct job)); if(0 == new_job) perror("Memory Allocation failed."); new_job->data = 100.0+thread_id; if(0 == job_queue){ job_queue = new_job; } else{ new_job->next = job_queue; job_queue = new_job; } sem_post(&job_queue_count); pthread_mutex_unlock(&job_queue_mutex); printf("INSIDE thread [%d], enqued job with data = [%f]\\n", thread_id,new_job->data); } void* thread_callback_dequeue(void* arg) { int thread_id = *((int*)arg); struct job* next_job = 0; sem_wait(&job_queue_count); pthread_mutex_lock(&job_queue_mutex); next_job = job_queue; job_queue = job_queue->next; pthread_mutex_unlock(&job_queue_mutex); printf("INSIDE thread [%d], processed job with data = [%f]\\n", thread_id,next_job->data); free(next_job); } main() { int count = 0; int ind = 0; int ret = 0; int status = 0; pthread_t thread_list[40]; int thread_list_int[40]; sem_init(&job_queue_count,0,0); job_queue = 0; for(count=0;count<40/3;count++){ thread_list_int[count] = count; ret = pthread_create(&thread_list[count],0, thread_callback_dequeue,&thread_list_int[count]); if(ret!=0){ fprintf(stderr,"[%d] thread creation failed...\\n",count); perror("Exiting..."); } } for(;count<40;count++){ thread_list_int[count] = count; ret = pthread_create(&thread_list[count],0, thread_callback_enqueue,&thread_list_int[count]); if(ret!=0){ fprintf(stderr,"[%d] thread creation failed...\\n",count); perror("Exiting..."); } } printf("Waiting for all children threads to be terminated...\\n"); for(ind=0;ind<40;ind++){ if(0 != pthread_join(thread_list[ind],(void*)&status)) perror("Thread Join failed."); printf("Completed thread [%d] with ret = [%d]\\n",ind,status); } return 0; }
0
#include <pthread.h> int block; int busy; int inode; pthread_mutex_t m_inode; pthread_mutex_t m_busy; void *allocator(){ pthread_mutex_lock(&m_inode); if(inode == 0){ pthread_mutex_lock(&m_busy); busy = 1; pthread_mutex_unlock(&m_busy); inode = 1; } block = 1; if (!(block == 1)) ERROR: goto ERROR;; pthread_mutex_unlock(&m_inode); return 0; } void *de_allocator(){ pthread_mutex_lock(&m_busy); if(busy == 0){ block = 0; if (!(block == 0)) ERROR: goto ERROR;; } pthread_mutex_unlock(&m_busy); return ((void *)0); } int main() { pthread_t t1, t2; __VERIFIER_assume(inode == busy); pthread_mutex_init(&m_inode, 0); pthread_mutex_init(&m_busy, 0); pthread_create(&t1, 0, allocator, 0); pthread_create(&t2, 0, de_allocator, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_mutex_destroy(&m_inode); pthread_mutex_destroy(&m_busy); return 0; }
1
#include <pthread.h> const int MAX_THREADS = 1024; long thread_count; long long n; double sum = 0; pthread_mutex_t mutex; void* Thread_sum(void* rank); void Get_args(int argc, char* argv[]); void Usage(char* prog_name); double Serial_pi(long long n); int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; double start, finish, elapsed; Get_args(argc, argv); GET_TIME(start); double serial_sum = Serial_pi(n); GET_TIME(finish); elapsed = finish - start; printf("Serial_pi computed %f and it took %f seconds.\\n", serial_sum, elapsed); GET_TIME(start); pthread_mutex_init(&mutex, 0); thread_handles = malloc (thread_count * sizeof ( pthread_t) ); for (thread = 0; thread < thread_count; thread++) { pthread_create(&thread_handles[thread], 0, Thread_sum, (void*) thread); } for (thread = 0; thread < thread_count; thread++) { pthread_join(thread_handles[thread], 0); } sum *= 4.0; free(thread_handles); GET_TIME(finish); elapsed = finish - start; printf("Thread_sum computed %f and it took %f seconds.\\n", sum, elapsed); return 0; } void* Thread_sum(void* rank) { long my_rank = (long) rank; double factor; long long i; long long my_n = n / thread_count; long long my_first_i = my_n * my_rank; long long my_last_i = my_first_i + my_n; if (my_first_i % 2 == 0) { factor = 1.0; } else { factor = -1.0; } for (i = my_first_i; i < my_last_i; i++, factor = -factor) { pthread_mutex_lock(&mutex); sum += factor / (2 * i + 1); pthread_mutex_unlock(&mutex); } return 0; } double Serial_pi(long long n) { double sum = 0.0; long long i; double factor = 1.0; for (i = 0; i < n; i++, factor = -factor) { sum += factor/(2*i+1); } return 4.0*sum; } void Get_args(int argc, char* argv[]) { if (argc != 3) Usage(argv[0]); thread_count = strtol(argv[1], 0, 10); if (thread_count <= 0 || thread_count > MAX_THREADS) Usage(argv[0]); n = strtoll(argv[2], 0, 10); if (n <= 0) Usage(argv[0]); } void Usage(char* prog_name) { fprintf(stderr, "usage: %s <number of threads> <n>\\n", prog_name); fprintf(stderr, " n is the number of terms and should be >= 1\\n"); fprintf(stderr, " n should be evenly divisible by the number of threads\\n"); exit(0); }
0
#include <pthread.h> pthread_mutex_t mutex; unsigned long int *a; unsigned long int *b; unsigned long int prod; int TAM_VET; void *f(void *ide) { int i = 0; int id = atoi(ide); int tam = TAM_VET/2; if (id > 0) { i = id * tam; } if (id == 2 -1) { tam += TAM_VET%2; } tam += i; pthread_mutex_lock(&mutex); for (i; i<tam; i++) prod += a[i] * b[i]; pthread_mutex_unlock(&mutex); return 0; } int main (int argc, char *argv[]) { int i; prod = 0.0; pthread_t threads[2]; pthread_mutex_init(&mutex, 0); if(argc<2){ printf("uso %s <tamanho vetores>\\n", argv[0]); exit(1); } TAM_VET = atoi(argv[1]); a = (unsigned long int *) malloc(sizeof(unsigned long int) * TAM_VET); b = (unsigned long int *) malloc(sizeof(unsigned long int) * TAM_VET); printf("Inicializando vetores A e B...\\n"); for (i=0; i<TAM_VET; i++) a[i] = 2; for (i=0; i<TAM_VET; i++) b[i] = 2; for (i=0; i<2; i++) pthread_create(&threads[i], 0, f, (void *)threads[i]); for (i=0; i<2; i++) pthread_join(threads[i], 0); printf("Calculando...\\n"); printf("Terminou!\\n"); printf("******************************************************\\n"); printf("Produto escalar: %lu\\n", prod); printf("******************************************************\\n"); free(a); free(b); pthread_mutex_destroy(&mutex); }
1
#include <pthread.h> void* process_thread(void *arg) { struct threads *p = (struct threads *) arg; fprintf(stderr, "Thread %u: start\\n", (unsigned int)pthread_self()); pthread_mutex_lock(&p->mutex); while(1) { char request_filename[16]; char response_filename[16]; switch(p->inout) { case 0: fprintf(stderr, "Thread %u: will write request\\n", (unsigned int)pthread_self()); if(p->conn.request_file == 0) { sprintf(request_filename, "%s_request", p->conn.tmp_name); p->conn.request_file = fopen(request_filename, "w"); if(p->conn.request_file == 0) { fprintf(stderr, "Thread %u: Cannot open file %s\\n", (unsigned int)pthread_self(), request_filename); exit(1); } fprintf(stderr, "Thread %u: Open file %s\\n", (unsigned int)pthread_self(), request_filename); } fwrite(p->data, p->data_length, 1, p->conn.request_file); fprintf(stderr, "Thread %u: Write ok\\n", (unsigned int)pthread_self()); break; case 2: fprintf(stderr, "Thread %u: Will close request\\n", (unsigned int)pthread_self()); sprintf(request_filename, "%s_request", p->conn.tmp_name); if(p->conn.request_file != 0) { fclose(p->conn.request_file); p->conn.request_file = 0; fprintf(stderr, "Thread %u: Close file %s\\n", (unsigned int)pthread_self(), request_filename); } break; case 1: fprintf(stderr, "Thread %u: Will write response\\n", (unsigned int)pthread_self()); if(p->conn.response_file == 0) { sprintf(response_filename, "%s_response", p->conn.tmp_name); p->conn.response_file = fopen(response_filename, "w"); if(p->conn.response_file == 0) { fprintf(stderr, "Thread %u: Cannot open file %s\\n", (unsigned int)pthread_self(), response_filename); exit(1); } fprintf(stderr, "Thread %u: Open file %s\\n", (unsigned int)pthread_self(), response_filename); } fwrite(p->data, p->data_length, 1, p->conn.response_file); fprintf(stderr, "Thread %u: Write ok\\n", (unsigned int)pthread_self()); break; case 3: fprintf(stderr, "Thread %u: Will close response\\n", (unsigned int)pthread_self()); sprintf(response_filename, "%s_response", p->conn.tmp_name); if(p->conn.response_file != 0) { fclose(p->conn.response_file); p->conn.response_file = 0; fprintf(stderr, "Thread %u: Close file %s\\n", (unsigned int)pthread_self(), response_filename); } break; case 4: fprintf(stderr, "Thread %u: will close all\\n", (unsigned int)pthread_self()); sprintf(request_filename, "%s_request", p->conn.tmp_name); if(p->conn.request_file != 0) { fclose(p->conn.request_file); p->conn.request_file = 0; fprintf(stderr, "Thread %u: Close file %s\\n", (unsigned int)pthread_self(), request_filename); } sprintf(response_filename, "%s_response", p->conn.tmp_name); if(p->conn.response_file != 0) { fclose(p->conn.response_file); p->conn.response_file = 0; fprintf(stderr, "Thread %u: Close file %s\\n", (unsigned int)pthread_self(), response_filename); } break; default: fprintf(stderr, "Thread %u: Unknown thread status\\n", (unsigned int)pthread_self()); exit(1); } p->consumed = 1; if(p->conn.request_file == 0 && p->conn.response_file == 0) { pthread_mutex_lock(&t_mutex); struct threads *q = t_head, *prev; if(t_head==p) { t_head = t_head->next; } else { while(q != p && q != 0) { prev = q; q = q->next; } if(q == 0) { fprintf(stderr, "Thread %u: Cannot delete thread from link list\\n", (unsigned int)pthread_self()); exit(1); } prev->next = p->next; } pthread_mutex_destroy(&p->mutex); pthread_cond_destroy(&p->cond); free(p); pthread_mutex_unlock(&t_mutex); fprintf(stderr, "Thread %u: exit\\n", (unsigned int)pthread_self()); pthread_exit(0); } fprintf(stderr, "Thread %u: sleep\\n", (unsigned int)pthread_self()); pthread_cond_wait(&p->cond, &p->mutex); fprintf(stderr, "Thread %u: awake from wait\\n", (unsigned int)pthread_self()); } }
0
#include <pthread.h> pthread_mutex_t the_mutex; pthread_cond_t condc, condp; int buffer[100]; int i = 0; void * producer(void *ptr) { while(1) { printf("producer locking critical region\\n"); pthread_mutex_lock(&the_mutex); while( i == 100) { printf("buffer not empty, producer sleeping\\n"); pthread_cond_wait(&condp, &the_mutex); } printf("producer producing element %d\\n", i); buffer[i] = i; i++; printf("producer signaling consumer to wake up\\n"); pthread_cond_signal(&condc); printf("producer releasing lock on critical region\\n"); pthread_mutex_unlock(&the_mutex); } } void * consumer(void *ptr) { while(1) { printf("consumer locking critical region\\n"); pthread_mutex_lock(&the_mutex); while(i == -1) { i = 0; printf("buffer is empty, consumer sleeping\\n"); pthread_cond_wait(&condc, &the_mutex); } printf("consumer consuming element %d\\n", i); buffer[i] = 0; i--; printf("consumer signaling producer to wake up\\n"); pthread_cond_signal(&condp); printf("consumer releasing lock on critical region\\n"); pthread_mutex_unlock(&the_mutex); } } int main() { 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(pro, 0); pthread_join(con, 0); pthread_cond_destroy(&condc); pthread_cond_destroy(&condp); pthread_mutex_destroy(&the_mutex); return 0; }
1
#include <pthread.h> struct proc { pid_t pid; int status; bool exited; int write_fd; int read_fd; pthread_mutex_t lock; struct fcgi* fcgi; }; static struct proc procs[NUM_PROCS]; static unsigned int procs_available; static pthread_mutex_t procs_lock; static struct list wait_queue; static pthread_mutex_t wait_queue_lock; static int proc_init (struct proc*); static struct proc* get_available_proc (); static void assign_proc (struct proc* p, struct fcgi* fcgi); void init_pushup () { unsigned int i; int ret; pthread_mutex_init (&procs_lock, 0); pthread_mutex_init (&wait_queue_lock, 0); list_init (&wait_queue); procs_available = NUM_PROCS; for (i = 0; i < NUM_PROCS; i++) { printf ("spawning child %u \\n", i); struct proc* p = &procs[i]; ret = proc_init (p); if (-1 == ret) { printf ("Error in creation of child \\n"); return; } else if (0 != ret) { ASSERT (1 == p->exited); exit (p->status); } } printf ("pushup initialized...\\n"); }; void end_pushup () { int i; struct proc* p; for (i = 0; i < NUM_PROCS; i++) { p = &procs[i]; printf ("waiting: %d \\n", p->pid); waitpid (p->pid, &p->status, 0); } }; int proc_init (struct proc* p) { ASSERT (p); dup (0); dup (1); dup (2); int writepipe[2] = {-1, -1}; int readpipe[2] = {-1, -1}; if (pipe (readpipe) < 0 || pipe (writepipe) < 0) { printf ("Failed to create pipes for child \\n"); return -1; } int childread = writepipe[0]; int childwrite = readpipe[1]; int parentread = readpipe[0]; int parentwrite = writepipe[1]; pid_t pid = fork (); if (pid == -1) { printf ("Failed to fork child \\n"); close (childread); close (childwrite); close (parentread); close (parentwrite); return -1; } if (pid != 0) { p->status = child_run (pid, childread, childwrite); p->exited = 1; return 1; } else { p->exited = 0; p->fcgi = 0; p->pid = pid; p->write_fd = parentwrite; p->read_fd = parentread; pthread_mutex_init (&p->lock, 0); return 0; } }; int pushup_dispatch (struct fcgi* fcgi) { struct proc* p; ASSERT (fcgi); pthread_mutex_lock (&procs_lock); if (0 == procs_available) { pthread_mutex_unlock (&procs_lock); pthread_mutex_lock (&wait_queue_lock); list_push_back (&wait_queue, &fcgi->elem); pthread_mutex_unlock (&wait_queue_lock); } else { p = get_available_proc (); ASSERT (0 != p); assign_proc (p, fcgi); pthread_mutex_unlock (&p->lock); pthread_mutex_unlock (&procs_lock); } }; static struct proc* get_available_proc () { int i; ASSERT (procs_available > 0); for (i = 0; i < NUM_PROCS; i++) { pthread_mutex_lock (&procs[i].lock); if (procs[i].fcgi == 0) { return &procs[i]; } pthread_mutex_unlock (&procs[i].lock); } NOT_REACHED; }; static void assign_proc (struct proc* p, struct fcgi* fcgi) { struct child_cmd cmd; ASSERT (p); ASSERT (p->fcgi == 0); ASSERT (fcgi); p->fcgi = fcgi; cmd.type = CMD_FCGI; cmd.content_length = sizeof (struct fcgi); write (p->write_fd, &cmd, sizeof (struct child_cmd)); write (p->write_fd, p->fcgi, sizeof (struct fcgi)); };
0
#include <pthread.h> void grab_forks(int* philosopher_id); void put_away_forks(int* philosopher_id); void test(int* philosopher_id); void initialize_mutex(); void* philosopher_life(void* philosopher_id); void think(int* philosopher_id); void eat(int* philosopher_id, int current_meal); pthread_mutex_t m; pthread_mutex_t s[5]; int state[5]; char *p_name[5] = {"Nietzsche", "Kant", "Plato", "Homer", "Aquinas"}; int main(){ pthread_t philosopher_thread[5]; int i; int philosopher_id_array[5]; initialize_mutex(); for(i = 0; i < 5; i++){ philosopher_id_array[i] = i; if(pthread_create(&(philosopher_thread[i]), 0, philosopher_life, (void *) &philosopher_id_array[i]) != 0){ perror("phtread_create"); exit(1); } } for(i = 0; i < 5; i++){ pthread_join(philosopher_thread[i], 0); } pthread_mutex_destroy(&m); for(i = 0; i < 5; i++){ pthread_mutex_destroy(&s[i]); } pthread_exit(0); return 0; } void* philosopher_life(void* philosopher_id){ int meal_counter; printf("p_id: [%d] name: [%s] \\thas joined the table.\\n", *(int*) philosopher_id, p_name[*(int*) philosopher_id]); for(meal_counter = 1; meal_counter < 2 + 1; meal_counter++){ think((int*) philosopher_id); eat((int*) philosopher_id, meal_counter); } printf("p_id: [%d] name: [%s] \\thas left the table.\\n", *(int*) philosopher_id, p_name[*(int*) philosopher_id]); } void eat(int* philosopher_id, int current_meal){ printf("p_id: [%d] name: [%s] \\tis going to grab left fork [%d] and right fork [%d].\\n", *philosopher_id, p_name[*philosopher_id], *philosopher_id, (*philosopher_id + 1) % 5); grab_forks(philosopher_id); printf("p_id: [%d] name: [%s] \\thas grabed forks and is eating meal [%d] with left fork [%d] right fork [%d].\\n", *philosopher_id, p_name[*philosopher_id], current_meal, *philosopher_id, (*philosopher_id + 1) % 5); sleep(2); put_away_forks(philosopher_id); printf("p_id: [%d] name: [%s] \\thas finished his meal [%d] with left fork [%d] right fork [%d].\\n", *philosopher_id, p_name[*philosopher_id], current_meal, *philosopher_id, (*philosopher_id + 1) % 5); } void grab_forks(int* philosopher_id){ pthread_mutex_lock(&m); state[*philosopher_id] = 2; test(philosopher_id); pthread_mutex_unlock(&m); pthread_mutex_lock(&s[*philosopher_id]); } void put_away_forks(int* philosopher_id){ int l = (*philosopher_id + 5 - 1) % 5; int r = (*philosopher_id + 1) % 5; pthread_mutex_lock(&m); state[*philosopher_id] = 1; test(&l); test(&r); pthread_mutex_unlock(&m); } void test(int* philosopher_id){ if(state[*philosopher_id] == 2 && state[(*philosopher_id + 5 - 1) % 5] != 3 && state[(*philosopher_id + 1) % 5] != 3){ state[*philosopher_id] = 3; pthread_mutex_unlock(&s[*philosopher_id]); } } void initialize_mutex(){ int i; if(pthread_mutex_init(&m, 0) != 0){ perror("mutex m"); exit(1); } for(i = 0; i < 5; i++){ if(pthread_mutex_init(&s[i], 0) != 0){ perror("mutex s"); exit(1); } pthread_mutex_lock(&s[i]); state[i] = 1; } } void think(int* philosopher_id){ printf("p_id: [%d] name: [%s] \\tis thinking.\\n", *philosopher_id, p_name[*philosopher_id]); sleep(1); }
1
#include <pthread.h> static char envbuf[4096]; extern char **environ; pthread_mutex_t env_mutex; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void thread_init(void) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&env_mutex, &attr); pthread_mutexattr_destroy(&attr); } int getenv_r(const char *name, char *buf, int buflen) { int i, len, olen; pthread_once(&init_done, thread_init); len = strlen(name); pthread_mutex_lock(&env_mutex); for(i = 0; environ[i] != 0; i++) { if((strncmp(name, environ[i], len) == 0)&& (environ[i][len] == '=')) { olen = strlen(&environ[i][len+1]); if(olen >= buflen){ pthread_mutex_unlock(&env_mutex); return(ENOSPC); } strcpy(buf, &environ[i][len+1]); pthread_mutex_unlock(&env_mutex); return 0; } } pthread_mutex_unlock(&env_mutex); return(ENOENT); } int main(int argc, char **argv) { int i=0; getenv_r("PWD", envbuf, 4096); printf("PWD:%s \\n", envbuf); return 0; }
0
#include <pthread.h> char shared_buffer[10]; int shared_count; pthread_mutex_t mutex; unsigned int prod_index = 0; unsigned int cons_index = 0; void * producer(void *arg); void * consumer(void *arg); int main() { pthread_t prod_tid, cons_tid1, cons_tid2; pthread_mutex_init(&mutex, 0); pthread_create(&prod_tid, 0, producer, 0); pthread_create(&cons_tid1, 0, consumer, 0); pthread_create(&cons_tid2, 0, consumer, 0); pthread_join(prod_tid, 0); pthread_join(cons_tid1, 0); pthread_join(cons_tid2, 0); pthread_mutex_destroy(&mutex); return 0; } void * producer(void *arg) { char key; long double usage; double load[1]; int cpu_load; FILE *fp; while (1) { fp = fopen("/proc/loadavg","r"); if(fp == 0){ perror("Error"); } else{ fscanf(fp,"%Lf",&usage); fclose(fp); printf("The current CPU utilization is : %Lf\\n",usage); cpu_load = (int)(usage * 100); printf("The percent of usage is: %d\\n",cpu_load); } scanf("%c", &key); while (1) { pthread_mutex_lock(&mutex); if (shared_count == 10) pthread_mutex_unlock(&mutex); else break; } shared_buffer[prod_index] = key; shared_count++; if (prod_index == 10 - 1) prod_index = 0; else prod_index++; pthread_mutex_unlock(&mutex); } return 0; } void * consumer(void *arg) { char key; int id = (int)pthread_self(); while (1) { while (1) { pthread_mutex_lock(&mutex); if (shared_count == 0) pthread_mutex_unlock(&mutex); else break; } key = shared_buffer[cons_index]; printf("consumer %d %c\\n", id, key); shared_count--; if (cons_index == 10 - 1) cons_index = 0; else cons_index++; pthread_mutex_unlock(&mutex); } return 0; }
1
#include <pthread.h> struct rtpp_pcnt_strm_priv { struct rtpp_pcnt_strm pub; struct rtpp_pcnts_strm cnt; pthread_mutex_t lock; }; static void rtpp_pcnt_strm_dtor(struct rtpp_pcnt_strm_priv *); static void rtpp_pcnt_strm_get_stats(struct rtpp_pcnt_strm *, struct rtpp_pcnts_strm *); static void rtpp_pcnt_strm_reg_pktin(struct rtpp_pcnt_strm *, struct rtp_packet *); struct rtpp_pcnt_strm * rtpp_pcnt_strm_ctor(void) { struct rtpp_pcnt_strm_priv *pvt; struct rtpp_refcnt *rcnt; pvt = rtpp_rzmalloc(sizeof(struct rtpp_pcnt_strm_priv), &rcnt); if (pvt == 0) { goto e0; } pvt->pub.rcnt = rcnt; if (pthread_mutex_init(&pvt->lock, 0) != 0) { goto e1; } pvt->pub.get_stats = &rtpp_pcnt_strm_get_stats; pvt->pub.reg_pktin = &rtpp_pcnt_strm_reg_pktin; CALL_SMETHOD(pvt->pub.rcnt, attach, (rtpp_refcnt_dtor_t)&rtpp_pcnt_strm_dtor, pvt); return ((&pvt->pub)); e1: CALL_SMETHOD(pvt->pub.rcnt, decref); free(pvt); e0: return (0); } static void rtpp_pcnt_strm_dtor(struct rtpp_pcnt_strm_priv *pvt) { rtpp_pcnt_strm_fin(&(pvt->pub)); pthread_mutex_destroy(&pvt->lock); free(pvt); } static void rtpp_pcnt_strm_get_stats(struct rtpp_pcnt_strm *self, struct rtpp_pcnts_strm *ocnt) { struct rtpp_pcnt_strm_priv *pvt; pvt = ((struct rtpp_pcnt_strm_priv *)((char *)(self) - offsetof(struct rtpp_pcnt_strm_priv, pub))); pthread_mutex_lock(&pvt->lock); memcpy(ocnt, &pvt->cnt, sizeof(struct rtpp_pcnts_strm)); pthread_mutex_unlock(&pvt->lock); } static void rtpp_pcnt_strm_reg_pktin(struct rtpp_pcnt_strm *self, struct rtp_packet *pkt) { struct rtpp_pcnt_strm_priv *pvt; double ipi; pvt = ((struct rtpp_pcnt_strm_priv *)((char *)(self) - offsetof(struct rtpp_pcnt_strm_priv, pub))); pthread_mutex_lock(&pvt->lock); pvt->cnt.npkts_in++; if (pvt->cnt.first_pkt_rcv == 0.0) { pvt->cnt.first_pkt_rcv = pkt->rtime; } else { ipi = fabs(pkt->rtime - pvt->cnt.last_pkt_rcv); if (pvt->cnt.longest_ipi < ipi) { pvt->cnt.longest_ipi = ipi; } } if (pvt->cnt.last_pkt_rcv < pkt->rtime) { pvt->cnt.last_pkt_rcv = pkt->rtime; } pthread_mutex_unlock(&pvt->lock); }
0
#include <pthread.h> static int global = 0; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t v = PTHREAD_COND_INITIALIZER; void perror_exit (const char *info) { perror (info); exit (1); } void *count_times (void *args) { int i = 1; while (1) { sleep (1); fprintf (stderr, "second: %d\\n", i++); } return (void *) 0; } void *tfn (void *args) { pthread_mutex_lock (&m); while (global !=100) pthread_cond_wait (&v, &m); fprintf (stderr, "t%d: global = %d\\n", (int) args, global); pthread_mutex_unlock (&m); return (void *) 0; } int main (int argc, char **argv) { if (argc != 2) { fprintf (stderr, "Usage: %s threads-number\\n", argv[0]); return -1; } pthread_mutex_init (&m, 0); pthread_cond_init (&v, 0); pthread_t tid; pthread_create (&tid, 0, count_times, 0); int i; int thread_nums = atoi (argv[1]); for (i = 0; i < thread_nums; i++) if (pthread_create (&tid, 0, tfn, (void *) i) != 0) perror_exit ("pthread_create falied"); sleep (1); pthread_mutex_lock (&m); global = 100; pthread_cond_broadcast (&v); sleep (3); pthread_mutex_unlock (&m); sleep (2); pthread_exit (0); }
1
#include <pthread.h> void* mutex = 0; void lock() { pthread_mutex_lock((pthread_mutex_t*)mutex); } void unlock() { pthread_mutex_unlock((pthread_mutex_t*)mutex); } void lock_init() { mutex = malloc(sizeof(pthread_mutex_t)); if(0 == mutex) return; pthread_mutex_init((pthread_mutex_t*)mutex, 0); } int num = 0; void* print(void* value) { num++; usleep(1000 * 100); printf("-----------------%d, %d\\n", num, syscall(SYS_gettid)); printf("create num:%u\\n", pthread_self()); while(1); } int main() { printf("-----%d------------\\n",50); lock_init(); printf("-----%d------------\\n", 52); int num = 0, i = 0; pthread_t tid; printf("please input you want create pthread num...\\n"); scanf("%d", &num); while(i < num) { printf("%d-----------\\n", i++); int ret = pthread_create(&tid, 0, print, 0); printf("create num:%u\\n", tid); } printf("pthrad created over\\n"); while(1); }
0
#include <pthread.h> int nr; char *filename; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; void *SmartFunction(void *arg) { char *s,command[150],result[10]; unsigned int len; int z; FILE *p; s = (char *) arg; len = snprintf(command,sizeof(command),"grep %s %s|wc -l",s,filename); if(len <= sizeof(command)) { p = popen(command,"r"); fgets(result,sizeof(result),p); z = atoi(result); } pthread_mutex_lock(&mutex1); nr+=z; pthread_mutex_unlock(&mutex1); return 0; } int main(int ac,char **av) { if (ac < 3) { printf("Program should get at least 3 parameters!\\n"); return (0); } else { int i; pthread_t threads[ac]; filename = (char *)malloc(sizeof(char) * strlen(av[1])); strcpy(filename,av[1]); i = 2; while(i < ac) { pthread_create(&threads[i],0,SmartFunction,(void*)av[i]); i++; } i = 2; while(i< ac) { pthread_join(threads[i],0); i++; } printf("The total sum is: %d\\n",nr); } return (0); }
1
#include <pthread.h> int variableManoseada; time_t tiempo; int a; pthread_mutex_t lock; pthread_mutex_t lock2; void tocarVariable(){ int variable = 0; while(1){ pthread_mutex_lock(&lock); pthread_mutex_lock(&lock2); printf("Dentro de los locks del Thread - Numero: %d\\n", variable); pthread_mutex_unlock(&lock2); pthread_mutex_unlock(&lock); variable ++; } } int main(void) { srand((unsigned) time(&tiempo)); pthread_t thread1; variableManoseada = 0; pthread_create(&thread1, 0, (void *)tocarVariable, 0); pthread_mutex_init(&lock, 0); pthread_mutex_init(&lock2, 0); int var = 0; while(1){ pthread_mutex_lock(&lock2); pthread_mutex_lock(&lock); printf("Dentro de los locks del main - Numero: %d\\n", var); pthread_mutex_unlock(&lock); pthread_mutex_unlock(&lock2); var++; } return 0; }
0
#include <pthread.h> struct AgentInfo{ int agent_id; int *num_tickets_p; }; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static void *sell_tickets(void *arg){ struct AgentInfo *st_info = arg; while(1){ pthread_mutex_lock(&mutex); if(*st_info->num_tickets_p == 0){ pthread_mutex_unlock(&mutex); break; } printf("Agent %d sells a ticket %d\\n", st_info->agent_id, *st_info->num_tickets_p); (*st_info->num_tickets_p)--; pthread_mutex_unlock(&mutex); if((rand() % 100) > 90) sleep(1); } printf("Agent %d done!\\n", st_info->agent_id); free(st_info); return 0; } int main(){ int numAgents = 10; int numTickets = 150; int i; struct AgentInfo *st_info; pthread_t tid[numAgents]; srand(time(0)); for(i = 0; i < numAgents; i++){ st_info = malloc(sizeof(struct AgentInfo)); st_info->agent_id = i; st_info->num_tickets_p = &numTickets; pthread_create(tid + i, 0, sell_tickets, (void *)st_info); } for(i = 0; i < numAgents; i++) { pthread_join(tid[i], 0); } pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> int val_a, val_b, val_c; int finished = 0; pthread_mutex_t mutex; pthread_cond_t conditionInput, conditionAdd, conditionPrint; void *add(void *none); void *print(void *none); int main() { int inp_a, inp_b; pthread_t thread_add, thread_print; if( pthread_create(&thread_add, 0, add, 0) ) exit(1); if( pthread_create(&thread_print, 0, print, 0) ) exit(2); if( pthread_mutex_init(&mutex, 0) ) exit(3); if( pthread_cond_init(&conditionInput, 0) ) exit(4); if( pthread_cond_init(&conditionAdd, 0) ) exit(5); if( pthread_cond_init(&conditionPrint, 0) ) exit(6); while( 1 ) { printf("\\n---- Enter two values (exit with entering val_a: 0, val_b: 0) ----\\n\\n"); printf("val_a: "); inp_a = scanf("%d", &val_a); printf("val_b: "); inp_b = scanf("%d", &val_b); if( (val_a == 0 && val_b == 0) ) { printf("Bye bye\\n"); break; } else if( inp_a == 0 || inp_b == 0 ) { printf("Bad input format, bye\\n"); break; } pthread_cond_signal(&conditionInput); pthread_cond_wait(&conditionPrint, &mutex); } pthread_cancel(thread_add); pthread_cancel(thread_print); pthread_cond_destroy(&conditionInput); pthread_cond_destroy(&conditionAdd); pthread_cond_destroy(&conditionPrint); return 0; } void *add(void *none) { while( 1 ) { pthread_mutex_lock(&mutex); pthread_cond_wait(&conditionInput, &mutex); val_c = val_a + val_b; pthread_cond_signal(&conditionAdd); pthread_mutex_unlock(&mutex); } return 0; } void *print(void *none) { while( 1 ) { pthread_mutex_lock(&mutex); pthread_cond_wait(&conditionAdd, &mutex); printf("\\n%d + %d = %d\\n", val_a, val_b, val_c); pthread_cond_signal(&conditionPrint); pthread_mutex_unlock(&mutex); } return 0; }
0
#include <pthread.h> int counter = 0; int readcounter = 0; int reads = 0, writes = 0; int maxcounter = 12; pthread_mutex_t counter_mutex; pthread_mutex_t write_mutex; pthread_cond_t counter_cond; void *write_counter(void *p) { long id = (long)p; int i = 20; while (i --> 0) { pthread_mutex_lock(&write_mutex); counter++; usleep(100); printf("Wrote: thread %ld, counter = %d.\\n", id, counter); writes++; pthread_mutex_unlock(&write_mutex); } return 0; } void *read_counter(void *p) { long id = (long)p; int i = 20; while (i-- > 0) { pthread_mutex_lock(&counter_mutex); if (++readcounter == 1) { pthread_mutex_lock(&write_mutex); } pthread_mutex_unlock(&counter_mutex); usleep(50); printf("Read: thread %ld, counter = %d.\\n", id, counter); pthread_mutex_lock(&counter_mutex); if (--readcounter == 0) pthread_mutex_unlock(&write_mutex); pthread_mutex_unlock (&counter_mutex); reads++; } return 0; } int main(int argc, char *argv[]) { long int i; int num = 10; pthread_t *reader, *writer;; pthread_mutex_init(&counter_mutex, 0); pthread_mutex_init(&write_mutex, 0); reader = malloc(2*num*sizeof(pthread_t)); writer = reader + num; for (i = 0; i < num; i++) { pthread_create(&reader[i], 0, read_counter, (void *)i); pthread_create(&writer[i], 0, write_counter, (void *)(i+num)); } for (i = 0; i < num; i++) { pthread_join(reader[i], 0); pthread_join(writer[i], 0); } printf ("Main(): Waited on %d threads. Final value of counter = %d. Done.\\n", num, counter); printf ("Main(): %d reads. %d writes. \\n", reads, writes); pthread_mutex_destroy(&counter_mutex); pthread_mutex_destroy(&write_mutex); pthread_exit (0); argc = argc; argv = argv; return 0; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int i = 1; void *thread2(void *junk) { pthread_mutex_lock(&mutex); printf("---------------------------------\\n"); printf("thread2: id %lu\\n", pthread_self()); printf("thread2: send signal to thread1...\\n"); if(!pthread_cond_signal(&cond)) printf("thread2: send signal ok!\\n"); else perror("thread2: send signal fail!\\n"); pthread_mutex_unlock(&mutex); return junk; } void *thread1(void* junk) { int i; pthread_t tmp_id; for (i=0; i<1000; i++) { pthread_mutex_lock(&mutex); printf("---------------- %d ------------------\\n", i+1); printf("thread1: create new thread...\\n"); if (!pthread_create(&tmp_id, 0, thread2, 0)) { printf("thread1: OK, id is %lu\\n", (unsigned long)tmp_id); printf("thread1: waiting new thread cond...\\n"); if(!pthread_cond_wait(&cond,&mutex)) printf("thread1: recv cond ok!\\n"); else perror("thread1: recv cond fail!\\n"); } else { perror("thread1: create failed!\\n"); } struct timespec to; to.tv_sec = 0; to.tv_nsec = 1000 * 1000 * 500; nanosleep(&to, 0); pthread_mutex_unlock(&mutex); } return junk; } int main() { pthread_t thread1_id; if (pthread_create(&thread1_id, 0, thread1, 0)) { perror("create thread1:"); return -1; } if (pthread_join(thread1_id, 0)) { perror("join thread1 error:"); return -1; } return 0; }
0
#include <pthread.h> pthread_mutex_t verrou = PTHREAD_MUTEX_INITIALIZER; struct data { int IMAGE[10]; int QuelThreadTravail[10]; }data; void * Fonction1(void *par){ int ma_fonction_numero = 1; struct data *mon_D1 = (struct data*)par; pthread_t moi=pthread_self(); printf("Je suis %i le premier thread\\n",(int)moi); for(int i=0; i<10;i++){ pthread_mutex_lock(&verrou); mon_D1->IMAGE[i]=5; mon_D1->QuelThreadTravail[i]=ma_fonction_numero; printf("Le thread %i travail sur la zone Z%i de l'image\\n",mon_D1->QuelThreadTravail[i],i); pthread_mutex_unlock(&verrou); } printf("Je suis %i le premier thread j'ai fini mon travail.\\n",(int)moi); pthread_exit(0); } void * Fonction2( void * par){ int ma_fonction_numero = 2; pthread_t moi=pthread_self(); struct data *mon_D1 = (struct data*)par; printf("Je suis %i le second thread\\n",(int)moi); for(int i=0;i<10;i++){ pthread_mutex_lock(&verrou); while(mon_D1->QuelThreadTravail[i]!=1){ pthread_mutex_unlock(&verrou); printf("Jattend que le 1-er thread ait finit de travail sur la case %i\\n",i); pthread_mutex_lock(&verrou); } mon_D1->IMAGE[i]=mon_D1->IMAGE[i]+3; mon_D1->QuelThreadTravail[i]++; printf("Le thread %i travail sur la zone Z%i de l'image\\n",mon_D1->QuelThreadTravail[i],i); pthread_mutex_unlock(&verrou); } printf("Je suis %i le second thread j'ai fini mon travail.\\n",(int)moi); pthread_exit(0); } int main(){ srand(time(0)); pthread_t T1; pthread_t T2; struct data D1; for(int i=0;i<10;i++){ D1.IMAGE[i]=0; D1.QuelThreadTravail[i]=0; } pthread_create(&T2,0,Fonction2,&D1); pthread_create(&T1,0,Fonction1,&D1); pthread_join(T1,0); pthread_join(T2,0); return 0; }
1
#include <pthread.h> pthread_mutex_t a; pthread_cond_t dispo, piece; int place=5; void* machineA() { while (1) { pthread_mutex_lock(&a); printf("Machine A crée une pièce.\\n"); while (place==0) { printf("Le panier est plein...\\n"); pthread_cond_wait(&dispo, &a); } printf("Machine A jette une pièce dans le panier.\\n"); place--; pthread_mutex_unlock(&a); if (place==4) pthread_cond_signal(&piece); sleep (2); } } void* machineB() { while (1) { pthread_mutex_lock(&a); while (place==5) { printf(" Le panier est vide !\\n"); pthread_cond_wait(&piece, &a); } printf(" Machine B récolte une pièce dans le panier.\\n"); place++; pthread_mutex_unlock(&a); printf(" Machine B traite une pièce.\\n"); if (place==1) pthread_cond_signal(&dispo); sleep(3); } } int main(int argc, char** argv) { pthread_t M1, M2; pthread_mutex_init(&a, 0); pthread_cond_init(&piece, 0); pthread_cond_init(&dispo, 0); pthread_create(&M1, 0, machineA, 0); pthread_create(&M2, 0, machineB, 0); pthread_join(M2,0); return 0; }
0
#include <pthread.h> int numOfPassengersOnBus; void* print_message(void* ptr); pthread_mutex_t verrou; int main(int argc, char* argv[]) { pthread_t tProducer, tConsumer1, tConsumer2; const char* msg1 = "Producer"; const char* msg2 = "Consumer A"; numOfPassengersOnBus = 0; pthread_mutex_init(&verrou, 0); int r1 = pthread_create(&tProducer, 0, print_message, (void*)msg1 ); int r2 = pthread_create(&tConsumer1, 0, print_message, (void*)msg2 ); pthread_join(tProducer, 0); pthread_join(tConsumer1, 0); return 0; } void* print_message(void* ptr) { srand(time(0)); char* msg = (char*) ptr; while(1) { if(msg[0]=='P') { pthread_mutex_lock(&verrou); while(numOfPassengersOnBus<=0) { numOfPassengersOnBus++; printf("%s produced %d\\n", msg, numOfPassengersOnBus); } pthread_mutex_unlock(&verrou); sleep(rand()%2); } else { pthread_mutex_lock(&verrou); while(numOfPassengersOnBus>0) { numOfPassengersOnBus--; printf("%s consumed %d\\n", msg, numOfPassengersOnBus); } pthread_mutex_unlock(&verrou); sleep(rand()%4); } } return 0; }
1
#include <pthread.h> { int global; pthread_mutex_t glock; int locals[4]; pthread_mutex_t llocks[4]; int threshold; } counter_t; counter_t *c; void init(counter_t *c, int threshold) { c->threshold = threshold; c->global = 0; pthread_mutex_init(&c->glock, 0); int i; for(i = 0; i < 4; i++) { c->locals[i] = 0; pthread_mutex_init(&c->llocks[i], 0); } } void update(counter_t *c, int thread_id, int amt) { pthread_mutex_lock(&c->llocks[thread_id]); c->locals[thread_id] += amt; if(c->locals[thread_id] >= c->threshold) { pthread_mutex_lock(&c->glock); c->global += c->locals[thread_id]; pthread_mutex_unlock(&c->glock); c->locals[thread_id] = 0; } pthread_mutex_unlock(&c->llocks[thread_id]); } void mandate_update(counter_t *c, int thread_id) { pthread_mutex_lock(&c->llocks[thread_id]); pthread_mutex_lock(&c->glock); c->global += c->locals[thread_id]; c->locals[thread_id] = 0; pthread_mutex_unlock(&c->glock); pthread_mutex_unlock(&c->llocks[thread_id]); } int get(counter_t *c) { int i; for(i = 0; i < 4; i++) { mandate_update(c, i); } pthread_mutex_lock(&c->glock); int val = c->global; pthread_mutex_unlock(&c->glock); return val; } void *main_update(void *arg) { int val = get(c); while(val < 400000) { int thread_id = *((int*)arg); update(c, thread_id, 1); val = get(c); } return 0; } void *main_get() { int val = get(c); while(val < 400000) { val = get(c); printf("current global counter is : %d\\n", val); } printf("global counter : %d\\n", val); return 0; } int main() { c = malloc(sizeof *c); init(c, 100); pthread_t local_counters[4]; pthread_t global_counter; int local_nums[4]; pthread_create(&global_counter, 0, main_get, 0); int i; for(i = 0; i < 4; i++) { local_nums[i] = i; pthread_create(&local_counters[i], 0, main_update, &local_nums[i]); } pthread_join(global_counter, 0); for(i = 0; i < 4; i++) pthread_join(local_counters[i], 0); return 0; }
0
#include <pthread.h> static pthread_mutex_t pthread_file_locks[OPEN_MAX] = { PTHREAD_MUTEX_INITIALIZER }; static inline pthread_mutex_t * pthread_fd_lock(int fd) { pthread_mutex_t * m = &pthread_file_locks[fd]; m->m_kind = PTHREAD_MUTEX_RECURSIVE_NP; return m; } void flockfile(FILE *stream) { int fd = fileno(stream); if (fd >= 0 && fd < OPEN_MAX) pthread_mutex_lock(pthread_fd_lock(fd)); } void funlockfile(FILE *stream) { int fd = fileno(stream); if (fd >= 0 && fd < OPEN_MAX) pthread_mutex_unlock(pthread_fd_lock(fd)); } int ftrylockfile(FILE *stream) { int fd = fileno(stream); if (fd >= 0 && fd < OPEN_MAX) return pthread_mutex_trylock(pthread_fd_lock(fd)); else return -1; } void __ffreelockfile(int fd) { if (fd >= 0 && fd < OPEN_MAX) { pthread_mutex_init(&pthread_file_locks[fd], 0); } } void __fresetlockfiles() { int fd; for (fd = 0; fd < OPEN_MAX; fd++) pthread_mutex_init(&pthread_file_locks[fd], 0); }
1
#include <pthread.h> struct foo { int f_count; pthread_mutex_t f_lock; struct foo *f_next; int f_id; }; struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo * foo_alloc(void) { struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) == 0) return 0; fp->f_count = 1; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return 0; } idx = (((unsigned long)fp) % 29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } struct foo * foo_find(int id) { struct foo *fp; int i; pthread_mutex_lock(&hashlock); for (i=0; i<29; i++) { for (fp=fh[i]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { foo_hold(fp); pthread_mutex_unlock(&hashlock); return(fp); } } } pthread_mutex_unlock(&hashlock); return(fp); } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&fp->f_lock); if (fp->f_count == 1) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&fp->f_lock); if (fp->f_count != 1) { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); pthread_mutex_unlock(&hashlock); return; } idx = (((unsigned long)fp) % 29); tfp = fh[idx]; if (tfp == fp) { fh[idx] = fp->f_next; } else { while (tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); } } int main(void) { exit(0); }
0
#include <pthread.h> pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; void * threadA(void *param ) { int i; for (i = 0; i < 5; i++) { pthread_mutex_lock(&mutex1); printf("threadA --> %d iteration\\n", i); sleep(rand() % 3); pthread_mutex_unlock(&mutex2); } pthread_exit(0); } void * threadB(void *param ) { int i; for (i = 0; i < 5; i++) { pthread_mutex_lock(&mutex2); printf("threadB --> %d iteration\\n", i); sleep(rand() % 3); pthread_mutex_unlock(&mutex1); } pthread_exit(0); } int main() { pthread_t tidA, tidB; srand(time(0)); pthread_setconcurrency(3); if (pthread_create(&tidA, 0, threadA, 0) || pthread_create(&tidB, 0, threadB, 0)) { perror("pthread_create"); abort(); } if (pthread_join(tidA, 0) != 0 || pthread_join(tidB, 0) != 0) { perror("pthread_join"); abort(); } return 0; }
1
#include <pthread.h> int calcSunriseSunset(double lat, double lon, int day, int month, int year, double zenith, int localOffset, double *riseTime, double *setTime) { int retVal=SUN_RISES_AND_SETS; lon=-lon; double N=floor(275*month/9)-(floor((month+9)/12)*(1+floor((year-4*floor(year/4)+2)/3)))+day-30; double lngHour=Rad2Deg(lon)/15; double localT=-1; short i=0; for(i=0;i<2;i++) { double t; if(i==0) t=N+((6-lngHour)/24); else t=N+((18-lngHour)/24); double M=0.9856*t-3.289; double L=M+(1.916*sin(Deg2Rad(M)))+(0.020*sin(Deg2Rad(2*M)))+282.634; if(L<0) L+=360; else if(L>360) L-=360; double RA=Rad2Deg(absAngle(atan(0.91764*tan(Deg2Rad(L))))); double Lquadrant=(floor(L/90))*90; double RAquadrant=(floor(RA/90))*90; RA+=Lquadrant-RAquadrant; RA=RA/15; double sinDec=0.39782*sin(Deg2Rad(L)); double cosDec=cos(asin(sinDec)); double cosH=(cos(zenith)-(sinDec*sin(lat)))/(cosDec*cos(lat)); if(cosH>=-1 && cosH<=1) { double H; if(i==0) H=360-Rad2Deg(acos(cosH)); else H=Rad2Deg(acos(cosH)); H=H/15; double T=H+RA-(0.06571*t)-6.622; double UT=T-lngHour; localT=UT+localOffset; if(localT<0) localT+=24; else if(localT>24) localT-=24; } else { if(i==0) retVal=SUN_NEVER_RISES; else retVal=SUN_NEVER_SETS; } if(i==0) *riseTime=localT; else *setTime=localT; } return retVal; } int calcSunriseSunsetWithInternalClockTime(double lat, double lon, double *riseTime, double *setTime) { struct tm time_str; long timestamp=time(0); time_str=*localtime(&timestamp); int year=time_str.tm_year+1900; int month=time_str.tm_mon+1; int day=time_str.tm_mday; return calcSunriseSunset(lat,lon,day,month,year,config.sunZenith,config.timeZone,riseTime,setTime); } void calcFlightPlanEphemerides(double lat, double lon, bool isDeparture) { double riseTime, setTime; if(gps.fixMode>MODE_NO_FIX) { pthread_mutex_lock(&gps.mutex); calcSunriseSunset(lat,lon,gps.day,gps.month,gps.year,config.sunZenith,0,&riseTime,&setTime); pthread_mutex_unlock(&gps.mutex); } else calcSunriseSunsetWithInternalClockTime(lat,lon,&riseTime,&setTime); if(isDeparture) { convertDecimal2DegMinSec(riseTime,&Ephemerides.deparure.sunriseHour,&Ephemerides.deparure.sunriseMin,&Ephemerides.deparure.sunriseSec); convertDecimal2DegMinSec(setTime,&Ephemerides.deparure.sunsetHour,&Ephemerides.deparure.sunsetMin,&Ephemerides.deparure.sunsetSec); } else { convertDecimal2DegMinSec(riseTime,&Ephemerides.destination.sunriseHour,&Ephemerides.destination.sunriseMin,&Ephemerides.destination.sunriseSec); convertDecimal2DegMinSec(setTime,&Ephemerides.destination.sunsetHour,&Ephemerides.destination.sunsetMin,&Ephemerides.destination.sunsetSec); } }
0
#include <pthread.h> void *sum(void *p); unsigned long int psum[8]; unsigned long int sumtotal = 0; unsigned long int n; int numthreads; pthread_mutex_t mutex; int main(int argc, char **argv) { pthread_t tid[8]; int i, myid[8]; struct timeval start, end; gettimeofday(&start, 0); scanf("%lu %d", &n, &numthreads); for (i = 0; i < numthreads; i++) { myid[i] = i; psum[i] = 0.0; pthread_create(&tid[i], 0, sum, &myid[i]); } for (i = 0; i < numthreads; i++) { pthread_join(tid[i], 0); } pthread_mutex_destroy(&mutex); gettimeofday(&end, 0); long spent = (end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec); printf("%lu\\n%ld\\n", sumtotal, spent); return 0; } void *sum(void *p) { int myid = *((int *) p); unsigned long int start = (myid * (unsigned long int) n) / numthreads; unsigned long int end = ((myid + 1) * (unsigned long int) n) / numthreads; unsigned long int i; for (i = start; i < end; i++) { psum[myid] += 2; } pthread_mutex_lock(&mutex); sumtotal += psum[myid]; pthread_mutex_unlock(&mutex); return 0 ; }
1
#include <pthread.h> int voti[2]; char film[2][40]; int pareri; pthread_mutex_t m; } sondaggio; sondaggio S; void init(sondaggio *s) { int i; s->pareri=0; for(i=0;i<2; i++) { printf("Qual è il nome del film numero %d ?", i+1); gets(s->film[i]); s->voti[i]=0; } pthread_mutex_init(&s->m, 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); } void *spettatore(void *t) { long tid, result=0; tid = (int)t; esprimi_pareri(&S, tid); pthread_exit((void*) result); } int main (int argc, char *argv[]) { pthread_t thread[3]; int rc, i_max; long t; float media, max; void *status; init(&S); 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); } 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]/3; printf("Valutazione media del film n.%ld (%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); return 0; }
0
#include <pthread.h> int buff[10]; int buff_index; pthread_mutex_t buff_mutex; pthread_cond_t buff_cond_full, buff_cond_empty; int push_front(int val) { if(buff_index < 10) { buff[buff_index++] = val; return 0; } else return -1; } int pop_front() { if(buff_index > 0) return buff[--buff_index]; else return -1; } void* producer(void* arg) { int result; while(1) { for(int i = 0 ; i < 20 ; i++) { pthread_mutex_lock(&buff_mutex); if(buff_index == 10) pthread_cond_wait(&buff_cond_empty, &buff_mutex); result = push_front(i); printf("producer : %d | result = %d\\n", i, result); pthread_cond_signal(&buff_cond_full); pthread_mutex_unlock(&buff_mutex); } } } void* consumer(void* arg) { int temp; while(1) { pthread_mutex_lock(&buff_mutex); if(buff_index == 0) pthread_cond_wait(&buff_cond_full, &buff_mutex); temp = pop_front(); printf("consumer : %d\\n", temp); pthread_cond_signal(&buff_cond_empty); pthread_mutex_unlock(&buff_mutex); } } int main() { pthread_t th1, th2; pthread_mutex_init(&buff_mutex, 0); pthread_cond_init(&buff_cond_empty, 0); pthread_cond_init(&buff_cond_full, 0); pthread_create(&th1, 0, producer, 0); pthread_create(&th2, 0, consumer, 0); pthread_join(th1, 0); pthread_join(th2, 0); return 0; }
1
#include <pthread.h> extern char **environ; pthread_mutex_t env_lock = PTHREAD_MUTEX_INITIALIZER; pthread_key_t key; pthread_once_t once = PTHREAD_ONCE_INIT; void key_create(void) { pthread_key_create(&key, free); } char * mygetenv(char *name) { int i; char *ptr; char *buf = 0; pthread_once(&once, key_create); buf = pthread_getspecific(key); if (!buf) { buf = (char *)malloc(512); if (!buf) { perror("malloc"); return 0; } pthread_setspecific(key, buf); } pthread_mutex_lock(&env_lock); for (i = 0; environ[i] != 0; i++) { if (strncmp(name, environ[i], strlen(name)) == 0 && environ[i][strlen(name)] == '=') { ptr = environ[i] + strlen(name) + 1; strcpy(buf, ptr); pthread_mutex_unlock(&env_lock); return buf; } } pthread_mutex_unlock(&env_lock); return 0; } int main(void) { int i = 0; char *ptr = mygetenv("PATH"); printf("%s\\n", ptr); free(ptr); exit(0); }
0
#include <pthread.h> int food = 10; int portions = 0; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_cooker = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_cannibal = PTHREAD_COND_INITIALIZER; void * cooker (void * arg); void * cannibals (void * arg); int main (int argc, char * argv[]) { pthread_t cookerThread, cannibalThread[100]; int i = 0, * id = 0; srand (time(0)); for (i = 0; i < 100; i++) { id = (int *) malloc (sizeof (int)); *id = i; if (pthread_create (&cannibalThread[i], 0, cannibals, (void *) id)) { printf ("Failed to create thread cannibalThread number %d\\n", i); return -1; } } if (pthread_create (&cookerThread, 0, cooker, (void *) id)) { printf ("Fail at creating cookerThread\\n"); return -1; } if (pthread_join (cannibalThread[0], 0)) { printf ("Could not do the join\\n"); return -1; } return 0; } void * cooker (void * arg) { int i = *((int *)arg); while (1) { pthread_mutex_lock (&lock); while (food > 0) pthread_cond_wait (&cond_cooker, &lock); portions = rand()%97 + 3; printf ("Cooker is cooking %d portions.\\n", portions); sleep (5); food = portions; printf ("Cooker has already cooked %d portions.\\nCooker is sleeping.\\n", portions); pthread_cond_broadcast (&cond_cannibal); pthread_mutex_unlock (&lock); } pthread_exit (0); } void * cannibals (void * arg) { int i = *((int *) arg); while (1) { pthread_mutex_lock (&lock); while (food == 0) { printf ("Cannibal %d is waiting for food.\\n", i); pthread_cond_wait (&cond_cannibal, &lock); } food--; printf ("Cannibal %d is eating. Food available: %d\\n", i, food); if (food == 0) { printf ("Cooker waken up by cannibal %d!\\n", i); pthread_cond_signal (&cond_cooker); } pthread_mutex_unlock (&lock); } pthread_exit (0); }
1
#include <pthread.h> void *thread_function(void *arg); pthread_mutex_t work_mutex; char work_area[1024]; int time_to_exit = 0; int main() { int res; pthread_t a_thread; void *thread_result; res = pthread_mutex_init(&work_mutex, 0); if (res != 0) { perror("Mutex initialization failed"); exit(1); } res = pthread_create(&a_thread, 0, thread_function, 0); if (res != 0) { perror("Thread creation failed"); exit(1); } pthread_mutex_lock(&work_mutex); printf("Input some text. Enter 'end' to finish\\n"); while(!time_to_exit) { fgets(work_area, 1024, stdin); pthread_mutex_unlock(&work_mutex); while(1){ pthread_mutex_lock(&work_mutex); if (work_area[0] != '\\0') { pthread_mutex_unlock(&work_mutex); sleep(1); } else { break; } } } pthread_mutex_unlock(&work_mutex); printf("\\nWaiting for thread ot finish...\\n"); res = pthread_join(a_thread, &thread_result); if (res != 0) { perror("Thread join failed"); exit(1); } printf("Thread joined\\n"); pthread_mutex_destroy(&work_mutex); exit(1); } void *thread_function(void *arg) { sleep(1); pthread_mutex_lock(&work_mutex); while(strncmp("end", work_area, 3) != 0) { printf("You input %d characters\\n", strlen(work_area) - 1); work_area[0] = '\\0'; pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); while (work_area[0] == '\\0') { pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); } } time_to_exit = 1; work_area[0] = '\\0'; pthread_mutex_unlock(&work_mutex); pthread_exit(0); }
0
#include <pthread.h> static const char SINGLENODE_CLVMD_SOCKNAME[] = "\\0singlenode_clvmd"; static int listen_fd = -1; static int init_comms() { struct sockaddr_un addr; listen_fd = socket(PF_UNIX, SOCK_STREAM, 0); if (listen_fd < 0) { DEBUGLOG("Can't create local socket: %s\\n", strerror(errno)); return -1; } fcntl(listen_fd, F_SETFD, 1); memset(&addr, 0, sizeof(addr)); memcpy(addr.sun_path, SINGLENODE_CLVMD_SOCKNAME, sizeof(SINGLENODE_CLVMD_SOCKNAME)); addr.sun_family = AF_UNIX; if (bind(listen_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { DEBUGLOG("Can't bind local socket: %s\\n", strerror(errno)); close(listen_fd); return -1; } if (listen(listen_fd, 10) < 0) { DEBUGLOG("Can't listen local socket: %s\\n", strerror(errno)); close(listen_fd); return -1; } return 0; } static int _init_cluster(void) { int r; r = init_comms(); if (r) return r; DEBUGLOG("Single-node cluster initialised.\\n"); return 0; } static void _cluster_closedown(void) { close(listen_fd); DEBUGLOG("cluster_closedown\\n"); destroy_lvhash(); } static void _get_our_csid(char *csid) { int nodeid = 1; memcpy(csid, &nodeid, sizeof(int)); } static int _csid_from_name(char *csid, const char *name) { return 1; } static int _name_from_csid(const char *csid, char *name) { sprintf(name, "%x", 0xdead); return 0; } static int _get_num_nodes() { return 1; } static void _add_up_node(const char *csid) { } static int _cluster_do_node_callback(struct local_client *master_client, void (*callback)(struct local_client *, const char *csid, int node_up)) { return 0; } int _lock_file(const char *file, uint32_t flags); static int *_locks = 0; static char **_resources = 0; static int _lock_max = 1; static pthread_mutex_t _lock_mutex = PTHREAD_MUTEX_INITIALIZER; static int _lock_resource(const char *resource, int mode, int flags, int *lockid) { int *_locks_1; char **_resources_1; int i, j; DEBUGLOG("lock_resource '%s', flags=%d, mode=%d\\n", resource, flags, mode); retry: pthread_mutex_lock(&_lock_mutex); for (i = 1; i < _lock_max; ++i) { if (!_resources[i]) break; if (!strcmp(_resources[i], resource)) { if ((_locks[i] & LCK_WRITE) || (_locks[i] & LCK_EXCL)) { DEBUGLOG("%s already write/exclusively locked...\\n", resource); goto maybe_retry; } if ((mode & LCK_WRITE) || (mode & LCK_EXCL)) { DEBUGLOG("%s already locked and WRITE/EXCL lock requested...\\n", resource); goto maybe_retry; } } } if (i == _lock_max) { _locks_1 = dm_realloc(_locks, 2 * _lock_max * sizeof(int)); if (!_locks_1) return 1; _locks = _locks_1; _resources_1 = dm_realloc(_resources, 2 * _lock_max * sizeof(char *)); if (!_resources_1) { return 1; } _resources = _resources_1; for (j = _lock_max; j < 2 * _lock_max; ++j) _resources[j] = 0; _lock_max = 2 * _lock_max; } *lockid = i; _locks[i] = mode; _resources[i] = dm_strdup(resource); DEBUGLOG("%s locked -> %d\\n", resource, i); pthread_mutex_unlock(&_lock_mutex); return 0; maybe_retry: pthread_mutex_unlock(&_lock_mutex); if (!(flags & LCK_NONBLOCK)) { usleep(10000); goto retry; } return 1; } static int _unlock_resource(const char *resource, int lockid) { DEBUGLOG("unlock_resource: %s lockid: %x\\n", resource, lockid); if(!_resources[lockid]) { DEBUGLOG("(%s) %d not locked\\n", resource, lockid); return 1; } if(strcmp(_resources[lockid], resource)) { DEBUGLOG("%d has wrong resource (requested %s, got %s)\\n", lockid, resource, _resources[lockid]); return 1; } dm_free(_resources[lockid]); _resources[lockid] = 0; return 0; } static int _is_quorate() { return 1; } static int _get_main_cluster_fd(void) { return listen_fd; } static int _cluster_fd_callback(struct local_client *fd, char *buf, int len, const char *csid, struct local_client **new_client) { return 1; } static int _cluster_send_message(const void *buf, int msglen, const char *csid, const char *errtext) { return 0; } static int _get_cluster_name(char *buf, int buflen) { strncpy(buf, "localcluster", buflen); buf[buflen - 1] = 0; return 0; } static struct cluster_ops _cluster_singlenode_ops = { .cluster_init_completed = 0, .cluster_send_message = _cluster_send_message, .name_from_csid = _name_from_csid, .csid_from_name = _csid_from_name, .get_num_nodes = _get_num_nodes, .cluster_fd_callback = _cluster_fd_callback, .get_main_cluster_fd = _get_main_cluster_fd, .cluster_do_node_callback = _cluster_do_node_callback, .is_quorate = _is_quorate, .get_our_csid = _get_our_csid, .add_up_node = _add_up_node, .reread_config = 0, .cluster_closedown = _cluster_closedown, .get_cluster_name = _get_cluster_name, .sync_lock = _lock_resource, .sync_unlock = _unlock_resource, }; struct cluster_ops *init_singlenode_cluster(void) { if (!_init_cluster()) return &_cluster_singlenode_ops; else return 0; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; char buf[10][1024]; int in; int out; int size; char* element[10]; }Ring_st; void QueueInit(Ring_st * ring) { int i; ring->in = 0; ring->out = 0; ring->size = 10; for(i=0;i<10;i++) ring->element[i] = buf[i]; } char* QueuePut(Ring_st * ring) { char* ptr = 0; if(ring->in == (( ring->out - 1 + ring->size) % ring->size)) { return ptr; } ptr = ring->element[ring->in]; return ptr; } void QueuePutUpdate(Ring_st * ring) { ring->in = (ring->in + 1) % ring->size; } char* QueueGet(Ring_st * ring) { char* ptr = 0; if(ring->in == ring->out) { return ptr; } ptr = ring->element[ring->out]; return ptr; } void QueueGutUpdate(Ring_st * ring) { ring->out = (ring->out + 1) % ring->size; } void *producer(void *ptr) { int i = 0; char *tmp; char data[1024]; Ring_st *ring = (Ring_st *)ptr; printf("I'm a producer\\n"); while (1) { pthread_mutex_lock(&mutex); usleep(2*900); tmp = (char *) QueuePut(ring); if(tmp != 0) { sprintf(data,"%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",i ,i ,i ,i ,i, i ,i ,i ,i ,i); memcpy(tmp, data, strlen(data)); printf("\\x1B[34min :Queue[%d] =%s\\033[0m\\r\\n", ring->in, ring->element[ring->in]); fflush(stdout); QueuePutUpdate(ring); } pthread_mutex_unlock(&mutex); i = i + 1; } pthread_exit(0); } void *consumer(void *ptr) { char *tmp; Ring_st *ring = (Ring_st *)ptr; printf("I'm a consumer\\n"); while(1) { pthread_mutex_lock(&mutex); usleep(900); tmp = (char *) QueueGet(ring); if(tmp != 0) { printf("\\x1B[32mout :Queue[%d] =%s\\033[0m\\r\\n", ring->out, ring->element[ring->out]);fflush(stdout); QueueGutUpdate(ring); } pthread_mutex_unlock(&mutex); } pthread_exit(0); } int main() { pthread_t producer_thread, consumer_thread; Ring_st ring; QueueInit(&ring); pthread_create(&consumer_thread,0,consumer,(void *)&ring); pthread_create(&producer_thread,0,producer,(void *)&ring); pthread_join(consumer_thread,0); return 0; }
0
#include <pthread.h> pthread_mutex_t messageMutex = PTHREAD_MUTEX_INITIALIZER; char * msgSend, * msgRcv; char beaconsLocation[NUMBER_BEACONS][20]; void initBeaconsLocation(char beacon[NUMBER_BEACONS][20], int size) { float margin = 1.1; sprintf(beacon[0], "%.2f %.2f ", margin, margin); sprintf(beacon[1], "%.2f %.2f ", margin, (float) H/2); sprintf(beacon[2], "%.2f %.2f ", margin, (float) H - margin); sprintf(beacon[3], "%.2f %.2f ", (float) W - margin, (float) H - margin); sprintf(beacon[4], "%.2f %.2f ", (float) W - margin, (float) H/2); sprintf(beacon[5], "%.2f %.2f ", (float) W - margin, margin); sprintf(beacon[6], "%.2f %.2f ", (float) W/2, (float) H/4 - margin); sprintf(beacon[7], "%.2f %.2f ", (float) W/2, (float) 3*H/4 - margin); } void * receiverThread(void* arg) { int lg_message = LG_MESS_DEFAUT; initReceiver(); setUser(1); while(1) recevoir(lg_message, msgRcv); return 0; } void * coordinatesThread(void* arg) { int lg_message = LG_MESS_DEFAUT; int n = *((int*)arg); while (1) { sleep(1); pthread_mutex_lock(&messageMutex); emettre(lg_message, msgSend, "11 "); pthread_mutex_unlock(&messageMutex); } return 0; } int main (int argc, char** argv) { int choix; int lg_message = LG_MESS_DEFAUT; int *n; char * msg = malloc(sizeof(char)*lg_message); pthread_mutex_t displayMutex = PTHREAD_MUTEX_INITIALIZER; initBeaconsLocation(beaconsLocation, (int) NUMBER_BEACONS); n = malloc(sizeof(int)); *n = 1; char * adr = malloc(12*sizeof(char)); adr = ADR_DIST; msgSend = malloc(sizeof(char)*lg_message); msgRcv = malloc(sizeof(char)*lg_message); pthread_t tid[2]; pthread_create(&tid[0], 0, receiverThread, 0); usleep(30000); initSender(adr); pthread_create(&tid[1], 0, coordinatesThread, n); pthread_mutex_lock(&displayMutex); printf("\\n Drone position : \\n"); printf(" Send : \\n\\n"); pthread_mutex_unlock(&displayMutex); while(1) { pthread_mutex_lock(&displayMutex); printf("What do you want to do ?\\n"); printf("0 -> Calibration (drone must lay flat on the floor)\\n"); printf("1 -> Magnetic calibration\\n"); printf("2 -> landing\\n"); printf("3 -> take off\\n"); printf("4 -> move roll \\n"); printf("5 -> move pitch\\n"); printf("6 -> move pitch roll\\n"); printf("7 -> emergency\\n"); printf("8 -> anti emergency\\n"); printf("9 -> start mission\\n"); printf("10 -> stop mission\\n"); printf("-1 to close the programm\\n"); pthread_mutex_unlock(&displayMutex); scanf("%d", &choix); getchar(); pthread_mutex_lock(&displayMutex); printf("\\033[%dA", 2); printf("\\033[%dM", 1); printf("\\033[%dJ", 2); pthread_mutex_unlock(&displayMutex); if (choix >= 0 && choix < 10) { sprintf(msg, " %d ", choix); } else { sprintf(msg, "%d ", choix); } if (choix == 9) { pthread_mutex_lock(&displayMutex); printf("\\033[%dA", 12); printf("\\033[%dM", 12); printf("Choose your beacon (from 0 to 7)\\n"); printf("0 -> %s\\n", beaconsLocation[0]); printf("1 -> %s\\n", beaconsLocation[1]); printf("2 -> %s\\n", beaconsLocation[2]); printf("3 -> %s\\n", beaconsLocation[3]); printf("4 -> %s\\n", beaconsLocation[4]); printf("5 -> %s\\n", beaconsLocation[5]); printf("6 -> %s\\n", beaconsLocation[6]); printf("7 -> %s\\n", beaconsLocation[7]); printf("\\n\\n"); pthread_mutex_unlock(&displayMutex); scanf("%d", &choix); strcat(msg, beaconsLocation[choix]); if (choix >= 0 && choix <=7) { pthread_mutex_lock(&messageMutex); emettre(lg_message, msgSend, msg); pthread_mutex_unlock(&messageMutex); } else { pthread_mutex_lock(&displayMutex); printf("incorrect choice\\n"); pthread_mutex_unlock(&displayMutex); } pthread_mutex_lock(&displayMutex); printf("\\033[%dA", 12); printf("\\033[%dM", 12); printf("\\033[%dJ", 2); pthread_mutex_unlock(&displayMutex); } else if (choix >= 0 && choix <= 10) { pthread_mutex_lock(&messageMutex); emettre(lg_message, msgSend, msg); pthread_mutex_unlock(&messageMutex); } else if (choix == -1) { pthread_cancel(tid[0]); pthread_cancel(tid[1]); closeSender(); closeReceiver(); break; } else { pthread_mutex_lock(&displayMutex); printf("incorrect choice\\n"); pthread_mutex_unlock(&displayMutex); } } return 0; }
1
#include <pthread.h> pthread_mutex_t bookLock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t rwCondition = PTHREAD_COND_INITIALIZER; int buffer[5] = {1,2,3,4,5}; int writing = 0; int reading = 0; int writers = 0; void *reader(void *param) { int id = (int) param; pthread_mutex_lock(&bookLock); while (writing || writers) { printf("R%d: Não estou lendo.\\n", id); printf("~DEBUG: writers = %d\\twriting = %d\\n", writers, writing); pthread_cond_wait(&rwCondition, &bookLock); } reading++; printf("R%d: Estou lendo.\\n", id); pthread_cond_broadcast(&rwCondition); pthread_mutex_unlock(&bookLock); pthread_mutex_lock(&bookLock); printf("R%d: Já li.\\n", id); reading--; pthread_cond_broadcast(&rwCondition); pthread_mutex_unlock(&bookLock); } void *writer(void *param) { int id = (int) param; pthread_mutex_lock(&bookLock); if (writers < 2) writers++; while (reading || writing) { printf("W%d: Esperando minha vez de escrever.\\n", id); printf("~DEBUG: reading = %d\\twriting = %d\\twriters = %d\\n", reading, writing, writers); pthread_cond_wait(&rwCondition, &bookLock); } writing++; printf("W%d: Estou escrevendo.\\n", id); pthread_mutex_unlock(&bookLock); pthread_mutex_lock(&bookLock); writing = 0; writers--; printf("W%d: Já escrevi.\\n", id); printf("Writers = %d\\n", writers); pthread_cond_broadcast(&rwCondition); pthread_mutex_unlock(&bookLock); } int main(int argc, char const *argv[]) { pthread_t readers[3]; pthread_t writers[2]; while (1) { for (size_t i = 0; i < 2; i++) pthread_create(&writers[i], 0, writer, (void *) i); for (size_t i = 0; i < 3; i++) pthread_create(&readers[i], 0, reader, (void *) i); } return 0; }
0
#include <pthread.h> pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER; int isGreen1 (int s) { return s == 0; } int isOrange1(int s) { return s == 1; } int isRed1(int s) { return s == 2; } void * signal1(void* d) { int status = 0; b1: printf("1 -> GREEN\\n"); sleep(2); status = 1; printf("1 -> ORANGE\\n"); sleep(1); status = 2; printf("1 -> RED\\n"); pthread_mutex_unlock(&m1); pthread_mutex_lock(&m2); status = 0; printf("1 -> GREEN\\n"); sleep(2); status = 1; printf("1 -> ORANGE\\n"); sleep(1); status = 2; printf("1 -> RED\\n"); pthread_mutex_unlock(&m1); e1: pthread_exit(0); } void * signal2(void* d) { int status = 2; b2: pthread_mutex_lock(&m1); status = 0; printf("2 -> GREEN\\n"); sleep(2); status = 1; printf("2 -> ORANGE\\n"); sleep(1); status = 2; printf("2 -> RED\\n"); pthread_mutex_unlock(&m2); e2: pthread_exit(0); } int main() { pthread_t t1, t2; printf("Start\\n"); pthread_mutex_lock(&m1); pthread_mutex_lock(&m2); printf("Create\\n"); pthread_create(&t1, 0, signal1, 0); pthread_create(&t2, 0, signal2, 0); printf("Join\\n"); pthread_join(t1, 0); pthread_join(t2, 0); printf("End\\n"); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex1,mutex2,mutex3,mutex4,mutex5; void *thr_fn1(void *arg); void *thr_fn2(void *arg); void *thr_fn3(void *arg); void *thr_fn4(void *arg); void *thr_fn5(void *arg); int main(void) { pthread_t tid1,tid2,tid3,tid4,tid5; pthread_mutex_init(&mutex1,0); pthread_mutex_init(&mutex2,0); pthread_mutex_init(&mutex3,0); pthread_mutex_init(&mutex4,0); pthread_mutex_init(&mutex5,0); pthread_create(&tid1,0,thr_fn1,0); pthread_create(&tid2,0,thr_fn2,0); pthread_create(&tid3,0,thr_fn3,0); pthread_create(&tid4,0,thr_fn4,0); pthread_create(&tid5,0,thr_fn5,0); pthread_join(tid1,0); pthread_join(tid2,0); pthread_join(tid3,0); pthread_join(tid4,0); pthread_join(tid5,0); return 0; } void *thr_fn1(void *arg) { int i; while(1) { i = rand()%10; printf("professor 1 begin to thinking %d seconds\\n ",i); sleep(i); pthread_mutex_lock(&mutex5); printf("professor 1 get the chopstick 5\\n"); pthread_mutex_lock(&mutex1); printf("professor 1 get the chopstick 1\\n"); printf("professor 1 begin to eat %d seconds\\n",i); sleep(i); pthread_mutex_unlock(&mutex1); pthread_mutex_unlock(&mutex5); } } void *thr_fn2(void *arg) { int i; while(1) { i = rand()%10; printf("professor 2 begin to thinking %d seconds\\n ",i); sleep(i); pthread_mutex_lock(&mutex1); printf("professor 2 get the chopstick 1\\n"); pthread_mutex_lock(&mutex2); printf("professor 2 get the chopstick 2\\n"); printf("professor 2 begin to eat %d seconds\\n",i); sleep(i); pthread_mutex_unlock(&mutex2); pthread_mutex_unlock(&mutex1); } } void *thr_fn3(void *arg) { int i; while(1) { i = rand()%10; printf("professor 3 begin to thinking %d seconds\\n ",i); sleep(i); pthread_mutex_lock(&mutex2); printf("professor 3 get the chopstick 2\\n"); pthread_mutex_lock(&mutex3); printf("professor 3 get the chopstick 3\\n"); printf("professor 3 begin to eat %d seconds\\n",i); sleep(i); pthread_mutex_unlock(&mutex3); pthread_mutex_unlock(&mutex2); } } void *thr_fn4(void *arg) { int i; while(1) { i = rand()%10; printf("professor 4 begin to thinking %d seconds\\n ",i); sleep(i); pthread_mutex_lock(&mutex3); printf("professor 4 get the chopstick 3\\n"); pthread_mutex_lock(&mutex4); printf("professor 4 get the chopstick 4\\n"); printf("professor 4 begin to eat %d seconds\\n",i); sleep(i); pthread_mutex_unlock(&mutex4); pthread_mutex_unlock(&mutex3); } } void *thr_fn5(void *arg) { int i; while(1) { i = rand()%10; printf("professor 5 begin to thinking %d seconds\\n ",i); sleep(i); pthread_mutex_lock(&mutex4); printf("professor 5 get the chopstick 4\\n"); pthread_mutex_lock(&mutex5); printf("professor 5 get the chopstick 5\\n"); printf("professor 5 begin to eat %d seconds\\n",i); sleep(i); pthread_mutex_unlock(&mutex5); pthread_mutex_unlock(&mutex4); } }
0
#include <pthread.h> int data = 0; pthread_cond_t c_par; pthread_cond_t c_impar; pthread_mutex_t senial; void *Par(void *arg); void *Impar(void *arg); int main(){ pthread_t par, impar; pthread_mutex_init(&senial, 0); pthread_cond_init(&c_par, 0); pthread_cond_init(&c_impar, 0); pthread_create(&par, 0, Par, 0); pthread_create(&impar, 0, Impar, 0); pthread_join(par, 0); pthread_join(impar, 0); pthread_mutex_destroy(&senial); pthread_cond_destroy(&c_par); pthread_cond_destroy(&c_impar); exit(0); } void *Par(void *arg){ int i = 0; while (i < 2000){ pthread_mutex_lock(&senial); pthread_cond_wait(&c_impar, &senial); data++; printf("%d par\\n", data); i++; pthread_mutex_unlock(&senial); pthread_cond_signal(&c_par); } } void *Impar(void *arg){ int i = 0; while(i < 2000){ pthread_mutex_lock(&senial); if(i > 0) pthread_cond_wait(&c_par, &senial); data++; printf("%d impar\\n", data); i++; pthread_mutex_unlock(&senial); pthread_cond_signal(&c_impar); } }
1
#include <pthread.h> pthread_mutex_t mut_num; pthread_mutex_t mut_file; sem_t sem; int number=1; int i=1; void read_data1(void) { int fd,fd2; char name[10]; char buf[100]; size_t size=0; int j=0; while(1) { pthread_mutex_lock(&mut_num); if(number > 10) { pthread_mutex_unlock(&mut_num); break; } sprintf(name,"%d.text",number); j=number; number++; pthread_mutex_unlock(&mut_num); sem_wait(&sem); fd=open(name,O_RDONLY); if(fd < 0) { printf("Open file failed\\n"); break; } size=read(fd,buf,100); if(size == 0) { printf("Read file failed\\n"); break; } close(fd); sem_post(&sem); write: pthread_mutex_lock(&mut_file); if(j == i) { fd2 = open("out.text",O_RDWR|O_CREAT|O_APPEND,0666); write(fd2,buf,size); close(fd2); write(1,buf,size); i++; pthread_mutex_unlock(&mut_file); } else { pthread_mutex_unlock(&mut_file); sleep(1); goto write; } } } void read_data2(void) { int fd,fd2; char name[10]; char buf[100]; size_t size=0; int j=0; while(1) { pthread_mutex_lock(&mut_num); if(number > 10) { pthread_mutex_unlock(&mut_num); break; } sprintf(name,"%d.text",number); j=number; number++; pthread_mutex_unlock(&mut_num); sem_wait(&sem); fd=open(name,O_RDONLY); if(fd < 0) { printf("Open file failed\\n"); break; } size=read(fd,buf,100); if(size == 0) { printf("Read file failed\\n"); break; } close(fd); sem_post(&sem); write: pthread_mutex_lock(&mut_file); if(j == i) { fd2 = open("out.text",O_RDWR|O_CREAT|O_APPEND,0666); write(fd2,buf,size); close(fd2); write(1,buf,size); i++; pthread_mutex_unlock(&mut_file); } else { pthread_mutex_unlock(&mut_file); sleep(1); goto write; } } } void read_data3(void) { int fd,fd2; char name[10]; char buf[100]; size_t size=0; int j; while(1) { pthread_mutex_lock(&mut_num); if(number > 10) { pthread_mutex_unlock(&mut_num); break; } sprintf(name,"%d.text",number); j = number; number++; pthread_mutex_unlock(&mut_num); sem_wait(&sem); fd=open(name,O_RDONLY); if(fd < 0) { printf("Open file failed\\n"); break; } size=read(fd,buf,100); if(size == 0) { printf("Read file failed\\n"); break; } close(fd); sem_post(&sem); write: pthread_mutex_lock(&mut_file); if(j == i) { fd2 = open("out.text",O_RDWR|O_CREAT|O_APPEND,0666); write(fd2,buf,size); close(fd2); write(1,buf,size); i++; pthread_mutex_unlock(&mut_file); } else { pthread_mutex_unlock(&mut_file); sleep(1); goto write; } } } int main() { pthread_t tid1,tid2,tid3; pthread_mutex_init(&mut_num,0); pthread_mutex_init(&mut_file,0); sem_init(&sem,0,2); pthread_create(&tid1,0,(void *)read_data1,0); pthread_create(&tid2,0,(void *)read_data2,0); pthread_create(&tid2,0,(void *)read_data3,0); pthread_join(tid1,0); pthread_join(tid2,0); pthread_join(tid3,0); }
0
#include <pthread.h> int n, *array; pthread_mutex_t array_mutex = PTHREAD_MUTEX_INITIALIZER; void *func(void *arg) { int thread_number = *((int *)arg), i, j; for (i = 0; i < n; i++) { int index_of_min = i; for (j = i; j < n; j++) { if (array[index_of_min] > array[j]) { index_of_min = j; } } pthread_mutex_lock(&array_mutex); printf("Thred %d switching positions %d and %d\\n", thread_number, i, index_of_min); int temp = array[i]; array[i] = array[index_of_min]; array[index_of_min] = temp; pthread_mutex_unlock(&array_mutex); usleep(10); } free(arg); return 0; } int main(int argc, char *argv[]) { int i; printf("N = "); scanf("%d", &n); array = malloc(sizeof(int) * n); pthread_t *array_threads = malloc(sizeof(pthread_t) * n); for (i = 0; i < n; i++) { int number; printf("array[%d] = ", i); scanf("%d", &number); array[i] = number; } for (i = 0 ; i < n ; i++) { int *temp_i = malloc(sizeof(int)); *temp_i = i; pthread_create (&array_threads[i], 0, func, temp_i); } for (i = 0 ; i < n ; i++) { pthread_join(array_threads[i] , 0) ; } for (i = 0 ; i < n ; i++) { printf("%d ", array[i]); } free(array); free(array_threads); return 0; }
1
#include <pthread.h> int num_philosophers; pthread_mutex_t stdout_mutex; pthread_mutex_t random_mutex; pthread_mutex_t *fork_mutex; pthread_t *philosophers; void * xmalloc (size_t n) { void *p = malloc (n); if (! p) { fprintf (stderr, "out of memory\\n"); exit (2); } return p; } void shared_printf (char *format, ...) { va_list ap; __builtin_va_start((ap)); pthread_mutex_lock (&stdout_mutex); vprintf (format, ap); pthread_mutex_unlock (&stdout_mutex); ; } int shared_random () { static unsigned int seed; int result; pthread_mutex_lock (&random_mutex); result = rand_r (&seed); pthread_mutex_unlock (&random_mutex); return result; } void my_usleep (long usecs) { struct timeval timeout; timeout.tv_sec = usecs / 1000000; timeout.tv_usec = usecs % 1000000; select (0, 0, 0, 0, &timeout); } void random_delay () { my_usleep ((shared_random () % 2000) * 100); } void print_philosopher (int n, char left, char right) { int i; shared_printf ("%*s%c %d %c\\n", (n * 4) + 2, "", left, n, right); } void * philosopher (void *data) { int n = * (int *) data; print_philosopher (n, '_', '_'); if (n == num_philosophers - 1) for (;;) { pthread_mutex_lock (&fork_mutex[(n + 1) % num_philosophers]); print_philosopher (n, '_', '!'); random_delay (); pthread_mutex_lock (&fork_mutex[n]); print_philosopher (n, '!', '!'); random_delay (); print_philosopher (n, '_', '_'); pthread_mutex_unlock (&fork_mutex[n]); pthread_mutex_unlock (&fork_mutex[(n + 1) % num_philosophers]); random_delay (); } else for (;;) { pthread_mutex_lock (&fork_mutex[n]); print_philosopher (n, '!', '_'); random_delay (); pthread_mutex_lock (&fork_mutex[(n + 1) % num_philosophers]); print_philosopher (n, '!', '!'); random_delay (); print_philosopher (n, '_', '_'); pthread_mutex_unlock (&fork_mutex[n]); pthread_mutex_unlock (&fork_mutex[(n + 1) % num_philosophers]); random_delay (); } return (void *) 0; } int main (int argc, char **argv) { num_philosophers = 5; { pthread_mutexattr_t ma; int i; pthread_mutexattr_init (&ma); pthread_mutex_init (&stdout_mutex, &ma); pthread_mutex_init (&random_mutex, &ma); fork_mutex = xmalloc (num_philosophers * sizeof (fork_mutex[0])); for (i = 0; i < num_philosophers; i++) pthread_mutex_init (&fork_mutex[i], &ma); pthread_mutexattr_destroy (&ma); } { int i; int *numbers = xmalloc (num_philosophers * sizeof (*numbers)); pthread_attr_t ta; philosophers = xmalloc (num_philosophers * sizeof (*philosophers)); pthread_attr_init (&ta); for (i = 0; i < num_philosophers; i++) { numbers[i] = i; pthread_create (&philosophers[i], &ta, philosopher, &numbers[i]); } pthread_attr_destroy (&ta); } sleep (1000000); for (;;) sleep (1000000); return 0; }
0
#include <pthread.h> int buffer[20 +1]; int slot; pthread_t producers[10 +1]; pthread_t consumers[7 +1]; pthread_mutex_t mutex; sem_t full; sem_t empty; void* produce(void* x) { int *y = (int*)x; int p = *y + 1; while (1) { sem_wait(&empty); pthread_mutex_lock(&mutex); slot++; printf("producer %d put to slot %d\\n", p, slot); pthread_mutex_unlock(&mutex); sem_post(&full); sched_yield(); } } void* consume(void* x) { int *y = (int*)x; int p = *y + 1; while (1) { sem_wait(&full); pthread_mutex_lock(&mutex); printf("consumer %d take from slot %d\\n", p, slot); slot--; pthread_mutex_unlock(&mutex); sem_post(&empty); sched_yield(); } } int main() { sem_init(&full, 0, 0); sem_init(&empty, 0, 20); pthread_mutex_init(&mutex, 0); slot = 0; int i; for(i = 0; i < 7; i++) pthread_create(consumers + i, 0, consume, (void *)&i); for(i = 0; i < 10; i++) pthread_create(producers + i, 0, produce, (void *)&i); sleep(1); return 0; }
1
#include <pthread.h> double **doubleVettToVerticalMatrix(double *vett, int dim); double **doubleMatrixTranspone(double **mat, int m, int n); void doubleMatrixPrint(double **mat, int m, int n); double *v1, *v2, *v; double **mat, **m1, **m1t, **m2; double result; int k; int n_thread_left; pthread_mutex_t n_thread_mutex; void *thread_function(void *param); int main(int argc, char **argv) { int retval; int i, j; if (argc < 2) { printf("Please provide an integer parameter k\\n"); return -1; } k = atoi(argv[1]); if (k == 0) { printf("Provide a non-zero parameter!\\n"); return -1; } srand(k); v1 = malloc(k * sizeof(double)); v2 = malloc(k * sizeof(double)); mat = malloc(k * sizeof(double *)); for (i = 0; i < k; i++) { v1[i] = ((double)rand()) / 32767 - 0.5; v2[i] = ((double)rand()) / 32767 - 0.5; mat[i] = malloc(k * sizeof(double)); for (j = 0; j < k; j++) { mat[i][j] = ((double)rand()) / 32767 - 0.5; } } v = malloc(k * sizeof(double)); m1 = doubleVettToVerticalMatrix(v1, k); m1t = doubleMatrixTranspone(m1, k, 1); printf("Matrix m1t:\\n"); doubleMatrixPrint(m1t, 1, k); printf("Matrix mat:\\n"); doubleMatrixPrint(mat, k, k); m2 = doubleVettToVerticalMatrix(v2, k); printf("Matrix m2:\\n"); doubleMatrixPrint(m2, k, 1); n_thread_left = k; pthread_mutex_init(&n_thread_mutex, 0); pthread_t *threads = malloc(k * sizeof(pthread_t)); for (i = 0; i < k; i++) { int *param = malloc(sizeof(int)); *param = i; retval = pthread_create(&threads[i], 0, thread_function, param); if (retval != 0) { printf("Error creating thread"); exit(-1); } pthread_detach(threads[i]); } pthread_exit(0); return 0; } void *thread_function(void *param) { int i = *(int *)param; int j; for (j = 0; j < k; j++) { v[i] += mat[i][j] * v2[j]; } pthread_mutex_lock(&n_thread_mutex); int tmp = --n_thread_left; pthread_mutex_unlock(&n_thread_mutex); fflush(stdout); if (tmp == 0) { result = 0; for (j = 0; j < k; j++) { result += v1[j] * v[j]; } printf("The result is: %f\\n", result); } return 0; } double **doubleVettToVerticalMatrix(double *vett, int dim) { int i; double **mat = malloc(dim * sizeof(double *)); for (i = 0; i < dim; i++) { mat[i] = malloc(dim * sizeof(double)); mat[i][0] = vett[i]; } return mat; } double **doubleMatrixTranspone(double **mat, int m, int n) { int i, j; double **result = malloc(n * sizeof(double *)); for (i = 0; i < n; i++) { result[i] = malloc(m * sizeof(double)); for (j = 0; j < m; j++) { result[i][j] = mat[j][i]; } } return result; } void doubleMatrixPrint(double ** mat, int m, int n) { int i, j; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { printf("%f\\t", mat[i][j]); } printf("\\n"); } }
0
#include <pthread.h> int allocated = 0; int bitmap_size; int free_num; int units_num; char* bitmap_ptr; void* alloc_ptr; int Mem_Init(int sizeOfRegion){ int pagesize = getpagesize(); int initsize = sizeOfRegion; if(allocated != 0 || sizeOfRegion <= 0){ fprintf(stderr, "ERROR!\\n"); return -1; } if(initsize % pagesize != 0){ initsize += (pagesize - (initsize % pagesize)); } int fd = open("/dev/zero", O_RDWR); alloc_ptr = mmap(0, initsize, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); if(alloc_ptr == MAP_FAILED){ perror("mmap"); exit(1); } close(fd); bitmap_size = initsize / (16 * 4); initsize -= bitmap_size; free_num = initsize; bitmap_ptr = alloc_ptr; alloc_ptr += bitmap_size; units_num = initsize/16; allocated = 1; return 0; } void* Mem_Alloc(int size){ int i = 0; int j = 0; char* tmp = bitmap_ptr; void* retptr; char* mapptr; int tmpj = 0; int count = 0; if(size < 0 || size > free_num || (size != 16 && size != 80 && size != 256)){ return 0; } while(1){ int alloc_num = 2; if((i * 4 + j * (1/2)) >= units_num){ return 0; } else if(((0x03 << j) & *tmp) == (0x03 << j)){ count = 0; alloc_num = 32; } else if(((0x01 << j) & *tmp) == (0x01 << j)){ count = 0; alloc_num = 2; } else if(((0x02 << j) & *tmp) == (0x02 << j)){ count = 0; alloc_num = 10; } else{ if(count == 0){ retptr = alloc_ptr + (((i * 8) + j) * 8); mapptr = tmp; tmpj = j; count = size/16; } count--; if(count == 0){ if(size == 16){ *mapptr = *mapptr | (0x01 << tmpj); free_num -= 16; } else if(size == 80){ *mapptr = *mapptr | (0x02 << tmpj); free_num -= 80; } else if(size == 256){ *mapptr = *mapptr | (0x03 << tmpj); free_num -= 256; } return retptr; } } if(j + alloc_num < 8){ j += alloc_num; } else{ i += (j + alloc_num) / 8; tmp += (j + alloc_num) / 8; j = (j + alloc_num) % 8; } } return 0; } int Mem_Free(void *ptr){ pthread_mutex_t lock; pthread_mutex_lock(&lock); int i, j; char* tmp; if(ptr == 0 || ptr < alloc_ptr || ptr > alloc_ptr + (units_num * 16) || (ptr - alloc_ptr) % 16 != 0){ pthread_mutex_unlock(&lock); return -1; } i = (ptr - alloc_ptr) / (16 * 4); j = ((ptr - alloc_ptr) % (16 * 4))/8; tmp = bitmap_ptr + i; if(((0x03 << j) & *tmp) == (0x03 << j)){ free_num += 256; *tmp = *tmp & ~(0x03 << j); } else if(((0x01 << j) & *tmp) == (0x01 << j)){ free_num += 16; *tmp = *tmp & ~(0x01 << j); } else if(((0x02 << j) & *tmp) == (0x02 << j)){ free_num += 80; *tmp = *tmp & ~(0x02 << j); } pthread_mutex_unlock(&lock); return 0; } int Mem_Available(){ return free_num; } void Mem_Dump(){ }
1
#include <pthread.h> int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *incrementer(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 *watcher(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while (count<12) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); count += 100; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char **argv) { int i, rc; long t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watcher, (void *)t1); pthread_create(&threads[1], &attr, incrementer, (void *)t2); pthread_create(&threads[2], &attr, incrementer, (void *)t3); for (i=0; i<3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Done.\\n", 3); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
0
#include <pthread.h> volatile double pi = 0.0; pthread_mutex_t pi_lock; volatile double intervals; void * process(void *arg) { register double width, localsum; register int i; register int iproc = (*((char *) arg) - '0'); width = 1.0 / intervals; localsum = 0; for (i=iproc; i<intervals; i+=2) { register double x = (i + 0.5) * width; localsum += 4.0 / (1.0 + x * x); } localsum *= width; pthread_mutex_lock(&pi_lock); pi += localsum; pthread_mutex_unlock(&pi_lock); return 0; } int main(int argc, char **argv) { pthread_t thread0, thread1; void *retval; intervals = atoi(argv[1]); pthread_mutex_init(&pi_lock, 0); if (pthread_create(&thread0, 0, process, "0") || pthread_create(&thread1, 0, process, "1")) { fprintf(stderr, "%s: cannot make thread\\n", argv[0]); exit(1); } if (pthread_join(thread0, &retval) || pthread_join(thread1, &retval)) { fprintf(stderr, "%s: thread join failed\\n", argv[0]); exit(1); } printf("Estimation of PI is %f\\n", pi); exit(0); }
1
#include <pthread.h> static int num = 0; static pthread_mutex_t mut_num = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond_num = PTHREAD_COND_INITIALIZER; static void *thr_primer(void *p); int main() { int i,err; pthread_t tid[3]; for(i = 0; i < 3; i++) { err = pthread_create(tid+i,0,thr_primer,(void *)i); if(err) { fprintf(stderr,"pthread_create():%s\\n",strerror(err)); exit(1); } } for(i = 30000000; i <= 30000200; i++) { pthread_mutex_lock(&mut_num); while(num != 0) { pthread_cond_wait(&cond_num,&mut_num); } num = i; pthread_cond_signal(&cond_num); pthread_mutex_unlock(&mut_num); } pthread_mutex_lock(&mut_num); while(num != 0) { pthread_cond_wait(&cond_num,&mut_num); } num = -1; pthread_cond_broadcast(&cond_num); pthread_mutex_unlock(&mut_num); for(i = 0; i < 3; i++) pthread_join(tid[i],0); pthread_mutex_destroy(&mut_num); pthread_cond_destroy(&cond_num); exit(0); } static void *thr_primer(void *p) { int i,j,mark; while(1) { pthread_mutex_lock(&mut_num); while(num == 0) { pthread_cond_wait(&cond_num,&mut_num); } if(num == -1) { pthread_mutex_unlock(&mut_num); break; } i = num; num = 0; pthread_cond_broadcast(&cond_num); pthread_mutex_unlock(&mut_num); mark = 1; for(j = 2; j < i/2 ; j++) { if(i % j == 0) { mark = 0; break; } } if(mark) printf("[%d]%d is a primer.\\n",(int)p,i); } pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t mutex1=PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2=PTHREAD_MUTEX_INITIALIZER; int px=1,py=2; void* thread1(void* arg) { int i; for(i=0;i<10;i++) { sleep(1); pthread_mutex_lock(&mutex1); printf("thread1:the value of px is %d\\n",px); pthread_mutex_unlock(&mutex1); } pthread_exit(0); } void* thread2(void* arg) { int i; for(i=0;i<10;i++) { sleep(1); pthread_mutex_lock(&mutex2); printf("thread2:the value of py is %d\\n",py); pthread_mutex_unlock(&mutex2); } pthread_exit(0); } void* thread3(void* arg) { int i; for(i=0;i<10;i++) { sleep(1); pthread_mutex_lock(&mutex1); if(pthread_mutex_trylock(&mutex2)==0) { printf("thread3:px=%d py=%d\\n",px,py); pthread_mutex_unlock(&mutex1); pthread_mutex_unlock(&mutex2); } else { pthread_mutex_unlock(&mutex1); i--; } } pthread_exit(0); } int main() { int i; pthread_t tid[3]; pthread_create(&tid[0],0,thread1,0); pthread_create(&tid[1],0,thread2,0); pthread_create(&tid[2],0,thread3,0); for(i=0;i<3;i++) { pthread_join(tid[i],0); } printf("all of thread is finished\\n"); return 0; }
1
#include <pthread.h> pthread_t tid[5]; int counter; pthread_mutex_t lock; pthread_cond_t cond; int work=0; void* doSomeThing(void *arg) { int who,tmp; int i = 0,j; counter += 1; who = counter; printf("\\n Job %d created\\n", who); for(j=0;j<5;j++){ pthread_mutex_lock(&lock); while(!work){ tmp = pthread_cond_wait(&cond, &lock); printf(" Job %d wait: %d\\n",who,tmp); } pthread_mutex_unlock(&lock); work = 0; printf(" Job %d started\\n", who); for(i=0; i<(1000000);i++); pthread_mutex_lock(&lock); work =1; pthread_cond_signal(&cond); pthread_mutex_unlock(&lock); } return 0; } int main(void) { int i = 0,j; int err; int tmp; if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } if (pthread_cond_init(&cond, 0) != 0) { printf("\\n cond init failed\\n"); return 1; } while(i < 5) { err = pthread_create(&(tid[i-1]), 0, &doSomeThing, 0); if (err != 0) printf("\\ncan't create thread :[%s]", strerror(err)); i++; } work = 1; tmp = pthread_cond_signal(&cond); printf("signal(): %d\\n",tmp); for(j=0;j<5;j++) pthread_join(tid[j], 0); pthread_mutex_destroy(&lock); return 0; }
0
#include <pthread.h> static struct sigaction sact[32]; static unsigned int jvmsigs = 0; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static pthread_t tid = 0; static signal_t os_signal = 0; static sigaction_t os_sigaction = 0; static int jvm_signal_installing = 0; static int jvm_signal_installed = 0; static void signal_lock() { pthread_mutex_lock(&mutex); if (jvm_signal_installing) { if (tid != pthread_self()) { pthread_cond_wait(&cond, &mutex); } } } static void signal_unlock() { pthread_mutex_unlock(&mutex); } static sa_handler_t call_os_signal(int sig, sa_handler_t disp, int is_sigset) { if (os_signal == 0) { if (!is_sigset) { os_signal = (signal_t)dlsym(RTLD_NEXT, "signal"); } else { os_signal = (signal_t)dlsym(RTLD_NEXT, "sigset"); } if (os_signal == 0) { printf("%s\\n", dlerror()); exit(0); } } return (*os_signal)(sig, disp); } static void save_signal_handler(int sig, sa_handler_t disp) { sigset_t set; sact[sig].sa_handler = disp; sigemptyset(&set); sact[sig].sa_mask = set; sact[sig].sa_flags = 0; } static sa_handler_t set_signal(int sig, sa_handler_t disp, int is_sigset) { sa_handler_t oldhandler; int sigused; signal_lock(); sigused = (((unsigned int)1 << sig) & jvmsigs) != 0; if (jvm_signal_installed && sigused) { oldhandler = sact[sig].sa_handler; save_signal_handler(sig, disp); signal_unlock(); return oldhandler; } else if (jvm_signal_installing) { oldhandler = call_os_signal(sig, disp, is_sigset); save_signal_handler(sig, oldhandler); jvmsigs |= ((unsigned int)1 << sig); signal_unlock(); return oldhandler; } else { oldhandler = call_os_signal(sig, disp, is_sigset); signal_unlock(); return oldhandler; } } sa_handler_t signal(int sig, sa_handler_t disp) { set_signal(sig, disp, 0); } sa_handler_t sigset(int sig, sa_handler_t disp) { set_signal(sig, disp, 1); } static int call_os_sigaction(int sig, const struct sigaction *act, struct sigaction *oact) { if (os_sigaction == 0) { os_sigaction = (sigaction_t)dlsym(RTLD_NEXT, "sigaction"); if (os_sigaction == 0) { printf("%s\\n", dlerror()); exit(0); } } return (*os_sigaction)(sig, act, oact); } int sigaction(int sig, const struct sigaction *act, struct sigaction *oact) { int res; int sigused; struct sigaction oldAct; signal_lock(); sigused = (((unsigned int)1 << sig) & jvmsigs) != 0; if (jvm_signal_installed && sigused) { if (oact != 0) { *oact = sact[sig]; } if (act != 0) { sact[sig] = *act; } signal_unlock(); return 0; } else if (jvm_signal_installing) { res = call_os_sigaction(sig, act, &oldAct); sact[sig] = oldAct; if (oact != 0) { *oact = oldAct; } jvmsigs |= ((unsigned int)1 << sig); signal_unlock(); return res; } else { res = call_os_sigaction(sig, act, oact); signal_unlock(); return res; } } void JVM_begin_signal_setting() { signal_lock(); jvm_signal_installing = 1; tid = pthread_self(); signal_unlock(); } void JVM_end_signal_setting() { signal_lock(); jvm_signal_installed = 1; jvm_signal_installing = 0; pthread_cond_broadcast(&cond); signal_unlock(); } struct sigaction *JVM_get_signal_action(int sig) { if ((((unsigned int)1 << sig) & jvmsigs) != 0) { return &sact[sig]; } return 0; }
1
#include <pthread.h> struct timeval begin_time; long int late = 0; long int done = 0; pthread_mutex_t lock; long int temp[128]; struct setting setting; struct record records[MAXREC]; void *context; void trace_replay(void *arg) { struct req_data req_data; struct timeval end_time, result_time, test_time; long int i; char *ip; i = *(long int *)arg; *(long int *)arg += 128; gettimeofday(&end_time, 0); timersub(&end_time, &begin_time, &result_time); timersub(&records[i].time, &result_time, &test_time); do { if (test_time.tv_sec < 0) { pthread_mutex_lock(&lock); late++; pthread_mutex_unlock(&lock); records[i].time.tv_sec = result_time.tv_sec; records[i].time.tv_usec = result_time.tv_usec; break; } if (test_time.tv_sec != 0) { sleep(test_time.tv_sec); } if (test_time.tv_usec >= 0) { usleep(test_time.tv_usec); } } while(0); req_data.offset = records[i].offset; req_data.length = records[i].length; req_data.op = records[i].op; ip = setting.nodes[records[i].dev_num].ip; req_send(context, &req_data, ip); gettimeofday(&end_time, 0); timersub(&end_time, &begin_time, &result_time); timersub(&result_time, &records[i].time, &records[i].res_time); } int main(int argc, const char *argv[]) { long int i, ret=0; threadpool_t *pool; struct timeval total_time; for (i = 0; i < 128; i++) { temp[i] = i; } init_rec_array(records); pthread_mutex_init(&lock, 0); pool = threadpool_init(128, 256, 0); if(!pool) { return -1; } ret = init_conf(&setting); if(ret) { return -1; } context = zmq_init(1); debug_puts("Init over... Start trace play. Begin time is Beijing time:"); time_t p_time = time(0); debug_puts(ctime(&p_time)); gettimeofday(&begin_time, 0); for (i = 0; i < MAXREC; i++) { ret = threadpool_add(pool, &trace_replay, (void *)&temp[i % 128], 0); if (ret) { debug_puts("TASK ADD ERROR"); break; } } sleep(1); threadpool_destroy(pool, 0); free(setting.nodes); zmq_term (context); total_time.tv_sec = total_time.tv_usec = 0; debug_print("Trace play over, %ld traces are late. now calculate total response time.", late); for (i = 0; i < MAXREC; i++) { timeradd(&total_time, &records[i].res_time, &total_time); } debug_print("Play %d traces in %ld.%lds", MAXREC, total_time.tv_sec, total_time.tv_usec); return 0; }
0
#include <pthread.h> static int running = 1; static pthread_mutex_t running_lock; static int initialized = 0; static pthread_t thread; static void* query_running_thread() { while( initialized ) { FILE* bspcfp; char output[128]; bspcfp = popen("bspc query 2>&1", "r"); fscanf( bspcfp, "%s", output ); pclose( bspcfp ); pthread_mutex_lock( &running_lock ); if( strcmp( output, "Failed" ) == 0 ) { running = 0; } else { running = 1; } pthread_mutex_unlock( &running_lock ); sleep( 2 ); } running = 0; return 0; } int bspc_init() { if( initialized ) return 0; pthread_mutex_init( &running_lock, 0 ); pthread_create( &thread, 0, &query_running_thread, 0 ); initialized = 1; return 1; } int bspc_destroy() { if( !initialized ) return 0; initialized = 0; pthread_join( thread, 0 ); pthread_mutex_destroy( &running_lock ); return 1; } int is_bspc_running() { if( !initialized ) return -1; int running_status = -1; pthread_mutex_lock( &running_lock ); running_status = running; pthread_mutex_unlock( &running_lock ); return running_status; }
1
#include <pthread.h> extern char **environ; pthread_mutex_t env_mutex; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void thread_init(void) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&env_mutex, &attr); pthread_mutexattr_destory(&attr); } int getenv_r(const char *name, char *buf, int buflen) { int i, len, olen; pthread_once(&init_done, thread_init); len = strlen(name); pthread_mutex_lock(&env_mutex); for (int i=0; environ[i] != 0; ++i) { if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { olen = strlen(&environ[i][len+1]); if (olen >= buflen) { pthread_mutex_unlock(&env_mutex); return (ENOSPC); } strcpy(buf, &environ[i][len+1]); pthread_mutex_unlock(&env_mutex); return 0; } } pthread_mutex_unlock(&env_mutex); return ENOENT; }
0
#include <pthread.h> pthread_mutex_t mutex; int matriz[100][10]; void imprime_matriz(){ int i, j; for(i=0;i<100;i++){ for(j=0;j<10;j++){ printf("%d\\t", matriz[i][j]); } printf("\\n\\n"); } } void* inicializa_matriz(void *p){ int i, col; col = (int)(size_t)p; pthread_mutex_lock(&mutex); for(i=0;i<100;i++) matriz[i][col] = rand()%100; pthread_mutex_unlock(&mutex); pthread_exit(0); } void * soma_coluna(void *p) { int i, soma = 0, col; col = (int)(size_t)p; pthread_mutex_lock(&mutex); for(i=0;i<100;i++) soma += matriz[i][col]; pthread_mutex_unlock(&mutex); printf("Coluna %d - somatorio: %d\\n", col+1, soma); pthread_exit(0); } int main(int argc, char **argv) { int i; pthread_t tid[10]; pthread_mutex_init(&mutex, 0); srand(time(0)); for(i=0;i<10;i++) pthread_create(&tid[i], 0, inicializa_matriz, (void *)(size_t) i); for(i=0;i<10;i++) pthread_join(tid[i], 0); imprime_matriz(); for(i=0;i<10;i++) pthread_create(&tid[i], 0, soma_coluna, (void *)(size_t) i); for(i=0;i<10;i++) pthread_join(tid[i], 0); pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> pthread_mutex_t head_p_mutex; struct list_node_s* lista = 0; pthread_mutex_t list_mutex; pthread_rwlock_t rwlock; struct list_node_s{ int data; struct list_node_s* next; pthread_mutex_t mutex; }; int Member(int value, struct list_node_s* head_p){ struct list_node_s* 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; } }; int sol2_Member( int value, struct list_node_s* head_pp){ struct list_node_s* temp_p; pthread_mutex_lock(&head_p_mutex); temp_p = head_pp; while ( temp_p != 0 && temp_p->data < value) { if( temp_p->next != 0 ){ pthread_mutex_lock(&(temp_p->next->mutex)); } if (temp_p == head_pp) { pthread_mutex_unlock(&head_p_mutex); } pthread_mutex_unlock(&(temp_p->mutex)); temp_p = temp_p->next; } if ( temp_p == 0 || temp_p->data > value ) { if( temp_p == head_pp ){ pthread_mutex_unlock(&head_p_mutex); } if(temp_p != 0){ pthread_mutex_unlock(&(temp_p->mutex)); } return 0; } else{ if (temp_p == head_pp) { pthread_mutex_unlock(&head_p_mutex); } pthread_mutex_unlock(&(temp_p->mutex)); return 1; } }; int Insert(int value, struct list_node_s** head_pp ){ struct list_node_s* curr_p = *head_pp; 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 = (struct list_node_s*) malloc(sizeof(struct list_node_s)); temp_p->data = value; temp_p->next = curr_p; if( pred_p == 0 ){ *head_pp = temp_p; } else{ pred_p->next = temp_p; } return 1; } else{ return 0; } }; int sol2_Insert(int value, struct list_node_s** head_pp ){ struct list_node_s* curr_p = *head_pp; 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 = (struct list_node_s*) malloc(sizeof(struct list_node_s)); temp_p->data = value; temp_p->next = curr_p; if( pred_p == 0 ){ pthread_mutex_lock(&head_p_mutex); *head_pp = temp_p; pthread_mutex_unlock(&head_p_mutex); } else{ pthread_mutex_lock(&(pred_p->mutex)); pred_p->next = temp_p; pthread_mutex_unlock(&(pred_p->mutex)); } return 1; } else{ return 0; } }; int Delete(int value, struct list_node_s** head_pp){ struct list_node_s* curr_p = *head_pp; 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_pp = curr_p->next; free(curr_p); } else { pred_p->next = curr_p->next; free(curr_p); } return 1; } else { return 0; } }; int sol2_Delete(int value, struct list_node_s** head_pp){ struct list_node_s* curr_p = *head_pp; 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){ pthread_mutex_lock(&head_p_mutex); *head_pp = curr_p->next; free(curr_p); pthread_mutex_unlock(&head_p_mutex); } else{ pthread_mutex_lock(&(pred_p->mutex)); pred_p->next = curr_p->next; free(curr_p); pthread_mutex_unlock(&(pred_p->mutex)); } return 1; } else{ return 0; } }; void Print(struct list_node_s** head_pp ){ struct list_node_s* curr_p = *head_pp; while ( curr_p != 0 ) { printf("%d-", curr_p->data); curr_p = curr_p->next; } printf("\\n"); }; void* Operaciones(void* id){ int i = 0; int num[10000]; for(i = 0; i <= 10000; ++i){ num[i]= rand() % 10000; sol2_Insert(rand() % 10000, &lista); } for(i = 0; i <= 80000; ++i){ sol2_Member(rand() % 10000, lista); } for(i = 0; i <= 10000; ++i){ sol2_Delete(num[rand() % 1000], &lista); } return 0; } int main(int argc, char* argv[]){ srand(time(0)); int n = atoi(argv[1]); long i = 0; clock_t start_t, end_t; double total_t; pthread_t* threads; threads = (pthread_t*) malloc(sizeof(pthread_t) * n); start_t = clock(); for( i = 0; i < n; ++i){ pthread_create(&threads[i], 0, Operaciones, (void*) i); } for( i = 0; i < n; ++i){ pthread_join(threads[i], 0); } end_t = clock(); total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC; printf("Total time: %f with %d threads.\\n", total_t, n ); return 0; }
0
#include <pthread.h> int run_thread_a = 1; pthread_mutex_t run_lock_a = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t run_cond_a = PTHREAD_COND_INITIALIZER; int run_thread_b = 0; pthread_mutex_t run_lock_b = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t run_cond_b = PTHREAD_COND_INITIALIZER; void *a(void *); void *b(void *); int main(){ int status; pthread_t thread_a; pthread_t thread_b; pthread_create(&thread_a, 0, a, (void *)0); pthread_create(&thread_b, 0, b, (void *)0); pthread_join(thread_a, (void **)&status); pthread_join(thread_b, (void **)&status); } void *a(void *i) { char str1[30]; while (1) { pthread_mutex_lock(&run_lock_a); while (!run_thread_a){ printf("Thread A is locking ...\\n"); pthread_cond_wait(&run_cond_a, &run_lock_a); } run_thread_a = 0; pthread_mutex_unlock(&run_lock_a); printf("Thread A is running ...\\n"); printf("Enter a string : "); scanf("%s%*c",str1); printf("Thread A : %s\\n", str1); pthread_mutex_lock(&run_lock_b); run_thread_b = 1; pthread_cond_signal(&run_cond_b); pthread_mutex_unlock(&run_lock_b); } } void *b(void *i) { char str2[30]; while (1) { pthread_mutex_lock(&run_lock_b); while (!run_thread_b){ printf("Thread B is locking ...\\n"); pthread_cond_wait(&run_cond_b, &run_lock_b); } run_thread_b = 0; pthread_mutex_unlock(&run_lock_b); printf("Thread B is running ...\\n"); printf("Enter a string : "); scanf("%s%*c",str2); printf("Thread B : %s\\n", str2); pthread_mutex_lock(&run_lock_a); run_thread_a = 1; pthread_cond_signal(&run_cond_a); pthread_mutex_unlock(&run_lock_a); } }
1
#include <pthread.h> extern char **environ; pthread_mutex_t env_mutex; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void thread_init(void) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&env_mutex, &attr); pthread_mutexattr_destroy(&attr); } int getenv_r(const char *name, char *buf, int buflen) { int i, len, olen; pthread_once(&init_done, thread_init); len = strlen(name); pthread_mutex_lock(&env_mutex); for(i = 0; environ[i] != 0; i++) { if((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { olen = strlen(&environ[i][len + 1]); if(olen >= buflen) { pthread_mutex_unlock(&env_mutex); return (ENOSPC); } strcpy(buf, &environ[i][len + 1]); pthread_mutex_unlock(&env_mutex); return 0; } } pthread_mutex_unlock(&env_mutex); return (ENOENT); }
0
#include <pthread.h> pthread_t Thread_set; pthread_t Thread_get; pthread_t timeout; pthread_attr_t schedAttr_set; pthread_attr_t schedAttr_get; pthread_attr_t schedAttr_time; struct sched_param set_param; struct sched_param get_param; struct sched_param time_param; pthread_mutex_t mutexLock; int test; { double Acc_x,Acc_y,Acc_z; double roll; double pitch; double yaw; struct timespec ts; }NAV; NAV *nav; void set_XYZ(void *a) { pthread_mutex_lock(&mutexLock); nav->Acc_x = rand(); nav->Acc_y = rand(); nav->Acc_z = rand(); nav->roll = rand(); nav->pitch = rand(); nav->yaw = rand(); clock_gettime(CLOCK_MONOTONIC, &(nav->ts)); pthread_mutex_unlock(&mutexLock); } void timed_lock(void *a) { int rc; struct timespec c={10,0}, b; while(1) { if(pthread_mutex_timedlock(&mutexLock,&c)!=0) { clock_gettime(CLOCK_REALTIME,&b); printf("No new data available at time: sec=%d, nsec=%d\\n",(int)b.tv_sec,(int)b.tv_nsec); return; } else { pthread_mutex_unlock(&mutexLock); } } } void get_XYZ(void *a) { pthread_mutex_lock(&mutexLock); printf("Acc_x= %f\\n",nav->Acc_x); printf("Acc_y= %f\\n",nav->Acc_y); printf("Acc_z= %f\\n",nav->Acc_z); printf("roll= %f\\n",nav->roll); printf("pitch= %f\\n",nav->pitch); printf("yaw= %f\\n",nav->yaw); printf("time: sec=%d, nsec=%d\\n",(int)nav->ts.tv_sec,(int)nav->ts.tv_nsec); pthread_mutex_unlock(&mutexLock); } int main (int argc, char *argv[]) { pthread_attr_init(&schedAttr_set); pthread_attr_init(&schedAttr_get); pthread_attr_init(&schedAttr_time); pthread_attr_setinheritsched(&schedAttr_set, PTHREAD_EXPLICIT_SCHED); pthread_attr_setschedpolicy(&schedAttr_set, SCHED_FIFO); pthread_attr_setinheritsched(&schedAttr_get, PTHREAD_EXPLICIT_SCHED); pthread_attr_setschedpolicy(&schedAttr_get, SCHED_FIFO); pthread_attr_setinheritsched(&schedAttr_time, PTHREAD_EXPLICIT_SCHED); pthread_attr_setschedpolicy(&schedAttr_time, SCHED_FIFO); set_param.sched_priority = 4; get_param.sched_priority = 3; time_param.sched_priority = 2; pthread_attr_setschedparam(&schedAttr_set, &set_param); pthread_attr_setschedparam(&schedAttr_get, &get_param); pthread_attr_setschedparam(&schedAttr_time, &time_param); int count = 0; nav = (NAV *) malloc(sizeof(NAV)); while(count < 2) { if(count==1) { pthread_create(&timeout, &schedAttr_time, timed_lock, (void*) 0); } pthread_create(&Thread_set, &schedAttr_set,set_XYZ,(void*) 0); pthread_create(&Thread_get, &schedAttr_get,get_XYZ,(void*) 0); count++; usleep(10000); } pthread_join(Thread_set,0); pthread_join(Thread_get,0); pthread_mutex_lock(&mutexLock); pthread_join(timeout,0); pthread_mutex_destroy(&mutexLock); }
1
#include <pthread.h> struct propset { char * str; int row; int delay; int dir; }; pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER; int main(int ac, char * av[]) { int c; pthread_t thrds[10]; struct propset props[10]; void *animate(); int num_msg; int i; if (ac==1) { printf("usage: tanimate str1 str2 ..\\n"); exit(1); } num_msg = setup(ac-1, av+1, props); for (i=0; i<num_msg; i++) { if ( pthread_create(&thrds[i], 0, animate, &props[i]) ) { fprintf(stderr, "error creating threadd"); endwin(); exit(0); } } while(1) { c = getch(); if (c == 'Q') break; if (c == ' ') { for (i=0; i<num_msg; i++) { props[i].dir = -props[i].dir; } } if (c >= '0' && c <= '9') { i = c-'0'; if (i < num_msg) props[i].dir = -props[i].dir; } } pthread_mutex_lock(&mx); for (i=0; i<num_msg; i++) pthread_cancel(thrds[i]); endwin(); return 0; } int setup(int nstrings, char * strings[], struct propset props[]) { int num_msg = (nstrings > 10? 10: nstrings); int i; srand(getpid()); for (i=0; i<num_msg; i++) { props[i].str = strings[i]; props[i].row = i; props[i].delay = 1+(rand()%15); props[i].dir = ((rand()%2) ? 1:-1); } initscr(); crmode(); noecho(); clear(); mvprintw(LINES-1, 0, "'Q' to quit, '0'...'%d' to bounce", num_msg-1); return num_msg; } void * animate (void * arg) { struct propset * info = arg; int len = strlen(info->str) + 2; int col = rand() % (COLS-len -3); while (1) { usleep(info->delay * 20000); pthread_mutex_lock(&mx); move(info->row, col); addch(' '); addstr(info->str); addch(' '); move(LINES-1, COLS-1); refresh(); pthread_mutex_unlock(&mx); col += info->dir; if (col<=0 && info->dir == -1) { info->dir = 1; } else if (col + len >= COLS && info->dir == 1) { info->dir = -1; } } }
0
#include <pthread.h>extern int __VERIFIER_nondet_int(); int idx=0; int ctr1=1, ctr2=0; int readerprogress1=0, readerprogress2=0; pthread_mutex_t mutex; void __VERIFIER_atomic_use1(int myidx) { __VERIFIER_assume(myidx <= 0 && ctr1>0); ctr1++; } void __VERIFIER_atomic_use2(int myidx) { __VERIFIER_assume(myidx >= 1 && ctr2>0); ctr2++; } void __VERIFIER_atomic_use_done(int myidx) { if (myidx <= 0) { ctr1--; } else { ctr2--; } } void __VERIFIER_atomic_take_snapshot(int readerstart1, int readerstart2) { readerstart1 = readerprogress1; readerstart2 = readerprogress2; } void __VERIFIER_atomic_check_progress1(int readerstart1) { if (__VERIFIER_nondet_int()) { __VERIFIER_assume(readerstart1 == 1 && readerprogress1 == 1); if (!(0)) ERROR: goto ERROR;; } return; } void __VERIFIER_atomic_check_progress2(int readerstart2) { if (__VERIFIER_nondet_int()) { __VERIFIER_assume(readerstart2 == 1 && readerprogress2 == 1); if (!(0)) ERROR: goto ERROR;; } return; } void *qrcu_reader1() { int myidx; while (1) { myidx = idx; if (__VERIFIER_nondet_int()) { __VERIFIER_atomic_use1(myidx); break; } else { if (__VERIFIER_nondet_int()) { __VERIFIER_atomic_use2(myidx); break; } else {} } } readerprogress1 = 1; readerprogress1 = 2; __VERIFIER_atomic_use_done(myidx); return 0; } void *qrcu_reader2() { int myidx; while (1) { myidx = idx; if (__VERIFIER_nondet_int()) { __VERIFIER_atomic_use1(myidx); break; } else { if (__VERIFIER_nondet_int()) { __VERIFIER_atomic_use2(myidx); break; } else {} } } readerprogress2 = 1; readerprogress2 = 2; __VERIFIER_atomic_use_done(myidx); return 0; } void* qrcu_updater() { int i; int readerstart1, readerstart2; int sum; __VERIFIER_atomic_take_snapshot(readerstart1, readerstart2); if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; }; if (sum <= 1) { if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; }; } else {} if (sum > 1) { pthread_mutex_lock(&mutex); if (idx <= 0) { ctr2++; idx = 1; ctr1--; } else { ctr1++; idx = 0; ctr2--; } if (idx <= 0) { while (ctr1 > 0); } else { while (ctr2 > 0); } pthread_mutex_unlock(&mutex); } else {} __VERIFIER_atomic_check_progress1(readerstart1); __VERIFIER_atomic_check_progress2(readerstart2); return 0; } int main() { pthread_t t1, t2, t3; pthread_mutex_init(&mutex, 0); pthread_create(&t1, 0, qrcu_reader1, 0); pthread_create(&t2, 0, qrcu_reader2, 0); pthread_create(&t3, 0, qrcu_updater, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> int *buffer; struct timeval t_a, t_b, t_c; double ta; double tb; double tc; int N; int B; int P; int C; pthread_mutex_t mutex; sem_t emptyBuf; sem_t fullBuf; int head = 0; int tail = 0; int special_flag = 0; int* consumer_array; void *producer(void *param) { int i = 0; int prod_id = (int)(intptr_t)param; for (i = prod_id; i < N; i+=P) { if (i%P == prod_id) { sem_wait(&emptyBuf); pthread_mutex_lock(&mutex); buffer[tail] = i; tail = (tail+1) % B; fflush(stdout); pthread_mutex_unlock(&mutex); sem_post(&fullBuf); } } } void *consumer(void *param) { const int B_local = B; int count = 0; int sq_root = 0; int receivedInt = 0; int con_id = (int)(intptr_t)param; if (special_flag == 1) { if (consumer_array[C] == con_id) { sem_wait(&fullBuf); pthread_mutex_lock(&mutex); receivedInt = buffer[head]; head = (head + 1) % B_local; if (sqrt(receivedInt) == (int)sqrt(receivedInt)) { printf("c%d %d %d\\n", con_id, receivedInt,(int)sqrt(receivedInt)); } fflush(stdout); pthread_mutex_unlock(&mutex); sem_post(&emptyBuf); } } while (count < N/C) { sem_wait(&fullBuf); pthread_mutex_lock(&mutex); receivedInt = buffer[head]; head = (head + 1) % B_local; if (sqrt(receivedInt) == (int)sqrt(receivedInt)) { printf("c%d %d %d\\n", con_id, receivedInt,(int)sqrt(receivedInt)); } fflush(stdout); pthread_mutex_unlock(&mutex); sem_post(&emptyBuf); count++; } } int main(int argc, char *argv[]) { N = atoi(argv[1]); B = atoi(argv[2]); P = atoi(argv[3]); C = atoi(argv[4]); if (N % C != 0) { special_flag = 1; } buffer = (int *)malloc(sizeof(int)*B); consumer_array = (int *)malloc(sizeof(int)*C); pthread_mutex_init(&mutex, 0); sem_init(&emptyBuf, 0, B); sem_init(&fullBuf, 0, 0); pthread_t prod_thread[P]; pthread_t con_thread[C]; int i; int k; gettimeofday(&t_a, 0); ta = t_a.tv_sec + t_a.tv_usec/1000000.0; for(i = 0; i < P; i++) { if (pthread_create(&prod_thread[i],0,producer,(void *)(intptr_t)i) != 0) { printf ("Unable to create producer thread\\n"); exit(1); } } for(k = 0; k < C; k++) { consumer_array[k] = k; if (pthread_create(&con_thread[k],0,consumer, (void *)(intptr_t)k) != 0) { printf ("Unable to create consumer thread\\n"); exit(1); } } gettimeofday(&t_b, 0); tb = t_b.tv_sec + t_b.tv_usec/1000000.0; for (i = 0; i < P; i++) { pthread_join(prod_thread[i],0); } for (k = 0; k < C; k++) { pthread_join(con_thread[k],0); } printf("...\\n"); printf("System Execution Time: %.6lf seconds\\n", tb-ta); return 0; return 0; }
0
#include <pthread.h> static void *handle_case(size_t num, size_t nsize) { size_t size; void *ret; if (!num || !nsize) return (0); size = num * nsize; if (nsize != size / num) return (0); ret = malloc(size); if (!ret) return (0); ft_memset(ret, 0, size); return (ret); } void *calloc(size_t num, size_t nsize) { void *ret; pthread_mutex_lock(&g_malloc_lock); ret = handle_case(num, nsize); pthread_mutex_unlock(&g_malloc_lock); return (ret); }
1
#include <pthread.h> static struct termios old, new; static struct termios g_old_kbd_mode; static char *device = "default"; float buffer_null[1024]; int main(void) { int err; int j,k; num_det = 0; send = 0; Fs = 44100; durationdefaultsize = 0; mode = 2; num_jef[0] = 2; num_jef[1] = 4; num_jef[2] = 9; num_jef[3] = 4; num_jef[4] = 0; num_jef[5] = 6; num_jef[6] = 1; num_jef[7] = 2; digit = num_jef[0]; for(j = 0; j < 1024; j++) { buffer_null[j] = 0; } buffer_2048 = (float **) malloc(sizeof(float*) * 16); buffer_11793 = (float **) malloc(sizeof(float*) * 16); buffer_22562 = (float **) malloc(sizeof(float*) * 16); buffer_33331 = (float **) malloc(sizeof(float*) * 16); buffer_44100 = (float **) malloc(sizeof(float*) * 16); for(k=0; k<16;k++){ buffer_2048[k] = (float *) malloc(sizeof(float) * 2048 ); buffer_11793[k] = (float *) malloc(sizeof(float) * 11793 ); buffer_22562[k] = (float *) malloc(sizeof(float) * 22562 ); buffer_33331[k] = (float *) malloc(sizeof(float) * 33331 ); buffer_44100[k] = (float *) malloc(sizeof(float) * 44100 ); } gen_tones(buffer_2048, 2048); gen_tones(buffer_11793, 11793); gen_tones(buffer_22562, 22562); gen_tones(buffer_33331, 33331); gen_tones(buffer_44100, 44100); set_station(); pthread_create( &thread1, 0, finding_freq, 0); pthread_create(&tkc, 0, menu, 0); while (ch1 != 'q') { if ((err = snd_pcm_open(&handle_w, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0) { printf("Playback open error: %s\\n", snd_strerror(err)); exit(1); } if ((err = snd_pcm_set_params(handle_w, SND_PCM_FORMAT_FLOAT, SND_PCM_ACCESS_RW_INTERLEAVED, 1, Fs, 1, 100000)) < 0) { printf("Playback open error: %s\\n", snd_strerror(err)); exit(1); } while((mode==1) & (ch1 != 'q')) { if(send){ switch( durationdefaultsize ) { case 0: (void) snd_pcm_writei(handle_w, buffer_2048[digit_], 2048); break; case 1: (void) snd_pcm_writei(handle_w, buffer_11793[digit_], 11793); break; case 2: (void) snd_pcm_writei(handle_w, buffer_22562[digit_], 22562); break; case 3: (void) snd_pcm_writei(handle_w, buffer_33331[digit_], 33331); break; case 4: (void) snd_pcm_writei(handle_w, buffer_44100[digit_], 44100); break; default: break; } send = 0; } else (void) snd_pcm_writei(handle_w, buffer_null, 1024); } snd_pcm_close(handle_w); usleep(100000); if ((err = snd_pcm_open (&handle_r, device, SND_PCM_STREAM_CAPTURE, 0)) < 0) { exit (1); } if ((err = snd_pcm_set_params(handle_r, SND_PCM_FORMAT_FLOAT, SND_PCM_ACCESS_RW_INTERLEAVED, 1, Fs, 1, 100000)) < 0) { printf("Playback open error: %s\\n", snd_strerror(err)); exit(1); } digit = num_jef[0]; num_det = 0; while((mode==0) & (ch1 != 'q')) { pthread_mutex_lock(&mutex_f); pthread_mutex_unlock(&mutex_s); pthread_mutex_lock(&mutex_w1); (void) snd_pcm_readi(handle_r, buffer_f, 2048); pthread_mutex_unlock(&mutex_w1); pthread_mutex_lock(&mutex_s); pthread_mutex_unlock(&mutex_f); (void) snd_pcm_readi(handle_r, buffer_s, 2048); } snd_pcm_close(handle_r); usleep(100000); } return 0; }
0
#include <pthread.h> sem_t th1_sem; sem_t th2_sem; pthread_mutex_t rsrcA; char filename[100]; FILE *fp; pthread_t thread1; pthread_t thread2; int32_t linecount, wordcount, charcount; void sighandler(int signum) { printf("Received signal %d\\n", signum); if(signum == SIGUSR1) { if(sem_post(&th1_sem)) perror("sem_post"); } else if(signum == SIGUSR2) { if(sem_post(&th2_sem)) perror("sem_post"); } if(signum == SIGTERM) { if(fp != 0) fclose(fp); pthread_kill(thread1, SIGTERM); pthread_kill(thread1, SIGTERM); sem_destroy(&th1_sem); sem_destroy(&th2_sem); pthread_mutex_destroy(&rsrcA); printf("Graceful exit \\n"); exit(0); } } void *thread1_fn() { char ch; while(1) { if(sem_wait(&th1_sem)) printf("sem_wait error\\n"); else { printf("File Analysis\\n"); pthread_mutex_lock(&rsrcA); fp = fopen(filename,"r"); if (!fp ) { printf("File could not be opened\\n"); } else { linecount = 0; wordcount = 0; charcount = 0; while ((ch=getc(fp)) != EOF) { if (ch != ' ' && ch != '\\n') { ++charcount; } if (ch == ' ' || ch == '\\n') { ++wordcount; } if (ch == '\\n') { ++linecount; } } } fclose(fp); fp = 0; pthread_mutex_unlock(&rsrcA); } } } void *thread2_fn() { while(1) { if(sem_wait(&th2_sem)) printf("sem_wait error\\n"); else { printf("Results of the File Analysis\\n"); pthread_mutex_lock(&rsrcA); printf("Lines : %d \\n", linecount); printf("Words : %d \\n", wordcount); printf("Characters : %d \\n", charcount); pthread_mutex_unlock(&rsrcA); } } } int main() { struct sigaction act; int ch; memset(&act, 0, sizeof(act)); act.sa_handler = sighandler; sigaction(SIGUSR1, &act, 0); sigaction(SIGUSR2, &act, 0); sigaction(SIGTERM, &act, 0); sem_init(&th1_sem, 0, 0); sem_init(&th2_sem, 0, 0); pthread_mutex_init(&rsrcA, 0); printf("Enter a filename :"); scanf("%s",filename); fp = fopen(filename,"w"); if (!fp ) { printf("File could not be opened\\n"); } else { printf("Enter text into file (characters after * are ignored)\\n"); while(1) { scanf("%c",(char*)&ch); if((char)ch == '*') { break; } fputc(ch, fp); } } fclose(fp); fp = 0; printf("Waiting for signals\\n"); if(pthread_create(&thread1, 0, &thread1_fn, 0)) { printf("Error creating thread 1\\n"); return 1; } if(pthread_create(&thread2, 0, &thread2_fn, 0)) { printf("Error creating thread 2\\n"); return 1; } if(pthread_join(thread1, 0)) { printf("Error joining thread\\n"); return 2; } if(pthread_join(thread2, 0)) { printf("Error joining thread\\n"); return 2; } if(pthread_mutex_destroy(&rsrcA) != 0) perror("mutex A destroy"); if(sem_destroy(&th1_sem)) perror("sem destroy"); if(sem_destroy(&th2_sem)) perror("sem destroy"); return 0; }
1
#include <pthread.h> int i = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; double x; double y; double z; double acc; double roll; double pitch; double yaw; timespec_t time; } attitude_t; attitude_t attitude; void *writer(void *ptr) { pthread_mutex_lock(&mutex); printf("writing data\\n"); i++; attitude.x = i; attitude.y = i; attitude.z = i; attitude.acc = i; attitude.roll = i; attitude.pitch = i; attitude.yaw = i; clock_gettime(0, &(attitude.time)); printf("Wrote data\\n"); printf("x:\\t\\t%f\\n", attitude.x); printf("y:\\t\\t%f\\n", attitude.y); printf("z:\\t\\t%f\\n", attitude.z); printf("acc:\\t\\t%f\\n", attitude.acc); printf("roll:\\t\\t%f\\n", attitude.roll); printf("pitch:\\t\\t%f\\n", attitude.pitch); printf("yaw:\\t\\t%f\\n", attitude.yaw); printf("timestamp:\\t%ld\\n", attitude.time.tv_nsec); printf("\\n"); usleep(15000000); pthread_mutex_unlock(&mutex); } void *reader(void *ptr) { int ret = -1; struct timespec delay; time_t current; delay.tv_sec = 0; delay.tv_nsec = 0; sleep(1); while(ret != 0) { delay.tv_sec = time(0) + 10; ret = pthread_mutex_timedlock(&mutex, &delay); if (ret != 0) { current = time(0); printf("No new data available at time %ld\\n", current); } } printf("Got data\\n"); printf("Reading attitude\\n"); printf("x:\\t\\t%f\\n", attitude.x); printf("y:\\t\\t%f\\n", attitude.y); printf("z:\\t\\t%f\\n", attitude.z); printf("acc:\\t\\t%f\\n", attitude.acc); printf("roll:\\t\\t%f\\n", attitude.roll); printf("pitch:\\t\\t%f\\n", attitude.pitch); printf("yaw:\\t\\t%f\\n", attitude.yaw); printf("timestamp:\\t%ld\\n", attitude.time.tv_nsec); printf("\\n"); pthread_mutex_unlock(&mutex); } int main() { pthread_t thread1, thread2; pthread_mutex_init(&mutex, 0); for (int j = 0; j < 5; j++) { pthread_create(&thread1, 0, reader, 0); pthread_create(&thread2, 0, writer, 0); pthread_join(thread1, 0); pthread_join(thread2, 0); } exit(0); }
0
#include <pthread.h> int typ; int pocz; int kon; int numer; } par_t; volatile int running_threads = 0; volatile int p_count = 0; pthread_mutex_t primes_mutex = PTHREAD_MUTEX_INITIALIZER; int pid; int chid; void *count_primes2(void *arg) { int status; int coid; par_t reply; coid = ConnectAttach(ND_LOCAL_NODE, pid, chid, _NTO_SIDE_CHANNEL, 0); while (1) { par_t args; args.typ = 10; args.numer = pthread_self(); status = MsgSend(coid, &args, sizeof(args), &reply, sizeof(reply)); if (reply.typ == 1) { sleep(1); int primes_count = 0; printf("Proces: %d, watek: %d\\n", getpid(), pthread_self()); int i; for (i = reply.pocz; i < reply.kon; i++) { int c; int prime = 1; for (c = 2; c <= i / 2; c++) { if (i % c == 0) { prime = 0; break; } } if (prime && i != 0 && i != 1) primes_count++; } printf("\\twatek: %d, poczatek %d, koniec %d, primes %d\\n", pthread_self(), reply.pocz, reply.kon, primes_count); pthread_mutex_lock(&primes_mutex); p_count += primes_count; pthread_mutex_unlock(&primes_mutex); } else if (reply.typ == 0) { return 0; } } } int main(int argc, char *argv[]) { pid = getpid(); chid = ChannelCreate(0); if (argc != 4) { printf("Proper usage: ./lab2 range_start range_end thread_count\\n"); return 0; } int range_start = atoi(argv[1]); int range_end = atoi(argv[2]); int threads_count = atoi(argv[3]); int range_length = (range_end - range_start) / (threads_count * 4); int i = 0; int f = 0; pthread_t tid; while (1) { if (running_threads < threads_count && !f) { pthread_create(&tid, 0, count_primes2, 0); running_threads++; continue; } else { f = 1; par_t args; int rcvid = MsgReceive(chid, &args, sizeof(args), 0); if (range_start + (i + 1) * range_length <= range_end) { if (args.typ == 10) { args.typ = 1; args.numer = i; args.pocz = range_start + i * range_length; args.kon = range_start + (i + 1) * range_length; int status = MsgReply(rcvid, EOK, &args, sizeof(args)); if (-1 == status) { perror("MsgReply"); } } i++; } else { args.typ = 0; int status = MsgReply(rcvid, EOK, &args, sizeof(args)); if (-1 == status) { perror("MsgReply"); } printf("Watek %d poprosil, ale nie ma\\n", args.numer); running_threads--; if (!running_threads) { break; } } } } printf("Liczb pierwszych: %d\\n", p_count); return 0; }
1
#include <pthread.h> static volatile sig_atomic_t iSig_quit; static volatile sig_atomic_t iSig_stats; static FILE* fout = 0; static void close_file(void* f) { fclose((FILE*)f); } static void* print_stats(void* arg) { pthread_detach(pthread_self()); ER_PTH(pthread_mutex_lock, &rep.mtx, "lock", 0, 0); if (!iSig_quit && fprintf(fout, "%ld - %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld\\n", (unsigned long)time(0), rep.stats->nput, rep.stats->nput_failed, rep.stats->nupdate, rep.stats->nupdate_failed, rep.stats->nget, rep.stats->nget_failed, rep.stats->nremove, rep.stats->nremove_failed, rep.stats->nlock, rep.stats->nlock_failed, rep.stats->concurrent_connections, rep.stats->current_size, rep.stats->max_size, rep.stats->current_objects, rep.stats->max_objects) < 0) { pthread_mutex_unlock(&rep.mtx); return (void*)-1; } pthread_mutex_unlock(&rep.mtx); fflush(fout); return (void*)0; } void* signal_setter(void* arg) { sigset_t mask; struct sigaction sa; int sig; pthread_t t_print_stats; sigfillset(&mask); pthread_sigmask(SIG_SETMASK, &mask, 0); iSig_quit = 0; memset(&sa, 0, sizeof(sa)); sa.sa_handler = sigusr1; sigaction(SIGUSR1, &sa, 0); sa.sa_handler = force_quit; sigaction(SIGINT, &sa, 0); sigaction(SIGTERM, &sa, 0); sigaction(SIGQUIT, &sa, 0); if (conf.StatFileName) fout = fopen(conf.StatFileName, "a"); if (fout) sa.sa_handler = sigusr2; else sa.sa_handler = SIG_IGN; sigaction(SIGUSR2, &sa, 0); pthread_cleanup_push(close_file, fout); pthread_detach(pthread_self()); sigemptyset(&mask); sigaddset(&mask, SIGALRM); pthread_sigmask(SIG_SETMASK, &mask, 0); while (!iSig_quit) { sigwait(&mask, &sig); if (iSig_stats) { pthread_create(&t_print_stats, 0, print_stats, 0); iSig_stats = 0; } } pthread_cleanup_pop(1); pthread_exit((void*)0); } void sigusr1(int s) { if (!conf.StatFileName || !fout) return; iSig_stats = 1; pthread_kill(t_signal, SIGALRM); } void sigusr2(int s) { pthread_mutex_lock(&gest_cli.mtx); gest_cli.shutting_down = 1; pthread_cond_signal(&gest_cli.cond_work); pthread_mutex_unlock(&gest_cli.mtx); iSig_quit = 1; pthread_cancel(t_dispatcher); pthread_kill(t_signal, SIGALRM); } void force_quit(int s) { iSig_quit = STOP_SIG = 1; pthread_cancel(t_dispatcher); pthread_kill(t_signal, SIGALRM); }
0
#include <pthread.h> pthread_t *threads; pthread_mutex_t mutex_variable; int nb_readers; sem_t sem_writers; }struct_priority_reader; void init_priority_reader(struct_priority_reader *struct_priority) { sem_init(&(struct_priority->sem_writers), 0, 1); pthread_mutex_init(&(struct_priority->mutex_variable),0); struct_priority->nb_readers=0; } int hasard(int inf, int sup) { return inf + (int)((double)(sup - inf + 1) * rand() / ((double)32767 + 1)); } void writer_lock(struct_priority_reader *struct_priority) { sem_wait(&(struct_priority->sem_writers)); } void write_msg() { printf("%s\\n","J'écris le fichier" ); sleep(1); } void writer_unlock(struct_priority_reader *struct_priority) { sem_post(&(struct_priority->sem_writers)); } void reader_lock(struct_priority_reader *struct_priority) { pthread_mutex_lock(&(struct_priority->mutex_variable)); struct_priority->nb_readers++; if(struct_priority->nb_readers==1) sem_wait(&(struct_priority->sem_writers)); pthread_mutex_unlock(&(struct_priority->mutex_variable)); } void read_msg() { printf("%s\\n","Je suis le lecteur" ); sleep(1); } void reader_unlock(struct_priority_reader *struct_priority) { pthread_mutex_lock(&(struct_priority->mutex_variable)); struct_priority->nb_readers--; if(struct_priority->nb_readers==0) sem_post(&(struct_priority->sem_writers)); pthread_mutex_unlock(&(struct_priority->mutex_variable)); } void* thread_reader(void* data) { struct_priority_reader* struct_priority; struct_priority = (struct_priority_reader*) data; reader_lock(struct_priority); read_msg(); reader_unlock(struct_priority); return 0; } void* thread_writer(void* data) { struct_priority_reader* struct_priority; struct_priority = (struct_priority_reader*) data; writer_lock(struct_priority); write_msg(); writer_unlock(struct_priority); return 0; } int main(int argc, char **argv) { srand(time(0)) ; int nb_thread = 0; int idx_thread= 0; if(argc<1) { printf("%s","Merci d'entrer le nombre de thread" ); return 0; } nb_thread=(int)strtol(argv[1], (char **)0, 10); threads= malloc(nb_thread*sizeof(pthread_t)); struct_priority_reader* struct_reader_writer; struct_reader_writer = malloc(sizeof(struct_priority_reader)); init_priority_reader(struct_reader_writer); int nb_reader=0; int nb_writer=0; while(idx_thread!=nb_thread) { if(hasard(0,1)) { pthread_create(&threads[idx_thread],0,thread_reader,struct_reader_writer); nb_reader++; } else { pthread_create(&threads[idx_thread],0,thread_writer,struct_reader_writer); nb_writer++; } idx_thread++; } printf("%d%s\\n",nb_reader," lecteurs créés." ); printf("%d%s\\n",nb_writer," ecrivains créés." ); idx_thread = 0; while(idx_thread!=nb_thread) { pthread_join(threads[idx_thread],0); idx_thread++; } return 0; }
1
#include <pthread.h> int mojazmiennaglobalna; pthread_mutex_t mojmuteks=PTHREAD_MUTEX_INITIALIZER; void *Hello(void *arg) { int i,j; for ( i=0; i<20; i++ ) { pthread_mutex_lock(&mojmuteks); j=mojazmiennaglobalna; j=j+1; printf("."); fflush(stdout); sleep(1); mojazmiennaglobalna=j; pthread_mutex_unlock(&mojmuteks); } return 0; } int main(void) { pthread_t mojwatek; int i; if ( pthread_create( &mojwatek, 0, Hello, 0) ) { printf("błąd przy tworzeniu wątka."); abort(); } for ( i=0; i<20; i++) { pthread_mutex_lock(&mojmuteks); mojazmiennaglobalna=mojazmiennaglobalna+1; pthread_mutex_unlock(&mojmuteks); printf("o"); fflush(stdout); sleep(1); } if ( pthread_join ( mojwatek, 0 ) ) { printf("błąd przy kończeniu wątka."); abort(); } printf("\\nWartość mojej zmiennej globalnej to %d\\n",mojazmiennaglobalna); exit(0); }
0
#include <pthread.h> void *req_handler(void *); void *pro_handler(void *); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int n; char buffer[256]; char record[50][3][20],temp[50][3][20],result[50][3][20]; char services[25][50] = { "AddTwoNumbers","SubtractTwoNumbers","MultiplyTwoNumbers","DivideTwoNumbers","SquarRoot","Square","Area","Volume","Perimeter", "Circumference","SurfaceArea","Integrate","Differentiate","Power","Logarithm","StringLength","Encrypt","Decrypt","EdgeDetection", "FFT","RayTracing","VolumRendering","ZBuffer","TextureMapping","MotionBlurr"}; int counter = 0; int a; void error(char *msg) { perror(msg); exit(1); } int main(int argc, char *argv[]) { int sockfd, newsockfd, portno, requestor, provider; struct sockaddr_in brok_addr, requ_addr; int ab; if (argc < 2) { fprintf(stderr,"ERROR, no port provided\\n"); exit(1); } sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); bzero((char *) &brok_addr, sizeof(brok_addr)); portno = atoi(argv[1]); brok_addr.sin_family = AF_INET; brok_addr.sin_addr.s_addr = INADDR_ANY; brok_addr.sin_port = htons(portno); if (bind(sockfd, (struct sockaddr *) &brok_addr, sizeof(brok_addr)) < 0) error("ERROR on binding"); listen(sockfd,5); requestor = sizeof(requ_addr); printf("Waiting for incoming connections\\n"); while(1){ newsockfd = accept(sockfd, (struct sockaddr *) &requ_addr, &requestor); if (newsockfd < 0) error("ERROR on accept"); puts("connection Accepted"); read(newsockfd, &ab, sizeof(int)); pthread_t req_thrd, pro_thrd; int *new_sock = malloc(1); *new_sock = newsockfd; if(ab == 1 ) { if(pthread_create(&req_thrd, 0, req_handler, (void*)new_sock) < 0) { puts("Could not creating thread"); return 1; } puts("connection1 Handler assigned"); close(newsockfd); } else { if(pthread_create(&pro_thrd, 0, pro_handler, (void*)new_sock) < 0) { puts("Could not creating thread"); return 1; } puts("connection2 Handler assigned"); } bzero(buffer,256); } return 0; } void *req_handler(void *sock) { int req_sock = *(int *)sock; int c=0; n = read(req_sock, &a, sizeof(int)); if(n < 0) puts("Error reading from socket"); printf("%d\\n",a ); pthread_mutex_lock(&mutex); for (int i = 0; i < counter; ++i) { if(strcmp(services[a-1],temp[i][2]) == 0) { strcpy(result[c][0],temp[i][0]); strcpy(result[c][1],temp[i][1]); strcpy(result[c][2],temp[i][2]); ++c; } } write(req_sock, result, sizeof(char)*50*3*20); pthread_mutex_unlock(&mutex); free(sock); } void *pro_handler(void *sock) { int pro_sock = *(int *)sock; int i,j,k,rows; while(1) { pthread_mutex_lock(&mutex); n = read(pro_sock, record,sizeof(char)*50*3*20); if (n < 0) error("ERROR reading from socket"); for(i=0;i<counter;i++) { if(strcmp(record[0][1],temp[i][1])==0) { for(j=0;j<2;j++) { for(k=i;k<counter;k++) { strcmp(temp[k][j],temp[k+1][j]); } --i; --counter; } } } for ( i = 0; i < 50; ++i) { if (strcmp(record[i][0],"") == 0) { break; } for (j = 0; j < 3; ++j) { strcpy(temp[counter][j],record[i][j]); } if(strcmp(record[i][0],"") != 0) { counter = counter + 1; } } pthread_mutex_unlock(&mutex); bzero(record,sizeof(char)*50*3*20); for ( i = 0; i < counter; ++i) { for (j = 0; j < 3; ++j) { printf("%s\\t",temp[i][j]); } printf("\\n"); } n = write(pro_sock,"I got your message",18); if (n < 0) error("ERROR writing to socket"); } }
1
#include <pthread.h> pthread_mutex_t mutexsum; int *a, *b; long sum=0.0; void* dotprod(void* arg){ int i, start, end, offset, len; long tid; tid = (long)arg; offset = tid; len = 100000; start = offset*len; end = start + len; printf("thread: %ld starting. start=%d end=%d\\n",tid,start,end-1); for (i=start; i<end ; i++) { pthread_mutex_lock(&mutexsum); sum += (a[i] * b[i]); pthread_mutex_unlock(&mutexsum); } printf("thread: %ld done. Global sum now is=%li\\n",tid,sum); pthread_exit((void*) 0); } int main (int argc, char* argv[]){ long i; void* status; pthread_t threads[8]; pthread_attr_t attr; a = (int*) malloc (8*100000*sizeof(int)); b = (int*) malloc (8*100000*sizeof(int)); for (i=0; i<100000*8; i++) a[i]=b[i]=1; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0;i<8;i++) pthread_create(&threads[i], &attr, dotprod, (void *)i); pthread_attr_destroy(&attr); for(i=0;i<8;i++) { pthread_join(threads[i], &status); } printf ("Final Global Sum=%li\\n",sum); free (a); free (b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
0
#include <pthread.h> int buffer[8]; int head = 0; int tail = 0; int num_elem = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void * produtor(){ int i = 0; while(i < 64){ sleep(1); if(num_elem < 8){ pthread_mutex_lock(&mutex); buffer[tail] = rand() % 64; printf("Produtor: acrescentei o numero %d\\n", buffer[tail]); tail = (tail+1) % 8; num_elem++; i++; pthread_mutex_unlock(&mutex); } else{ printf("Produtor: O buffer está cheio\\n"); } } } void * consumidor(){ int i; while(i < 64){ sleep(2); if(num_elem > 0){ pthread_mutex_lock(&mutex); printf("Consumidor: Consumi o numero %d\\n", buffer[head]); head = (head+1) % 8; num_elem--; i++; pthread_mutex_unlock(&mutex); } else{ printf("Consumidor: O buffer está vazio\\n"); } } } int main(int argc, char const *argv[]) { pthread_t threads[2]; pthread_create(&threads[0], 0, produtor, 0); pthread_create(&threads[1], 0, consumidor, 0); pthread_join(threads[0], 0); pthread_join(threads[1], 0); return 0; }
1
#include <pthread.h> int *vet; int left; int right; } mergeParamType; int swapsCount; int runningThreadsSorting; pthread_mutex_t runningThreadsSortingME; mergeParamType *params; int nthreads; sem_t sem1, sem2; void inefficientSort(int *v, int dim); void bubbleSort(mergeParamType *param); void *threadFunction(void * param); int main (int argc, char ** argv) { int n, len; struct stat stat_buf; int fd; char *paddr; int *v; if (argc != 2) { printf ("Syntax: %s filename\\n", argv[0]); return (1); } if ((fd = open (argv[1], O_RDWR)) == -1) perror ("open"); if (fstat (fd, &stat_buf) == -1) perror ("fstat"); len = stat_buf.st_size; n = len / sizeof (int); paddr = mmap ((caddr_t) 0, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (paddr == (caddr_t) - 1) perror ("mmap"); close (fd); v = (int *) paddr; inefficientSort(v, n); pthread_exit(0); printf("i am not executed!\\n"); return 0; } void inefficientSort(int *v, int dim) { int i; pthread_t *threads; nthreads = ceil(log10(dim)); int region_size = dim / nthreads; threads = malloc(nthreads * sizeof(pthread_t)); params = malloc (nthreads * sizeof(mergeParamType)); setbuf(stdout, 0); pthread_mutex_init(&runningThreadsSortingME, 0); sem_init(&sem1, 0, 0); sem_init(&sem2, 0, 0); runningThreadsSorting = nthreads; setbuf(stdout, 0); for (i = 0; i < nthreads; i++) { params[i].vet = v; params[i].left = region_size * i; if(i == nthreads - 1) { params[i].right = dim - 1; } else { params[i].right = region_size * (i + 1) -1; } pthread_create(&threads[i], 0, threadFunction, &params[i]); } } void bubbleSort(mergeParamType *p) { int *vet = p->vet; int l = p->left; int r = p->right; int i, j, temp; for (i = l; i < r; i++) { for (j = l; j < r - i + l; j++) { if (vet[j] > vet[j+1]) { temp = vet[j]; vet[j] = vet[j+1]; vet[j+1] = temp; } } } return; } void *threadFunction(void * param) { mergeParamType *p = (mergeParamType *)param; int i, j = 0, k; pthread_detach(pthread_self()); do { bubbleSort(param); pthread_mutex_lock(&runningThreadsSortingME); k = --runningThreadsSorting; pthread_mutex_unlock(&runningThreadsSortingME); if (k == 0) { swapsCount = 0; for(i = 0; i < nthreads - 1; i++) { int extreme = params[i].right; if (p->vet[extreme] > p->vet[extreme + 1]) { int temp = p->vet[extreme]; p->vet[extreme] = p->vet[extreme + 1]; p->vet[extreme + 1] = temp; swapsCount++; } } for(i = 0; i < nthreads; i++) { sem_post(&sem1); } } sem_wait(&sem1); pthread_mutex_lock(&runningThreadsSortingME); k = ++runningThreadsSorting; pthread_mutex_unlock(&runningThreadsSortingME); if(k == nthreads) { for(i = 0; i < nthreads; i++) { sem_post(&sem2); } } sem_wait(&sem2); j++; } while(swapsCount); return 0; }
0