text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
int64_t target_nanos;
timer_t timerid;
static int current_buffer;
static int writer_current_buffer;
static int bufpos[2];
static char buffers[2][(1024*1024)];
static
int64_t read_nanos(int type)
{
struct timespec ts;
int rv = clock_gettime(type, &ts);
if (rv < 0) {
perror("clock_gettime");
abort();
}
return (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec;
}
static
int int_min(int a, int b)
{
return a > b ? b : a;
}
static
void handle_timer_tick(void)
{
int64_t nanos = read_nanos(CLOCK_MONOTONIC);
int current = current_buffer;
int pos = bufpos[current];
if (pos > (1024*1024) - 1024) {
fprintf(stderr, "%lld exceeded bufsize!\\n", (long long)nanos);
return;
}
long long diff = (long long)(nanos - target_nanos);
int srv = snprintf(buffers[current] + pos, (1024*1024) - pos,
"%.9f %lld\\n",
read_nanos(CLOCK_REALTIME) * (double)1E-9, diff);
bufpos[current] = int_min(pos + srv, (1024*1024));
target_nanos += 1000000000LL;
}
static pthread_mutex_t current_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t have_data_cond = PTHREAD_COND_INITIALIZER;
void *rt_thread(void *dummy)
{
struct sched_param sp;
sigset_t ss;
int rv;
sigemptyset(&ss);
sigaddset(&ss, SIGRTMIN);
while (1) {
int signo;
sigwait(&ss, &signo);
assert(signo == SIGRTMIN);
pthread_mutex_lock(¤t_buffer_lock);
handle_timer_tick();
pthread_cond_signal(&have_data_cond);
pthread_mutex_unlock(¤t_buffer_lock);
}
}
int main()
{
struct sigevent sev;
struct itimerspec its;
struct sigaction sa;
pthread_t threadid;
struct sched_param sp;
sigset_t ss;
int rv;
sp.sched_priority = sched_get_priority_max(SCHED_FIFO);
rv = sched_setscheduler(getpid(), SCHED_FIFO, &sp);
if (rv < 0) {
perror("sched_setscheduler");
exit(1);
}
setvbuf(stdout, 0, _IONBF, 0);
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = SIG_DFL;
sigaction(SIGHUP, &sa, 0);
sigaction(SIGINT, &sa, 0);
sigaction(SIGQUIT, &sa, 0);
memset(&sp, 0, sizeof(sp));
rv = mlockall(MCL_CURRENT | MCL_FUTURE);
if (rv < 0) {
perror("mlockall");
exit(1);
}
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = SIGRTMIN;
sev.sigev_value.sival_ptr = &timerid;
if (timer_create(CLOCK_MONOTONIC, &sev, &timerid) == -1) {
perror("timer_create");
exit(1);
}
sigemptyset(&ss);
sigaddset(&ss, SIGRTMIN);
sigprocmask(SIG_BLOCK, &ss, 0);
rv = pthread_create(&threadid, 0, rt_thread, 0);
if (rv) {
errno = rv;
perror("pthread_create");
exit(1);
}
rv = clock_gettime(CLOCK_MONOTONIC, &its.it_value);
if (rv < 0) {
perror("clock_gettime");
abort();
}
its.it_value.tv_sec += 2;
its.it_value.tv_nsec = 0;
its.it_interval.tv_sec = 1;
its.it_interval.tv_nsec = 0;
target_nanos = 1000000000LL * its.it_value.tv_sec + its.it_value.tv_nsec;
rv = timer_settime(timerid, TIMER_ABSTIME, &its, 0);
if (rv < 0) {
perror("timer_settime");
exit(1);
}
pthread_mutex_lock(¤t_buffer_lock);
while (1) {
int current = current_buffer;
int pos;
if (!bufpos[current]) {
pthread_cond_wait(&have_data_cond, ¤t_buffer_lock);
continue;
}
current_buffer = current ^ 1;
pos = bufpos[current];
pthread_mutex_unlock(¤t_buffer_lock);
fwrite(buffers[current], 1, pos, stdout);
bufpos[current] = 0;
pthread_mutex_lock(¤t_buffer_lock);
}
}
| 1
|
#include <pthread.h>
int NUM_LOOPS = 32;
int NUM_THREADS = 2;
struct timespec start_time;
struct timespec end_time;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t mainCV = PTHREAD_COND_INITIALIZER;
pthread_cond_t workerCV = PTHREAD_COND_INITIALIZER;
int counter=0;
volatile struct fifo
{
volatile unsigned int array[(1000)];
volatile unsigned int head_index;
volatile unsigned int tail_index;
volatile int is_full;
volatile int is_empty;
volatile int turn;
};
volatile void* consumer(fifo_t* fifo_array)
{
assert(fifo_array);
int count = 0;
int i;
int j;
unsigned int sig = 0;
while(1)
{
pthread_mutex_lock(&lock);
pthread_cond_wait(&mainCV,&lock);
pthread_mutex_unlock(&lock);
for(i = 0; i < NUM_THREADS; i++)
{
fifo_t* fifo = fifo_array + i;
for(j = 0; j < (1000); j++)
{
assert(fifo->is_empty == 0);
assert(fifo->tail_index < (1000));
sig ^= fifo->array[fifo->tail_index];
sig += (sig >> 16);
fifo->tail_index = (fifo->tail_index+1) % (1000);
fifo->is_full = 0;
fifo->is_empty = (fifo->head_index == fifo->tail_index) ? 1 : 0;
}
}
pthread_mutex_lock(&lock);
counter=0;
pthread_cond_broadcast(&workerCV);
pthread_mutex_unlock(&lock);
count++;
if(count == NUM_LOOPS)
break;
}
printf("sig=%x\\n",sig);
return 0;
}
volatile void* producer(fifo_t* fifo)
{
assert(fifo);
int i;
int count = 0;
int seed = 0x12345678;
while(1)
{
for(i = 0; i < (1000); i++)
{
seed ^= seed + (seed >> 13) + (count - 543) + count + i;
assert(fifo->is_full == 0);
assert(fifo->head_index < (1000));
fifo->array[fifo->head_index] = seed;
fifo->head_index = (fifo->head_index+1) % (1000);
fifo->is_full = fifo->head_index == fifo->tail_index ? 1 : 0;
fifo->is_empty = 0;
}
pthread_mutex_lock(&lock);
counter++;
if(counter==NUM_THREADS){
pthread_cond_signal(&mainCV);
}
pthread_cond_wait(&workerCV, &lock);
pthread_mutex_unlock(&lock);
count++;
if(count == NUM_LOOPS)
break;
}
return;
}
int main (int argc, char *argv[])
{
int i;
int j;
unsigned int seed = 0x1234567;
assert(argc == 3);
NUM_THREADS = atoi(argv[1]);
NUM_LOOPS = atoi(argv[2]);
printf("NUM_THREADS:%d, NUM_LOOPS:%d\\n", NUM_THREADS, NUM_LOOPS);
pthread_t* thread_array = 0;
thread_array = malloc(sizeof(thread_array[0])*NUM_THREADS);
fifo_t* fifo_array = 0;
fifo_array = malloc(sizeof(fifo_array[0])*NUM_THREADS);
for(i = 0; i < NUM_THREADS; i++)
{
fifo_t* fifo = fifo_array + i;
for(j = 0; j < (1000); j++)
{
seed = seed ^ (seed > 15) + i;
fifo->array[j] = seed;
}
fifo->head_index = 0;
fifo->tail_index = 0;
fifo->is_full = 0;
fifo->is_empty = 1;
}
pthread_attr_t attr;
int rc;
void *status;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
clock_gettime(CLOCK_REALTIME, &start_time);
for(i = 0; i < NUM_THREADS; i++)
rc = pthread_create(&(thread_array[i]), &attr, (void *)producer, (void *)(fifo_array + i));
consumer(fifo_array);
for(i = 0; i < NUM_THREADS; i++)
pthread_join(&(thread_array[i]), &status);
clock_gettime(CLOCK_REALTIME, &end_time);
pthread_attr_destroy(&attr);
printf("Main: program completed. Exiting.\\n");
printf("s_time.tv_sec:%lld, s_time.tv_nsec:%09lld\\n", (long long int)start_time.tv_sec, (long long int)start_time.tv_nsec);
printf("e_time.tv_sec:%lld, e_time.tv_nsec:%09lld\\n", (long long int)end_time.tv_sec, (long long int)end_time.tv_nsec);
if(end_time.tv_nsec > start_time.tv_nsec)
{
printf("diff_time:%lld.%09lld\\n",
(long long int)end_time.tv_sec - (long long int)start_time.tv_sec,
(long long int)end_time.tv_nsec - (long long int)start_time.tv_nsec);
}
else
{
printf("diff_time:%lld.%09lld\\n",
(long long int)end_time.tv_sec - (long long int)start_time.tv_sec - 1,
(long long int)end_time.tv_nsec - (long long int)start_time.tv_nsec + 1000*1000*1000);
}
return 0;
}
| 0
|
#include <pthread.h>
int
pthread_once(pthread_once_t *once_control, void (*init_routine)(void))
{
pthread_mutex_lock(&once_control->mutex);
if (once_control->state == PTHREAD_NEEDS_INIT) {
init_routine();
once_control->state = PTHREAD_DONE_INIT;
}
pthread_mutex_unlock(&once_control->mutex);
return (0);
}
| 1
|
#include <pthread.h>
static void *treader(void *_);
static void *twriter(void *_);
int main(void);
static pthread_mutex_t mutex;
static pthread_cond_t cond;
static int counter = 0;
static int quit = 0;
void *
treader(void *_)
{
sleep(6);
while (!quit) {
pthread_mutex_lock(&mutex);
while (counter == 0 && !quit) {
printf("[%2u] treader%u: no messages in queue, waiting\\n", counter, _);
pthread_cond_wait(&cond, &mutex);
}
if (!quit) {
printf("[%2u] treader%u: getting message from queue\\n", counter--, _);
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
return 0;
}
void *
twriter(void *_)
{
for (int i = 0; i < 8; i++) {
pthread_mutex_lock(&mutex);
printf("\\033[32m[%2u] twriter%u: sending %u\\033[0m\\n", counter, _, i);
counter++;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
sleep(2);
}
pthread_mutex_lock(&mutex);
printf("[ ] twriter%u: end\\n", _);
quit = 1;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
return 0;
}
int
main()
{
pthread_t thread1, thread2, thread3;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
pthread_mutex_lock(&mutex);
pthread_create(&thread1, 0, treader, (void*)1);
pthread_create(&thread2, 0, treader, (void*)2);
pthread_create(&thread3, 0, twriter, (void*)1);
pthread_mutex_unlock(&mutex);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
pthread_join(thread3, 0);
return 0;
}
| 0
|
#include <pthread.h>
static sigset_t set;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static int quitflag = 0;
static void *thread_func(void *arg)
{
int ret = 0;
int signo = 0;
for (;;)
{
ret = sigwait(&set, &signo);
if (ret < 0)
{
fprintf(stderr, "sigwait failure\\n");
pthread_exit(0);
}
switch (signo)
{
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
printf("thread_quit\\n");
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
break;
}
}
}
int main(int argc, char *argv[])
{
sigset_t oset;
pthread_t thid;
pthread_create(&thid, 0, thread_func, 0);
pthread_mutex_lock(&lock);
while (quitflag == 0)
{
pthread_cond_wait(&cond, &lock);
}
pthread_mutex_unlock(&lock);
quitflag = 0;
if (sigprocmask(SIG_SETMASK, &oset, 0) < 0)
{
fprintf(stderr, "SIG_SETMASK sigprocmask failure\\n");
return 1;
}
return 0;
}
| 1
|
#include <pthread.h>
const int MAX_KEY = 65536;
const int MAX_THREADS = 1024;
struct node {
int data;
struct node* next;
};
struct node* head = 0;
int n = 1000;
int m = 10000;
float mMember = 0.50;
float mInsert = 0.25;
float mDelete = 0.25;
int thread_count = 1;
double start_time, finish_time, time_elapsed;
int member_count=0;
int insert_count=0;
int delete_count=0;
pthread_rwlock_t rwlock;
pthread_mutex_t count_mutex;
int Member(int value);
int Insert(int value);
int Delete(int value);
void Clear_Memory(void);
int Is_Empty(void);
void* Thread_Function(void* rank);
int main(int argc, char* argv[]) {
if (argc != 2){
fprintf(stderr, "please provide a command line argument for thread count less than %d\\n", MAX_THREADS);
exit(0);
}
thread_count = strtol(argv[1], 0, 10);
if (thread_count <= 0 || thread_count > MAX_THREADS){
fprintf(stderr, "please provide a command line argument for thread count less than %d\\n", MAX_THREADS);
exit(0);
}
int i=0;
for(;i<n;i++){
int r = rand()%65536;
if(!Insert(r)){
i--;
}
}
pthread_t* thread_handles;
thread_handles = malloc(thread_count*sizeof(pthread_t));
pthread_mutex_init(&count_mutex, 0);
pthread_rwlock_init(&rwlock, 0);
start_time = clock();
for (i = 0; i < thread_count; i++)
pthread_create(&thread_handles[i], 0, Thread_Function, (void*) i);
for (i = 0; i < thread_count; i++)
pthread_join(thread_handles[i], 0);
finish_time = clock();
time_elapsed = (finish_time - start_time)/CLOCKS_PER_SEC;
printf("%.10f\\n", time_elapsed);
Clear_Memory();
pthread_rwlock_destroy(&rwlock);
pthread_mutex_destroy(&count_mutex);
free(thread_handles);
return 0;
}
int Member(int value) {
struct node* temp;
temp = head;
while (temp != 0 && temp->data < value)
temp = temp->next;
if (temp == 0 || temp->data > value) {
return 0;
} else {
return 1;
}
}
int Insert(int value) {
struct node* current = head;
struct node* pred = 0;
struct node* temp;
int return_value = 1;
while (current != 0 && current->data < value) {
pred = current;
current = current->next;
}
if (current == 0 || current->data > value) {
temp = malloc(sizeof(struct node));
temp->data = value;
temp->next = current;
if (pred == 0)
head = temp;
else
pred->next = temp;
} else {
return_value = 0;
}
return return_value;
}
int Delete(int value) {
struct node* current = head;
struct node* pred = 0;
int return_value = 1;
while (current != 0 && current->data < value) {
pred = current;
current = current->next;
}
if (current != 0 && current->data == value) {
if (pred == 0) {
head = current->next;
free(current);
} else {
pred->next = current->next;
free(current);
}
} else {
return_value = 0;
}
return return_value;
}
void Clear_Memory(void) {
struct node* currentent;
struct node* next;
if (Is_Empty()) return;
currentent = head;
next = currentent->next;
while (next != 0) {
free(currentent);
currentent = next;
next = currentent->next;
}
free(currentent);
}
int Is_Empty(void) {
if (head == 0)
return 1;
else
return 0;
}
void* Thread_Function(void* rank) {
int i, val;
int my_member=0;
int my_insert=0;
int my_delete=0;
int ops_per_thread = m/thread_count;
for (i = 0; i < ops_per_thread; i++) {
float operation_choice = (rand()%10000/10000.0);
val = rand()%MAX_KEY;
if (operation_choice < mMember) {
pthread_rwlock_rdlock(&rwlock);
Member(val);
pthread_rwlock_unlock(&rwlock);
my_member++;
} else if (operation_choice < mMember + mInsert) {
pthread_rwlock_wrlock(&rwlock);
Insert(val);
pthread_rwlock_unlock(&rwlock);
my_insert++;
} else {
pthread_rwlock_wrlock(&rwlock);
Delete(val);
pthread_rwlock_unlock(&rwlock);
my_delete++;
}
}
pthread_mutex_lock(&count_mutex);
member_count += my_member;
insert_count += my_insert;
delete_count += my_delete;
pthread_mutex_unlock(&count_mutex);
return 0;
}
| 0
|
#include <pthread.h>
static FILE *logfp = 0;
static enum log_level llev = -1;
static pid_t pid;
static pthread_mutex_t logfmutex;
void error_helper_init(const char *logfpath, enum log_level lev)
{
if (logfp) {
fprintf(stderr, "Log file already initialized");
return;
}
if (! (logfp = fopen(logfpath, "a"))) {
perror("Opening log file");
fprintf(stderr, "Setting log file pointer to stderr\\n");
logfp = stderr;
} else {
fprintf(stderr, "Log file initialized successfully and can be found at '%s'\\n", logfpath);
}
pid = getpid();
pthread_mutex_init(&logfmutex, 0);
llev = lev;
}
void error_helper_destroy(void)
{
llev = -1;
if (logfp && logfp != stderr) {
fflush(logfp);
fclose(logfp);
}
pthread_mutex_destroy(&logfmutex);
}
enum log_level get_log_level(void)
{
return llev;
}
static int do_add_log(const char *msg, enum log_level lev)
{
if (lev < get_log_level()) {
return 0;
}
int llen = 0;
int nwrote = 0;
pthread_mutex_lock(&logfmutex);
llen = strlen(msg);
nwrote = fprintf(logfp, "{%d-%lu} %s", pid, pthread_self(), msg);
fflush(logfp);
pthread_mutex_unlock(&logfmutex);
if (nwrote < llen) {
return -1;
}
return 0;
}
static int is_logfp_valid(void)
{ return (logfp != 0); }
void do_log_mute(const char *msg, enum log_level lev)
{
if (! is_logfp_valid()) {
logfp = stderr;
fprintf(stderr, "Error helper module not initalized properly\\n");
}
if (do_add_log(msg, lev)) {
fprintf(stderr, "Problem in logging message: %s", msg);
}
}
| 1
|
#include <pthread.h>
int thread_count;
int barrier_thread_count = 0;
pthread_mutex_t barrier_mutex;
pthread_cond_t ok_to_proceed;
void Usage(char* prog_name);
void *Thread_work(void* rank);
int main(int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
if (argc != 2)
Usage(argv[0]);
thread_count = strtol(argv[1], 0, 10);
thread_handles = malloc (thread_count*sizeof(pthread_t));
pthread_mutex_init(&barrier_mutex, 0);
pthread_cond_init(&ok_to_proceed, 0);
for (thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread], 0,Thread_work, (void*) thread);
for (thread = 0; thread < thread_count; thread++)
pthread_join(thread_handles[thread], 0);
printf("Elapsed time = %e seconds\\n", finish - start);
pthread_mutex_destroy(&barrier_mutex);
pthread_cond_destroy(&ok_to_proceed);
free(thread_handles);
return 0;
}
void Usage(char* prog_name) {
fprintf(stderr, "usage: %s <number of threads>\\n", prog_name);
exit(0);
}
void *Thread_work(void* rank) {
int i;
for (i = 0; i < 100; i++) {
pthread_mutex_lock(&barrier_mutex);
barrier_thread_count++;
if (barrier_thread_count == thread_count) {
barrier_thread_count = 0;
pthread_cond_broadcast(&ok_to_proceed);
} else {
while (pthread_cond_wait(&ok_to_proceed,
&barrier_mutex) != 0);
}
pthread_mutex_unlock(&barrier_mutex);
}
return 0;
}
| 0
|
#include <pthread.h>
int TimeSig[4][6] = {{7, 1, 0, 0, 0, 0},
{7, 1, 1, 0, 0, 0},
{7, 1, 3, 1, 0, 0},
{7, 1, 1, 3, 1, 1}};
pthread_t pthread;
int fd;
volatile void *gpio_addr;
volatile unsigned int *gpio_datain;
volatile unsigned int *gpio_setdataout_addr;
volatile unsigned int *gpio_cleardataout_addr;
void *turn_LED (void *);
int init_LED ()
{
int thread_id;
fd = open("/dev/mem", O_RDWR);
printf("Mapping %X - %X (size: %X)\\n", GPIO1_BASE,
GPIO1_BASE + GPIO_SIZE, GPIO_SIZE);
gpio_addr = mmap(0, GPIO_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd,
GPIO1_BASE);
gpio_datain = gpio_addr + GPIO_DATAIN;
gpio_setdataout_addr = gpio_addr + GPIO_SETDATAOUT;
gpio_cleardataout_addr = gpio_addr + GPIO_CLEARDATAOUT;
if(gpio_addr == MAP_FAILED) {
printf("Unable to map GPIO\\n");
exit(1);
}
printf("GPIO mapped to %p\\n", gpio_addr);
printf("GPIO SETDATAOUTADDR mapped to %p\\n", gpio_setdataout_addr);
printf("GPIO CLEARDATAOUT mapped to %p\\n", gpio_cleardataout_addr);
pthread_mutex_init (&mutex_lock, 0);
thread_id = pthread_create (&pthread, 0, turn_LED, 0);
if (thread_id < 0)
{
printf ("Can't make thread\\n");
munmap((void *)gpio_addr, GPIO_SIZE);
close(fd);
return -1;
}
else
{
printf ("This is a thread!\\n");
return 0;
}
}
void *turn_LED (void *data)
{
int time;
int beat[4] = {2, 3, 4, 6};
while (keepgoing)
{
pthread_mutex_lock (&mutex_lock);
if (run == True)
{
time = 60000000 / (tempo * 2);
*gpio_setdataout_addr = TimeSig[status][location]<<USER_LED;
printf ("%d", TimeSig[status][location]);
fflush (stdout);
usleep (time);
*gpio_cleardataout_addr = TimeSig[status][location]<<USER_LED;
usleep (time);
if (++location >= beat[status])
location = 0;
}
else usleep (100000);
pthread_mutex_unlock (&mutex_lock);
}
pthread_exit (0);
}
void exit_LED ()
{
keepgoing = 0;
pthread_mutex_destroy (&mutex_lock);
pthread_join (pthread, 0);
munmap((void *)gpio_addr, GPIO_SIZE);
close(fd);
}
| 1
|
#include <pthread.h>
int writers; int locked; int reading;
pthread_mutex_t lock; pthread_cond_t scoreboard_request = PTHREAD_COND_INITIALIZER;
void initialse_scoreboard_locks(){
if (pthread_mutex_init(&lock, 0) !=0){
printf("\\nFailed to initialse mutex lock, closing server\\n");
exit(0);
}
}
void destroy_scoreboard_locks(){
pthread_mutex_destroy(&lock);
}
void start_writing(){
pthread_mutex_lock(&lock);
writers++;
while(reading + locked != 0){
pthread_cond_wait(&scoreboard_request, &lock);
}
locked++;
pthread_mutex_unlock(&lock);
}
void finished_writing(){
pthread_mutex_lock(&lock);
writers--;
locked--;
pthread_cond_signal(&scoreboard_request);
pthread_mutex_unlock(&lock);
}
void start_reading(){
pthread_mutex_lock(&lock);
while (writers != 0){
pthread_cond_wait(&scoreboard_request, &lock);
}
reading++;
pthread_mutex_unlock(&lock);
}
void finished_reading(){
pthread_mutex_lock(&lock);
reading--;
pthread_cond_signal(&scoreboard_request);
pthread_mutex_unlock(&lock);
}
| 0
|
#include <pthread.h>
enum fb_state {
FB_SLEEP,
FB_AWAKE,
NUM_FB_STATES
};
static enum fb_state fb_state = FB_AWAKE;
static const char *fb_file_names[] = {
[FB_SLEEP] = "/sys/power/wait_for_fb_sleep",
[FB_AWAKE] = "/sys/power/wait_for_fb_wake"
};
static pthread_t fb_monitor_thread;
static pthread_mutex_t fb_state_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t fb_state_cond = PTHREAD_COND_INITIALIZER;
static int wait_for_fb = 0;
static const char state_path[] = "/sys/power/state";
static const char wakelock_path[] = "/sys/power/wake_lock";
static const char wakeunlock_path[] = "/sys/power/wake_unlock";
static const char autosleep_path[] = "/sys/power/autosleep";
static const char mem_str[] = "mem";
static const char on_str[] = "on";
static int wait_for_file(const char *fname)
{
int fd, ret;
char buf;
fd = open(fname, O_RDONLY);
if (fd == -1)
return -errno;
do {
ret = read(fd, &buf, 1);
} while (ret == -1 && errno == EINTR);
close(fd);
return ret == -1 ? -errno : 0;
}
static void *fb_monitor_thread_func( void *unused)
{
enum fb_state next_state;
int ret;
while (1) {
next_state = fb_state == FB_SLEEP ? FB_AWAKE : FB_SLEEP;
ret = wait_for_file(fb_file_names[next_state]);
if (ret)
continue;
pthread_mutex_lock(&fb_state_mutex);
fb_state = next_state;
pthread_cond_signal(&fb_state_cond);
pthread_mutex_unlock(&fb_state_mutex);
}
wait_for_fb = 0;
return 0;
}
static int start_fb_monitor_thread(void)
{
if (access(fb_file_names[FB_SLEEP], F_OK))
return 0;
if (access(fb_file_names[FB_AWAKE], F_OK))
return 0;
return !pthread_create(&fb_monitor_thread, 0,
fb_monitor_thread_func, 0);
}
static int earlysuspend_enter(void)
{
int ret;
int len = ARRAY_SIZE(mem_str) - 1;
ret = sysfs_write(state_path, mem_str, len);
if (ret == len && wait_for_fb) {
pthread_mutex_lock(&fb_state_mutex);
while (fb_state != FB_SLEEP)
pthread_cond_wait(&fb_state_cond, &fb_state_mutex);
pthread_mutex_unlock(&fb_state_mutex);
}
return ret < 0 ? ret : 0;
}
static int earlysuspend_exit(void)
{
int ret;
int len = ARRAY_SIZE(on_str) - 1;
ret = sysfs_write(state_path, on_str, len);
if (ret == len && wait_for_fb) {
pthread_mutex_lock(&fb_state_mutex);
while (fb_state != FB_AWAKE)
pthread_cond_wait(&fb_state_cond, &fb_state_mutex);
pthread_mutex_unlock(&fb_state_mutex);
}
return ret < 0 ? ret : 0;
}
static int earlysuspend_acquire_wake_lock(const char *name)
{
int ret = sysfs_write(wakelock_path, name, strlen(name));
return ret < 0 ? ret : 0;
}
static int earlysuspend_release_wake_lock(const char *name)
{
int ret = sysfs_write(wakeunlock_path, name, strlen(name));
return ret < 0 ? ret : 0;
}
static const struct suspend_handler earlysuspend_handler = {
.enter = earlysuspend_enter,
.exit = earlysuspend_exit,
.acquire_wake_lock = earlysuspend_acquire_wake_lock,
.release_wake_lock = earlysuspend_release_wake_lock,
};
const struct suspend_handler *earlysuspend_detect(void)
{
if (!sysfs_file_exists(autosleep_path) &&
sysfs_file_exists(wakelock_path) &&
sysfs_file_exists(state_path)) {
wait_for_fb = start_fb_monitor_thread();
return &earlysuspend_handler;
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t produce_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t consume_mutex = PTHREAD_MUTEX_INITIALIZER;
int b;
unsigned char stack[4001];
int out_max,in_max;
void *consumer();
void *producer();
void cpu_eat(int count){
unsigned long loop;
int k;
loop=1;
for (k=0; k<count; k++){
loop = loop+3;
}
}
void main(int argc, char *argv[] )
{
int rc, i;
pthread_t t[2];
if (argc != 3) {
printf("./sem <out_loop> <in_loop> \\n");
return 1;
}
out_max = atoi(argv[1]);
in_max = atoi(argv[2]);
if (in_max ==0){
in_max = 200000;
}
clone((void *) &consumer, &stack[4000], 9000, 0, 0);
producer();
}
void add_buffer(int i){
cpu_eat(in_max);
b = i;
}
int get_buffer(){
cpu_eat(in_max);
return b ;
}
int exit_done=0;
void *producer()
{
int i = 0;
printf("I'm a producer\\n");
while (1) {
pthread_mutex_lock(&produce_mutex);
add_buffer(i);
pthread_mutex_unlock(&consume_mutex);
i = i + 1;
if (exit_done > 0){
break;
}
}
printf(" Producer completed : %d \\n",i);
fflush(stdout);
while(1){
if (exit_done==1){
exit_done=2;
return;
}
}
}
void *consumer()
{
int i,v;
int max_loop=out_max;
printf("I'm a consumer\\n");
for (i=0;i<max_loop;i++) {
pthread_mutex_lock(&consume_mutex);
v = get_buffer();
pthread_mutex_unlock(&produce_mutex);
}
pthread_mutex_unlock(&produce_mutex);
printf(" Consumer completed : %d \\n",max_loop);
fflush(stdout);
exit_done=1;
while(1){
if (exit_done==2){
return;
}
pthread_mutex_unlock(&produce_mutex);
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int buffer[10];
int pos_consumer = 0;
int pos = 0;
sem_t s;
sem_t t;
pthread_mutex_t lock_posc;
void * producer (void * a)
{
int temp;
while(1)
{
sem_wait(&s);
pthread_mutex_lock(&lock_posc);
buffer[pos]=rand();
temp = buffer[pos];
pos++;
pos=pos%9;
pthread_mutex_unlock(&lock_posc);
sem_post(&t);
printf("producer: %d\\n", temp);
}
}
void * consumer (void * a)
{
int b;
while(1)
{
sem_wait(&t);
pthread_mutex_lock(&lock_posc);
b=buffer[pos_consumer];
sleep(2);
pos_consumer++;
pos_consumer=pos_consumer%9;
pthread_mutex_unlock(&lock_posc);
sem_post(&s);
printf("consumer: %d\\n", b);
}
}
int main()
{
sem_init(&s,0,10);
sem_init(&t,0,0);
pthread_t threads1;
pthread_t threads2;
pthread_t threads3;
pthread_t threads4;
pthread_create(&threads1, 0, consumer, 0);
pthread_create(&threads2, 0, producer, 0);
pthread_create(&threads3, 0, consumer, 0);
pthread_create(&threads4, 0, producer, 0);
pthread_join(threads1,0);
pthread_join(threads2,0);
pthread_join(threads3,0);
pthread_join(threads4,0);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int arr_len;
} args_struct;
double g_PI = 0.0;
static pthread_mutex_t mutex;
void* monte_carlo(void* v_as) {
args_struct* as = v_as;
int arr_len = (*as).arr_len;
for (int i = 0; i < arr_len; i++) {
double random_x = rand()/(double)32767;
double random_y = rand()/(double)32767;
pthread_mutex_lock(&mutex);
g_PI += random_x*random_x + random_y*random_y <= 1;
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main(int argc, char* argv[])
{
int i;
void* v_args;
args_struct* args = malloc(sizeof(args_struct));
double pi = 0;
int num_threads = 5;
pthread_t thread[num_threads];
srand(time(0));
pthread_mutex_init(&mutex, 0);
if (argc != 2) {
printf("ERROR: Needs exactly 1 argument.\\n");
exit(1);
}
int len = atoi(argv[1]);
(*args).arr_len = len;
v_args = (void*)(args);
for (i = 0; i < num_threads; i++) {
if (pthread_create(&thread[i], 0, &monte_carlo, v_args) != 0) {
printf("ERROR: Monte Carlo thread created incorrectly.\\n");
exit(0);
}
}
for (i = 0; i < num_threads; i++)
pthread_join(thread[i], 0);
pi = g_PI*4.0/(len * num_threads);
printf("Pi is: %f\\n", pi);
free(args);
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t mutexScanf;
void* print_prime_factors(void* fd)
{
int combien_de_nombres_lus ;
uint64_t premier;
uint64_t nombre = 0;
FILE* fichier = (FILE*) fd;
while(1)
{
pthread_mutex_lock(&mutexScanf);
combien_de_nombres_lus = fscanf(fichier, "%lu", &nombre);
pthread_mutex_unlock(&mutexScanf);
if( combien_de_nombres_lus != 1)
{
break;
}
printf("%lu :", nombre);
premier=2;
while(premier <= sqrt(nombre))
{
if(nombre%premier == 0)
{
printf(" %lu", premier);
nombre /= premier;
}
else
{
premier++;
}
}
printf(" %lu", nombre);
printf("\\n");
}
return 0;
}
int main(int argc, char* argv[])
{
FILE* fichier = 0;
pthread_t tid1, tid2;
char* filename;
if(argc > 1)
{
filename=argv[1];
}
else
{
filename="nombresGeneres.txt";
}
fichier = fopen(filename, "r+");
if(fichier != 0)
{
pthread_create(&tid1, 0, print_prime_factors, fichier);
pthread_create(&tid2, 0, print_prime_factors, fichier);
pthread_join(tid2, 0);
pthread_join(tid1, 0);
}
else
{
printf("Impossible d'ouvrir le fichier nombresPremiers.txt");
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t *fork_lft, *fork_rgt;
const char *name;
pthread_t thread;
int fail;
} Philosopher;
int running = 1;
void *PhilPhunction(void *p) {
Philosopher *phil = (Philosopher*)p;
int failed;
int tries_left;
pthread_mutex_t *fork_lft, *fork_rgt, *fork_tmp;
while (running) {
printf("%s is sleeping --er thinking\\n", phil->name);
sleep( 1+ rand()%8);
fork_lft = phil->fork_lft;
fork_rgt = phil->fork_rgt;
printf("%s is hungry\\n", phil->name);
tries_left = 2;
do {
failed = pthread_mutex_lock( fork_lft);
failed = (tries_left>0)? pthread_mutex_trylock( fork_rgt )
: pthread_mutex_lock(fork_rgt);
if (failed) {
pthread_mutex_unlock( fork_lft);
fork_tmp = fork_lft;
fork_lft = fork_rgt;
fork_rgt = fork_tmp;
tries_left -= 1;
}
} while(failed && running);
if (!failed) {
printf("%s is eating\\n", phil->name);
sleep( 1+ rand() % 8);
pthread_mutex_unlock( fork_rgt);
pthread_mutex_unlock( fork_lft);
}
}
return 0;
}
void Ponder()
{
const char *nameList[] = { "Kant", "Guatma", "Russel", "Aristotle", "Bart" };
pthread_mutex_t forks[5];
Philosopher philosophers[5];
Philosopher *phil;
int i;
int failed;
for (i=0;i<5; i++) {
failed = pthread_mutex_init(&forks[i], 0);
if (failed) {
printf("Failed to initialize mutexes.");
exit(1);
}
}
for (i=0;i<5; i++) {
phil = &philosophers[i];
phil->name = nameList[i];
phil->fork_lft = &forks[i];
phil->fork_rgt = &forks[(i+1)%5];
phil->fail = pthread_create( &phil->thread, 0, PhilPhunction, phil);
}
sleep(40);
running = 0;
printf("cleanup time\\n");
for(i=0; i<5; i++) {
phil = &philosophers[i];
if ( !phil->fail && pthread_join( phil->thread, 0) ) {
printf("error joining thread for %s", phil->name);
exit(1);
}
}
}
int main()
{
Ponder();
return 0;
}
| 0
|
#include <pthread.h>
int r_count = 0, share = 0;
pthread_mutex_t mu_access;
pthread_mutex_t mu_r_count;
void * reader (void * input)
{
pthread_detach(pthread_self());
pthread_mutex_lock(&mu_r_count);
if(r_count==0)
pthread_mutex_lock(&mu_access);
++r_count;
pthread_mutex_unlock(&mu_r_count);
printf("i'm a reader! now share is:%d\\n", share);
pthread_mutex_lock(&mu_r_count);
--r_count;
if(r_count==0)
pthread_mutex_unlock(&mu_access);
pthread_mutex_unlock(&mu_r_count);
return 0;
}
void * writer (void * input)
{
pthread_mutex_lock(&mu_access);
++share;
pthread_mutex_unlock(&mu_access);
return 0;
}
int main(int argc, char const *argv[])
{
srand(time(0));
pthread_mutex_init(&mu_access,0);
pthread_mutex_init(&mu_r_count,0);
int temp[20], re = 0, wr = 0;
for (int i = 0; i < 30; ++i)
{
temp[i] = rand();
if(temp[i]%2 == 0)
re++;
else
wr++;
}
printf("There are %d readers and %d writers been sent!\\n",re, wr );
pthread_t temp_thread;
for(int i = 0; i < 30; ++i)
{
if(temp[i]%2 == 0)
pthread_create(&temp_thread, 0, reader, 0);
else
pthread_create(&temp_thread, 0, writer, 0);
}
pthread_mutex_destroy(&mu_access,0);
pthread_mutex_destroy(&mu_r_count,0);
while(1);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
void printer(char *str)
{
pthread_mutex_lock(&mutex);
while(*str!='\\0')
{
putchar(*str);
fflush(stdout);
str++;
sleep(1);
}
printf("\\n");
pthread_mutex_unlock(&mutex);
}
void printer2(char *str)
{
while(*str!='\\0')
{
putchar(*str);
fflush(stdout);
str++;
sleep(1);
}
printf("\\n");
}
void *thread_fun_1(void *arg)
{
char *str = "hello";
printer(str);
}
void *thread_fun_2(void *arg)
{
char *str = "world";
printer(str);
}
int main(void)
{
pthread_t tid1, tid2;
pthread_mutex_init(&mutex, 0);
pthread_create(&tid1, 0, thread_fun_1, 0);
pthread_create(&tid2, 0, thread_fun_2, 0);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
int count = 0;
int thread_ids[3] = {0,1,2};
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *inc_count(void *t)
{
int i;
long my_id = (long)t;
for (i=0; i<10; i++) {
pthread_mutex_lock(&count_mutex);
count++;
if (count == 12) {
pthread_cond_signal(&count_threshold_cv);
printf("inc_count(): thread %ld, count = %d Threshold reached.\\n",
my_id, count);
}
printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n",
my_id, count);
pthread_mutex_unlock(&count_mutex);
sleep(1);
}
pthread_exit(0);
}
void *watch_count(void *t)
{
long my_id = (long)t;
printf("Starting watch_count(): thread %ld\\n", my_id);
pthread_mutex_lock(&count_mutex);
while (count<12) {
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %ld Condition signal received.\\n", my_id);
count += 125;
printf("watch_count(): thread %ld count now = %d.\\n", my_id, count);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main (int argc, char *argv[])
{
int i, rc;
long t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, watch_count, (void *)t1);
pthread_create(&threads[1], &attr, inc_count, (void *)t2);
pthread_create(&threads[2], &attr, inc_count, (void *)t3);
for (i=0; i<3; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited on %d threads. Done.\\n", 3);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
{ int sum;
pthread_mutex_t lock;
}ct_sum;
void * add1(void * cnt)
{
pthread_mutex_lock(&(((ct_sum*)cnt)->lock));
int i;
for( i=0;i<50;i++){
(*(ct_sum*)cnt).sum+=i;}
pthread_mutex_unlock(&(((ct_sum*)cnt)->lock));
pthread_exit(0);
return 0;
}
void * add2(void *cnt)
{
int i;
cnt= (ct_sum*)cnt;
pthread_mutex_lock(&(((ct_sum*)cnt)->lock));
for( i=50;i<101;i++)
{ (*(ct_sum*)cnt).sum+=i;
}
pthread_mutex_unlock(&(((ct_sum*)cnt)->lock));
pthread_exit(0);
return 0;
}
int main(void)
{ int i;
pthread_t ptid1,ptid2;
int sum=0;
ct_sum cnt;
pthread_mutex_init(&(cnt.lock),0);
cnt.sum=0;
pthread_create(&ptid1,0,add1,&cnt);
pthread_create(&ptid2,0,add2,&cnt);
pthread_mutex_lock(&(cnt.lock));
printf("sum %d\\n",cnt.sum);
pthread_mutex_unlock(&(cnt.lock));
pthread_join(ptid1,0);
pthread_join(ptid2,0);
pthread_mutex_destroy(&(cnt.lock));
printf("sum %d\\n",cnt.sum);
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static void*
thread_func( void* arg )
{
pthread_t self = pthread_self();
struct timespec ts;
clockid_t clock;
int e;
pthread_mutex_lock( &lock );
e = pthread_getcpuclockid( self, &clock );
if (e != 0) {
fprintf(stderr, "pthread_getcpuclockid(%08lx,) returned error %d: %s\\n", self, e, strerror(e));
pthread_mutex_unlock( &lock );
return 0;
}
ts.tv_sec = 0;
ts.tv_nsec = 300000000 + ((int)arg)*50000000;
nanosleep( &ts, &ts );
clock_gettime( clock, &ts );
fprintf(stderr, "thread %08lx: clock_gettime() returned %g nsecs\\n", self, ts.tv_sec*1e9 + ts.tv_nsec);
pthread_mutex_unlock( &lock );
return 0;
}
int main( void )
{
int nn;
pthread_attr_t attr;
pthread_t threads[16];
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (nn = 0; nn < 16; nn++) {
pthread_create( &threads[nn], &attr, thread_func, (void*)nn );
}
for (nn = 0; nn < 16; nn++) {
void* dummy;
pthread_join( threads[nn], &dummy );
}
return 0;
}
| 1
|
#include <pthread.h>
extern int dmeventd_debug;
static pthread_mutex_t _register_mutex = PTHREAD_MUTEX_INITIALIZER;
static int _register_count = 0;
static struct dm_pool *_mem_pool = 0;
static void *_lvm_handle = 0;
static pthread_mutex_t _event_mutex = PTHREAD_MUTEX_INITIALIZER;
static void _temporary_log_fn(int level,
const char *file ,
int line ,
int dm_errno ,
const char *message)
{
level &= ~(_LOG_STDERR | _LOG_ONCE);
switch (level) {
case _LOG_DEBUG:
if (dmeventd_debug >= 3)
syslog(LOG_DEBUG, "%s", message);
break;
case _LOG_INFO:
if (dmeventd_debug >= 2)
syslog(LOG_INFO, "%s", message);
break;
case _LOG_NOTICE:
if (dmeventd_debug >= 1)
syslog(LOG_NOTICE, "%s", message);
break;
case _LOG_WARN:
syslog(LOG_WARNING, "%s", message);
break;
case _LOG_ERR:
syslog(LOG_ERR, "%s", message);
break;
default:
syslog(LOG_CRIT, "%s", message);
}
}
void dmeventd_lvm2_lock(void)
{
if (pthread_mutex_trylock(&_event_mutex)) {
syslog(LOG_NOTICE, "Another thread is handling an event. Waiting...");
pthread_mutex_lock(&_event_mutex);
}
}
void dmeventd_lvm2_unlock(void)
{
pthread_mutex_unlock(&_event_mutex);
}
int dmeventd_lvm2_init(void)
{
int r = 0;
pthread_mutex_lock(&_register_mutex);
if (!_mem_pool && !(_mem_pool = dm_pool_create("mirror_dso", 1024)))
goto out;
if (!_lvm_handle) {
lvm2_log_fn(_temporary_log_fn);
if (!(_lvm_handle = lvm2_init())) {
dm_pool_destroy(_mem_pool);
_mem_pool = 0;
goto out;
}
lvm2_run(_lvm_handle, "_memlock_inc");
}
_register_count++;
r = 1;
out:
pthread_mutex_unlock(&_register_mutex);
return r;
}
void dmeventd_lvm2_exit(void)
{
pthread_mutex_lock(&_register_mutex);
if (!--_register_count) {
lvm2_run(_lvm_handle, "_memlock_dec");
dm_pool_destroy(_mem_pool);
_mem_pool = 0;
lvm2_exit(_lvm_handle);
_lvm_handle = 0;
}
pthread_mutex_unlock(&_register_mutex);
}
struct dm_pool *dmeventd_lvm2_pool(void)
{
return _mem_pool;
}
int dmeventd_lvm2_run(const char *cmdline)
{
return lvm2_run(_lvm_handle, cmdline);
}
| 0
|
#include <pthread.h>
struct threadParameter{
int* nbThreadTotal;
int* nbThreadWaitingForSync;
int doneCreating;
pthread_cond_t doneCreatingCond;
pthread_cond_t controlePoint;
pthread_mutex_t mut;
pthread_mutex_t mutCreation;
};
void initThreadParameter(struct threadParameter* p){
p->nbThreadTotal=malloc(sizeof(int*));
*(p->nbThreadTotal)=0;
p->nbThreadWaitingForSync=malloc(sizeof(int*));
*(p->nbThreadWaitingForSync)=0;
p->doneCreating=0;
pthread_cond_init(&(p->doneCreatingCond),0);
pthread_cond_init(&(p->controlePoint),0);
pthread_mutex_init(&(p->mut),0);
pthread_mutex_init(&(p->mutCreation),0);
}
void destroyThreadParameter(struct threadParameter* p){
free(p->nbThreadTotal);
free(p->nbThreadWaitingForSync);
}
void waitpoint(struct threadParameter* c){
pthread_mutex_lock(&(c->mut));
*(c->nbThreadWaitingForSync)+=1;
if(*(c->nbThreadWaitingForSync)!=*(c->nbThreadTotal)){
pthread_cond_wait(&(c->controlePoint),&(c->mut));
}
else{
*(c->nbThreadWaitingForSync)=0;
pthread_cond_broadcast(&(c->controlePoint));
};
pthread_mutex_unlock(&(c->mut));
}
void* f(void*p){
struct threadParameter* c=(struct threadParameter*)p;
sleep(1);
printf("done on my first work\\n");
pthread_mutex_lock(&(c->mutCreation));
while(!c->doneCreating){
pthread_cond_wait(&(c->doneCreatingCond),&(c->mutCreation));
}
pthread_cond_broadcast(&(c->doneCreatingCond));
pthread_mutex_unlock(&(c->mutCreation));
printf("going back to work\\n");
sleep(1);
waitpoint(c);
sleep(1);
printf("I'm done working on task 1\\n");
waitpoint(c);
sleep(1);
printf("I'm done working on task 2\\n");
waitpoint(c);
sleep(1);
printf("I'm done working on task 3, gonna go sleep\\n");
sleep(1);
pthread_exit(0);
}
int main(){
struct threadParameter* p=malloc(sizeof(struct threadParameter));
initThreadParameter(p);
pthread_t idT[10];
for(size_t i=0;i<10;++i){
pthread_mutex_lock(&(p->mut));
if(pthread_create(&idT[i],0,f,(void*)p)){
fprintf(stderr,"failed creating a thread\\n");
return 1;
}
*(p->nbThreadTotal)+=1;
pthread_mutex_unlock(&(p->mut));
}
p->doneCreating=1;
pthread_cond_broadcast(&(p->doneCreatingCond));
for(size_t i=0;i<10;++i){
pthread_join(idT[i],0);
}
destroyThreadParameter(p);
free(p);
return 0;
}
| 1
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER;
void *thr_fn(void *arg)
{
int err, signo;
for(;;)
{
err = sigwait(&mask,&signo);
if(err != 0)
err_exit(err,"sigwait failed");
switch(signo)
{
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&waitloc);
return(0);
default:
printf("unexpected signal %d\\n",signo);
exit(1);
}
}
}
int main(void)
{
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask,SIGQUIT);
sigaddset(&mask,SIGINT);
if((err = pthread_sigmask(SIG_BLOCK,&mask,&oldmask)) != 0)
err_exit(err,"SIG_BLOCK error");
err = pthread_create(&tid,0,thr_fn,0);
if(err != 0)
err_exit(err,"can't create thread");
pthread_mutex_lock(&lock);
while(quitflag == 0)
pthread_cond_wait(&waitloc,&lock);
pthread_mutex_unlock(&lock);
quitflag= 0;
if(sigprocmask(SIG_SETMASK,&oldmask,0) < 0)
err_sys("SIG_SETMASK error");
exit(0);
}
| 0
|
#include <pthread.h>
int nitems;
pthread_mutex_t mutex= PTHREAD_MUTEX_INITIALIZER;
int buff[1000000];
int nput=0;
int nval=0;
void *produce(void *), *consume(void *);
int
main(int argc, char **argv)
{
int i, nthreads, count[100];
pthread_t tid_produce[100], tid_consume;
nitems = 100000;
nthreads = 3;
for (i = 0; i < nthreads; i++) {
count[i] = 0;
pthread_create(&tid_produce[i], 0, produce, &count[i]);
}
for (i = 0; i < nthreads; i++) {
pthread_join(tid_produce[i], 0);
printf("count[%d] = %d\\n", i, count[i]);
}
pthread_create(&tid_consume, 0, consume, 0);
pthread_join(tid_consume, 0);
exit(0);
}
void *
produce(void *arg)
{
for ( ; ; ) {
pthread_mutex_lock(&mutex);
if (nput >= nitems) {
pthread_mutex_unlock(&mutex);
return(0);
}
buff[nput] = nval;
nput++;
nval++;
pthread_mutex_unlock(&mutex);
*((int *) arg) += 1;
}
}
void *
consume(void *arg)
{
int i;
for (i = 0; i < nitems; i++) {
if (buff[i] != i)
printf("buff[%d] = %d\\n", i, buff[i]);
}
return(0);
}
| 1
|
#include <pthread.h>
buffer_item START_NUMBER;
buffer_item buffer[8];
int MIN_SLEEP_TIME = 1;
int MAX_SLEEP_TIME = 5;
pthread_mutex_t mutex;
sem_t empty, full;
int sleepTime, producerThreads, consumerThreads, insertPointer, removePointer, totalCount;
void getDataFromCommandLine(int argc, char *const *argv);
void initSyncTools();
void createThreads();
void *producer(void *param);
int insert_item(buffer_item item);
void *consumer(void *param);
int remove_item(buffer_item *item);
int randomIntOverRange(int min, int max);
int main(int argc, char *argv[]) {
getDataFromCommandLine(argc, argv);
initSyncTools();
createThreads();
sleep(sleepTime);
return 0;
}
void getDataFromCommandLine(int argCount, char *const *argValues) {
if (argCount != 5) {
fprintf(stderr, "Usage: <sleep time> <producer threads> <consumer threads> <start number>\\n");
exit(1);
}
sleepTime = atoi(argValues[1]);
producerThreads = atoi(argValues[2]);
consumerThreads = atoi(argValues[3]);
START_NUMBER = atoi(argValues[4]);
}
void initSyncTools() {
pthread_mutex_init(&mutex, 0);
sem_init(&empty, 0, 8);
sem_init(&full, 0, 0);
totalCount = 0;
removePointer = 0;
insertPointer = 0;
}
void createThreads() {
pthread_t producers[producerThreads];
pthread_t consumers[consumerThreads];
pthread_attr_t attr;
pthread_attr_init(&attr);
int i, j;
for (i = 0; i < producerThreads; i++) {
pthread_create(&producers[i], &attr, producer, 0);
}
for (j = 0; j < consumerThreads; j++) {
pthread_create(&consumers[j], &attr, consumer, 0);
}
}
int insert_item(buffer_item item) {
int result = 0;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
if (totalCount != 8) {
buffer[insertPointer] = item;
insertPointer = (insertPointer + 1) % 8;
totalCount++;
} else {
result = -1;
}
pthread_mutex_unlock(&mutex);
sem_post(&full);
return result;
}
int remove_item(buffer_item *item) {
int result = 0;
sem_wait(&full);
pthread_mutex_lock(&mutex);
if (totalCount != 0) {
*item = buffer[removePointer];
removePointer = (removePointer + 1) % 8;
totalCount--;
} else {
result = -1;
}
pthread_mutex_unlock(&mutex);
sem_post(&empty);
return result;
}
void *producer(void *param) {
buffer_item item;
while (1) {
sleep(randomIntOverRange(MIN_SLEEP_TIME, MAX_SLEEP_TIME));
item = START_NUMBER;
START_NUMBER++;
if (insert_item(item)) {
printf("Error occured: producer\\n");
} else {
printf("Producer %u produced %d\\n", (unsigned int) pthread_self(), item);
}
}
}
void *consumer(void *param) {
buffer_item item;
while (1) {
sleep(randomIntOverRange(MIN_SLEEP_TIME, MAX_SLEEP_TIME));
if (remove_item(&item)) {
printf("Error occured: consumer\\n");
} else {
printf("Consumer %u consumed %d\\n", (unsigned int) pthread_self(), item);
}
}
}
int randomIntOverRange(int min, int max)
{
return min + rand() % (max + 1 - min);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t conditionalVariable;
int threadCounter = 0;
void* threadFunction( void* rank );
int main( void )
{
pthread_mutex_init( &mutex, ( pthread_mutexattr_t* ) 0 );
pthread_cond_init( &conditionalVariable, ( pthread_condattr_t* ) 0 );
pthread_t* threadHandles = ( pthread_t* )malloc( 8 * sizeof( pthread_t ) );
for( long threadIndex = 0; threadIndex < 8; threadIndex++ )
{
pthread_create( ( threadHandles + threadIndex ), 0, threadFunction, ( void* )threadIndex );
}
for( long threadIndex = 0; threadIndex < 8; threadIndex++ )
{
pthread_join( *( threadHandles + threadIndex ), 0 );
}
pthread_mutex_destroy( &mutex );
pthread_cond_destroy( &conditionalVariable );
}
void* threadFunction( void* rank )
{
long threadRank = ( long ) rank;
pthread_mutex_lock( &mutex );
threadCounter = threadCounter + 1;
printf( "thread %ld used the mutex-->threadCounter:%d\\n", threadRank, threadCounter );
if( threadCounter == 8 )
{
threadCounter = 0;
printf( "thread %ld notifies other threads...\\n\\n", threadRank );
pthread_cond_broadcast( &conditionalVariable );
}
else
{
printf(" thread %ld was suspended...\\n", threadRank );
while( pthread_cond_wait( &conditionalVariable, &mutex ) != 0 );
}
pthread_mutex_unlock( &mutex );
printf("thread %ld pass through the first barrier...\\n\\n",threadRank );
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *forfood(void* arg);
int main(void)
{
const int ppl_n = 1000;
pthread_t ppl[ppl_n];
int i;
int count = 0;
for(i=0; i<ppl_n; i++) {
Pthread_create(&ppl[i], 0, forfood, &count);
}
for(i=0; i<ppl_n; i++) {
Pthread_join(ppl[i], 0);
}
printf("The final count is %d\\n", count);
pthread_exit(0);
return 0;
}
void *forfood(void* arg) {
int i;
int* count = (int*)arg;
pthread_mutex_lock(&mutex);
for(i=0; i<1000; i++) {
(*count)++;
}
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int a[(10 * 1000 * 1000 + 3)];
int b[(10 * 1000 * 1000 + 3)];
int sum;
pthread_mutex_t mutex[1];
static int
array_sequencial_prod(int *a, int *b, unsigned ini, unsigned end)
{
int sum = 0;
unsigned i;
for (i = ini; i < end; i++) {
sum += a[i] * b[i];
}
return sum;
}
static void *
thread_func(void *data)
{
unsigned id = *((unsigned *) data);
unsigned ini = id * ((10 * 1000 * 1000 + 3) / 83);
unsigned end = ini + ((10 * 1000 * 1000 + 3) / 83);
int sum_partial = 0;
sum_partial = array_sequencial_prod(a, b, ini, end);
pthread_mutex_lock(mutex);
sum += sum_partial;
pthread_mutex_unlock(mutex);
printf("thread id: %i, ini: %i, end: %i, sum: %i\\n", id, ini, end,
sum_partial);
return 0;
}
static void
array_init(int *array, unsigned size)
{
unsigned i;
for (i = 0; i < size; i++) {
array[i] = rand() % 10;
}
}
static int
array_parallel_prod(int *a, int *b)
{
unsigned i;
unsigned id[83];
pthread_t t[83];
pthread_mutex_init(mutex, 0);
for (i = 0; i < 83; i++) {
id[i] = i;
pthread_create(&t[i], 0, thread_func, (void *) &id[i]);
}
for (i = 0; i < 83; i++) {
pthread_join(t[i], 0);
}
pthread_mutex_destroy(mutex);
if (0 < ((10 * 1000 * 1000 + 3) % 83)) {
for (i = 83 * ((10 * 1000 * 1000 + 3) / 83); i < (10 * 1000 * 1000 + 3); i++) {
sum += a[i] * b[i];
}
}
return sum;
}
int
main(void)
{
srand(time(0));
array_init(a, (10 * 1000 * 1000 + 3));
array_init(b, (10 * 1000 * 1000 + 3));
printf("parallel: %i\\n", array_parallel_prod(a, b));
printf("sequencial: %i\\n", array_sequencial_prod(a, b, 0, (10 * 1000 * 1000 + 3)));
return 0;
}
| 1
|
#include <pthread.h>
int
pthread_join(pthread_t tid, void **status)
{
pthread_thread_t *joinee, *joiner;
if ((joinee = tidtothread(tid)) == NULL_THREADPTR)
return EINVAL;
joiner = CURPTHREAD();
assert_preemption_enabled();
disable_preemption();
pthread_lock(&(joinee->lock));
if (joinee->flags & THREAD_DETACHED) {
pthread_unlock(&(joinee->lock));
enable_preemption();
return EINVAL;
}
pthread_unlock(&(joinee->lock));
enable_preemption();
pthread_mutex_lock(&joinee->mutex);
while (!joinee->dead) {
pthread_testcancel();
pthread_cond_wait(&joinee->cond, &joinee->mutex);
}
pthread_testcancel();
disable_preemption();
if (status)
*status = (void *) joinee->exitval;
pthread_mutex_unlock(&joinee->mutex);
pthread_destroy_internal(joinee);
enable_preemption();
return 0;
}
| 0
|
#include <pthread.h>
void *runner(void *param);
double **A, **inv;
double del;
size_t n;
int i;
int j;
} matIndex;
void initMatrix(double ***a, int m, int n);
void getMatrix(double ***a, int m, int n);
pthread_mutex_t lock;
pthread_attr_t attr;
double determinant(double **a, int n);
void inverse();
int main(int argc, char const *argv[]) {
printf("Enter the dimensions of the matrix:\\n");
scanf("%lu", &n);
initMatrix(&A, n, n);
getMatrix(&A, n, n);
printf("Determinant = %lf\\n", determinant(A,n));
inverse();
printf("Matrix inv = inverse(A)\\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%lf ", inv[i][j]);
}
printf("\\n");
}
return 0;
}
double determinant(double **a, int n) {
if (n == 1)
return a[0][0];
if (n == 2)
return a[0][0] * a[1][1] - a[1][0] * a[0][1];
int det = 0, sign=1;
for (int j1 = 0; j1 < n; j1++) {
double **m = calloc((n - 1), sizeof(double *));
for (int i = 0; i < n - 1; i++)
m[i] = calloc((n - 1), sizeof(double));
for (int i = 1; i < n; i++) {
int j2 = 0;
for (int j = 0; j < n; j++) {
if (j == j1)
continue;
m[i - 1][j2] = a[i][j];
j2++;
}
}
det += sign * a[0][j1] * determinant(m, n - 1);
sign = -sign;
for (int i = 0; i < n - 1; i++)
free(m[i]);
free(m);
}
return det;
}
void inverse() {
del = determinant(A,n);
if (del == 0)
exit(0);
initMatrix(&inv, n, n);
pthread_attr_init(&attr);
pthread_mutex_init(&lock, 0);
pthread_t **tidMat = calloc(sizeof(pthread_t *), n);
for (int i = 0; i < n; i++) {
tidMat[i] = calloc(sizeof(pthread_t), n);
}
matIndex curIndex = {.i = 0, .j = 0};
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
pthread_mutex_lock(&lock);
curIndex.i = i; curIndex.j = j;
pthread_create(&tidMat[i][j], &attr, runner, &curIndex);
}
}
}
void *runner(void *param) {
matIndex *index = param;
int indexI = index->i;
int indexJ = index->j;
pthread_mutex_unlock(&lock);
double **B;
initMatrix(&B, n - 1, n - 1);
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-1; j++) {
B[i][j] = A[(i+indexI+1)%n][(j+indexJ+1)%n];
}
}
double det = determinant(B, n-1);
inv[indexJ][indexI] = det / del;
pthread_exit(0);
}
void initMatrix(double ***a, int m, int n) {
*a = calloc(sizeof(int *), m);
for (int i = 0; i < m; i++) {
(*a)[i] = calloc(sizeof(int), n);
}
}
void getMatrix(double ***a, int m, int n) {
printf("Input matrix\\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%lf", &(*a)[i][j]);
}
}
}
| 1
|
#include <pthread.h>
void log_info(const char* fmt, ...)
{
va_list va;
__builtin_va_start((va));
vprintf(fmt, va);
;
}
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer = 0;
void* producer(void* ptr)
{
int i;
for (i=0; i<=1000; ++i)
{
pthread_mutex_lock(&the_mutex);
while (0 != buffer)
{
pthread_cond_wait(&condp, &the_mutex);
}
buffer = i;
log_info("%ld buffer %d\\n", pthread_self(), buffer);
pthread_cond_signal(&condc);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
void* consumer(void* ptr)
{
int i;
for (i=0; i<1000; ++i)
{
pthread_mutex_lock(&the_mutex);
while (0 == buffer)
{
pthread_cond_wait(&condc, &the_mutex);
}
buffer = 0;
log_info("%ld buffer %d\\n", pthread_self(), buffer);
pthread_cond_signal(&condp);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
int main(int argc, char** argv)
{
pthread_t pro, con;
pthread_mutex_init(&the_mutex, 0);
pthread_cond_init(&condc, 0);
pthread_cond_init(&condp, 0);
pthread_create(&pro, 0, producer, 0);
pthread_create(&con, 0, consumer, 0);
pthread_join(pro, 0);
pthread_join(con, 0);
pthread_mutex_destroy(&the_mutex);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
return 0;
}
| 0
|
#include <pthread.h>
int global_value = 0;
pthread_mutex_t global_value_mutex;
void *reader(void *arg);
void *writer(void *arg);
int main(int argc, char **argv)
{
pthread_t tid[20];
int rc;
int i;
srand(47);
pthread_mutex_init(&global_value_mutex, 0);
for (i = 0; i < 20; i++)
{
if (i % 8 == 0)
{
rc = pthread_create(&tid[i], 0, writer, (void *) i);
}
else
{
rc = pthread_create(&tid[i], 0, reader, (void *) i);
}
if (rc != 0)
{
}
}
for (i = 0; i < 20; i++)
{
pthread_join(tid[i], 0);
}
pthread_mutex_destroy(&global_value_mutex);
pthread_exit((void *) 0);
}
void *writer(void *arg)
{
int id = (int) arg;
for (;;)
{
pthread_mutex_lock(&global_value_mutex);
global_value += id;
pthread_mutex_unlock(&global_value_mutex);
sleep(rand() % 5);
}
pthread_exit((void *) 0);
}
void *reader(void *arg)
{
int id = (int) arg;
for (;;)
{
pthread_mutex_lock(&global_value_mutex);
pthread_mutex_unlock(&global_value_mutex);
sleep(rand() % 3);
}
pthread_exit((void *) 0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int flag =0 ;
void * pthread_a(void *arga){
sleep(100000);
fprintf(stderr,"flag a %ld\\n",flag);
pthread_mutex_lock(&mutex);
flag = 1;
fprintf(stderr,"flag a %ld\\n",flag);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
fprintf(stderr , "a finish !\\n");
sleep(1);
pthread_exit(0);
}
void * pthread_b(void *argb){
pthread_mutex_lock(&mutex);
fprintf(stderr,"flag b %ld\\n",flag);
while(flag != 1)
pthread_cond_wait(&cond,&mutex);
flag = 2;
fprintf(stderr,"flag b %ld\\n",flag);
pthread_mutex_unlock(&mutex);
fprintf(stderr , "b finish !\\n!");
pthread_exit(0);
}
int arg[2]={0};
int main(void)
{
pthread_t tid[2];
int ret;
ret = pthread_create(&tid[0], 0,pthread_a, 0);
if (ret != 0 )
fprintf(stderr , "create a error\\n");
ret = pthread_create(&tid[1], 0,pthread_b, 0);
if (ret != 0 )
fprintf(stderr , "create b error\\n");
pthread_join(tid[0],0);
pthread_join(tid[1],0);
sleep(1);
fprintf(stderr , "main exit ! \\n");
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mtx;
static void * xbee_frame_parser(void * data)
{
pthread_mutex_lock(&mtx);
struct xbee_rawframe * tmp = (struct xbee_rawframe *)data;
switch(tmp->header.api) {
case 0x95: {
struct xbee_idframe * frame = malloc(3 + tmp->header.length +1);
memcpy(frame, tmp, 3 + tmp->header.length +1);
pthread_mutex_unlock(&mtx);
free(frame);
}
case 0x90: {
struct xbee_dataframe * frame = malloc(3 + tmp->header.length +1);
memcpy(frame, tmp, 3 + tmp->header.length +1);
pthread_mutex_unlock(&mtx);
free(frame);
}
default:
pthread_mutex_unlock(&mtx);
break;
}
}
void xbee_start_server(void)
{
struct xbee_rawframe * frame = malloc(sizeof(struct xbee_rawframe));
for(;;) {
if (xbee_read(frame) == -1) {
continue;
}
pthread_t th;
if (pthread_create(&th, 0, xbee_frame_parser, frame)) {
printf("Error creating thread\\n");
exit(1);
}
}
free(frame);
}
| 1
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc=PTHREAD_COND_INITIALIZER;
void* thr_fn(void* arg)
{
int err,signo;
while(1)
{
err=sigwait(&mask,&signo);
if(err!=0)
err_exit(err,"sig_wait error");
switch(signo)
{
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag=1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&waitloc);
return;
default:
printf("unexpected signed %d\\n",signo);
exit(1);
}
}
}
int main()
{
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 not create thread");
pthread_mutex_lock(&lock);
while(quitflag==0)
pthread_cond_wait(&waitloc,&lock);
pthread_mutex_unlock(&lock);
quitflag=0;
if(sigprocmask(SIG_SETMASK,&oldmask,0)<0)
err_sys("SIG_SETMASK error");
exit(0);
}
| 0
|
#include <pthread.h>
int somme_val=0;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
void *thread_rand(void *arg) {
int *pt=(int*)arg;
int random_val;
random_val=(int) (10*((double)rand())/32767);
printf("Argument recu : %d, thread_id : %d\\n", *pt, (int)pthread_self());
printf("random_val : %d\\n", random_val);
pthread_mutex_lock(&mutex);
somme_val+=random_val;
pthread_mutex_unlock(&mutex);
*pt=*pt*2;
pthread_exit(pt);
}
int main(int argc, char ** argv){
pthread_t tid[10 +1];
pthread_attr_t attr;
int i,res=0;
int* status;
int* pt_ind;
for (i=1;i<10 +1;i++) {
pt_ind=(int*)malloc(sizeof(i));
*pt_ind=i;
if (pthread_create(&tid[i],0,thread_rand,(void *)pt_ind)!=0) {
printf("ERREUR:creation\\n");
exit(1);
}
}
for (i=1;i<10 +1;i++) {
if(pthread_join(tid[i],(void **)&status)!=0) {
printf("ERREUR:joindre\\n");
exit(2);
}
else {
printf("Thread %d se termine avec status %d.\\n",i,*status);
res=res+*status;
}
}
printf("La somme est %d\\n",somme_val);
printf("La valeur renvoyée est %d\\n",res);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t barrier;
pthread_cond_t go;
int numWorkers;
double read_timer() {
static bool initialized = 0;
static struct timeval start;
struct timeval end;
if( !initialized )
{
gettimeofday( &start, 0 );
initialized = 1;
}
gettimeofday( &end, 0 );
return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec);
}
double start_time, end_time;
int size, stripSize;
int sum;
int max;
int max_y;
int max_x;
int min;
int min_y;
int min_x;
int matrix[10000][10000];
void *Worker(void *);
int main(int argc, char *argv[]) {
int i, j;
long l;
pthread_attr_t attr;
pthread_t workerid[10];
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
pthread_mutex_init(&barrier, 0);
pthread_cond_init(&go, 0);
size = (argc > 1)? atoi(argv[1]) : 10000;
numWorkers = (argc > 2)? atoi(argv[2]) : 10;
if (size > 10000) size = 10000;
if (numWorkers > 10) numWorkers = 10;
stripSize = size/numWorkers;
srand(time(0));
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
matrix[i][j] = rand() % 99;
}
}
sum = 0;
max = 0 - 1;
min = 99 + 1;
max_x = -1;
max_y = -1;
min_x = -1;
min_y = -1;
start_time = read_timer();
for (l = 0; l < numWorkers; l++)
{
pthread_create(&workerid[l], &attr, Worker, (void *) l);
}
for(l = 0; l < numWorkers; l++)
{
pthread_join(workerid[l], 0);
}
end_time = read_timer();
printf("The total is %d\\n", sum);
printf("The min value is %d, and is located at (%d,%d).\\n", min, min_y, min_x);
printf("The max value is %d, and is located at (%d,%d).\\n", max, max_y, max_x);
printf("The execution time is %g sec\\n", end_time - start_time);
pthread_exit(0);
}
void *Worker(void *arg) {
long myid = (long) arg;
int total, i, j, first, last, local_min, local_min_x, local_min_y, local_max, local_max_x, local_max_y;
first = myid*stripSize;
last = (myid == numWorkers - 1) ? (size - 1) : (first + stripSize - 1);
total = 0;
local_min_x = -1;
local_min_y = -1;
local_max_x = -1;
local_max_y = -1;
local_min = 99 + 1;
local_max = 0 - 1;
for (i = first; i <= last; i++)
{
for (j = 0; j < size; j++)
{
int matrix_value = matrix[i][j];
total += matrix_value;
if(matrix_value < local_min)
{
local_min = matrix_value;
local_min_y = i;
local_min_x = j;
}
if(matrix_value > local_max)
{
local_max = matrix_value;
local_max_y = i;
local_max_x = j;
}
}
}
pthread_mutex_lock(&barrier);
sum += total;
if(min > local_min)
{
min = local_min;
min_x = local_min_x;
min_y = local_min_y;
}
if(max < local_max)
{
max = local_max;
max_x = local_max_x;
max_y = local_max_y;
}
pthread_mutex_unlock(&barrier);
pthread_exit(0);
}
| 0
|
#include <pthread.h>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;
int init(QType *q)
{
q->head=0;
q->tail=0;
q->amount=0;
}
int empty(QType * q)
{
if (q->head == q->tail)
{
printf("queue is empty\\n");
return (-1);
}
else
return 0;
}
int full(QType * q)
{
if (q->amount == (20))
{
printf("queue is full\\n");
return (-2);
}
else
return 0;
}
int enqueue(QType *q, int x)
{
q->element[q->tail] = x;
q->amount++;
if (q->tail == (20))
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == (20))
{
q->head = 1;
}
else
q->head++;
return x;
}
void *t1(void *arg)
{
int value, i;
pthread_mutex_lock(&m);
value = __VERIFIER_nondet_int();
if (enqueue(&queue,value)) {
goto ERROR;
}
stored_elements[0]=value;
if (empty(&queue)) {
goto ERROR;
}
pthread_mutex_unlock(&m);
for(
i=0; i<((20)-1); i++)
{
pthread_mutex_lock(&m);
if (enqueue_flag)
{
value = __VERIFIER_nondet_int();
enqueue(&queue,value);
stored_elements[i+1]=value;
enqueue_flag=(0);
dequeue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
ERROR:
__VERIFIER_error();
}
void *t2(void *arg)
{
int i;
for(
i=0; i<(20); i++)
{
pthread_mutex_lock(&m);
if (dequeue_flag)
{
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;
}
| 1
|
#include <pthread.h>
int pthread_barrier_init(pthread_barrier_t* barrier,
const void* barrier_attr,
unsigned count) {
barrier->count = count;
pthread_mutex_init(&barrier->mutex, 0);
pthread_cond_init(&barrier->cond, 0);
return 0;
}
int pthread_barrier_wait(pthread_barrier_t* barrier) {
pthread_mutex_lock(&barrier->mutex);
if (--barrier->count == 0) {
pthread_cond_broadcast(&barrier->cond);
pthread_mutex_unlock(&barrier->mutex);
return PTHREAD_BARRIER_SERIAL_THREAD;
}
do {
pthread_cond_wait(&barrier->cond, &barrier->mutex);
} while (barrier->count > 0);
pthread_mutex_unlock(&barrier->mutex);
return 0;
}
int pthread_barrier_destroy(pthread_barrier_t *barrier) {
barrier->count = 0;
pthread_cond_destroy(&barrier->cond);
pthread_mutex_destroy(&barrier->mutex);
return 0;
}
int pthread_yield(void) {
sched_yield();
return 0;
}
| 0
|
#include <pthread.h>
static void *save_thread_entrypoint(void *);
void start_autosave(pthread_t *p, struct save_thread_args *args)
{
strcpy(args->filename, DEFAULT_AUTOSAVE_FILENAME);
int status = pthread_create(p, 0, save_thread_entrypoint, (void *)args);
if (status)
{
printf("\\t\\tCould not acquire thread. Autosave failed.\\n");
return;
}
}
void stop_autosave(pthread_t *p, struct save_thread_args *args)
{
int x, *y;
y = &x;
if (p != 0)
{
pthread_cancel(*p);
pthread_join(*p, (void **) &y);
free(p);
}
if (args != 0)
{
if (args->filename != 0)
{
free(args->filename);
args->filename = 0;
}
}
}
static void *save_thread_entrypoint(void *b)
{
struct save_thread_args *args = (struct save_thread_args *)b;
struct book_node *books = args->head;
int old_cancel_state;
for (;;)
{
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancel_state);
pthread_mutex_lock(args->book_mutex);
export_books(books, args->filename);
pthread_mutex_unlock(args->book_mutex);
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_cancel_state);
sleep(AUTOSAVE_SECONDS);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_cond_t condc, condp;
pthread_mutex_t mutex;
int producer_id = 0;
int consumer_id = 0;
int resource = 0;
void *producer()
{
int id = ++producer_id;
while(1)
{
sleep(1);
pthread_mutex_lock(&mutex);
while(resource == 10)
{
printf("Producer %d: waitting\\n", id);
pthread_cond_wait(&condp,&mutex);
printf("Producer %d: resumed\\n", id);
}
resource++;
printf("Producer %d: %d -> %d\\n", id,resource-1,resource);
pthread_cond_signal(&condc);
pthread_mutex_unlock(&mutex);
}
}
void *consumer()
{
int id = ++consumer_id;
while(1)
{
sleep(1);
pthread_mutex_lock(&mutex);
while(resource == 0)
{
printf("Consumer %d: waitting\\n",id);
pthread_cond_wait(&condc,&mutex);
printf("Consumer %d: resumed\\n",id);
}
resource--;
printf("Consumer %d: %d -> %d\\n", id,resource+1,resource);
pthread_cond_signal(&condp);
pthread_mutex_unlock(&mutex);
}
}
int main()
{
int pn,cn;
printf("please input the sum of producer:");
scanf("%d",&pn);
printf("please input the sum of consumer:");
scanf("%d",&cn);
pthread_t pid[pn];
pthread_t cid[cn];
int retp[pn],retc[cn];
int initMutex = pthread_mutex_init(&mutex,0);
if (initMutex != 0)
{
printf("mutex init failed\\n");
exit(1);
}
for (int i = 0; i < pn; ++i)
{
retp[i] = pthread_create(&pid[i],0,producer,(void *)(&i));
if (retp[i] != 0)
{
printf("producer%d create failed\\n", i);
exit(1);
}
}
for (int i = 0; i < cn; ++i)
{
retc[i] = pthread_create(&cid[i],0,consumer,0);
if (retc[i] != 0)
{
printf("consumer%d create failed\\n", i);
exit(1);
}
}
for(int i = 0; i < pn; i++)
{
pthread_join(pid[i],0);
}
for(int i = 0; i < cn; i++)
{
pthread_join(cid[i],0);
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
exit(0);
}
| 0
|
#include <pthread.h>
pthread_t threads[3];
char buf[20];
int count=0;
pthread_mutex_t mutex,mutex2;
pthread_cond_t rdv;
void rdv_fonc(){
pthread_mutex_lock(&mutex2);
count++;
while(count < 3) pthread_cond_wait(&rdv,&mutex2);
if(count == 3) pthread_cond_broadcast(&rdv);
pthread_mutex_unlock(&mutex2);
}
void *th_fonc (void *arg) {
int is, numero, i,j, m1;
numero = (int)arg;
m1 = 20 + numero*10;
i = m1;
printf("numero= %d, i=%d \\n",numero,i);
switch(numero)
{
case 0 : { pthread_mutex_lock(&mutex);
drawstr (30,125, "_0_", 3);
drawrec (100,100,100+m1*10,30);
pthread_mutex_unlock(&mutex);
for (j=1;j<=m1;j++) {
if (j==10) rdv_fonc();
printf("num %d j=%d\\n",numero,j);
pthread_mutex_lock(&mutex);
fillrec (100,102,100+j*10,26,"yellow");
pthread_mutex_unlock(&mutex);
usleep(500000);
}
flushdis ();
return ( (void *)(numero+100) );
break;
}
case 1 : {
pthread_mutex_lock(&mutex);
drawstr (30, 175, "_1_", 3);
drawrec (100,150,100+m1*10,30);
pthread_mutex_unlock(&mutex);
for (j=1;j<=m1;j++) {
if (j==10) rdv_fonc();
printf("num %d j=%d\\n",numero,j);
pthread_mutex_lock(&mutex);
fillrec (100,152,100+j*10,26,"white");
pthread_mutex_unlock(&mutex);
usleep(700000);
}
flushdis ();
return ( (void *)(numero+100) );
break;
}
case 2 : {
pthread_mutex_lock(&mutex);
drawstr (30, 225, "_2_", 3);
drawrec (100,200,100+m1*10,30);
pthread_mutex_unlock(&mutex);
for (j=1;j<=m1;j++) {
if (j==10) rdv_fonc();
printf("num %d j=%d\\n",numero,j);
pthread_mutex_lock(&mutex);
fillrec (100,202,100+j*10,26,"green");
pthread_mutex_unlock(&mutex);
usleep(300000);
}
flushdis ();
return ( (void *)(numero+100) );
break;
}
}
}
int liretty (char *prompt, char *buffer) {
int i;
printf("\\n%s",prompt);
i = scanf ("%s",buffer);
return strlen(buffer);
}
main() {
void *val=0;
int nlu, is,i=0;
is = pthread_mutex_init(&mutex, 0);
if (is==-1) perror("err. init thread_mutex");
is = pthread_cond_init (&rdv, 0);
if (is==-1) perror("err. init thread_cond");
initrec();
pthread_mutex_lock(&mutex);
drawrec (290,50,2,200);
pthread_mutex_unlock(&mutex);
for(i=0; i<3; i++) {
printf("ici main, création thread %d\\n",i);
is = pthread_create( &threads[i], 0, th_fonc, (void *)i );
if (is==-1) perror("err. création thread");
}
for(i=0; i<3; i++) {
is = pthread_join( threads[i], &val);
if (is==-1) perror("err. join thread");
printf("ici main, fin thread %d\\n",(int)val);
}
nlu = liretty("sortir ?",buf);
printf("--fin--\\n");
detruitrec();
exit(0);
}
| 1
|
#include <pthread.h>
volatile int i = 0, j = 0;
void *thr( void *mtx ) {
pthread_mutex_t *mutex1 = ( (pthread_mutex_t **)mtx )[ 0 ];
pthread_mutex_t *mutex2 = ( (pthread_mutex_t **)mtx )[ 1 ];
pthread_mutex_lock( mutex1 );
pthread_mutex_lock( mutex2 );
i = (i + 1) % 3;
pthread_mutex_unlock( mutex2 );
pthread_mutex_unlock( mutex1 );
return 0;
}
void *other( void *_ ) {
while ( 1 )
j = (j + 1) % 3;
}
int main() {
pthread_mutex_t a = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t b = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t c = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t *ab[] = { &a, &b };
pthread_mutex_t *bc[] = { &b, &c };
pthread_mutex_t *ca[] = { &c, &a };
pthread_mutex_t *ba[] = { &b, &a };
pthread_t ta, tb, ot;
pthread_create( &ot, 0, other, 0 );
pthread_create( &ta, 0, thr, &ab );
pthread_create( &tb, 0, thr, &bc );
thr( ca );
pthread_join( ta, 0 );
pthread_join( tb, 0 );
for ( ;; );
return 0;
}
| 0
|
#include <pthread.h>
LIST list_init(bool allowdups);
bool list_destroy(LIST *l);
bool list_insert(LIST l, uintptr_t *item);
bool list_remove(LIST l, uintptr_t *item);
bool list_contains(LIST l, uintptr_t *item);
bool list_get(LIST l, uintptr_t *item);
bool list_look(LIST l, uintptr_t *item);
struct ListStruct {
Node head;
pthread_mutex_t mxlock;
bool allowdups;
};
struct NodeStruct {
size_t key;
Node next;
uintptr_t data;
};
LIST list_init(bool allowdups) {
LIST list = malloc(sizeof(*list));
if (list == 0) {
errno = ENOMEM;
return (0);
}
Node sentinel = malloc(sizeof(*sentinel));
if (sentinel == 0) {
errno = ENOMEM;
return (0);
}
sentinel->key = 0;
sentinel->next = 0;
sentinel->data = 0;
list->head = sentinel;
pthread_mutex_init(&list->mxlock, 0);
list->allowdups = allowdups;
return (list);
}
bool list_destroy(LIST *l) {
pthread_mutex_lock(&(*l)->mxlock);
Node curr = (*l)->head, succ = 0;
while (curr != 0) {
succ = curr->next;
free(curr);
curr = succ;
}
pthread_mutex_unlock(&(*l)->mxlock);
pthread_mutex_destroy(&(*l)->mxlock);
free(*l);
*l = 0;
return (1);
}
static inline void list_traverse(Node head, size_t key, uintptr_t *item, Node *eprev, Node *ecurr) {
Node prev = head, curr = prev->next;
while (curr != 0) {
if (curr->key == key && item != 0 && curr->data == *item) {
break;
}
if (curr->key > key) {
break;
}
prev = curr;
curr = curr->next;
}
*eprev = prev;
*ecurr = curr;
}
bool list_insert(LIST l, uintptr_t *item) {
Node node = malloc(sizeof(*node));
if (node == 0) {
errno = ENOMEM;
return (0);
}
size_t key = *item;
node->key = key;
node->data = *item;
pthread_mutex_lock(&l->mxlock);
Node prev, curr;
list_traverse(l->head, key, item, &prev, &curr);
if (!l->allowdups && curr != 0 && curr->key == key) {
pthread_mutex_unlock(&l->mxlock);
free(node);
errno = EEXIST;
return (0);
}
node->next = curr;
prev->next = node;
pthread_mutex_unlock(&l->mxlock);
return (1);
}
bool list_remove(LIST l, uintptr_t *item) {
size_t key = *item;
pthread_mutex_lock(&l->mxlock);
Node prev, curr;
list_traverse(l->head, key, item, &prev, &curr);
if (curr != 0 && curr->key == key) {
prev->next = curr->next;
pthread_mutex_unlock(&l->mxlock);
free(curr);
return (1);
}
pthread_mutex_unlock(&l->mxlock);
errno = ENOENT;
return (0);
}
bool list_contains(LIST l, uintptr_t *item) {
size_t key = *item;
pthread_mutex_lock(&l->mxlock);
Node prev, curr;
list_traverse(l->head, key, item, &prev, &curr);
if (curr != 0 && curr->key == key) {
pthread_mutex_unlock(&l->mxlock);
return (1);
}
pthread_mutex_unlock(&l->mxlock);
errno = ENOENT;
return (0);
}
bool list_get(LIST l, uintptr_t *item) {
pthread_mutex_lock(&l->mxlock);
Node prev = l->head, curr = prev->next;
if (curr == 0) {
pthread_mutex_unlock(&l->mxlock);
errno = ENOENT;
return (0);
}
prev->next = curr->next;
pthread_mutex_unlock(&l->mxlock);
*item = curr->data;
free(curr);
return (1);
}
bool list_look(LIST l, uintptr_t *item) {
pthread_mutex_lock(&l->mxlock);
Node curr = l->head->next;
if (curr == 0) {
pthread_mutex_unlock(&l->mxlock);
errno = ENOENT;
return (0);
}
*item = curr->data;
pthread_mutex_unlock(&l->mxlock);
return (1);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t done;
int id;
}params;
void* printId(void* arg){
int id;
pthread_mutex_lock(&(*(params*)(arg)).mutex);
id = (*(params*)(arg)).id;
printf("Hello from Thread %d\\n", id);
pthread_mutex_unlock(&(*(params*)(arg)).mutex);
pthread_cond_signal(&(*(params*)(arg)).done);
}
int main() {
pthread_t threads[5];
params pars;
pthread_mutex_init (&pars.mutex , 0);
pthread_cond_init (&pars.done, 0);
pthread_mutex_lock (&pars.mutex);
int i;
for(i = 0; i < 5; i++) {
pars.id = i;
pthread_create(&threads[i], 0, printId, &pars);
pthread_cond_wait (&pars.done, &pars.mutex);
}
for(i = 0; i < 5; i++) {
pthread_join(threads[i], 0);
}
pthread_mutex_destroy (&pars.mutex);
pthread_cond_destroy (&pars.done);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t tcp_lost_mutex;
static void *process_function(void *);
static void process_function_actual(int job_type);
static int process_judege(struct Job *job);
static void forcecontrol(struct tcp_stream *a_tcp,struct half_stream *snd, struct half_stream *rcv);
static void forcemanage(struct tcp_stream * a_tcp);
extern void tcp_lost_manage_init(){
register_job(JOB_TYPE_TCP_TIMER,process_function,process_judege,CALL_BY_TIMER);
}
static void *process_function(void *arg){
int job_type = JOB_TYPE_TCP_TIMER;
while(1){
pthread_mutex_lock(&(job_mutex_for_cond[job_type]));
pthread_cond_wait(&(job_cond[job_type]),&(job_mutex_for_cond[job_type]));
pthread_mutex_unlock(&(job_mutex_for_cond[job_type]));
process_function_actual(job_type);
}
}
static void process_function_actual(int job_type){
struct Job_Queue private_jobs;
private_jobs.front = 0;
private_jobs.rear = 0;
get_jobs(job_type,&private_jobs);
struct Job current_job;
time_t nowtime;
struct tcp_stream *a_tcp;
int i;
if(tcp_stream_table == 0)
return;
pthread_mutex_lock(&tcp_lost_mutex);
while(!jobqueue_isEmpty(&private_jobs)){
jobqueue_delete(&private_jobs,¤t_job);
nowtime = time((time_t *)0);
for(i=0; i<tcp_stream_table_size; i++){
a_tcp = tcp_stream_table[i];
while(a_tcp) {
if(nowtime - a_tcp->lasttime >= configuration.tcp_delay_max_time){
forcemanage(a_tcp);
}
a_tcp = a_tcp->next_node;
}
}
}
pthread_mutex_unlock(&tcp_lost_mutex);
}
static int process_judege(struct Job *job){
return 1;
}
static void forcecontrol(struct tcp_stream *a_tcp,struct half_stream *snd, struct half_stream *rcv){
struct skbuff *pakiet;
pakiet = rcv->list;
while (pakiet) {
struct skbuff *tmp;
add_from_skb(a_tcp, rcv, snd, pakiet->data,
pakiet->len, pakiet->seq, pakiet->fin, pakiet->urg,
pakiet->urg_ptr + pakiet->seq - 1);
rcv->rmem_alloc -= pakiet->truesize;
if (pakiet->prev)
pakiet->prev->next = pakiet->next;
else
rcv->list = pakiet->next;
if (pakiet->next)
pakiet->next->prev = pakiet->prev;
else
rcv->listtail = pakiet->prev;
tmp = pakiet->next;
free(pakiet->data);
free(pakiet);
pakiet = tmp;
}
}
static void forcemanage(struct tcp_stream * a_tcp){
struct half_stream *snd, *rcv;
snd = &a_tcp->client;
rcv = &a_tcp->server;
forcecontrol(a_tcp,snd,rcv);
rcv = &a_tcp->client;
snd = &a_tcp->server;
forcecontrol(a_tcp,snd,rcv);
}
| 1
|
#include <pthread.h>
struct list {
int data;
pthread_mutex_t lock;
struct list *next;
};
struct list *shared = 0;
void *run(void *arg) {
struct list *cur;
for (cur = shared; cur; cur = cur->next) {
pthread_mutex_lock(&cur->lock);
cur->data++;
pthread_mutex_unlock(&cur->lock);
}
cur = cur->next;
return 0;
}
int main() {
pthread_t t1, t2;
int i;
for (i = 0; i < 42; i++) {
struct list *new;
new = (struct list *) malloc(sizeof(struct list));
new->next = shared;
pthread_mutex_init(&new->lock, 0);
shared = new;
}
for (i = 0; i < 42; i++) {
struct list *new = (struct list *) malloc(sizeof(struct list));
new->next = shared;
pthread_mutex_init(&new->lock, 0);
shared = new;
}
pthread_create(&t1, 0, run, 0);
pthread_create(&t2, 0, run, 0);
return 1;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mtx;
sem_t sem;
int S=0, count = 0;
void barrier_point(){
pthread_mutex_lock(&mtx);
count++;
pthread_mutex_unlock(&mtx);
if(count < 45){
sem_wait(&sem);
}
if(count == 45){
sem_post(&sem);
}
}
void* fct_ptr_thr(void *v){
int tid = *(int*)v;
printf("%d reached the barrier \\n", tid);
barrier_point();
printf("%d passed the barrier \\n", tid);
}
int main(){
int i;
printf("NRTHRDS=%d\\n", 45);
pthread_t pthr[45];
if( pthread_mutex_init(&mtx, 0)){
perror(0);
return errno;
}
if( sem_init(&sem, 0, S)){
perror(0);
return errno;
}
int x[45];
for( i=0; i < 45; i++){
x[i] = i;
}
for( i=0; i < 45; i++){
pthread_create(&pthr[i], 0, fct_ptr_thr, &x[i]);
}
for( i=0; i < 45; i++){
pthread_join(pthr[i], 0);
}
pthread_mutex_destroy(&mtx);
sem_destroy(&sem);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t barrier;
pthread_cond_t go;
int numWorkers;
int numArrived = 0;
void Barrier() {
pthread_mutex_lock(&barrier);
numArrived++;
if (numArrived == numWorkers) {
numArrived = 0;
pthread_cond_broadcast(&go);
} else
pthread_cond_wait(&go, &barrier);
pthread_mutex_unlock(&barrier);
}
double read_timer() {
static bool initialized = 0;
static struct timeval start;
struct timeval end;
if( !initialized ){
gettimeofday( &start, 0 );
initialized = 1;
}
gettimeofday( &end, 0 );
return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec);
}
double start_time, end_time;
int size, stripSize;
int sums[10];
int matrix[10000][10000];
int localMaxIndex[10][3];
int localMinIndex[10][3];
void *Worker(void *);
int main(int argc, char *argv[]) {
int i, j;
long l;
pthread_attr_t attr;
pthread_t workerid[10];
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
pthread_mutex_init(&barrier, 0);
pthread_cond_init(&go, 0);
size = (argc > 1)? atoi(argv[1]) : 10000;
numWorkers = (argc > 2)? atoi(argv[2]) : 10;
if (size > 10000) size = 10000;
if (numWorkers > 10) numWorkers = 10;
stripSize = size/numWorkers;
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
matrix[i][j] = rand()%99;
}
}
start_time = read_timer();
for (l = 0; l < numWorkers; l++)
pthread_create(&workerid[l], &attr, Worker, (void *) l);
pthread_exit(0);
}
void *Worker(void *arg) {
long myid = (long) arg;
int total, i, j, first, last;
int maxIndex[2], minIndex[2], max, min;
first = myid*stripSize;
last = (myid == numWorkers - 1) ? (size - 1) : (first + stripSize - 1);
total = 0;
max = 0;
min = 32767;
for (i = first; i <= last; i++)
for (j = 0; j < size; j++){
total += matrix[i][j];
if(matrix[i][j]>max){
max = matrix[i][j];
maxIndex[0] = i;
maxIndex[1] = j;
}
if(matrix[i][j] < min){
min = matrix[i][j];
minIndex[0] = i;
minIndex[1] = j;
}
}
localMaxIndex[myid][0] = max;
localMinIndex[myid][0] = min;
localMaxIndex[myid][1] = maxIndex[0];
localMinIndex[myid][1] = minIndex[0];
localMaxIndex[myid][2] = maxIndex[1];
localMinIndex[myid][2] = minIndex[1];
sums[myid] = total;
Barrier();
if (myid == 0) {
total = 0;
max = 0;
min = 32767;
for (i = 0; i < numWorkers; i++){
total += sums[i];
if(localMaxIndex[i][0] > max){
max = localMaxIndex[i][0];
maxIndex[0] = localMaxIndex[i][1];
maxIndex[1] = localMaxIndex[i][2];
}
if(localMinIndex[i][0] < min){
min = localMinIndex[i][0];
minIndex[0] = localMinIndex[i][1];
minIndex[1] = localMinIndex[i][2];
}
}
end_time = read_timer();
printf("The maximum element is %i with index %i %i\\n", max, maxIndex[0], maxIndex[1]);
printf("The minimum element is %i with index %i %i\\n", min, minIndex[0], minIndex[1]);
printf("The total is %d\\n", total);
printf("The execution time is %g sec\\n", end_time - start_time);
}
}
| 0
|
#include <pthread.h>
int nbLignes;
int nbMsg;
} Parametres;
pthread_mutex_t lock;
void demanderAcces(void) {
pthread_mutex_lock(&lock);
};
void libererAcces(void) {
pthread_mutex_unlock(&lock);
};
void thdErreur(int codeErr, char *msgErr, void *codeArret) {
fprintf(stderr, "%s: %d soit %s \\n", msgErr, codeErr, strerror(codeErr));
pthread_exit(codeArret);
}
void *thd_afficher (void *arg) {
int i, j, etat;
Parametres param = *(Parametres *)arg;
int s1, s2;
for(i = 0; i < param.nbMsg; i++) {
demanderAcces();
for(j = 0; j < param.nbLignes; j++) {
printf("Afficheur(%lu), j'affiche Ligne %d/%d - Msg %d/%d \\n", pthread_self(), j, param.nbLignes, i, param.nbMsg);
usleep(10);
}
libererAcces();
}
printf("Thread %lu, je me termine \\n", pthread_self());
pthread_exit((void *)0);
}
int main(int argc, char *argv[]) {
pthread_t idThdAfficheurs[20];
Parametres param[20];
int i, etat, nbThreads;
if(argc != 2) {
printf("Usage : %s <Nb de threads>\\n", argv[0]);
exit(1);
}
if(pthread_mutex_init(&lock, 0)) {
fprintf(stderr, "Cannot init mutex : %s\\n", strerror(errno));
exit(1);
}
nbThreads = atoi(argv[1]);
if(nbThreads > 20)
nbThreads = 20;
for(i = 0; i < nbThreads; i++) {
param[i].nbLignes = 3 + i;
param[i].nbMsg = i * 2;
if((etat = pthread_create(&idThdAfficheurs[i], 0, thd_afficher, ¶m[i])) != 0)
thdErreur(etat, "Creation afficheurs", 0);
}
for(i = 0; i < nbThreads; i++) {
if((etat = pthread_join(idThdAfficheurs[i], 0)) != 0)
thdErreur(etat, "Join threads afficheurs", 0);
}
printf("\\nFin de l'execution du thread principal \\n");
pthread_mutex_destroy(&lock);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t m;
pthread_cond_t cond;
char str[100];
bool str_available;
void* producer(void* arg ) {
while (1) {
fgets(str, sizeof str, stdin);
pthread_mutex_lock(&m);
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[sizeof str];
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>
pthread_t odd_thread, even_thread;
pthread_mutex_t lock;
pthread_cond_t cond;
int is_even;
void* even_print(void *data) {
int *max = data;
int i;
for (i = 0; i < *max; i += 2) {
pthread_mutex_lock(&lock);
while (is_even != 1) {
pthread_cond_wait(&cond, &lock);
}
is_even = 0;
printf("%d, ", i);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
}
return 0;
}
void* odd_print(void *data) {
int *max = data;
int i;
for (i = 1; i < *max; i += 2) {
pthread_mutex_lock(&lock);
while (is_even != 0) {
pthread_cond_wait(&cond, &lock);
}
is_even = 1;
printf("%d, ", i);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
}
return 0;
}
int main(int argc, char *argv[]) {
int max = 100;
is_even = 1;
pthread_cond_init(&cond, 0);
pthread_mutex_init(&lock, 0);
pthread_create(&even_thread, 0, &even_print, &max);
pthread_create(&odd_thread, 0, &odd_print, &max);
pthread_join(even_thread, 0);
pthread_join(odd_thread, 0);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
return 0;
}
| 1
|
#include <pthread.h>
int MAX_ITER = 200;
int num = 5;
double waiting_time_averages [ 5 ];
enum { thinking, hungry, eating } state [ 5 ];
pthread_mutex_t lock;
pthread_cond_t self [ 5 ];
pthread_t philo [ 5 ];
int identity [ 5 ] = { 0, 1, 2, 3, 4 };
int eat_count = 0;
void *phil_run ( void *arg );
void *pickup_forks ( int );
void *return_forks ( int );
void *test ( int );
int main ( )
{
pthread_mutex_init ( &lock, 0 );
int i = 0;
for ( i = 0; i < num; i++ )
{
state [ i ] = thinking;
pthread_cond_init ( &self [ i ], 0 );
waiting_time_averages [ i ] = 0.0;
}
for ( i = 0; i < num; i++ )
{
pthread_create ( &philo [ i ], 0, phil_run, &identity [i]);
}
for ( i = 0; i < num; i++ )
{
pthread_join ( philo [ i ], 0 );
printf ( "Thread of Philospher %d is finished executing \\n", i+1 );
}
printf ( "The Hungry Time averages of Philosphers are : \\n" );
for ( i = 0; i < num; i++ )
{
printf ( " PHILOSPHER %d ------------- %f \\n", i+1, waiting_time_averages [ i ] );
}
return 0;
}
void *phil_run ( void *arg )
{
int *tmp_ptr = ( int *)arg;
int id = *tmp_ptr;
double total_waiting_time = 0.0;
time_t start_t, end_t;
double time_of_wait;
printf ("Philospher %d started working \\n",id + 1);
time_t t;
srand ( ( unsigned ) time ( &t ) );
for ( int iter = 0; iter < MAX_ITER; iter++ )
{
int rand_time = ( rand())%2 + 1;
printf ( "Philospher %d is Thinking for %d seconds. \\n", id + 1 , rand_time );
sleep ( rand_time );
time ( &start_t );
pickup_forks ( id );
time ( &end_t );
time_of_wait = difftime ( end_t, start_t );
printf ( "Philospher %d is Hungry for %f seconds. \\n", id + 1, time_of_wait );
int rnd_time = ( rand())%2 + 1;
sleep ( rnd_time );
printf ( "Philospher %d eating at %d th time for %d seconds. \\n", id + 1, iter+1, rnd_time );
return_forks ( id );
eat_count++;
total_waiting_time = total_waiting_time + time_of_wait;
}
waiting_time_averages [ id ] = total_waiting_time / 200.00;
return 0;
}
void *pickup_forks ( int id )
{
pthread_mutex_lock ( &lock );
state [ id ] = hungry;
pthread_mutex_unlock ( &lock );
test ( id );
pthread_mutex_lock ( &lock );
if ( state [ id ] != eating )
{
pthread_cond_wait ( &self [ id ], &lock );
}
pthread_mutex_unlock ( &lock );
return 0;
}
void *return_forks ( int id )
{
pthread_mutex_lock ( &lock );
state [ id ] = thinking;
pthread_mutex_unlock ( &lock );
test ( ( id + num - 1 ) % num );
test ( ( id + 1 ) % num );
}
void *test ( int id )
{
int is_even = ( id % 2 == 0);
int num1 = ( id + num -1 ) % num;
int num2 = ( id + 1 ) % num;
if ( is_even )
{
pthread_mutex_lock( &lock );
if ( (state[num1] != eating) && (state[num2] != eating) && (state[id] == hungry) )
{
state[ id ] = eating;
pthread_cond_signal ( &self [ id ] );
}
pthread_mutex_unlock( &lock );
}
else
{
pthread_mutex_lock( &lock );
if ( (state[num1] != eating) && (state[num2] != eating) && (state[id] == hungry) )
{
state[ id ] = eating;
pthread_cond_signal ( &self [ id ] );
}
pthread_mutex_unlock( &lock );
}
}
| 0
|
#include <pthread.h>
long udelay = 1000000;
float *det_time;
int changed = 0, detected = 0;
int N, NUM_THREADS;
void exitfunc(int sig)
{
int i;
float max = det_time[0], min = det_time[0];
float mean = 0, sdev = 0, range;
printf("\\n%d Threads & %d Signals & Change frequency %f s\\n", NUM_THREADS, N, (float) udelay/1000000);
printf("Changed: %d detected: %d \\n", changed, detected);
for (i = 0; i < detected; ++i)
{
mean += det_time[i];
if (det_time[i] > max)
max = det_time[i];
if (det_time[i] < min)
min = det_time[i];
}
printf("Real time Detection time: %.0f μs \\n", max*1000000);
mean /= detected;
for (i = 0; i < detected; ++i){
sdev += (det_time[i]-mean)*(det_time[i]-mean);
}
sdev = sqrt(sdev/detected);
range = max - min;
printf("Mean Detection Time: %.0f μs and Standard deviation: %.0f μs\\n", mean*1000000, sdev*1000000);
printf("Value Range: %.0f μs\\n", 1000000*range);
_exit(0);
}
volatile int *signalArray;
volatile int flag=1;
struct timeval *timeStamp;
pthread_mutex_t mutexdet;
void *SensorSignalReader (void *args);
void *ChangeDetector (void *args);
int main(int argc, char **argv)
{
NUM_THREADS = sysconf(_SC_NPROCESSORS_ONLN);
printf("Number of Processor Cores = %d\\n", NUM_THREADS);
long i;
if (argc != 3) {
printf("Usage: %s N NUM_THREADS \\n"
" where\\n"
" N : number of signals to monitor\\n"
" NUM_THREADS : number of threads to execute\\n"
, argv[0]);
return (1);
}
NUM_THREADS = atoi(argv[2]);
N = atoi(argv[1]);
printf("%d Threads & %d Signals \\n", NUM_THREADS, N);
signal(SIGALRM, exitfunc);
alarm(20);
signalArray = (int *) malloc(N*sizeof(int));
timeStamp = (struct timeval *) malloc(N*sizeof(struct timeval));
det_time = (float*) malloc(20000*sizeof(float));
pthread_t sigGen;
pthread_t sigDet[NUM_THREADS];
pthread_mutex_init(&mutexdet, 0);
pthread_attr_t pthread_custom_attr;
pthread_attr_init(&pthread_custom_attr);
pthread_attr_setdetachstate(&pthread_custom_attr, PTHREAD_CREATE_JOINABLE);
for (i=0; i<N; i++) {
signalArray[i] = 0;
}
for(i=0; i<NUM_THREADS; i++){
pthread_create(&sigDet[i],&pthread_custom_attr, ChangeDetector, (void *) i );
}
sleep(2);
pthread_create (&sigGen, 0, SensorSignalReader, 0);
for(i=0; i<NUM_THREADS; i++){
pthread_join(sigDet[i], 0);
}
return 0;
}
void *SensorSignalReader (void *arg)
{
char buffer[30];
struct timeval tv;
time_t curtime;
srand(time(0));
while (1) {
int t = rand() % 10 + 1;
usleep(t*udelay/10);
int r = rand() % N;
signalArray[r] ^= 1;
if (signalArray[r]) {
changed++;
gettimeofday(&tv, 0);
timeStamp[r] = tv;
curtime = tv.tv_sec;
strftime(buffer,30,"%d-%m-%Y %T.",localtime(&curtime));
printf("Changed %5d at Time %s%d\\n",r,buffer,tv.tv_usec);
}
}
}
void *ChangeDetector (void *arg1)
{
long tid;
long i;
tid = (long) arg1;
if (tid >= N)
pthread_exit(0);
long Num_cells;
Num_cells = N / NUM_THREADS;
if (N%NUM_THREADS!=0) Num_cells++;
long start = tid*Num_cells;
long end = (start+Num_cells-1 < N) ? start+Num_cells-1 : N-1;
if (tid == NUM_THREADS-1)
end = N-1;
if(start>end)
pthread_exit(0);
printf("Thread %ld started. [%ld,%ld]\\n", tid, start, end);
char buffer[30];
struct timeval tv;
time_t curtime;
int comp_Array[Num_cells];
for (i = 0; i < Num_cells; i++)
comp_Array[i] = signalArray[start+i];
while (1) {
for (i =0; i < Num_cells; ++i)
{
if (signalArray[start+i]!=comp_Array[i]) {
if (signalArray[start+i]==1){
gettimeofday(&tv, 0);
curtime = tv.tv_sec;
strftime(buffer,30,"%d-%m-%Y %T.",localtime(&curtime));
printf("Detcted %5ld at Time %s%d after %ld.%06d sec // Thread %ld \\n",start+i,buffer,tv.tv_usec,
tv.tv_sec - timeStamp[start+i].tv_sec,
tv.tv_usec - timeStamp[start+i].tv_usec, tid);
pthread_mutex_lock (&mutexdet);
det_time[detected] = (float) (tv.tv_sec - timeStamp[start+i].tv_sec) + 0.000001 * (tv.tv_usec - timeStamp[start+i].tv_usec);
detected++;
pthread_mutex_unlock (&mutexdet);
}
comp_Array[i] = signalArray[start+i];
}
}
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock ;
pthread_cond_t snd ;
pthread_cond_t rcv ;
int number[10] ;
int occupied ;
int start ;
} FilterArguments ;
FilterArguments* newFilter();
void* filter( void* arguments );
void send( int value, FilterArguments *shared );
int receive( FilterArguments *shared );
void send( int value, FilterArguments *shared ){
pthread_mutex_lock( &(shared->lock) );
while( shared->occupied >= 10){
pthread_cond_wait( &(shared->rcv), &(shared->lock) );
}
int index = (shared->start + shared->occupied)%10;
shared->number[index] = value ;
shared->occupied++;
pthread_cond_signal ( &(shared->snd) );
pthread_mutex_unlock ( &(shared->lock) );
}
int receive( FilterArguments *shared ){
pthread_mutex_lock( &(shared->lock) );
while( shared->occupied <= 0 ){
pthread_cond_wait( &(shared->snd), &(shared->lock) );
}
int received = shared->number[shared->start];
shared->start = (shared->start +1)%10;
shared->occupied--;
pthread_cond_signal( &(shared->rcv) );
pthread_mutex_unlock ( &(shared->lock) );
return received ;
}
FilterArguments* newFilter( ){
pthread_t thread ;
FilterArguments *shared = ( FilterArguments* ) malloc( sizeof( FilterArguments ) );
pthread_mutex_init( &(shared->lock), 0 );
pthread_cond_init( &(shared->snd), 0 );
pthread_cond_init( &(shared->rcv), 0 );
shared->start = 0;
shared->occupied = 0;
pthread_create( &thread, 0,
&filter, shared );
return shared ;
}
void* filter( void* arguments )
{
FilterArguments *rcv = ( FilterArguments* ) arguments ;
int divider = receive( rcv );
printf("%i\\n", divider);
FilterArguments *snd = newFilter();
int received ;
while(1){
received = receive( rcv );
if( received % divider != 0 ){
send( received, snd );
}
}
}
int main ()
{
int iteration = 2 ;
FilterArguments *shared = newFilter();
while(1){
send(iteration++, shared);
}
}
| 0
|
#include <pthread.h>
{
int buf[5];
int in;
int out;
} sbuf_t;
sbuf_t shared;
sem_t spaces;
sem_t items;
pthread_mutex_t mutex;
void *Producer(void *arg)
{
int i, item, index;
index = (int)arg;
for (i=0; i < 10; i++)
{
item = i;
sem_wait(&spaces);
pthread_mutex_lock(&mutex);
shared.buf[shared.in] = item;
shared.in = (shared.in+1)%5;
printf("[P%d] Producing %d ...\\n", index, item);
pthread_mutex_unlock(&mutex);
sem_post(&items);
sleep(1);
}
return 0;
}
void *Consumer(void *arg)
{
int i, item, index;
index = (int)arg;
for (i=10; i > 0; i--) {
sem_wait(&items);
pthread_mutex_lock(&mutex);
item=i;
item=shared.buf[shared.out];
shared.out = (shared.out+1)%5;
printf("[C%d] Consuming %d ...\\n", index, item);
pthread_mutex_unlock(&mutex);
sem_post(&spaces);
sleep(1);
}
return 0;
}
int main()
{
pthread_t idP, idC;
int index;
sem_init(&items, 0, 0);
sem_init(&spaces, 0, 5);
pthread_mutex_init(&mutex, 0);
printf("\\nSync-Producer-Consumer.sweb\\n\\n");
printf("A possible solution to the producer-consumer problem using semaphores and mutexes.\\n");
for (index = 0; index < 1; index++)
{
pthread_create(&idP, 0, Producer, (void*)index);
}
for(index=0; index<1; index++)
{
pthread_create(&idC, 0, Consumer, (void*)index);
}
for (index = 0; index < 1; index++)
pthread_join(idP, 0);
for(index=0; index<1; index++)
pthread_join(idC,0);
return 0;
}
| 1
|
#include <pthread.h>
int sock, my_ppid, my_id;
pthread_t tid_send_hey;
pthread_t tid_get_hey;
pthread_mutex_t mutex;
void Clean_Up() {
char msgout[MAX_LINE];
char my_host[MAX_HOST_NAME];
printf("\\nHey Client goes bye bye.");
pthread_kill(tid_get_hey, SIGINT);
pthread_kill(tid_send_hey, SIGINT);
gethostname(my_host,MAX_HOST_NAME);
sprintf(msgout,"LOGOUT,%s,%s,%d;12345",getlogin(),my_host,my_id);
pthread_mutex_lock(&mutex);
send(sock, msgout, strlen(msgout) + 1, 0);
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);
exit(0);
}
void Send_Hey(void *arg)
{
int send_sock = (int) arg;
while (1) {
sleep (SLEEP_TIME);
pthread_mutex_lock(&mutex);
send(send_sock, "HEY;", 5, 0);
pthread_mutex_unlock(&mutex);
}
}
void Get_Hey(void *arg)
{
int a, b, c, d, found, map[MAX_LOGINS];
int get_sock = (int) arg;
char *tmp;
struct heybook old, *current;
tmp=malloc(sizeof(struct heybook));
current=malloc(sizeof(struct heybook));
old.count=0;
while (1) {
for (a=0; a < MAX_LOGINS ; a++) map[a] = 0;
recv(get_sock, tmp, sizeof(struct heybook), MSG_WAITALL);
memcpy(current,tmp,sizeof(struct heybook));
for (a=0; a < current->count; a++)
{
found = 0;
for (b=0; b<old.count; b++)
{
if ( (!strcmp(old.login[b].name,current->login[a].name)) &&
(!strcmp(old.login[b].host,current->login[a].host)) &&
(old.login[b].ppid == current->login[a].ppid) )
{
map[b] = 1;
found = 1;
}
}
if (found==0)
{
printf("\\n %s has logged IN on %s (%d).",
current->login[a].name,
current->login[a].host,
current->login[a].ppid);
}
}
for (a=0; a < old.count; a++)
{
if (map[a]==FALSE)
{
printf("\\n %s has logged OUT from %s (%d).",
old.login[a].name,
old.login[a].host,
old.login[a].ppid);
}
}
old.count = current->count;
for (a=0; a < current->count; a++)
{
old.login[a].ppid = current->login[a].ppid;
strcpy(old.login[a].name, current->login[a].name);
strcpy(old.login[a].host, current->login[a].host);
}
}
}
int main(int argc, char *argv[]) {
char name[MAX_NAME],
host[MAX_HOST_NAME],
my_host[MAX_HOST_NAME],
msgout[MAX_LINE],
*server;
int bytes;
my_ppid = getppid();
server = argv[1];
pthread_mutex_init(&mutex, 0);
printf("\\nTrying to connect to server %s at port %d...", server, PORT);
sock = sockconnect(server, PORT);
if (sock == -1) {
printf("\\nCouldn't connect to the server!");
exit(1); }
signal(SIGINT, Clean_Up);
gethostname(my_host,MAX_HOST_NAME);
my_id = (int) (getpid());
sprintf(msgout,"LOGIN,%s,%s,%d;",getlogin(),my_host,my_id);
pthread_mutex_lock(&mutex);
bytes = send(sock, msgout, strlen(msgout)+1, 0);
pthread_mutex_unlock(&mutex);
if (bytes == -1) {
printf("\\nCouldn't send command!");
Clean_Up();
} else {
printf("\\nSent Login Info.");
}
pthread_create(&tid_send_hey, 0, (void*) &Send_Hey, (void*) sock);
pthread_create(&tid_get_hey, 0, (void*) &Get_Hey, (void*) sock);
while (1) {
sleep (2);
if (my_ppid != getppid()) Clean_Up();
}
}
| 0
|
#include <pthread.h>
struct thread_info {
pthread_t thread;
pthread_mutex_t wakeup_mutex;
pthread_cond_t wakeup_send, wakeup_receive;
unsigned len;
char *data;
};
struct thread_info *newthread(void *(*func)(void *))
{
struct thread_info *ti = malloc(sizeof(struct thread_info));
memset(ti, 0, sizeof(struct thread_info));
pthread_create(&(ti->thread), 0, func, ti);
return ti;
}
void thread_send(struct thread_info *ti, char *data, unsigned len)
{
pthread_mutex_lock(&(ti->wakeup_mutex));
if (ti->len)
pthread_cond_wait(&(ti->wakeup_send), &(ti->wakeup_mutex));
ti->data = data;
ti->len = len;
pthread_cond_signal(&(ti->wakeup_receive));
pthread_mutex_unlock(&(ti->wakeup_mutex));
}
void thread_receive(struct thread_info *ti, char **data, unsigned *len)
{
pthread_mutex_lock(&(ti->wakeup_mutex));
if (!ti->len)
pthread_cond_wait(&(ti->wakeup_receive), &(ti->wakeup_mutex));
*data = ti->data;
*len = ti->len;
ti->len = 0;
pthread_cond_signal(&(ti->wakeup_send));
pthread_mutex_unlock(&(ti->wakeup_mutex));
}
void *hello_thread(void *thread_data)
{
struct thread_info *ti = (struct thread_info *)thread_data;
for (;;) {
unsigned len;
char *data;
thread_receive(ti, &data, &len);
if (!data) break;
printf("%.*s", len, data);
free(data);
}
return 0;
}
int main(int argc, char *argv[])
{
void *result;
char *data = strdup("Hello world!\\n");
struct thread_info *ti = newthread(hello_thread);
thread_send(ti, data, strlen(data));
thread_send(ti, 0, 1);
pthread_join(ti->thread, &result);
return (long)result;
}
| 1
|
#include <pthread.h>
void *hit(void *);
float elapsed_time_msec(struct timespec *, struct timespec *, long *, long *);
long num_hits=0, num_threads=0;
pthread_mutex_t mutex;
int main (int argc, char *argv[])
{
float pi;
pthread_t tid[32];
int i, myid[32];
struct timespec t0, t1;
unsigned long sec, nsec;
float comp_time;
if (argc != 2) {
printf("Usage: %s <num_threads>\\n", argv[0]);
exit(0);
}
num_threads = atoi(argv[1]);
if (num_threads > 32) {
printf("num_threads > MAXTHREADS (%d)\\n", 32);
exit(0);
}
; if (clock_gettime(CLOCK_MONOTONIC, &(t0)) < 0) { perror("clock_gettime( ):"); exit(1); };
pthread_mutex_init(&mutex, 0);
for (i = 0; i < num_threads; i++) {
myid[i] = i;
pthread_create(&tid[i], 0, hit, &myid[i]);
}
for (i = 0; i < num_threads; i++) {
pthread_join(tid[i], 0);
}
pthread_mutex_destroy(&mutex);
pi = 4.0 * num_hits / (100*1000*1000);
; if (clock_gettime(CLOCK_MONOTONIC, &(t1)) < 0) { perror("clock_gettime( ):"); exit(1); };
comp_time = elapsed_time_msec(&t0, &t1, &sec, &nsec);
num_threads, pi, (long) (100*1000*1000), comp_time);
pthread_exit(0);
}
void *hit(void * tid)
{
int myid = *((int *)tid);
long start = (myid * (long)(100*1000*1000))/num_threads;
long end = ((myid+1) * (long)(100*1000*1000)) /num_threads;
long i, my_hits=0;
double x, y;
for (i=start; i < end; i++) {
x = ((double) random())/ 32767;
y = ((double) random())/ 32767;
if (x*x + y*y < 1.0)
my_hits++;
}
pthread_mutex_lock (&mutex);
num_hits += my_hits;
pthread_mutex_unlock (&mutex);
pthread_exit(0);
}
float elapsed_time_msec(struct timespec *begin, struct timespec *end, long *sec, long *nsec)
{
if (end->tv_nsec < begin->tv_nsec) {
*nsec = 1000000000 - (begin->tv_nsec - end->tv_nsec);
*sec = end->tv_sec - begin->tv_sec -1;
}
else {
*nsec = end->tv_nsec - begin->tv_nsec;
*sec = end->tv_sec - begin->tv_sec;
}
return (float) (*sec) * 1000 + ((float) (*nsec)) / 1000000;
}
| 0
|
#include <pthread.h>
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo {
int f_count;
pthread_mutex_t f_lock;
struct foo *f_next;
int f_id;
};
struct foo *foo_alloc(void)
{
struct foo *fp;
int idx;
if ((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 1;
if (pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return (0);
}
idx = (((unsigned long)fp) % 29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
}
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;
int idx;
idx = (((unsigned long)fp) % 29);
pthread_mutex_lock(&hashlock);
for (fp = fh[idx]; fp != 0; fp = fp->f_next) {
if (fp->f_id == id) {
fp->f_count++;
break;
}
}
pthread_mutex_unlock(&hashlock);
return (fp);
}
void foo_rele(struct foo *fp)
{
struct foo *tfp;
int idx;
pthread_mutex_lock(&hashlock);
if (--fp->f_count == 0) {
idx = (((unsigned long)fp) % 29);
tfp = fh[idx];
if (tfp == fp) {
fh[idx] = fp->f_next;
} else {
while (tfp->f_next != fp) {
tfp = tfp->f_next;
}
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
} else {
pthread_mutex_unlock(&hashlock);
}
}
| 1
|
#include <pthread.h>
void
rdwr_lock_init(struct rdwrlock *rwp)
{
rwp->lock = PTHREAD_MUTEX_INITIALIZER;
rwp->rdsok = PTHREAD_COND_INITIALIZER;
rwp->wrok = PTHREAD_COND_INITIALIZER;
rwp->rwlock = 0;
rwp->nwrs_wait = 0;
rwp->thrid = 0;
}
void
rd_lock(struct rdwrlock *rwp)
{
assert(rwp != 0);
pthread_mutex_lock(&rwp->lock);
while (rwp->rwlock < 0 || rwp->nwrs_wait)
pthread_cond_wait(&rwp->rdsok, &rwp->lock);
rwp->rwlock++;
pthread_mutex_unlock(&rwp->lock);
}
void
wr_lock(struct rdwrlock *rwp)
{
assert(rwp != 0);
pthread_mutex_lock(&rwp->lock);
rwp->thrid = pthread_self();
while (rwp->rwlock != 0) {
rwp->nwrs_wait++;
pthread_cond_wait(&rwp->wrok, &rwp->lock);
rwp->nwrs_wait--;
}
rwp->rwlock = -1;
pthread_mutex_unlock(&rwp->lock);
}
void
rdwr_unlock(struct rdwrlock *rwp)
{
assert(rwp != 0);
pthread_mutex_lock(&rwp->lock);
if (rwp->rwlock < 0)
rwp->rwlock = 0;
else
rwp->rwlock--;
if (rwp->thrid != 0)
rwp->thrid = 0;
if (rwp->nwrs_wait && rwp->rwlock == 0) {
pthread_mutex_unlock(&rwp->lock);
pthread_cond_signal(&rwp->wrok);
} else if (rwp->nwrs_wait == 0) {
pthread_mutex_unlock(&rwp->lock);
pthread_cond_broadcast(&rwp->rdsok);
}
}
| 0
|
#include <pthread.h>
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo {
int f_count;
pthread_mutex_t f_lock;
struct foo *f_next;
int f_id;
};
struct foo *foo_alloc(void)
{
struct foo *fp;
int idx;
if ((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 1;
if (pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return(0);
}
idx = (((unsigned long)fp)%29);
printf("The value of (unsigned long)fp is: %ld\\n", (unsigned long)fp);
printf("The value of sizeof(*fp) is: %u\\n", sizeof(*fp));
printf("The value of HASH(fp) is: %d\\n", idx);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
}
return(fp);
}
void foo_hold(struct foo *fp)
{
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
struct foo *foo_find(int id)
{
struct foo *fp;
int idx;
idx = (((unsigned long)fp)%29);
pthread_mutex_lock(&hashlock);
for (fp = fh[idx]; fp != 0; fp = fp->f_next) {
if (fp->f_id == id) {
foo_hold(fp);
break;
}
}
pthread_mutex_unlock(&hashlock);
return(fp);
}
void foo_rele(struct foo *fp)
{
struct foo *tfp;
int idx;
pthread_mutex_lock(&fp->f_lock);
if (fp->f_count == 1) {
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_lock(&hashlock);
pthread_mutex_lock(&fp->f_lock);
if (fp->f_count != 1) {
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
return;
}
idx = (((unsigned long)fp)%29);
tfp = fh[idx];
if (tfp == fp) {
fh[idx] = fp->f_next;
} else {
while (tfp->f_next != fp)
tfp = tfp->f_next;
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
printf("Release Success!\\n");
} else {
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
}
}
void main()
{
struct foo *test;
test = foo_alloc();
foo_rele(test);
}
| 1
|
#include <pthread.h>
char buffer[20];
int inptr=0, outptr=0, inbuffer=0;
struct timespec delay;
struct timeval tv;
pthread_mutex_t mutex;
sem_t s_produtor, s_consumidor;
bool stop = 0;
void *killBySiginal()
{
char c;
printf("Digite o Sinal:\\n");
scanf(" %c",&c);
if(c == "T"){
printf("Parou com o Sinal %s", &c);
stop = 1;
}
stop = 0;
sleep(1);
}
void mostrabuffer(char *mens)
{
int i, s_pro, s_con;
printf("%-10s ", mens);
for (i=0; i<20; i++) {
printf("%c", buffer[i]);
}
sem_getvalue(&s_produtor, &s_pro);
sem_getvalue(&s_consumidor, &s_con);
printf(" p=%03d c=%03d (%03d)\\n", s_pro, s_con, inbuffer);
}
void push(char c)
{
if (inbuffer<20) {
pthread_mutex_lock(&mutex);
buffer[inptr]=c;
inptr=(inptr+1)%20;
inbuffer++;
pthread_mutex_unlock(&mutex);
}
}
char pop(void)
{
char c;
if (inbuffer>0) {
pthread_mutex_lock(&mutex);
c=buffer[outptr];
buffer[outptr]=' ';
outptr=(outptr+1)%20;
inbuffer--;
pthread_mutex_unlock(&mutex);
}
return(c);
}
void produtor(void *ptr)
{
int n=100;
char c;
while (n>0) {
sem_wait(&s_produtor);
c=rand()%26+'A';
push(c);
mostrabuffer("push");
n--;
sem_post(&s_consumidor);
tv.tv_sec=0;
tv.tv_usec=((int)rand())%500000;
select(0, 0, 0, 0, &tv);
if(killBySiginal())
break;
}
pthread_exit(0);
}
void consumidor(void *ptr)
{
int n=100;
char c;
while (n>0) {
sem_wait(&s_consumidor);
c=pop();
mostrabuffer("pop");
n--;
sem_post(&s_produtor);
tv.tv_sec=0;
tv.tv_usec=((int)rand())%500000;
select(0, 0, 0, 0, &tv);
if(killBySiginal())
break;
}
pthread_exit(0);
}
main()
{
printf("Thiago Gonçalves Cardoso Resnede\\n");
printf("Rafael Abadala Burle\\n");
printf("Matheus Gama\\n");
printf("Marcelo Cézar de almeida Junior\\n");
printf("Matheus Souza Silva\\n");
pthread_t produtor_t, consumidor_t;
char *message1 = "abdafsfasdfasdfasdfasdfasdfasdcd";
char *message2 = "hkljhklhkjhlhkhkjlkhkjh";
int i;
srand(time(0));
for (i=0; i<20; i++);
buffer[i]=' ';
sem_init(&s_produtor, 0, 20);
sem_init(&s_consumidor, 0, 0);
mostrabuffer("init");
pthread_create(&produtor_t, 0, (void*)&produtor, 0);
pthread_create(&consumidor_t, 0, (void*)&consumidor, 0);
pthread_join(produtor_t, 0);
pthread_join(consumidor_t, 0);
mostrabuffer("end");
sem_destroy(&s_produtor);
sem_destroy(&s_consumidor);
exit(0);
}
| 0
|
#include <pthread.h>
volatile int global_counter = 0;
volatile int shared_array_1[5] = {1,2,3,4,5};
volatile int shared_array_2[5] = {0,0,0,0,0};
pthread_mutex_t mutex_global;
void* hello(void* id)
{
int i;
if (*((int*)id) == 0)
{
pthread_mutex_lock(&mutex_global);
for (i=0; i<5; i++)
{
shared_array_2[i] = shared_array_1[i] + 1*i;
global_counter++;
printf("%d: Shared Array 1 [%d] = %d \\n", *((int*) id), i, shared_array_1[i]);
}
pthread_mutex_unlock(&mutex_global);
}
else
{
for (i=0; i<5; i++)
{
while(global_counter <= i);
printf("%d: Shared Array 2 [%d] = %d \\n", *((int*) id), i, shared_array_2[i]);
}
}
return 0;
}
int main(int argc, char* argv[])
{
const int COUNT = 2;
int i, y;
pthread_t thread[COUNT];
int ids[COUNT];
for (i=0; i<COUNT; i++)
{
ids[i] = i;
int retval = pthread_create(&thread[i], 0, hello, &ids[i]);
if (retval)
{
perror("ptherad_created failed");
return 1;
}
}
for (i=0; i<COUNT; i++) pthread_join(thread[i], 0);
pthread_mutex_destroy(&mutex_global);
return 0;
}
| 1
|
#include <pthread.h>
long max_queue_size = 10000;
long *buffer;
long size;
long max_size;
long index;
long outdex;
pthread_mutex_t *mutex;
pthread_cond_t *full;
pthread_cond_t *empty;
}queue_t;
void queue_enqueue(queue_t *queue, long value){
pthread_mutex_lock(queue->mutex);
while (queue->size == queue->max_size){
pthread_cond_wait(queue->full, queue->mutex);
}
queue->buffer[queue->index] = value;
queue->size ++;
queue->index ++;
queue->index %= queue->max_size;
pthread_mutex_unlock(queue->mutex);
pthread_cond_broadcast(queue->empty);
}
long queue_dequeue(queue_t * queue){
pthread_mutex_lock(queue->mutex);
while (queue->size == 0){
pthread_cond_wait(queue->empty, queue->mutex);
}
long value = queue->buffer[queue->outdex];
queue->size --;
queue->outdex ++;
queue->outdex %= queue->max_size;
pthread_mutex_unlock(queue->mutex);
pthread_cond_broadcast(queue->full);
return value;
}
queue_t *init_queue(long max_size){
queue_t *queue;
queue = malloc(sizeof(queue_t));
queue->buffer = malloc(sizeof(long) * max_size);
queue->size = 0;
queue->max_size = max_size;
queue->index = 0;
queue->outdex = 0;
queue->mutex = malloc(sizeof(pthread_mutex_t));
pthread_mutex_init(queue->mutex, 0);
queue->full = malloc(sizeof(pthread_cond_t));
pthread_cond_init(queue->full, 0);
queue->empty = malloc(sizeof(pthread_cond_t));
pthread_cond_init(queue->empty, 0);
return queue;
}
void *check_number(void *a){
queue_t *inbound_queue = (queue_t*)a;
queue_t *outbound_queue;
long prime = queue_dequeue(inbound_queue);
printf("new prime number: %ld\\n", prime);
long nat_number = 0;
int newThread = 0;
while(!newThread){
nat_number = queue_dequeue(inbound_queue);
if(nat_number % prime != 0){
newThread = 1;
outbound_queue = init_queue(max_queue_size);
queue_enqueue(outbound_queue, nat_number);
}
}
pthread_t thread;
pthread_create ( &thread,
0 ,
&check_number ,
outbound_queue);
while(1){
nat_number = queue_dequeue(inbound_queue);
if(nat_number % prime != 0){
queue_enqueue(outbound_queue, nat_number);
}
}
}
int main(int argc, char *argv[]){
long n = 3;
pthread_t thread_one;
queue_t *outbound_queue = init_queue(max_queue_size);
queue_enqueue(outbound_queue, n);
printf("new prime number: %ld\\n", n);
pthread_create (&thread_one,
0 ,
&check_number ,
outbound_queue);
do{
n += 2;
queue_enqueue(outbound_queue, n);
}while(1);
}
| 0
|
#include <pthread.h>
int count = 0;
int thread_ids[3] = {0,1,2};
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *inc_count(void *t) {
int i;
long my_id = (long)t;
for (i=0; i<10; i++) {
pthread_mutex_lock(&count_mutex);
count++;
if (count == 12) {
pthread_cond_signal(&count_threshold_cv);
printf("inc_count(): thread %ld, count = %d Threshold reached.\\n", my_id,count);
}
printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count);
pthread_mutex_unlock(&count_mutex);
sleep(1);
}
pthread_exit(0);
}
void *watch_count(void *t) {
long my_id = (long)t;
printf("Starting watch_count(): thread %ld\\n", my_id);
pthread_mutex_lock(&count_mutex);
while (count<12) {
pthread_cond_wait(&count_threshold_cv,&count_mutex);
printf("watch_count(): thread %ld Condition signal received.\\n", my_id);
count += 125;
printf("watch_count(): thread %ld count now = %d.\\n", my_id, count);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main (int argc, char *argv[]) {
int i, rc;
long t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, watch_count, (void *)t1);
pthread_create(&threads[1], &attr, inc_count, (void *)t2);
pthread_create(&threads[2], &attr, inc_count, (void *)t3);
for (i=0; i<3; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited on %d threads. Done.\\n", 3);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t agente;
pthread_mutex_t fumadores[3];
char *necesita[3] = {"TabacoPapel", "TabacoFosforos", "PapelFosforos"};
bool enLaMesa[3] = {0, 0, 0};
pthread_mutex_t pusherM[3];
void *fumador(void *arg) {
int idFumador = *(int *) arg;
int tipo = idFumador % 3;
int i;
for (i = 0; i < 3; ++i) {
printf("Fumador %d >> Esperando %s\\n",idFumador, necesita[tipo]);
pthread_mutex_lock(&fumadores[tipo]);
printf("Fumador %d << Haciendo Cigarro\\n", idFumador);
usleep(rand() % 50000);
pthread_mutex_unlock(&agente);
printf("Fumador %d -- Fumando\\n", idFumador);
usleep(rand() % 50000);
}
return 0;
}
pthread_mutex_t pusher_lock;
void *pusher(void *arg) {
int pusher_id = *(int *) arg;
int i;
for (i = 0; i < 12; ++i) {
pthread_mutex_lock(&pusherM[pusher_id]);
pthread_mutex_lock(&pusher_lock);
if (enLaMesa[(pusher_id + 1) % 3]) {
enLaMesa[(pusher_id + 1) % 3] = 0;
pthread_mutex_unlock(&fumadores[(pusher_id + 2) % 3]);
}
else if (enLaMesa[(pusher_id + 2) % 3]) {
enLaMesa[(pusher_id + 2) % 3] = 0;
pthread_mutex_unlock(&fumadores[(pusher_id + 1) % 3]);
}
else {
enLaMesa[pusher_id] = 1;
}
pthread_mutex_unlock(&pusher_lock);
}
return 0;
}
void *agent(void *arg) {
int agent_id = *(int *) arg;
int i;
for (i = 0; i < 3; ++i) {
usleep(rand() % 200000);
pthread_mutex_lock(&agente);
pthread_mutex_unlock(&pusherM[agent_id]);
pthread_mutex_unlock(&pusherM[(agent_id + 1) % 3]);
printf("==> Agente %d Dando %s \\n",
agent_id, necesita[(agent_id + 2) % 3]);
}
return 0;
}
int main(int argc, char *arvg[]) {
srand(time(0));
pthread_mutex_init(&agente, 0);
pthread_mutex_init(&pusher_lock, 0);
int i;
for (i = 0; i < 3; ++i) {
pthread_mutex_init(&fumadores[i], 0);
pthread_mutex_init(&pusherM[i], 0);
}
int fumador_ids[3];
pthread_t fumador_threads[3];
for (i = 0; i < 3; ++i) {
fumador_ids[i] = i;
if (pthread_create(&fumador_threads[i], 0, fumador, &fumador_ids[i]) == EAGAIN) {
perror("no hay recursos suficientes");
return 0;
}
}
int pusher_ids[3];
pthread_t pusher_threads[3];
for (i = 0; i < 3; ++i) {
pusher_ids[i] = i;
if (pthread_create(&pusher_threads[i], 0, pusher, &pusher_ids[i]) == EAGAIN) {
perror("no hay recursos suficientes");
return 0;
}
}
int agent_ids[3];
pthread_t agent_threads[3];
for (i = 0; i < 3; ++i) {
agent_ids[i] = i;
if (pthread_create(&agent_threads[i], 0, agent, &agent_ids[i]) == EAGAIN) {
perror("no hay recursos suficientes");
return 0;
}
}
for (i = 0; i < 3; ++i) {
pthread_join(fumador_threads[i], 0);
}
return 0;
}
| 0
|
#include <pthread.h>
static int var_sonar_prox_data[18];
static pthread_mutex_t Sonar_Prox_Write_Lock = PTHREAD_MUTEX_INITIALIZER;
void Init_Sonar_Prox(void)
{
int ii;
pthread_mutex_unlock(&Sonar_Prox_Write_Lock);
for(ii=0; ii < 16;ii++){
var_sonar_prox_data[ii]=-1;
}
}
double Get_Sonar_Distance(int indexid)
{
return ((var_sonar_prox_data[(indexid%17)] ) * 0.01);
}
void Print_Sonar_Data(void)
{
while(pthread_mutex_lock(&Sonar_Prox_Write_Lock) != 0)
{
usleep(1177);
}
pthread_mutex_unlock(&Sonar_Prox_Write_Lock);
}
void Set_Sonar_Data(int rawdata, char indexid)
{
int bugfix =indexid;
while(pthread_mutex_lock(&Sonar_Prox_Write_Lock) != 0)
{
usleep(116);
}
if(rawdata > 0)
{
var_sonar_prox_data[bugfix] = rawdata;
}else{
var_sonar_prox_data[bugfix] = 0;
}
pthread_mutex_unlock(&Sonar_Prox_Write_Lock);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
void ThreadClean(void* arg)
{
pthread_mutex_unlock(&mutex);
}
void* child1(void* arg)
{
while(1)
{
printf("thread 1 get running\\n");
printf("thread 1 pthread_mutex_lock return %d\\n",
pthread_mutex_lock(&mutex)
);
pthread_cond_wait(&cond,&mutex);
printf("thread 1 condition applied\\n");
pthread_mutex_unlock(&mutex);
sleep(5);
}
return;
}
void* child2(void* arg)
{
while(1)
{
sleep(3);
printf("thread 2 get running.\\n");
printf("thread 2 pthread_mutex_lock return %d\\n",
pthread_mutex_lock(&mutex)
);
pthread_cond_wait(&cond,&mutex);
printf("thread 2 condition applied\\n");
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main(int argc,char* argv[])
{
pthread_t tid1,tid2;
printf("hello,condition variable test\\n");
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond,0);
pthread_create(&tid1,0,child1,0);
pthread_create(&tid2,0,child2,0);
while(1)
{
pthread_cancel(tid1);
sleep(2);
pthread_cond_signal(&cond);
}
sleep(10);
return 0;
}
| 0
|
#include <pthread.h>
static int capulet_count;
static int montague_count;
static pthread_mutex_t lock_access = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t clear = PTHREAD_COND_INITIALIZER;
struct person{
char * family;
char * name;
unsigned int arrival_time;
unsigned int stay_time;
};
void * capulet(void * arg){
struct person* a_person = (struct person *) arg;
printf("%s %s arrives at time %d\\n", a_person->family, a_person->name, a_person->arrival_time);
pthread_mutex_lock(&lock_access);
while(montague_count > 0){
pthread_cond_wait(&clear, &lock_access);
}
capulet_count++;
pthread_cond_signal(&clear);
printf("%s %s enters the plaza\\n", a_person->family, a_person->name);
pthread_mutex_unlock(&lock_access);
sleep(a_person->stay_time);
pthread_mutex_lock(&lock_access);
printf("%s %s leaves the plaza\\n", a_person->family, a_person->name);
capulet_count--;
if(capulet_count == 0)
pthread_cond_broadcast(&clear);
pthread_mutex_unlock(&lock_access);
pthread_exit((void*)0);
}
void * montague(void * arg){
struct person* a_person = (struct person *) arg;
printf("%s %s arrives at time %d\\n", a_person->family, a_person->name, a_person->arrival_time);
pthread_mutex_lock(&lock_access);
while(capulet_count > 0){
pthread_cond_wait(&clear, &lock_access);
}
montague_count++;
pthread_cond_signal(&clear);
printf("%s %s enters the plaza\\n", a_person->family, a_person->name);
pthread_mutex_unlock(&lock_access);
sleep(a_person->stay_time);
pthread_mutex_lock(&lock_access);
printf("%s %s leaves the plaza\\n", a_person->family, a_person->name);
montague_count--;
if(montague_count == 0)
pthread_cond_broadcast(&clear);
pthread_mutex_unlock(&lock_access);
pthread_exit((void*)0);
}
int main(void){
char * buffer;
struct person log[20];
int n_child= 0;
int n_arg = 0;
while(1){
scanf("%ms", &buffer);
if (buffer == 0)
break;
if (n_arg == 0) { log[n_child].family = buffer;};
if (n_arg == 1) { log[n_child].name = buffer;};
if (n_arg == 2) { log[n_child].arrival_time = atoi(buffer);};
if (n_arg == 3) { log[n_child].stay_time = atoi(buffer);
n_arg = -1;
n_child++;
};
n_arg++;
}
pthread_t tids[n_child];
void * (*gang) (void*);
for(int i = 0; i < n_child; i++){
gang = (strcmp(log[i].family, "Capulet") == 0)? capulet: montague;
if(i!=0)
sleep(log[i].arrival_time - log[i-1].arrival_time);
pthread_create(&tids[i], 0, gang, &log[i]);
}
for(int i = 0; i < n_child; i++){
pthread_join(tids[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
extern void PaUtil_DevicesChanged(unsigned, void*);
static pthread_t g_thread_id;
static pthread_mutex_t g_mutex;
static volatile sig_atomic_t g_run = 0;
static int device_list_size(void)
{
snd_ctl_t *handle;
int card, err, dev, idx;
int nb = 0;
snd_ctl_card_info_t *info;
snd_pcm_info_t *pcminfo;
snd_ctl_card_info_alloca(&info);
snd_pcm_info_alloca(&pcminfo);
card = -1;
if (snd_card_next(&card) < 0 || card < 0)
{
return nb;
}
while (card >= 0)
{
char name[32];
sprintf(name, "hw:%d", card);
if ((err = snd_ctl_open(&handle, name, 0)) < 0)
{
goto next_card;
}
if ((err = snd_ctl_card_info(handle, info)) < 0)
{
snd_ctl_close(handle);
goto next_card;
}
dev = -1;
while (1)
{
unsigned int count;
int hasPlayback = 0;
int hasCapture = 0;
snd_ctl_pcm_next_device(handle, &dev);
if (dev < 0)
break;
snd_pcm_info_set_device(pcminfo, dev);
snd_pcm_info_set_subdevice(pcminfo, 0);
snd_pcm_info_set_stream(pcminfo, SND_PCM_STREAM_CAPTURE);
if ((err = snd_ctl_pcm_info(handle, pcminfo)) >= 0)
{
hasCapture = 1;
}
snd_pcm_info_set_stream(pcminfo, SND_PCM_STREAM_PLAYBACK);
if ((err = snd_ctl_pcm_info(handle, pcminfo)) >= 0)
{
hasPlayback = 1;
count = snd_pcm_info_get_subdevices_count(pcminfo);
}
if(hasPlayback == 0 && hasCapture == 0)
continue;
nb++;
}
snd_ctl_close(handle);
next_card:
if (snd_card_next(&card) < 0)
{
break;
}
}
return nb;
}
static void* thread_fcn(void* data)
{
int currentDevices = 0;
currentDevices = device_list_size();
while(g_run)
{
int count = 0;
sleep(1);
count = device_list_size();
if(count != currentDevices)
{
int add = (count > currentDevices) ? 1 : 2;
currentDevices = count;
PaUtil_DevicesChanged(add, 0);
}
}
return 0;
}
void PaUtil_InitializeHotPlug()
{
pthread_mutex_init(&g_mutex, 0);
g_run = 1;
pthread_create(&g_thread_id, 0, thread_fcn, 0);
}
void PaUtil_TerminateHotPlug()
{
void* ret = 0;
g_run = 0;
pthread_join(g_thread_id, &ret);
pthread_mutex_destroy(&g_mutex);
}
void PaUtil_LockHotPlug()
{
pthread_mutex_lock(&g_mutex);
}
void PaUtil_UnlockHotPlug()
{
pthread_mutex_unlock(&g_mutex);
}
| 0
|
#include <pthread.h>
struct philosopher {
int id;
pthread_t thread;
pthread_mutex_t *left_fork;
pthread_mutex_t *right_fork;
sem_t *semaphore;
};
int rand_range(int min, int max)
{
return rand() % (max - min + 1) + min;
}
void get_forks(struct philosopher *philosopher)
{
pthread_mutex_lock(philosopher->left_fork);
pthread_mutex_lock(philosopher->right_fork);
}
void put_forks(struct philosopher *philosopher)
{
pthread_mutex_unlock(philosopher->left_fork);
pthread_mutex_unlock(philosopher->right_fork);
}
void *philosopher_thread_routine(void *phil_ptr)
{
struct philosopher *philosopher = phil_ptr;
while (1) {
printf("philosopher %d is thinking\\n", philosopher->id);
sleep(rand_range(1, 20));
sem_wait(philosopher->semaphore);
get_forks(philosopher);
printf("philosopher %d is eating\\n", philosopher->id);
sleep(rand_range(2, 9));
put_forks(philosopher);
sem_post(philosopher->semaphore);
}
return 0;
}
void spawn_threads(const int n)
{
struct philosopher *philosophers;
pthread_mutex_t *forks;
sem_t *semaphore;
int i;
philosophers = alloca(sizeof(struct philosopher) * n);
forks = alloca(sizeof(pthread_mutex_t) * n);
semaphore = alloca(sizeof(sem_t));
sem_init(semaphore, 0, n - 1);
for (i = 0; i < n; i++) {
pthread_mutex_init(&forks[i], 0);
}
for (i = 0; i < n; i++) {
philosophers[i].id = i;
pthread_create(&philosophers[i].thread, 0,
philosopher_thread_routine, &philosophers[i]);
philosophers[i].left_fork = &forks[i];
if (i < n - 1) {
philosophers[i].right_fork = &forks[i + 1];
} else {
philosophers[i].right_fork = &forks[0];
}
philosophers[i].semaphore = semaphore;
}
for (i = 0; i < n; i++) {
pthread_join(philosophers[i].thread, 0);
}
}
int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr,
"USAGE: %s <num_philosophers>\\n",
argv[0]);
return 1;
} else {
int n = atoi(argv[1]);
if (n > 0) {
spawn_threads(n);
} else {
fprintf(stderr,
"error: <num_philosophers> must be > 0\\n");
return 1;
}
}
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t screenMutex = PTHREAD_MUTEX_INITIALIZER;
void safe_update_screen() {
pthread_mutex_lock(&screenMutex);
update_screen();
pthread_mutex_unlock(&screenMutex);
}
char safe_get_screen_char(int multipart, int col, int row) {
if (!multipart)
pthread_mutex_lock(&screenMutex);
char ch = get_screen_char(col, row);
if (!multipart)
pthread_mutex_unlock(&screenMutex);
return ch;
}
void safe_set_screen_char(int multipart, int col, int row, char ch) {
if (!multipart)
pthread_mutex_lock(&screenMutex);
set_screen_char(col, row, ch);
if (!multipart)
pthread_mutex_unlock(&screenMutex);
}
void safe_blink_screen(char * charset) {
pthread_mutex_lock(&screenMutex);
blink_screen(charset);
pthread_mutex_unlock(&screenMutex);
}
int safe_find_target(int multipart, char ch, int * col, int * row) {
if (!multipart)
pthread_mutex_lock(&screenMutex);
int target = find_target(ch, col, row);
if (!multipart)
pthread_mutex_unlock(&screenMutex);
return target;
}
int safe_move_to_target(int multipart, int col, int row, int * to_col, int * to_row) {
if (!multipart)
pthread_mutex_lock(&screenMutex);
int target = move_to_target(col, row, to_col, to_row);
if (!multipart)
pthread_mutex_unlock(&screenMutex);
return target;
}
void lockScreen() {
pthread_mutex_lock(&screenMutex);
}
void unlockScreen() {
pthread_mutex_unlock(&screenMutex);
}
| 0
|
#include <pthread.h>
struct counter {
pthread_mutex_t lock;
long max;
};
static void * thread_local(void *arg)
{
int i;
struct counter *c = (struct counter *) arg;
pthread_mutex_lock(&c->lock);
for (i = 0; i < c->max; i++){
pthread_mutex_unlock(&c->lock);
pthread_mutex_lock(&c->lock);
}
pthread_mutex_unlock(&c->lock);
return 0;
}
int main(int argc, char *argv[])
{
int i, n, k;
int st;
pthread_attr_t attr;
pthread_t *tid;
struct counter c;
if (argc < 3) {
printf("t_lock times threads.\\n");
return -1;
}
n = atoi(argv[1]);
k = atoi(argv[2]);
tid = malloc(sizeof(pthread_t) * k);
st = pthread_attr_init(&attr);
if (st != 0) {
perror("pthread_attr_init");
return -1;
}
c.max = n;
if (pthread_mutex_init(&c.lock, 0) != 0)
{
perror("pthread_mutex_init");
return 1;
}
for (i = 0; i < k; i++) {
st = pthread_create(tid+i, &attr, thread_local, &c);
if (st != 0) {
printf("i: %d.\\n", i);
perror("pthread_create");
return -1;
}
}
for (i = 0; i < k; i++) {
st = pthread_join(tid[i], 0);
if (st != 0) {
perror("pthread_join");
return -1;
}
}
pthread_mutex_destroy(&c.lock);
free(tid);
return 0;
}
| 1
|
#include <pthread.h>
static void initDestroyer(struct destroyer *, int, int);
static void animateDestroyer(pthread_t, struct destroyer *);
void *sendDestroyer(void *arg) {
struct destroyer *ship = arg;
pthread_t destRocketThread;
srand(getpid());
while(1) {
if (!ship->isAlive) {
sleep(10 + (rand()%20));
initDestroyer(ship, rand()%15, 1+(rand()%10));
pthread_create(&destRocketThread, 0,
shootDestRocket, ship);
animateDestroyer(destRocketThread, ship);
}
}
}
void initDestroyer(struct destroyer *ship, int row, int delay) {
strncpy(ship->topMessage, DESTROYER_TOP, DESTROYER_LEN);
strncpy(ship->botMessage, DESTROYER_BOT, DESTROYER_LEN);
ship->length = DESTROYER_LEN;
ship->row = row;
ship->col = 0;
ship->dir = 1;
ship->delay = delay;
ship->hit = 0;
ship->isAlive = 1;
}
void animateDestroyer(pthread_t thread, struct destroyer *ship) {
int i;
while (1) {
usleep(ship->delay*20000);
pthread_mutex_lock(&mx);
move(ship->row, ship->col);
addch(' ');
addnstr(ship->topMessage, DESTROYER_LEN);
addch(' ');
move(LINES-1, COLS-1);
refresh();
move(ship->row + 1, ship->col);
addch(' ');
addnstr(ship->botMessage, DESTROYER_LEN);
addch(' ');
move(LINES-1, COLS-1);
refresh();
pthread_mutex_unlock(&mx);
if ((ship->col + ship->length + 2) >= COLS && ship->dir == 1)
ship->dir = -1;
if (ship->col <= 0 && ship->dir == -1)
ship->dir = 1;
if (ship->hit > 100) {
pthread_mutex_lock(&mx);
move(ship->row, ship->col);
for (i=0; i <= ship->length; i++)
addch(' ');
move(ship->row + 1, ship->col);
for (i=0; i <= ship->length; i++)
addch(' ');
move(LINES-1, COLS-1);
refresh();
pthread_mutex_unlock(&mx);
break;
}
ship->col += ship->dir;
}
ship->isAlive = 0;
eraseDestroyerRocket();
pthread_cancel(thread);
}
| 0
|
#include <pthread.h>
pthread_t thread;
pthread_mutex_t mutex;
int clientNumber = 0;
int allClientSocket[100];
void *broadcastAllClient(void *arg);
int main() {
if(pthread_mutex_init(&mutex,0) != 0) {
printf("뮤텍스 생성에 실패했습니다.\\n");
return 0;
}
int serverSocket = socket(PF_INET, SOCK_STREAM, 0);
struct sockaddr_in serverAddress;
memset(&serverAddress, 0, sizeof(serverAddress));
serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(11111);
if(bind(serverSocket, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) == -1) {
printf("서버 소켓을 바인드 하는데 실패했습니다.\\n");
return 0;
}
if(listen(serverSocket, 5) == -1) {
printf("서버 소켓을 listen 모드로 설정하는데 실패했습니다.\\n");
return 0;
}
printf("채팅 서버가 실행되었습니다.\\n");
printf("***** 전체 대화 내용 *****\\n");
while(1) {
struct sockaddr_in clientAddress;
int clientAddress_size = sizeof(clientAddress);
int clientSocket = accept(serverSocket, (struct sockaddr *)&clientAddress, &clientAddress_size);
pthread_mutex_lock(&mutex);
clientNumber++;
allClientSocket[clientNumber-1] = clientSocket;
pthread_mutex_unlock(&mutex);
char greeMessage[100];
sprintf(greeMessage, "[서버]환영합니다. 대화명을 입력해 주세요.\\n");
write(clientSocket, greeMessage, sizeof(greeMessage));
pthread_create(&thread, 0, broadcastAllClient, (void *)clientSocket);
}
printf("채팅을 종료합니다.\\n");
return 0;
}
void *broadcastAllClient(void *arg) {
char fromClient[30 +100];
int myClientSocket = (int)arg;
int i = 0;
while(1) {
int readlen = read(myClientSocket, fromClient, sizeof(fromClient));
if(readlen <= 0) {
break;
}
printf("%s\\n", fromClient);
pthread_mutex_lock(&mutex);
for(i=0;i<clientNumber;i++) {
if(allClientSocket[i] != myClientSocket) {
write(allClientSocket[i], fromClient, sizeof(fromClient));
}
}
pthread_mutex_unlock(&mutex);
}
pthread_mutex_lock(&mutex);
for(i=0;i<clientNumber;i++) {
if(allClientSocket[i] == myClientSocket) {
for(i;i<clientNumber-1;i++) {
allClientSocket[i] = allClientSocket[i+1];
}
break;
}
clientNumber--;
pthread_mutex_unlock(&mutex);
close(myClientSocket);
}
}
| 1
|
#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 ("fileQuestion10efficace.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;
}
| 0
|
#include <pthread.h>
int total = 17;
int ate[5];
pthread_mutex_t turn;
pthread_t philosophers[5];
int ismax(int id)
{
int i;
int max;
int cnt =0;
max = ate[0];
for(i = 0; i < 5; i++)
{
if(ate[i] > max)
max = ate[i];
}
for(i = 0; i < 5; i++)
if(ate[i] == ate[id])
cnt++;
if(cnt == 5)
return 2;
if(max == ate[id])
return 1;
return 0;
}
void * eat(void *tid)
{
long myid = (long) tid;
while(1)
{
pthread_mutex_lock(&turn);
if(total == 0)
{
pthread_mutex_unlock(&turn);
break;
}
if ( (ismax(myid) == 1) )
{
pthread_mutex_unlock(&turn);
pthread_yield();
continue;
}
total -=1;
ate[myid] +=1;
pthread_mutex_unlock(&turn);
pthread_yield();
}
}
int main(int argc,char *argv[],char *envp[])
{
int i;
pthread_attr_t attr;
pthread_mutex_init(&turn,0);
pthread_attr_init(&attr);
for(i = 0; i < 5; i++)
{
pthread_create(&philosophers[i],&attr,eat,(void *)i);
printf("created a philosopher \\n");
}
for(i = 0; i < 5; i++)
pthread_join(philosophers[i],0);
for(i = 0; i < 5;i++)
printf("Philosopher %d ate total %d\\n",i,ate[i]);
pthread_mutex_destroy(&turn);
return 0;
}
| 1
|
#include <pthread.h>
struct tinfo {
pthread_t id;
int num;
};
int resources = 0;
int upper_bound_blocked = 0;
int lower_bound_blocked = 0;
pthread_mutex_t mx_res;
pthread_cond_t free_slot, item_ready;
void random_wait(int min, int max) {
struct timespec sleep_time;
sleep_time.tv_sec = 0;
sleep_time.tv_nsec = ((rand() % (max - min)) + min) * 1000;
nanosleep(&sleep_time, 0);
}
void * producer(void * arg) {
struct tinfo * current_thread = arg;
printf("Mam do wyprodukowania %d danych.\\n", current_thread->num);
int data = current_thread->num;
while (data > 0) {
pthread_mutex_lock(&mx_res);
while (resources == 4800) {
upper_bound_blocked++;
pthread_cond_wait(&free_slot, &mx_res);
}
resources++;
pthread_cond_signal(&item_ready);
pthread_mutex_unlock(&mx_res);
data--;
random_wait(1*10, 1*20);
}
return 0;
}
void * consumer(void * arg) {
struct tinfo * current_thread = arg;
printf("Mam do skonsumowania %d danych.\\n", current_thread->num);
int data = current_thread->num;
while (data > 0) {
pthread_mutex_lock(&mx_res);
while (resources == 0) {
lower_bound_blocked++;
pthread_cond_wait(&item_ready, &mx_res);
}
resources--;
pthread_cond_signal(&free_slot);
pthread_mutex_unlock(&mx_res);
data--;
random_wait(5*10, 5*20);
}
return 0;
}
int main(void) {
struct tinfo producers[5];
struct tinfo consumers[10];
int tmp;
srand(time(0));
printf("Losowanie dóbr...\\n");
for (int i = 0; i < 10; i++) {
consumers[i].num = 0;
}
for (int i = 0; i < 5; i++) {
producers[i].num = 0;
}
for (int i = 0; i < 50000; i++) {
tmp = rand() % 10;
consumers[tmp].num++;
tmp = rand() % 5;
producers[tmp].num++;
}
for (int i = 0; i < 10; i++) {
printf("%d ", consumers[i].num);
}
printf("\\n");
for (int i = 0; i < 5; i++) {
printf("%d ", producers[i].num);
}
printf("\\n");
printf("Start!\\n");
for (int i = 0; i < 10; i++) {
pthread_create(&consumers[i].id, 0, &consumer, &consumers[i]);
}
for (int i = 0; i < 5; i++) {
pthread_create(&producers[i].id, 0, &producer, &producers[i]);
}
for (int i = 0; i < 10; i++) {
pthread_join(consumers[i].id, 0);
}
for (int i = 0; i < 5; i++) {
pthread_join(producers[i].id, 0);
}
printf("Upper %d\\n", upper_bound_blocked);
printf("Lower %d\\n", lower_bound_blocked);
return 0;
}
| 0
|
#include <pthread.h>
void *f1();
void *f2();
int n;
int m;
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
main()
{
pthread_t thread1, thread2;
pthread_create( &thread1, 0, &f1, 0);
pthread_create( &thread2, 0, &f2, 0);
pthread_join( thread1, 0);
pthread_join( thread2, 0);
exit(0);
}
void *f1(void *arg)
{
int r;
m = 5;
pthread_mutex_lock( &count_mutex );
pthread_cond_wait( &condition_var, &count_mutex );
r = n + m;
printf("f1 = %d\\n", r);
return 0;
}
void *f2(void *arg)
{
int r;
n = 2;
r = m - n;
printf("f2 = %d\\n", r);
pthread_mutex_unlock( &count_mutex );
pthread_cond_signal( &condition_var );
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t r_mutex;
pthread_mutex_t mutex;
pthread_mutex_t writer_mutex;
int writer_count=0;
int shared_data=1;
pthread_t tid;
pthread_attr_t attr;
void *writer(void *param);
void *reader(void *param);
void *writer(void *param) {
while(1) {
pthread_mutex_lock(&mutex);
writer_count++;
if(writer_count==1)
pthread_mutex_lock(&r_mutex);
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&writer_mutex);
shared_data++;
printf("\\n(%07d) -- wrote: %05d",syscall(SYS_gettid),shared_data);
sleep(1);
pthread_mutex_unlock(&writer_mutex);
pthread_mutex_lock(&mutex);
writer_count--;
if(writer_count==0)
pthread_mutex_unlock(&r_mutex);
pthread_mutex_unlock(&mutex);
sleep(rand()%10+1);
}
}
void *reader(void *param) {
while(1) {
pthread_mutex_lock(&r_mutex);
printf("\\n(%07d) -- read: %05d",syscall(SYS_gettid),shared_data);
pthread_mutex_unlock(&r_mutex);
sleep(rand()%10+1);
}
}
int main(int argc, char *argv[]) {
srand(time(0));
if(argc != 4) {
fprintf(stderr, "USAGE:./main.out <INT> <INT> <INT>\\n");
exit(1);
}
int mainSleepTime = atoi(argv[1]);
int numWriter = atoi(argv[2]);
int numReader = atoi(argv[3]);
pthread_mutex_init(&r_mutex, 0);
pthread_mutex_init(&mutex, 0);
pthread_mutex_init(&writer_mutex, 0);
writer_count = 0;
pthread_t * thread = malloc ((numWriter+numReader)*sizeof(pthread_t));
int i;
for(i = 0; i < numWriter; i++) {
thread[i]=pthread_create(&tid,&attr,writer,0);
}
for(i = 0; i < numReader; i++) {
thread[numReader+i]=pthread_create(&tid,&attr,reader,0);
}
sleep(mainSleepTime);
printf("\\nExit the program\\n");
exit(0);
}
| 0
|
#include <pthread.h>
struct testdata
{
pthread_mutex_t mutex;
pthread_cond_t cond;
} td;
pthread_t thread1;
int t1_start = 0;
int signaled = 0;
void alarm_handler(int signo)
{
printf("Error: failed to wakeup thread\\n");
pthread_cancel(thread1);
exit(PTS_UNRESOLVED);
}
void *t1_func(void *arg)
{
int rc;
if (pthread_mutex_lock(&td.mutex) != 0) {
fprintf(stderr,"Thread1 failed to acquire mutex\\n");
exit(PTS_UNRESOLVED);
}
fprintf(stderr,"Thread1 started\\n");
t1_start = 1;
fprintf(stderr,"Thread1 is waiting for the cond\\n");
rc = pthread_cond_wait(&td.cond, &td.mutex);
if (rc != 0) {
fprintf(stderr,"pthread_cond_wait return %d\\n", rc);
exit(PTS_UNRESOLVED);
}
fprintf(stderr,"Thread1 wakened\\n");
if (signaled == 0) {
fprintf(stderr,"Thread1 did not block on the cond at all\\n");
printf("Test FAILED\\n");
exit(PTS_FAIL);
}
pthread_mutex_unlock(&td.mutex);
return 0;
}
int main()
{
struct sigaction act;
if (pthread_mutex_init(&td.mutex, 0) != 0) {
fprintf(stderr,"Fail to initialize mutex\\n");
return PTS_UNRESOLVED;
}
if (pthread_cond_init(&td.cond, 0) != 0) {
fprintf(stderr,"Fail to initialize cond\\n");
return PTS_UNRESOLVED;
}
if (pthread_create(&thread1, 0, t1_func, 0) != 0) {
fprintf(stderr,"Fail to create thread 1\\n");
return PTS_UNRESOLVED;
}
while(!t1_start)
usleep(100);
if (pthread_mutex_lock(&td.mutex) != 0) {
fprintf(stderr,"Main: Fail to acquire mutex\\n");
return PTS_UNRESOLVED;
}
if (pthread_mutex_unlock(&td.mutex) != 0) {
fprintf(stderr,"Main: Fail to release mutex\\n");
return PTS_UNRESOLVED;
}
sleep(2);
act.sa_handler=alarm_handler;
act.sa_flags=0;
sigemptyset(&act.sa_mask);
sigaction(SIGALRM, &act, 0);
alarm(5);
fprintf(stderr,"Time to wake up thread1 by signaling a condition\\n");
signaled = 1;
if (pthread_cond_signal(&td.cond) != 0) {
fprintf(stderr,"Main: Fail to signal cond\\n");
return PTS_UNRESOLVED;
}
pthread_join(thread1, 0);
printf("Test PASSED\\n");
return PTS_PASS;
}
| 1
|
#include <pthread.h>
pthread_mutex_t spoon[5];
void phil_init(int a, int* b, int* c)
{
*b=(a>0) ? a-1 : 5;
*c=a;
printf("Philosopher %d started\\n", a+1);
return;
}
int check_If_Spoons_Are_Available(int a, int b, int c)
{
int sum=0;
if(a&1) {
sum = pthread_mutex_trylock(&spoon[c])==0 ? 0 : 10;
sum += pthread_mutex_trylock(&spoon[b])==0 ? 0 : 1;
} else {
sum = pthread_mutex_trylock(&spoon[b])==0 ? 0 : 1;
sum += pthread_mutex_trylock(&spoon[c])==0 ? 0 : 10;
}
return sum;
}
void Release_Spoons(int a, int b, int c)
{
if(a&1) {
pthread_mutex_unlock(&spoon[b]);
pthread_mutex_unlock(&spoon[c]);
} else {
pthread_mutex_unlock(&spoon[c]);
pthread_mutex_unlock(&spoon[b]);
}
}
void wait_for_others_to_finish(int a, int b ,int c, int d)
{
switch( a ) {
case 1: printf("Philosopher %d waiting since right spoon is unavailable\\n",b+1);
pthread_mutex_lock(&spoon[c]);
break;
case 10: printf("Philosopher %d waiting since left spoon is unavailable\\n", b+1);
pthread_mutex_lock(&spoon[d]);
break;
case 11: printf("Philosopher %d waiting since both spoons are unavailable\\n", b+1);
if( a&1 ) {
pthread_mutex_lock(&spoon[d]);
pthread_mutex_lock(&spoon[c]);
} else {
pthread_mutex_lock(&spoon[d]);
pthread_mutex_lock(&spoon[c]);
}
break;
}
return;
}
void Eat(int a)
{
printf("philosopher %d eating\\n", a+1);
sleep(rand()%5);
printf("philosopher %d finished eating\\n", a+1);
}
void philo(void * arg)
{
int back;
int front;
int tmp;
int id=*((int*)arg);
phil_init(id, &back, &front);
while(1) {
printf("philosopher %d thinking\\n", id+1);
sleep(rand()%6);
if((tmp=check_If_Spoons_Are_Available(id, back, front))!=0)
wait_for_others_to_finish(tmp, id, back, front);
Eat(id);
Release_Spoons(*((int*)arg), back, front);
}
}
int main(int argc, char* argv[])
{
pthread_t S[5];
int *g;
for(int i=0; i<5; i++)
pthread_mutex_init(&spoon[i], 0);
g=(int*)malloc(5*sizeof(int));
for(int i=0; i<5; i++) {
g[i]=i;
pthread_create(&S[i], 0, (void*)&philo,(void*)&g[i]);
}
pthread_join(S[0], 0);
exit(0);
}
| 0
|
#include <pthread.h>
buffer_t buffer[10];
int buffer_index;
pthread_mutex_t buffer_mutex;
sem_t full_sem;
sem_t empty_sem;
void insertbuffer(buffer_t value) {
if (buffer_index < 10) {
buffer[buffer_index++] = value;
} else {
printf("Buffer overflow\\n");
}
}
buffer_t dequeuebuffer() {
if (buffer_index > 0) {
return buffer[--buffer_index];
} else {
printf("Buffer underflow\\n");
}
return 0;
}
int isempty() {
if (buffer_index == 0)
return 1;
return 0;
}
int isfull() {
if (buffer_index == 10)
return 1;
return 0;
}
void *producer2(void *thread_n) {
int thread_numb = *(int *)thread_n;
buffer_t value;
int i=0;
while (i++ < 2) {
sleep(rand() % 10);
value = rand() % 100;
pthread_mutex_lock(&buffer_mutex);
do {
pthread_mutex_unlock(&buffer_mutex);
sem_wait(&full_sem);
pthread_mutex_lock(&buffer_mutex);
} while (isfull());
insertbuffer(value);
pthread_mutex_unlock(&buffer_mutex);
sem_post(&empty_sem);
printf("Producer %d added %d to buffer\\n", thread_numb, value);
}
pthread_exit(0);
}
void *consumer2(void *thread_n) {
int thread_numb = *(int *)thread_n;
buffer_t value;
int i=0;
while (i++ < 2) {
pthread_mutex_lock(&buffer_mutex);
do {
pthread_mutex_unlock(&buffer_mutex);
sem_wait(&empty_sem);
pthread_mutex_lock(&buffer_mutex);
} while (isempty());
value = dequeuebuffer(value);
pthread_mutex_unlock(&buffer_mutex);
sem_post(&full_sem);
printf("Consumer %d dequeue %d from buffer\\n", thread_numb, value);
}
pthread_exit(0);
}
int main(int argc, int **argv) {
buffer_index = 0;
pthread_mutex_init(&buffer_mutex, 0);
sem_init(&full_sem,
0,
10);
sem_init(&empty_sem,
0,
0);
pthread_t thread[10];
int thread_numb[10];
int i;
for (i = 0; i < 10; ) {
thread_numb[i] = i;
pthread_create(thread + i,
0,
producer2,
thread_numb + i);
i++;
thread_numb[i] = i;
pthread_create(&thread[i],
0,
consumer2,
&thread_numb[i]);
i++;
}
for (i = 0; i < 10; i++)
pthread_join(thread[i], 0);
pthread_mutex_destroy(&buffer_mutex);
sem_destroy(&full_sem);
sem_destroy(&empty_sem);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int counter;
void* work_thread(void* tParam){
struct thread_data *myData;
myData=(struct thread_data *) tParam;
long me;
int radius, NUM_THREADS, xsize, ysize, part_start, part_length;
pixel* src;
pixel* halfway;
double w[3000];
NUM_THREADS = myData->started_threads;
me = myData->threadID;
radius = myData->radius;
xsize = myData->xsize;
ysize = myData->ysize;
src = myData->src;
halfway = myData->halfway;
calc_part(&part_start, &part_length, me, NUM_THREADS, ysize);
get_gauss_weights(radius,w);
blurfilter_part_1(xsize, src, radius, w, halfway, part_start, part_length);
pthread_mutex_lock(&mutex);
counter++;
pthread_cond_broadcast(&cond);
while(counter < NUM_THREADS){
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
blurfilter_part_2(xsize, ysize, src, radius, w, halfway, part_start, part_length);
return 0;
}
int main (int argc, char ** argv) {
int i, NUM_THREADS, xsize, ysize, colmax, radius, imagecounter;
double w[3000];
pixel* src;
pixel* halfway;
int init_id = 0;
struct timespec stop, start;
char *imagename, *filename, *outfile;
if (argc != 3) {
fprintf(stderr, "Usage: %s threads write_images(0 or 1)\\n", argv[0]);
exit(1);
}
NUM_THREADS = atoi(argv[1]);
for(imagecounter = 0; imagecounter<4; imagecounter++){
switch(imagecounter){
case 0:
imagename = "im1.ppm";
filename = "im1blur.txt";
outfile = "test1.ppm";
break;
case 1:
imagename = "im2.ppm";
filename = "im2blur.txt";
outfile = "test2.ppm";
break;
case 2:
imagename = "im3.ppm";
filename = "im3blur.txt";
outfile = "test3.ppm";
break;
case 3:
imagename = "im4.ppm";
filename = "im4blur.txt";
outfile = "test4.ppm";
break;
}
int ii;
for(ii=0;ii<10;ii++){
radius = pow(2,ii);
src = malloc(MAX_PIXELS*sizeof(*src));
halfway = malloc(MAX_PIXELS*sizeof(*src));
if(read_ppm (imagename, &xsize, &ysize, &colmax, (char *) src) != 0){
exit(1);
}
if (colmax > 255) {
fprintf(stderr, "Too large maximum color-component value\\n");
exit(1);
}
printf("Has read the image, starting time...\\n");
clock_gettime(CLOCK_REALTIME, &start);
pthread_t thread_handle[NUM_THREADS];
struct thread_data thread_data_array[NUM_THREADS];
for(i=0; i<NUM_THREADS; i++){
thread_data_array[i].xsize = xsize;
thread_data_array[i].ysize = ysize;
thread_data_array[i].radius = radius;
thread_data_array[i].src = src;
thread_data_array[i].halfway = halfway;
thread_data_array[i].started_threads = NUM_THREADS;
}
for(i=0; i<NUM_THREADS; i++) {
thread_data_array[i].threadID = i;
pthread_create(&thread_handle[i], 0, work_thread, &(thread_data_array[i]));
}
for(i=0; i<NUM_THREADS; i++) {
pthread_join(thread_handle[i], 0);
}
clock_gettime(CLOCK_REALTIME, &stop);
printf("Threads eliminated, filtering took: %g secs\\n", (stop.tv_sec - start.tv_sec) +
1e-9*(stop.tv_nsec - start.tv_nsec)) ;
printf("Writing output file...\\n");
if(argv[2] == 1){
if(write_ppm (outfile, xsize, ysize, (char *)src) != 0)
exit(1);
}
if(write_txt (filename, radius, ((stop.tv_sec - start.tv_sec) +
1e-9*(stop.tv_nsec - start.tv_nsec)), NUM_THREADS ) != 0)
exit(1);
}
}
return 0;
}
| 0
|
#include <pthread.h>
static int iter = 1000;
static int num_threads = 16;
void *thread_create(void *arg) {
return 0;
}
static inline void pthreads_bench_create() {
pthread_t tids[num_threads];
for (int i = 0; i < num_threads; i++) {
pthread_create(&tids[i], 0, thread_create, 0);
}
for (int i = 0; i < num_threads; i++) {
void *ret;
pthread_join(tids[i], &ret);
}
}
static pthread_mutex_t mutex_counter = PTHREAD_MUTEX_INITIALIZER;
void *thread_mutex(void *arg) {
pthread_mutex_lock(&mutex_counter);
(*((int *) arg))++;
pthread_mutex_unlock(&mutex_counter);
return arg;
}
static inline void pthreads_bench_mutex() {
pthread_t tids[num_threads];
int counter = 0;
for (int i = 0; i < num_threads; i++) {
pthread_create(&tids[i], 0, thread_mutex, &counter);
}
for (int i = 0; i < num_threads; i++) {
void *ret;
pthread_join(tids[i], &ret);
}
}
void *thread_sem(void *arg) {
sem_t *sem = (sem_t *) arg;
sem_wait(sem);
return arg;
}
static inline void pthreads_bench_sem() {
pthread_t tids[num_threads];
sem_t sem;
sem_init(&sem, 0, num_threads);
for (int i = 0; i < num_threads; i++) {
pthread_create(&tids[i], 0, thread_sem, &sem);
}
for (int i = 0; i < num_threads; i++) {
void *ret;
pthread_join(tids[i], &ret);
}
sem_destroy(&sem);
}
void usage(const char *command) {
fprintf(stderr, "Usage: %s [-i <iterations>] [-n <no. of threads>]\\n", command);
}
int main(int argc, char *argv[]) {
int ch;
while ((ch = getopt(argc, argv, "i:n:h?")) != -1) {
switch (ch) {
case 'i':
iter = atoi(optarg);
break;
case 'n':
num_threads = atoi(optarg);
break;
case '?':
case 'h':
usage(argv[0]);
break;
default:
break;
}
}
BENCH_OP(pthreads_bench_create);
BENCH_OP(pthreads_bench_mutex);
BENCH_OP(pthreads_bench_sem);
pthread_mutex_destroy(&mutex_counter);
}
| 1
|
#include <pthread.h>
int n_cats = 0;
int n_dogs = 0;
int n_birds = 0;
volatile int playingRecord[3] = {0};
clock_t start;
time_t gstart_t, gend_t;
double gdiff_t;
int gtimeProvided = 0;
volatile int catsinground = 0;
volatile int dogsinground = 0;
volatile int birdsinground = 0 ;
pthread_mutex_t lock;
pthread_cond_t CV_birdsPlaying;
pthread_cond_t CV_dogsPlaying;
pthread_cond_t CV_catsPlaying;
void cat_exit();
void dog_exit();
void bird_exit();
void play();
void* cat_enter(void *arg) {
time_t start_t, end_t;
time(&start_t);
int timeProvided = 10;
double diff_t;
while (1) {
int data = *(int*) arg;
pthread_mutex_lock(&lock);
while (dogsinground > 0) {
pthread_cond_wait(&CV_dogsPlaying, &lock);
}
while (birdsinground > 0) {
pthread_cond_wait(&CV_birdsPlaying, &lock);
}
playingRecord[data]++;
play();
catsinground++;
pthread_mutex_unlock(&lock);
time(&end_t);
diff_t = difftime(end_t, start_t);
if (diff_t > timeProvided) {
printf("Provided time = %d\\n", timeProvided);
printf("Execution time = %f\\n", diff_t);
cat_exit();
break;
}
cat_exit();
}
pthread_exit(0);
}
void* bird_enter(void *arg) {
time_t start_t, end_t;
time(&start_t);
int timeProvided = 10;
double diff_t;
while (1) {
int data = *(int*) arg;
pthread_mutex_lock(&lock);
while (catsinground > 0) {
pthread_cond_wait(&CV_catsPlaying, &lock);
}
play();
birdsinground++;
playingRecord[data]++;
pthread_mutex_unlock(&lock);
time(&end_t);
diff_t = difftime(end_t, start_t);
if (diff_t > timeProvided) {
printf("Provided time = %d\\n", timeProvided);
printf("Execution time = %f\\n", diff_t);
bird_exit();
break;
}
bird_exit();
}
pthread_exit(0);
}
void* dog_enter(void *arg) {
time_t start_t, end_t;
time(&start_t);
int timeProvided = 10;
double diff_t;
int data = *(int*) arg;
while (1) {
pthread_mutex_lock(&lock);
while (catsinground > 0) {
pthread_cond_wait(&CV_catsPlaying, &lock);
}
play();
playingRecord[data]++;
dogsinground++;
pthread_mutex_unlock(&lock);
time(&end_t);
diff_t = difftime(end_t, start_t);
if (diff_t > timeProvided) {
printf("Provided time = %d\\n", timeProvided);
printf("Execution time = %f\\n", diff_t);
printf("Exiting of the program...\\n");
dog_exit();
break;
}
dog_exit();
}
pthread_exit(0);
}
void cat_exit(void) {
pthread_mutex_lock(&lock);
if (catsinground > 0)
catsinground--;
if (catsinground == 0){
pthread_mutex_unlock(&lock);
pthread_cond_broadcast(&CV_catsPlaying);
} else {
pthread_mutex_unlock(&lock);
}
}
void dog_exit(void) {
pthread_mutex_lock(&lock);
if (dogsinground > 0)
dogsinground--;
if (dogsinground == 0) {
pthread_mutex_unlock(&lock);
pthread_cond_broadcast(&CV_dogsPlaying);
} else {
pthread_mutex_unlock(&lock);
}
}
void bird_exit(void) {
pthread_mutex_lock(&lock);
if (birdsinground > 0)
birdsinground--;
if (birdsinground == 0){
pthread_mutex_unlock(&lock);
pthread_cond_broadcast(&CV_birdsPlaying);
} else {
pthread_mutex_unlock(&lock);
}
}
void play(void) {
for (int i = 0; i < 10;i++) {
assert(catsinground >= 0 && catsinground <= n_cats);
assert(dogsinground >= 0 && dogsinground <= n_dogs);
assert(birdsinground >= 0 && birdsinground <= n_birds);
assert(catsinground == 0 || dogsinground == 0);
assert(catsinground == 0 || birdsinground == 0);
}
}
int main(int argc, char const *argv[]) {
if (argc <3) {
printf("%s\\n", "provide proper number of arguments");
exit(0);
}
n_cats = strtol(argv[1], 0, 10);
n_dogs = strtol(argv[2], 0, 10);
n_birds = strtol(argv[3], 0, 10);
pthread_t catThr[n_cats];
pthread_t dogThr[n_dogs];
pthread_t birdThr[n_birds];
int catThreadData[2] = {0};
int dogThreadData[2] = {1};
int birdThreadData[2] = {2};
time(&gstart_t);
int i,rc;
for (i = 0; i < n_cats; i++) {
if ((rc = pthread_create(&catThr[i], 0, cat_enter , &catThreadData[0])))
{
fprintf(stderr, "error:pthread creat, rc : %d\\n",rc);
return 1;
}
}
for (i = 0; i < n_dogs; i++) {
if ((rc = pthread_create(&dogThr[i], 0, dog_enter , &dogThreadData[0])))
{
fprintf(stderr, "error:pthread creat, rc : %d\\n",rc);
return 1;
}
}
for (i = 0; i < n_birds; i++) {
if ((rc = pthread_create(&birdThr[i], 0, bird_enter , &birdThreadData[0])))
{
fprintf(stderr, "error:pthread creat, rc : %d\\n",rc);
return 1;
}
}
for (i = 0; i < n_cats; ++i) {
pthread_join(catThr[i], 0);
}
for (i = 0; i < n_dogs; ++i) {
pthread_join(dogThr[i], 0);
}
for (i = 0; i < n_birds; ++i) {
pthread_join(birdThr[i], 0);
}
for (i = 0; i < 1; ++i) {
printf("Cats %d Entered CS : %d\\n",i , playingRecord[0]);
printf("dogs %d Entered CS : %d\\n",i , playingRecord[1]);
printf("birds %d Entered CS : %d\\n",i , playingRecord[2]);
}
return 0;
}
| 0
|
#include <pthread.h>
static int glob = 0;
static pthread_mutex_t mtx1 = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t mtx2 = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t mtx3 = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t mtx4 = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t mtx5 = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t mtx6 = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t mtx7 = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t mtx8 = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t mtx9 = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t mtx10 = PTHREAD_MUTEX_INITIALIZER;
static void *
threadFunc1(void *arg)
{
int loops = *((int* )arg);
int j,s;
pthread_mutex_lock(&mtx1);
pthread_mutex_lock(&mtx2);
glob += 1;
printf("in t1 glob = %d\\n", glob);
pthread_mutex_unlock(&mtx2);
pthread_mutex_unlock(&mtx1);
return 0;
}
static void *
threadFunc2(void *arg)
{
int loops = *((int* )arg);
int j,s;
pthread_mutex_lock(&mtx2);
pthread_mutex_lock(&mtx1);
glob += 1;
printf("in t2 glob = %d\\n", glob);
pthread_mutex_unlock(&mtx1);
pthread_mutex_unlock(&mtx2);
return 0;
}
static void *
threadFunc3(void *arg)
{
int loops = *((int* )arg);
int j,s;
pthread_mutex_lock(&mtx3);
pthread_mutex_lock(&mtx4);
glob += 1;
printf("in t1 glob = %d\\n", glob);
pthread_mutex_unlock(&mtx4);
pthread_mutex_unlock(&mtx3);
return 0;
}
static void *
threadFunc4(void *arg)
{
int loops = *((int* )arg);
int j,s;
pthread_mutex_lock(&mtx4);
pthread_mutex_lock(&mtx3);
glob += 1;
printf("in t1 glob = %d\\n", glob);
pthread_mutex_unlock(&mtx3);
pthread_mutex_unlock(&mtx4);
return 0;
}
static void *
threadFunc5(void *arg)
{
int loops = *((int* )arg);
int j,s;
pthread_mutex_lock(&mtx5);
pthread_mutex_lock(&mtx6);
glob += 1;
printf("in t2 glob = %d\\n", glob);
pthread_mutex_unlock(&mtx6);
pthread_mutex_unlock(&mtx5);
return 0;
}
static void *
threadFunc6(void *arg)
{
int loops = *((int* )arg);
int j,s;
pthread_mutex_lock(&mtx6);
pthread_mutex_lock(&mtx5);
glob += 1;
printf("in t1 glob = %d\\n", glob);
pthread_mutex_unlock(&mtx5);
pthread_mutex_unlock(&mtx6);
return 0;
}
static void *
threadFunc7(void *arg)
{
int loops = *((int* )arg);
int j,s;
pthread_mutex_lock(&mtx7);
pthread_mutex_lock(&mtx8);
glob += 1;
printf("in t1 glob = %d\\n", glob);
pthread_mutex_unlock(&mtx8);
pthread_mutex_unlock(&mtx7);
return 0;
}
static void *
threadFunc8(void *arg)
{
int loops = *((int* )arg);
int j,s;
pthread_mutex_lock(&mtx8);
pthread_mutex_lock(&mtx7);
glob += 1;
printf("in t2 glob = %d\\n", glob);
pthread_mutex_unlock(&mtx7);
pthread_mutex_unlock(&mtx8);
return 0;
}
static void *
threadFunc9(void *arg)
{
int loops = *((int* )arg);
int j,s;
pthread_mutex_lock(&mtx9);
pthread_mutex_lock(&mtx10);
glob += 1;
printf("in t1 glob = %d\\n", glob);
pthread_mutex_unlock(&mtx10);
pthread_mutex_unlock(&mtx9);
return 0;
}
static void *
threadFunc10(void *arg)
{
int loops = *((int* )arg);
int j,s;
pthread_mutex_lock(&mtx10);
pthread_mutex_lock(&mtx9);
glob += 1;
printf("in t1 glob = %d\\n", glob);
pthread_mutex_unlock(&mtx9);
pthread_mutex_unlock(&mtx10);
return 0;
}
int
main(int argc, char *argv[])
{
pthread_t t1, t2 , t3,t4 , t5 , t6,t7, t8 , t9,t10;
int loops, s;
loops = 100000;
s = pthread_create(&t1, 0, threadFunc1, &loops);
s = pthread_create(&t2, 0, threadFunc2, &loops);
s = pthread_create(&t3, 0, threadFunc3, &loops);
s = pthread_create(&t4, 0, threadFunc4, &loops);
s = pthread_create(&t5, 0, threadFunc5, &loops);
s = pthread_create(&t6, 0, threadFunc6, &loops);
s = pthread_create(&t7, 0, threadFunc7, &loops);
s = pthread_create(&t8, 0, threadFunc8, &loops);
s = pthread_create(&t9, 0, threadFunc9, &loops);
s = pthread_create(&t10, 0, threadFunc10, &loops);
printf("glob = %d\\n", glob);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t turno;
int leyendo, escribiendo, escritores;
void inicializar_le()
{
pthread_mutex_init(&lock, 0);
pthread_cond_init(&turno, 0);
leyendo = 0;
escribiendo = 0;
escritores = 0;
}
void entrada_lectores()
{
pthread_mutex_lock(&lock);
if (escritores) {
pthread_cond_wait(&turno, &lock);
}
while (escribiendo) {
pthread_cond_wait(&turno, &lock);
}
leyendo++;
pthread_mutex_unlock(&lock);
}
void salida_lectores()
{
pthread_mutex_lock(&lock);
leyendo--;
pthread_cond_broadcast(&turno);
pthread_mutex_unlock(&lock);
}
void entrada_escritores()
{
pthread_mutex_lock(&lock);
escritores++;
while (leyendo || escribiendo)
pthread_cond_wait(&turno, &lock);
escribiendo++;
escritores--;
pthread_mutex_unlock(&lock);
}
void salida_escritores()
{
pthread_mutex_lock(&lock);
escribiendo--;
pthread_cond_broadcast(&turno);
pthread_mutex_unlock(&lock);
}
void eliminar_le()
{
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&turno);
}
| 0
|
#include <pthread.h>
static bool baro_swing_available;
static int32_t baro_swing_raw;
static pthread_mutex_t baro_swing_mutex = PTHREAD_MUTEX_INITIALIZER;
static void *baro_read(void *data )
{
struct input_event ev;
ssize_t n;
int fd_sonar = open("/dev/input/baro_event", O_RDONLY);
if (fd_sonar == -1) {
printf("Unable to open baro event to read pressure\\n");
return 0;
}
while (TRUE) {
n = read(fd_sonar, &ev, sizeof(ev));
if (n == sizeof(ev) && ev.type == EV_ABS && ev.code == ABS_PRESSURE) {
pthread_mutex_lock(&baro_swing_mutex);
baro_swing_available = 1;
baro_swing_raw = ev.value;
pthread_mutex_unlock(&baro_swing_mutex);
}
}
return 0;
}
void baro_init(void)
{
baro_swing_available = 0;
baro_swing_raw = 0;
pthread_t baro_thread;
if (pthread_create(&baro_thread, 0, baro_read, 0) != 0) {
printf("[swing_board] Could not create baro reading thread!\\n");
}
}
void baro_periodic(void) {}
void baro_event(void)
{
pthread_mutex_lock(&baro_swing_mutex);
if (baro_swing_available) {
float pressure = 100.f * ((float)baro_swing_raw) / 4096.f;
AbiSendMsgBARO_ABS(BARO_BOARD_SENDER_ID, pressure);
baro_swing_available = 0;
}
pthread_mutex_unlock(&baro_swing_mutex);
}
| 1
|
#include <pthread.h>
char describe[20];
int size;
} Task_t, *Task_p;
static Task_p ptask = 0;
static pthread_mutex_t hasTaskLock;
static pthread_mutex_t noTaskLock;
static pthread_cond_t hasTaskCond;
static pthread_cond_t noTaskCond;
static void init() {
ptask = 0;
pthread_mutex_init(&hasTaskLock, 0);
pthread_mutex_init(&noTaskLock, 0);
pthread_cond_init(&hasTaskCond, 0);
pthread_cond_init(&noTaskCond, 0);
}
static void finalize() {
pthread_mutex_destroy(&hasTaskLock);
pthread_mutex_destroy(&noTaskLock);
pthread_cond_destroy(&hasTaskCond);
pthread_cond_destroy(&noTaskCond);
}
void* producer_thr(void* arg) {
static int counter = 1;
while (1) {
pthread_mutex_lock(&noTaskLock);
if (counter == 100) break;
while (ptask != 0) {
pthread_cond_wait(&noTaskCond, &noTaskLock);
}
ptask = (Task_p)malloc(sizeof(Task_t));
ptask->size = counter++;
pthread_mutex_unlock(&noTaskLock);
pthread_cond_broadcast(&hasTaskCond);
}
}
void* consumer_thr(void* arg) {
while (1) {
pthread_mutex_lock(&hasTaskLock);
while (ptask == 0) {
pthread_cond_wait(&hasTaskCond, &hasTaskLock);
}
printf("consumer: size is %d\\n", ptask->size);
free(ptask);
ptask = 0;
pthread_mutex_unlock(&hasTaskLock);
pthread_cond_broadcast(&noTaskCond);
}
}
int main() {
init();
atexit(finalize);
pthread_t tid1, tid2;
pthread_create(&tid1, 0, consumer_thr, 0);
pthread_create(&tid2, 0, producer_thr, 0);
pthread_join(tid1, 0);
return 0;
}
| 0
|
#include <pthread.h>
key_t key;
int shmid;
int *cnt;
enum {STATE1, STATE2, STATE3, STATE4} state = STATE1;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond3 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond4 = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t count_sem;
void *Count1(void *a)
{
unsigned int i, *myid;
myid = (unsigned int *) a;
for(i = 0; i < 1000000; i++) {
pthread_mutex_lock(&mutex);
while(state != STATE1)
pthread_cond_wait(&cond1, &mutex);
pthread_mutex_unlock(&mutex);
sem_wait(&count_sem);
*cnt = *cnt + 1;
*cnt = *cnt + 1;
*cnt = *cnt + 1;
*cnt = *cnt + 1;
*cnt = *cnt + 1;
sem_post(&count_sem);
pthread_mutex_lock(&mutex);
state = STATE2;
pthread_cond_signal(&cond2);
pthread_mutex_unlock(&mutex);
}
}
void *Count2(void *a)
{
unsigned int i, *myid;
myid = (unsigned int *) a;
for(i = 0; i < 1000000; i++) {
pthread_mutex_lock(&mutex);
while(state != STATE2)
pthread_cond_wait(&cond2, &mutex);
pthread_mutex_unlock(&mutex);
sem_wait(&count_sem);
*cnt = *cnt + 1;
*cnt = *cnt + 1;
*cnt = *cnt + 1;
*cnt = *cnt + 1;
*cnt = *cnt + 1;
sem_post(&count_sem);
pthread_mutex_lock(&mutex);
state = STATE3;
pthread_cond_signal(&cond3);
pthread_mutex_unlock(&mutex);
}
}
void *Count3(void *a)
{
unsigned int i, *myid;
myid = (unsigned int *) a;
for(i = 0; i < 1000000; i++) {
pthread_mutex_lock(&mutex);
while(state != STATE3)
pthread_cond_wait(&cond3, &mutex);
pthread_mutex_unlock(&mutex);
sem_wait(&count_sem);
*cnt = *cnt + 1;
*cnt = *cnt + 1;
*cnt = *cnt + 1;
*cnt = *cnt + 1;
*cnt = *cnt + 1;
sem_post(&count_sem);
pthread_mutex_lock(&mutex);
state = STATE4;
pthread_cond_signal(&cond4);
pthread_mutex_unlock(&mutex);
}
}
void *Count4(void *a)
{
unsigned int i, *myid;
myid = (unsigned int *) a;
for(i = 0; i < 1000000; i++) {
pthread_mutex_lock(&mutex);
while(state != STATE4)
pthread_cond_wait(&cond4, &mutex);
pthread_mutex_unlock(&mutex);
sem_wait(&count_sem);
*cnt = *cnt + 1;
*cnt = *cnt + 1;
*cnt = *cnt + 1;
*cnt = *cnt + 1;
*cnt = *cnt + 1;
sem_post(&count_sem);
pthread_mutex_lock(&mutex);
state = STATE1;
pthread_cond_signal(&cond1);
pthread_mutex_unlock(&mutex);
}
}
void sharedMemory()
{
if ((key = ftok("file", 'R')) == -1) {
perror("ftok");
exit(1);
}
if ((shmid = shmget(key, sizeof(pthread_t), 0644 | IPC_CREAT)) == -1) {
perror("shmget");
exit(1);
}
cnt = shmat(shmid, (void *)0, 0);
if (cnt == (int *)(-1)) {
perror("shmat");
exit(1);
}
*cnt = 0;
printf("segment contains: \\"%d\\"\\n", *cnt);
}
void dtachMemory() {
if (shmdt(cnt) == -1) {
perror("shmdt");
exit(1);
}
}
int main(int argc, char * argv[])
{
pthread_t tid[4];
sharedMemory();
int res = sem_init(&count_sem, 0, 1);
if(res < 0) {
perror("Semaphore initialization failed");
exit(0);
}
unsigned int i, id[4];
for(i = 0; i < 4; i++) {
id[i] = i+1;
}
pthread_create(&tid[0], 0, Count1, (void* ) &id[0]);
pthread_create(&tid[1], 0, Count2, (void* ) &id[1]);
pthread_create(&tid[2], 0, Count3, (void* ) &id[2]);
pthread_create(&tid[3], 0, Count4, (void* ) &id[3]);
for(i = 0; i < 4; i++) {
pthread_join(tid[i], 0);
}
if (*cnt != 5*4*1000000)
printf("\\n BOOM! cnt is [%d], should be %d\\n", *cnt, 5*4*1000000);
else
printf("\\n OK! cnt is [%d]\\n", *cnt);
sem_destroy(&count_sem);
dtachMemory();
pthread_exit(0);
}
| 1
|
#include <pthread.h>
struct foo{
int f_count;
pthread_mutex_t f_lock;
};
struct foo*
foo_alloc(void)
{
struct foo* fp;
if((fp = malloc(sizeof(struct foo))) != 0){
fp->f_count = 1;
if(pthread_mutex_init(&fp->f_lock, 0) != 0){
free(fp);
return 0;
}
}
return fp;
}
void
foo_hold(struct foo *fp)
{
pthread_mutex_lock(&fp->f_lock);
++fp->f_count;
pthread_mutex_unlock(&fp->f_lock);
}
void
foo_rele(struct foo *fp)
{
pthread_mutex_lock(&fp->f_lock);
if(--fp->f_count == 0){
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
}else{
pthread_mutex_unlock(&fp->f_lock);
}
}
| 0
|
#include <pthread.h>
const int start_size = 2048;
unsigned long long FILE_SIZE;
char *buf;
int num_threads;
int fd;
int read;
char *data;
volatile char *data1;
volatile int waiting_threads;
volatile int finished_threads;
volatile int size;
pthread_cond_t ready = PTHREAD_COND_INITIALIZER;
pthread_cond_t finish = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
volatile uint64_t doorbell[8 * 16];
void start_all_pthreads(void)
{
int i;
for (i = 0; i < num_threads; i++)
doorbell[i * 8] = 0x1;
}
bool all_pthreads_finished(void)
{
int i;
for (i = 0; i < num_threads; i++)
if (doorbell[i * 8] != 0x2)
return 0;
return 1;
}
inline bool pthread_can_start(int pid)
{
return (doorbell[pid * 8] == 0x1);
}
inline void signal_pthread_finished(int pid)
{
doorbell[pid * 8] = 0x2;
}
void *pthread_transfer(void *arg)
{
int pid = *(int *)arg;
unsigned long long count;
int unit = size / num_threads;
size_t offset = unit * pid;
int i;
char *data_begin;
while(1) {
unit = size / num_threads;
pthread_mutex_lock(&lock);
while (waiting_threads == 0)
pthread_cond_wait(&ready, &lock);
waiting_threads &= ~(1 << pid);
pthread_mutex_unlock(&lock);
data_begin = data1 + offset;
if (read)
memcpy(buf + offset, data_begin, unit);
else
mmx2_memcpy(data_begin, buf + offset, unit);
pthread_mutex_lock(&lock);
finished_threads |= 1 << pid;
pthread_mutex_unlock(&lock);
if (finished_threads == (1 << num_threads) - 1)
pthread_cond_signal(&finish);
}
pthread_exit(0);
return 0;
}
int main(int argc, char **argv)
{
pthread_t *pthreads;
int pids[16];
int i;
long long time;
size_t len;
char c = 'a';
char unit;
struct timespec start, end;
unsigned long long count;
FILE *output;
char fs_type[20];
char quill_enabled[40];
char file_size_num[20];
char filename[60];
if (argc < 7) {
printf("Usage: ./pthread_test_mmap $FS $QUILL $fops $num_threads $FILE_SIZE $filename\\n");
return 0;
}
strcpy(fs_type, argv[1]);
strcpy(quill_enabled, argv[2]);
if (!strcmp(argv[3], "read"))
read = 1;
else if (!strcmp(argv[3], "write"))
read = 0;
else {
printf("fops error!\\n");
return 0;
}
num_threads = atoi(argv[4]);
if (num_threads <= 0 || num_threads > 16)
num_threads = 1;
strcpy(file_size_num, argv[5]);
len = strlen(file_size_num);
unit = file_size_num[len - 1];
file_size_num[len - 1] = '\\0';
FILE_SIZE = atoll(file_size_num);
switch (unit) {
case 'K':
case 'k':
FILE_SIZE *= 1024;
break;
case 'M':
case 'm':
FILE_SIZE *= 1048576;
break;
case 'G':
case 'g':
FILE_SIZE *= 1073741824;
break;
default:
return 0;
break;
}
if (FILE_SIZE < (4UL * 1024 * 1024))
FILE_SIZE = (4UL * 1024 * 1024);
if (FILE_SIZE > 2147483648)
FILE_SIZE = 2147483648;
strcpy(filename, argv[6]);
output = fopen(filename, "a");
if (posix_memalign((void *)&buf, (4UL * 1024 * 1024), (4UL * 1024 * 1024)))
return 0;
fd = open("/mnt/ramdisk/test1", O_CREAT | O_RDWR, 0640);
data = (char *)mmap(0, FILE_SIZE, PROT_WRITE, MAP_SHARED | MAP_POPULATE, fd, 0);
data1 = data;
printf("warm up...\\n");
printf("warm up done.\\n");
pthreads = (pthread_t *)malloc(num_threads * sizeof(pthread_t));
for (i = 0; i < num_threads; i++) {
pids[i] = i;
pthread_create(pthreads + i, 0, pthread_transfer, (void *)(pids + i));
}
for (size = start_size; size <= (4UL * 1024 * 1024); size <<= 1) {
count = FILE_SIZE / size;
lseek(fd, 0, 0);
data1 = data;
clock_gettime(CLOCK_MONOTONIC, &start);
for (i = 0; i < count; i++) {
pthread_mutex_lock(&lock);
waiting_threads = (1 << num_threads) - 1;
finished_threads = 0;
pthread_mutex_unlock(&lock);
pthread_cond_broadcast(&ready);
pthread_mutex_lock(&lock);
while (finished_threads != (1 << num_threads) - 1) {
pthread_cond_wait(&finish, &lock);
}
pthread_mutex_unlock(&lock);
data1 += size;
}
clock_gettime(CLOCK_MONOTONIC, &end);
time = (end.tv_sec - start.tv_sec) * 1e9 + (end.tv_nsec - start.tv_nsec);
printf("%s: Size %d bytes,\\t %lld times,\\t %lld nanoseconds,\\t Bandwidth %f MB/s, latenct %lld nanoseconds.\\n", argv[3], size, count, time, FILE_SIZE * 1024.0 / time, time / count);
fprintf(output, "%s,%s,%s,%d,%d,%lld,%lld,%lld,%f\\n", fs_type, quill_enabled, argv[3], num_threads, size, FILE_SIZE, count, time, FILE_SIZE * 1.0 / time);
}
fclose(output);
close(fd);
for (i = 0; i < num_threads; i++) {
pthread_join(pthreads[i], 0);
}
free(buf);
free(pthreads);
munmap(data, FILE_SIZE);
return 0;
}
| 1
|
#include <pthread.h>
static void ping(void);
void
thread_ping(void *arg)
{
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t cond_mutex = PTHREAD_MUTEX_INITIALIZER;
struct timespec timeout;
while (1) {
ping();
timeout.tv_sec = time(0) + get_configei(get_config(),"base","checkinterval");
timeout.tv_nsec = 0;
pthread_mutex_lock(&cond_mutex);
pthread_cond_timedwait(&cond, &cond_mutex, &timeout);
pthread_mutex_unlock(&cond_mutex);
}
}
char *coin_ping()
{
char *extra_string ="coin_ping on going";
char *request;
safe_asprintf(&request,
"POST %s HTTP/1.0\\r\\n"
"User-Agent: EOTU %s\\r\\n"
"Content-Type:application/json\\r\\n"
"Host: %s\\r\\n"
"content-length:%d\\r\\n\\r\\n"
"%s",
get_configes(get_config(),"server","ping_path"),
VERSION,
get_configes(get_config(),"server","authserv_hostname"),strlen(extra_string),
extra_string);
return request;
}
char *coin_common(char *reponse,char *path,char *host)
{
char *request;
safe_asprintf(&request,
"POST %s HTTP/1.0\\r\\n"
"User-Agent: EOTU %s\\r\\n"
"Content-Type:application/json\\r\\n"
"Host: %s\\r\\n"
"content-length:%d\\r\\n\\r\\n"
"%s",
path,
VERSION,
host,strlen(reponse),
reponse);
return request;
}
void ping_handle(char *res)
{
debug(LOG_NOTICE, "Get Ping Response: \\r\\n%s \\r\\nhow to handle is on going\\r\\n" ,res);
}
static void ping(void)
{
char *request;
int sockfd;
static int authdown = 0;
sockfd = connect_auth_server();
if (sockfd == -1) {
if (!authdown) {
authdown = 1;
}
return;
}
request = coin_ping();
char *res;
res = http_get(sockfd,request);
pthread_t ponse;
int result = pthread_create(&ponse, 0, (void *)ping_handle, safe_strdup(res));
if (result != 0) {
debug(LOG_ERR, "FATAL: Failed to create a new thread (message_thread) - exiting");
return ;
}
pthread_detach(ponse);
return ;
}
| 0
|
#include <pthread.h>
int mediafirefs_unlink(const char *path)
{
printf("FUNCTION: unlink. path: %s\\n", path);
const char *key;
int retval;
struct mediafirefs_context_private *ctx;
ctx = fuse_get_context()->private_data;
pthread_mutex_lock(&(ctx->mutex));
key = folder_tree_path_get_key(ctx->tree, ctx->conn, path);
if (key == 0) {
fprintf(stderr, "key is NULL\\n");
pthread_mutex_unlock(&(ctx->mutex));
return -ENOENT;
}
retval = mfconn_api_file_delete(ctx->conn, key);
if (retval != 0) {
fprintf(stderr, "mfconn_api_file_create unsuccessful\\n");
pthread_mutex_unlock(&(ctx->mutex));
return -EAGAIN;
}
else
{
account_add_state_flags(ctx->account, ACCOUNT_FLAG_DIRTY_SIZE);
}
folder_tree_update(ctx->tree, ctx->conn, 1);
pthread_mutex_unlock(&(ctx->mutex));
return 0;
}
| 1
|
#include <pthread.h>
struct cyclic {
int type;
char *prefix;
unsigned nbackups;
unsigned maxsize;
unsigned period;
time_t period_start;
FILE *file;
pthread_mutex_t lock;
pthread_mutex_t mutex;
int flock;
};
static int cyc_check_open_file(struct cyclic *cyc);
static int cyc_open_periodic(struct cyclic *cyc);
static int cyc_open_filesize(struct cyclic *cyc);
struct cyclic * cyc_init_periodic(const char *prefix, unsigned period)
{
struct cyclic *cyc;
if(period == 0) return 0;
cyc = (struct cyclic *)malloc(sizeof(struct cyclic));
if(!cyc) goto out;
cyc->type = (1<<1);
cyc->prefix = strdup(prefix);
if(!cyc->prefix) goto out;
cyc->nbackups = -1;
cyc->maxsize = -1;
cyc->period = period;
cyc->period_start = 0;
cyc->file = 0;
if(pthread_mutex_init(&(cyc->lock), 0)) goto out;
if(pthread_mutex_init(&(cyc->mutex), 0)) goto out;
cyc->flock = 0;
return cyc;
out:
perror("cyc_init_periodic");
if(cyc && cyc->prefix) free(cyc->prefix);
if(cyc) free(cyc);
return 0;
}
struct cyclic * cyc_init_filesize(const char *prefix,
unsigned nbackups, unsigned maxsize)
{
struct cyclic *cyc;
if(maxsize == 0) return 0;
cyc = (struct cyclic *)malloc(sizeof(struct cyclic));
if(!cyc) goto out;
cyc->type = (1<<0);
cyc->prefix = strdup(prefix);
if(!cyc->prefix) goto out;
cyc->nbackups = nbackups;
cyc->maxsize = maxsize;
cyc->period = -1;
cyc->period_start = -1;
cyc->file = 0;
if(pthread_mutex_init(&(cyc->lock), 0)) goto out;
if(pthread_mutex_init(&(cyc->mutex), 0)) goto out;
cyc->flock = 0;
return cyc;
out:
perror("cyc_init_filesize");
if(cyc && cyc->prefix) free(cyc->prefix);
if(cyc) free(cyc);
return 0;
}
void cyc_destroy(struct cyclic *cyc)
{
if(cyc->file) {
int oldstate;
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
fclose(cyc->file);
pthread_setcancelstate(oldstate, &oldstate);
}
pthread_mutex_destroy(&(cyc->mutex));
free(cyc->prefix);
free(cyc);
}
int cyc_printf(struct cyclic *cyc, const char *fmt, ...)
{
char line[1024];
va_list ap;
int oldstate;
int cnt = 0;
__builtin_va_start((ap));
pthread_mutex_lock(&cyc->mutex);
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
if(cyc_check_open_file(cyc)) {
vsnprintf(line, 1024, fmt, ap);
cnt = fputs(line, cyc->file);
fflush(cyc->file);
}
pthread_setcancelstate(oldstate, &oldstate);
pthread_mutex_unlock(&cyc->mutex);
;
return cnt;
}
int cyc_vprintf(struct cyclic *cyc, const char *fmt, va_list ap)
{
char line[1024];
int oldstate;
int cnt = 0;
pthread_mutex_lock(&cyc->mutex);
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
if(cyc_check_open_file(cyc)) {
vsnprintf(line, 1024, fmt, ap);
cnt = fputs(line, cyc->file);
fflush(cyc->file);
}
pthread_setcancelstate(oldstate, &oldstate);
pthread_mutex_unlock(&cyc->mutex);
return cnt;
}
void cyc_flush(struct cyclic *cyc)
{
int oldstate;
pthread_mutex_lock(&cyc->mutex);
if(!cyc->file) {
pthread_mutex_unlock(&cyc->mutex);
return;
}
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
fflush(cyc->file);
pthread_setcancelstate(oldstate, &oldstate);
pthread_mutex_unlock(&cyc->mutex);
}
void cyc_file_lock(struct cyclic *cyc)
{
pthread_mutex_lock(&cyc->lock);
pthread_mutex_lock(&cyc->mutex);
cyc->flock = 1;
pthread_mutex_unlock(&cyc->mutex);
}
void cyc_file_unlock(struct cyclic *cyc)
{
pthread_mutex_lock(&cyc->mutex);
cyc->flock = 0;
pthread_mutex_unlock(&cyc->mutex);
pthread_mutex_unlock(&cyc->lock);
}
static int cyc_check_open_file(struct cyclic *cyc)
{
if(cyc->flock && cyc->file) return 1;
switch(cyc->type) {
case (1<<1): {
unsigned now = time(0);
if(!cyc->file || now-cyc->period_start > cyc->period) {
return cyc_open_periodic(cyc);
}
break;
}
case (1<<0): {
if(!cyc->file || ftell(cyc->file) > cyc->maxsize) {
return cyc_open_filesize(cyc);
}
break;
}
default: {
return 0;
break;
}
}
return 1;
}
static int cyc_open_periodic(struct cyclic *cyc)
{
if(cyc->file) fclose(cyc->file);
cyc->file = 0;
cyc->period_start = (time(0) / cyc->period) * cyc->period;
struct tm tm;
if(!gmtime_r(&cyc->period_start, &tm)) return 0;
char *fname = malloc(strlen(cyc->prefix) + 80);
if(!fname) return 0;
sprintf(fname, "%s.%04d%02d%02d%02d%02d%02d", cyc->prefix,
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
cyc->file = fopen(fname, "w");
free(fname);
if(!cyc->file) return 0;
setvbuf(cyc->file, 0, _IOLBF, 0);
return 1;
}
static int cyc_open_filesize(struct cyclic *cyc)
{
if(cyc->file) fclose(cyc->file);
cyc->file = 0;
int bufsz = strlen(cyc->prefix) + 80;
char *fname = malloc(bufsz);
if(!fname) return 0;
int i;
for(i = cyc->nbackups - 2; i >= 0; i--) {
fname[0] = '\\0';
sprintf(fname, "%s.%d", cyc->prefix, i);
if(access(fname, F_OK)) continue;
char *fnew = malloc(bufsz);
if(!fnew) goto out_fname;
fnew[0] = '\\0';
sprintf(fnew, "%s.%d", cyc->prefix, i+1);
rename(fname, fnew);
free(fnew);
}
fname[0] = '\\0';
sprintf(fname, "%s.0", cyc->prefix);
cyc->file = fopen(fname, "w");
free(fname);
if(!cyc->file) return 0;
if(setvbuf(cyc->file, 0, _IOLBF, 0));
return 1;
out_fname:
{ int tmp = errno;
free(fname);
errno = tmp; }
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t number_mutex;
int globalnumber=0;
void * write_globalnumber()
{
globalnumber += 1;
globalnumber += 1;
globalnumber += 1;
sleep(1);
globalnumber += 1;
globalnumber += 1;
globalnumber += 1;
printf("%da\\n",globalnumber);
printf("b\\n");
pthread_exit(0);
}
void* read_globalnumber()
{
int tmp;
pthread_mutex_lock(&number_mutex);
tmp=globalnumber;
printf("%dc\\n",tmp);
pthread_mutex_unlock(&number_mutex);
pthread_exit(0);
}
int main(void)
{
pthread_t thid1;
pthread_t thid2;
int tmp;
pthread_mutex_init(&number_mutex, 0);
printf("start\\n\\n");
pthread_create(&thid1, 0, (void *)write_globalnumber, 0);
pthread_create(&thid2, 0, (void *)read_globalnumber, 0);
sleep(1);
tmp=globalnumber;
printf("%d\\n",tmp);
sleep(5);
printf("\\n\\n");
return 0;
}
| 1
|
#include <pthread.h>
int thread_count;
long current_thread = 0;
pthread_mutex_t sequence_mutex;
pthread_cond_t ok_to_proceed;
void Usage(char* prog_name);
void *Thread_work(void* rank);
int main(int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
if (argc != 2) Usage(argv[0]);
thread_count = strtol(argv[1], 0, 10);
thread_handles = malloc (thread_count*sizeof(pthread_t));
pthread_mutex_init(&sequence_mutex, 0);
pthread_cond_init(&ok_to_proceed, 0);
for (thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread], (pthread_attr_t*) 0,
Thread_work, (void*) thread);
for (thread = 0; thread < thread_count; thread++) {
pthread_join(thread_handles[thread], 0);
}
pthread_mutex_destroy(&sequence_mutex);
pthread_cond_destroy(&ok_to_proceed);
free(thread_handles);
return 0;
}
void Usage(char* prog_name) {
fprintf(stderr, "usage: %s <number of threads>\\n", prog_name);
exit(0);
}
void *Thread_work(void* rank) {
long my_rank = (long) rank;
while(1) {
pthread_mutex_lock(&sequence_mutex);
if (current_thread == my_rank) {
printf("Hello from thread %ld of %d\\n", my_rank, thread_count);
fflush(stdout);
current_thread++;
pthread_cond_broadcast(&ok_to_proceed);
pthread_mutex_unlock(&sequence_mutex);
break;
} else {
while (pthread_cond_wait(&ok_to_proceed,
&sequence_mutex) != 0);
}
pthread_mutex_unlock(&sequence_mutex);
}
return 0;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.