text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg); int pthread_join(pthread_t thread, void **retval); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; long iteration; int NTHREADS; long nfot; unsigned int seed1; unsigned int seed2; float PI; int globalSayac = 0; int tumNoktalar = 0; int j; float x, y; void* runner(void* arg) { pthread_mutex_lock(&mutex); for (j = 0; j < nfot; j++) { tumNoktalar = tumNoktalar + 1; x = rand_r(&seed1) % 1; y = rand_r(&seed2) % 1; if ((x * x + y * y) <= 1) { globalSayac = globalSayac + 1; } } pthread_mutex_unlock(&mutex); } int main(int argc, char *argv[]) { int i; seed1 = time(0); seed2 = time(0); if (argc != 3) { fprintf(stderr, "Usage: %s <Iteration> <NumThread>\\n", argv[0]); exit(1); } iteration = atol(argv[1]); NTHREADS = atoi(argv[2]); nfot = iteration / NTHREADS; pthread_t threads[NTHREADS]; threads[NTHREADS] = malloc((NTHREADS * sizeof(pthread_t))); for (i = 0; i < NTHREADS; i++) { pthread_create(&threads[i], 0, runner, 0); } for (i = 0; i < NTHREADS; i++) { pthread_join(threads[i], 0); } pthread_mutex_destroy(&mutex); PI = (globalSayac / tumNoktalar) * 4; printf("PI = %f\\n", PI); return 0; }
1
#include <pthread.h> struct msm_frame* get_frame(struct fifo_queue* queue) { struct msm_frame *p = 0; do{}while(0); pthread_mutex_lock(&(queue->mut)); do{}while(0); if (queue->front) { struct fifo_node *node = dequeue (queue); do{}while(0); if (node) { p = (struct msm_frame *)node->f; free (node); } } pthread_mutex_unlock(&(queue->mut)); do{}while(0); return p; } int8_t add_frame(struct fifo_queue* queue, struct msm_frame *p) { if (!p) { do{}while(0); return FALSE; } do{}while(0); do{}while(0); pthread_mutex_lock(&(queue->mut)); struct fifo_node *node = malloc (sizeof (struct fifo_node)); if (node) { node->f = p; node->next = 0; enqueue (queue, node); } else { pthread_mutex_unlock(&(queue->mut)); do{}while(0); return FALSE; } pthread_mutex_unlock(&(queue->mut)); do{}while(0); return TRUE; } inline void flush_queue (struct fifo_queue* queue) { do{}while(0); pthread_mutex_lock(&(queue->mut)); while (queue->front) { struct fifo_node *node = dequeue (queue); if (node) { do{}while(0) ; free (node); } } pthread_mutex_unlock(&(queue->mut)); do{}while(0); } inline void flush_and_destroy_queue (struct fifo_queue* queue) { do{}while(0); pthread_mutex_lock(&(queue->mut)); while (queue->front) { struct fifo_node *node = dequeue (queue); if (node) { do{}while(0) ; if (node->f) free(node->f); free (node); } } pthread_mutex_unlock(&(queue->mut)); do{}while(0); } void wait_queue (struct fifo_queue* queue) { do{}while(0); pthread_mutex_lock(&(queue->mut)); if ((queue->num_of_frames) <=0){ pthread_cond_wait(&(queue->wait), &(queue->mut)); } pthread_mutex_unlock(&(queue->mut)); do{}while(0); } void signal_queue (struct fifo_queue* queue) { do{}while(0); pthread_mutex_lock(&(queue->mut)); pthread_cond_signal(&(queue->wait)); pthread_mutex_unlock(&(queue->mut)); do{}while(0); } struct msm_frame* begin (void** iterator, struct fifo_queue* queue) { struct fifo_node *node = queue->front; struct msm_frame *p = 0; *iterator = (void *)node; if (node == 0) return p; p = (struct msm_frame *)node->f; return p; } struct msm_frame* next (void** iterator) { struct fifo_node *node = (struct fifo_node *)*iterator; struct msm_frame *p = 0; if (node == 0) return p; node = node->next; if (node == 0) return p; p = (struct msm_frame *)node->f; *iterator = (void *)node; return p; } struct msm_frame* end (struct fifo_queue* queue) { struct fifo_node *node = queue->back; struct msm_frame *p = 0; if (node == 0) return p; p = (struct msm_frame *)node->f; return p; }
0
#include <pthread.h> void * thread_fcn(void * thread_arg); int myID; int num_threads; double step; double *sum_p; pthread_mutex_t *lock_p; } thread_args_t; int main(int argc, char *argv[]) { double start_time, end_time; double pi; double sum = 0.0; double step = 1.0/(double) 400000000; int num_threads = get_integer_environment("NUM_THREADS", 1, "number of threads"); thread_args_t thread_args[num_threads]; pthread_t threads[num_threads]; pthread_mutex_t lock; start_time = get_time(); pthread_mutex_init(&lock, 0); for (int i = 0; i < num_threads; ++i) { thread_args_t * args_p = &thread_args[i]; args_p->myID = i; args_p->num_threads = num_threads; args_p->step = step; args_p->sum_p = &sum; args_p->lock_p = &lock; } for (int i = 0; i < num_threads; ++i) pthread_create(&threads[i], 0, thread_fcn, (void *) &thread_args[i]); for (int i = 0; i < num_threads; ++i) pthread_join(threads[i], 0); pthread_mutex_destroy(&lock); pi = step * sum; end_time = get_time(); printf("parallel program results with %d threads:\\n", num_threads); printf("computed pi = %g (%17.15f)\\n",pi, pi); printf("difference between computed pi and math.h M_PI = %17.15f\\n", fabs(pi - 3.14159265358979323846)); printf("time to compute = %g seconds\\n", end_time - start_time); return 0; } void * thread_fcn(void * thread_arg) { thread_args_t * args_p = (thread_args_t *) thread_arg; double x; double part_sum = 0.0; for (int i=args_p->myID; i < 400000000; i += args_p->num_threads) { x = (i+0.5)*args_p->step; part_sum += 4.0/(1.0+x*x); } pthread_mutex_lock(args_p->lock_p); *(args_p->sum_p) += part_sum; pthread_mutex_unlock(args_p->lock_p); pthread_exit((void* ) 0); }
1
#include <pthread.h> int fd_ip = -1; int fd_ip_server; pthread_mutex_t mutex_fd_ip; char bf_ip[256] = ""; void *setup_ip(void *arg){ struct sockaddr_in addr_server = { 0 }, addr_client = { 0 }; pthread_t thread_read; int portno, fd_temp; printf("Port No: "); scanf("%d",&portno); fd_ip_server = socket(AF_INET, SOCK_STREAM, 0); if(fd_ip_server < 0){ perror("ERROR opening ip socket.\\n"); } addr_server.sin_family = AF_INET; addr_server.sin_addr.s_addr = INADDR_ANY; addr_server.sin_port = htons(portno); if(bind(fd_ip_server, (struct sockaddr *) &addr_server, sizeof(addr_server)) < 0) perror("ERROR on binding.\\n"); printf("Rpi listening to port %d\\n", portno); listen(fd_ip_server,5); int len_client = sizeof(addr_client); while((fd_temp = accept(fd_ip_server, (struct sockaddr *) &addr_client, &len_client)) >= 0){ if(fd_ip >= 0){ pthread_mutex_lock(&mutex_fd_ip); close(fd_ip); fd_ip = fd_temp; pthread_mutex_unlock(&mutex_fd_ip); } else { fd_ip = fd_temp; } printf("Accept connection from PC.\\n"); pthread_create(&thread_read, 0, from_ip, (void*)1); } printf("Socket closed. Stop transmitting.\\n"); pthread_exit(0); } void *from_ip(void *arg){ while(1){ bzero(bf_ip,sizeof(bf_ip)); if(read(fd_ip,bf_ip,sizeof(bf_ip)) <= 0) break; printf("Receive: %s\\n",bf_ip); } printf("Disconnection occurs. Thread terminating...\\n"); pthread_exit(0); } void close_ip(){ close(fd_ip); close(fd_ip_server); printf("Close from socket.\\n"); } int main(){ printf("Program start up!\\n"); pthread_attr_t attr; pthread_t threads; pthread_mutex_init(&mutex_fd_ip,0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads,&attr, setup_ip, (void*)1); pthread_join(threads,0); pthread_attr_destroy(&attr); pthread_mutex_destroy(&mutex_fd_ip); printf("Program terminating...\\n"); pthread_exit(0); }
0
#include <pthread.h>extern void __VERIFIER_error(); unsigned int __VERIFIER_nondet_uint(); static int top = 0; static unsigned int arr[800]; pthread_mutex_t m; _Bool flag = 0; void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { top == 0 ? 1 : 0; } int push(unsigned int *stack, int x) { if (top == 800) { printf("stack overflow\\n"); return -1; } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (get_top() == 0) { printf("stack underflow\\n"); return -2; } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for (i = 0; i < 800; i++) { __CPROVER_assume(((800 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint() % 800; if (push(arr, tmp) == (-1)) error(); flag = 1; pthread_mutex_unlock(&m); } } } void *t2(void *arg) { int i; for (i = 0; i < 800; i++) { __CPROVER_assume(((800 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); if (flag) { if (!(pop(arr) != (-2))) error(); } pthread_mutex_unlock(&m); } } } int main(void) { pthread_t id1; pthread_t id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> struct cometData { int sendCount; struct cometData *next_cd; long long ch_id; pthread_mutex_t ch_mutex; pthread_cond_t ch_cond; char *httpDomain; long long extraData; } *cdList = 0; pthread_mutex_t cdlMutex; char * callHomeScript = "<script type=\\"text/javascript\\">top.postMessage(\\"CallHome %lld\\",\\"%s\\")</script>"; static int toClient(void *cls, uint64_t pos, char *buf, int max) { struct timespec abstime = { 0, 0 }; struct timeval curtime; struct cometData *cd = cls; int slb, rslt; char * keepAliveMsg = "<script type=\\"text/javascript\\">top.postMessage(\\"CallHome keepalive\\",\\"%s\\")</script>"; char * startingMsg = "<script type=\\"text/javascript\\">top.postMessage(\\"CallHome starting %lld\\",\\"%s\\")</script>"; char * restartMsg = "<script type=\\"text/javascript\\">location.reload(1)</script>"; if( cd->sendCount++ == 0) { if (max < strlen(startingMsg)+10) return 0; sprintf(buf,startingMsg,cd->ch_id,cd->httpDomain); } else if (cd->sendCount > 1000) { if (max < strlen(restartMsg)+10,cd->httpDomain) return 0; sprintf(buf,restartMsg); } else { pthread_mutex_lock(&cd->ch_mutex); gettimeofday(&curtime, 0); abstime.tv_sec = curtime.tv_sec + 30; rslt = pthread_cond_timedwait(&cd->ch_cond, &cd->ch_mutex, &abstime); pthread_mutex_unlock(&cd->ch_mutex); if( rslt == ETIMEDOUT) { if( max < strlen(keepAliveMsg)+1) return 0; sprintf(buf,keepAliveMsg,cd->httpDomain); } else { if (max < strlen(callHomeScript)+strlen(cd->httpDomain)+10) return 0; sprintf(buf,callHomeScript,cd->extraData,cd->httpDomain); } } slb = strlen(buf); memset (&buf[slb], ' ', max-slb-1); buf[max-1] = '\\n'; return max; } static int callHomeIn(void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **ptr) { static int aptr; struct MHD_Response *response; int ret; long long id; long long extra; char *httpDomain; if (0 != strcmp(method, MHD_HTTP_METHOD_GET)) return MHD_NO; if (&aptr != *ptr) { *ptr = &aptr; return MHD_YES; } *ptr = 0; if (strcmp(&url[1],"idcreate")==0) { struct cometData *cd; id = atoll(MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "id")); pthread_mutex_lock(&cdlMutex); for(cd = cdList; cd!=0; cd=cd->next_cd) { if( id==cd->ch_id) { break; } } if( cd==0) { cd = (struct cometData *)malloc(sizeof(struct cometData)); cd->next_cd = cdList; cd->ch_id = id; pthread_mutex_init(&cd->ch_mutex, 0); pthread_cond_init (&cd->ch_cond, 0); cdList = cd; response = MHD_create_response_from_data(strlen("OK"), (void *) "OK", MHD_NO, MHD_NO); ret = MHD_queue_response(connection, MHD_HTTP_OK, response); } else { response = MHD_create_response_from_data(strlen("Failed"), (void *) "Failed", MHD_NO, MHD_NO); ret = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response); } pthread_mutex_unlock(&cdlMutex); } else if (strcmp(&url[1],"fromserver")==0) { struct cometData *cd; id = atoll(MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "id")); extra = atoll(MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "extra")); for(cd = cdList; cd!=0; cd=cd->next_cd) { if( id==cd->ch_id) { pthread_mutex_lock(&cd->ch_mutex); cd->extraData = extra; pthread_cond_signal(&cd->ch_cond); pthread_mutex_unlock(&cd->ch_mutex); break; } } if( cd==0) { } response = MHD_create_response_from_data(strlen("OK"), (void *) "OK", MHD_NO, MHD_NO); ret = MHD_queue_response(connection, MHD_HTTP_OK, response); } else if (strcmp(&url[1],"toclient")==0) { struct cometData *cd; id = atoll(MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "id")); httpDomain = MHD_lookup_connection_value (connection, MHD_GET_ARGUMENT_KIND, "httpDomain"); for(cd = cdList; cd!=0; cd=cd->next_cd) { if( id==cd->ch_id) { break; } } if( cd==0) { response = MHD_create_response_from_data(strlen("not found"), (void *) "not found", MHD_NO, MHD_NO); ret = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response); } else { if (cd->httpDomain!=0 && strcmp(cd->httpDomain,httpDomain)!=0) { free(cd->httpDomain); cd->httpDomain = 0; } if( cd->httpDomain == 0) { cd->httpDomain = (char *)malloc(strlen(httpDomain)+1); strcpy(cd->httpDomain,httpDomain); } cd->sendCount = 0; cd->extraData = 0; response = MHD_create_response_from_callback (-1, 256, &toClient, (void *)cd, 0); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); } } else { response = MHD_create_response_from_data(strlen("Eh?"), (void *) "Eh?", MHD_NO, MHD_NO); ret = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response); } MHD_destroy_response(response); return ret; } int main(int argc, char * const *argv) { struct MHD_Daemon *d; if (argc != 2) { printf("usage: %s PORT\\n", argv[0]); return 1; } pthread_mutex_init(&cdlMutex,0); d = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG, atoi( argv[1]), 0, 0, &callHomeIn, 0, MHD_OPTION_END); if (d == 0) return 1; for(;;) sleep(600); MHD_stop_daemon(d); return 1; }
0
#include <pthread.h> pthread_t thread_id; int thread_num,id; int copy_COUNT_GLOBAL; char color[6]; int condition; } ThreadData; pthread_mutex_t jet_mutex; int CONDITION_JET ,COUNT_GLOBAL; void jetFly(ThreadData *jet){ pthread_mutex_lock(&jet_mutex); if(CONDITION_JET== jet->condition){ CONDITION_JET = jet->id; COUNT_GLOBAL++; jet->copy_COUNT_GLOBAL = COUNT_GLOBAL; printf("COUNT_GLOBAL = %d jet->color = %s CONDITION_JET = %d\\n", jet->copy_COUNT_GLOBAL,jet->color,CONDITION_JET); } pthread_mutex_unlock(&jet_mutex); } void *fly_API(void *thread) { ThreadData *jet = (ThreadData*)thread; while(COUNT_GLOBAL < 10){ jetFly(jet); sleep(2); } pthread_exit(0); } void init_data(ThreadData *jet){ COUNT_GLOBAL=0; CONDITION_JET=2; jet[0].condition=2; jet[0].id=0; jet[0].copy_COUNT_GLOBAL=COUNT_GLOBAL; strcpy(jet[0].color, "green"); jet[1].id=1; jet[1].condition=0; jet[1].copy_COUNT_GLOBAL=COUNT_GLOBAL; strcpy(jet[1].color, "yellow"); jet[2].id=2; jet[2].condition=1; jet[2].copy_COUNT_GLOBAL=COUNT_GLOBAL; strcpy(jet[2].color, "red"); } int main(int argc, char *argv[]) { int i; ThreadData thread[3]; init_data(thread); for(i=0;i<3;i++){ printf("jet[%d].condition=%d\\n",thread[i].id,thread[i].condition); printf("-----------------------------------------\\n"); } pthread_mutex_init(&jet_mutex, 0); for(i=0; i<3; i++) { thread[i].thread_num=i; pthread_create(&(thread[i].thread_id), 0, fly_API, (void *)(&thread[i])); } for (i = 0; i < 3; i++){ pthread_join(thread[i].thread_id, 0); } pthread_mutex_destroy(&jet_mutex); return 0; }
1
#include <pthread.h> pthread_mutex_t m; int s; void* thr1(void* arg) { int l = __VERIFIER_nondet_int(0, 1000); l = 4; pthread_mutex_lock (&m); s = l; __VERIFIER_assert (s == l); pthread_mutex_unlock (&m); return 0; } int main() { s = __VERIFIER_nondet_int(0, 1000); pthread_t t[5]; pthread_mutex_init (&m, 0); int i = 0; pthread_create (&t[i], 0, thr1, 0); i++; pthread_create (&t[i], 0, thr1, 0); i++; pthread_create (&t[i], 0, thr1, 0); i++; pthread_create (&t[i], 0, thr1, 0); i++; pthread_create (&t[i], 0, thr1, 0); return 0; }
0
#include <pthread.h> int flag = 0; pthread_mutex_t m; pthread_cond_t c = PTHREAD_COND_INITIALIZER; void * thread1(void *p) { for(;;){ pthread_mutex_lock(&m); while ( flag == 0) pthread_cond_wait(&c, &m); pthread_mutex_unlock(&m); if (flag ){ write(1, p, 1); sleep(1); } } } int main() { pthread_mutex_init(&m, 0); pthread_t tid1; pthread_t tid2; pthread_create(&tid1,0,thread1, "."); pthread_create(&tid2,0,thread1, "*"); for(;;) { char ch; char d; scanf("%c", &ch); scanf("%c", &d); pthread_mutex_lock(&m); if ( ch == 'a') { flag = 1; pthread_cond_signal(&c); } else if ( ch == 'b') { flag = 1; pthread_cond_broadcast(&c); } else { flag = 0; } pthread_mutex_unlock(&m); sleep(1); } pthread_join(tid1,0); pthread_join(tid2,0); pthread_mutex_destroy(&m); }
1
#include <pthread.h> static pthread_once_t g_init = PTHREAD_ONCE_INIT; static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t g_lcd_lock = PTHREAD_MUTEX_INITIALIZER; static struct light_state_t g_notification; static struct light_state_t g_battery; struct led_data redled = { .max_brightness = "/sys/class/leds/red/max_brightness", .brightness = "/sys/class/leds/red/brightness", .delay_on = "/sys/class/leds/red/delay_on", .delay_off = "/sys/class/leds/red/delay_off", .blink = 0 }; struct led_data greenled = { .max_brightness = "/sys/class/leds/green/max_brightness", .brightness = "/sys/class/leds/green/brightness", .delay_on = "/sys/class/leds/green/delay_on", .delay_off = "/sys/class/leds/green/delay_off", .blink = 0 }; struct led_data blueled = { .max_brightness = "/sys/class/leds/blue/max_brightness", .brightness = "/sys/class/leds/blue/brightness", .delay_on = "/sys/class/leds/blue/delay_on", .delay_off = "/sys/class/leds/blue/delay_off", .blink = 0 }; struct led_data lcd = { .max_brightness = "/sys/class/leds/lcd_backlight0/max_brightness", .brightness = "/sys/class/leds/lcd_backlight0/brightness", .delay_on = "/sys/class/leds/lcd_backlight0/delay_on", .delay_off = "/sys/class/leds/lcd_backlight0/delay_off", .blink = 0 }; void init_globals(void) { pthread_mutex_init(&g_lock, 0); pthread_mutex_init(&g_lcd_lock, 0); } static int write_int(const char* path, int val) { int fd = open(path, O_WRONLY); ALOGE_IF(fd < 0,"Failed to open %s", path); if (fd < 0) return -1; char buffer[20]; int bytes = sprintf(buffer, "%d\\n", val); ssize_t amt = write(fd, buffer, (size_t)bytes); close(fd); return amt == -1 ? -1 : 0; } static int read_int(const char *path) { char buffer[12]; int fd = open(path, O_RDONLY); ALOGE_IF(fd < 0, "Failed to open %s", path); if (fd < 0) return -1; int rc = read(fd, buffer, sizeof(buffer) -1); close(fd); if (rc <= 0) return -1; buffer[rc] = 0; return strtol(buffer, 0, 0); } static int is_lit(struct light_state_t const* state) { return state->color & 0x00ffffff; } static int rgb_to_brightness(struct light_state_t const* state) { int color = state-> color & 0x00ffffff; return ((77 * ((color >> 16) & 0x00ff)) + (150 * ((color >> 8) & 0x00ff)) + (29 * (color & 0x00ff))) >> 8; } static int set_light_backlight(struct light_device_t* dev, struct light_state_t const* state) { int err; int brightness = (rgb_to_brightness(state) * 39); int max_brightness = read_int(lcd.max_brightness); if(!dev) return -1; pthread_mutex_lock(&g_lcd_lock); err = write_int(lcd.brightness, brightness); pthread_mutex_unlock(&g_lcd_lock); return err; } static int set_speaker_light_locked(struct light_device_t* dev, struct light_state_t const* state) { int red, green, blue, brightness; bool blink; int delay_on, delay_off; unsigned int colorRGB; if(!dev) return -1; switch (state->flashMode) { case LIGHT_FLASH_NONE: delay_on = 0; delay_off = 0; brightness = 0; break; case LIGHT_FLASH_TIMED: delay_on = state->flashOnMS; delay_off = state->flashOffMS; break; default: delay_on = 0; delay_off = 0; break; } colorRGB = state->color; red = (colorRGB >> 16) & 0xFF; green = (colorRGB >> 8) & 0xFF; blue = colorRGB & 0xFF; if(delay_on > 0 && delay_off > 0) { blink = 1; if (red) { write_int(redled.delay_on, delay_on); write_int(redled.delay_off, delay_off); } if (green) { write_int(greenled.delay_on, delay_on); write_int(greenled.delay_off, delay_off); } if (blue) { write_int(blueled.delay_on, delay_on); write_int(blueled.delay_off, delay_off); } else { write_int(redled.brightness, red); write_int(greenled.brightness, green); write_int(blueled.brightness, blue); } } return 0; } static int close_lights(struct light_device_t *dev) { if (dev) free(dev); return 0; } static int open_lights(const struct hw_module_t* module, char const* name, struct hw_device_t** device) { int (*set_light)(struct light_device_t* dev, struct light_state_t const* state); if (0 == strcmp(LIGHT_ID_BACKLIGHT, name)) set_light = set_light_backlight; else return -EINVAL; pthread_once(&g_init, init_globals); struct light_device_t *dev = malloc(sizeof(struct light_device_t)); if(!dev) return -ENOMEM; memset(dev, 0, sizeof(*dev)); dev->common.tag = HARDWARE_DEVICE_TAG; dev->common.version = 0; dev->common.module = (struct hw_module_t*)module; dev->common.close = (int (*)(struct hw_device_t*))close_lights; dev->set_light = set_light; *device = (struct hw_device_t*)dev; return 0; } static struct hw_module_methods_t lights_module_methods = { .open = open_lights, }; struct hw_module_t HAL_MODULE_INFO_SYM = { .tag = HARDWARE_MODULE_TAG, .version_major = 1, .version_minor = 0, .id = LIGHTS_HARDWARE_MODULE_ID, .name = "Honor 8 LED driver", .author = "Honor 8 Dev Team.", .methods = &lights_module_methods, };
0
#include <pthread.h> void *thread_function_Even(void *arg); void *thread_function_Odd(void *arg); void *Read_Buff(void *arg); int run_now = 1; int i = 0; sem_t bin_sem1; sem_t bin_sem2; int Buffer[50]; char message[] = "Hello World"; pthread_mutex_t work_mutex; int main(void) { int res; pthread_t a_thread_even, b_thread_odd, read_thread; void *thread_result_even, *thread_result_odd, *read_buff_result; res = sem_init(&bin_sem1, 0, 0); if(res != 0){ perror("Semaphore creation is failed\\n"); exit(1); } res = sem_init(&bin_sem2, 0, 1); if(res != 0){ perror("Semaphore creation is failed\\n"); exit(1); } res = pthread_mutex_init(&work_mutex, 0); if(res != 0){ perror("Mutex creation is failed\\n"); exit(1); } res = pthread_create(&a_thread_even, 0, thread_function_Even, (void *)message); if(res != 0){ perror("Thread creation is failed\\n"); exit(1); } printf("waiting for thread to finish............\\n"); res = pthread_create(&read_thread, 0, Read_Buff, (void *)message); if(res != 0){ perror("read_buff Thread joined is failed\\n"); exit(1); } res = pthread_join(a_thread_even, &thread_result_even); if(res != 0){ perror("even Thread joined is failed\\n"); exit(1); } printf("%s\\n",(char *)thread_result_even); res = pthread_join(read_thread, &read_buff_result); if(res != 0){ perror("read buff Thread joined is failed\\n"); exit(1); } printf("%s\\n",(char *)read_buff_result); exit(0); } void *thread_function_Even(void *arg) { int in=0; for(i =0; i<10; i++){ if(i%2 == 0){ sem_wait(&bin_sem2); pthread_mutex_lock(&work_mutex); Buffer[in] = i; printf(" write on BUFF = %d\\n",i); in = (in +1)% 50 ; pthread_mutex_unlock(&work_mutex); sem_post(&bin_sem1); } } pthread_exit("Even function is done \\n"); } void *Read_Buff(void *arg) { int out=0, item; while(out != 5){ sem_wait(&bin_sem1); pthread_mutex_lock(&work_mutex); item = Buffer[out]; printf("reading is done %d\\n",item); out = (out +1)%50; pthread_mutex_unlock(&work_mutex); sem_post(&bin_sem2); } pthread_exit("reading done e\\n"); }
1
#include <pthread.h> struct job { int id; struct job *next; }; void process_job (struct job *one_job) { printf("Thread_%d is process job %d\\n", (int)pthread_self (), one_job->id); } pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER; void *thread_func (void *data) { while (1) { struct job *next_job; struct job **job_queue = (struct job **)data; pthread_mutex_lock (&job_queue_mutex); if (*job_queue == 0) next_job = 0; else { next_job = *job_queue; *job_queue = (*job_queue)->next; } pthread_mutex_unlock (&job_queue_mutex); if (next_job == 0) break; process_job (next_job); free (next_job); } return 0; } void enqueue_job (struct job **job_queue, struct job * new_job) { pthread_mutex_lock (&job_queue_mutex); new_job->next = *job_queue; *job_queue = new_job; pthread_mutex_unlock (&job_queue_mutex); } int main() { const int SIZE = 3; pthread_t threads[SIZE]; int i; struct job *job_queue = 0; for (i = 0; i < SIZE; i++) { pthread_create (&(threads[i]), 0, thread_func, &job_queue); } for (i = 0; i < 10; i++) { struct job *new_job = malloc (sizeof (struct job)); new_job->id = i; enqueue_job (&job_queue, new_job); sleep(1); } for (i = 0; i < SIZE; i++) { pthread_join (threads[i], 0); } return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; struct timespec timeout; int use_timeout; void *run(void *arg) { int retcode; printf("in child: sleeping\\n"); sleep(2); if (use_timeout) { retcode = pthread_mutex_timedlock(&mutex, &timeout); } else { retcode = pthread_mutex_lock(&mutex); } handle_thread_error(retcode, "child failed (timed)lock", PROCESS_EXIT); printf("child got mutex\\n"); sleep(5); printf("child releases mutex\\n"); pthread_mutex_unlock(&mutex); printf("child released mutex\\n"); sleep(10); printf("child exiting\\n"); return 0; } void usage(char *argv0, char *msg) { printf("%s\\n\\n", msg); printf("Usage:\\n\\n%s\\n lock mutexes without lock\\n\\n%s -t <number>\\n lock mutexes with timout after given number of seconds\\n", argv0, argv0); exit(1); } int main(int argc, char *argv[]) { int retcode; use_timeout = (argc >= 2 && strcmp(argv[1], "-t") == 0); if (is_help_requested(argc, argv)) { usage(argv[0], ""); } timeout.tv_sec = (time_t) 200; timeout.tv_nsec = (long) 0; if (use_timeout && argc >= 3) { int t; sscanf(argv[2], "%d", &t); timeout.tv_sec = (time_t) t; } printf("timout(%ld sec %ld msec)\\n", (long) timeout.tv_sec, (long) timeout.tv_nsec); pthread_t thread; pthread_create(&thread, 0, run, 0); printf("in parent: setting up\\n"); pthread_mutex_init(&mutex, 0); sleep(2); printf("in parent: getting mutex\\n"); if (use_timeout) { retcode = pthread_mutex_timedlock(&mutex, &timeout); } else { retcode = pthread_mutex_lock(&mutex); } handle_thread_error(retcode, "parent failed (timed)lock", PROCESS_EXIT); printf("parent got mutex\\n"); sleep(5); printf("parent releases mutex\\n"); pthread_mutex_unlock(&mutex); printf("parent released mutex\\n"); printf("parent waiting for child to terminate\\n"); pthread_join(thread, 0); pthread_mutex_destroy(&mutex); printf("done\\n"); exit(0); }
1
#include <pthread.h> { int p_index; int c_index; int num[2]; }BUFFER; BUFFER buf; pthread_mutex_t pc_mutex; pthread_cond_t pc_condp, pc_condc; void * producer(void * nul) { int i; for (i = 1; i <= 10; ++i) { pthread_mutex_lock(&pc_mutex); while(buf.p_index == buf.c_index) { printf("producer wait \\n"); pthread_cond_wait(&pc_condp, &pc_mutex); } buf.num[buf.p_index] = i; printf("producer produces buf[%d] = %d \\n", buf.p_index, buf.num[buf.p_index] ); buf.p_index++; buf.p_index %= 2; sleep(2); pthread_cond_signal(&pc_condc); pthread_mutex_unlock(&pc_mutex); } pthread_exit(0); } void * consumer(void * nul) { int i; for (i = 1; i <= 10; ++i) { pthread_mutex_lock(&pc_mutex); while(buf.p_index == (buf.c_index + 1)% 2) { printf("consumer wait \\n"); pthread_cond_wait(&pc_condc, &pc_mutex); } buf.c_index += 1; buf.c_index %= 2; printf("consumer consumes buf[%d] = %d \\n",buf.c_index, buf.num[buf.c_index]); buf.num[buf.c_index] = 0; sleep(1); pthread_cond_signal(&pc_condp); pthread_mutex_unlock(&pc_mutex); } pthread_exit(0); } int main(int argc, char const *argv[]) { int i; pthread_t thread[3]; pthread_attr_t attr; for (i = 0; i < 2; ++i) { buf.num[i] = 0; } buf.p_index = 1; buf.c_index = 0; pthread_mutex_init(&pc_mutex, 0); pthread_cond_init(&pc_condp, 0); pthread_cond_init(&pc_condc, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&thread[0], &attr, producer, 0); pthread_create(&thread[2], &attr, producer, 0); pthread_create(&thread[1], &attr, consumer, 0); pthread_join(thread[0], 0); pthread_join(thread[1], 0); pthread_join(thread[2], 0); pthread_mutex_destroy(&pc_mutex); pthread_cond_destroy(&pc_condc); pthread_cond_destroy(&pc_condp); pthread_attr_destroy(&attr); pthread_exit(0); return 0; }
0
#include <pthread.h> pthread_mutex_t m[3]; int printed=0; void* print_message ( void* str ){ int i = 0; int k = 1; int err; pthread_mutex_lock( &m[2]); if (printed) pthread_mutex_unlock(&m[0]); for ( i = 0; i < 4*3; i++ ){ if (err=pthread_mutex_lock(&m[k])) printf("%s Gotcha! - lock %d, error %s\\n", str, k, strerror(err)); k=(k+1)%3; if (err=pthread_mutex_unlock(&m[k])) printf("%s Gotcha! - unlock %d, error %s\\n", str, k, strerror(err)); if (k==2) { printf("Message : %s\\n", (char*)str); printed=1; } k=(k+1)%3; } pthread_mutex_unlock( &m[2] ); return 0; } int main ( int argc, char* argv ){ pthread_t pthread; pthread_mutexattr_t mattr; int i=0; int err; pthread_mutexattr_init(&mattr); if (pthread_mutexattr_settype(&mattr, PTHREAD_MUTEX_ERRORCHECK)) printf("boo\\n"); for (i=0; i<3; i++) pthread_mutex_init(&m[i], &mattr); pthread_mutex_lock(&m[0]); if ( err = pthread_create (&pthread, 0, print_message, (void*)"child" )){ fprintf ( stderr, "Error in creating thread %s\\n", strerror(err)); exit(0); } while (!printed) { sched_yield(); } print_message ( (void*) "parent" ); pthread_join(pthread, 0); for (i=0; i<3; i++) pthread_mutex_destroy( &m[i] ); printf("\\n"); pthread_exit (0); return 0; }
1
#include <pthread.h> char* fila[FILA_MAX]; pthread_mutex_t mutex; sem_t consumidor; int index_produtor; int index_consumidor; int working=1; void * thread_code (void * args); char* myfiles[NB_FILES]; void init_myfiles () { int i,n,counter; int numbers[NB_FILES]; char* tmp; srand(time(0)); counter= NB_FILES; for (i=0; i< NB_FILES; i++) { myfiles[i] = malloc (15); sprintf (myfiles[i], "SO2014-%1d.txt", i); } for(i=0;i< NB_THREADS;++i){ n = rand() % counter; tmp = myfiles[n+i]; myfiles[n+i] = myfiles[i]; myfiles[i] = tmp; counter--; } } int main(){ struct timeval st , et; int i, error; pthread_t threads[NB_THREADS]; int returnValues[NB_THREADS]; pthread_mutex_init(&mutex, 0); sem_init(&consumidor,0,0); index_produtor=0; index_consumidor=0; init_myfiles (); gettimeofday(&st , 0); for(i=0;i<NB_THREADS;i++){ error = pthread_create(&threads[i], 0, thread_code,0); } char buffer[2]; printf("Ficheiro:"); int n=scanf("%s", &buffer); while (strcmp(buffer,"sair")!=0){ for (i=0; i< NB_FILES; i++) { if(strcmp(myfiles[i], buffer)==0){ pthread_mutex_lock(&mutex); fila[index_produtor] = malloc (15); sprintf (fila[index_produtor],buffer); index_produtor=(index_produtor+1)%FILA_MAX; sem_post(&consumidor); pthread_mutex_unlock(&mutex); } } printf("Ficheiro:"); n=scanf("%s", &buffer); } return 0; for(i=0;i<NB_THREADS;i++){ pthread_join(threads[i], (void *) &returnValues[i]); } gettimeofday(&et , 0); printf("Running time of program: %d microseconds\\n",(et.tv_usec - st.tv_usec)); pthread_mutex_destroy(&mutex); sem_destroy(&consumidor); return 0; } void * thread_code (void * args) { int res; while (working){ res=1; char* file_to_open = malloc(15); sem_wait(&consumidor); pthread_mutex_lock(&mutex); file_to_open = fila[index_consumidor]; printf("%s",file_to_open); index_consumidor=(index_consumidor+1)%FILA_MAX; pthread_mutex_unlock(&mutex); printf("%s\\n", file_to_open); int fd; struct timeval tvstart; if (gettimeofday(&tvstart, 0) == -1) { perror("Could not get time of day, exiting."); res= -1; } srandom ((unsigned)tvstart.tv_usec); fd = open (file_to_open, O_RDONLY); printf("Monitor will check if file %s is consistent...\\n", file_to_open); if (fd == -1) { perror ("Error opening file"); res= -1; } else { char string_to_read[STRING_SZ]; char first_string[STRING_SZ]; int i, nbytes; if (flock(fd, LOCK_SH | LOCK_NB) < 0) { if (errno == EWOULDBLOCK) perror ("Wait unlock"); else { perror ("Error locking file"); res= -1; } } if (flock(fd, LOCK_SH) < 0) { perror ("Error locking file"); res= -1; } if (read (fd, first_string, STRING_SZ) == -1) { perror ("Error reading file"); res= -1; } for (i=0; i<NB_ENTRIES-1; i++) { if ((nbytes = read (fd, string_to_read, STRING_SZ)) == -1) { perror ("Error reading file"); res= -1; break; } if (nbytes == 0){ fprintf (stderr, "\\nInconsistent file (too few lines): %s\\n", file_to_open); res= -1; break; } if (strncmp(string_to_read, first_string, STRING_SZ)) { fprintf (stderr, "\\nInconsistent file: %s\\n", file_to_open); res= -1; break; } } if (read (fd, string_to_read, STRING_SZ) > 0){ fprintf (stderr, "\\nInconsistent file (too many lines): %s\\n", file_to_open); res= -1; break; } if (flock(fd, LOCK_UN) < 0) { perror ("Error unlocking file"); res= -1; break; } if (close (fd) == -1) { perror ("Error closing file"); res= -1; break; } } if (res==1) printf("It's ok!!!\\n"); else printf("It's wrong\\n"); } pthread_exit((void*)1); }
0
#include <pthread.h> int thread_count_; int **dp_; int city_count_; pthread_mutex_t *muts; void* thread_subcal (void* rank); int main (int argc, char* argv[]) { long thread_i; pthread_t* thread_handle_pt; double start, end; if (argc < 2) { printf("Please indicate the number of threads!\\n"); return 1; } thread_count_ = strtol(argv[1], 0, 10); Lab2_loadinput(&dp_, &city_count_); thread_handle_pt = malloc(thread_count_*sizeof(pthread_t)); muts = malloc(city_count_ * sizeof(pthread_mutex_t)); int z; for (z = 0; z < city_count_; z++) { pthread_mutex_init(&muts[z], 0); } GET_TIME(start); for (thread_i = 0; thread_i < thread_count_; ++thread_i) { pthread_create(&thread_handle_pt[thread_i], 0, thread_subcal, (void*)thread_i); } for (thread_i = 0; thread_i < thread_count_; ++thread_i) { pthread_join(thread_handle_pt[thread_i], 0); } GET_TIME(end); printf("The elapsed time is %lfs.\\n", end-start); for (z = 0; z < city_count_; z++) { pthread_mutex_destroy(&muts[z]); } free(thread_handle_pt); Lab2_saveoutput(dp_, city_count_, end-start); DestroyMat(dp_, city_count_); return 0; } void* thread_subcal(void* rank){ long myrank = (long)rank; int i, j, k, temp; for (k = 0; k < city_count_; ++k) { pthread_mutex_lock(&muts[k]); for (i = myrank * city_count_ / thread_count_; i < (myrank + 1) * city_count_ / thread_count_; ++i) { if (i != k) { while (pthread_mutex_trylock(&muts[i]) != 0) { pthread_mutex_unlock(&muts[k]); pthread_mutex_lock(&muts[k]); } } for (j = 0; j < city_count_; ++j) { if ((temp = dp_[i][k]+dp_[k][j]) < dp_[i][j]) dp_[i][j] = temp; } if (i != k) { pthread_mutex_unlock(&muts[i]); } } pthread_mutex_unlock(&muts[k]); } return 0; }
1
#include <pthread.h> pthread_t thread1, thread2, thread3; pthread_mutex_t lock1, lock2, lock3; void *workOne(void *arg) { pthread_mutex_lock(&lock1); usleep(1000); pthread_mutex_lock(&lock2); usleep(1000); pthread_mutex_unlock(&lock2); pthread_mutex_unlock(&lock1); return arg; } void *workTwo(void *arg) { pthread_mutex_lock(&lock2); usleep(1000); pthread_mutex_lock(&lock3); usleep(1000); pthread_mutex_unlock(&lock3); pthread_mutex_unlock(&lock2); return arg; } void *workThree(void *arg) { pthread_mutex_lock(&lock3); usleep(1000); pthread_mutex_lock(&lock1); usleep(1000); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock3); return arg; } int main() { int ret; ret = pthread_mutex_init(&lock1, 0); if (ret) { fprintf(stderr, "pthread_mutex_init, error: %d\\n", ret); return ret; } ret = pthread_mutex_init(&lock2, 0); if (ret) { fprintf(stderr, "pthread_mutex_init, error: %d\\n", ret); return ret; } ret = pthread_mutex_init(&lock3, 0); if (ret) { fprintf(stderr, "pthread_mutex_init, error: %d\\n", ret); return ret; } ret = pthread_create(&thread1, 0, workOne, 0); if (ret) { fprintf(stderr, "pthread_create, error: %d\\n", ret); return ret; } ret = pthread_create(&thread2, 0, workTwo, 0); if (ret) { fprintf(stderr, "pthread_create, error: %d\\n", ret); return ret; } ret = pthread_create(&thread3, 0, workThree, 0); if (ret) { fprintf(stderr, "pthread_create, error: %d\\n", ret); return ret; } ret = pthread_join(thread1, 0); if (ret) { fprintf(stderr, "pthread_join, error: %d\\n", ret); return ret; } ret = pthread_join(thread2, 0); if (ret) { fprintf(stderr, "pthread_join, error: %d\\n", ret); return ret; } ret = pthread_join(thread3, 0); if (ret) { fprintf(stderr, "pthread_join, error: %d\\n", ret); return ret; } ret = pthread_mutex_destroy(&lock3); if (ret) { fprintf(stderr, "pthread_mutex_destroy, error: %d\\n", ret); return ret; } ret = pthread_mutex_destroy(&lock2); if (ret) { fprintf(stderr, "pthread_mutex_destroy, error: %d\\n", ret); return ret; } ret = pthread_mutex_destroy(&lock1); if (ret) { fprintf(stderr, "pthread_mutex_destroy, error: %d\\n", ret); return ret; } return 0; }
0
#include <pthread.h> int main(int argc, char *argv[]) { int rc; joblist_t *job; pthread_t udsserverThread; pthread_t tcpserverThread; pthread_t announceThread; pthread_t discoverThread; pthread_t expireThread; openlog("peerslave", LOG_PID | LOG_PERROR, LOG_USER); setlogmask(LOG_MASK(LOG_EMERG) | LOG_MASK(LOG_ALERT) | LOG_MASK(LOG_CRIT)); peerinit(0); if ((rc = pthread_create(&tcpserverThread, 0, tcpserver, (void *)0))>0) { PANIC("failed to start tcpserver thread\\n"); } else { DEBUG(LOG_NOTICE, "started tcpserver thread"); } if ((rc = pthread_create(&announceThread, 0, announce, (void *)0))>0) { PANIC("failed to start announce thread\\n"); } else { DEBUG(LOG_NOTICE, "started announce thread"); } if ((rc = pthread_create(&discoverThread, 0, discover, (void *)0))>0) { PANIC("failed to start discover thread\\n"); } else { DEBUG(LOG_NOTICE, "started discover thread"); } if ((rc = pthread_create(&expireThread, 0, expire, (void *)0))>0) { DEBUG(LOG_NOTICE, "failed to start expire thread"); exit(1); } else { DEBUG(LOG_NOTICE, "started expire thread"); } pthread_mutex_lock(&mutexhost); host->status = STATUS_IDLE; pthread_mutex_unlock(&mutexhost); while (1) { fprintf(stderr, "test: --------------------------\\n"); pthread_mutex_lock(&mutexjoblist); if (joblist) { fprintf(stderr, "test: job.version = %u\\n", joblist->job->version); fprintf(stderr, "test: job.id = %u\\n", joblist->job->id); fprintf(stderr, "test: job.argsize = %u\\n", joblist->job->argsize); fprintf(stderr, "test: job.optsize = %u\\n", joblist->job->optsize); fprintf(stderr, "test: host.name = %s\\n", joblist->host->name); fprintf(stderr, "test: host.port = %u\\n", joblist->host->port); fprintf(stderr, "test: host.id = %u\\n", joblist->host->id); } pthread_mutex_unlock(&mutexjoblist); usleep(1000000); } return 0; }
1
#include <pthread.h> size_t k; int file; char* word; int N; pthread_t* threads; volatile sig_atomic_t *thread_complete; pthread_mutex_t mutex; struct thread_args { int id; } **args; void exit_program(int status, char* message) { if(status == 0) { printf("%s\\n",message); } else { perror(message); } exit(status); } int seek_for_word(char *buffer) { char id_str[sizeof(int)], text[RECORDSIZE+1]; char *strtok_pointer; char strtok_buf[RECORDSIZE*k]; strtok_pointer = strtok_buf; for(int i =0;i<k;++i) { char *p = strtok_r(buffer, SEPARATOR,&strtok_pointer); strcpy(id_str, p); int id = atoi(id_str); p = strtok_r(0, "\\n",&strtok_pointer); if(p!=0) { strncpy(text, p, RECORDSIZE+1); if (strstr(text, word) != 0) { return id; } } } return -1; } void *parallel_reader(void *arg) { pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,0); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,0); int id; char buffer[1024*k]; struct thread_args *tmp = arg; int jump = tmp->id; long multiplier = RECORDSIZE*jump*k; while(pread(file,buffer,RECORDSIZE*k,multiplier) > 0) { if((id = seek_for_word(buffer)) != -1) { pthread_mutex_lock(&mutex); printf("Found the word %s! Record id: %d, thread id: %zu\\n",word,id,pthread_self()); pthread_t self_id = pthread_self(); for(int i=0;i<N;++i) { if(threads[i] != self_id) { int err; if(!thread_complete[i]) { if ((err = pthread_cancel(threads[i])) != 0) { fprintf(stderr, "Error cancelling thread %zu: %s\\n", threads[i], strerror(err)); break; } } } } pthread_mutex_unlock(&mutex); pthread_cancel(self_id); } multiplier += (N*RECORDSIZE*k); } pthread_mutex_lock(&mutex); thread_complete[jump] = 1; pthread_mutex_unlock(&mutex); return 0; } void exit_handler() { if(file!=0) { close(file); } if(threads != 0) { free(threads); } if(thread_complete != 0) { free((void *) thread_complete); } if(args !=0) { for (int i = 0; i < N; ++i) { if (args[i] != 0) free(args[i]); } free(args); } } int main(int argc, char ** argv) { if(argc != 5) { exit_program(0, "Pass 4 arguments: N - the number of threads, filename - the name of the file to read records from" "k - the number of records read by a thread in a single access, word - the word we seek in the file for"); } atexit(exit_handler); N = atoi(argv[1]); char *filename = argv[2]; k = (size_t) atoi(argv[3]); if(k<=0 || N <= 0) { exit_program(0,"Pass the N and k parameters > 0"); } word = argv[4]; if((file = open(filename, O_RDONLY)) == -1) { exit_program(1, "Couldn't open the file to read records from"); } pthread_mutex_init(&mutex,0); threads = malloc(sizeof(int)*N); thread_complete = calloc((size_t) N, sizeof(sig_atomic_t)); args = malloc(sizeof(struct thread_args*)*N); for(int i=0;i<N;++i) { args[i] = malloc(sizeof(struct thread_args)); args[i]->id = i; if(pthread_create(&threads[i],0,parallel_reader,args[i])) { exit_program(1,"Failed to create thread"); } } for(int i=0;i<N;++i) { if(pthread_join(threads[i],0)) { exit_program(1,"Threads didn't end successfully"); } } pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> struct foo* fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; int id; pthread_mutex_t f_lock; struct foo* next; }; struct foo* foo_alloc(int id) { struct foo* fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->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->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[HASH[id]]; fp != 0; fp = fp->next) { if (fp->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->id) % 29); tfp = fh[idx]; if (tfp == fp) { fh[idx] = fp->next; } else { while (tfp->next != fp) { tfp = fp->next; } tfp->next = fp->next; } pthread_mutex_unlock(&hashlock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { pthread_mutex_unlock(&hashlock); } }
1
#include <pthread.h> extern pthread_mutex_t global_data_mutex; void update_temp_data (int temp_fd) { char temp[6]; float realtemp; int read_rc; assert(-1 != temp_fd); memset(temp, 0, 6); lseek(temp_fd,0,0); read_rc = read(temp_fd,temp,5); if(0 > read_rc) { close(temp_fd); global_config.temp_fd = -1; return; } realtemp = atof(temp); app_debug(debug, "DS1820 Temp:\\t%2.1f\\n", realtemp); if (global_config.ignore_wsi_temp == 1) { if ((realtemp > (float)150) || (realtemp == (float)0.000)) { app_debug(info, "Got garbage from the DS1820 sensor (%3.2f %s %d). Rejecting\\n", realtemp, temp, read_rc); } else { app_debug(debug, "DS1820 Temp:\\t%2.1f\\n",realtemp); pthread_mutex_lock(&global_data_mutex); global_data.temp = realtemp; global_data.updatetime = time(0); pthread_mutex_unlock(&global_data_mutex); } } return; } void update_temp2_data (int temp_fd) { char temp[6]; float realtemp; int read_rc; assert(-1 != temp_fd); memset(temp, 0, 9); lseek(temp_fd,0,0); read_rc = read(temp_fd,temp,5); if(0 > read_rc) { close(temp_fd); global_config.temp_fd = -1; return; } realtemp = atof(temp); app_debug(debug, "DS1820 Temp:\\t%2.1f\\n",realtemp); if (global_config.ignore_wsi_temp == 1) { if ((realtemp > (float)150) || (realtemp == (float)0.000)) { app_debug(info, "Got garbage from the 2nd DS1820 sensor (%3.2f %s %d). Rejecting\\n", realtemp, temp, read_rc); } else { app_debug(debug,"DS1820 Temp:\\t%2.1f\\n",realtemp); pthread_mutex_lock(&global_data_mutex); global_data.temp2 = realtemp; global_data.updatetime = time(0); pthread_mutex_unlock(&global_data_mutex); } } return; }
0
#include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void *thread() { long i = 0; unsigned int count = 0; struct timeval start, end; float time_cost; gettimeofday(&start, 0); for ( i; i < 10000000; i++ ) { pthread_mutex_lock(&lock); count++; pthread_mutex_unlock(&lock); } gettimeofday(&end, 0); time_cost = 1000000 * (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec); time_cost /= 1000000; printf("%u: count = %u, i = %ld, time_cost = %f\\n", pthread_self(), count, i, time_cost); } int main() { pthread_t tid[50]; int i; for ( i = 0; i < 50; i++ ) pthread_create(&tid[i], 0, thread, 0); for ( i = 0; i < 50; i++ ) pthread_join(tid[i], 0); return 0; }
1
#include <pthread.h> pthread_mutex_t mta, mtb; pthread_t a, b; void* funca(void *arg) { int i; for(i = 0; i < 10; ++ i) { pthread_mutex_lock(&mta); printf("Thread A = %d\\n", (int)pthread_self()); pthread_mutex_unlock(&mtb); } return 0; } void* funcb(void *arg) { int i; for(i = 0; i < 10; ++ i) { pthread_mutex_lock(&mtb); printf("Thread B = %d\\n", (int)pthread_self()); pthread_mutex_unlock(&mta); } return 0; } int main() { pthread_mutex_init(&mta, 0); pthread_mutex_init(&mtb, 0); pthread_mutex_lock(&mtb); pthread_create(&a, 0, funca, 0); pthread_create(&b, 0, funcb, 0); pthread_join(a, 0); pthread_join(b, 0); pthread_mutex_destroy(&mta); pthread_mutex_destroy(&mtb); return 0; }
0
#include <pthread.h> extern struct th *assign_r; extern struct queue *start; extern pthread_mutex_t mut_que; extern pthread_mutex_t mut_th_status; extern pthread_mutex_t mutex_assign; extern pthread_cond_t *thread_wake; extern pthread_cond_t new_in_que; extern pthread_cond_t served; extern int *thread_status; extern int sleep_t; extern int sort; extern int debug; extern int NUM_THREADS; void *schedlr_fn(void *arg) { struct queue *assign=0; int i; int tc; int count; assign=(struct queue*) calloc(1,sizeof(struct queue)); sleep(sleep_t); if (debug ==1 ){ printf("Schedular will start scheduling now after initial %d seconds wait",sleep_t); fflush(stdout);} while(1) { pthread_mutex_lock (&mut_que); i=traverse_queue_wh(); if (i == 0){ pthread_cond_wait(&new_in_que, &mut_que);} i=traverse_queue_wh(); if (sort ==1 && i !=0 ){ schedule_sjf(i);} pthread_mutex_unlock (&mut_que); while ( i != 0) { for (tc =0; tc <=NUM_THREADS-1 ; tc++) { pthread_mutex_lock(&mut_th_status); if ( thread_status[tc] == 0) { if (debug ==1 ){ printf("\\nSchedular found a free thread %d",tc); fflush(stdout);} pthread_mutex_lock(&mut_que); pthread_mutex_lock(&mutex_assign); assign=start; strcpy(assign_r[tc].wh_req,assign->wh_req); strcpy(assign_r[tc].req_type,assign->req_type); strcpy(assign_r[tc].file_or_dir_name,assign->file_or_dir_name); assign_r[tc].size=assign->size; assign_r[tc].fdc=assign->fdc; strcpy(assign_r[tc].in_time,assign->in_time); start=start->next; free(assign); pthread_mutex_unlock(&mut_que); pthread_cond_signal(&thread_wake[tc]); pthread_mutex_unlock(&mutex_assign); thread_status[tc]=1; pthread_mutex_unlock(&mut_th_status); break; } else if ( thread_status[tc] != 0 && tc == NUM_THREADS-1 ) { pthread_mutex_unlock(&mut_th_status); sleep(2); tc=0; } else {pthread_mutex_unlock(&mut_th_status);} } i--; } } pthread_exit(0); }
1
#include <pthread.h> int npoints[4] = {100, 500, 1000, 2000}; static int num_circle_count = 0; pthread_mutex_t circle_lock = PTHREAD_MUTEX_INITIALIZER; float random_gen(float from, float to) { int r = rand(); float fr = (float) r / (float) 32767; fr = fr * (to - from); fr = fr + from; return fr; } void* pi(void *a) { struct timeval start, end; gettimeofday(&start, 0); int npoint = npoints[(int)a]; long circle_count = 0; int i; for(i = 0; i < npoint; i ++){ float x = random_gen(0, 1); float y = random_gen(0, 1); float dis = sqrt(x * x + y * y); if ( dis <= 1) { pthread_mutex_lock(&circle_lock); num_circle_count ++; pthread_mutex_unlock(&circle_lock); } } gettimeofday(&end, 0); fprintf(stderr, "The running time of the computation thread %d is %f\\n", (int)a, 1.0 * ((end.tv_sec - start.tv_sec)*1000000 + (end.tv_usec - start.tv_usec) ) / 1000000); return 0; } int main(int argc, char** argv) { pthread_t pid[4]; int num_points = 0; int order[4]; int i; for(i = 0; i < 4; i ++ ) { order[i] = atoi(argv[i+1]); } for(i = 0; i < 4; i ++ ) { printf("create a thread to throw %d points\\n", npoints[order[i]]); pthread_create(&pid[i], 0, pi, (void*)order[i]); num_points += npoints[i]; } for(i = 0; i < 4; i ++ ) { pthread_join(pid[i], 0); } printf("The pi is %f\\n", 4.0 *num_circle_count / num_points); return 0; }
0
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top = 0; static unsigned int arr[400]; pthread_mutex_t m; _Bool flag = 0; void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { top == 0 ? 1 : 0; } int push(unsigned int *stack, int x) { if (top == 400) { printf("stack overflow\\n"); return -1; } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (get_top() == 0) { printf("stack underflow\\n"); return -2; } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for (i = 0; i < 400; i++) { __CPROVER_assume(((400 - i) >= 0) && (i >= 0)); { __CPROVER_assume(((400 - i) >= 0) && (i >= 0)); { __CPROVER_assume(((400 - i) >= 0) && (i >= 0)); { __CPROVER_assume(((400 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint() % 400; if (push(arr, tmp) == (-1)) error(); flag = 1; pthread_mutex_unlock(&m); } } } } } } void *t2(void *arg) { int i; for (i = 0; i < 400; i++) { __CPROVER_assume(((400 - i) >= 0) && (i >= 0)); { __CPROVER_assume(((400 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); if (flag) { if (!(pop(arr) != (-2))) error(); } pthread_mutex_unlock(&m); } } } } int main(void) { pthread_t id1; pthread_t id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> pthread_mutex_t x; pthread_t t1[10],t2[10]; sem_t db; int rc; void init() { pthread_mutex_init(&x,0); sem_init(&db,1,1); rc=0; } void reader() { printf("\\nReader trying to enter "); pthread_mutex_lock(&x); rc++; if(rc==1) sem_wait(&db); printf("\\n%d reader inside",rc); pthread_mutex_unlock(&x); sleep(3); pthread_mutex_lock(&x); if(rc==0) sem_post(&db); printf("\\n%d Reader leaving",rc--); pthread_mutex_unlock(&x); } void writer() { printf("\\nWriter trying to enter "); sem_wait(&db); printf("\\nWriter inside"); sleep(3); sem_post(&db); printf("\\nWriter leaving"); } void main() { int nr,nw,i,j; printf("\\nREADER WRITER (READER'S PRIORITY)"); printf("\\n---------------------------------"); init(); printf("\\nEnter the number of readers :\\t"); scanf("%d",&nr); printf("Enter the number of writers :\\t"); scanf("%d",&nw); for(i=0;i<nr;i++) pthread_create(&t1[i],0,reader,0); for(j=0;j<nw;j++) pthread_create(&t2[j],0,writer,0); for(i=0;i<nr;i++) pthread_join(t1[i],0); for(j=0;j<nw;j++) pthread_join(t2[j],0); printf("\\n\\n"); }
0
#include <pthread.h> { int data; struct my_list* next; }product_list; product_list *head = 0; static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t need_product = PTHREAD_COND_INITIALIZER; void InitList(product_list *list) { if(0 != head) { list->next = 0; list->data = 0; } } void* consumer(void *_val) { product_list *p = 0; while(1) { pthread_mutex_lock(&lock); while(head == 0) { pthread_cond_wait(&need_product,&lock); } p = head; head = head->next; p->next = 0; pthread_mutex_unlock(&lock); printf("consum success,val is :%d\\n",p->data); p = 0; } return 0; } void* product(void *_val) { while(1) { sleep(1); product_list *p = malloc(sizeof(product_list)); pthread_mutex_lock(&lock); InitList(p); p->data = rand()%1000; p->next = head; head = p; pthread_mutex_unlock(&lock); printf("call consumer!product succsee,val is:%d\\n",p->data); pthread_cond_signal(&need_product); } } int main() { pthread_t t_product; pthread_t t_consumer; pthread_create(&t_product,0,product,0); pthread_create(&t_consumer,0,consumer,0); pthread_join(t_product,0); pthread_join(t_consumer,0); return 0; }
1
#include <pthread.h> enum pt_state { SETUP, IDLE, JOB, DIE }; int task; int size; enum pt_state state; pthread_cond_t work_cond; pthread_mutex_t work_mtx; } pt_info; pthread_t threads[3][2]; pt_info shared_info[3][2]; void *task_type1(void *arg) { pt_info *info = (pt_info *) arg; int task = info->task; int size = 0; pthread_mutex_lock(&(info->work_mtx)); printf("<worker %i:%i> start\\n", task, 0); info->state = IDLE; while (1) { pthread_cond_wait(&(info->work_cond), &(info->work_mtx)); if (DIE == info->state) { break; } if (IDLE == info->state) { continue; } size = info->size; printf("<worker %i:%i> JOB start\\n", task, 0); usleep(size*1000000); printf("<worker %i:%i> JOB end\\n", task, 0); info->state = IDLE; } pthread_mutex_unlock(&(info->work_mtx)); pthread_exit(0); } void *task_type2(void *arg) { pt_info *info = (pt_info *) arg; int task = info->task; int size = 0; pthread_mutex_lock(&(info->work_mtx)); printf("<worker %i:%i> start\\n", task, 1); info->state = IDLE; while (1) { pthread_cond_wait(&(info->work_cond), &(info->work_mtx)); if (DIE == info->state) { break; } if (IDLE == info->state) { continue; } size = info->size; printf("<worker %i:%i> JOB start\\n", task, 1); usleep(size*1000000); printf("<worker %i:%i> JOB end\\n", task, 1); info->state = IDLE; } pthread_mutex_unlock(&(info->work_mtx)); pthread_exit(0); } void task_start(int task, int type, int size) { pt_info *info = &(shared_info[task][type]); pthread_mutex_lock(&(info->work_mtx)); info->size = size; info->state = JOB; pthread_cond_signal(&(info->work_cond)); pthread_mutex_unlock(&(info->work_mtx)); } void task_wait(int task, int type) { pt_info *info = &(shared_info[task][type]); while (1) { pthread_mutex_lock(&(info->work_mtx)); if (IDLE == info->state) { break; } pthread_mutex_unlock(&(info->work_mtx)); } pthread_mutex_unlock(&(info->work_mtx)); } void app_init() { int i; pt_info *info = 0; for (i = 0; i < 3; i++) { info = &(shared_info[i][0]); info->task = i; info->size = 0; info->state = SETUP; pthread_cond_init(&(info->work_cond), 0); pthread_mutex_init(&(info->work_mtx), 0); pthread_create(&threads[i][0], 0, task_type1, (void *)info); task_wait(i, 0); } for (i = 0; i < 3; i++) { info = &(shared_info[i][1]); info->task = i; info->size = 0; info->state = SETUP; pthread_cond_init(&(info->work_cond), 0); pthread_mutex_init(&(info->work_mtx), 0); pthread_create(&threads[i][1], 0, task_type2, (void *)info); task_wait(i, 1); } } void app_exit() { int i; int d; pt_info *info = 0; for (i = 0; i < 3; i++) { for (d = 0; d < 2; d++) { info = &(shared_info[i][d]); pthread_mutex_lock(&(info->work_mtx)); printf("app_exit: send DIE to <worker %i:%i>\\n", i, d); info->state = DIE; pthread_cond_signal(&(info->work_cond)); pthread_mutex_unlock(&(info->work_mtx)); pthread_join(threads[i][d], 0); pthread_mutex_destroy(&(info->work_mtx)); pthread_cond_destroy(&(info->work_cond)); } } } int main(int argc, char *argv[]) { app_init(); printf("Init done\\n"); task_start(0, 0, 1); task_start(1, 0, 1); task_start(0, 1, 5); task_start(0, 0, 2); task_wait(0, 1); task_wait(0, 0); app_exit(); return 0; }
0
#include <pthread.h> int fillCount = 0, emptyCount = 5; pthread_mutex_t buffer_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t buffer_not_full = PTHREAD_COND_INITIALIZER; pthread_cond_t buffer_not_empty = PTHREAD_COND_INITIALIZER; sem_t buffer_sem; void produce(void* i); void consume(void* i); void produce_good(void* i); void consume_good(void* i); void produce_sem(void* i); void consume_sem(void* i); int main(int argc, char **argv[]) { pthread_t P,C; int pid, cid; pid = 1; cid = 1; pthread_create(&P, 0, (void*)&produce_good, (void*)(&pid)); pthread_create(&C, 0, (void*)&consume_good, (void*)(&cid)); sem_init(&buffer_sem, 0, 1); pthread_join(P, 0); pthread_join(C, 0); return 0; } void produce(void* i) { int p = *((int*)(i)); printf("Producer %d created\\n", p); while(1) { pthread_mutex_lock(&buffer_mutex); if(emptyCount != 0) { printf("Producer %d is producing\\n", p); sleep(rand()%5); fillCount++; emptyCount--; } pthread_mutex_unlock(&buffer_mutex); } } void produce_sem(void* i) { int p = *((int*)(i)); printf("Producer %d created\\n", p); while(1) { sem_wait(&buffer_sem); if(emptyCount != 0) { printf("Producer %d is producing\\n", p); sleep(rand()%5); fillCount++; emptyCount--; } sem_post(&buffer_sem); } } void consume_sem(void* i) { int c = *((int*)i); printf("Consumer %d created\\n", c); while(1) { sem_wait(&buffer_sem); if(fillCount != 0) { printf("Consumer %d is consuming\\n", c); sleep(rand()%4); fillCount--; emptyCount++; } sem_post(&buffer_sem); } } void consume(void* i) { int c = *((int*)i); printf("Consumer %d created\\n", c); while(1) { pthread_mutex_lock(&buffer_mutex); if(fillCount != 0) { printf("Consumer %d is consuming\\n", c); sleep(rand()%4); fillCount--; emptyCount++; } pthread_mutex_unlock(&buffer_mutex); } } void produce_good(void* i) { int p = *((int*)(i)); printf("Producer %d created\\n", p); while(1) { printf("Producer %d is producing\\n", p); sleep(rand()%2); pthread_mutex_lock(&buffer_mutex); if(emptyCount == 0) { pthread_cond_wait(&buffer_not_full ,&buffer_mutex); } fillCount++; emptyCount--; pthread_mutex_unlock(&buffer_mutex); pthread_cond_signal(&buffer_not_empty); } } void consume_good(void* i) { int c = *((int*)i); printf("Consumer %d created\\n", c); while(1) { printf("Consumer %d is consuming\\n", c); sleep(rand()%1); pthread_mutex_lock(&buffer_mutex); if(fillCount == 0) { pthread_cond_wait(&buffer_not_empty ,&buffer_mutex); } fillCount--; emptyCount++; pthread_mutex_unlock(&buffer_mutex); pthread_cond_signal(&buffer_not_full); } }
1
#include <pthread.h> pthread_t broadcast_thread; pthread_mutex_t broadcast_cond_mtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t broadcast_cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t latest_entry_mtx = PTHREAD_MUTEX_INITIALIZER; int started = 0; struct log_entry latest_entry = {0}; long last_broadcast_time_ms = 0; int last_pop = 0; pthread_t broadcast_thread; void *logserver_broadcast_thread(void *args); int actuator_logserver_init(void) { if(logserver_start()) { fprintf(stderr, "Error: logserver initialization failed\\n"); return -1; } if(pthread_create(&broadcast_thread, 0, logserver_broadcast_thread, 0) != 0) { fprintf(stderr, "Error creating logserver broadcast thread\\n"); logserver_cleanup(); return -1; } return 0; } void actuator_logserver_cleanup(void) { pthread_cancel(broadcast_thread); logserver_cleanup(); } void *logserver_broadcast_thread(void *args) { struct log_entry entry; while(1) { if(pthread_cond_wait(&broadcast_cond, &broadcast_cond_mtx) == 0) { if(pthread_mutex_lock(&latest_entry_mtx) == 0) { entry = latest_entry; latest_entry.pop = 0; pthread_mutex_unlock(&latest_entry_mtx); } broadcast_log(&entry); } } return 0; } void actuator_logserver_new_meas_hook(struct measurement *meas) { int broadcast = 0; struct timespec time; if(pthread_mutex_lock(&latest_entry_mtx) == 0) { latest_entry.knop_val = meas->knop_pct; latest_entry.temp = meas->temp; if(latest_entry.pop == 0) { latest_entry.pop = meas->pop; } if(started && clock_gettime(CLOCK_MONOTONIC, &time) == 0) { long time_ms = time.tv_sec*1000 + time.tv_nsec/1000000; if(time_ms > last_broadcast_time_ms+500) { broadcast = 1; last_broadcast_time_ms = time_ms; } } pthread_mutex_unlock(&latest_entry_mtx); } if(broadcast) { if(pthread_cond_signal(&broadcast_cond)) { fprintf(stderr, "Could not signal new measurement cond\\n"); } } } void actuator_logserver_new_time_hook(struct timespec abs_time, struct timespec rel_time) { if(pthread_mutex_lock(&latest_entry_mtx) == 0) { latest_entry.time_ms = abs_time.tv_sec*1000 + abs_time.tv_nsec/1000000; pthread_mutex_unlock(&latest_entry_mtx); } } void actuator_logserver_new_state_hook(enum system_state old_state, enum system_state new_state) { if(old_state == IDLE && new_state == ACTIVE) { if(pthread_mutex_lock(&latest_entry_mtx) == 0) { started = 1; pthread_mutex_unlock(&latest_entry_mtx); } } else if(old_state == ACTIVE && new_state == IDLE) { if(pthread_mutex_lock(&latest_entry_mtx) == 0) { started = 0; pthread_mutex_unlock(&latest_entry_mtx); } } } const struct actuator_operations actuator_logserver_ops = { .init = actuator_logserver_init, .cleanup = actuator_logserver_cleanup, .new_measurement_hook = actuator_logserver_new_meas_hook, .new_time_hook = actuator_logserver_new_time_hook, .new_state_hook = actuator_logserver_new_state_hook, }; const struct actuator_descriptor actuator_logserver_desc = { .identifier = "logserver", .aops = &actuator_logserver_ops, };
0
#include <pthread.h> pthread_mutex_t corda = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t decisao = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t turno = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int contA = 50; int contB = 50; int escolhaA; int escolhaB; void macaco_passandoA(int i); void macaco_passandoB(int i); void imprime_macaco(); void * macacoA(void * arg); void * macacoB(void * arg); int main(){ pthread_t mA[50], mB[50]; int i; int *id; for(i = 0; i < 50; i++){ id = (int*)malloc(sizeof(int)); *id = i; pthread_create(&mA[i], 0, macacoA, (void*) (id)); } for(i = 0; i < 50; i++){ id = (int*)malloc(sizeof(int)); *id = i; pthread_create(&mB[i], 0, macacoB, (void*) (id)); } pthread_join(mA[0], 0); return 0; } void * macacoA(void * arg){ int i = *((int *) arg); while(1){ escolhaA = rand()%100; if(escolhaA < 50){ escolhaA = 1; }else{ escolhaA = 0; } pthread_mutex_lock(&turno); if(escolhaA && contA > 0){ contA = contA - 1; contB = contB + 1; pthread_mutex_lock(&corda); } macaco_passandoA(i); pthread_mutex_unlock(&turno); pthread_mutex_unlock(&corda); } } void * macacoB(void * arg){ int i = *((int *) arg); while(1){ escolhaB = rand()%1; if(escolhaB < 50){ escolhaB = 1; }else{ escolhaB = 0; } pthread_mutex_lock(&turno); if(escolhaB && contB > 0){ contB = contB - 1; contA = contA + 1; pthread_mutex_lock(&corda); } macaco_passandoB(i); pthread_mutex_unlock(&turno); pthread_mutex_unlock(&corda); } } void macaco_passandoA(int i) { printf(" ~o --------> o/\\n"); printf("*A* *B*\\n"); printf("MacacoA %d esta passando para o outro morro\\n", i); imprime_macaco(); sleep(2); } void macaco_passandoB(int i) { printf(" o/ <-------- o~\\n"); printf("*A* *B*\\n"); printf("MacacoB %d esta passando para o outro morro\\n", i); imprime_macaco(); sleep(2); } void imprime_macaco(){ printf("Numero de macacos\\n Morro A: %d\\n Morro B: %d\\n", contA, contB); }
1
#include <pthread.h> pthread_mutex_t m; pthread_cond_t cond; char str[100]; bool str_available; void* producer(void* arg ) { while (1) { char buf[sizeof str]; fgets(buf, sizeof buf, stdin); pthread_mutex_lock(&m); strncpy(str, buf, sizeof str); str_available = 1; pthread_cond_signal(&cond); pthread_mutex_unlock(&m); } } void* consumer(void* arg ) { while (1) { pthread_mutex_lock(&m); while (!str_available) { pthread_cond_wait(&cond, &m); } char str_snapshot[100]; strncpy(str_snapshot, str, sizeof str_snapshot); str_available = 0; pthread_mutex_unlock(&m); printf("Got string: %s", str_snapshot); for (int i = 0; i < 4; i++) { usleep(500000); } printf("Repeating: %s", str_snapshot); } } int main(void) { pthread_mutex_init(&m, 0); pthread_cond_init(&cond, 0); pthread_t id1, id2; assert(pthread_create(&id1, 0, producer, 0) == 0); assert(pthread_create(&id2, 0, consumer, 0) == 0); assert(pthread_join(id1, 0) == 0); assert(pthread_join(id2, 0) == 0); pthread_cond_destroy(&cond); pthread_mutex_destroy(&m); return 0; }
0
#include <pthread.h> int minimum_value, partial_list_size; pthread_mutex_t minimum_value_lock; { int readers; int writer; pthread_cond_t readers_proceed; pthread_cond_t writer_proceed; int pending_writers; pthread_mutex_t read_write_lock; } mylib_rwlock_t; void mylib_rwlock_init (mylib_rwlock_t *l) { l -> readers = l -> writer = l -> pending_writers = 0; pthread_mutex_init(&(l -> read_write_lock), 0); pthread_cond_init(&(l -> readers_proceed), 0); pthread_cond_init(&(l -> writer_proceed), 0); } void mylib_rwlock_rlock(mylib_rwlock_t *l) { pthread_mutex_lock(&(l -> read_write_lock)); while ((l -> pending_writers > 0) || (l -> writer > 0)) pthread_cond_wait(&(l -> readers_proceed), &(l -> read_write_lock)); l -> readers ++; pthread_mutex_unlock(&(l -> read_write_lock)); } void mylib_rwlock_wlock(mylib_rwlock_t *l) { pthread_mutex_lock(&(l -> read_write_lock)); while ((l -> writer > 0) || (l -> readers > 0)) { l -> pending_writers ++; pthread_cond_wait(&(l -> writer_proceed),&(l -> read_write_lock)); } l -> pending_writers --; l -> writer ++; pthread_mutex_unlock(&(l -> read_write_lock)); } void mylib_rwlock_unlock(mylib_rwlock_t *l) { pthread_mutex_lock(&(l -> read_write_lock)); if (l -> writer > 0) l -> writer = 0; else if (l -> readers > 0) l -> readers --; pthread_mutex_unlock(&(l -> read_write_lock)); if ((l -> readers == 0) && (l -> pending_writers > 0)) pthread_cond_signal(&(l -> writer_proceed)); else if (l -> readers > 0) pthread_cond_broadcast(&(l -> readers_proceed)); } void *find_min_rw(void *list_ptr) { int *partial_list_pointer, my_min, i; mylib_rwlock_t read_write_lock; my_min = 0; partial_list_pointer = (int *) list_ptr; for (i = 0; i < partial_list_size; i++) if (partial_list_pointer[i] < my_min) my_min = partial_list_pointer[i]; mylib_rwlock_rlock(&read_write_lock); if (my_min < minimum_value) { mylib_rwlock_unlock(&read_write_lock); mylib_rwlock_wlock(&read_write_lock); minimum_value = my_min; } mylib_rwlock_unlock(&read_write_lock); pthread_exit(0); } int main() { static long list[100000000],i,n; minimum_value = 0; printf("enter the number of threads for which you want to run this program \\n"); scanf("%d",&n); pthread_t thread1[n]; pthread_mutex_init(&minimum_value_lock, 0); for(i=0;i<100;i++) { list[i]=random(100000000); } partial_list_size =100000000/n; for(i=0;i<n;i++) pthread_create( &thread1[i], 0, find_min_rw, &list); for(i=0;i<n;i++) pthread_join( thread1[i], 0); printf("The minimum value out of 100 million integers is%d\\n ",minimum_value); printf("NOTE: This program takes a list of size 100million integers as asked in the programming assighnment\\n"); printf("The number of threads running on this program is %d\\n:",n); return 0; }
1
#include <pthread.h> static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static unsigned count; void* thread_func(void* arg) { unsigned i; for (i = 0; i < 1000; ++i) { void* ptr; ptr = malloc(22816); memset(ptr, 0, 22816); free(ptr); } pthread_mutex_lock(&mutex); ++count; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); return 0; } int main(int argc, char **argv) { pthread_t thread[10]; int result; int i; for (i = 0; i < 10; i++) { pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN + 4096); result = pthread_create(&thread[i], &attr, thread_func, 0); pthread_attr_destroy(&attr); assert(result == 0); } pthread_mutex_lock(&mutex); while (count < 10 && pthread_cond_wait(&cond, &mutex) == 0) ; pthread_mutex_unlock(&mutex); for (i = 0; i < 10; i++) pthread_join(thread[i], 0); fflush(stdout); fprintf(stderr, "Done.\\n"); return 0; }
0
#include <pthread.h> pthread_mutex_t action_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t action_cond = PTHREAD_COND_INITIALIZER; int cancel_operation = 0; void restore_coocked_mode(void* dummy) { system("stty -raw echo"); } void* read_user_input(void* data) { int c; pthread_cleanup_push(restore_coocked_mode, 0); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); system("stty raw -echo"); while ((c = getchar()) != EOF) { if (c == 'e') { cancel_operation = 1; pthread_cond_signal(&action_cond); pthread_exit(0); } } pthread_cleanup_pop(1); } void* file_line_count(void* data) { char* data_file = (char*)data; FILE* f = fopen(data_file, "r"); int wc = 0; int c; if (!f) { perror("fopen"); exit(1); } pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); while ((c = getc(f)) != EOF) { if (c == '\\n') wc++; } fclose(f); pthread_cond_signal(&action_cond); return (void*)wc; } int main(int argc, char* argv[]) { pthread_t thread_line_count; pthread_t thread_user_input; void* line_count; printf("Checking file size (press 'e' to cancel operation)..."); fflush(stdout); pthread_create(&thread_line_count, 0, file_line_count, (void*)"very_large_data_file"); pthread_create(&thread_user_input, 0, read_user_input, (void*)"very_large_data_file"); pthread_mutex_lock(&action_mutex); pthread_cond_wait(&action_cond, &action_mutex); pthread_mutex_unlock(&action_mutex); if (cancel_operation) { pthread_join(thread_user_input, 0); printf("operation canceled\\n"); fflush(stdout); pthread_cancel(thread_line_count); } else { pthread_join(thread_line_count, &line_count); pthread_cancel(thread_user_input); pthread_join(thread_user_input, 0); printf("'%d' lines.\\n", (int)line_count); } return 0; }
1
#include <pthread.h> int recordSize = 1024; int threadsNr; char *fileName; int fd; int numOfRecords; int creatingFinished = 0; char *word; int rc; int someonefound = 0; int detachedNr = 0; pthread_key_t key; pthread_t *threads; int *wasJoin; pthread_mutex_t mutexForRecords = PTHREAD_MUTEX_INITIALIZER; long gettid() { return syscall(SYS_gettid); } void signalHandler(int signal){ if(signal == SIGUSR1) { printf("Received SIGUSR1\\n"); } else if(signal == SIGTERM) { printf("Received SIGTERM\\n"); } printf("PID: %d TID: %ld\\n", getpid(), pthread_self()); return; } void* threadFun(void *oneArg) { pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); pthread_t threadHandle = pthread_self(); pthread_t threadID = gettid(); printf("new thread with handle: %ld with tid: %ld\\n", threadHandle,threadID); char **readRecords; readRecords = calloc(numOfRecords, sizeof(char*)); for(int i = 0;i<numOfRecords;i++) readRecords[i] = calloc(1024, sizeof(char)); if(pthread_equal(threadHandle,threads[0])!=0) { sigset_t set; sigfillset(&set); pthread_sigmask(SIG_SETMASK, &set, 0); sleep(2); } pthread_setspecific(key, readRecords); readRecords = pthread_getspecific(key); while(!creatingFinished); int finish = 0; int moreBytesToRead = 1; int numOfReadedBytes; while(!finish && moreBytesToRead) { pthread_mutex_lock(&mutexForRecords); for(int i=0;i<numOfRecords;i++) { numOfReadedBytes = read(fd, readRecords[i], 1024); if(numOfReadedBytes==-1) { perror("error while reading in threadFun"); exit(1); } if(numOfReadedBytes<1024) moreBytesToRead = 0; } pthread_mutex_unlock(&mutexForRecords); for(int i = 0; i<numOfRecords; i++) { if(strstr(readRecords[i], word) != 0) { char recID[10]; strncpy(recID, readRecords[i], 10); printf("%ld: found word in record number %d\\n", threadID, atoi(recID)); } } } if(pthread_detach(threadHandle) != 0) { perror("pthread_detach error"); exit(1); } detachedNr++; pthread_exit(0); } int openFile(char *fileName) { int fd = open(fileName, O_RDONLY); if(fd == -1) { perror("file open error"); exit(-1); } else return fd; } void createThread(pthread_t *thread) { rc = pthread_create(thread, 0, threadFun, 0); if(rc != 0) { perror("thread create error"); exit(-1); } } int main(int argc, char *argv[]) { if(argc!=6) { puts("Bad number of arguments"); puts("Appropriate arguments:"); printf("[program] [threads nr] [file] \\n"); printf("[records nr] [word to find] [test nr]"); return 1; } printf("MAIN -> PID: %d TID: %ld\\n", getpid(), pthread_self()); threadsNr = atoi(argv[1]); fileName = calloc(1,sizeof(argv[2])); fileName = argv[2]; numOfRecords = atoi(argv[3]); word = calloc(1,sizeof(argv[4])); word = argv[4]; int test = atoi(argv[5]); if(test != 1 && test != 2 && test != 3 && test != 4) { puts("wrong test number"); exit(1); } fd = openFile(fileName); char **readRecords = calloc(numOfRecords, sizeof(char*)); for(int i = 0;i<numOfRecords;i++) readRecords[i] = calloc(1024, sizeof(char)); pthread_key_create(&key, 0); threads = calloc(threadsNr, sizeof(pthread_t)); wasJoin = calloc(threadsNr, sizeof(int)); for(int i=0; i<threadsNr; i++) { createThread(&threads[i]); } creatingFinished = 1; usleep(100); if(test == 1) { puts("sending SIGUSR1 signal"); pthread_kill(threads[0],SIGUSR1); } if(test == 2) { puts("sending SIGTERM signal"); pthread_kill(threads[0],SIGTERM); } if(test == 3) { puts("sending SIGKILL signal"); pthread_kill(threads[0],SIGKILL); } if(test == 4) { puts("sending SIGSTOP signal"); pthread_kill(threads[0],SIGSTOP); } while(detachedNr != threadsNr) { usleep(100); } printf("End of program\\n\\n"); if(close(fd)<0) { perror("close error"); return 1; } free(threads); return 0; }
0
#include <pthread.h> int main(int argc, char *argv[]) { int fd = 0; int ret = 0; battleship_shmem_t* dataPtr; pthread_mutexattr_t myattr; fd = shm_open("/myshmemobject", O_RDWR | O_CREAT, S_IRWXU); if (fd == -1) { printf("error creating the shared memory object.\\n"); exit(1); } ftruncate(fd, sizeof(battleship_shmem_t)); dataPtr = mmap(0, sizeof(battleship_shmem_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); pthread_mutexattr_init(&myattr); pthread_mutexattr_setpshared(&myattr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&dataPtr->myshmemmutex, &myattr); pthread_cond_init(&dataPtr->condvar, 0); dataPtr->infoToCheck = 1; dataPtr->shared_ship_info.x = 0; dataPtr->shared_ship_info.y = 0; while (1) { pthread_mutex_lock(&dataPtr->myshmemmutex); while (dataPtr->infoToCheck == 1) { printf("Game Engine : waiting for info from sever\\n"); ret = pthread_cond_wait(&dataPtr->condvar, &dataPtr->myshmemmutex); } printf("Game Engine : executing command\\n"); switch (dataPtr->command) { case eClientMoveUp: dataPtr->shared_ship_info.y++; break; case eClientMoveDown: dataPtr->shared_ship_info.y--; break; case eClientMoveLeft: dataPtr->shared_ship_info.x--; break; case eClientMoveRight: dataPtr->shared_ship_info.x++; break; case eClientMoveAuto: dataPtr->shared_ship_info.x++; dataPtr->shared_ship_info.y++; break; default: break; } dataPtr->infoToCheck = 1; pthread_cond_signal(&dataPtr->condvar); pthread_mutex_unlock(&dataPtr->myshmemmutex); } pthread_mutexattr_destroy(&myattr); pthread_mutex_destroy(&dataPtr->myshmemmutex); close(fd); munmap(dataPtr, sizeof(battleship_shmem_t)); shm_unlink("/myshmemobject"); return 0; }
1
#include <pthread.h> static pthread_mutex_t atomic_lock = PTHREAD_MUTEX_INITIALIZER; int atomic_int_get(volatile int *ptr) { int res; pthread_mutex_lock(&atomic_lock); res = *ptr; pthread_mutex_unlock(&atomic_lock); return res; } void atomic_int_set(volatile int *ptr, int val) { pthread_mutex_lock(&atomic_lock); *ptr = val; pthread_mutex_unlock(&atomic_lock); } int atomic_int_add_and_fetch(volatile int *ptr, int inc) { int res; pthread_mutex_lock(&atomic_lock); *ptr += inc; res = *ptr; pthread_mutex_unlock(&atomic_lock); return res; } void *atomic_ptr_cas(void * volatile *ptr, void *oldval, void *newval) { void *ret; pthread_mutex_lock(&atomic_lock); ret = *ptr; if (ret == oldval) *ptr = newval; pthread_mutex_unlock(&atomic_lock); return ret; } int atomic_int_inc(volatile int *ptr) { return atomic_int_add_and_fetch(ptr, 1); } int atomic_int_dec(volatile int *ptr) { return atomic_int_add_and_fetch(ptr, -1); }
0
#include <pthread.h> void* writer(void*); void* reader(void*); unsigned *addr; pthread_mutex_t mutex_write; pthread_mutex_t mutex_read; pthread_cond_t cv; main(int argc, char * argv[]) { int fd; pthread_t reader_tid, writer_tid; fd = shm_open("/mymem", O_RDWR | O_CREAT, 0777); if (fd == -1) { perror("Open failed"); exit(0); } if (ftruncate(fd, sizeof(*addr)) == -1) { perror("ftruncate error"); exit(0); } addr = (unsigned *)(mmap(0, sizeof(*addr), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)); if (addr == MAP_FAILED) { perror("mmap failed"); exit(0); } printf("Map addr is %6.6X\\n", addr); close(fd); *addr = 0; pthread_mutex_init(&mutex_write, 0); pthread_mutex_init(&mutex_read, 0); pthread_mutex_lock(&mutex_read); pthread_cond_init(&cv, 0); pthread_create(&writer_tid, 0, writer, 0); pthread_create(&reader_tid, 0, reader, 0); pthread_join(writer_tid, 0); pthread_join(reader_tid, 0); } void* writer(void* argv) { int i; for (i = 0; i < 10 + 1;) { printf("%d ->\\n", i); pthread_mutex_lock(&mutex_write); *addr = i; pthread_mutex_unlock(&mutex_read); i++; } pthread_exit(0); } void* reader(void* argv) { for (;;) { pthread_mutex_lock(&mutex_read); printf("%d <-\\n", *addr); if (*addr == 10) { pthread_exit(0); } pthread_mutex_unlock(&mutex_write); } }
1
#include <pthread.h> int data[(3)]; int start; int end; int count; } pool_t; int items_to_produce = 20; pthread_mutex_t mtx; pthread_mutex_t mtx_item_prod; pthread_cond_t cond_nonempty; pthread_cond_t cond_nonfull; pool_t pool; void init_pool(pool_t * pool); void push(pool_t * pool, int value); int pop(pool_t * pool); int size(pool_t * pool); int produce_one(void); int has_more_to_produce(void); void * producer(void * ptr); void * consumer(void * ptr); int main(int argc, char ** argv) { pthread_t cons0, cons1, cons2; pthread_t prod0, prod1; srand((unsigned int)time(0)); init_pool(&pool); pthread_mutex_init(&mtx, 0); pthread_cond_init(&cond_nonempty, 0); pthread_cond_init(&cond_nonfull, 0); pthread_create(&cons0, 0, consumer, (void *)0); pthread_create(&cons1, 0, consumer, (void *)1); pthread_create(&cons2, 0, consumer, (void *)2); pthread_mutex_init(&mtx_item_prod, 0); pthread_create(&prod0, 0, producer, (void *)0); pthread_create(&prod1, 0, producer, (void *)1); pthread_join(prod0, 0); pthread_join(prod1, 0); pthread_cond_destroy(&cond_nonempty); pthread_cond_destroy(&cond_nonfull); pthread_mutex_destroy(&mtx); return 0; } void init_pool(pool_t * pool) { pool->start = 0; pool->end = -1; pool->count = 0; } void push(pool_t * pool, int value) { pthread_mutex_lock(&mtx); while (pool->count >= (3)) pthread_cond_wait(&cond_nonfull, &mtx); pool->end = (pool->end + 1) % (3); pool->data[pool->end] = value; items_to_produce--; pool->count++; pthread_mutex_unlock(&mtx); } int pop(pool_t * pool) { int value; pthread_mutex_lock(&mtx); while (pool->count <= 0) pthread_cond_wait(&cond_nonempty, &mtx); value = pool->data[pool->start]; pool->start = (pool->start + 1) % (3); pool->count--; pthread_mutex_unlock(&mtx); return value; } int size(pool_t * pool) { int result = 0; pthread_mutex_lock(&mtx); result = pool->count; pthread_mutex_unlock(&mtx); return result; } int produce_one(void) { int result = 0; pthread_mutex_lock(&mtx_item_prod); result = items_to_produce--; pthread_mutex_unlock(&mtx_item_prod); return result; } int has_more_to_produce(void) { int result = 0; pthread_mutex_lock(&mtx_item_prod); result = (items_to_produce > 0); pthread_mutex_unlock(&mtx_item_prod); return result; } void * producer(void * ptr) { int value; while (has_more_to_produce()) { value = produce_one(); printf("producer %d: %d\\n", (int)ptr, value); push(&pool, value); pthread_cond_broadcast(&cond_nonempty); usleep(500 + (rand() % 500)); } pthread_exit(0); } void * consumer(void * ptr) { while (items_to_produce > 0 || size(&pool) > 0) { printf("consumer %d: %d\\n", (int)ptr, pop(&pool)); pthread_cond_broadcast(&cond_nonfull); } pthread_exit(0); }
0
#include <pthread.h> int flag=0; int n; int i=13; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condizione = PTHREAD_COND_INITIALIZER; void *scrittore (void *p){ int fd = open ("file.txt",O_WRONLY); char *buff =malloc(sizeof(int)); while(i<n){ pthread_mutex_lock(&mutex); sprintf(buff, "%d",i); write(fd,buff,sizeof(int)); i++; pthread_mutex_unlock(&mutex); } pthread_exit(0); } void *lettore (void *p){ int fd = open ("file.txt",O_RDONLY); char *buff =malloc(sizeof(int)); int bRead=0; do{ pthread_mutex_lock(&mutex); bRead=read(fd,buff,sizeof(int)); printf("%s\\n",buff ); pthread_mutex_unlock(&mutex); sleep(1); }while(bRead>0); if (i>=1) { pthread_mutex_lock(&mutex); pthread_cond_signal(&condizione); pthread_mutex_unlock(&mutex); } pthread_exit(0); } void *fine(void *p){ pthread_mutex_lock(&mutex); while(i<n){ pthread_cond_wait(&condizione,&mutex); } pthread_mutex_unlock(&mutex); printf("Finito\\n"); pthread_exit(0); } int main(int argc, char const *argv[]) { n=atoi(argv[1]); if (n>37 || n<13) { perror("Valore non corretto"); exit(1); } unlink("file.txt"); int fd = open("file.txt",O_CREAT,S_IRWXU|S_IRWXG|S_IRWXO); close(fd); pthread_t thread[3]; pthread_create(&thread[0],0,scrittore,0); pthread_create(&thread[1],0,lettore,0); pthread_create(&thread[2],0,fine,0); for (int i = 0; i < 3; i++) { pthread_join(thread[i],0); } return 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; struct arg{ int i; }; void cal(int i, void* p); static void* func(void *p); int main(int argc, const char *argv[]) { int err, i; pthread_t tid[4]; for (i = 0; i < 4; i++) { err = pthread_create(tid+i, 0, func, (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 < 4; i++) { pthread_join(tid[i], 0); } pthread_mutex_destroy(&mut_num); pthread_cond_destroy(&cond_num); exit(0); } static void* func(void *p) { int i; 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); cal(i, p); } pthread_exit(0); } void cal(int i, void* p) { int j,mark; mark = 1; for(j = 2; j < i/2; j++) { if(i % j == 0) { mark = 0; break; } } if(mark) printf("[%d][%d]%d is a primer.\\n",(int)p,syscall(SYS_gettid),i); }
0
#include <pthread.h> { char *message; }MESSAGE; MESSAGE myMessage; pthread_t tid[2]; int messageIndex; pthread_mutex_t lock; void* readPerson1(void *arg) { int i = 0; char tempChar; FILE *input = fopen("Person1", "r"); tempChar = getc(input); while (tempChar != EOF) { pthread_mutex_lock(&lock); for(i; i < messageIndex; i++) { tempChar = fgetc(input); if(tempChar == '\\n') tempChar = fgetc(input); if(tempChar == EOF) break; } while((tempChar != EOF) && (tempChar != '0')) { if(tempChar != '\\n') { myMessage.message[messageIndex] = tempChar; tempChar = getc(input); i++; if(tempChar != '0') messageIndex++; } else tempChar = getc(input); } pthread_mutex_unlock(&lock); } fclose(input); return 0; } void* readPerson2(void *arg) { int i = 0; char tempChar; FILE *input = fopen("Person2", "r"); tempChar = getc(input); while (tempChar != EOF) { pthread_mutex_lock(&lock); for(i; i < messageIndex; i++) { tempChar = fgetc(input); if(tempChar == '\\n') tempChar = fgetc(input); if(tempChar == EOF) break; } while((tempChar != EOF) && (tempChar != '0')) { if(tempChar != '\\n') { myMessage.message[messageIndex] = tempChar; tempChar = getc(input); i++; if(tempChar != '0') messageIndex++; } else tempChar = getc(input); } pthread_mutex_unlock(&lock); } fclose(input); return 0; } int main(void) { myMessage.message = (char*)malloc(501*sizeof(char)); messageIndex = 0; pthread_create(&(tid[0]), 0, &readPerson1, 0); pthread_create(&(tid[1]), 0, &readPerson2, 0); pthread_join(tid[0], 0); pthread_join(tid[1], 0); pthread_mutex_destroy(&lock); printf("%s\\n", myMessage.message); return 0; }
1
#include <pthread.h> pthread_mutex_t glock; pthread_cond_t gcond; void *release(void *tmp) { pthread_cond_signal(&gcond); pthread_cond_signal(&gcond); } void *test(void *tmp) { pthread_mutex_lock(&glock); printf("%s main lock getpid:%d\\n", "18:45:34", getpid()); printf("%s main lock syscall(SYS_gettid):%ld\\n", "18:45:34", syscall(SYS_gettid)); printf("%s main lock pthread_self:%lu\\n", "18:45:34", pthread_self()); pthread_mutex_unlock(&glock); } int main() { pthread_t pid_1, pid_2, pid_3; printf("Wez : E\\n"); pthread_mutex_init(&glock, 0); pthread_create(&pid_1, 0, &test, 0); pthread_create(&pid_2, 0, &test, 0); sleep (3); printf("Wez : X\\n"); return 0; }
0
#include <pthread.h> long min(long a, long b) { if(a > b) return b; else return a; } struct input { long num; long cT; }; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; long divisor = 2; long curThread = 0; long timecount = 0; void *createThread(void *input) { struct input *in = input; long actual = in->cT; printf("Hello from thread No. %d!\\n", actual); pthread_t arr[in->num]; long tcount = 0; long maxThreads = in->num; struct input threads[maxThreads]; pthread_t p1, p2; long comp = min((long)floor(maxThreads/divisor), 16); while(tcount < maxThreads) { pthread_mutex_lock(&mutex); curThread++; struct input in; in.num = comp; in.cT = curThread; threads[tcount] = in; pthread_create(&arr[tcount], 0, createThread, &threads[tcount]); pthread_mutex_unlock(&mutex); tcount++; } long i; for (i = 0; i < maxThreads; i++) pthread_join(arr[i], 0); printf("Bye from thread No. %d!\\n", actual); } int main() { struct input maxThreads; maxThreads.num = 25; maxThreads.cT = curThread; createThread(&maxThreads); printf("Insgesamt erzeugte Threads: %d\\n", curThread); }
1
#include <pthread.h> pthread_mutex_t Mutex; int Hours, Minutes, Seconds; void init_clock(void) { Hours = 11; Minutes = 59; Seconds = 30; pthread_mutex_init(&Mutex, 0); } void increment_time(void) { pthread_mutex_lock(&Mutex); Seconds++; if (Seconds > 59) { Seconds = 0; Minutes++; if (Minutes > 59) { Minutes = 0; Hours++; if (Hours > 11) { Hours = 0; } } } pthread_mutex_unlock(&Mutex); } void set_time(int hours, int minutes, int seconds) { pthread_mutex_lock(&Mutex); Hours = hours; Minutes = minutes; Seconds = seconds; pthread_mutex_unlock(&Mutex); } void get_time(int *hours, int *minutes, int *seconds) { pthread_mutex_lock(&Mutex); *hours = Hours; *minutes = Minutes; *seconds = Seconds; pthread_mutex_unlock(&Mutex); } void make_display_message(char display_message[], int hours, int minutes, int seconds) { display_message[0] = hours / 10 + '0'; display_message[1] = hours % 10 + '0'; display_message[2] = ':'; display_message[3] = minutes / 10 + '0'; display_message[4] = minutes % 10 + '0'; display_message[5] = ':'; display_message[6] = seconds / 10 + '0'; display_message[7] = seconds % 10 + '0'; display_message[8] = '\\0'; } void time_from_set_message(char message[], int *hours, int *minutes, int *seconds) { sscanf(message,"set:%d:%d:%d",hours, minutes, seconds); } int time_ok(int hours, int minutes, int seconds) { return hours >= 0 && hours <= 11 && minutes >= 0 && minutes <= 59 && seconds >= 0 && seconds <= 59; } void display_time(int hours, int minutes, int seconds) { char display_message[20]; char draw_message[100]; make_display_message(display_message, hours, minutes, seconds); sprintf(draw_message, "Time: %s", display_message); si_ui_draw_begin(); si_ui_draw_string("send \\"set:hh:mm:ss\\" to set time", 90, 20); si_ui_draw_string(draw_message, 145, 55); si_ui_draw_end(); } void *clock_thread(void *unused) { int hours, minutes, seconds; while (1) { get_time(&hours, &minutes, &seconds); display_time(hours, minutes, seconds); increment_time(); usleep(1000000); } } void * set_thread(void *unused) { char message[SI_UI_MAX_MESSAGE_SIZE]; int hours, minutes, seconds; si_ui_set_size(400, 200); while(1) { si_ui_receive(message); if (strncmp(message, "set", 3) == 0) { time_from_set_message(message, &hours, &minutes, &seconds); if (time_ok(hours, minutes, seconds)) { set_time(hours, minutes, seconds); } else { si_ui_show_error("Illegal value for hours, minutes or seconds"); } } else if (strcmp(message, "exit") == 0) { exit(0); } else { si_ui_show_error("unexpected message type"); } } } int main(void) { si_ui_init(); init_clock(); pthread_t clock_thread_handle; pthread_t set_thread_handle; pthread_create(&clock_thread_handle, 0, clock_thread, 0); pthread_create(&set_thread_handle, 0, set_thread, 0); pthread_join(clock_thread_handle, 0); pthread_join(set_thread_handle, 0); return 0; }
0
#include <pthread.h> int shared = 0; pthread_mutex_t mutex_shared; void * increment(void *arg) { int i; for(i=0; i<1000; i++) { pthread_mutex_lock(&mutex_shared); shared++; pthread_mutex_unlock(&mutex_shared); } pthread_exit(0); } int main (int argc, char *argv[]) { void *status; pthread_mutex_init(&mutex_shared, 0); pthread_t threads[1000]; int i; int rc; for(i=0; i<1000; i++) { rc = pthread_create(&threads[i], 0, increment, (void *)0); if (rc){ printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } for(i=0; i<1000; i++) { pthread_join(threads[i],&status); } printf("Shared=%d\\n",shared); pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t candado; pthread_cond_t producido; pthread_cond_t consumido; char buffer[8]; int contador; int entrada; int salida; int posFrase; int posLlave; int producidos; int consumidos; FILE *file; FILE *cesar; char *llave; int tamBuffer; static char *archivo; void getElement(void); void putElement(void); void init(); int readChar(FILE *file); void writeChar(FILE *Cesar, char dato); int getTamFile(FILE *file); char * append(char *s); char * append(char *s) { int len = strlen(s); char buf[len+6]; strcpy(buf, s); buf[len] = '.'; buf[len+1] = 'c'; buf[len+2] = 'e'; buf[len+3] = 's'; buf[len+4] = 'a'; buf[len+5] = 'r'; buf[len+6] = 0; return strdup(buf); } void writeChar(FILE *Cesar, char dato) { fprintf(Cesar, "%c", dato); } int readChar(FILE *file) { return fgetc(file); } int getTamFile(FILE *file) { fseek(file, 0, 2); int aux = ((ftell(file)) ); fseek(file, 0, 0); return aux; } void init() { printf("Inicializando Variables \\n"); entrada = 0; salida = 0; contador = 0; posLlave = 0; consumidos = getTamFile(file); producidos = getTamFile(file); pthread_mutex_init(&candado, 0); pthread_cond_init(&producido, 0); pthread_cond_init(&consumido, 0); } void getElement(void) { while (consumidos != 0) { pthread_mutex_lock(&candado); while (contador == 0) { pthread_cond_wait(&producido, &candado); } if (consumidos > 0) { char dato = buffer[salida]; salida = (salida + 1) % 8; contador = contador - 1; consumidos = consumidos > 0 ? (consumidos - 1) : 0; writeChar(cesar, dato); } pthread_mutex_unlock(&candado); pthread_cond_signal(&consumido); } } void putElement(void) { while (!feof(file)) { pthread_mutex_lock(&candado); while (contador == 8) { pthread_cond_wait(&consumido, &candado); } if (!feof(file)) { int val = readChar(file); char dato = val + llave[posLlave] == 0 ? val : val + llave[posLlave]; buffer[entrada] = dato; posLlave = (posLlave + 1) % strlen(llave); producidos = producidos - 1; entrada = (entrada + 1) % 8; contador = contador + 1; } pthread_mutex_unlock(&candado); pthread_cond_signal(&producido); } } int main(int argc, char **argv) { archivo = argv[1]; file = fopen(archivo, "rb"); if (!file) { printf("El archivo no existe.."); } else { archivo = append(archivo); cesar = fopen(archivo, "w"); init(); printf("Inicio del programa \\n"); printf("Digite la llave para el cifrado del archivo: "); llave = (char*) malloc(sizeof (char*)); scanf("%[^\\n]", llave); fflush(stdin); fflush(stdout); int numHilos; printf("Digite el numero de hilos: "); scanf("%i", &numHilos); fflush(stdin); fflush(stdout); pthread_t thread[numHilos]; for (int i = 1; i <= numHilos; i++) { if (i % 2 == 0) { pthread_create(&thread[i], 0, (void *) &getElement, 0); } else { pthread_create(&thread[i], 0, (void *) &putElement, 0); } } for (int i = 1; i <= numHilos; i++) { pthread_join(thread[i], 0); } pthread_mutex_destroy(&candado); pthread_cond_destroy(&producido); pthread_cond_destroy(&consumido); free(llave); fclose(file); fclose(cesar); printf("\\n<=Archivo Codificado=>"); } return 0; }
0
#include <pthread.h> int NO_READERS; int NO_WRITERS; int NO_READERS_READING = 0; int NO_WRITERS_WRITING = 0; bool VERBOSE; pthread_mutex_t resourceMutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t tryResourceMutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t readerMutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t writerMutex = PTHREAD_MUTEX_INITIALIZER; void *readerJob(void *arg) { while (1) { pthread_mutex_lock(&tryResourceMutex); pthread_mutex_lock(&readerMutex); NO_READERS_READING++; if (NO_READERS_READING == 1) { pthread_mutex_lock(&resourceMutex); } pthread_mutex_unlock(&readerMutex); pthread_mutex_unlock(&tryResourceMutex); readMemory((int) (uintptr_t) arg, SHARED_ARRAY, SHARED_ARRAY_SIZE, RANGE, VERBOSE); pthread_mutex_lock(&readerMutex); NO_READERS_READING--; if (NO_READERS_READING == 0) { pthread_mutex_unlock(&resourceMutex); } pthread_mutex_unlock(&readerMutex); } return 0; } void *writerJob(void *arg) { while (1) { pthread_mutex_lock(&writerMutex); NO_WRITERS_WRITING++; if (NO_WRITERS_WRITING == 1) { pthread_mutex_lock(&tryResourceMutex); } pthread_mutex_unlock(&writerMutex); pthread_mutex_lock(&resourceMutex); writeMemory(SHARED_ARRAY, SHARED_ARRAY_SIZE, RANGE, VERBOSE); pthread_mutex_unlock(&resourceMutex); pthread_mutex_lock(&writerMutex); NO_WRITERS_WRITING--; if (NO_WRITERS_WRITING == 0) { pthread_mutex_unlock(&tryResourceMutex); } pthread_mutex_unlock(&writerMutex); } return 0; } int main(int argc, char *argv[]) { parseArguments(argc, argv, 2, &NO_READERS, &NO_WRITERS, &VERBOSE); printf("Readers–writers problem: writers-preference (readers may starve) with mutex synchronization.\\n"); printf(" NO_READERS=%i, NO_WRITERS=%i, VERBOSE=%i\\n\\n", NO_READERS, NO_WRITERS, VERBOSE); pthread_t *readersThreadsIds = malloc(NO_READERS * sizeof(pthread_t)); if (readersThreadsIds == 0) { cannotAllocateMemoryError(); } pthread_t *writersThreadsIds = malloc(NO_READERS * sizeof(pthread_t)); if (writersThreadsIds == 0) { cannotAllocateMemoryError(); } srand(time(0)); initSharedArray(); for (int i = 0; i < NO_READERS; ++i) { if (pthread_create(&readersThreadsIds[i], 0, readerJob, (void *) (uintptr_t) i) != 0) { throwError("pthread_create error"); } } for (int i = 0; i < NO_WRITERS; ++i) { if (pthread_create(&writersThreadsIds[i], 0, writerJob, 0) != 0) { throwError("pthread_create error"); } } for (int i = 0; i < NO_READERS; ++i) { if (pthread_join(readersThreadsIds[i], 0) != 0) { throwError("pthread_join error"); } } for (int i = 0; i < NO_WRITERS; ++i) { if (pthread_join(writersThreadsIds[i], 0) != 0) { throwError("pthread_join error"); } } free(readersThreadsIds); free(writersThreadsIds); pthread_mutex_destroy(&resourceMutex); pthread_mutex_destroy(&tryResourceMutex); pthread_mutex_destroy(&readerMutex); pthread_mutex_destroy(&writerMutex); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_t tidP[20],tidC[20]; sem_t full,empty; int counter; int buffer[10]; void initialize() { pthread_mutex_init(&mutex,0); sem_init(&full,1,0); sem_init(&empty,1,10); counter=0; } void write(int item) { buffer[counter++]=item; } int read() { return(buffer[--counter]); } void * producer (void * param) { int waittime,item,i; item=rand()%5; waittime=rand()%5; sem_wait(&empty); pthread_mutex_lock(&mutex); printf("\\nProducer has produced item: %d\\n",item); write(item); pthread_mutex_unlock(&mutex); sem_post(&full); } void * consumer (void * param) { int waittime,item; waittime=rand()%5; sem_wait(&full); pthread_mutex_lock(&mutex); item=read(); printf("\\nConsumer has consumed item: %d\\n",item); pthread_mutex_unlock(&mutex); sem_post(&empty); } int main() { int n1,n2,i; initialize(); printf("\\nEnter the no of producers: "); scanf("%d",&n1); printf("\\nEnter the no of consumers: "); scanf("%d",&n2); for(i=0;i<n1;i++) pthread_create(&tidP[i],0,producer,0); for(i=0;i<n2;i++) pthread_create(&tidC[i],0,consumer,0); for(i=0;i<n1;i++) pthread_join(tidP[i],0); for(i=0;i<n2;i++) pthread_join(tidC[i],0); exit(0); }
0
#include <pthread.h> extern int function_status; extern pthread_mutex_t mut; extern FILE* fp_small; extern FILE* fp_big; extern int gameLdStatus; void initAction() { gameLdStatus = -1; initPeripheral(); } void oledOutput(int num, int status) { clearImage(); switch(status) { case -1: break; case 0: addAttentionFlag(); break; case 2: addMeditationFlag(); break; case 3: addPoorSignalFlag(); break; case 4: addDeltaFlag(); break; case 5: addThetaFlag(); break; case 6: addLowAlphaFlag(); break; case 7: addHighAlphaFlag(); break; case 8: addLowBetaFlag(); break; case 9: addHighBetaFlag(); break; case 10: addLowGammaFlag(); break; case 11: addMiddleGammaFlag(); break; } handleNumber(num); printImage(); } void game1(int attention) { int oldStatus = gameLdStatus; if(attention>50 && gameLdStatus>=-1 && gameLdStatus<6) { gameLdStatus++; } else if(attention<50 && gameLdStatus>-1 && gameLdStatus<=6) { gameLdStatus--; } if(oldStatus == gameLdStatus) { } else if(oldStatus < gameLdStatus) { setLedValue(gameLdStatus, 1); } else if(oldStatus > gameLdStatus) { setLedValue(oldStatus, 0); } } void action(int *signal, int config) { pthread_mutex_lock(&mut); char buffer[1024]; memset(buffer, '\\0', sizeof(buffer)); if(config == 0) { snprintf(buffer, 1024, "%d\\n", signal[1]); fwrite(buffer, 1, strlen(buffer), fp_small); pthread_mutex_unlock(&mut); return; } if(function_status != 1) { initAction(); } switch(function_status) { case 0: oledOutput(signal[10], 0); break; case 1: oledOutput(signal[10], 0); game1(signal[10]); break; case 2: oledOutput(signal[11], 2); break; case 3: oledOutput(signal[0], 3); break; case 4: oledOutput(signal[2], 4); break; case 5: oledOutput(signal[3], 5); break; case 6: oledOutput(signal[4], 6); break; case 7: oledOutput(signal[5], 7); break; case 8: oledOutput(signal[6], 8); break; case 9: oledOutput(signal[7], 9); break; case 10: oledOutput(signal[8], 10); break; case 11: oledOutput(signal[9], 11); break; case 12: setPeripheralData(signal[6], signal[7], signal[8], signal[10], signal[11]); int result = getPeripheralResult(); addEmotionFlag(result); printImage(); break; default: clearImage(); printImage(); break; } snprintf(buffer, 1024, "%d %d %d %d %d %d %d %d %d %d %d\\n", signal[10], signal[11], signal[0], signal[2], signal[3], signal[4], signal[5], signal[6], signal[7], signal[8], signal[9]); fwrite(buffer, 1, strlen(buffer), fp_big); pthread_mutex_unlock(&mut); }
1
#include <pthread.h> static pthread_mutex_t l_memleak_lock = PTHREAD_MUTEX_INITIALIZER; struct mem_leak{ unsigned int size; void *mem; char file[NAME_MAX]; int line; struct mem_leak *next; }; struct mem_leak *mem_head = 0; static unsigned int mem_total = 0; void *mem_leak_alloc(unsigned int size, char *file, int line) { void *ptr; ptr = malloc(size); if(ptr == 0){ LOG(LOG_LEVEL_ERROR, "%s", "malloc error!!"); return ptr; } struct mem_leak *pml = malloc(sizeof(struct mem_leak)); if(pml == 0){ free(ptr); LOG(LOG_LEVEL_ERROR, "%s", "malloc error!!"); return 0; } pml->mem = ptr; pml->size = size; snprintf(pml->file, NAME_MAX, "%s", file); pml->line = line; pthread_mutex_lock(&l_memleak_lock); pml->next = mem_head; mem_head = pml; mem_total += size; pthread_mutex_unlock(&l_memleak_lock); return ptr; } int mem_leak_free(void *mem) { struct mem_leak *ptr, *pre; pthread_mutex_lock(&l_memleak_lock); ptr = mem_head; while(ptr){ if(ptr->mem == mem){ if(ptr == mem_head) mem_head = ptr->next; else pre->next = ptr->next; mem_total -= ptr->size; free(ptr); free(mem); pthread_mutex_unlock(&l_memleak_lock); return 0; } pre = ptr; ptr = ptr->next; } pthread_mutex_unlock(&l_memleak_lock); return 0; } void mem_leak_dump() { struct mem_leak *ptr; unsigned int total_leak_size = 0; LOG(LOG_LEVEL_WARNING, "%s", "memory leak dump"); ptr = mem_head; while(ptr){ LOG(LOG_LEVEL_WARNING, "%s%d%s%x%s%s%s%d", "!!memory leak!! size:", ptr->size, " Addr", ptr->mem, " File:", ptr->file, " Line:", ptr->line); total_leak_size += ptr->size; ptr = ptr->next; } LOG(LOG_LEVEL_WARNING, "%s%d", "memory leak total:", mem_total); return ; }
0
#include <pthread.h> unsigned int nR = 0; unsigned int nW = 0; unsigned int rCnt = 0; unsigned int wCnt = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t okR = PTHREAD_COND_INITIALIZER; pthread_cond_t okW = PTHREAD_COND_INITIALIZER; void readerIn(){ pthread_mutex_lock(&mutex); if (nW > 0 || wCnt>0) { rCnt++; pthread_cond_wait(&okR, &mutex); rCnt--; } nR++; pthread_mutex_unlock(&mutex); } void readerOut(){ pthread_mutex_lock(&mutex); nR--; if (nR == 0) { pthread_cond_signal(&okW); } pthread_mutex_unlock(&mutex); } void writerIn(){ pthread_mutex_lock(&mutex); if (nR > 0 || nW > 0) { wCnt++; pthread_cond_wait(&okW, &mutex); wCnt--; } nW = 1; pthread_mutex_unlock(&mutex); } void writerOut(){ pthread_mutex_lock(&mutex); nW = 0; if (rCnt>0) { pthread_cond_signal(&okR); } else { pthread_cond_signal(&okW); } pthread_mutex_unlock(&mutex); }
1
#include <pthread.h> int M, N, count = 1; static pthread_mutex_t *mutex; pthread_t *thread = 0; int *thread_ID = 0; void *thread_func(void *arg); int main(int argc, char const *argv[]){ if (argc != 3){ printf("Usage: ./ex6 M N, M threads, N counting!\\n"); return 0; } printf("Mutex program starting!\\n"); M = atoi(argv[1]); N = atoi(argv[2]); thread = (pthread_t *) malloc(M*sizeof(pthread_t)); mutex = malloc(M*sizeof(pthread_mutex_t)); thread_ID = (int *) malloc(M*sizeof(int)); int i; for (i = 0; i < M; i++){ pthread_mutex_init(&mutex[i], 0); pthread_mutex_lock(&mutex[i]); } for (i = 0; i < M; i++){ thread_ID[i] = i+1; pthread_create(&thread[i], 0, thread_func, &thread_ID[i]); } for (i = 0; i < M; i++){ pthread_join(thread[i], 0); } printf("Terminating process...\\n"); for(i = 0; i < M; i++) pthread_mutex_destroy(&mutex[i]); pthread_exit(0); if(thread != 0) free(thread); if(thread_ID != 0) free(thread_ID); if(mutex != 0) free(mutex); return 0; } void *thread_func(void *arg){ int ID = *((int *) arg); printf("Hello World! I'm thread %d\\n", ID); do{ if (ID==M) pthread_mutex_unlock(&mutex[0]); pthread_mutex_lock(&mutex[ID-1]); if (count <= N) printf("Thread %d counting %d\\n", ID, count); count++; if(count > N && ID == M) pthread_mutex_unlock(&mutex[0]); if(ID < M) pthread_mutex_unlock(&mutex[ID]); }while(count < N); pthread_exit(0); return 0; }
0
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void *thr_fn(void *arg) { int err, signo; pthread_t tid = pthread_self(); for( ; ; ) { err = sigwait(&mask, &signo); if(err != 0) err_exit(err, "sigwait failed"); switch(signo) { case SIGINT: printf("\\nthread: %ld, sig interrupt\\n", tid); break; case SIGQUIT: printf("\\nthread: %ld, sig quit\\n", tid); pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&cond); return (void*)0; default: printf("unexpected signal %d\\n", signo); exit(1); } } return (void *)0; } int main(void) { int err; sigset_t oldmask; pthread_t tid; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGQUIT); if((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) err_exit(err, "SIG_BLOCK error"); err = pthread_create(&tid, 0, thr_fn, 0); if(err != 0) err_exit(err, "can't create thread"); pthread_mutex_lock(&lock); while(quitflag == 0) pthread_cond_wait(&cond, &lock); pthread_mutex_unlock(&lock); quitflag = 0; if(sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) err_sys("SIG_SETMASK error"); printf("main thread %ld quits.\\n", pthread_self()); return 0; }
1
#include <pthread.h> void display_statistics(){ struct timeval current_time; gettimeofday(&current_time, 0); float temp = calculate_time_difference(current_time,emulation_start_time); printf("%012.3fms: emulation ends\\n",temp); pthread_mutex_lock(&mutex); printf("Total Q1 : %f\\n",average_number_of_packets_in_Q1); printf("Total Q2 : %f\\n",average_number_of_packets_in_Q2); average_number_of_packets_in_Q1 = average_number_of_packets_in_Q1 / temp; average_number_of_packets_in_Q2 = average_number_of_packets_in_Q2 / temp; average_number_of_packets_at_S = average_number_of_packets_at_S / temp; printf("\\nStatistics:\\n\\n"); printf(" average packet inter-arrival time = "); if(average_packet_inter_arrival_time >= 0.0){ printf("%f\\n",average_packet_inter_arrival_time / 1000.0); } else { printf("N/A\\n"); } printf(" average packet service time = "); if(average_packet_service_time >= 0.0){ printf("%f\\n\\n",average_packet_service_time / 1000.0); } else { printf("N/A\\n\\n"); } printf(" average number of packets in Q1 = "); if(average_number_of_packets_in_Q1 >= 0.0){ printf("%f\\n",average_number_of_packets_in_Q1); } else { printf("N/A\\n"); } printf(" average number of packets in Q2 = "); if(average_number_of_packets_in_Q2 >= 0.0){ printf("%f\\n",average_number_of_packets_in_Q2); } else { printf("N/A\\n"); } printf(" average number of packets in S = "); if(average_number_of_packets_at_S >= 0.0){ printf("%f\\n\\n",average_number_of_packets_at_S); } else { printf("N/A\\n\\n"); } printf(" average time a packet spent in system = "); if(average_time_a_packet_spent_in_system >= 0.0){ printf("%f\\n",average_time_a_packet_spent_in_system / 1000.0); } else { printf("N/A\\n"); } printf(" standard deviation for the time spent in system = "); if(standard_deviation_for_time_spent_in_system >= 0.0){ printf("%f\\n\\n",standard_deviation_for_time_spent_in_system / 1000.0); } else { printf("N/A\\n\\n"); } printf(" token drop probability = "); if(token_drop_probability >= 0.0){ printf("%f\\n",token_drop_probability); } else { printf("N/A\\n"); } printf(" packet drop probability = "); if(packet_drop_probability >= 0.0){ printf("%f\\n",packet_drop_probability); } else { printf("N/A\\n"); } pthread_mutex_unlock(&mutex); }
0
#include <pthread.h> char rxFrame[MAXRXFRAME]; char logBuffer[MAXLOGBUFFER]; ssize_t readline(int fd, void *vptr, size_t maxlen); void decodeRxFrame(void); void resyncFrame(void); void ackFrame(void); void *rx_thService(void *arg) { int n; bzero(logBuffer, sizeof(logBuffer)); sprintf(logBuffer, "INFO::rx_thService: Iniciando hilo rxdata..."); F_syslog("%s", logBuffer); while(1) { pthread_mutex_lock(&link_mlock); while (linkStatus != LINKUP) { pthread_cond_wait(&socketRdy_cvlock, &link_mlock); } pthread_mutex_unlock(&link_mlock); while ( ( n = readline(sockfd, rxFrame, MAXRXFRAME) ) > 0) { decodeRxFrame(); bzero(&rxFrame, sizeof(rxFrame)); pthread_mutex_lock(&link_mlock); linkStatus = LINKUP; pthread_mutex_unlock(&link_mlock); } switch ( n ) { case 0: pthread_mutex_lock(&link_mlock); linkStatus = LINKDOWN; pthread_mutex_unlock(&link_mlock); bzero(logBuffer, sizeof(logBuffer)); sprintf(logBuffer, "INFO::rx_thService: El server cerro el socket."); F_syslog("%s", logBuffer); break; case -1: pthread_mutex_lock(&link_mlock); linkStatus = LINKERROR; pthread_mutex_unlock(&link_mlock); bzero(logBuffer, sizeof(logBuffer)); sprintf(logBuffer, "ERROr::rx_thService: Error al leer el socket."); F_syslog("%s", logBuffer); break; } } } ssize_t readline(int fd, void *vptr, size_t maxlen) { ssize_t n, rc; char c, *ptr; ptr = vptr; for (n = 1; n < maxlen; n++) { again: if ( ( rc = read(fd, &c, 1)) == 1) { if (c == '\\0') goto again; *ptr++ = c; if (c == '\\n') break; } else if (rc == 0) { if ( n == 1) return(0); else break; } else { if (errno == EINTR) { goto again; } return (-1); } } *ptr = 0; return(n); } void decodeRxFrame(void) { char *token, cp[MAXRXFRAME]; char parseDelimiters[] = ">,<"; char dlgId[7]; char frameType[2]; strcpy(cp, rxFrame); token = strtok(cp, parseDelimiters); strcpy( dlgId, token); token = strtok(0, parseDelimiters); strncpy( frameType, token, 1); switch (frameType[0]) { case '?': resyncFrame(); break; case '!': ackFrame(); break; default: bzero(logBuffer, sizeof(logBuffer)); sprintf(logBuffer, "ERROR::decodeRxFrame: rx err frame: %s", rxFrame); F_syslog("%s", logBuffer); break; } } void resyncFrame(void) { int n; char txBuffer[MAXTXBUFFER]; bzero(logBuffer, sizeof(logBuffer)); sprintf(logBuffer, "INFO::resyncFrame: rx resync frame: %s", rxFrame); F_syslog("%s", logBuffer); bzero(logBuffer, sizeof(logBuffer)); sprintf(txBuffer, ">%s,?<\\n", systemParameters.dlgId); pthread_mutex_lock(&socket_mlock); n = write(sockfd, txBuffer,strlen(txBuffer)); pthread_mutex_unlock(&socket_mlock); bzero(logBuffer, sizeof(logBuffer)); if (n < 0) { pthread_mutex_lock(&link_mlock); linkStatus = LINKERROR; pthread_mutex_unlock(&link_mlock); sprintf(logBuffer, "ERROR::resyncFrame: error de trasmision de resync ack"); } else { sprintf(logBuffer, "INFO::resyncFrame: tx resync ack: %s", txBuffer); } F_syslog("%s", logBuffer); clockResync(rxFrame); } void ackFrame(void) { pthread_mutex_lock(&systemVars_mlock); systemVars.pktWaitingAck = 0; pthread_mutex_unlock(&systemVars_mlock); bzero(logBuffer, sizeof(logBuffer)); sprintf(logBuffer, "INFO::ackFrame: rx ack frame: %s", rxFrame); F_syslog("%s", logBuffer); }
1
#include <pthread.h> struct servent *getservbyport(int port, const char *proto) { char *buf = _serv_buf(); if (!buf) return 0; return getservbyport_r(port, proto, (struct servent *) buf, buf + sizeof(struct servent), SERV_BUFSIZE); } struct servent *getservbyport_r(int port, const char *proto, struct servent *result, char *buf, int bufsize) { pthread_mutex_lock(&serv_iterate_lock); setservent(0); while ((result = getservent_r(result, buf, bufsize)) != 0) { if (result->s_port != port) continue; if (proto == 0 || strcmp(result->s_proto, proto) == 0) break; } pthread_mutex_unlock(&serv_iterate_lock); return result; }
0
#include <pthread.h> char y, x; }POSICAO; char fim, humano,num; int tempo; }JOGADOR; int maxY, maxX; POSICAO ele[4]={ {3,10},{15,15},{12,40},{19,45}}; pthread_mutex_t trinco; void *move_jogador(void *dados){ JOGADOR *j; POSICAO d; int ch; j=(JOGADOR *) dados; do{ if (!j->humano){ ch=rand()%4; d.y=0;d.x=0; switch(ch){ case 0:d.y--;break; case 1:d.y++;break; case 2:d.x--;break; case 3:d.x++;break; } if (j->num>=0&&j->num<4){ pthread_mutex_lock(&trinco); mvaddch(ele[j->num].y,ele[j->num].x,' '); ele[j->num].y+=d.y; ele[j->num].x+=d.x; mvaddch(ele[j->num].y,ele[j->num].x,'0'+j->num); refresh(); } pthread_mutex_unlock(&trinco); } usleep(j->tempo); }while(!j->fim); pthread_exit(0); } int main(void){ POSICAO d; JOGADOR j[4]={{0,0,0,100000},{0,0,1,300000},{0,0,2,500000},{0,0,3,700000}}; pthread_t tarefa[4]; int ch,i,num; initscr(); noecho(); cbreak(); keypad(stdscr,TRUE); curs_set(0); getmaxyx(stdscr,maxY,maxX); pthread_mutex_init(&trinco,0); for(i=0;i<4;i++) pthread_create(&tarefa[i],0,&move_jogador,(void *)&j[i]); num=-1; do{ ch=getch(); d.y=0; d.x=0; switch(ch){ case '0':num=0; j[0].humano=1; break; case '1':num=1;j[1].humano=1;break; case '2':num=2;j[2].humano=1;break; case '3':num=3;j[3].humano=1;break; case 'd':num=-1; for (i=0;i<4;i++){ j[i].humano=0; } break; case KEY_UP: d.y--; break; case KEY_DOWN: d.y++; break; case KEY_LEFT: d.x--; break; case KEY_RIGHT: d.x++; break; } if(num>=0&&num<4){ pthread_mutex_lock(&trinco); mvaddch(ele[num].y,ele[num].x,' '); ele[num].y+=d.y; ele[num].x+=d.x; mvaddch(ele[num].y,ele[num].x,'0'+num); refresh(); pthread_mutex_unlock(&trinco); } }while(ch!='q'); for(i=0;i<4;i++){ j[i].fim=1; pthread_join(tarefa[i],0); } pthread_mutex_destroy(&trinco); endwin(); exit(0); }
1
#include <pthread.h> pthread_mutex_t globalMutex[2]; pthread_cond_t globalCondVar[2]; static void *threadFunc1(void *args) { assert(args == 0); pthread_mutex_lock(&globalMutex[0]); pthread_cond_wait(&globalCondVar[0], &globalMutex[0]); printf("X modified by threadFunc 1\\n"); pthread_mutex_unlock(&globalMutex[0]); return 0; } static void *threadFunc2(void *args) { assert(args == 0); pthread_mutex_lock(&globalMutex[1]); pthread_cond_wait(&globalCondVar[1], &globalMutex[1]); printf("X Modified by threadFunc 2\\n"); pthread_mutex_unlock(&globalMutex[1]); return 0; } int main(void) { pthread_t thread[2]; pthread_mutex_init(&globalMutex[0], 0); pthread_mutex_init(&globalMutex[1], 0); pthread_cond_init(&globalCondVar[0], 0); pthread_cond_init(&globalCondVar[1], 0); pthread_create(&thread[0], 0, threadFunc1, 0); pthread_create(&thread[1], 0, threadFunc2, 0); struct timespec nap = { .tv_sec = 0, .tv_nsec = 10000 }; nanosleep(&nap, 0); pthread_mutex_lock(&globalMutex[0]); pthread_mutex_lock(&globalMutex[1]); pthread_cond_signal(&globalCondVar[0]); pthread_cond_signal(&globalCondVar[1]); pthread_mutex_unlock(&globalMutex[0]); pthread_mutex_unlock(&globalMutex[1]); pthread_join(thread[1], 0); pthread_join(thread[0], 0); pthread_cond_destroy(&globalCondVar[0]); pthread_cond_destroy(&globalCondVar[1]); pthread_mutex_destroy(&globalMutex[0]); pthread_mutex_destroy(&globalMutex[1]); return 0; }
0
#include <pthread.h> int sockfd; int recvCounter[256]; float neighbourRR[256]; char recvRouter[MAX_PACKET_LEN]; int recvLen; pthread_mutex_t recv_mutex; pthread_t p_id; pthread_attr_t p_attr; void cul_linkQuality(); void recv_init(){ printf("recv_init\\n"); if( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ){ perror("Recv_init---socket."); printf("errno:%d\\n",errno); exit(1); } int so_broadcast =1; setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &so_broadcast, sizeof(so_broadcast)); struct sockaddr_in broadcast_addr; bzero(&broadcast_addr, sizeof(broadcast_addr)); broadcast_addr.sin_family=AF_INET; broadcast_addr.sin_port = htons( BROADCASTPORT ); if( inet_aton(BROADCASTIP,&broadcast_addr.sin_addr)<0 ){ perror("Recv_init---inet_aton."); printf("errno:%d\\n",errno); exit(1); } if( bind(sockfd,(struct sockaddr*)&broadcast_addr,sizeof(broadcast_addr))<0){ perror("Recv_init---bind."); printf("errno:%d\\n",errno); exit(1); } pthread_mutex_init(&recv_mutex, 0); pthread_attr_init (&p_attr); pthread_attr_setdetachstate(&p_attr, PTHREAD_CREATE_DETACHED); if( pthread_create(&p_id,&p_attr,(void*)cul_linkQuality,0) !=0 ){ printf("cul_linkQuality start error!%s\\n",strerror(errno)); abort(); exit(1); } } void recv_departure(){ sleep(2); printf("recv_departure\\n"); char tmp[200]; char packet[MAX_PACKET_LEN]; int len; int i=0; int j=0; struct sockaddr_in addr; size_t addrlen; memset(tmp,0,sizeof(tmp)); while(1){ if( (len=recvfrom(sockfd, packet, MAX_PACKET_LEN, 0, (struct sockaddr *)&addr, &addrlen))<0 ){ perror("recv---recvfrom."); printf("errno:%d\\n",errno); } else{ strcpy(tmp, inet_ntoa(addr.sin_addr)); if(strcmp(HOSTIP,tmp)!=0){ int ID=0; int tmplen = strlen(tmp); for(i=tmplen-1,j=1; i>=0; i--){ if(tmp[i]=='.') break; else{ ID=ID+(tmp[i]-'0')*j; } j=j*10; } if(ID!=0){ printf("recv---recvfrom %s:len=%d msg=%x\\n",tmp,len,packet[1]); pthread_mutex_lock( &recv_mutex); updateRouter(ID, packet+1,len-1,neighbourRR); recvCounter[ID]++; pthread_mutex_unlock( &recv_mutex); } } } } } void cul_linkQuality(){ int i=0; float RR; float NRR; int preEtx[256]; memset(preEtx,0,sizeof(preEtx)); while(1){ sleep(20); pthread_mutex_lock( &recv_mutex); for(i=0;i<256;i++){ RR=recvCounter[i]/10.0; recvCounter[i]=0; NRR=neighbourRR[i]; neighbourRR[i]=NRR*0.5+RR*0.5; if(neighbourRR[i]>0 || RR>0 || NRR>0){ printf("cul_linkQuality---ID=%d RR=%0.2f NRR=%0.2f neighbourRR[ID]=%0.2f\\n",i,RR,NRR,neighbourRR[i]); } } printf("\\n"); pthread_mutex_unlock( &recv_mutex); } }
1
#include <pthread.h> void ports_resume_class_rpcs (struct port_class *class) { pthread_mutex_lock (&_ports_lock); assert_backtrace (class->flags & PORT_CLASS_INHIBITED); class->flags &= ~PORT_CLASS_INHIBITED; if (class->flags & PORT_CLASS_BLOCKED) { class->flags &= ~PORT_CLASS_BLOCKED; pthread_cond_broadcast (&_ports_block); } pthread_mutex_unlock (&_ports_lock); }
0
#include <pthread.h> int A[] = {1, 7, 9, -33, 1, 4, 11, 0, 891, 3}; int FOUND = 0; int COUNT = 0; pthread_mutex_t lock; void *partition(void *p) { int i; long tid = (long) p; int numCells = 10 / 10; int remainingCells = 10 % 10; int startCell = numCells * tid; int endCell; if (tid == 10 - 1) endCell = numCells * tid + numCells + remainingCells; else endCell = numCells * tid + numCells; for (i = startCell; i < endCell; i++) printf("Tid %d does cell %d\\n", tid, i); for (i = startCell; i < endCell; i++) if (A[i] == 1) { FOUND = 1; pthread_mutex_lock(&lock); COUNT++; pthread_mutex_unlock(&lock); } pthread_exit(0); } int main(void) { int i; long t; void *status; pthread_t tid[10]; pthread_mutex_init(&lock, 0); for (t = 0; t < 10; t++) pthread_create(&tid[t], 0, partition, (void *) t); for (t = 0; t < 10; t++) pthread_join(tid[t], &status); printf("%d found = %d times\\n", 1, COUNT); pthread_mutex_destroy(&lock); return 0; }
1
#include <pthread.h> struct prodcons { int buffer[8]; pthread_mutex_t lock; int readpos , writepos; pthread_cond_t notempty; pthread_cond_t notfull; }; void init(struct prodcons * b){ pthread_mutex_init(&b->lock,0); pthread_cond_init(&b->notempty,0); pthread_cond_init(&b->notfull,0); b->readpos=0; b->writepos=0; } void put(struct prodcons* b,int data){ pthread_mutex_lock(&b->lock); if((b->writepos + 1) % 8 == b->readpos) { pthread_cond_wait(&b->notfull, &b->lock) ; } b->buffer[b->writepos]=data; b->writepos++; if(b->writepos >= 8) b->writepos=0; pthread_cond_signal(&b->notempty); pthread_mutex_unlock(&b->lock); } int get(struct prodcons *b){ int data; pthread_mutex_lock(&b->lock); if(b->writepos == b->readpos) { pthread_cond_wait(&b->notempty, &b->lock); } data = b->buffer[b->readpos]; b->readpos++; if(b->readpos >= 8) b->readpos=0; pthread_cond_signal(&b->notfull); pthread_mutex_unlock(&b->lock); return data; } struct prodcons buffer; void *producer(void *data) { int n; for(n = 0; n < 10000; n++) { printf("%d \\n", n) ; put(&buffer, n); } put(&buffer, (-1)); return 0; } void *consumer(void * data) { int d; while(1) { d = get(&buffer); if(d == (-1)) break; printf("%d\\n", d); } return 0; } int main(void) { pthread_t th_a, th_b; void *retval; init(&buffer); pthread_create(&th_a, 0, producer, 0); pthread_create(&th_b, 0, consumer, 0); pthread_join(th_a, &retval); pthread_join(th_b, &retval); return 0; }
0
#include <pthread.h> void ports_resume_port_rpcs (void *portstruct) { struct port_info *pi = portstruct; pthread_mutex_lock (&_ports_lock); assert_backtrace (pi->flags & PORT_INHIBITED); pi->flags &= ~PORT_INHIBITED; if (pi->flags & PORT_BLOCKED) { pi->flags &= ~PORT_BLOCKED; pthread_cond_broadcast (&_ports_block); } pthread_mutex_unlock (&_ports_lock); }
1
#include <pthread.h> void print_error(int error, char* message){ puts(message); puts(strerror(error)); } void print_error_exit(int error, char* message){ puts(message); puts(strerror(error)); exit(1); } void * search_file(void * text_to_find); int file_desc; pthread_t *threads; pthread_mutex_t p_mutex; int records_number; int threads_number; void atexit_function(){ free(threads); close(file_desc); } struct record{ int id; char text[1024 - sizeof(int)]; }; int main(int argc, char **argv){ atexit(atexit_function); if(argc != 5){ printf("usage: ./records_counter <file name> <threads number> <records number> <searched word>"); exit(1); } if( (file_desc = open(argv[1], O_RDONLY)) == -1) print_error_exit(errno, "can not open file"); if( (pthread_mutex_init(&p_mutex, 0)) !=0 ) print_error_exit(errno, "error in pthread_mutex_init"); threads_number = atoi(argv[2]); records_number = atoi(argv[3]); threads = malloc( sizeof(pthread_t) *threads_number); int i; for(i = 0; i < threads_number; i++){ if(pthread_create(&threads[i], 0, search_file, argv[4]) == -1); } for(i = 0; i < threads_number; i++){ if(pthread_join(threads[i], 0) == -1) print_error(errno, "error in pthread_join"); } exit(0); } void* search_file(void * text_to_find){ struct record * buffer; pthread_setcanceltype( PTHREAD_CANCEL_DEFERRED, 0); int bytes_read = 1; int file_offset; buffer = malloc( sizeof(char)*1024 + 1); int finish_flag = 0; pthread_cleanup_push(pthread_mutex_unlock, (void *) &p_mutex); while(bytes_read > 0 && finish_flag == 0){ int j; for(j = 0; j < records_number; j++){ pthread_mutex_lock(&p_mutex); if( (file_offset = lseek(file_desc, 0, 1)) == -1) print_error(errno, "erron in lseek"); if( (bytes_read = read(file_desc, buffer, 1024)) == -1) print_error(errno, "errno in read"); pthread_testcancel(); buffer->text[1024 -sizeof(int)] = 0; char *substr; substr = strstr(buffer->text, text_to_find); if(substr != 0){ int i; for(i = 0; i < threads_number; i++){ if(threads[i] != pthread_self()) pthread_cancel(threads[i]); } int line = file_offset/1024; printf("id of thread: %ld id of record: %d\\n", (long)pthread_self(), line +1); finish_flag = 1; pthread_mutex_unlock(&p_mutex); break; } pthread_mutex_unlock(&p_mutex); } } pthread_cleanup_pop(0); printf("finished\\n"); fflush(stdout); return 0; }
0
#include <pthread.h> pthread_cond_t mycond = PTHREAD_COND_INITIALIZER; pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER; { int _data; struct node* _next; }node_t,*node_p,**node_pp; node_p CreatNode(node_pp list, int data) { assert(list); node_p node = (node_p)malloc(sizeof(node_t)); node->_next = 0; node->_data = data; return node; } void InitList(node_pp list) { assert(list); *list = CreatNode(list,0); } int IsEmpty(node_p list) { if((list == 0) || list->_next == 0) { return 1; } else return 0; } void PushHead(node_p list, int data) { assert(list); node_p node = CreatNode(&list,data); if(node != 0) { node->_next = list->_next; list->_next = node; } } void DelNode(node_p node) { node->_next = 0; node->_data = 0; free(node); } void PopHead(node_p list) { if(list == 0) { return; } else { node_p del = list->_next; list->_next = del->_next; DelNode(del); } } void DestoryList(node_p list) { node_p del = list->_next; while(del) { PopHead(list); del = del->_next; } DelNode(list); } void Show(node_p list) { assert(list); node_p node = list->_next; while(node) { printf("%d ",node->_data); node = node->_next; } printf("\\n"); } void* thread_product(void* arg) { node_p head = (node_p)arg; while(1) { usleep(1236); srand((unsigned int )time(0)); int data = rand()%10000; pthread_mutex_lock(&mylock); PushHead(head,data); pthread_mutex_unlock(&mylock); pthread_cond_signal(&mycond); printf("product done,data is: %d\\n",data); } } void *thread_consumer(void* arg) { node_p head = (node_p)arg; while(1) { pthread_mutex_lock(&mylock); if( IsEmpty(head) ) { pthread_cond_wait(&mycond, &mylock); } PopHead(head); pthread_mutex_unlock(&mylock); printf("consumer done.data is: %d\\n",head->_data); } } int main() { node_p head; InitList(&head); pthread_t tid1,tid2; int ret1 = pthread_create(&tid1,0,thread_product, head); int ret2 = pthread_create(&tid2,0,thread_consumer, head); pthread_join(tid1,0); pthread_join(tid2,0); return 0; }
1
#include <pthread.h> int scapremedy_exec(const char * dir, const char *remediation_file) { pid_t pid; pid = fork(); if ( pid == 0 ) { int fd = open("/dev/null", O_RDONLY); int fd2; int i; struct rscap_hash * hash; const char * cmd; const char * argv_list[1024]; char argv[32]; chdir(dir); fd2 = open("results.out", O_CREAT|O_TRUNC|O_WRONLY, 0660); close(0); dup2(fd, 0); dup2(fd2, 1); dup2(fd2, 2); for ( i = 3; i < 1024 ; i ++ ) close(i); hash = rscap_config_load(remediation_file); if ( hash == 0 ) { fprintf(stderr, "Could not parse %s\\n", remediation_file); exit(1); } cmd = rscap_config_get(hash, "Command"); if ( cmd == 0 ) { fprintf(stderr, "Missing Command= in %s\\n", remediation_file); exit(1); } argv_list[0] = cmd; for ( i = 0 ; i < 1024 - 1 ; i ++ ) { snprintf(argv, sizeof(argv), "Arg%d", i); argv_list[i] = rscap_config_get(hash, argv); if ( argv_list[i] == 0 ) break; } rscap_hash_free(hash); for ( i = 0 ; argv_list[i] != 0 ; i ++ ) printf("arg%d=%s\\n", i, argv_list[i]); execv(cmd, (char* const*)argv_list); perror("execv()"); _exit(1); } return pid; } static int _scapremedy_exec_script(struct rscap_signature_cfg * sig_cfg, const char * dir, const char * path, struct scap_task * task) { char * remediation_tar_archive; char * remediation_file; struct rscap_hash * hash; rscap_log("Should eval dir=%s path=%s\\n", dir, path); remediation_tar_archive = rscap_mk_path(dir, "remediation.tgz", 0); hash = rscap_load_signatures(sig_cfg, dir, "remediation.tgz"); if ( hash == 0 ) { rscap_log("Invalid archive for job %s (No/Invalid signature)\\n", path); rscap_free(remediation_tar_archive); goto err; } if ( rscap_untar(remediation_tar_archive, dir, hash, 0) != 0 ) { rscap_log("Invalid archive for job %s (bad signature)\\n", path); rscap_hash_free(hash); rscap_free(remediation_tar_archive); goto err; } rscap_free(remediation_tar_archive); rscap_hash_free(hash); remediation_file = rscap_mk_path(dir, "command", 0); if ( rscap_file_readable(remediation_file) < 0 ) { rscap_log("Invalid archive for job %s (%s not included)\\n", path, remediation_file); rscap_free(remediation_file); goto err; } pthread_mutex_lock(&task->mx); task->fork_pid = scapremedy_exec(dir, remediation_file); pthread_mutex_unlock(&task->mx); if ( task->fork_pid > 0) { for ( ;; ) { int e; errno = 0; e = waitpid(task->fork_pid, 0, 0); if ( e >= 0 ) break; if ( e < 0 && errno != EINTR ) break; } } pthread_mutex_lock(&task->mx); if ( task->finished == 0 ) task->finished = SCAP_TASK_SUCCESS; pthread_mutex_unlock(&task->mx); rscap_free(remediation_file); return 0; err: pthread_mutex_lock(&task->mx); task->finished = SCAP_TASK_ERROR; pthread_mutex_unlock(&task->mx); return -1; } static void * _scapremedy_exec_script_bootstrap(void * arg) { struct scap_task * task = (struct scap_task*) arg; _scapremedy_exec_script(task->sig_cfg, task->path, task->dir, task); return 0; } int scapremedy_exec_script(struct scap_task * task) { pthread_mutex_lock(&task->mx); pthread_create(&task->thread, 0, _scapremedy_exec_script_bootstrap, task); pthread_mutex_unlock(&task->mx); return 0; }
0
#include <pthread.h> int state[5]; int chopstick[5]; pthread_mutex_t mutex; pthread_cond_t con_var; void *at_table(void* i); void test(); int main(int argc, const char * argv[]) { for (int i = 0; i < 5; ++i) { chopstick[i] = 1; state[i] = 1; } srand(time(0)); pthread_mutex_init(&mutex, 0); pthread_cond_init(&con_var, 0); pthread_t philosopher[5]; for (int i = 0; i < 5; ++i) { pthread_create(&philosopher[i], 0, at_table, i); } for (int i = 0; i < 5; ++i) { pthread_join(philosopher[i], 0); } } void pickup_forks(int philosopher_number) { printf("%d is picking \\n", philosopher_number); pthread_mutex_lock(&mutex); while (!(chopstick[philosopher_number] && chopstick[(philosopher_number+1)%5])) { pthread_cond_wait(&con_var, &mutex); } state[philosopher_number] = 0; chopstick[philosopher_number] = 0; chopstick[(philosopher_number + 1) % 5] = 0; printf("The philosopher %d is eating\\n", philosopher_number); printf("And the state of all philosopher_number\\n\\n"); for (int i = 0; i < 5 ; ++i) { printf("philosopher %d is %d\\n", i, state[i]); } printf("\\n"); test(); pthread_mutex_unlock(&mutex); } void return_forks(int philosopher_number) { pthread_mutex_lock(&mutex); chopstick[philosopher_number] = 1; chopstick[(philosopher_number + 1) % 5] = 1; state[philosopher_number] = 1; pthread_cond_signal(&con_var); pthread_mutex_unlock(&mutex); } void eating() { int time = rand() % 2 + 1; sleep(time); } void *at_table (void* i) { while (1) { pickup_forks((int)i); eating(); return_forks((int)i); } } void test() { for (int i = 0; i < 5; ++i) { if(state[i] == 0 && state[(i+1) % 5] == 0) { return; } } }
1
#include <pthread.h> void send_req(int fd, struct qstat *tt) { volatile uint64_t a; char ver[64]; struct iovec iov[6] = { {.iov_base = "GET ", .iov_len = 4}, {.iov_base = gp, .iov_len = gl}, {.iov_base = ver, .iov_len = 0}, {.iov_base = " HTTP/1.1\\r\\nHost: ", .iov_len = 17}, {.iov_base = hp, .iov_len = hl}, {.iov_base = "\\r\\nUser-Agent: Quasar\\r\\nConnection: keep-alive\\r\\n\\r\\n", .iov_len = 48}}; struct msghdr mh = { .msg_name = 0, .msg_namelen = 0, .msg_iov = iov, .msg_iovlen = 6, .msg_control = 0, .msg_controllen = 0, .msg_flags = 0}; struct linger xx = {.l_onoff = 1, .l_linger = 0}; a = vercur; if (++a >= vernum) a = 0; vercur = a; snprintf(ver, sizeof(ver), "%llu", (unsigned long long int) a); if (gp[gl - 1] == '?' || gp[gl - 1] == '&' || gp[gl - 1] == '_') iov[2].iov_len = strlen(ver); else iov[2].iov_len = 0; while ( (a = sendmsg(fd, &mh, MSG_DONTWAIT | MSG_NOSIGNAL)) < 0 && errno == EINTR); if (a < 0) { sre = errno; setsockopt(fd, SOL_SOCKET, SO_LINGER, &xx, sizeof(xx)); while (close(fd) < 0 && errno == EINTR); pthread_mutex_lock(&tt->mx); tt->cox++; pthread_mutex_unlock(&tt->mx); } else { pthread_mutex_lock(&tt->mx); tt->rps++; pthread_mutex_unlock(&tt->mx); } }
0
#include <pthread.h> uint64_t nb; FILE * file; char str[60]; pthread_t thread0; pthread_t thread1; pthread_mutex_t lock; pthread_mutex_t lockScreen; const int MAX_FACTORS=64; void print_prime_factors(uint64_t n); int get_prime_factors(uint64_t n,uint64_t* dest); void* thread_prime_factors(void * u) { pthread_mutex_lock(&lock); while ( fgets(str, 60, file)!=0 ) { nb=atol(str); pthread_mutex_unlock(&lock); print_prime_factors(nb); pthread_mutex_lock(&lock); } pthread_mutex_unlock(&lock); return 0; } void print_prime_factors(uint64_t n) { uint64_t factors[MAX_FACTORS]; int j,k; k=get_prime_factors(n,factors); pthread_mutex_lock(&lockScreen); printf("%ju: ",n); for(j=0; j<k; j++) { printf("%ju ",factors[j]); } printf("\\n"); pthread_mutex_unlock(&lockScreen); } int get_prime_factors(uint64_t n,uint64_t* dest) { int compteur=0; uint64_t i; while ( n%2 == 0) { n=n/2; dest[compteur]=(uint64_t)2; compteur++; } while ( n%3 == 0) { n=n/3; dest[compteur]=(uint64_t)3; compteur++; } while ( n%5 == 0) { n=n/5; dest[compteur]=(uint64_t)5; compteur++; } for( i=7; n!=1 ; i++ ) { while (n%i==0) { n=n/i; dest[compteur]=i; compteur++; } } if(n!=1) { dest[compteur]=n; compteur++; } return compteur; } int main(void) { file = fopen ("fileQuestion10pasEfficace.txt","r"); if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex file init failed\\n"); return 1; } if (pthread_mutex_init(&lockScreen, 0) != 0) { printf("\\n mutex screen init failed\\n"); return 1; } pthread_create(&thread0, 0, thread_prime_factors, 0); pthread_create(&thread1, 0, thread_prime_factors, 0); pthread_join(thread0, 0); pthread_join(thread1, 0); pthread_mutex_destroy(&lock); pthread_mutex_destroy(&lockScreen); return 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 to finish...\\n"); res = pthread_join(a_thread, &thread_result); if (res != 0) { perror("Thread join failed"); exit(1); } printf("Thread joined\\n"); pthread_mutex_destroy(&work_mutex); exit(0); } void *thread_function(void *arg) { sleep(1); pthread_mutex_lock(&work_mutex); while(strncmp("end", work_area, 3) != 0) { printf("You input %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 pthread_barrier_t barrier; static pthread_t *writers, *readers; static pthread_mutex_t lock; void *reader(void *arg) { unsigned nreads = *(unsigned *)arg, i; int p; volatile int tmp = 0; pthread_barrier_wait(&barrier); ct_start_clock(); for (i = 0; i < nreads; i++) { pthread_mutex_lock(&lock); while (++tmp % 64); pthread_mutex_unlock(&lock); } return 0; } void *writer(void *arg) { unsigned nwrites = *(unsigned *) arg, i; volatile int tmp = 0; pthread_barrier_wait(&barrier); ct_start_clock(); for (i = 0; i < nwrites; i++) { pthread_mutex_lock(&lock); while (++tmp % 128); pthread_mutex_unlock(&lock); } return 0; } void rwlock_test(unsigned nreaders, unsigned nreads_per_reader, unsigned nwriters, unsigned nwrites_per_writer) { int i, j; void *ret; if (nreaders) { readers = malloc(sizeof(pthread_t) * nreaders); assert(readers); } if (nwriters) { writers = malloc(sizeof(pthread_t) * nwriters); assert(writers); } pthread_barrier_init(&barrier, 0, nreaders + nwriters); for (i = 0; i < nreaders; i++) { assert(!pthread_create(readers + i, 0, reader, &nreads_per_reader)); } for (j = 0; j < nwriters; j++) { assert(!pthread_create(writers + j, 0, writer, &nwrites_per_writer)); } for (i = 0; i < nreaders; i++) { assert(!pthread_join(readers[i], &ret)); assert(!ret); } for (j = 0; j < nwriters; j++) { assert(!pthread_join(writers[j], &ret)); assert(!ret); } ct_stop_clock(); if (readers) free(readers); if (writers) free(writers); readers = writers = 0; } int main(int argc, char **argv) { char *test_name = "---pthread_mutex(glibc-2.11.3)---"; char *csv_header = "runtime(s),cpu_time"; char *csv_path = "./lock-tests.csv"; ct_info_t *info; info = ct_init_info(test_name, csv_path); ct_add_line(info, "%-*s%-*s\\n", 16, "runtime(s)", 16, "cpu_time"); rwlock_test(1<<7, 1<<14, 1<<7, 1<<14); ct_add_line(info, "%-*g%-*g\\n", 16, ct_wall_clock_time(), 16, ct_cpu_time()); rwlock_test(1<<7, 1<<14, 1<<0, 1<<14); ct_add_line(info, "%-*g%-*g\\n", 16, ct_wall_clock_time(), 16, ct_cpu_time()); rwlock_test(1<<7, 1<<14, 0, 1<<14); ct_add_line(info, "%-*g%-*g\\n", 16, ct_wall_clock_time(), 16, ct_cpu_time()); ct_fini_info(info); }
1
#include <pthread.h> struct msg { struct msg *m_next; }; struct msg *workq; pthread_cond_t qready = PTHREAD_COND_INITIALIZER; pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER; void process_msg() { struct msg *mp; for (;;) { pthread_mutex_lock(&qlock); while (workq == 0) pthread_cond_wait(&qready, &qlock); mp = workq; workq = mp->m_next; pthread_mutex_unlock(&qlock); } } void enqueue_msg(struct msg *mp) { pthread_mutex_lock(&qlock); mp->m_next = workq; workq = mp; pthread_mutex_unlock(&qlock); pthread_cond_signal(&qready); }
0
#include <pthread.h> void welcome(char* nickname, char* username, char* hostname, int socket) { char* msg = (char*)malloc(MAX_MSG_LEN+1); msg[0] = '\\0'; sprintf(msg,":%s 001 %s :Welcome to the Internet Relay Network %s!%s@%s\\r\\n", serverHost,nickname,nickname,username,hostname); pthread_mutex_t clock = get_lock_from_sock(socket); pthread_mutex_lock(&clock); if (send(socket, msg, strlen(msg), 0) <= 0) { sock_is_gone(socket); free(msg); perror("Socket send() failed"); close(socket); pthread_exit(0); } pthread_mutex_unlock(&clock); free(msg); } void your_host(char* nickname, char* hostname, int socket) { char* msg = (char*)malloc(MAX_MSG_LEN+1); msg[0] = '\\0'; sprintf(msg, ":%s 002 %s :Your host is %s, running version chirc-0.3.2\\r\\n", serverHost,nickname,hostname); pthread_mutex_t clock = get_lock_from_sock(socket); pthread_mutex_lock(&clock); if (send(socket, msg, strlen(msg), 0) <= 0) { pthread_mutex_unlock(&clock); sock_is_gone(socket); free(msg); perror("Socket send() failed"); close(socket); pthread_exit(0); } pthread_mutex_unlock(&clock); free(msg); } void created(char* nickname, int socket) { char* msg = (char*)malloc(MAX_MSG_LEN+1); char buffer[80]; struct tm* timeinfo; timeinfo = localtime(&creationtime); strftime(buffer,80,"%F %X",timeinfo); msg[0] = '\\0'; sprintf(msg, ":%s 003 %s :This server was created %s\\r\\n", serverHost, nickname, buffer); pthread_mutex_t clock = get_lock_from_sock(socket); pthread_mutex_lock(&clock); if (send(socket, msg, strlen(msg), 0) <= 0) { pthread_mutex_unlock(&clock); sock_is_gone(socket); free(msg); perror("Socket send() failed"); close(socket); pthread_exit(0); } pthread_mutex_unlock(&clock); free(msg); } void my_info(char* nickname, int socket) { char* msg = (char*)malloc(MAX_MSG_LEN+1); msg[0] = '\\0'; sprintf(msg, ":%s 004 %s %s chirc-0.3.2 ao mtov\\r\\n", serverHost,nickname,serverHost); pthread_mutex_t clock = get_lock_from_sock(socket); pthread_mutex_lock(&clock); if (send(socket, msg, strlen(msg), 0) <= 0) { pthread_mutex_unlock(&clock); sock_is_gone(socket); free(msg); perror("Socket send() failed"); close(socket); pthread_exit(0); } pthread_mutex_unlock(&clock); free(msg); }
1
#include <pthread.h> static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t condition = PTHREAD_COND_INITIALIZER; static void * my_condition_thread (void * arg) { pthread_mutex_lock (&mutex); printf (" thread: enter CS\\n"); sleep (4); printf (" thread: wait...\\n"); pthread_cond_wait (&condition, &mutex); printf (" thread: signalled\\n"); sleep (2); printf (" thread: leave CS\\n"); pthread_mutex_unlock (&mutex); return (arg); } static void condition_test (void) { pthread_t my_thread; pthread_create (&my_thread, 0, my_condition_thread, 0); sleep (2); printf ("willing to enter...\\n"); pthread_mutex_lock (&mutex); printf ("enter CS\\n"); sleep (2); printf ("signal\\n"); pthread_cond_signal (&condition); sleep (2); pthread_mutex_unlock (&mutex); printf ("leave CS\\n"); pthread_join (my_thread, 0); } static void mask_test (void) { printf ("\\nbitmask of nineteen 1's: %04x\\n", ((1 << (19)) - 1)); } int main (void) { condition_test(); mask_test(); return (0); }
0
#include <pthread.h> int first,second; }two_ints_t; void* server(void *arg){ int i = 0; int r = 15; while(1){ printf("%d\\n",i); i ++; if(i == 10) { pthread_exit((void*)&r); } } } pthread_t start_servers(){ pthread_t thread; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr,20*1024*1024); int i; void **r = 0; for(i = 0; i < 5; i ++) { pthread_create(&thread,&attr,server,0); pthread_join(thread,r); } return thread; } semaphore P(semaphore s){ if ( s > 0 ) s --; else while(!s); } semaphore V(semaphore s){ s ++; return s; } semaphore empty = 10; semaphore occupied = 0; int nextin = 0; int nextout = 0; char buffer[10]; void Producer(char item){ P(empty); buffer[nextin] = item; nextin ++; if(nextin == 10) nextin = 0; V(occupied); } char Consumer(){ P(occupied); char item; item = buffer[nextout]; nextout ++; if(nextout == 10) nextout = 0; V(empty); return item; } int main() { start_servers(); pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; int x; pthread_mutex_lock(&m); x = x + 1; pthread_mutex_unlock(&m); sem_t semaphore; int err; err = sem_init(&semaphore, 0, 10); err = sem_wait(&semaphore); err = sem_post(&semaphore); return 0; }
1
#include <pthread.h> pthread_mutex_t mx, my; int x=2, y=2; void *thread1() { int a; pthread_mutex_lock(&mx); a = x; pthread_mutex_lock(&my); y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; pthread_mutex_unlock(&my); a = a + 1; pthread_mutex_lock(&my); y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; pthread_mutex_unlock(&my); x = x + x + a; pthread_mutex_unlock(&mx); assert(x!=47); return 0; } void *thread2() { pthread_mutex_lock(&mx); x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; pthread_mutex_unlock(&mx); return 0; } void *thread3() { pthread_mutex_lock(&my); y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; pthread_mutex_unlock(&my); return 0; } int main() { pthread_t t1, t2, t3; pthread_mutex_init(&mx, 0); pthread_mutex_init(&my, 0); pthread_create(&t1, 0, thread1, 0); pthread_create(&t2, 0, thread2, 0); pthread_create(&t3, 0, thread3, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); pthread_mutex_destroy(&mx); pthread_mutex_destroy(&my); return 0; }
0
#include <pthread.h> extern char** environ; static pthread_key_t key; static pthread_once_t once_init = PTHREAD_ONCE_INIT; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static void thread_init(void) { pthread_key_create(&key, free); } char* getenv(const char* name) { pthread_once(&once_init, thread_init); pthread_mutex_lock(&mutex); char* value_buffer = pthread_getspecific(key); if (!value_buffer) { if (!(value_buffer = malloc(4096))) { pthread_mutex_unlock(&mutex); return 0; } pthread_setspecific(key, value_buffer); } int len = strlen(name); int i; for (i = 0; environ[i] != 0; ++i) { if (!strncmp(name, environ[i], len) && (environ[i][len] == '=')) { strncpy(value_buffer, &environ[i][len + 1], 4096 - 1); pthread_mutex_unlock(&mutex); return value_buffer; } } pthread_mutex_unlock(&mutex); return 0; } int main(int argc, char* argv[]) { printf("HOME:%s\\n", getenv("HOME")); return 0; }
1
#include <pthread.h> pthread_t thread1, thread2; static pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER; void *workOne(void *arg) { pthread_mutex_lock(&lock1); usleep(1000); pthread_mutex_unlock(&lock1); pthread_mutex_lock(&lock2); usleep(1000); pthread_mutex_unlock(&lock2); return arg; } void *workTwo(void *arg) { usleep(1000); pthread_mutex_lock(&lock1); usleep(1000); pthread_mutex_unlock(&lock1); pthread_mutex_lock(&lock2); usleep(1000); pthread_mutex_unlock(&lock2); return arg; } int main() { int ret; ret = pthread_create(&thread1, 0, workOne, 0); if (ret) { fprintf(stderr, "pthread_create, error: %d\\n", ret); return ret; } ret = pthread_create(&thread2, 0, workTwo, 0); if (ret) { fprintf(stderr, "pthread_create, error: %d\\n", ret); return ret; } ret = pthread_join(thread1, 0); if (ret) { fprintf(stderr, "pthread_join, error: %d\\n", ret); return ret; } ret = pthread_join(thread2, 0); if (ret) { fprintf(stderr, "pthread_join, error: %d\\n", ret); return ret; } return 0; }
0
#include <pthread.h> static struct malloc_infos arena; static int __malloc_initialized = 0; static void lock(void) { if (unlikely(!__malloc_initialized)) return ; pthread_mutex_lock(&arena.mutex); } static void unlock(void) { if (unlikely(!__malloc_initialized)) return ; pthread_mutex_unlock(&arena.mutex); } static size_t npowof2(size_t size) { size_t i; size--; for (i = 1; i < sizeof(size) * 8; i <<= 1) size = size | (size >> i); return (size + 1); } static void malloc_init(void) { if (likely(__malloc_initialized)) return ; memset(&arena, 0, sizeof(arena)); pthread_mutex_init(&arena.mutex, 0); } static struct chunk * mem2chunk(void *p) { return (p ? (struct chunk *) p - 1 : 0); } static void * chunk2mem(struct chunk *chunk) { return (chunk ? chunk + 1 : 0); } void * get_chunk_aligned(size_t size, size_t alignment) { struct chunk *chunk = 0, *newp; size_t asize = size; char *p = 0; malloc_init(); if (alignment <= MALLOC_ALIGNMENT) return get_chunk(size); if ((alignment & (alignment - 1)) != 0) alignment = npowof2(alignment); if (!size) return 0; size = npowof2(size + MALLOC_MINSIZE + alignment + sizeof (struct chunk)); lock(); chunk = chunk_search(&arena, size); if (!chunk) goto end; chunk_remove_free(&arena, chunk); p = chunk2mem(chunk); if ((((unsigned long) (p)) % alignment) != 0) { char *brk = (char *) mem2chunk(align(p, alignment)); if ((long) (brk - (char *) (p)) < MALLOC_MINSIZE) brk += alignment; newp = (struct chunk *) brk; newp->size = chunk->size - sizeof (struct chunk) - (brk - p); newp->type = MALLOC_CHUNK_USED; chunk->size = brk - p; chunk->alignment = 0; chunk_insert_main(&arena, chunk, newp); chunk_append_free(&arena, chunk); chunk = newp; chunk->alignment = alignment; chunk->asked_size = asize; p = chunk2mem(chunk); } chunk_split(&arena, chunk, asize); end: unlock(); return p; } void * get_chunk(size_t size) { struct chunk *chunk = 0; size_t asize = size; malloc_init(); if (!size) return 0; size = npowof2(size); lock(); chunk = chunk_search(&arena, size); if (chunk) { chunk_remove_free(&arena, chunk); chunk_split(&arena, chunk, size); chunk->asked_size = asize; chunk->alignment = MALLOC_ALIGNMENT; } unlock(); return chunk2mem(chunk); } void free_chunk(void *ptr) { struct chunk *chunk; malloc_init(); if (!ptr) return; chunk = ((struct chunk *) ptr - 1); if (chunk->type != MALLOC_CHUNK_USED) { return; } lock(); chunk_append_free(&arena, chunk); chunk_fusion(&arena, chunk); chunk_give_back(&arena); unlock(); } void show_alloc_mem(void) { struct chunk *chunk; chunk = arena.lmain; puts("START\\t\\tSIZE\\tASIZE\\tALIGN\\tTYPE"); while (chunk) { printf("%p\\t", (void *) chunk); printf("%zu\\t%zu\\t%zu\\t", chunk->size, chunk->asked_size, chunk->alignment); if (chunk->type == MALLOC_CHUNK_FREE) puts("free"); else if (chunk->type == MALLOC_CHUNK_USED) puts("used"); else printf("bad (%zx)\\n", chunk->type); chunk = chunk->main_prev; } for (int i = MALLOC_SHIFT_LOW; i <= MALLOC_SHIFT_HIGH; ++i) printf("%6d : %zu\\n", 1 << i, arena.lfree_cnt[i]); }
1
#include <pthread.h> struct mode_extra_status { int output_pipe_fd; pthread_mutex_t mutex; union switch_data answer; long long rest_time[SWITCH_BUTTON_NUM + 1]; int score; pthread_t background_worker; bool terminated; }; static void *background_worker_main (void *arg); struct mode_extra_status *mode_extra_construct (int output_pipe_fd) { struct mode_extra_status *status; status = malloc (sizeof (*status)); status->output_pipe_fd = output_pipe_fd; pthread_mutex_init (&status->mutex, 0); status->answer.val = 0; status->score = 0; status->terminated = 0; pthread_create (&status->background_worker, 0, &background_worker_main, status); return status; } void mode_extra_destroy (struct mode_extra_status *status) { atomic_store_bool (&status->terminated, 1); pthread_join (status->background_worker, 0); pthread_mutex_destroy (&status->mutex); free (status); } int mode_extra_switch (struct mode_extra_status *status, union switch_data data) { pthread_mutex_lock (&status->mutex); int16_t correct = status->answer.val & data.val; int16_t incorrect = (status->answer.val ^ data.val) & data.val; LOG (LOGGING_LEVEL_HIGH, "[Main Process] correct = %03X, incorrect = %03X.", correct, incorrect); status->answer.val ^= correct; for (int i = 0; i < SWITCH_BUTTON_NUM; ++i) { status->score += (correct & 1); status->score -= (incorrect & 1); correct >>= 1; incorrect >>= 1; } if (status->score < 0) status->score = 0; output_message_fnd_send (status->output_pipe_fd, status->score); pthread_mutex_unlock (&status->mutex); return 0; } static void *background_worker_main (void *arg) { struct mode_extra_status *status = arg; long long prev_nano_time = get_nano_time (); long long prev_creation_time = 0; while (!atomic_load_bool (&status->terminated)) { pthread_mutex_lock (&status->mutex); long long cur_nano_time = get_nano_time (); long long time_gap = cur_nano_time - prev_nano_time; prev_nano_time = cur_nano_time; if (status->answer.bit_fields.s1) { status->rest_time[ 1 ] -= time_gap; if (status->rest_time[ 1 ] < 0) { status->answer.bit_fields.s1 = 0; if (status->score > 0) --status->score; } }; if (status->answer.bit_fields.s2) { status->rest_time[ 2 ] -= time_gap; if (status->rest_time[ 2 ] < 0) { status->answer.bit_fields.s2 = 0; if (status->score > 0) --status->score; } }; if (status->answer.bit_fields.s3) { status->rest_time[ 3 ] -= time_gap; if (status->rest_time[ 3 ] < 0) { status->answer.bit_fields.s3 = 0; if (status->score > 0) --status->score; } }; if (status->answer.bit_fields.s4) { status->rest_time[ 4 ] -= time_gap; if (status->rest_time[ 4 ] < 0) { status->answer.bit_fields.s4 = 0; if (status->score > 0) --status->score; } }; if (status->answer.bit_fields.s5) { status->rest_time[ 5 ] -= time_gap; if (status->rest_time[ 5 ] < 0) { status->answer.bit_fields.s5 = 0; if (status->score > 0) --status->score; } }; if (status->answer.bit_fields.s6) { status->rest_time[ 6 ] -= time_gap; if (status->rest_time[ 6 ] < 0) { status->answer.bit_fields.s6 = 0; if (status->score > 0) --status->score; } }; if (status->answer.bit_fields.s7) { status->rest_time[ 7 ] -= time_gap; if (status->rest_time[ 7 ] < 0) { status->answer.bit_fields.s7 = 0; if (status->score > 0) --status->score; } }; if (status->answer.bit_fields.s8) { status->rest_time[ 8 ] -= time_gap; if (status->rest_time[ 8 ] < 0) { status->answer.bit_fields.s8 = 0; if (status->score > 0) --status->score; } }; if (status->answer.bit_fields.s9) { status->rest_time[ 9 ] -= time_gap; if (status->rest_time[ 9 ] < 0) { status->answer.bit_fields.s9 = 0; if (status->score > 0) --status->score; } }; long long delay_base = 300LL * 1000LL * 1000LL; long long micro_delay = (rand () % 10 + 1) * delay_base; double delay_coef = 5 / ((status->score + 10) / 20.0); if (cur_nano_time - prev_creation_time > delay_coef * delay_base) { int no = 1 + rand () % SWITCH_BUTTON_NUM; status->rest_time[no] = micro_delay; status->answer.val |= (1 << (no-1)); prev_creation_time = cur_nano_time; } output_message_fnd_send (status->output_pipe_fd, status->score); struct dot_matrix_data dot_data = { { { 0, }, } }; int16_t bit_mask = 1; const int x_jump = 2, x_size = 3; const int y_jump = 3, y_size = 4; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (status->answer.val & bit_mask) { int base_y = i * y_jump; int base_x = j * x_jump; for (int y = base_y; y < base_y + y_size; ++y) for (int x = base_x; x < base_x + x_size; ++x) dot_data.data[y][x] = 1; } bit_mask <<= 1; } } output_message_dot_matrix_send (status->output_pipe_fd, &dot_data); pthread_mutex_unlock (&status->mutex); usleep ((10*1000)); } return 0; }
0
#include <pthread.h> static struct netlink_listener *nl; static int local_socket; static pthread_mutex_t init_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t start_lock = PTHREAD_MUTEX_INITIALIZER; static uint32_t init_count; static uint32_t start_count; static int start(void) { int error = 0; pthread_mutex_lock(&start_lock); if (start_count++ == 0) { error = nl->start(); if (error) { LOGE("Failed to start netlink_listener: %s\\n", strerror(errno)); goto error; } } pthread_mutex_unlock(&start_lock); return 0; error: start_count = 0; pthread_mutex_unlock(&start_lock); return -1; } static int stop(void) { int error = 0; pthread_mutex_lock(&start_lock); if (--start_count == 0) { error = nl->stop(); if (error) { LOGE("Failed to stop netlink_listener: %s\\n", strerror(errno)); goto error; } close(local_socket); local_socket = -1; nl = 0; } pthread_mutex_unlock(&start_lock); return 0; error: start_count = 1; pthread_mutex_unlock(&start_lock); return -1; } static int is_start(void) { pthread_mutex_lock(&start_lock); int started = nl->is_start(); pthread_mutex_unlock(&start_lock); return started; } static int init(void) { struct sockaddr_nl nladdr; int size = 64 * 1024; pthread_mutex_lock(&init_lock); if (init_count++ == 0) { memset(&nladdr, 0, sizeof(nladdr)); nladdr.nl_family = AF_NETLINK; nladdr.nl_pid = (pthread_self() << 16) | getpid(); nladdr.nl_groups = 0xffffffff; local_socket = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT); if (local_socket < 0) { LOGE("Unable to create uevent local_socket: %s\\n", strerror(errno)); goto error; } if (setsockopt(local_socket, SOL_SOCKET, SO_RCVBUFFORCE, &size, sizeof(size)) < 0) { LOGE("Unable to set uevent local_socket options: %s\\n", strerror(errno)); goto error; } if (bind(local_socket, (struct sockaddr *)&nladdr, sizeof(nladdr)) < 0) { LOGE("Unable to bind uevent local_socket: %s\\n", strerror(errno)); goto error; } nl = get_netlink_listener(); if (nl->init(local_socket)) { LOGE("Failed to init netlink listener\\n"); goto error; } } pthread_mutex_unlock(&init_lock); return 0; error: init_count = 0; pthread_mutex_unlock(&init_lock); return -1; } static int deinit(void) { pthread_mutex_lock(&init_lock); if (init_count-- == 0) { if (is_start()) stop(); } pthread_mutex_unlock(&init_lock); return 0; } static void register_handler(struct netlink_handler* handler) { assert_die_if(handler == 0, "Handler is NULL\\n"); nl->register_handler(handler); } static void unregister_handler(struct netlink_handler* handler) { assert_die_if(handler == 0, "Handler is NULL\\n"); nl->unregister_handler(handler); } static struct netlink_manager this = { .init = init, .deinit = deinit, .start = start, .is_start = is_start, .stop = stop, .register_handler = register_handler, .unregister_handler = unregister_handler, }; struct netlink_manager* get_netlink_manager(void) { return &this; }
1
#include <pthread.h> pthread_mutex_t vt_lcd_mutex = PTHREAD_MUTEX_INITIALIZER; void VTinit(void) { VTinitialize_ports(); VTinitLCD(); } void VTinitialize_ports() { XGpio_mSetDataDirection(XPAR_LCD_BASEADDR, 2, 0x0); XGpio_mSetDataDirection(XPAR_LCD_BASEADDR, 1, 0xffffffff); } void VTlcd_write( char c, char mode ) { pthread_mutex_lock( &vt_lcd_mutex ); char chigh = c >> 4; XGpio_mSetDataDirection(XPAR_LCD_BASEADDR, 2, 0); XGpio_mWriteReg(XPAR_LCD_BASEADDR, 0, 0); XGpio_mWriteReg(XPAR_LCD_BASEADDR, 8, chigh); XGpio_mWriteReg(XPAR_LCD_BASEADDR, 0, 8|mode); XGpio_mWriteReg(XPAR_LCD_BASEADDR, 0, mode); sleep( 1 ); if (mode < 16) { XGpio_mWriteReg(XPAR_LCD_BASEADDR, 8, c); XGpio_mWriteReg(XPAR_LCD_BASEADDR, 0, 8|mode); XGpio_mWriteReg(XPAR_LCD_BASEADDR, 0, mode); sleep( 1 ); } pthread_mutex_unlock( &vt_lcd_mutex ); } void VTinitLCD() { sleep(40); VTlcd_write( 0x30, 16 | 0); sleep(20); VTlcd_write( 0x30, 16 | 0); sleep(1); VTlcd_write( 0x30, 16 | 0); sleep(1); VTlcd_write( 0x20, 16 | 0); sleep(1); VTlcd_write( 0x28, 0); VTlcd_write( 0x6, 0); VTlcd_write( 0xc, 0); VTlcd_write( 0x1, 0); sleep(8); } void VTprintLCD( const char *str, int line ) { char eos = 0; int i; VTlcd_write( 0x80 | ((line-1)*40), 0 ); for (i=0; i<16; i++) { if ( (str[i] == 0) || (eos == 1)) { VTlcd_write( ' ', 4); eos = 1; } else { VTlcd_write( str[i], 4); } } }
0
#include <pthread.h> int insideCircleCount = 0; int roundsPerThread = 0; int threadNum = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *MonteCarlo(){ int pointsInCircleFromThread = 0; unsigned int rand_state = rand(); int i; for(i = 0; i < roundsPerThread; i++){ double x = rand_r(&rand_state) / ((double)32767 + 1) * 2.0 - 1.0; double y = rand_r(&rand_state) / ((double)32767 + 1) * 2.0 - 1.0; if( (x*x) + (y*y) < 1){ pointsInCircleFromThread++; } } pthread_mutex_lock(&mutex); threadNum++; printf("%d pointsInsideCircle from thread %d\\n",pointsInCircleFromThread,threadNum); insideCircleCount += pointsInCircleFromThread; pthread_mutex_unlock(&mutex); return 0; } int main(){ printf("Monte Carlo PI Estimation: \\n\\n"); printf("Enter number of threads to use: "); int numOfThreads = 1; scanf("%d",&numOfThreads); if(numOfThreads <= 0){ numOfThreads = 1; } int maxRoundsPerThread = ((32767 - 1)/(4*numOfThreads)); printf("Enter number of rounds to perform per thread: (1-%d) ",maxRoundsPerThread); scanf("%d",&roundsPerThread); if(roundsPerThread <= 0){ roundsPerThread = 1; }else if(roundsPerThread > maxRoundsPerThread){ roundsPerThread = maxRoundsPerThread; } time_t startTime; time_t finishTime; time_t totalTime; startTime = time(0); srand(startTime); pthread_t *threads = malloc(numOfThreads * sizeof(pthread_t)); pthread_attr_t attr; pthread_attr_init(&attr); int i; for (i = 0; i < numOfThreads; i++) { pthread_create(&threads[i], &attr, MonteCarlo, (void *) 0); } for (i = 0; i < numOfThreads; i++) { pthread_join(threads[i], 0); } pthread_mutex_destroy(&mutex); free(threads); double pi = ((double)(4*insideCircleCount))/(roundsPerThread*numOfThreads); finishTime = time(0); printf("%d threads with %d rounds per thread estimated PI to be: %f",numOfThreads,roundsPerThread,pi); totalTime = finishTime - startTime; printf("\\nprogram finished in %ld seconds",totalTime); printf("\\n"); return 0; }
1
#include <pthread.h> int MAX_NUMBER = 65535; int max_m_operations = 200; int thread_count = 8; int initial_length = 10; int seed =18; double member_fraction = 0.80; double insert_fraction = 0.10; double delete_fraction = 0.10; struct node** head_node; pthread_mutex_t list_mutex; int max_member_number=0; int max_insert_number=0; int max_delete_number=0; struct node { int data; struct node *next; }; int Member(int value, struct node* head){ struct node* curr=head; while(curr!=0 && curr->data < value) curr = curr->next; if(curr == 0 || curr->data > value){ return 0; }else{ return 1; } } int Insert(int value, struct node** head){ struct node* curr = *head; struct node* prev = 0; struct node* temp; while(curr!=0 && curr-> data < value){ prev=curr; curr=curr->next; } if(curr==0 || curr->data > value){ temp = malloc(sizeof(struct node)); temp->data = value; temp->next = curr; if(prev==0){ *head=temp; } else{ prev->next=temp; } return 1; }else{ return 0; } } int Delete(int value, struct node** head){ struct node* curr= *head; struct node* prev= 0; while(curr!=0 && curr-> data < value){ prev=curr; curr=curr->next; } if(curr!=0 && curr->data == value){ if(prev == 0){ *head = curr->next; free(curr); }else{ prev->next = curr->next; free(curr); } return 1; }else{ return 0; } } void Populate_list(int seed, struct node** head, int n){ srand(seed); *head = malloc(sizeof(struct node)); (*head)->data = rand() % (MAX_NUMBER + 1); int result = 0; for(int i=0;i<n-1;i++){ result = Insert(rand() % (MAX_NUMBER + 1),head); if(!result){ i=i-1; } } } void* Thread_operation(void* rank){ int thread_max_member_number = max_member_number/thread_count; int thread_max_insert_number = max_insert_number/thread_count; int thread_max_delete_number = max_delete_number/thread_count; int thread_member_number=0; int thread_insert_number=0; int thread_delete_number=0; srand(seed); int operation; int random_number; while(thread_member_number<thread_max_member_number || thread_insert_number<thread_max_insert_number || thread_delete_number<thread_max_delete_number){ random_number = rand() % (MAX_NUMBER+1); operation = random_number % 3; if(operation==0 && thread_member_number < thread_max_member_number){ thread_member_number++; pthread_mutex_lock(&list_mutex); Member(random_number, *head_node); pthread_mutex_unlock(&list_mutex); } else if(operation==1 && thread_insert_number < thread_max_insert_number){ thread_insert_number++; pthread_mutex_lock(&list_mutex); Insert(random_number, head_node); pthread_mutex_unlock(&list_mutex); } else if(operation==2 && thread_delete_number < thread_max_delete_number){ thread_delete_number++; pthread_mutex_lock(&list_mutex); Delete(random_number, head_node); pthread_mutex_unlock(&list_mutex); } } return 0; } int main() { head_node = malloc(sizeof(struct node*)); pthread_mutex_init(&list_mutex, 0); int iterations=0; initial_length=1000; max_m_operations=10000; member_fraction=0.99; insert_fraction=0.005; delete_fraction=0.005; thread_count=4; printf("Enter number of samples: "); scanf("%d",&iterations); printf("Enter n: "); scanf("%d",&initial_length); printf("Enter m: "); scanf("%d",&max_m_operations); printf("Enter member_fraction: "); scanf("%lf",&member_fraction); printf("Enter insert_fraction: "); scanf("%lf",&insert_fraction); printf("Enter delete_fraction: "); scanf("%lf",&delete_fraction); printf("Enter thread count: "); scanf("%d",&thread_count); double timespent[iterations]; for(seed=10; seed<11+iterations; seed++){ Populate_list(seed, head_node, initial_length); max_member_number = (int)max_m_operations*member_fraction; max_insert_number = (int)max_m_operations*insert_fraction; max_delete_number = (int)max_m_operations*delete_fraction; clock_t begin = clock(); pthread_t threads[thread_count]; long thread; for(thread=0;thread<thread_count;thread++){ pthread_create(&threads[thread], 0, Thread_operation, (void*) thread); } for(thread=0; thread<thread_count;thread++){ pthread_join(threads[thread],0); } clock_t end = clock(); double time_spent = (double)(end - begin) / CLOCKS_PER_SEC; timespent[seed-10]=time_spent; printf("Percentage Complete: %.0f %%",((seed-10)*100)/(float)iterations); printf("\\r"); } double sum=0, sum_var=0, average=0, std_deviation=0, variance=0; for (int i = 0; i < iterations; i++) { sum += timespent[i]; } average = sum / (float)iterations; for (int i = 0; i < iterations; i++) { sum_var = sum_var + pow((timespent[i] - average), 2); } variance = sum_var / (float)(iterations-1); std_deviation = sqrt(variance); printf("Average: %f, std_deviation: %f\\n",average,std_deviation); return 0; }
0
#include <pthread.h> struct message_queue { struct message_queue* next; int count; } * tasks; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition = PTHREAD_COND_INITIALIZER; struct message_queue* process_message(void* thread_num) { pthread_mutex_lock(&mutex); while (!tasks) pthread_cond_wait(&condition, &mutex); printf("thread:%ld processing message...\\n", (long)thread_num + 1); struct message_queue* current = tasks; tasks = current->next; pthread_mutex_unlock(&mutex); if (sleep(1) != 0) { perror("sleep error"); } printf("thread:%ld processing message done...\\n", (long)thread_num + 1); return current; } void enqueue_message(struct message_queue* message) { pthread_mutex_lock(&mutex); message->next = tasks; tasks = message; pthread_mutex_unlock(&mutex); pthread_cond_broadcast(&condition); } void* thread_function(void* arg) { while (1) { struct message_queue* done_message = process_message(arg); free(done_message); } return 0; } int main(int argc, char* argv[]) { pthread_t threads[4]; long i; for (i = 0; i < 4; ++i) pthread_create(&threads[i], 0, thread_function, (void*)i); int task_count = 10; while (task_count) { struct message_queue* entry = (struct message_queue*)malloc(sizeof(struct message_queue)); entry->count = 0; int current_task = task_count--; printf("start enqueue message:%d...\\n", current_task); enqueue_message(entry); printf("enqueue message done:%d\\n", current_task); } for (i = 0; i < 4; ++i) pthread_join(threads[i], 0); return 0; }
1
#include <pthread.h>extern int __VERIFIER_nondet_int(void); extern void __VERIFIER_error() ; int element[(20)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int __VERIFIER_nondet_int(); int stored_elements[(20)]; _Bool enqueue_flag, dequeue_flag; QType queue; void init(QType *q) { q->head=0; q->tail=0; q->amount=0; } int empty(QType * q) { if (q->head == q->tail) { printf("queue is empty\\n"); return (-1); } else return 0; } int full(QType * q) { if (q->amount == (20)) { printf("queue is full\\n"); return (-2); } else return 0; } int enqueue(QType *q, int x) { q->element[q->tail] = x; q->amount++; if (q->tail == (20)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (20)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); if (enqueue_flag) { for(i=0; i<(20); i++) { value = __VERIFIER_nondet_int(); enqueue(&queue,value); stored_elements[i]=value; } enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); return 0; } void *t2(void *arg) { int i; pthread_mutex_lock(&m); if (dequeue_flag) { for(i=0; i<(20); i++) { if (empty(&queue)!=(-1)) if (!dequeue(&queue)==stored_elements[i]) { ERROR: __VERIFIER_error(); } } dequeue_flag=(0); enqueue_flag=(1); } pthread_mutex_unlock(&m); return 0; } int main(void) { pthread_t id1, id2; enqueue_flag=(1); dequeue_flag=(0); init(&queue); if (!empty(&queue)==(-1)) { ERROR: __VERIFIER_error(); } pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, &queue); pthread_create(&id2, 0, t2, &queue); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> int n_buckets; int contador = 0; pthread_mutex_t lock; int *values; int tamanho; }bucket; void bubble_sort(int *v, int tam){ int i,j,temp,trocou; for(j=0; j<tam-1; j++){ trocou = 0; for(i = 0; i < tam -1; i++){ if(v[i+1] < v[i]){ temp = v[i]; v[i] = v[i + 1]; v[i + 1] = temp; trocou = 1; } } if(!trocou) break; } } int incrementar_contador() { pthread_mutex_lock(&lock); contador++; pthread_mutex_unlock(&lock); return contador - 1; } void* thread(void *param) { bucket *p = (bucket *) param; while (1) { int c = incrementar_contador(); if (c >= n_buckets) break; bubble_sort(p[c].values, p[c].tamanho); printf("Thread %d processando balde %d\\n ", (int)pthread_self() , c); } pthread_exit(0); } int main(int argc, char **argv) { int tamanho = atoi(argv[1]); int n_threads = atoi(argv[2]); n_buckets = atoi(argv[3]); int i; int *vetor = (int *) malloc(sizeof(int)*tamanho); srand((unsigned)time(0)); for (i = 0; i < tamanho; i++) { vetor[i] = rand() % (tamanho - 1); printf("vetor[%d] = %d \\n", i, vetor[i]); } bucket *balde = (bucket *) malloc(sizeof(bucket) * n_buckets); int minRange = 0; int maxRange = tamanho/n_buckets; int resto = tamanho%n_buckets; int j; int qntElemBalde; for (i = 0; i<n_buckets; i++) { balde[i].values = (int *) malloc(sizeof(int)*tamanho); qntElemBalde = 0; for (j = 0; j<tamanho; j++) { if(vetor[j] >= minRange && vetor[j] <= maxRange) { balde[i].values[qntElemBalde] = vetor[j]; printf("balde[%d] = %d \\n", i, balde[i].values[qntElemBalde]); qntElemBalde++; } } balde[i].tamanho = qntElemBalde; printf("\\nMinRange = %d\\nMaxRange = %d\\nTamanho = %d \\n", minRange, maxRange,qntElemBalde); minRange = maxRange + 1; if (i < resto) { maxRange = minRange + (tamanho/n_buckets); } else{ maxRange = minRange + (tamanho/n_buckets) - 1; } } pthread_t *threads = (pthread_t *) malloc(sizeof(pthread_t) * n_threads); for (i=0; i<n_threads; i++) { pthread_create(&threads[i], 0, thread, (void *) balde); } for(i = 0; i < n_threads; i++) pthread_join(threads[i], 0); int cont = 0; for (i = 0; i<n_buckets; i++) { for (j = 0; j<balde[i].tamanho; j++) { vetor[cont] = balde[i].values[j]; printf(" %d, ", vetor[cont]); cont++; } } free(threads); free(balde); return 0; }
1
#include <pthread.h> void netfs_release_peropen (struct peropen *po) { pthread_mutex_lock (&po->np->lock); if (--po->refcnt) pthread_mutex_unlock (&po->np->lock); else { if (po->root_parent) mach_port_deallocate (mach_task_self (), po->root_parent); if (po->shadow_root && po->shadow_root != po->np) { pthread_mutex_lock (&po->shadow_root->lock); netfs_nput (po->shadow_root); } if (po->shadow_root_parent) mach_port_deallocate (mach_task_self (), po->shadow_root_parent); if (po->lock_status != LOCK_UN) fshelp_acquire_lock (&po->np->userlock, &po->lock_status, &po->np->lock, LOCK_UN); netfs_nput (po->np); free (po->path); free (po); } }
0
#include <pthread.h> int count = 5; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *decrement(void *arg); void *increment(void *arg); int main(int argc, char const *argv[]) { int i1 = 1; int i2 = 1; pthread_t tid1; pthread_t tid2; pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond, 0); pthread_create(&tid1, 0, decrement, 0); pthread_create(&tid2, 0, increment, 0); i2 = pthread_join(tid2, 0); i1 = pthread_join(tid1, 0); if( (i1==0) && (i2==0)) { printf("count = %d, the main thread!\\n", count); pthread_cond_destroy(&cond); pthread_mutex_destroy(&mutex); } return 0; } void *increment(void *arg) { sleep(1); while(1) { pthread_mutex_lock(&mutex); count += 1; if(count > 0) { printf("count = %d, change cond state!\\n", count); pthread_cond_signal(&cond); } pthread_mutex_unlock(&mutex); if(count == 10) { printf("count = 10, thread 2 is over!\\n"); return 0; } } } void *decrement(void *arg) { while(1) { pthread_mutex_lock(&mutex); while(count <= 0) { printf("count <= 0,thread1 is hanging\\n"); pthread_cond_wait(&cond, &mutex); sleep(1); printf("sleep!\\n"); } count -= 1; pthread_mutex_unlock(&mutex); if(count == 9) { printf("count = 9, thread 1 is over\\n"); return 0; } } }
1
#include <pthread.h> int mediafirefs_removexattr(const char *path, const char *list) { printf("FUNCTION: removexattr. path: %s\\n", path); (void)path; (void)list; struct mediafirefs_context_private *ctx; ctx = fuse_get_context()->private_data; pthread_mutex_lock(&(ctx->mutex)); fprintf(stderr, "removexattr not implemented\\n"); pthread_mutex_unlock(&(ctx->mutex)); return -ENOSYS; }
0
#include <pthread.h> void * thread_section(void* i); int check_prime(int i); void kill_threads(); pthread_t threads[5]; pthread_mutex_t lock; int found = 0; int main() { int i, status; if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); exit(1); } srand(time(0)); for (i = 0; i < 5; i++) { status = pthread_create(&threads[i], 0, thread_section, 0); if (status != 0) { perror("error creating threads"); exit(1); } } pthread_exit(0); } void * thread_section(void * args) { int random = 0; while (1) { random = rand() % 100; if (check_prime(random)) { if (found) pause(); found = 1; pthread_mutex_lock(&lock); kill_threads(); printf("%d\\n", random); pthread_mutex_unlock(&lock); break; } } pthread_exit(0); } int check_prime(int i) { int j; if (i <= 1) return 0; for (j = 2; j < i; j++) { if (i % j == 0 && i != j) return 0; } return 1; } void kill_threads() { int i; for (i = 0; i < 5; i++) { if (!pthread_equal(pthread_self(), threads[i])) { pthread_cancel(threads[i]); } } }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t vez = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t lotou = PTHREAD_COND_INITIALIZER; int contador = 0; int contador_servidores = 0; int contador_estagiarios = 0; void* servidor(void * a){ int i = *((int *) a); while(1){ pthread_mutex_lock(&mutex); contador++; pthread_mutex_unlock(&mutex); if(contador<=4){ pthread_mutex_lock(&mutex); printf("Servidor %d: vou trabalhar em uma baia!\\n", i); pthread_mutex_unlock(&mutex); sleep(5); pthread_mutex_lock(&mutex); printf("Servidor %d: vou deixar a baia.\\n", i); contador--; pthread_cond_signal(&lotou); if(contador_servidores > 0) { contador_servidores--; } pthread_mutex_unlock(&mutex); sleep(5); }else{ pthread_mutex_lock(&mutex); printf("Lotado\\n"); printf("Servidor %d: vou esperar >:|\\n", i); contador_servidores++; contador--; pthread_cond_wait(&lotou, &mutex); pthread_mutex_unlock(&mutex); } } } int main(){ pthread_t s[10]; pthread_t e[2]; int i; int *id; for (i = 0; i < 10 ; i++) { id = (int *) malloc(sizeof(int)); *id = i; pthread_create(&s[i], 0, servidor, (void *) (id)); } for (i = 0; i < 10 ; i++) { pthread_join(s[i],0); } return 0; }
0
#include <pthread.h> pthread_mutex_t chopstick[6] ; void *eat_think(void *arg) { char phi = *(char *)arg; int left,right; switch (phi){ case 'A': left = 5; right = 1; break; case 'B': left = 1; right = 2; break; case 'C': left = 2; right = 3; break; case 'D': left = 3; right = 4; break; case 'E': left = 4; right = 5; break; } int i; for(;;){ usleep(3000); pthread_mutex_lock(&chopstick[left]); printf("Philosopher %c fetches chopstick %d\\n", phi, left); if (pthread_mutex_trylock(&chopstick[right]) == EBUSY){ pthread_mutex_unlock(&chopstick[left]); continue; } printf("Philosopher %c fetches chopstick %d\\n", phi, right); printf("Philosopher %c is eating.\\n",phi); usleep(3000); pthread_mutex_unlock(&chopstick[left]); printf("Philosopher %c release chopstick %d\\n", phi, left); pthread_mutex_unlock(&chopstick[right]); printf("Philosopher %c release chopstick %d\\n", phi, right); } } int main(){ pthread_t A,B,C,D,E; int i; for (i = 0; i < 5; i++) pthread_mutex_init(&chopstick[i],0); pthread_create(&A,0, eat_think, "A"); pthread_create(&B,0, eat_think, "B"); pthread_create(&C,0, eat_think, "C"); pthread_create(&D,0, eat_think, "D"); pthread_create(&E,0, eat_think, "E"); pthread_join(A,0); pthread_join(B,0); pthread_join(C,0); pthread_join(D,0); pthread_join(E,0); return 0; }
1
#include <pthread.h> uint32_t Timer_timeouts[NB_SOFT_TIMERS]; uint8_t Timer_wraps[NB_SOFT_TIMERS]; uint32_t Timer_prev; pthread_mutex_t Timer_mut; uint32_t Timer_millis() { struct timespec current; int res; uint32_t millis; res = clock_gettime(CLOCK_REALTIME, &current); if (res != 0) { perror("[ERROR]: Could not get current time : "); return 0; } else { millis = current.tv_sec * 1000; millis += current.tv_nsec / 1000000; return millis; } } void Timer_setup(struct Timer_Instance *_instance) { pthread_mutex_init(&Timer_mut, 0); uint8_t i; for (i = 0; i < NB_SOFT_TIMERS; i++) { Timer_timeouts[i] = 0; Timer_wraps[i] = 0; } Timer_prev = Timer_millis(); } void Timer_enqueue_timeout(uint8_t id, uint16_t listener_id) { } void Timer_loop(struct Timer_Instance *_instance) { while (1) { pthread_mutex_lock(&Timer_mut); uint32_t current = Timer_millis(); uint8_t i; for (i = 0; i < NB_SOFT_TIMERS; i++) { if (Timer_timeouts[i] > 0) { if (current >= Timer_prev) { if (current > Timer_timeouts[i] && Timer_wraps[i] == 0) { Timer_enqueue_timeout(i, _instance->listener_id); Timer_timeouts[i] = 0; Timer_wraps[i] = 0; } } else { if (Timer_wraps[i] == 0) { Timer_enqueue_timeout(i, _instance->listener_id); Timer_timeouts[i] = 0; } else { Timer_wraps[i] = 0; if (current > Timer_timeouts[i]) { Timer_enqueue_timeout(i, _instance->listener_id); Timer_timeouts[i] = 0; } } } } } Timer_prev = current; pthread_mutex_unlock(&Timer_mut); usleep(1000); } } void Timer_timer_start(uint8_t id, uint32_t delay) { if (id < NB_SOFT_TIMERS) { uint32_t current = Timer_millis(); uint32_t timeout = current + delay; if (timeout == 0) timeout = 1; pthread_mutex_lock(&Timer_mut); Timer_timeouts[id] = timeout; Timer_wraps[id] = (timeout > current) ? 0 : 1; pthread_mutex_unlock(&Timer_mut); } } void Timer_timer_cancel(uint8_t id) { if (id < NB_SOFT_TIMERS) { pthread_mutex_lock(&Timer_mut); Timer_timeouts[id] = 0; Timer_wraps[id] = 0; pthread_mutex_unlock(&Timer_mut); } }
0
#include <pthread.h> { int k,i; }param; int graph[100][100]; int n; pthread_mutex_t mutex; void *iterate (void *t) { pthread_mutex_lock(&mutex); struct param *parameters=t; int k=parameters->k; int i=parameters->i; int j=0; for(j=0;j<n;j++) { if(graph[i][k]+graph[k][j]<graph[i][j]) { graph[i][j]=graph[i][k]+graph[k][j]; } } pthread_mutex_unlock(&mutex); pthread_exit(0); } void floyd() { int i,j,k; pthread_t threads[n]; pthread_attr_t attr; pthread_mutex_init(&mutex,0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); for(k=0;k<n;k++) { for(i=0;i<n;i++) { param *parameters=malloc(sizeof(param)); parameters->i=i; parameters->k=k; pthread_create(&threads[i],&attr,iterate,(void *)parameters); } for(i=0;i<n;i++) { pthread_join(threads[i],0); } } pthread_attr_destroy(&attr); pthread_mutex_destroy(&mutex); } int main() { int m, i, j, k, w; printf("enter n and m\\n"); scanf("%d %d",&n,&m); printf("Enter m edges in <v1> <v2> <weight> format\\n"); for(k=0;k<m;k++) { scanf("%d %d %d",&i,&j,&w); graph[i-1][j-1]=graph[j-1][i-1]=w; } for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(graph[i][j]==0) graph[i][j]=graph[j][i]=1000000000; if(i==j) graph[i][j]=0; } } floyd(); for(i=0;i<n;i++) { for(j=0;j<n;j++) printf("%d\\t",graph[i][j]); printf("\\n"); } }
1
#include <pthread.h> void msg_mutex_init(pthread_mutex_t *mutex) { pthread_mutexattr_t mutexattr; pthread_mutexattr_init(&mutexattr); pthread_mutexattr_setpshared(&mutexattr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(mutex, &mutexattr); } void msg_cond_init(pthread_cond_t *cond) { pthread_condattr_t condattr; pthread_condattr_init(&condattr); pthread_condattr_setpshared(&condattr, PTHREAD_PROCESS_SHARED); pthread_cond_init(cond, &condattr); } void msg_mutex_lock(pthread_mutex_t *mutex) { pthread_mutex_lock(mutex); } void msg_mutex_unlock(pthread_mutex_t *mutex) { pthread_mutex_unlock(mutex); } void msg_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex) { pthread_cond_wait(cond, mutex); } void msg_cond_signal(pthread_cond_t *cond) { pthread_cond_signal(cond); } int msg_cond_timedwait( pthread_cond_t *cond, pthread_mutex_t *mutex, struct timespec *ts) { return pthread_cond_timedwait(cond, mutex, ts); } void msg_pthread_create(void *(*start_routine)(void *), void *arg) { pthread_attr_t attr; pthread_t pthread; pthread_attr_init(&attr); pthread_create(&pthread, &attr, start_routine, arg); pthread_attr_destroy(&attr); }
0