text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
int counter, busy;
pthread_mutex_t mutex;
pthread_cond_t cv;
} control_t;
control_t control = {0, 1, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER};
void cleanup_handler(void *args)
{
control_t *s = (control_t *)args;
s->counter--;
printf("Cleanup handle: counter = %d. \\n", s->counter);
pthread_mutex_unlock(&(s->mutex));
}
void *my_thread(void *args)
{
pthread_cleanup_push(cleanup_handler, (void *)&control);
pthread_mutex_lock(&control.mutex);
control.counter++;
while(control.busy){
pthread_cond_wait(&control.cv, &control.mutex);
}
pthread_cleanup_pop(1);
}
int main(int argc, char **argv)
{
pthread_t thread_id[5];
int i;
void *result;
printf("Creating the threads. \\n");
for(i = 0; i < 5; i++)
pthread_create(&thread_id[i], 0, my_thread, 0);
sleep(5);
printf("Cancelling the threads. \\n");
for(i = 0; i < 5; i++){
pthread_cancel(thread_id[i]);
pthread_join(thread_id[i], &result);
if(result == PTHREAD_CANCELED)
printf("Thread was cancelled. \\n");
else
printf("Thread was not cancelled. \\n");
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int var = 1, num = 5;
pthread_mutex_t m_var, m_num;
void *tfn(void *arg)
{
int i = (int)arg;
if (i == 1) {
printf("*\\n");
pthread_mutex_lock(&m_var);
var = 22;
sleep(1);
pthread_mutex_lock(&m_num);
num = 66;
pthread_mutex_unlock(&m_var);
pthread_mutex_unlock(&m_num);
printf("----thread %d finish\\n", i);
pthread_exit(0);
} else if (i == 2) {
printf("**\\n");
pthread_mutex_lock(&m_num);
var = 33;
sleep(1);
pthread_mutex_lock(&m_var);
num = 99;
pthread_mutex_unlock(&m_var);
pthread_mutex_unlock(&m_num);
printf("----thread %d finish\\n", i);
pthread_exit(0);
}
return 0;
}
int main(void)
{
pthread_t tid1, tid2;
int ret1, ret2;
pthread_mutex_init(&m_var, 0);
pthread_mutex_init(&m_num, 0);
pthread_create(&tid1, 0, tfn, (void *)1);
pthread_create(&tid2, 0, tfn, (void *)2);
sleep(3);
printf("var = %d, num = %d\\n", var, num);
ret1 = pthread_mutex_destroy(&m_var);
ret2 = pthread_mutex_destroy(&m_num);
if (ret1 == 0 && ret2 == 0)
printf("------------destroy mutex finish\\n");
pthread_join(tid1, 0);
pthread_join(tid2, 0);
printf("------------join thread finish\\n");
return 0;
}
| 0
|
#include <pthread.h>
unsigned long long calls = 0, ticks = 0;
double sum = 0;
pthread_mutex_t calls_lock = PTHREAD_MUTEX_INITIALIZER;
static void timer_tick(union sigval _arg)
{
(void)_arg;
unsigned long long res;
pthread_mutex_lock(&calls_lock);
res = calls;
calls = 0;
pthread_mutex_unlock(&calls_lock);
double speed = (double)(res * SIZEOF_UINT64) / 1024.0;
sum += speed;
ticks++;
double avg_speed = sum / (double)ticks;
printf("Current speed: %1.3lf KiB/s\\tAverage speed: %1.3lf KiB/s\\n", speed, avg_speed);
}
int main(int argc, char** argv)
{
timer_t timer_info;
struct sigevent timer_event;
timer_event.sigev_notify = SIGEV_THREAD;
timer_event.sigev_notify_function = timer_tick;
timer_event.sigev_notify_attributes = 0;
struct itimerspec timer_time;
timer_time.it_interval.tv_sec = 1;
timer_time.it_interval.tv_nsec = 0;
timer_time.it_value.tv_sec = 1;
timer_time.it_value.tv_nsec = 0;
int opts;
unsigned int fast = 0;
struct option longopts[] =
{
{"fast", no_argument, 0, 'f'},
{0, 0, 0, 0}
};
while ((opts = getopt_long(argc, argv, "f", longopts, 0)) != -1)
switch (opts)
{
case 'f':
fast = 1;
break;
default:
fprintf(stderr, "Unknown option: %c\\n", opts);
exit(EX_USAGE);
break;
}
pfrng_init();
int cpus = 1;
printf("Using %d thread(s)\\n", cpus);
volatile uint64_t n ;
timer_create(CLOCK_REALTIME, &timer_event, &timer_info);
timer_settime(timer_info, 0, &timer_time, 0);
while (1)
{
if (fast)
n = pfrng_get_u64_fast();
else
n = pfrng_get_u64();
pthread_mutex_lock(&calls_lock);
calls++;
pthread_mutex_unlock(&calls_lock);
}
pfrng_done();
exit(EX_OK);
}
| 1
|
#include <pthread.h>
struct account {
double balance;
pthread_mutex_t mutex;
};
account *myacct;
void *threadMain(void *);
pthread_t *tids;
int numThreads;
int count;
int main(int argc, char **argv)
{
int i;
if (argc < 2) {
fprintf(stderr, "Usage: %s <numThreads> <iterations>\\n", argv[0]);
exit(1);
}
numThreads = atoi(argv[1]);
count = atoi(argv[2]);
if (numThreads > 32) {
fprintf(stderr, "Usage: %s Too many threads specified. Defaulting to 32.\\n", argv[0]);
numThreads = 32;
}
myacct = (account *) malloc(sizeof(account));
myacct->balance = 0.0;
pthread_mutex_init(&(myacct->mutex), 0);
printf("initial balance = %lf\\n", myacct->balance);
tids = (pthread_t *) malloc(sizeof(pthread_t)*numThreads);
for (i=0; i<numThreads; i++)
pthread_create(&tids[i], 0, threadMain, (void *) 0);
for (i=0; i<numThreads; i++)
pthread_join(tids[i], 0);
printf("final balance = %lf\\n", myacct->balance);
exit(0);
}
void *threadMain(void *arg)
{
int i;
int amount;
for (i=0; i<count; i++) {
amount = 1;
pthread_mutex_lock(&(myacct->mutex));
myacct->balance += amount;
pthread_mutex_unlock(&(myacct->mutex));
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER;
void *
thr_fn(void *arg)
{
int err, signo;
for (;;)
{
err = sigwait(&mask, &signo);
if (err != 0)
err_exit(err, "sigwait failed");
switch (signo)
{
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&waitloc);
return(0);
default:
printf("unexpected signal %d\\n", signo);
exit(1);
}
}
}
int
main(void)
{
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0)
err_exit(err, "SIG_BLOCK error");
err = pthread_create(&tid, 0, thr_fn, 0);
if (err != 0)
err_exit(err, "can’t create thread");
pthread_mutex_lock(&lock);
while (quitflag == 0)
pthread_cond_wait(&waitloc, &lock);
pthread_mutex_unlock(&lock);
quitflag = 0;
if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0)
err_sys("SIG_SETMASK error");
exit(0);
}
| 1
|
#include <pthread.h>
static void *threadMain(void *dummy);
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int numWaiting = 0;
int
main()
{
int x[10], i;
pthread_t t[10];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 1024 * 1024);
for (i = 0; i < 10 - 1; i++) {
x[i] = i;
if (pthread_create(&t[i], &attr, &threadMain, x + i) < 0) {
fprintf(stderr, "error creating thread: %s\\n", strerror(errno));
return -1;
}
}
x[10 - 1] = 10 - 1;
threadMain(x + 10 - 1);
return 0;
}
static void *
threadMain(void *_n)
{
int *n = (int *)_n;
int count = 0;
while (1) {
pthread_mutex_lock(&mutex);
if (numWaiting > 10 / 2) {
pthread_cond_signal(&cond);
}
numWaiting++;
pthread_cond_wait(&cond, &mutex);
numWaiting--;
pthread_mutex_unlock(&mutex);
if (count++ % 1000 == 0) {
printf("thread%3d: %8d\\n", *n, count / 1000);
}
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t condv;
int64_t size;
struct nu_free_cell* next;
} nu_free_cell;
static const int64_t CHUNK_SIZE = 65536;
static const int64_t CELL_SIZE = (int64_t)sizeof(nu_free_cell);
static nu_free_cell* nu_free_list = 0;
static int64_t nu_malloc_count = 0;
static int64_t nu_malloc_bytes = 0;
static int64_t nu_free_count = 0;
static int64_t nu_free_bytes = 0;
static int64_t nu_malloc_chunks = 0;
static int64_t nu_free_chunks = 0;
int64_t
nu_free_list_length()
{
pthread_mutex_lock(&mutex);
int len = 0;
for (nu_free_cell* pp = nu_free_list; pp != 0; pp = pp->next) {
len++;
}
pthread_mutex_unlock(&mutex);
return len;
}
void
nu_print_free_list()
{
pthread_mutex_lock(&mutex);
nu_free_cell* pp = nu_free_list;
printf("= Free list: =\\n");
for (; pp != 0; pp = pp->next) {
printf("%lx: (cell %ld %lx)\\n", (int64_t) pp, pp->size, (int64_t) pp->next);
}
pthread_mutex_unlock(&mutex);
}
void
nu_mem_print_stats()
{
fprintf(stderr, "\\n== nu_mem stats ==\\n");
fprintf(stderr, "malloc count: %ld\\n", nu_malloc_count);
fprintf(stderr, "malloc bytes: %ld\\n", nu_malloc_bytes);
fprintf(stderr, "free count: %ld\\n", nu_free_count);
fprintf(stderr, "free bytes: %ld\\n", nu_free_bytes);
fprintf(stderr, "malloc chunks: %ld\\n", nu_malloc_chunks);
fprintf(stderr, "free chunks: %ld\\n", nu_free_chunks);
fprintf(stderr, "free list length: %ld\\n", nu_free_list_length());
}
static
void
nu_free_list_coalesce()
{
nu_free_cell* pp = nu_free_list;
int free_chunk = 0;
while (pp != 0 && pp->next != 0) {
if (((int64_t)pp) + pp->size == ((int64_t) pp->next)) {
pp->size += pp->next->size;
pp->next = pp->next->next;
}
pp = pp->next;
}
}
static
void
nu_free_list_insert(nu_free_cell* cell)
{
if (nu_free_list == 0 || ((uint64_t) nu_free_list) > ((uint64_t) cell)) {
cell->next = nu_free_list;
nu_free_list = cell;
return;
}
nu_free_cell* pp = nu_free_list;
while (pp->next != 0 && ((uint64_t)pp->next) < ((uint64_t) cell)) {
pp = pp->next;
}
cell->next = pp->next;
pp->next = cell;
nu_free_list_coalesce();
}
static
nu_free_cell*
free_list_get_cell(int64_t size)
{
nu_free_cell** prev = &nu_free_list;
for (nu_free_cell* pp = nu_free_list; pp != 0; pp = pp->next) {
if (pp->size >= size) {
*prev = pp->next;
return pp;
}
prev = &(pp->next);
}
return 0;
}
static
nu_free_cell*
make_cell()
{
void* addr = mmap(0, CHUNK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
nu_free_cell* cell = (nu_free_cell*) addr;
nu_malloc_chunks += 1;
cell->size = CHUNK_SIZE;
return cell;
}
void*
hw11_malloc(size_t usize)
{
pthread_mutex_lock(&mutex);
int64_t size = (int64_t) usize;
int64_t alloc_size = size + sizeof(int64_t);
if (alloc_size < CELL_SIZE) {
alloc_size = CELL_SIZE;
}
nu_malloc_count += 1;
nu_malloc_bytes += alloc_size;
if (alloc_size > CHUNK_SIZE) {
void* addr = mmap(0, alloc_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
*((int64_t*)addr) = alloc_size;
nu_malloc_chunks += 1;
pthread_mutex_unlock(&mutex);
return addr + sizeof(int64_t);
}
nu_free_cell* cell = free_list_get_cell(alloc_size);
if (!cell) {
cell = make_cell();
}
int64_t rest_size = cell->size - alloc_size;
if (rest_size >= CELL_SIZE) {
void* addr = (void*) cell;
nu_free_cell* rest = (nu_free_cell*) (addr + alloc_size);
rest->size = rest_size;
nu_free_list_insert(rest);
}
*((int64_t*)cell) = alloc_size;
pthread_mutex_unlock(&mutex);
return ((void*)cell) + sizeof(int64_t);
}
void
hw11_free(void* addr)
{
pthread_mutex_lock(&mutex);
nu_free_cell* cell = (nu_free_cell*)(addr - sizeof(int64_t));
int64_t size = *((int64_t*) cell);
if (size > CHUNK_SIZE) {
nu_free_chunks += 1;
munmap((void*) cell, size);
}
else {
cell->size = size;
nu_free_list_insert(cell);
}
nu_free_count += 1;
nu_free_bytes += size;
pthread_mutex_unlock(&mutex);
}
void*
hw11_realloc(void* ptr, size_t size)
{
void* new_ptr;
if(size > 0) {
new_ptr = hw11_malloc(size);
pthread_mutex_lock(&mutex);
nu_free_cell* cell = (nu_free_cell*)(ptr - sizeof(int64_t));
int64_t size_old = *((int64_t*) cell);
memcpy(new_ptr, ptr, size_old);
pthread_mutex_unlock(&mutex);
}
hw11_free(ptr);
return new_ptr;
}
| 1
|
#include <pthread.h>
volatile int enqueued = 0;
volatile int dequeued = 0;
pthread_mutex_t queue_mutex;
pthread_cond_t queue_emptiness_cv;
void *consumer( void *arg )
{
intptr_t id = ( intptr_t ) arg;
while ( 1 ) {
pthread_mutex_lock( &queue_mutex );
while ( dequeued < 2 && enqueued == 0 ) {
printf( "Consumer ID = %d is going to sleep.\\n", id );
pthread_cond_wait( &queue_emptiness_cv, &queue_mutex );
printf( "Consumer ID = %d was woken up.\\n", id );
}
if ( dequeued == 2 ) {
pthread_mutex_unlock( &queue_mutex );
break;
}
assert( enqueued > 0 );
++dequeued;
--enqueued;
printf( "Consumer ID = %d dequeued an item.\\n", id );
pthread_mutex_unlock( &queue_mutex );
sleep( 1 );
}
return 0;
}
int main( void )
{
int i;
pthread_t * threads = ( pthread_t * )( malloc( sizeof( pthread_t ) * 2 ) );
if ( !threads )
return 1;
pthread_mutex_init( &queue_mutex, 0 );
pthread_cond_init ( &queue_emptiness_cv, 0 );
for ( i=0; i<2; i++ ) {
pthread_create( &threads[i], 0, consumer, ( void* )( intptr_t )( i+1 ) );
}
for ( i=0; i<2; i++ ) {
sleep(1);
pthread_mutex_lock( &queue_mutex );
enqueued++;
pthread_cond_signal( &queue_emptiness_cv );
pthread_mutex_unlock( &queue_mutex );
}
pthread_cond_broadcast( &queue_emptiness_cv );
for ( i=0; i<2; i++ ) {
pthread_join( threads[i], 0 );
}
assert( enqueued == 0 );
assert( dequeued == 2 );
pthread_mutex_destroy( &queue_mutex );
pthread_cond_destroy ( &queue_emptiness_cv );
free( threads );
return 0;
}
| 0
|
#include <pthread.h>
unsigned int counts[3] = {0,0,0};
pthread_mutex_t m;
char* fileName;
} child_t;
char* fileName;
int charType;
} grandchild_t;
void* child_thread_function(void*);
void* grandchild_thread_function(void*);
bool existsFile(char*);
int main(int argc, char* argv[]) {
if (argc < 2) {
fprintf(stderr, "ERROR: No files to read.\\n");
return 1;
}
int i = 0;
bool noFiles = 1;
for (i = 0; i < argc-1; i++) {
if (existsFile(argv[i+1])) {
noFiles = 0;
break;
} else {
fprintf(stderr, "ERROR: %s does not exist\\n", argv[i+1]);
}
}
if (noFiles == 1) {
return 1;
}
printf("THREAD %u: Program started (top-level thread)\\n", (unsigned int)pthread_self());
fflush(stdout);
pthread_t tid[argc-1];
for (i = 0; i < argc-1; i+=1) {
if (!existsFile(argv[i+1])) {
fprintf(stderr, "ERROR: %s does not exist\\n", argv[i+1]);
continue;
}
child_t* child = malloc(sizeof(child_t));
child->fileName = argv[i+1];
int rc = pthread_create(&tid[i], 0, child_thread_function, child);
if ( rc != 0 ) {
fprintf( stderr, "pthread_create() failed (%d): %s\\n",
rc, strerror( rc ) );
return 1;
}
printf("THREAD %u: Created child thread for %s\\n", (unsigned int)pthread_self(), argv[i+1]);
fflush(stdout);
}
unsigned int ** x = malloc (3*sizeof(int*));
for (i = 0; i < argc-1; i++) {
pthread_join( tid[i], (void **)&x );
counts[0] += *x[0];
counts[1] += *x[1];
counts[2] += *x[2];
}
free(x);
printf("THREAD %u: All files contain %d alnum, %d space, and %d other characters\\n",
(unsigned int)pthread_self(), counts[0], counts[1], counts[2]);
fflush(stdout);
printf("THREAD %u: Program ended (top-level thread)\\n", (unsigned int)pthread_self());
fflush(stdout);
return 0;
}
void* child_thread_function(void* arg) {
child_t* child = (child_t*) arg;
printf("THREAD %u: Processing %s (created three child threads)\\n", (unsigned int)pthread_self(), child->fileName);
fflush(stdout);
int j = 0;
pthread_t gtid[3];
int** c = malloc(3*sizeof(unsigned int));
for (j = 0; j < 3; j++) {
grandchild_t* grandchild = malloc(sizeof(grandchild_t));
grandchild->fileName = child->fileName;
grandchild->charType = j;
int rc = pthread_create(>id[j], 0, grandchild_thread_function, grandchild);
if ( rc != 0 ) {
fprintf( stderr, "pthread_create() failed (%d): %s\\n",
rc, strerror( rc ) );
exit(1);
}
}
int** x = malloc(sizeof(int*));
for (j = 0; j < 3; j++) {
pthread_join( gtid[j], (void**)x );
c[j] = *x;
}
free(x);
printf("THREAD %u: File %s contains %d alnum, %d space, and %d other characters\\n", (unsigned int)pthread_self(),
child->fileName, *c[0], *c[1], *c[2]);
pthread_exit(c);
}
void* grandchild_thread_function(void* arg) {
pthread_mutex_lock(&m);
grandchild_t* grandchild = (grandchild_t*) arg;
char* types[3] = {"alphanumeric", "whitespace", "other"};
FILE* fp = fopen(grandchild->fileName, "r");
if (fp == 0) {
fprintf(stderr, "ERROR: Could not open %s\\n", grandchild->fileName);
exit(1);
}
int* count = malloc(sizeof(int));
*count = 0;
char c;
while (!feof(fp)) {
c = fgetc(fp);
if (grandchild->charType == 0 && isalnum(c)) {
*count += 1;
} else if (grandchild->charType == 1 && isspace(c)) {
*count += 1;
} else if (grandchild->charType == 2 && !isalnum(c) && !isspace(c)) {
*count += 1;
}
}
if (grandchild->charType == 2) {
*count -= 1;
}
if (fclose(fp) != 0) {
fprintf(stderr, "ERROR: Could not close %s\\n", grandchild->fileName);
exit(1);
}
printf("THREAD %u: Added %s count of %d to totals (then exiting)\\n", (unsigned int)pthread_self(), types[grandchild->charType], *count);
fflush(stdout);
pthread_mutex_unlock(&m);
pthread_exit(count);
}
bool existsFile(char* fileName) {
FILE * file = fopen(fileName, "r");
if (file == 0) {
return 0;
} else {
fclose(file);
return 1;
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_barrier_t barrier;
static int shared = 0;
static inline void acquire_lock()
{
pthread_mutex_lock(&lock);
}
static inline void release_lock()
{
pthread_mutex_unlock(&lock);
}
void *thread_func(void *arg)
{
int i;
pthread_barrier_wait(&barrier);
for (i = 0; i < (10 * 1000000); i++)
{
acquire_lock();
release_lock();
}
return 0;
}
int main(void)
{
pthread_t threads[2];
int i, rc;
pthread_mutex_init(&lock, 0);
pthread_barrier_init(&barrier, 0, 2);
for (i = 0; i < 2; i++){
rc = pthread_create(&threads[i], 0, thread_func, &i);
DIE(rc == -1, "pthread_create");
}
for (i = 0; i < 2; i++){
rc = pthread_join(threads[i], 0);
DIE(rc == -1, "pthread_join");
}
printf("Mutex version - shared = %d\\n", shared);
pthread_mutex_destroy(&lock);
pthread_barrier_destroy(&barrier);
return 0;
}
| 0
|
#include <pthread.h>
static char *amconfigs[MAX_CONFIG] = {0};
static int amconfig_inited = 0;
static pthread_mutex_t config_lock;
static char *malloc_config_item()
{
return malloc(CONFIG_PATH_MAX + CONFIG_VALUE_MAX + 8);
}
static void free_config_item(char *item)
{
free(item);
}
static int get_matched_index(const char * path)
{
int len = strlen(path);
char *ppath;
int i;
if (len >= CONFIG_PATH_MAX) {
return -40;
}
for (i = 0; i < MAX_CONFIG; i++) {
ppath = amconfigs[i];
if (ppath)
;
if (ppath != 0 && strncmp(path, ppath, len) == 0) {
return i;
}
}
return -10;
}
static int get_unused_index(const char * path)
{
int i;
for (i = 0; i < MAX_CONFIG; i++) {
if (amconfigs[i] == 0) {
return i;
}
}
return -20;
}
int am_config_init(void)
{
pthread_mutex_init(&config_lock,0);
pthread_mutex_lock(&config_lock);
memset(amconfigs, 0, sizeof(amconfigs));
amconfig_inited = 1;
pthread_mutex_unlock(&config_lock);
return 0;
}
int am_getconfig(const char * path, char *val, const char * def)
{
int i;
if (!amconfig_inited) {
am_config_init();
}
pthread_mutex_lock(&config_lock);
i = get_matched_index(path);
if (i >= 0) {
strcpy(val, amconfigs[i] + CONFIG_VALUE_OFF);
} else if (def != 0) {
strcpy(val, def);
}
pthread_mutex_unlock(&config_lock);
return i >= 0 ? 0 : i;
}
int am_setconfig(const char * path, const char *val)
{
int i;
char **pppath, *pconfig;
char value[CONFIG_VALUE_MAX];
char *setval = 0;
int ret = -1;
if (!amconfig_inited) {
am_config_init();
}
if (strlen(path) > CONFIG_PATH_MAX) {
return -1;
}
if (val != 0) {
setval = strdup(val);
setval[CONFIG_VALUE_MAX] = '\\0';
}
pthread_mutex_lock(&config_lock);
i = get_matched_index(path);
if (i >= 0) {
pppath = &amconfigs[i];
if (!setval || strlen(setval) == 0) {
free_config_item(*pppath);
amconfigs[i] = 0;
ret = 1;
goto end_out;
}
} else {
i = get_unused_index(path);
if (i < 0) {
ret = i;
goto end_out;
}
if (!setval || strlen(setval) == 0) {
ret = 1;
goto end_out;
}
;
pppath = &amconfigs[i];
*pppath = malloc_config_item();
if (!*pppath) {
ret = -4;
goto end_out;
}
}
pconfig = *pppath;
strcpy(pconfig, path);
strcpy(pconfig + CONFIG_VALUE_OFF, setval);
ret = 0;
end_out:
free(setval);
pthread_mutex_unlock(&config_lock);
return ret;
}
int am_dumpallconfigs(void)
{
int i;
char *config;
pthread_mutex_lock(&config_lock);
for (i = 0; i < MAX_CONFIG; i++) {
config = amconfigs[i];
if (config != 0) {
fprintf(stderr, "[%d] %s=%s\\n", i, config, config + CONFIG_VALUE_OFF);
}
}
pthread_mutex_unlock(&config_lock);
return 0;
}
int am_setconfig_float(const char * path, float value)
{
char buf[CONFIG_VALUE_MAX];
int len;
len = snprintf(buf, CONFIG_VALUE_MAX - 1, "%f", value);
buf[len] = '\\0';
return am_setconfig(path, buf);
}
int am_getconfig_float(const char * path, float *value)
{
char buf[CONFIG_VALUE_MAX];
int ret = -1;
*value = -1.0;
ret = am_getconfig(path, buf, "-1");
if (ret == 0) {
ret = sscanf(buf, "%f", value);
}
return ret > 0 ? 0 : -2;
}
int am_getconfig_bool(const char * path)
{
char buf[CONFIG_VALUE_MAX];
int ret = -1;
ret = am_getconfig(path, buf, "false");
if (ret == 0) {
if(strcasecmp(buf,"true")==0 || strcmp(buf,"1")==0)
return 1;
}
return 0;
}
| 1
|
#include <pthread.h>
void *searchfile(void *);
char *pattern;
pthread_t fileThreadsCall[50];
pthread_mutex_t mutexfile=PTHREAD_MUTEX_INITIALIZER;
void *searchfile(void *filename){
FILE *fileptr;
char *tmpfilename=filename;
char line[1000];
if ( (fileptr=fopen(tmpfilename,"r")) == 0){
perror("Thread failed to open file");
exit (1);
}
void *match;
int numMatchlines=match;
numMatchlines=0;
while ( !(feof(fileptr)) ){
fgets(line,1024,fileptr);
strstr(line,pattern);
if ((strstr(line,pattern))!= 0){
pthread_mutex_lock(&mutexfile);
fprintf(stdout,"Filename %s at Line: %s \\n", tmpfilename, line);
pthread_mutex_unlock(&mutexfile);
numMatchlines++;
}
}
if ( fclose(fileptr) == EOF )
perror("Failed to close file descriptor");
printf("File: %s has a total number of %d matchlines \\n", tmpfilename, numMatchlines);
pthread_exit((void*)filename);
return numMatchlines;
}
int main(int argc, char**argv){
if (argc<2){
errno=EINVAL;
exit (1);
}
int fileNum=argc-2;
pattern=argv[1];
void *status;
pthread_attr_t attr;
void *filename;
char **files=calloc(fileNum, sizeof(char*));
int k;
for (k=0; k<fileNum; k++)
files[k]=malloc(fileNum*sizeof(char));
int numarg;
for (numarg=0; numarg<fileNum; numarg++)
files[numarg]=filename;
int y;
for (y=0; y<fileNum; y++)
files[y]=argv[2+y];
pthread_mutex_init(&mutexfile, 0);
int i;
for (i=0; i<fileNum ; i++){
if ( (pthread_create(&fileThreadsCall[i],0,searchfile,(void*)files[i])) != 0)
perror("Cannot create pthread \\n");
fprintf(stdout,"Filename %s \\n", files[i]);
}
int j;
int threadretval[fileNum];
for (j=0; j<fileNum; j++){
if ( (threadretval[j]=pthread_join(fileThreadsCall[j], &status)) != 0)
perror("pthread_join doesn't work \\n");
fprintf(stdout, "Thread join successfully with return value: %d \\n", threadretval[j]);
}
pthread_mutex_destroy(&mutexfile);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int NumProcs;
pthread_mutex_t SyncLock;
pthread_cond_t SyncCV;
int SyncCount;
pthread_mutex_t ThreadLock;
int Count;
int num_threads=0;
int **grid;
int xdim;
int ydim;
int timesteps;
void Barrier()
{
int ret;
pthread_mutex_lock(&SyncLock);
SyncCount++;
if(SyncCount == num_threads) {
ret = pthread_cond_broadcast(&SyncCV);
SyncCount = 0;
assert(ret == 0);
} else {
ret = pthread_cond_wait(&SyncCV, &SyncLock);
assert(ret == 0);
}
pthread_mutex_unlock(&SyncLock);
}
void* ThreadLoop(void* tmp)
{
int threadId = *((int*) tmp);
int ret;
int startTime, endTime;
int i,j,k;
for(k=0;k<timesteps;k++){
for(j=1+threadId;j<ydim-1;j+=num_threads)
for(i=1;i<xdim-1;i++){
if(k%2==1){
if((i+j)%2==0){
grid[j][i] = (grid[j-1][i] + grid[j][i-1] + grid[j][i] + grid[j][i+1] + grid[j+1][i]) / 5;
}
}
else{
if((i+j)%2!=0){
grid[j][i] = (grid[j-1][i] + grid[j][i-1] + grid[j][i] + grid[j][i+1] + grid[j+1][i]) / 5;
}
}
}
Barrier();
}
}
void ocean (int **grid_rec, int xdim_rec, int ydim_rec, int timesteps_rec, int num_threads_rec)
{
grid = grid_rec;
xdim = xdim_rec;
ydim = ydim_rec;
timesteps = timesteps_rec;
pthread_t* threads;
pthread_attr_t attr;
int ret;
int dx;
num_threads = num_threads_rec;
threads = (pthread_t *) malloc(sizeof(pthread_t) * num_threads);
assert(threads != 0);
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
ret = pthread_mutex_init(&SyncLock, 0);
assert(ret == 0);
ret = pthread_mutex_init(&ThreadLock, 0);
assert(ret == 0);
ret = pthread_cond_init(&SyncCV, 0);
assert(ret == 0);
SyncCount = 0;
Count = 0;
int thread_arg[num_threads];
for(dx=0; dx < num_threads; dx++) {
thread_arg[dx]=dx;
ret = pthread_create(&threads[dx], &attr, ThreadLoop, (void*)(thread_arg+dx));
assert(ret == 0);
}
for(dx=0; dx < num_threads; dx++) {
ret = pthread_join(threads[dx], 0);
assert(ret == 0);
}
pthread_mutex_destroy(&ThreadLock);
pthread_mutex_destroy(&SyncLock);
pthread_cond_destroy(&SyncCV);
pthread_attr_destroy(&attr);
}
| 1
|
#include <pthread.h>
struct paramA{
int sock;
int nb_processus;
char ** processus;
};
struct paramB{
int sock;
char * com;
};
struct paramC{
char * mes;
};
struct paramD{
int sock;
};
pthread_mutex_t verrou;
int initSocketClient(char *host, short port){
int sock, val;
struct sockaddr_in serv;
sock=socket(AF_INET, SOCK_STREAM,0);
if (sock==-1) {
printf("Erreur d'utilisation de la fonction socket\\n");
return -1;
}
struct hostent * info;
info=gethostbyname(host);
serv.sin_family=AF_INET;
serv.sin_port=htons(port);
serv.sin_addr.s_addr=*((uint32_t *)info->h_addr);
val=connect(sock, (struct sockaddr *) &serv, sizeof(struct sockaddr_in));
if (val==-1) {
printf("Erreur d'utilisation de la fonction connect\\n");
return -1;
}
return sock;
}
void * Alerte(void *par){
struct paramA *argj=(struct paramA *)par;
int alerte=1;
int j,h,ok=1;
int i=0;
FILE * fp;
char * msg;
char buf[5];
int actif[(*argj).nb_processus];
while(alerte){
sleep(30);
pthread_mutex_lock(&verrou);
for(j=0 ;j<(*argj).nb_processus ; j++){
asprintf(&msg,"ps -e | grep -w '%s' | cut -d\\":\\" -f3 | cut -d\\" \\" -f2 | wc -l",(*argj).processus[j]);
fp=popen(msg,"r");
while( fgets(buf,sizeof buf,fp) != 0 && ok) {
if(buf[i]!='0'){
actif[j]=1;
ok=0;
}
else{
actif[j]=0;
}
i++;
}
ok=1;
i=0;
pclose(fp);
}
j=0;
for(h=0;h<(*argj).nb_processus;h++){
if(actif[h]){
printf("%i",actif[h]);
write((*argj).sock,"A",1);
write((*argj).sock,(*argj).processus[h],sizeof((*argj).processus[h]));
}
}
pthread_mutex_unlock(&verrou);
}
}
void * Controle(void *par){
struct paramB *argj=(struct paramB *)par;
pthread_mutex_lock(&verrou);
write((*argj).sock,"C",1);
FILE * pf;
char * msg;
asprintf(&msg,"%s",(*argj).com);
pf = popen(msg,"r");
char * str2=malloc(sizeof(*str2));
char * str3="";
while(fscanf(pf,"%s",str2) != EOF){
asprintf(&str3,"%s %s",str3,str2);
}
write((*argj).sock,str3,strlen(str3));
pclose(pf);
pthread_mutex_unlock(&verrou);
}
void * Message(void *par){
struct paramC *argj=(struct paramC *)par;
pthread_mutex_lock(&verrou);
printf("%s",(*argj).mes);
pthread_mutex_unlock(&verrou);
}
void Visuelle(void *par){
struct paramD *argj=(struct paramD *)par;
while(1){
sleep(60);
pthread_mutex_lock(&verrou);
system("DISPLAY=:0.0 import -window root screenshot.jpg");
pthread_mutex_unlock(&verrou);
}
}
int main(int args, char *arg[]){
int sock;
sock=initSocketClient(arg[1], atoi(arg[2]));
if (sock==-1) return -1;
char * processus[10];
processus[0]="firefox";
processus[1]="evince";
processus[2]="emacs";
int nb_processus=3;
pthread_t th1,th2,th3,th4;
struct paramA *pa=(struct paramA *)malloc(sizeof(struct paramA));
(*pa).sock=sock;
(*pa).nb_processus=nb_processus;
(*pa).processus=processus;
char * com="date";
struct paramB *pb=(struct paramB *)malloc(sizeof(struct paramB));
(*pb).sock=sock;
(*pb).com=com;
char * mes="Ceci est le test de la fonction Message \\n";
struct paramC *pc=(struct paramC *)malloc(sizeof(struct paramC));
(*pc).mes=mes;
struct paramD *pd=(struct paramD *)malloc(sizeof(struct paramD));
(*pd).sock=sock;
pthread_mutex_init(&verrou, 0);
pthread_create(&th1, 0,Alerte,(void *)pa);
pthread_create(&th2, 0,Controle,(void *)pb);
pthread_create(&th3, 0,Message,(void *)pc);
pthread_create(&th4, 0,Visuelle,(void *)pd);
pthread_join(th3,0);
pthread_join(th2,0);
pthread_join(th1,0);
pthread_join(th4,0);
pthread_mutex_destroy(&verrou);
close(sock);
return 0;
}
| 0
|
#include <pthread.h>
void usage(void)
{
printf("getopt [-d?] [-c count]\\n");
errno = 0;
}
int
main(int argc, char **argv)
{
struct timeval starttime, endtime;
pthread_mutex_t lock;
int count = 1000000;
int debug = 0;
int i;
char word[256];
extern int optind, opterr;
extern char *optarg;
while ((word[0] = getopt(argc, argv, "c:d?")) != (char)EOF) {
switch (word[0]) {
case 'd':
debug++;
break;
case 'c':
count = atoi(optarg);
break;
case '?':
usage();
return(OK);
default:
usage();
return(NOTOK);
}
}
pthread_mutex_init(&lock, 0);
if (gettimeofday(&starttime, 0)) {
perror ("gettimeofday");
return 1;
}
for (i = 0; i < count; i++) {
pthread_mutex_lock(&lock);
pthread_mutex_unlock(&lock);
}
if (gettimeofday(&endtime, 0)) {
perror ("gettimeofday");
return 1;
}
printf("%d mutex locks/unlocks no contention took %ld usecs.\\n", count,
(endtime.tv_sec - starttime.tv_sec) * 1000000 +
(endtime.tv_usec - starttime.tv_usec));
return 0;
}
| 1
|
#include <pthread.h>
unsigned long val = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *fun1(void *args)
{
unsigned long i = 0;
printf("thread id: %lu args: %s\\n", pthread_self(), (char*)args);
pthread_mutex_lock(&mutex);
for (i = 0; i < 1000000; i++)
val++;
printf("thread 1 val = %lu\\n", val);
pthread_mutex_unlock(&mutex);
pthread_exit((void*)0x1);
}
void *fun2(void *args)
{
unsigned long i = 0;
printf("thread id: %lu args: %s\\n", pthread_self(), (char*)args);
for (i = 0; i < 1000000; i++)
{
pthread_mutex_lock(&mutex);
val++;
pthread_mutex_unlock(&mutex);
}
printf("thread 2 val = %lu\\n", val);
pthread_exit((void*)0x2);
}
int main(void)
{
void *val = 0;
pthread_t tid[2];
pthread_create(&tid[0], 0, fun1, "thread 1");
pthread_create(&tid[1], 0, fun2, "thread 2");
if (pthread_join(tid[0], &val) != 0)
{
printf("join 线程1失败....\\n");
}
if (pthread_join(tid[1], &val) != 0)
{
printf("join 线程2失败....\\n");
}
if (pthread_mutex_destroy(&mutex) != 0)
{
printf("销毁信号量失败....\\n");
}
return 0;
}
| 0
|
#include <pthread.h>
struct prodcons
{
int buffer[16];
pthread_mutex_t lock;
int readpos, writepos;
pthread_cond_t notempty;
pthread_cond_t notfull;
};
void init(struct prodcons *b)
{
pthread_mutex_init(&b->lock, 0);
pthread_cond_init(&b->notempty, 0);
pthread_cond_init(&b->notfull, 0);
b->readpos = 0;
b->writepos = 0;
}
void put(struct prodcons *b, int data)
{
pthread_mutex_lock(&b->lock);
if ((b->writepos + 1) % 16 == b->readpos)
{
pthread_cond_wait(&b->notfull, &b->lock);
}
b->buffer[b->writepos] = data;
b->writepos++;
if (b->writepos >= 16)
b->writepos = 0;
pthread_cond_signal(&b->notempty);
pthread_mutex_unlock(&b->lock);
}
int get(struct prodcons *b)
{
int data;
pthread_mutex_lock(&b->lock);
if (b->writepos == b->readpos)
{
pthread_cond_wait(&b->notempty, &b->lock);
}
data = b->buffer[b->readpos];
b->readpos++;
if (b->readpos >= 16)
b->readpos = 0;
pthread_cond_signal(&b->notfull);
pthread_mutex_unlock(&b->lock);
return data;
}
struct prodcons buffer;
void *producer(void *data)
{
int n;
for (n = 0; n < 100; n++)
{
printf("%d --->\\n", n);
put(&buffer, n);
}
put(&buffer, ( - 1));
return 0;
}
void *consumer(void *data)
{
int d;
while (1)
{
d = get(&buffer);
if (d == ( - 1))
break;
printf("--->%d \\n", d);
}
return 0;
}
int main(void)
{
pthread_t th_a, th_b;
void *retval;
init(&buffer);
pthread_create(&th_a, 0, producer, 0);
pthread_create(&th_b, 0, consumer, 0);
pthread_join(th_a, &retval);
pthread_join(th_b, &retval);
return 0;
}
| 1
|
#include <pthread.h>
void *threadfunc(void *);
void unlock(void *);
pthread_mutex_t mutex;
pthread_cond_t cond;
int share;
int
main(int argc, char *argv[])
{
pthread_t thread;
int ret;
printf("Test of CV state after cancelling a wait\\n");
ret = pthread_mutex_init(&mutex, 0);
if (ret) errx(1, "pthread_mutex_init: %s", strerror(ret));
ret = pthread_cond_init(&cond, 0);
if (ret) errx(1, "pthread_cond_init: %s", strerror(ret));
ret = pthread_mutex_lock(&mutex);
if (ret) errx(1, "pthread_mutex_lock: %s", strerror(ret));
ret = pthread_create(&thread, 0, threadfunc, 0);
if (ret) errx(1, "pthread_create: %s", strerror(ret));
while (share == 0) {
ret = pthread_cond_wait(&cond, &mutex);
if (ret) errx(1, "pthread_cond_wait: %s", strerror(ret));
}
ret = pthread_mutex_unlock(&mutex);
if (ret) errx(1, "pthread_mutex_unlock: %s", strerror(ret));
ret = pthread_cancel(thread);
if (ret) errx(1, "pthread_cancel: %s", strerror(ret));
ret = pthread_join(thread, 0);
if (ret) errx(1, "pthread_join: %s", strerror(ret));
ret = pthread_cond_destroy(&cond);
if (ret) errx(1, "pthread_cond_destroy: %s", strerror(ret));
printf("CV successfully destroyed.\\n");
ret = pthread_mutex_destroy(&mutex);
if (ret) errx(1, "pthread_mutex_destroy: %s", strerror(ret));
return 0;
}
void *
threadfunc(void *arg)
{
int ret;
ret = pthread_mutex_lock(&mutex);
if (ret) errx(1, "pthread_mutex_lock: %s", strerror(ret));
pthread_cleanup_push(unlock, &mutex);
while (1) {
share = 1;
ret = pthread_cond_broadcast(&cond);
if (ret) errx(1, "pthread_cond_broadcast: %s", strerror(ret));
ret = pthread_cond_wait(&cond, &mutex);
if (ret) errx(1, "pthread_cond_wait: %s", strerror(ret));
}
pthread_cleanup_pop(0);
ret = pthread_mutex_unlock(&mutex);
if (ret) errx(1, "pthread_mutex_unlock: %s", strerror(ret));
return 0;
}
void
unlock(void *arg)
{
pthread_mutex_unlock((pthread_mutex_t *)arg);
}
| 0
|
#include <pthread.h>
void* funProd(void *arg);
void* funPosr(void *arg);
void* funKons(void *arg);
struct bufCykl
{
int dane[16];
int we;
int wy;
int licznik;
pthread_mutex_t *semafor;
pthread_cond_t *cond;
};
int odczyt(struct bufCykl *buf);
void zapis(struct bufCykl *buf, int wartosc);
struct bufCykl buforProdPosr;
struct bufCykl buforPosrKons;
int main()
{
pthread_mutex_t semProdPosr = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t semPosrKons = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condProdPosr = PTHREAD_COND_INITIALIZER;
pthread_cond_t condPosrKons = PTHREAD_COND_INITIALIZER;
pthread_t producent;
pthread_t posrednik;
pthread_t konsument;
buforProdPosr.we = buforProdPosr.wy = buforProdPosr.licznik = 0;
buforProdPosr.semafor = &semProdPosr;
buforProdPosr.cond = &condProdPosr;
buforPosrKons.we = buforPosrKons.wy = buforPosrKons.licznik = 0;
buforPosrKons.semafor = &semPosrKons;
buforPosrKons.cond = &condPosrKons;
pthread_create(&producent, 0, funProd, &buforProdPosr);
pthread_create(&posrednik, 0, funPosr, 0);
pthread_create(&konsument, 0, funKons, &buforPosrKons);
pthread_join(producent, 0);
pthread_join(posrednik, 0);
pthread_join(konsument, 0);
return 0;
}
void* funProd(void *arg)
{
int i;
struct bufCykl *buf = (struct bufCykl *) arg;
for (i=0; i<20; i++)
{
zapis(buf, i);
sleep(1);
}
}
void* funPosr(void *arg)
{
int i;
struct bufCykl *buf1 = &buforProdPosr;
struct bufCykl *buf2 = &buforPosrKons;
for (i=0; i<20; i++)
{
int x = odczyt(buf1);
x*=2;
zapis(buf2, x);
}
}
void* funKons(void *arg)
{
int i;
struct bufCykl *buf = (struct bufCykl *) arg;
for (i=0; i<20; i++)
{
int x = odczyt(buf);
printf("x=%d\\n", x);
}
}
int odczyt(struct bufCykl *buf)
{
int wynik;
int odczytano = 0;
pthread_mutex_lock (buf->semafor);
while (buf->licznik == 0)
pthread_cond_wait(buf->cond, buf->semafor);
wynik = buf->dane[buf->wy];
buf->licznik--;
buf->wy++;
buf->wy %= 16;
pthread_mutex_unlock (buf->semafor);
pthread_cond_signal(buf->cond);
return wynik;
}
void zapis(struct bufCykl *buf, int wartosc)
{
pthread_mutex_lock (buf->semafor);
while (buf->licznik == 16)
pthread_cond_wait(buf->cond, buf->semafor);
buf->dane[buf->we] = wartosc;
buf->licznik++;
buf->we++;
buf->we %= 16;
pthread_mutex_unlock (buf->semafor);
pthread_cond_signal(buf->cond);
}
| 1
|
#include <pthread.h>
int num_threads = 30;
int N = 100000;
float result;
pthread_mutex_t mutex;
struct ThreadInput {
float dx;
int id;
float result;
};
float f(float x) {
return sin(x);
}
void * thread_func1(void * arg_ptr);
void * thread_func2(void * arg_ptr);
main() {
int i;
pthread_t tids[num_threads];
int ids[num_threads];
struct ThreadInput thread_inputs[num_threads];
float f_val[2];
double t;
float loc_vals[num_threads];
for(i = 0; i < num_threads; i++) ids[i] = i;
printf("N: "); scanf("%d", &N);
printf("Number of threads: "); scanf("%d", &num_threads);
FILE *file = fopen("results_logs.txt", "a");
if(file == 0) {
printf("Error opening file!\\n");
}
printf("N: %d, l_watkow: %d:\\n", N, num_threads);
fprintf(file, "N: %d, l_watkow: %d:\\n", N, num_threads);
t = czas_zegara();
float a, b, x1, x2, dx;
a = 0;
b = 3.1415;
dx = (b-a)/N;
x1 = a;
f_val[0] = f(x1);
for(i = 0; i < N; i++) {
x2 = x1 + dx;
f_val[1] = f(x2);
result += f_val[0] + f_val[1];
f_val[0] = f_val[1];
x1 = x2;
}
result *= 0.5 * dx;
t = czas_zegara() - t;
printf("\\tCzas zegara: %f\\n", t);
printf("Wynik: %.6f\\t[Single-thread]\\n", result);
fprintf(file, "\\tCzas zegara: %f\\n", t);
fprintf(file, "Wynik: %.6f\\t[Single-thread]\\n", result);
result = 0.0;
if(pthread_mutex_init(&mutex, 0) != 0) {
printf("Mutex init error\\n");
}
t = czas_zegara();
for(i = 0; i < num_threads; i++) {
pthread_create(&tids[i], 0, thread_func1, (void*)&ids[i]);
}
for(i = 0; i < num_threads; i++) {
pthread_join(tids[i], 0);
}
result *= 0.5 * dx;
t = czas_zegara() - t;
printf("\\tCzas zegara: %f\\n", t);
printf("Wynik: %.6f\\t[Multi-thread (4.)] \\n", result);
fprintf(file, "\\tCzas zegara: %f\\n", t);
fprintf(file, "Wynik: %.6f\\t[Multi-thread (4.)] \\n", result);
result = 0.0;
for(i = 0; i < num_threads; i++) {
thread_inputs[i].dx = dx;
thread_inputs[i].id = i;
}
t = czas_zegara();
for(i = 0; i < num_threads; i++) {
pthread_create(&tids[i], 0, thread_func2, (void*)&thread_inputs[i]);
}
for(i = 0; i < num_threads; i++) {
pthread_join(tids[i], 0);
}
for(i = 0; i< num_threads; i++) {
result += thread_inputs[i].result;
}
result *= 0.5 * dx;
t = czas_zegara() - t;
printf("\\tCzas zegara: %f\\n", t);
printf("Wynik: %.6f\\t[Multi-thread (5.)] \\n", result);
fprintf(file, "\\tCzas zegara: %f\\n", t);
fprintf(file, "Wynik: %.6f\\t[Multi-thread (5.)] \\n", result);
fprintf(file, "\\n-----------------\\n\\n");
fclose(file);
exit(0);
}
void * thread_func1(void * arg_ptr) {
float a, b, x1, x2, dx;
float loc_result = 0;
float f_val[2];
int myN, i;
int id = *(int*)arg_ptr;
a = 0;
b = 3.1415;
dx = (b-a)/N;
myN = N/num_threads;
x1 = id * dx * myN;
f_val[0] = f(x1);
for(i = 0; i < myN; i++) {
x2 = x1 + dx;
f_val[1] = f(x2);
loc_result += f_val[0] + f_val[1];
f_val[0] = f_val[1];
x1 = x2;
}
pthread_mutex_lock(&mutex);
result += loc_result;
pthread_mutex_unlock(&mutex);
return(0);
}
void * thread_func2(void * arg_ptr) {
struct ThreadInput *t_in = (struct ThreadInput*)arg_ptr;
float a, b, a_loc, b_loc, dx_loc, x1, x2;
int N, i;
float loc_result = 0.0;
float f_val[2];
int id = t_in->id;
float dx = t_in->dx;
a = 0;
b = 3.1415;
float thread_interval = (b-a) / num_threads;
a_loc = a + id * thread_interval;
b_loc = a + (id+1) * thread_interval;
dx_loc = dx;
int N_loc = (b_loc-a_loc)/dx_loc;
x1 = a_loc;
f_val[0] = f(x1);
for(i = 0; i < N_loc; i++) {
x2 = x1 + dx_loc;
f_val[1] = f(x2);
loc_result += f_val[0] + f_val[1];
f_val[0] = f_val[1];
x1 = x2;
}
pthread_mutex_lock(&mutex);
t_in->result = loc_result;
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int THREADNUM = 1;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_t* threads;
void*
printHello(void* args)
{
int i = 0;
pthread_mutex_lock(&mutex);
for(;i < 1000000; i++){
fprintf(stdout,"Hello ");
fprintf(stdout,"World!\\n");
}
pthread_mutex_unlock(&mutex);
return 0;
}
void
joinThreads(void)
{
int i;
for(i = 0; i < THREADNUM; i++)
pthread_join(threads[i],0);
}
int
main(void)
{
clock_t start = clock();
if((threads = (pthread_t*) malloc(sizeof(pthread_t) * THREADNUM)) == 0){
perror("Failed to malloc for threads ");
exit(1);
}
if(pthread_mutex_init(&mutex,0) != 0){
perror("Mutex Init Error ");
exit(1);
}
int i;
for(i = 0; i < THREADNUM; i++){
if(pthread_create(&threads[i],0,printHello,0) != 0){
perror("pthread_create failure ");
joinThreads();
exit(1);
}
}
joinThreads();
start = clock() - start;
int msec = start * 1000 / CLOCKS_PER_SEC / THREADNUM;
fprintf(stdout,"Takse took about %d seconds and %d miliseconds per thread\\n",msec/1000,msec%1000);
free(threads);
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
unsigned int TEST_VALUE_CA[8][3] = {
{CMD_WRITE, REG_INTERRUPT_MASK_0, 0x555555},
{CMD_SUB, 2, 0},
{CMD_WRITE, REG_INTERRUPT_MASK_1, 0xFF7777},
{CMD_SUB, 0, 0},
{CMD_WRITE, REG_USB, 0x001001},
{CMD_UNSUB, 0, 0},
{CMD_UNSUB, 2, 0}
};
int VT_mc13783_CA_setup(void) {
int rv = TFAIL;
rv = TPASS;
return rv;
}
int VT_mc13783_CA_cleanup(void) {
int rv = TFAIL;
rv = TPASS;
return rv;
}
int VT_mc13783_test_CA(void) {
int rv = TPASS, fd, i = 0;
fd = open(MC13783_DEVICE, O_RDWR);
if (fd < 0) {
pthread_mutex_lock(&mutex);
tst_resm(TFAIL, "Unable to open %s", MC13783_DEVICE);
pthread_mutex_unlock(&mutex);
return TFAIL;
}
for (i = 0; i < 8; i++) {
if (VT_mc13783_opt
(fd, TEST_VALUE_CA[i][0], TEST_VALUE_CA[i][1],
&(TEST_VALUE_CA[i][2])) != TPASS) {
rv = TFAIL;
}
}
if (close(fd) < 0) {
pthread_mutex_lock(&mutex);
tst_resm(TFAIL, "Unable to close file descriptor %d",
fd);
pthread_mutex_unlock(&mutex);
return TFAIL;
}
return rv;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int comida = 6;
struct filosofo{
char * nombre;
int cantComida;
pthread_mutex_t ten1;
pthread_mutex_t ten2;
};
struct tenedor{
int estado;
};
void * comer( void * h1)
{
struct filosofo * fil;
fil = (struct filosofo*) h1;
printf("%s %s \\n", fil->nombre, "esta pensando");
while(fil->cantComida > 0){
printf("%s %s \\n", fil->nombre, "tiene hambre");
pthread_mutex_lock( &fil->ten1 );pthread_mutex_lock( &fil->ten2 );
printf("%s %s \\n", fil->nombre, "agarro los 2 tenedores");
while(fil->cantComida > 0){
fil->cantComida--;
printf("%s %s \\n", fil->nombre, "esta comiendo");
}
}
printf("%s %s \\n", fil->nombre, "termino de comer");
pthread_mutex_unlock( &fil->ten1 );
pthread_mutex_unlock( &fil->ten2 );
}
int main() {
pthread_t thread1, thread2,thread3,thread4,thread5;
struct filosofo * fil1 = (struct filosofo *) malloc (sizeof(struct filosofo));
struct filosofo* fil2 = (struct filosofo *) malloc (sizeof(struct filosofo));
struct filosofo * fil3 = (struct filosofo *) malloc (sizeof(struct filosofo));
struct filosofo * fil4 = (struct filosofo *) malloc (sizeof(struct filosofo));
struct filosofo * fil5 = (struct filosofo *) malloc (sizeof(struct filosofo));
fil1->nombre = "Platon";
fil1->cantComida = comida;
fil1->ten1 = mutex;
fil1->ten2 = mutex;
fil2->nombre = "Descartes";
fil2->cantComida = comida;
fil2->ten1 = mutex;
fil2->ten2 = mutex;
fil3->nombre = "Nietsche";
fil3->cantComida = comida;
fil3->ten1 = mutex;
fil3->ten2 = mutex;
fil4->nombre = "Hegel";
fil4->cantComida = comida;
fil4->ten1 = mutex;
fil4->ten2 = mutex;
fil5->nombre = "Aristoteles";
fil5->cantComida = comida;
fil5->ten1 = mutex;
fil5->ten2 = mutex;
int iret1, iret2,iret3,iret4,iret5;
iret1 = pthread_create( &thread1, 0, comer, (void*) fil1);
iret2 = pthread_create( &thread2, 0, comer, (void*) fil2);
iret3 = pthread_create( &thread3, 0, comer, (void*) fil3);
iret4 = pthread_create( &thread4, 0, comer, (void*) fil4);
iret5 = pthread_create( &thread5, 0, comer, (void*) fil5);
pthread_join( thread1, 0);
pthread_join( thread2, 0);
pthread_join( thread3, 0);
pthread_join( thread4, 0);
pthread_join( thread5, 0);
printf("Thread 1 returns: %d\\n",iret1);
printf("Thread 2 returns: %d\\n",iret2);
printf("Thread 3 returns: %d\\n",iret3);
printf("Thread 4 returns: %d\\n",iret4);
printf("Thread 5 returns: %d\\n",iret5);
return 0;
}
| 1
|
#include <pthread.h>
int num_thr;
pthread_mutex_t mutex;
struct thread_data{
double *A;
int left;
int right;
};
double get_wall_time(){
struct timeval time;
if (gettimeofday(&time,0)){
return 0;
}
return (double)time.tv_sec + (double)time.tv_usec * .000001;
}
int partition(double a[], int left, int right){
int i, j;
double pivot,temp;
pivot = a[left];
i = left;
j = right+1;
while( 1){
do ++i; while(a[i] <= pivot && i <= right);
do --j; while(a[j] > pivot);
if( i >= j ){
break;
}
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
temp = a[left];
a[left] = a[j];
a[j] = temp;
return j;
}
void quicksort(double a[], int left, int right){
int pivot;
if( left < right ){
pivot = partition( a, left, right);
quicksort( a, left, pivot-1);
quicksort( a, pivot+1, right);
}
}
void *pquicksortHelp(void *threadarg){
int pivot,i;
void *status;
struct thread_data *mydata;
mydata = (struct thread_data *) threadarg;
if (num_thr <= 0 || mydata->left == mydata->right){
quicksort(mydata->A, mydata->left, mydata->right);
pthread_exit(0);
}
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pivot = partition(mydata->A, mydata->left, mydata->right);
struct thread_data thread_data_array[2];
for (i = 0;i < 2;i ++){
thread_data_array[i].A = mydata->A;
pthread_mutex_lock (&mutex);
num_thr--;
pthread_mutex_unlock (&mutex);
}
thread_data_array[0].left = mydata->left;
thread_data_array[0].right = pivot-1;
thread_data_array[1].left = pivot+1;
thread_data_array[1].right = mydata->right;
pthread_t threads[2];
for (i = 0;i < 2;i ++){
pthread_create(&threads[i], &attr, pquicksortHelp, (void *) &thread_data_array[i]);
}
pthread_attr_destroy(&attr);
for (i = 0;i < 2;i ++){
pthread_join(threads[i], &status);
}
pthread_exit(0);
}
void pquicksort(double a[], int size){
void *status;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_mutex_init(&mutex, 0);
struct thread_data mydata;
mydata.A = a;
mydata.left = 0;
mydata.right = size - 1;
pthread_t thread1;
pthread_create(&thread1, &attr, pquicksortHelp, (void *) &mydata);
pthread_attr_destroy(&attr);
pthread_join(thread1, &status);
}
int isSorted(double a[], int size)
{
int i;
for (i = 1;i < size;i ++){
if (a[i] < a[i-1]){
printf("at loc %d, %e < %e \\n", i, a[i], a[i-1]);
return 0;
}
}
return 1;
}
int main(int argc, char *argv[]) {
int i,num_elem;
double *A;
double start_time,end_time;
num_elem = 10000;
num_thr = 4;
if (argc == 3){
num_elem = atoi(argv[1]);
num_thr = atoi(argv[2]);
}else{
printf("\\nNo arguments given, continuing with default values: NUM_ELEMENTS 10000 NUM_THREADS 4\\n");
}
A = malloc(num_elem * sizeof(double));
srand48((unsigned int)time(0));
for (i=0;i<num_elem;i++){
A[i] = drand48() * 100;
}
start_time = get_wall_time();
pquicksort(A,num_elem);
end_time = get_wall_time();
if (!isSorted(A, num_elem)){
printf("\\nList did not get sorted dummy!\\n");
}else{
printf("\\nEverything went great, the list is sorted!\\n");
}
printf("Processing (Wall) time: %f s\\n\\n", (end_time-start_time) );
free(A);
pthread_mutex_destroy (&mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int buffer[4];
int in;
int out;
int buffer_is_empty()
{
return in == out;
}
int buffer_is_full()
{
return (in + 1) % 4 == out;
}
int get_item()
{
int item;
item = buffer[out];
out = (out + 1) % 4;
return item;
}
void put_item(int item)
{
buffer[in] = item;
in = (in + 1) % 4;
}
pthread_mutex_t mutex;
pthread_cond_t wait_empty_buffer;
pthread_cond_t wait_full_buffer;
void *consume(void *arg)
{
int i;
int item;
for (i = 0; i < (4 * 2); i++) {
pthread_mutex_lock(&mutex);
while (buffer_is_empty())
pthread_cond_wait(
&wait_full_buffer,
&mutex);
item = get_item();
printf(" consume item: %c\\n", item);
sleep(1);
pthread_cond_signal(&wait_empty_buffer);
pthread_mutex_unlock(&mutex);
}
return 0;
}
void produce()
{
int i;
int item;
for (i = 0; i < (4 * 2); i++) {
pthread_mutex_lock(&mutex);
while (buffer_is_full())
{
pthread_cond_wait(&wait_empty_buffer, &mutex);
}
item = i + 'a';
printf("produce item: %c\\n", item);
put_item(item);
sleep(1);
pthread_cond_signal(&wait_full_buffer);
pthread_mutex_unlock(&mutex);
}
}
int main()
{
pthread_t consumer_tid;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&wait_empty_buffer, 0);
pthread_cond_init(&wait_full_buffer, 0);
pthread_create(&consumer_tid, 0, consume, 0);
produce();
return 0;
}
| 1
|
#include <pthread.h>
void *(*process)(void *arg);
void *arg;
struct task_worker *next;
}t_task;
pthread_mutex_t lock;
pthread_cond_t cond_lock;
t_task *queue_task;
int shutdown;
pthread_t *threadid;
int max_thread_num;
int cur_queue_size;
}t_task_pool;
int pool_add_task(void *(*proc)(void *arg),void *arg);
void *pthread_routine(void *);
static t_task_pool *pool=0;
void pool_init(int max_num){
pool=(t_task_pool *)malloc(sizeof(t_task_pool));
pthread_mutex_init(&(pool->lock),0);
pthread_cond_init(&(pool->cond_lock),0);
pool->queue_task=0;
pool->max_thread_num=max_num;
pool->cur_queue_size=0;
pool->shutdown=0;
pool->threadid=(pthread_t *)malloc(sizeof(pthread_t)*(pool->max_thread_num));
int i=0;
for(i=0;i<pool->max_thread_num;i++){
pthread_create(&(pool->threadid[i]),0,pthread_routine,0);
}
}
int pool_add_task(void *(*proc)(void *arg),void *arg){
t_task *newtask=(t_task *)malloc(sizeof(t_task));
newtask->process=proc;
newtask->arg=arg;
newtask->next=0;
pthread_mutex_lock(&(pool->lock));
t_task *ptast=pool->queue_task;
if(ptast!=0){
while(ptast->next!=0){
ptast=ptast->next;
}
ptast->next=newtask;
}else{
pool->queue_task=newtask;
}
pool->cur_queue_size++;
pthread_mutex_unlock(&(pool->lock));
pthread_cond_signal(&(pool->cond_lock));
return 0;
}
int pool_destroy(){
if(pool->shutdown==1){
return -1;
}
pool->shutdown=1;
pthread_cond_broadcast(&(pool->cond_lock));
int i;
for(i=0;i<pool->max_thread_num;i++){
pthread_join(pool->threadid[i],0);
}
free(pool->threadid);
t_task *p=0;
while(pool->queue_task!=0){
p=pool->queue_task;
pool->queue_task=pool->queue_task->next;
free(p);
}
pthread_mutex_destroy(&(pool->lock));
pthread_cond_destroy(&(pool->cond_lock));
free(pool);
pool=0;
return 0;
}
void * pthread_routine(void *arg){
while(1){
pthread_mutex_lock(&(pool->lock));
while(pool->cur_queue_size==0&&pool->shutdown!=1){
pthread_cond_wait(&(pool->cond_lock),&(pool->lock));
}
if(pool->shutdown){
pthread_mutex_unlock(&(pool->lock));
pthread_exit(0);
}
pool->cur_queue_size--;
t_task *head=pool->queue_task;
pool->queue_task=pool->queue_task->next;
pthread_mutex_unlock(&(pool->lock));
(*(head->process))(head->arg);
free(head);
head=0;
}
pthread_exit(0);
}
void * pro(void *arg){
int *p=(int *)&arg;
printf(" %d\\n",*p);
sleep(1);
return 0;
}
int main(void){
pool_init(3);
int *num=(int *)malloc(sizeof(int)*10);
int i=0;
for (i = 0; i < 10; ++i)
{
pool_add_task(pro,(void *)&num[i]);
}
sleep(5);
pool_destroy();
return 0;
}
| 0
|
#include <pthread.h>
int q[5];
int qsiz;
pthread_mutex_t mq;
void queue_init ()
{
pthread_mutex_init (&mq, 0);
qsiz = 0;
}
void queue_insert (int x)
{
int done = 0;
printf ("prod: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz < 5)
{
done = 1;
q[qsiz] = x;
qsiz++;
}
pthread_mutex_unlock (&mq);
}
}
int queue_extract ()
{
int done = 0;
int x = -1, i = 0;
printf ("consumer: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz > 0)
{
done = 1;
x = q[0];
qsiz--;
for (i = 0; i < qsiz; i++) q[i] = q[i+1];
__VERIFIER_assert (qsiz < 5);
q[qsiz] = 0;
}
pthread_mutex_unlock (&mq);
}
return x;
}
void swap (int *t, int i, int j)
{
int aux;
aux = t[i];
t[i] = t[j];
t[j] = aux;
}
int findmaxidx (int *t, int count)
{
int i, mx;
mx = 0;
for (i = 1; i < count; i++)
{
if (t[i] > t[mx]) mx = i;
}
__VERIFIER_assert (mx >= 0);
__VERIFIER_assert (mx < count);
t[mx] = -t[mx];
return mx;
}
int source[6];
int sorted[6];
void producer ()
{
int i, idx;
for (i = 0; i < 6; i++)
{
idx = findmaxidx (source, 6);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 6);
queue_insert (idx);
}
}
void consumer ()
{
int i, idx;
for (i = 0; i < 6; i++)
{
idx = queue_extract ();
sorted[i] = idx;
printf ("m: i %d sorted = %d\\n", i, sorted[i]);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 6);
}
}
void *thread (void * arg)
{
(void) arg;
producer ();
return 0;
}
int main ()
{
pthread_t t;
int i;
__libc_init_poet ();
for (i = 0; i < 6; i++)
{
source[i] = __VERIFIER_nondet_int(0,20);
printf ("m: init i %d source = %d\\n", i, source[i]);
__VERIFIER_assert (source[i] >= 0);
}
queue_init ();
pthread_create (&t, 0, thread, 0);
consumer ();
pthread_join (t, 0);
return 0;
}
| 1
|
#include <pthread.h>
int buf[10];
pthread_mutex_t block;
sem_t filled;
sem_t empty;
int pos=0;
void* producerFunc(void *args)
{
int item;
while(1)
{
item=30;
sem_wait(&empty);
pthread_mutex_lock(&block);
if(pos<10)
{
buf[pos]=item;
pos++;
}
pthread_mutex_unlock(&block);
sem_post(&filled);
sleep(1);
}
}
void* consumerFunc(void *args)
{
int item;
while(1)
{
sem_wait(&filled);
pthread_mutex_lock(&block);
if(pos>0)
{
pos--;
item=buf[pos];
disp(item);
}
pthread_mutex_unlock(&block);
sem_post(&empty);
sleep(1);
}
return 0;
}
void main(int argc,void* argv[])
{
int i=0;
pthread_t producer;
pthread_t consumer[4];
pthread_mutex_init(&block,0);
sem_init(&full,0,0);
sem_init(&empty,0,10);
pthread_create(&producer,0,producerFunc,0);
pthread_create(&consumer[0],0,consumerFunc,0);
pthread_create(&consumer[1],0,consumerFunc,0);
pthread_create(&consumer[2],0,consumerFunc,0);
pthread_create(&consumer[3],0,consumerFunc,0);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t logLock;
int bstapp_logging_init(void)
{
int rv = 0;
FILE *fp;
rv = pthread_mutex_init(&logLock, 0);
_BSTAPP_ASSERT_NET_ERROR( (rv == 0), "BSTAPP : Error creating logging mutex \\n");
fp = fopen(BSTAPP_COMMUNICATION_LOG_FILE, "w");
if (fp != 0)
{
fclose(fp);
}
return 0;
}
int bstapp_message_log(char *message, int length, bool isFromAgent)
{
FILE *fp = 0;
char timeString[BSTAPP_MAX_STRING_LENGTH] = { 0 };
time_t logtime;
struct tm *timeinfo;
int i = 0;
time(&logtime);
timeinfo = localtime(&logtime);
strftime(timeString, BSTAPP_MAX_STRING_LENGTH, "%Y-%m-%d %H:%M:%S ", timeinfo);
pthread_mutex_lock(&logLock);
fp = fopen(BSTAPP_COMMUNICATION_LOG_FILE, "a");
if (fp == 0)
{
_BSTAPP_LOG(_BSTAPP_DEBUG_ERROR, "Log : Unable to open file for logging [%d:%s] \\n",
errno, strerror(errno));
pthread_mutex_unlock(&logLock);
return -1;
}
fputs(timeString, fp);
if (isFromAgent)
{
fputs("Message from Agent \\n", fp);
}
else
{
fputs("Message to Agent \\n", fp);
}
for (i = 0; i < length; i++)
{
fputc(message[i], fp);
}
fputs("\\n", fp);
fclose(fp);
pthread_mutex_unlock(&logLock);
return 0;
}
| 1
|
#include <pthread.h>
enum {
STATE_THINKING,
STATE_HUNGRY,
STATE_EATING
};
struct strFil {
int id;
int state;
int numRefeicoes;
sem_t semAlterandoGrafos;
sem_t semAguardandoGarfo;
};
int numFilosofos;
Filosofo * filosofos;
pthread_mutex_t lockImprimindoEstado;
int getSleepTime() {
return (rand() % 10) + 1;
}
void inicializaFilosofos() {
filosofos = (Filosofo *) malloc(sizeof(Filosofo) * numFilosofos);
int i;
for(i = 0; i < numFilosofos; i++) {
filosofos[i].id = i;
filosofos[i].state = STATE_THINKING;
filosofos[i].numRefeicoes = 0;
if(sem_init(&filosofos[i].semAlterandoGrafos, 0, 1) != 0) {
printf("Erro ao inicializar semafaro!\\n");
exit(1);
}
if(sem_init(&filosofos[i].semAguardandoGarfo, 0, 0) != 0) {
printf("Erro ao inicializar semafaro!\\n");
exit(1);
}
}
}
void imprimeEstadoFilosofos() {
pthread_mutex_lock(&lockImprimindoEstado);
int i;
for(i = 0; i < numFilosofos; i++) {
switch(filosofos[i].state) {
case STATE_THINKING:
printf("T ");
break;
case STATE_EATING:
printf("E ");
break;
case STATE_HUNGRY:
printf("H ");
break;
}
}
printf("\\n");
pthread_mutex_unlock(&lockImprimindoEstado);
}
int possoComer(Filosofo * filosofo) {
int idFilosofoEsquerda = (filosofo->id + (numFilosofos-1))%numFilosofos;
int idFilosofoDireita = (filosofo->id + 1) % numFilosofos;
if(filosofos[idFilosofoEsquerda].state == STATE_EATING || filosofos[idFilosofoDireita].state == STATE_EATING) {
return 0;
}
if(filosofos[idFilosofoEsquerda].state == STATE_HUNGRY && filosofos[idFilosofoEsquerda].numRefeicoes < filosofo->numRefeicoes) {
return 0;
}
if(filosofos[idFilosofoDireita].state == STATE_HUNGRY && filosofos[idFilosofoDireita].numRefeicoes < filosofo->numRefeicoes) {
return 0;
}
return 1;
}
void pensar(Filosofo * filosofo) {
filosofo->state = STATE_THINKING;
imprimeEstadoFilosofos();
sleep(getSleepTime());
}
void adquirirGarfos(Filosofo * filosofo) {
sem_wait(&filosofo->semAlterandoGrafos);
filosofo->state = STATE_HUNGRY;
imprimeEstadoFilosofos();
int idFilosofoEsquerda = (filosofo->id + (numFilosofos-1))%numFilosofos;
int idFilosofoDireita = (filosofo->id + 1) % numFilosofos;
while(!possoComer(filosofo)) {
sem_wait(&filosofo->semAguardandoGarfo);
}
}
void largarGarfos(Filosofo* filosofo) {
sem_wait(&filosofo->semAlterandoGrafos);
filosofo->state = STATE_THINKING;
imprimeEstadoFilosofos();
int idFilosofoEsquerda = (filosofo->id + (numFilosofos-1))%numFilosofos;
int idFilosofoDireita = (filosofo->id + 1) % numFilosofos;
if(filosofos[idFilosofoEsquerda].state == STATE_HUNGRY) {
sem_post(&filosofos[idFilosofoEsquerda].semAguardandoGarfo);
}
if(filosofos[idFilosofoDireita].state == STATE_HUNGRY) {
sem_post(&filosofos[idFilosofoDireita].semAguardandoGarfo);
}
sem_post(&filosofo->semAlterandoGrafos);
}
void comer(Filosofo * filosofo) {
filosofo->state = STATE_EATING;
imprimeEstadoFilosofos();
filosofo->numRefeicoes++;
sem_post(&filosofo->semAlterandoGrafos);
sleep(getSleepTime());
largarGarfos(filosofo);
}
void * filosofar (void * arg) {
Filosofo * meuFilosofo = (Filosofo *) arg;
printf("Inicializando filosofo %d\\n", meuFilosofo->id);
while(1) {
pensar(meuFilosofo);
adquirirGarfos(meuFilosofo);
comer(meuFilosofo);
}
}
int main (int argc, char **argv) {
pthread_t * threads;
int numThreads = 3;
int c;
while ((c = getopt (argc, argv, "n:")) != -1) {
switch (c)
{
case 'n':
numThreads = atoi(optarg);
break;
}
}
if(numThreads < 3) {
printf("Numero de filosofos invalido!\\n");
return 0;
}
printf("Usando %d filosofos!\\n", numThreads);
time_t t;
srand((unsigned) time(&t));
numFilosofos = numThreads;
inicializaFilosofos();
threads = (pthread_t *) malloc(sizeof(pthread_t) * numThreads);
pthread_mutex_init(&lockImprimindoEstado, 0);
int i;
printf("Criando threads...\\n");
for(i = 0; i < numThreads; i++) {
pthread_create(&threads[i], 0, filosofar, (void *) &filosofos[i]);
}
for(i = 0; i < numThreads; i++) {
pthread_join(threads[i], 0);
}
free(threads);
return 0;
}
| 0
|
#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);
printf("pthread_mutex_lock gained, setting quitflag: %d to 1\\n", quitflag);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&waitloc);
return(0);
default:
printf("unexpected signal %d\\n", signo);
exit(1);
}
}
}
int main(void)
{
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0)
err_exit(err, "SIG_BLOCK error");
err = pthread_create(&tid, 0, thr_fn, 0);
if (err != 0)
err_exit(err, "can't create thread");
pthread_mutex_lock(&lock);
printf("locked in main\\n");
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);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
int cant;
int buffer[5];
int DATOS_A_PRODUCIR = 20;
void Productor()
{
int dato, i, pos;
pos = 0;
dato = 1000;
i = 0;
while (i < DATOS_A_PRODUCIR) {
sleep(1);
pthread_mutex_lock(&mutex);
while (cant < 5) {
buffer[pos] = dato;
dato++;
pos = (pos + 1);
if (pos >= 5) {
pos = 0;
}
cant++;
i++;
printf
("Productor posicion: %d, dato: %d, cantidad: %d, i: %d\\n",
pos, dato, cant, i);
}
pthread_mutex_unlock(&mutex);
}
printf("Termino produccion: %d\\n", i);
pthread_exit(0);
}
void Consumidor()
{
int dato, i, pos;
pos = 0;
i = 0;
while (i < DATOS_A_PRODUCIR) {
pthread_mutex_lock(&mutex);
while (cant > 0) {
dato = buffer[pos];
pos = (pos + 1);
if (pos > (5 - 1)) {
pos = 0;
}
cant--;
i++;
printf
("Consumidor posicion: %d, dato: %d, cantidad: %d, i: %d\\n",
pos, dato, cant, i);
}
pthread_mutex_unlock(&mutex);
}
printf("Termino Consumo: %d\\n", i);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
pthread_t th1, th2;
pthread_mutex_init(&mutex, 0);
if (argc == 2) {
printf("argv[0]= %s , argv[1]= %s , argc=%d\\n", argv[0], argv[1],
argc);
DATOS_A_PRODUCIR = atoi(argv[1]);
}
pthread_create(&th1, 0, (void *)&Productor, 0);
pthread_create(&th2, 0, (void *)&Consumidor, 0);
pthread_join(th1, 0);
pthread_join(th2, 0);
printf("Productor-Consumidor con mutex: termina\\n");
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER;
int isGreen1 (int s) {
return s == 0;
}
int isGreen2 (int s) {
return s == 0;
}
void * signal1(void* d) {
int status = 0;
b1:
printf("1 -> GREEN\\n");
sleep(2);
status = 1;
printf("1 -> ORANGE\\n");
sleep(1);
status = 2;
printf("1 -> RED\\n");
pthread_mutex_unlock(&m1);
pthread_mutex_lock(&m2);
status = 0;
printf("1 -> GREEN\\n");
sleep(2);
status = 1;
printf("1 -> ORANGE\\n");
sleep(1);
status = 2;
printf("1 -> RED\\n");
pthread_mutex_unlock(&m1);
e1:
pthread_exit(0);
}
void * signal2(void* d) {
int status = 2;
printf("2 -> RED\\n");
b2:
pthread_mutex_lock(&m1);
status = 0;
printf("2 -> GREEN\\n");
sleep(2);
status = 1;
printf("2 -> ORANGE\\n");
sleep(1);
status = 2;
printf("2 -> RED\\n");
pthread_mutex_unlock(&m2);
e2:
pthread_exit(0);
}
int main() {
pthread_t t1, t2;
printf("Start\\n");
pthread_mutex_lock(&m1);
pthread_mutex_lock(&m2);
printf("Create\\n");
pthread_create(&t1, 0, signal1, 0);
pthread_create(&t2, 0, signal2, 0);
printf("Join\\n");
pthread_join(t1, 0);
pthread_join(t2, 0);
printf("End\\n");
return 0;
}
| 1
|
#include <pthread.h>
pthread_t tid[8];
pthread_mutex_t mutex;
int *array;
int length = 1000000000;
int private_count[8];
int count = 0;
int double_count = 0;
int t = 8;
int max_threads = 0;
void *count3s_thread(void *arg) {
int i;
struct timeval tv1,tv2;
int length_per_thread = length/max_threads;
int id = *((int*)(&arg));
int start = id * length_per_thread;
printf("\\tThread [%d] starts [%d] length [%d]\\n",id, start, length_per_thread);
gettimeofday(&tv1,0);
for (i = start; i < start + length_per_thread; i++) {
if (array[i] == 3) {
private_count[id]++;
}
}
pthread_mutex_lock(&mutex);
count = count + private_count[id];
pthread_mutex_unlock(&mutex);
gettimeofday(&tv2,0);
printf("\\tThread [%d] ended - delay %lf\\n",id,
(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));
}
void initialize_vector() {
int i = 0;
array = (int*) malloc(sizeof(int) * 1000000000);
if (array == 0) {
printf("Allocation memory failed!\\n");
exit(-1);
}
for (; i < 1000000000; i++) {
array[i] = rand() % 20;
if (array[i] == 3)
double_count++;
}
}
int main(int argc, char *argv[]) {
int i = 0;
int err;
struct timeval tv1, tv2, tv3, tv4;
if (argc == 2) {
max_threads = atoi(argv[1]);
if (max_threads > 8)
max_threads = 8;
} else {
max_threads = 8;
}
printf("[3s-05] Using %d threads\\n",max_threads);
srand(time(0));
printf("*** 3s-05 ***\\n");
printf("Initializing vector... ");
fflush(stdout);
gettimeofday(&tv1, 0);
initialize_vector();
gettimeofday(&tv2, 0);
printf("Vector initialized! - elapsed %lf sec.\\n",(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
(double) (tv2.tv_sec - tv1.tv_sec));
fflush(stdout);
gettimeofday(&tv3, 0);
pthread_mutex_init(&mutex,0);
while (i < max_threads) {
private_count[i] = 0;
err = pthread_create(&tid[i], 0, &count3s_thread, (void*)i);
if (err != 0)
printf("[3s-05] Can't create a thread: [%d]\\n", i);
else
printf("[3s-05] Thread created!\\n");
i++;
}
i = 0;
for (; i < max_threads; i++) {
void *status;
int rc;
rc = pthread_join(tid[i], &status);
if (rc) {
printf("ERROR; retrun code from pthread_join() is %d\\n", rc);
exit(-1);
} else {
printf("Thread [%d] exited with status [%ld]\\n", i, (long)status);
}
}
printf("[3s-05] Count by threads %d\\n", count);
printf("[3s-05] Double check %d\\n", double_count);
pthread_mutex_destroy(&mutex);
gettimeofday(&tv4,0);
printf("[[3s-05] Elapsed time %lf sec.\\n", (double) (tv4.tv_usec - tv3.tv_usec) / 1000000 +
(double) (tv4.tv_sec - tv3.tv_sec));
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
int g_flag = 0;
pthread_t t1, t2;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *t1_func(void *param)
{
printf("this is thread 1\\n");
pthread_mutex_lock(&mutex);
g_flag = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
pthread_join(t2, 0);
}
void *t2_func(void *param)
{
printf("this is thread 2\\n");
pthread_mutex_lock(&mutex);
g_flag = 2;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
int main(int argc, char *argv[])
{
pthread_mutex_lock(&mutex);
pthread_create(&t1, 0, t1_func, 0);
pthread_create(&t2, 0, t2_func, 0);
while (g_flag == 0) {
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
int val;
struct node *next;
pthread_mutex_t mutex;
} node;
node sentinel = {32767, 0, PTHREAD_MUTEX_INITIALIZER};
node dummy = {INT_MIN, &sentinel, PTHREAD_MUTEX_INITIALIZER};
node *list = &dummy;
bool contains(int item) {
node *current = list->next;
while (current->val < item)
current = current->next;
return current->val == item;
}
void insert(int item) {
node *prev = list;
pthread_mutex_lock(&prev->mutex);
node *current = list->next;
pthread_mutex_lock(¤t->mutex);
while (item > current->val) {
pthread_mutex_unlock(&prev->mutex);
prev = current;
current = current->next;
pthread_mutex_lock(¤t->mutex);
}
node *new = malloc(sizeof(node));
new->val = item;
new->next = current;
pthread_mutex_init(&new->mutex, 0);
prev->next = new;
pthread_mutex_unlock(&prev->mutex);
pthread_mutex_unlock(¤t->mutex);
}
void delete(int item) {
node *prev = list;
pthread_mutex_lock(&prev->mutex);
node *current = list->next;
pthread_mutex_lock(¤t->mutex);
while (item > current->val) {
pthread_mutex_unlock(&prev->mutex);
prev = current;
current = current->next;
pthread_mutex_lock(¤t->mutex);
}
node *removed = 0;
if (current->val == item) {
prev->next = current->next;
removed = current;
}
pthread_mutex_unlock(&prev->mutex);
pthread_mutex_unlock(¤t->mutex);
if (removed != 0) free(removed);
return;
}
void print_list() {
node *current = list->next;
while (current->next != 0) {
printf("%d -> ", current->val);
current = current->next;
}
printf("\\n");
}
void *procedural_test() {
int items[] = {100,150,4,90,11,564};
for(int i = 0; i < sizeof(items)/sizeof(items[0]); i++) {
printf("Inserting: %d\\n", items[i]);
insert(items[i]);
print_list();
}
for(int i = 0; i < sizeof(items)/sizeof(items[0]); i++) {
printf("Deleting: %d\\n", items[i]);
delete(items[i]);
print_list();
}
printf("Thread done, printing:\\n");
print_list();
}
void concurrent_test() {
pthread_t one;
pthread_t two;
pthread_create(&one, 0, procedural_test, 0);
pthread_create(&two, 0, procedural_test, 0);
pthread_join(one, 0);
pthread_join(two, 0);
}
void *benchInsert(void* arg) {
int start = ((args*)arg)->start;
int stop = ((args*)arg)->stop;
for(int i = start; i < stop; i++)
insert(i);
}
void *benchDelete(void* arg) {
int start = ((args*)arg)->start;
int stop = ((args*)arg)->stop;
for(int i = start; i < stop; i++)
delete(i);
}
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("usage: list <total> <threads>\\n");
exit(0);
}
int n = atoi(argv[2]);
int inc = (atoi(argv[1]) / n);
printf("%d threads doing %d operations each\\n", n, inc);
pthread_t *threads = malloc(n * sizeof(pthread_t));
args *arg = malloc(n * sizeof(args));
for(int i = 0; i < n; i++) {
arg[i].start = i * inc;
arg[i].stop = (i + 1) * inc;
}
struct timespec t_start, t_stop;
clock_gettime(CLOCK_MONOTONIC_COARSE, &t_start);
for(int i = 0; i < n; i++)
pthread_create(&threads[i], 0, benchInsert, &arg[i]);
for(int i = 0; i < n; i++)
pthread_join(threads[i], 0);
for(int i = 0; i < n; i++)
pthread_create(&threads[i], 0, benchDelete, &arg[i]);
for(int i = 0; i < n; i++)
pthread_join(threads[i], 0);
clock_gettime(CLOCK_MONOTONIC_COARSE, &t_stop);
long wall_sec = t_stop.tv_sec - t_start.tv_sec;
long wall_nsec = t_stop.tv_nsec - t_start.tv_nsec;
long wall_msec = (wall_sec * 1000) + (wall_nsec / 1000000);
printf("done in %ld ms\\n", wall_msec);
printf("Program finished, printing list:\\n");
print_list();
return 0;
}
| 0
|
#include <pthread.h>
struct xurfaced xurfaced;
static void *xurfaced_thread_render(void *arg)
{
struct xurfaced *xurfaced = (struct xurfaced *)arg;
struct timespec ts;
struct timeval tv;
while (xurfaced->running)
{
pthread_mutex_lock(&xurfaced->mutexMenu);
xurfaced_render_prep(xurfaced->backend, xurfaced->menu);
xurfaced_render_blit(xurfaced->backend);
pthread_mutex_unlock(&xurfaced->mutexMenu);
gettimeofday(&tv, 0);
ts.tv_sec = tv.tv_sec;
ts.tv_nsec = tv.tv_usec * 1000;
ts.tv_nsec += 10 * 1000 * 1000;
pthread_cond_timedwait(&xurfaced->condRender, &xurfaced->mutexRender, &ts);
}
return 0;
}
static void *xurfaced_thread_event(void *arg)
{
struct xurfaced *xurfaced = (struct xurfaced *)arg;
while (xurfaced->running)
xurfaced_event_handler(xurfaced);
return 0;
}
static void xurfaced_signal_term(int sig)
{
xurfaced.running = 0;
}
static void xurfaced_signal_usr1(int sig)
{
struct xurfaced_menu *menu = xurfaced_menu_init(&xurfaced);
if (!menu)
return;
pthread_mutex_lock(&xurfaced.mutexMenu);
if (xurfaced.menu)
xurfaced_menu_destroy(xurfaced.menu);
xurfaced.menu = menu;
pthread_mutex_unlock(&xurfaced.mutexMenu);
}
void xurfaced_execute(char *command, int pipe[])
{
char args[4096], *argv[32];
memcpy(args, command, strlen(command) + 1);
argv[0] = strtok(args, " ");
unsigned int i = 0;
while ((argv[++i] = strtok(0, " ")));
int pid = fork();
int pchild;
if (pid == -1)
return;
if (!pid)
{
pchild = getpid();
if (pipe)
{
close(1);
dup(pipe[1]);
close(pipe[0]);
close(pipe[1]);
}
if (xurfaced.backend->display)
close(xurfaced.backend->descriptor);
setsid();
execvp(argv[0], argv);
exit(1);
}
if (pipe)
{
close(pipe[1]);
int status;
wait(&status);
}
}
static void xurfaced_run(struct xurfaced *xurfaced)
{
xurfaced->running = 1;
xurfaced->paused = 0;
pthread_mutex_init(&xurfaced->mutexRender, 0);
pthread_cond_init(&xurfaced->condRender, 0);
pthread_mutex_init(&xurfaced->mutexMenu, 0);
pthread_create(&xurfaced->threadRender, 0, xurfaced_thread_render, xurfaced);
pthread_create(&xurfaced->threadEvents, 0, xurfaced_thread_event, xurfaced);
pthread_join(xurfaced->threadEvents, 0);
pthread_join(xurfaced->threadRender, 0);
pthread_mutex_destroy(&xurfaced->mutexMenu);
pthread_cond_destroy(&xurfaced->condRender);
pthread_mutex_destroy(&xurfaced->mutexRender);
}
static void xurfaced_init_config(struct xurfaced_config *config)
{
char *home = getenv("HOME");
sprintf(config->base, "%s/.xurfaced", home);
sprintf(config->head, "%s/head", config->base);
sprintf(config->oninit, "%s/oninit", config->base);
sprintf(config->onexit, "%s/onexit", config->base);
sprintf(config->pid, "%s/pid", config->base);
sprintf(config->key, "%s/key", config->base);
sprintf(config->notify, "%s/notify", config->base);
}
static void xurfaced_init(struct xurfaced *xurfaced)
{
int status;
struct stat info;
char copyCmd[128];
signal(SIGTERM, xurfaced_signal_term);
signal(SIGUSR1, xurfaced_signal_usr1);
xurfaced_init_config(&xurfaced->config);
if (stat(xurfaced->config.base, &info) == -1)
{
sprintf(copyCmd, "/bin/cp -r /usr/share/xurfaced %s", xurfaced->config.base);
system(copyCmd);
}
char pid[32];
sprintf(pid, "%u", getpid());
xurfaced_config_write(xurfaced->config.pid, pid);
sync();
xurfaced->backend = xurfaced_display_create();
xurfaced->clients = xurfaced_client_list_create();
xurfaced_window_init(xurfaced->backend);
xurfaced_render_init(xurfaced->backend);
xurfaced_execute(xurfaced->config.oninit, 0);
wait(&status);
}
static void xurfaced_destroy(struct xurfaced *xurfaced)
{
xurfaced_menu_destroy(xurfaced->menu);
xurfaced_client_list_destroy(xurfaced->clients);
xurfaced_render_destroy(xurfaced->backend);
xurfaced_window_destroy(xurfaced->backend);
xurfaced_display_destroy(xurfaced->backend);
}
int main(int argc, char *argv[])
{
xurfaced_init(&xurfaced);
xurfaced_run(&xurfaced);
xurfaced_destroy(&xurfaced);
return 0;
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
int element[(800)];
int head;
int tail;
int amount;
} QType;
pthread_mutex_t m;
int __VERIFIER_nondet_int();
int stored_elements[(800)];
_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 == (800))
{
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 == (800))
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == (800))
{
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<((800)-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<(800); 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;
}
| 0
|
#include <pthread.h>
int value;
int n_wait;
pthread_mutex_t lock;
pthread_cond_t cond;
}sem_t;
int sem_init(sem_t *sem, int pshared, unsigned int value);
int sem_wait(sem_t *sem);
int sem_post(sem_t *sem);
int sem_trywait(sem_t *sem);
int sem_getvalue(sem_t *sem, int *sval);
int sem_destroy(sem_t *sem);
sem_t sem;
void* produtor(void *arg);
void* consumidor(void *arg);
int produce_item();
int remove_item();
void insert_item(int item);
void consume_item(int item);
double drand48(void);
void srand48(long int seedval);
int b[10];
int cont = 0;
int prodpos = 0;
int conspos = 0;
int main(){
pthread_t p[10];
pthread_t c[10];
sem_init(&sem, 0, 10);
int i;
int* id = 0;
srand48(time(0));
for(i = 0; i < 10; i++){
id = (int*)malloc(sizeof(int));
*id = i;
pthread_create(&p[i], 0, produtor, (void*)(id));
}
for(i = 0; i < 10; i++){
id = (int*)malloc(sizeof(int));
*id = i;
pthread_create(&c[i], 0, consumidor, (void*)(id));
}
pthread_join(p[0], 0);
pthread_join(c[0], 0);
return 0;
}
void* produtor(void* arg){
int i = *((int*)arg);
int item;
while(1){
sem_wait(&sem);
item = produce_item();
b[prodpos] = item;
prodpos = (prodpos + 1)%10;
sem_post(&sem);
insert_item(item);
}
}
void* consumidor(void* arg){
int i = *((int*)arg);
int item;
while(1){
sem_wait(&sem);
item = remove_item(conspos);
conspos = (conspos + 1)%10;
sem_post(&sem);
consume_item(item);
}
}
int produce_item(){
printf("Gerando...\\n");
sleep(1);
return (int)(drand48()*1000);
}
int remove_item(int conspos){
printf("removendo..\\n");
sleep(1);
return b[conspos];
}
void insert_item(int item){
printf("Unidades produzidas: %d\\n", item);
sleep(1);
}
void consume_item(int item){
printf("Consumindo %d unidades\\n", item);
sleep(1);
}
int sem_init(sem_t *sem, int pshared, unsigned int value){
sem->value = value;
sem->n_wait = 0;
pthread_mutex_init(&sem->lock, 0);
pthread_cond_init(&sem->cond, 0);
return 0;
}
int sem_wait(sem_t *sem){
pthread_mutex_lock(&sem->lock);
if(sem->value > 0)
sem->value--;
else{
sem->n_wait++;
pthread_cond_wait(&sem->cond, &sem->lock);
}
pthread_mutex_unlock(&sem->lock);
return 0;
}
int sem_post(sem_t *sem){
pthread_mutex_lock(&sem->lock);
if (sem->n_wait){
sem->n_wait--;
pthread_cond_signal(&sem->cond);
}else
sem->value++;
pthread_mutex_unlock(&sem->lock);
return 0;
}
int sem_trywait(sem_t *sem){
int r;
pthread_mutex_lock(&sem->lock);
if(sem->value > 0){
sem->value--;
r = 0;
}else
r = 1;
pthread_mutex_unlock(&sem->lock);
return r;
}
int sem_getvalue(sem_t *sem, int *sval){
pthread_mutex_lock(&sem->lock);
*sval = sem->value;
pthread_mutex_unlock(&sem->lock);
return 0;
}
int sem_destroy(sem_t *sem){
if(sem->n_wait)
return 1;
pthread_mutex_destroy(&sem->lock);
pthread_cond_destroy(&sem->cond);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t ma, mb;
int data1, data2;
pthread_mutex_t ja, jb;
int join1, join2;
void * thread1(void * arg)
{
pthread_mutex_lock(&ma);
data1++;
pthread_mutex_unlock(&ma);
pthread_mutex_lock(&ma);
data2++;
pthread_mutex_unlock(&ma);
pthread_mutex_lock(&ja);
join1 = 1;
pthread_mutex_unlock(&ja);
return 0;
}
void * thread2(void * arg)
{
pthread_mutex_lock(&ma);
data1+=5;
pthread_mutex_unlock(&ma);
pthread_mutex_lock(&ma);
data2-=6;
pthread_mutex_unlock(&ma);
pthread_mutex_lock(&jb);
join2 = 1;
pthread_mutex_unlock(&jb);
return 0;
}
void *main_continuation (void *arg);
pthread_t t1, t2;
int main()
{
pthread_mutex_init(&ja, 0);
pthread_mutex_init(&jb, 0);
join1 = join2 = 0;
pthread_mutex_init(&ma, 0);
pthread_mutex_init(&mb, 0);
data1 = 10;
data2 = 10;
pthread_create(&t1, 0, thread1, 0);
pthread_create(&t2, 0, thread2, 0);
pthread_t tt;
pthread_create (&tt, 0, main_continuation, 0);
pthread_join (tt, 0);
return 0;
}
void *main_continuation (void *arg)
{
int i;
pthread_mutex_lock (&ja);
i = join1;
pthread_mutex_unlock (&ja);
if (i == 0) return 0;
pthread_mutex_lock (&jb);
i = join2;
pthread_mutex_unlock (&jb);
if (i == 0) return 0;
__VERIFIER_assert (data1 == 16);
__VERIFIER_assert (data2 == 5);
return 0;
}
| 0
|
#include <pthread.h>
int g_Count = 0;
int nNum, nLoop;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t my_condition=PTHREAD_COND_INITIALIZER;
void *consume(void* arg)
{
int inum = 0;
inum = (int)arg;
while(1)
{
pthread_mutex_lock(&mutex);
printf("consum:%d\\n", inum);
while (g_Count == 0)
{
printf("consum:%d 开始等待\\n", inum);
pthread_cond_wait(&my_condition, &mutex);
printf("consum:%d 醒来\\n", inum);
}
printf("consum:%d 消费产品begin\\n", inum);
g_Count--;
printf("consum:%d 消费产品end\\n", inum);
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_exit(0);
}
void *produce(void* arg)
{
int inum = 0;
inum = (int)arg;
while(1)
{
pthread_mutex_lock(&mutex);
if (g_Count > 20)
{
printf("produce:%d 产品太多,需要控制,休眠\\n", inum);
pthread_mutex_unlock(&mutex);
sleep(1);
continue;
}
else
{
pthread_mutex_unlock(&mutex);
}
pthread_mutex_lock(&mutex);
printf("产品数量:%d\\n", g_Count);
printf("produce:%d 生产产品begin\\n", inum);
g_Count++;
printf("produce:%d 生产产品end\\n", inum);
printf("produce:%d 发条件signal begin\\n", inum);
pthread_cond_signal(&my_condition);
printf("produce:%d 发条件signal end\\n", inum);
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_exit(0);
}
int main()
{
int i =0;
pthread_t tidArray[2 +4 +10];
for (i=0; i<2; i++)
{
pthread_create(&tidArray[i], 0, consume, (void *)i);
}
sleep(1);
for (i=0; i<4; i++)
{
pthread_create(&tidArray[i+2], 0, produce, (void*)i);
}
for (i=0; i<2 +4; i++)
{
pthread_join(tidArray[i], 0);
}
printf("进程也要结束1233\\n");
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t thereAreOxygen, thereAreHydrogen;
int numberOxygen = 0 , numberHydrogen=0;
int activeOxygen = 0 , activeHydrogen=0;
long currentOxygen = 0 , currentHydrogen=0;
int flagExit=0;
void dataIn(){
int var=-3;
if(numberHydrogen==1 && flagExit==0){
while (var<-1) {
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n");
printf("Aviso: Queda 1 atomo de hidrogeno.\\nIngrese atomos de hidrogeno o ingrese -1 para salir:", numberHydrogen );
scanf("%d",&var);
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n");
}
if(var==-1){
flagExit=1;
}else{
numberHydrogen+=var;
}
}
var=-3;
if(numberOxygen==0 && numberHydrogen>0 && flagExit==0){
while (var<-1) {
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n");
printf("Aviso: Hay %d atomo(s) de hidrogeno, se necesitan %d atomo(s) de oxigeno.\\nIngrese atomos de oxigeno o ingrese -1 para salir: ", numberHydrogen,(numberHydrogen/2));
scanf("%d",&var);
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n");
}
if(var==-1){
flagExit=1;
}else{
numberOxygen+=var;
}
}
var=-3;
if(numberHydrogen==0 && numberOxygen>0 && flagExit==0){
while (var<-1) {
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n");
printf("Aviso: Hay %d atomo(s) de oxigeno, se necesitan %d atomo(s) hidrogeno.\\nIngrese atomos de hidrogeno o ingrese -1 para salir: ", numberOxygen, (numberOxygen*2) );
scanf("%d",&var);
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n");
}
if(var==-1){
flagExit=1;
}else{
numberHydrogen+=var;
}
}
if (flagExit==1) {
printf("Escriba 1 para salir, o cualquier numero para cancelar.. :");
scanf("%d",&var);
if(var==1){
exit(0);
}
else{
flagExit=0;
dataIn();
}
}
}
void startOxygen(){
pthread_mutex_lock(&lock);
++activeOxygen;
while (activeHydrogen<2 && activeOxygen>1) {
pthread_cond_wait(&thereAreOxygen, &lock);
}
++currentOxygen;
--numberOxygen;
pthread_mutex_unlock(&lock);
}
void doneOxygen() {
pthread_mutex_lock(&lock);
--activeOxygen;
pthread_cond_broadcast(&thereAreHydrogen);
pthread_mutex_unlock(&lock);
}
void startHydrogen(){
pthread_mutex_lock(&lock);
++activeHydrogen;
while (activeOxygen<1 && activeHydrogen>2) {
pthread_cond_wait(&thereAreHydrogen, &lock);
}
--numberHydrogen;
++currentHydrogen;
pthread_mutex_unlock(&lock);
}
void doneHydrogen() {
pthread_mutex_lock(&lock);
--activeHydrogen;
pthread_cond_signal(&thereAreOxygen);
pthread_mutex_unlock(&lock);
}
void *Oxigeno(void *id) {
long tid = (long)id;
printf("oxigeno (%ld) preparado para ser H2O \\n", tid);
startOxygen();
printf("oxigeno (%ld) convirtiendose \\n",tid);
sleep(rand()%5);
printf("oxigeno (%ld) es H2O \\n", tid);
doneOxygen();
dataIn();
sleep(rand()%5);
pthread_exit(0);
}
void *Hidrogeno(void *id) {
long tid = (long)id;
startHydrogen();
sleep(rand()%5);
doneHydrogen();
sleep(rand()%5);
pthread_exit(0);
}
int main(int argc, char const *argv[]) {
int n_oxygen=-3;
int n_hydrogen=-3;
pthread_t oxygen, hydrogen[2];
long i=0;
srand(time(0));
printf("\\n--------------Nombre del programa--------------\\n\\tCreación de moleculas de agua\\n\\n");
while (n_oxygen<-1){
printf("Ingrese numero de Oxigeno: ");
scanf("%d",&n_oxygen);
}
numberOxygen+=n_oxygen;
while (n_hydrogen<-1) {
printf("Ingrese numero de hidrogeno:");
scanf("%d",&n_hydrogen);
}
numberHydrogen+=n_hydrogen;
while ( numberOxygen>0 && numberHydrogen>0) {
for (i=0; i<2; i++) {
if (pthread_create(&hydrogen[i], 0, Hidrogeno, (void *)(i))) {
printf("Error creando thread hidrogeno[%ld]\\n", i);
exit(1);
}
}
i=0;
if (pthread_create(&oxygen, 0,Oxigeno, (void *)currentOxygen)) {
printf("Error creando thread oxigeno[%ld]\\n", i);
exit(1);
}
void *status;
for (i=0; i<2; i++)
{
pthread_join(hydrogen[i],&status);
}
pthread_join(oxygen,&status);
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_t io_thread;
char input[64000];
uint16_t input_size, input_offset;
uint8_t io_mode;
char vm_shared_io_buffer[64000];
uint16_t io_buffer_index, io_buffer_ri;
pthread_mutex_t io_mutex;
int valid_program_char(char ch) {
return ('a' <= ch && 'z' >= ch) || ch == '\\r' || ch == '\\n' || ch == ' ';
}
void handle_vm_io(char ch) {
if (get_curses_mode() & SET_BP_ACTIVE) {
char chr;
int i = 0;
char buffer[64];
while((chr = getchar()) != '\\r') {
buffer[i++] = chr;
mvwprintw(status_window, 5, 30+i, "%c", chr);
wrefresh(status_window);
}
buffer[i] = 0;
set_breakpoint(strtol(buffer, 0, 16));
disable_set_breakpoint();
} else
if (ch == 27) {
ch = getchar();
if (ch == 'd') run_disassembler();
if (ch == 'x') dump_disassembler();
if (ch == 'a') enable_trace();
if (ch == 'e') next_step();
if (ch == 'q') enable_set_breakpoint();
if (ch == 'w') enable_set_value();
}
}
void * handle_io() {
while(1) {
char ch;
if (input_offset < input_size) {
ch = input[input_offset++];
} else {
ch = getchar_unlocked();
}
if (valid_program_char(ch)) {
pthread_mutex_lock(&io_mutex);
vm_shared_io_buffer[io_buffer_index++] = ((ch == '\\r' || ch == '\\n') ? '\\n' : ch);
if (io_buffer_index > 63999) {
io_buffer_index = 0;
}
pthread_mutex_unlock(&io_mutex);
} else {
handle_vm_io(ch);
}
}
}
void create_io_thread() {
if(pthread_create(&io_thread, 0, handle_io, 0)) {
perror("Error creating thread\\n");
exit(1);
} else {
printf("IO Thread created successfuly\\n");
}
}
char getchr() {
char ch;
if (get_curses_mode() & CURSES_MODE_ACTIVE) {
pthread_mutex_lock(&io_mutex);
if (io_buffer_ri < io_buffer_index || (io_buffer_ri && !io_buffer_index)) {
ch = vm_shared_io_buffer[io_buffer_ri++];
if (io_buffer_ri > 63999)
io_buffer_ri = 0;
wprintw(vm_window, "%c", ch);
wrefresh(vm_window);
pthread_mutex_unlock(&io_mutex);
return ch;
} else {
ch = -1;
}
pthread_mutex_unlock(&io_mutex);
return ch;
} else {
return getchar();
}
}
void putchr(uint16_t ch) {
if (get_curses_mode() & CURSES_MODE_ACTIVE) {
wprintw(vm_window, "%c", ch);
wrefresh(vm_window);
} else {
putchar(ch);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t m[1];
pthread_cond_t c[1];
volatile long x, y;
void produce(long batch_id, long n_consumers) {
pthread_mutex_lock(m);
assert(y == batch_id * n_consumers);
while (x != y) {
pthread_cond_wait(c, m);
}
y += n_consumers;
pthread_cond_broadcast(c);
pthread_mutex_unlock(m);
}
void consume(long batch_id, long n_consumers) {
pthread_mutex_lock(m);
(void)batch_id;
(void)n_consumers;
while (x == y) {
pthread_cond_wait(c, m);
}
x++;
if (x == y) {
pthread_cond_signal(c);
}
pthread_mutex_unlock(m);
}
long n;
long n_consumers;
} arg_t;
void * producer(void * arg_) {
arg_t * arg = (arg_t *)arg_;
long n = arg->n;
long n_consumers = arg->n_consumers;
long i;
for (i = 0; i < n; i++) {
produce(i, n_consumers);
}
return 0;
}
void * consumer(void * arg_) {
arg_t * arg = (arg_t *)arg_;
long n = arg->n;
long n_consumers = arg->n_consumers;
long i;
for (i = 0; i < n; i++) {
consume(i, n_consumers);
}
return 0;
}
int main(int argc, char ** argv) {
long n = (argc > 1 ? atoi(argv[1]) : 1000);
long n_consumers = (argc > 2 ? atoi(argv[2]) : 100);
pthread_mutex_init(m, 0);
pthread_cond_init(c, 0);
x = y = 0;
arg_t arg[1] = { { n, n_consumers } };
pthread_t cons_tids[n_consumers];
long i;
for (i = 0; i < n_consumers; i++) {
pthread_create(&cons_tids[i], 0, consumer, arg);
}
pthread_t prod_tid;
pthread_create(&prod_tid, 0, producer, arg);
for (i = 0; i < n_consumers; i++) {
pthread_join(cons_tids[i], 0);
}
pthread_join(prod_tid, 0);
if (n * n_consumers == x && y == x) {
printf("OK: n * n_consumers == x == y == %ld\\n", x);
return 0;
} else {
printf("NG: n * n_consumers == %ld, x == %ld, y == %ld\\n",
n * n_consumers, x, y);
return 1;
}
}
| 0
|
#include <pthread.h>
int iCounter = 0;
pthread_mutex_t pmMux1 = PTHREAD_MUTEX_INITIALIZER;
void *PrintMessage (void *pvData)
{
char *pszMessage = (char *)pvData;
pthread_mutex_lock (&pmMux1);
iCounter += 1;
printf ("In %s: iCounter=%d\\n", pszMessage, iCounter);
usleep(200);
iCounter += 1;
printf ("In %s: iCounter=%d\\n", pszMessage, iCounter);
usleep(200);
pthread_mutex_unlock (&pmMux1);
return 0;
}
void main (void)
{
pthread_t pThread1, pThread2;
char *pszMessage1 = "Thread 1";
char *pszMessage2 = "Thread 2";
printf("Before threads started.\\n");
pthread_create (&pThread1, 0, PrintMessage, (void *) pszMessage1);
pthread_create (&pThread2, 0, PrintMessage, (void *) pszMessage2);
printf("After threads started.\\n");
pthread_join(pThread1, 0);
pthread_join(pThread2, 0);
printf("After threads finished.\\n");
}
| 1
|
#include <pthread.h>
static pthread_mutex_t lock;
static pthread_cond_t cond;
static int running;
static int go;
static char *port;
void *worker(void *arg)
{
struct mrpc_conn_set *cset=arg;
struct mrpc_connection *conn;
int i;
int ret;
pthread_mutex_lock(&lock);
running++;
pthread_cond_broadcast(&cond);
while (!go)
pthread_cond_wait(&cond, &lock);
pthread_mutex_unlock(&lock);
for (i=0; i<50; i++) {
ret=mrpc_conn_create(&conn, cset, 0);
if (ret)
die("%s in mrpc_conn_create() on iteration %d",
strerror(ret), i);
ret=mrpc_connect(conn, AF_UNSPEC, 0, port);
if (ret)
die("%s in mrpc_connect() on iteration %d",
strerror(ret), i);
sync_client_set_ops(conn);
sync_client_run(conn);
trigger_callback_sync(conn);
invalidate_sync(conn);
mrpc_conn_close(conn);
mrpc_conn_unref(conn);
}
pthread_mutex_lock(&lock);
running--;
pthread_mutex_unlock(&lock);
pthread_cond_broadcast(&cond);
return 0;
}
int main(int argc, char **argv)
{
struct mrpc_conn_set *sset;
struct mrpc_conn_set *cset;
pthread_t thr;
int i;
sset=spawn_server(&port, proto_server, sync_server_accept, 0,
5);
mrpc_set_disconnect_func(sset, disconnect_normal);
if (mrpc_conn_set_create(&cset, proto_client, 0))
die("Couldn't create conn set");
mrpc_set_disconnect_func(cset, disconnect_user);
for (i=0; i<5; i++)
start_monitored_dispatcher(cset);
pthread_mutex_init(&lock, 0);
pthread_cond_init(&cond, 0);
for (i=0; i<25; i++) {
if (pthread_create(&thr, 0, worker, cset))
die("Couldn't create thread");
if (pthread_detach(thr))
die("Couldn't detach thread");
}
pthread_mutex_lock(&lock);
while (running < 25)
pthread_cond_wait(&cond, &lock);
go=1;
pthread_cond_broadcast(&cond);
while (running)
pthread_cond_wait(&cond, &lock);
pthread_mutex_unlock(&lock);
mrpc_conn_set_unref(cset);
mrpc_listen_close(sset);
mrpc_conn_set_unref(sset);
expect_disconnects(25 * 50, 25 * 50, 0);
free(port);
return 0;
}
| 0
|
#include <pthread.h>
static void sig_alrm(int signo);
static sigjmp_buf jmpbuf;
static void sig_alrm(int signo)
{
siglongjmp(jmpbuf, 1);
}
int udp_recv(int sockfd, struct packet_t* packet, struct sockaddr* sockAddr)
{
int len = sizeof(*sockAddr);
bzero(sockAddr, len);
if(recvfrom(sockfd, packet, sizeof(*packet), 0, sockAddr, &len) != -1)
{
return 1;
}
printf("error udp_recv:recvfrom errno:%s\\n", strerror(errno));
return -1;
}
int udp_send(int sockfd, struct packet_t* packet, struct sockaddr* sockAddr)
{
int len = sockAddr == 0? 0 : sizeof(*sockAddr);
if(sendto(sockfd, packet, sizeof(*packet), 0, sockAddr, len) > 0)
{
return 1;
}
printf("error udp_send:sendto errno:%s\\n", strerror(errno));
return -1;
}
int deQueue(struct packet_t* packet)
{
pthread_mutex_lock(&queMutex);
if(queueCapacity == queueSize)
{
pthread_mutex_unlock(&queMutex);
return -1;
}
memcpy(packet, &queue[tail], sizeof(struct packet_t));
bzero(&queue[tail], sizeof(struct packet_t));
queueCapacity++;
tail = (tail+1) % queueSize;
pthread_mutex_unlock(&queMutex);
return 1;
}
int peekQueueTail(struct packet_t* packet)
{
pthread_mutex_lock(&queMutex);
if(queueCapacity == queueSize)
{
pthread_mutex_unlock(&queMutex);
return -1;
}
memcpy(packet, &queue[tail], sizeof(struct packet_t));
pthread_mutex_unlock(&queMutex);
return 1;
}
int peekQueueHead(struct packet_t* packet)
{
pthread_mutex_lock(&queMutex);
if(queueCapacity == 0)
{
pthread_mutex_unlock(&queMutex);
return -1;
}
memcpy(packet, &queue[head], sizeof(struct packet_t));
pthread_mutex_unlock(&queMutex);
return 1;
}
int enQueue(struct packet_t* packet)
{
pthread_mutex_lock(&queMutex);
int n;
if(queueCapacity == 0)
{
pthread_mutex_unlock(&queMutex);
return -1;
}
if(queueCapacity == queueSize)
{
memcpy(&queue[head], packet, sizeof(struct packet_t));
queueCapacity--;
pthread_mutex_unlock(&queMutex);
return 1;
}
else if((n = packet->seq - queue[head].seq) == 1)
{
head = (head+1)%queueSize;
memcpy(&queue[head], packet, sizeof(struct packet_t));
queueCapacity--;
while((head+1)%queueSize!=tail && queue[(head+1)%queueSize].seq!=0)
{
head = (head+1)%queueSize;
queueCapacity--;
}
pthread_mutex_unlock(&queMutex);
return 1;
}
else if(n > 0 && n <= queueCapacity)
{
memcpy(&queue[(head+n)%queueSize], packet, sizeof(struct packet_t));
pthread_mutex_unlock(&queMutex);
return -1;
}
pthread_mutex_unlock(&queMutex);
return -1;
}
| 1
|
#include <pthread.h>
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo
{
int f_count;
pthread_mutex_t f_lock;
int f_id;
struct foo *f_next;
};
struct foo *foo_alloc(int id)
{
struct foo *fp;
int idx;
if((fp = malloc(sizeof(struct foo))) != 0)
{
fp->f_count = 1;
fp->f_id = id;
if(pthread_mutex_init(&fp->f_lock, 0) != 0)
{
free(fp);
return 0;
}
}
idx = (((unsigned long)id)%29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
return (fp);
}
void foo_hold(struct foo *fp)
{
pthread_mutex_lock(&hashlock);
fp->f_count++;
pthread_mutex_unlock(&hashlock);
}
struct foo *foo_find(int id)
{
struct foo *fp;
pthread_mutex_lock(&hashlock);
for(fp = fh[(((unsigned long)id)%29)]; fp != 0; fp = fp->f_next)
{
if(fp->f_id == id)
{
fp->f_count++;
break;
}
}
pthread_mutex_lock(&hashlock);
return (fp);
}
void foo_rele(struct foo *fp)
{
struct foo *tfp;
int idx;
pthread_mutex_lock(&hashlock);
if(--fp->f_count == 0)
{
idx = (((unsigned long)fp->f_id)%29);
tfp = fh[idx];
if(tfp == fp)
{
fh[idx] = fp->f_next;
}
else
{
while(tfp->f_next != fp)
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(&fp->f_lock);
}
}
| 0
|
#include <pthread.h>
static int items_sent = 0;
static int items_recieved = 0;
char buf[10];
int items_onBuffer;
int in, out;
pthread_mutex_t mutex;
pthread_cond_t add;
pthread_cond_t take;
} buffer_t;
buffer_t buff;
void * producer(void *);
void * consumer(void *);
init_buffer(void)
{
buff.in = 0;
buff.out = 0;
buff.items_onBuffer = 0;
}
main( int argc, char *argv[] )
{
long i;
pthread_cond_init(&(buff.add), 0);
pthread_cond_init(&(buff.take), 0);
pthread_t prod_thrs[16];
pthread_t cons_thrs[32];
pthread_attr_t attr;
pthread_attr_init (&attr);
printf("Buffer size = %d, items to send = %d\\n",
10, 8*(1024*1024));
printf("\\n The System is working....\\n");
for(i = 0; i < 16; i++)
pthread_create(&prod_thrs[i], &attr, producer, (void *)i);
for(i = 0; i < 32; i++)
pthread_create(&cons_thrs[i], &attr, consumer, (void *)i);
pthread_attr_destroy(&attr);
for (i = 0; i < 16; i++)
pthread_join(prod_thrs[i], 0);
for (i = 0; i < 32; i++)
pthread_join(cons_thrs[i], 0);
printf("\\nmain() reporting that all %d threads have terminated\\n", i);
}
void * producer(void *thr_id)
{
int item;
int i;
int pquite=0;
while(!pquite)
{
if(items_sent<8*(1024*1024))
{
pthread_mutex_lock(&(buff.mutex));
if (buff.items_onBuffer == 10)
while (buff.items_onBuffer == 10)
pthread_cond_wait(&(buff.take), &(buff.mutex) );
item=items_sent++;
buff.buf[buff.in++] = item;
buff.in = (buff.in+1)%10;
buff.items_onBuffer++;
}
else
pquite=1;
pthread_cond_signal(&(buff.add));
pthread_mutex_unlock(&(buff.mutex));
}
printf("producer exiting.\\n");
pthread_exit(0);
}
void * consumer(void *thr_id)
{
int item;
int i;
int c_quit=0;
while(!c_quit) {
if (items_recieved<8*(1024*1024))
{
pthread_mutex_lock(&(buff.mutex) );
if (buff.items_onBuffer == 0)
while(buff.items_onBuffer == 0)
pthread_cond_wait(&(buff.add), &(buff.mutex) );
item = buff.buf[buff.out++];
buff.out = (buff.out+1)%10;
buff.items_onBuffer--;
items_recieved++;
pthread_cond_signal(&(buff.take));
pthread_mutex_unlock(&(buff.mutex));
}
else
c_quit=1;
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t hMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t h2Mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t oMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t conditionHydrogen = PTHREAD_COND_INITIALIZER;
pthread_cond_t conditionH2ydrogen = PTHREAD_COND_INITIALIZER;
pthread_cond_t conditionOxygen = PTHREAD_COND_INITIALIZER;
int currentHydrogenAtoms = 0;
int currentOxygenAtoms = 0;
int moleculesCreated = 0;
char hydrogenUsed = 0;
char oxygenUsed = 0;
void *addHydrogen(void *args) {
pthread_mutex_lock(&hMutex);
printf("ADDING one atom of HYDROGEN - (ID: %lu)\\n", pthread_self());
currentHydrogenAtoms++;
pthread_cond_signal(&conditionH2ydrogen);
pthread_cond_signal(&conditionHydrogen);
while(currentOxygenAtoms < 1) {
pthread_cond_wait(&conditionOxygen, &hMutex);
}
pthread_mutex_unlock(&hMutex);
pthread_mutex_lock(&h2Mutex);
while(currentHydrogenAtoms < 2) {
pthread_cond_wait(&conditionH2ydrogen, &h2Mutex);
}
hydrogenUsed++;
printf("USING one atom of HYDROGEN - (ID: %lu)\\n", pthread_self());
if (hydrogenUsed == 2 && oxygenUsed == 1) {
hydrogenUsed = oxygenUsed = 0;
currentHydrogenAtoms -= 2;
currentOxygenAtoms--;
moleculesCreated++;
}
pthread_mutex_unlock(&h2Mutex);
}
void *addOxygen(void *args) {
pthread_mutex_lock(&oMutex);
printf("ADDING one atom of OXYGEN - (ID: %lu)\\n", pthread_self());
currentOxygenAtoms++;
pthread_cond_signal(&conditionOxygen);
while(currentHydrogenAtoms < 2) {
pthread_cond_wait(&conditionHydrogen, &oMutex);
}
printf("USING one atom of OXYGEN - (ID: %lu)\\n", pthread_self());
oxygenUsed++;
if (hydrogenUsed == 2 && oxygenUsed == 1) {
hydrogenUsed = oxygenUsed = 0;
currentHydrogenAtoms -= 2;
currentOxygenAtoms--;
moleculesCreated++;
}
pthread_mutex_unlock(&oMutex);
}
int main() {
int numberOfMolecules = 0;
printf("Indique el numero de moleculas H20 a crear: ");
scanf("%d", &numberOfMolecules);
int nOfThreads = (numberOfMolecules * 2) + numberOfMolecules;
int hCreated = 0;
int oCreated = 0;
pthread_t allThreads[nOfThreads];
pthread_mutex_init( &hMutex, 0 );
pthread_mutex_init( &oMutex, 0 );
for (int i = 0; i < nOfThreads; ++i) {
if (hCreated < (numberOfMolecules * 2) && oCreated < numberOfMolecules) {
if ((rand() % 100) >= 50) {
pthread_create(&allThreads[i], 0, addOxygen, 0);
oCreated++;
} else {
pthread_create(&allThreads[i], 0, addHydrogen, 0);
hCreated++;
}
} else if (hCreated < (numberOfMolecules * 2)) {
pthread_create(&allThreads[i], 0, addHydrogen, 0);
hCreated++;
} else if (oCreated < numberOfMolecules) {
pthread_create(&allThreads[i], 0, addOxygen, 0);
oCreated++;
}
sleep(1);
}
for (int i = 0; i < nOfThreads; i++) {
pthread_join(allThreads[i],0);
}
return 0;
}
| 0
|
#include <pthread.h>
struct producers
{
int buffer[4];
pthread_mutex_t lock;
int readpos, writepos;
pthread_cond_t notempty;
pthread_cond_t notfull;
};
void init(struct producers *b)
{
pthread_mutex_init(&b->lock,0);
pthread_cond_init(&b->notempty,0);
pthread_cond_init(&b->notfull,0);
b->readpos=0;
b->writepos=0;
}
void put(struct producers *b, int data)
{
pthread_mutex_lock(&b->lock);
while((b->writepos+1)%4==b->readpos)
{
pthread_cond_wait(&b->notfull,&b->lock);
}
b->buffer[b->writepos]=data;
b->writepos++;
if(b->writepos>=4) b->writepos=0;
pthread_cond_signal(&b->notempty);
pthread_mutex_unlock(&b->lock);
}
int get(struct producers *b)
{
int data;
pthread_mutex_lock(&b->lock);
while(b->writepos==b->readpos)
{
pthread_cond_wait(&b->notempty,&b->lock);
}
data=b->buffer[b->readpos];
b->readpos++;
if(b->readpos>=4) b->readpos=0;
pthread_cond_signal(&b->notfull);
pthread_mutex_unlock(&b->lock);
return data;
}
struct producers buffer;
void *producer(void *data)
{
int n;
for(n=0;n<10;n++)
{
printf("Producer : %d-->\\n",n);
put(&buffer,n);
}
put(&buffer,(-1));
return 0;
}
void *consumer(void *data)
{
int d;
while(1)
{
d=get(&buffer);
if(d==(-1)) break;
printf("Consumer: --> %d\\n",d);
}
return 0;
}
int main()
{
pthread_t tha,thb;
void *retval;
init(&buffer);
pthread_create(&tha,0,producer,0);
pthread_create(&thb,0,consumer,0);
pthread_join(tha,&retval);
pthread_join(thb,&retval);
return 0;
}
| 1
|
#include <pthread.h>
int cs_work(const char *pathname){
struct dirent *dirEntry;
DIR *dir;
dir = opendir(pathname);
dirEntry = readdir(dir);
int counter = 0;
while ((dirEntry = readdir(dir))){
char p[1<<10];
int strLength = snprintf(p, sizeof(p) - 1, "%s/%s", pathname, dirEntry->d_name);
p[strLength] = 0;
if (dirEntry->d_type == DT_DIR){
if (strcmp(dirEntry->d_name, ".") == 0 || strcmp(dirEntry->d_name, "..") == 0)
continue;
counter += cs_work(p);
}else if (dirEntry->d_type == DT_LNK || dirEntry->d_type == DT_REG){
if (strncmp(dirEntry->d_name, ".", 1) == 0)
continue;
FILE *fd;
fd = fopen(p, "r");
fseek(fd, 0L, 2);
counter += ftell(fd);
fclose(fd);
}
}
closedir(dir);
return counter;
}
int co_work(const char *pathname){
struct dirent *dirEntry;
DIR *dir;
dir = opendir(pathname);
dirEntry = readdir(dir);
int counter = 0;
while ((dirEntry = readdir(dir))){
char p[1<<10];
int strLength = snprintf(p, sizeof(p)-1, "%s/%s", pathname, dirEntry->d_name);
p[strLength] = 0;
if (dirEntry->d_type == DT_DIR){
if (strcmp(dirEntry->d_name, ".") == 0 || strcmp(dirEntry->d_name, "..") == 0)
continue;
counter += co_work(p);
}
else if (dirEntry->d_type == DT_LNK || dirEntry->d_type == DT_REG){
if (strncmp(dirEntry->d_name, ".", 1) == 0)
continue;
counter++;
}
}
closedir(dir);
return counter;
}
void *func(void *vars){
pthread_mutex_t *mut = vars;
while (1){
pthread_mutex_lock(mut);
int flag = -1;
char name[1<<7] = {0};
char tmp[1<<5] = {0};
if (scanf("%s %s", tmp, name) == EOF){
pthread_mutex_unlock(mut);
return 0;
}
if (strcmp("co", tmp) == 0){
flag = 1;
}else{
flag = 0;
}
pthread_mutex_unlock(mut);
int answer = -1;
if (flag == 0){
answer = cs_work(name);
}else if (flag == 1){
answer = co_work(name);
}
printf("%s %s %d\\n", flag ? "co":"cs", name, answer);
}
}
int main(int argc, const char * argv[]){
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, 0);
int threadsNum = atoi(argv[1]);
pthread_t **threads = (pthread_t**)calloc(threadsNum, sizeof(pthread_t*));
pthread_mutex_t *data = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t));
data = &mutex;
for (int i = 0; i < threadsNum; i++){
threads[i] = (pthread_t*)calloc(1, sizeof(pthread_t));
pthread_create(threads[i], 0, func, data);
}
for (int i = 0; i < threadsNum; i++){
pthread_join(*threads[i], 0);
free(threads[i]);
}
return 0;
}
| 0
|
#include <pthread.h>
int shared_count;
int thread_count;
pthread_mutex_t barrier_mutex;
void Usage(char* prog_name);
void *Thread_work(void* rank);
int main(int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
double start, finish;
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);
shared_count = 0;
GET_TIME(start);
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);
GET_TIME(finish);
printf("Elapsed time = %e seconds\\n", finish - start);
pthread_mutex_destroy(&barrier_mutex);
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;
int i;
for (i = 0; i < 10; i++) {
pthread_mutex_lock(&barrier_mutex);
shared_count++;
pthread_mutex_unlock(&barrier_mutex);
printf("At iteration %d, thread %ld arrives\\n", i, my_rank);
while (shared_count < thread_count);
if (shared_count==thread_count-1)
shared_count = 0;
}
return 0;
}
| 1
|
#include <pthread.h>
const char * working_extension;
int working_count = 0;
int working_interval = 0;
int working_progress = 0;
pthread_mutex_t parameter_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t timelapse_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_t worker;
bool working = 0;
bool should_cancel = 0;
long seconds_to_nanos(const long seconds) {
return seconds * 1000000000L;
}
void nanos_to_time(struct timespec * target, const long nanos) {
target->tv_sec = nanos / 1000000000L;
target->tv_nsec = nanos % 1000000000L;
}
int timeval_subtract ( struct timeval *result, struct timeval *x, struct timeval *y) {
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000L + 1;
y->tv_usec -= 1000000L * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000L) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000L;
y->tv_usec += 1000000L * nsec;
y->tv_sec -= nsec;
}
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
return x->tv_sec < y->tv_sec;
}
long time_diff(struct timeval * start, struct timeval * end) {
struct timeval res;
timeval_subtract(&res, end, start);
return (res.tv_usec * 1000);
}
void * internal_capture(void * arg) {
pthread_mutex_lock(&timelapse_lock);
struct timeval start, end;
struct timespec to_wait, waited;
int local_count = tl_get_count();
int local_interval = tl_get_interval();
char time_buffer[15];
const long nano_interval = seconds_to_nanos(local_interval);
const int num_len = digits(local_count);
const int buf_len = num_len + 18;
char * buffer = (char*) malloc(sizeof(char) * buf_len);
long diff = 0;
for(int i = 0; i < local_count; i++) {
gettimeofday(&start, 0);
time_t t = time(0);
strftime(time_buffer, 15, "%Y%m%d%H%M%S", localtime(&t));
snprintf(buffer, buf_len, "%0*d_%s", num_len, i+1, time_buffer);
printf("Timelapse capture: %s\\n", buffer);
tc_take_picture(buffer, 0, 1);
pthread_mutex_lock(¶meter_lock);
working_progress = i + 1;
pthread_mutex_unlock(¶meter_lock);
gettimeofday(&end, 0);
if(i < (local_count -1)) {
diff = time_diff(&start, &end);
nanos_to_time(&to_wait, nano_interval - diff);
if(nanosleep(&to_wait, &waited) == -1) {
pthread_mutex_lock(¶meter_lock);
if(should_cancel) {
pthread_mutex_unlock(¶meter_lock);
break;
}
pthread_mutex_unlock(¶meter_lock);
}
}
pthread_mutex_lock(¶meter_lock);
if(should_cancel) {
pthread_mutex_unlock(¶meter_lock);
break;
}
pthread_mutex_unlock(¶meter_lock);
}
free(buffer);
working = 0;
pthread_mutex_unlock(&timelapse_lock);
return 0;
}
int tl_start(const int interval, const int count, char * prefix) {
if(tl_in_progress()) {
return -1;
}
pthread_mutex_lock(&timelapse_lock);
pthread_mutex_lock(¶meter_lock);
working_interval = interval;
working_count = count;
working = 1;
should_cancel = 0;
pthread_mutex_unlock(&timelapse_lock);
pthread_create(&worker, 0, &internal_capture, 0);
pthread_mutex_unlock(¶meter_lock);
return 0;
}
int tl_get_count() {
pthread_mutex_lock(¶meter_lock);
int result = working_count;
pthread_mutex_unlock(¶meter_lock);
return result;
}
int tl_get_progress() {
pthread_mutex_lock(¶meter_lock);
int result = working_progress;
pthread_mutex_unlock(¶meter_lock);
return result;
}
int tl_get_interval() {
pthread_mutex_lock(¶meter_lock);
int result = working_interval;
pthread_mutex_unlock(¶meter_lock);
return result;
}
bool tl_in_progress() {
pthread_mutex_lock(¶meter_lock);
bool result = working;
pthread_mutex_unlock(¶meter_lock);
return result;
}
void tl_cancel() {
if(tl_in_progress()) {
pthread_mutex_lock(¶meter_lock);
should_cancel = 1;
pthread_kill(worker,SIGALRM);
pthread_mutex_unlock(¶meter_lock);
}
}
void tl_wait() {
pthread_join(worker, 0);
}
int tl_get_status(FILE * output) {
fprintf(output, "{\\n");
if(tl_in_progress()) {
fprintf(output, "\\t\\"status\\" : \\"processing\\",\\n");
fprintf(output, "\\t\\"interval\\" : \\"%d\\",\\n", tl_get_interval());
fprintf(output, "\\t\\"number\\" : \\"%d\\",\\n", tl_get_count());
fprintf(output, "\\t\\"current\\" : \\"%d\\"\\n", tl_get_progress());
}
else {
fprintf(output, "\\t\\"status\\" : \\"off\\"\\n");
}
fprintf(output, "}\\n");
fflush(output);
return 0;
}
| 0
|
#include <pthread.h>
void *takeThisRequest(char *buffer, int new_socket, int typeCon) {
char request[1024];
strcpy(request, buffer);
char *split;
char *word;
char *requestFile;
char *connectionType;
split = strtok(request, " ");
char connection[10];
int flag=0;
while (split != 0) {
word = split;
if ((strcmp(split, "GET") == 0) || (strcmp(split, "HEAD") == 0) || (strcmp(split, "DELETE") == 0)) {
split = strtok(0, " ");
flag=1;
requestFile = split;
printf("Requested File: %s\\n", requestFile);
if (strcmp(word, "GET") == 0){
getRequest(requestFile, new_socket, typeCon);
break;
}else{
if (strcmp(word, "HEAD") == 0){
printf("paei head\\n");
sendHead(requestFile, new_socket, typeCon);
break;
}else{
if (strcmp(word, "DELETE") == 0){
sendDelete(requestFile, new_socket, typeCon);
break;
}
}
}
}
split = strtok(0, " ");
}
if (flag==0){
sendNotImpl(new_socket, typeCon);
}
return;
}
int handleThreads(int new_socket) {
char *buffer = malloc(bufsize);
recv(new_socket, buffer, bufsize, 0);
while (buffer == 0) {
recv(new_socket, buffer, bufsize, 0);
}
char request[1024];
int typeCon = -1;
char *split;
char *word;
char *requestFile;
strcpy(request, buffer);
char findCon[50];
char connectionType[11];
char *sub;
sub = strstr(request, "Connection:");
char *sub2 = strstr(sub, "keep-alive");
char *sub3 = strstr(sub, "close");
if (sub2 != 0) {
typeCon = 1;
}
if (sub3 != 0) {
typeCon = 0;
}
takeThisRequest(buffer, new_socket, typeCon);
if (typeCon == 1) {
printf("Epistrefei keep-alive\\n");
return 1;
} else {
printf("kleinei i sindesi\\n");
close(new_socket);
return 0;
}
return 0;
}
void *handle() {
pthread_mutex_lock(&mut);
int now_socket = dequeue(queue);
pthread_mutex_unlock(&mut);
int goOn = handleThreads(now_socket);
while (goOn == 1) {
printf("apo handle\\n");
goOn = handleThreads(now_socket);
}
pthread_mutex_lock(&mut);
busy = busy - 1;
pthread_cond_wait(&con, &mut);
handle();
return;
}
| 1
|
#include <pthread.h>
void init_sem_and_mutexes();
void destroy_sem_and_mutexes();
int main()
{
int err=0;
init_sem_and_mutexes();
err = udp_init_client(&tinfo_connection.conn, UDP_PORT, SERVER_IP);
if (err!=0)
{
printf("error connecting to server");
}
printf("created udp conn\\n");
pthread_t udprecv, pidctrl, sighandl;
err = pthread_create(&udprecv, 0, UDP_listener, 0);
if (err!=0)
{
printf("Thread Creation failed\\n");
}
printf("created udp listener");
err = pthread_create(&pidctrl, 0, PIDctrl, 0);
if (err!=0)
{
perror("Thread Creation failed\\n");
}
err = pthread_create(&sighandl, 0,signalHandler,0 );
if (err!=0)
{
perror("Thread Creation failed\\n");
}
pthread_mutex_lock(&tinfo_connection.sendlock);
err = udp_send(&tinfo_connection.conn, "START", sizeof("START"));
if (err==-1){
printf("Failed to start simulation\\n");
}
pthread_mutex_unlock(&tinfo_connection.sendlock);
printf("started simulation\\n");
err = pthread_join(pidctrl, 0);
if (err != 0) {
printf("Joining of thread failed stooped\\n");
}
pthread_mutex_lock(&tinfo_connection.sendlock);
err = udp_send(&tinfo_connection.conn, "STOP", sizeof("STOP"));
if (err==-1){
printf("Failed to stop simulation\\n");
}
pthread_mutex_unlock(&tinfo_connection.sendlock);
return 0;
}
void init_sem_and_mutexes(){
int err1 = sem_init(&new_sig,0,0);
int err2 = sem_init(&y_updt,0,0);
if ((err1|| err2)!=0)
{
perror("Sem init failed");
}
int errc= pthread_mutex_init(&tinfo_connection.sendlock,0);
int erro = pthread_mutex_init(&tinfo_output.lock, 0);
if ((errc||erro)!=0)
{
perror("Mutex init failed");
}
}
void destroy_sem_and_mutexes(){
int err1= sem_destroy(&new_sig);
int err2= sem_destroy(&y_updt);
int err3= pthread_mutex_destroy(&tinfo_connection.sendlock);
int err4= pthread_mutex_destroy(&tinfo_output.lock);
if( (err1 || err2 || err3 || err4)!=0)
{
perror("Could not destroy the sem or mutex");
}
}
| 0
|
#include <pthread.h>
{
int side;
pid_t monkey_id;
} pthread_args;
int crossing;
int goingRight;
int goingLeft;
int count;
pthread_mutex_t mux;
sem_t sem;
int side(void);
void* monkeyDay(void* monkey_args);
void crossRight(pthread_args* monkey);
void crossLeft(pthread_args* monkey);
void crosses(pthread_args* monkey);
int side(void)
{
int rate = rand() % 100;
if(rate < 50)
return 0;
else
return 1;
}
void* monkeyDay(void* monkey_args)
{
pthread_args* monkey = ((pthread_args*) monkey_args);
int cross;
monkey->monkey_id = syscall( __NR_gettid );
monkey->side = side();
while(1)
{
cross = rand() % 100;
if(cross < 70)
{
if(monkey->side == 0)
crossRight(monkey);
else
crossLeft(monkey);
}
else
{
printf("\\nHello, I'm monkey %d and I do not want to cross. Bye! \\n", monkey->monkey_id);
return;
}
}
}
void crossRight(pthread_args* monkey)
{
int control, flag;
do {
pthread_mutex_lock(&mux);
if (crossing == 0)
{
goingLeft = 0;
goingRight = 1;
crossing = 1;
count = 0;
flag = 1;
}
else if((goingRight == 1) && (count >= 10))
{
flag = 0;
}
flag = flag && (goingRight == 1);
pthread_mutex_unlock(&mux);
} while (!flag);
pthread_mutex_lock(&mux);
sem_post(&sem);
count++;
pthread_mutex_unlock(&mux);
pthread_mutex_lock(&mux);
pthread_mutex_unlock(&mux);
crosses(monkey);
pthread_mutex_lock(&mux);
sem_wait(&sem);
pthread_mutex_unlock(&mux);
pthread_mutex_lock(&mux);
sem_getvalue(&sem, &control);
if(control <= 0)
{
crossing = 0;
goingRight = 0;
count = 0;
}
pthread_mutex_unlock(&mux);
}
void crossLeft(pthread_args* monkey)
{
int control, flag;
do {
pthread_mutex_lock(&mux);
if (crossing == 0)
{
goingRight = 0;
goingLeft = 1;
crossing = 1;
count = 0;
flag = 1;
}
else if((goingLeft == 1) && (count >= 10))
{
flag = 0;
}
flag = flag && (goingLeft == 1);
pthread_mutex_unlock(&mux);
} while (!flag);
pthread_mutex_lock(&mux);
sem_post(&sem);
count++;
pthread_mutex_unlock(&mux);
pthread_mutex_lock(&mux);
pthread_mutex_unlock(&mux);
crosses(monkey);
pthread_mutex_lock(&mux);
sem_wait(&sem);
pthread_mutex_unlock(&mux);
pthread_mutex_lock(&mux);
sem_getvalue(&sem, &control);
if(control <= 0)
{
crossing = 0;
goingLeft = 0;
count = 0;
}
pthread_mutex_unlock(&mux);
}
void crosses(pthread_args* monkey)
{
int i;
for(i = 0; i < 2; i++)
sleep(1);
if(monkey->side == 1)
{
monkey->side = 0;
printf("\\nHello, I'm monkey %d and I already have crossed L -> R.", monkey->monkey_id);
}
else
{
monkey->side = 1;
printf("\\nHello, I'm monkey %d and I already have crossed R -> L.", monkey->monkey_id);
}
}
int main(int argc, char **argv)
{
struct timeb tmb;
ftime(&tmb);
srand(tmb.time * 1000 + tmb.millitm);
pthread_t monkeys_id[10];
pthread_args monkeys_args[10];
int i = 0;
pthread_mutex_init(&mux, 0);
sem_init(&sem, 0, 0);
do
{
pthread_create(&monkeys_id[i], 0, monkeyDay, (void*) &monkeys_args[i]);
i++;
}while(i < 10);
for(i = 0; i < 10; i++)
{
pthread_join(monkeys_id[i], 0);
}
sem_close(&sem);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t entry_mutex = PTHREAD_MUTEX_INITIALIZER;
void* thread_func(void *data) {
struct parking_details *pdata = (struct parking_details *)data;
pthread_mutex_lock(&entry_mutex);
printf("\\n enter the car details thread : %d",pdata->thread_instance);
printf("\\n car number :");
scanf("%s",pdata->car_number);
printf("\\n token id : ");
scanf("%d",&pdata->token_id);
printf("driver name :");
scanf("%s",pdata->driver_name);
printf("driver mother name :");
scanf("%s",pdata->driver_mother_name);
pthread_mutex_unlock(&entry_mutex);
return 0;
}
int main (int argc,char* argv[]) {
pthread_t thread1_id, thread2_id,thread3_id;
time_t clk = time(0);
struct parking_details car[MAX_CAR];
int segment_id;
char* shared_memory;
struct shmid_ds shmbuffer;
int segment_size;
const int shared_segment_size = 0x64;
segment_id = shmget (SHMEM_KEY, shared_segment_size,IPC_CREAT | S_IRUSR | S_IWUSR);
printf("exit segment id : %d \\n",segment_id);
shared_memory = (char*) shmat (segment_id, 0, 0);
printf ("shared memory attached at address %p\\n", shared_memory);
shmctl (segment_id, IPC_STAT, &shmbuffer);
segment_size = shmbuffer.shm_segsz;
printf ("segment size: %d\\n", segment_size);
printf ("string : %s\\n",shared_memory);
printf(" Current timing of the process is %s \\n",ctime(&clk));
printf("Inside Exit system process \\n");
car[0].thread_instance = 1;
pthread_create(&thread1_id,0,&thread_func,(void *)&car[0]);
car[1].thread_instance = 2;
pthread_create(&thread2_id,0,&thread_func,(void *)&car[1]);
car[2].thread_instance = 3;
pthread_create(&thread3_id,0,&thread_func,(void *)&car[2]);
pthread_join(thread1_id,0);
pthread_join(thread2_id,0);
pthread_join(thread3_id,0);
shmdt (shared_memory);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t chopsticks[5];
void chopsticks_init(){
int i = 0;
for (i = 0; i<5; i++){
pthread_mutex_init(&chopsticks[i], 0);
}
return;
}
void chopsticks_destroy(){
int i = 0;
for (i = 0; i<5; i++){
pthread_mutex_destroy(&chopsticks[i]);
}
return;
}
void pickup_chopsticks(int phil_id){
int right_c = (phil_id)%5;
int left_c = (phil_id-1 == -1 )? 5 - 1 : phil_id-1 ;
printf("Philospher %d is thinking...\\n", phil_id);
usleep(random() % 1000);
if (phil_id % 2 == 0){
printf("Philosopher %d is trying to pick the right chopstick.\\n", phil_id);
pthread_mutex_lock(&chopsticks[right_c]);
pickup_right_chopstick(phil_id);
printf("Philosopher %d is trying to pick the left chopstick.\\n", phil_id);
pthread_mutex_lock(&chopsticks[left_c]);
pickup_left_chopstick(phil_id);
}
else{
printf("Philosopher %d is trying to pick the left chopstick.\\n", phil_id);
pthread_mutex_lock(&chopsticks[left_c]);
pickup_left_chopstick(phil_id);
printf("Philosopher %d is trying to pick the right chopstick.\\n", phil_id);
pthread_mutex_lock(&chopsticks[right_c]);
pickup_right_chopstick(phil_id);
}
printf("Philospher %d is now eating...\\n", phil_id);
usleep(random() % 1000);
}
void putdown_chopsticks(int phil_id){
int right_c = (phil_id)%5;
int left_c = (phil_id-1 == -1 )? 5 - 1 : phil_id-1 ;
printf("Philospher %d is still eating...\\n", phil_id);
usleep(random() % 1000);
if (phil_id % 2 == 0){
printf("Philosopher %d is trying to put down the left chopstick.\\n", phil_id);
putdown_left_chopstick(phil_id);
pthread_mutex_unlock(&chopsticks[left_c]);
printf("Philosopher %d is trying to put down the right chopstick.\\n", phil_id);
putdown_right_chopstick(phil_id);
pthread_mutex_unlock(&chopsticks[right_c]);
}
else{
printf("Philosopher %d is trying to put down the right chopstick.\\n", phil_id);
putdown_right_chopstick(phil_id);
pthread_mutex_unlock(&chopsticks[right_c]);
printf("Philosopher %d is trying to put down the left chopstick.\\n", phil_id);
putdown_left_chopstick(phil_id);
pthread_mutex_unlock(&chopsticks[left_c]);
}
printf("Philospher %d is now thinking again...\\n", phil_id);
}
| 1
|
#include <pthread.h>
int deb; int fin; int *res; int *tab;
pthread_mutex_t*mut;
} Tableau;
void *cherche(void *a) {
int i;
Tableau *t=(Tableau *)a;
for(i=t->deb;i<t->fin;i++){
pthread_mutex_lock(t->mut);
if(*(t->res)< t->tab[i])
*(t->res)=t->tab[i];
pthread_mutex_unlock(t->mut);
}return 0;
}
int main(int argc, char ** argv) {
int res=-1;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
int *tab=malloc(2*sizeof(int));
int i;
int n=atoi(argv[1]);
srand(time(0));
pthread_t*tid=malloc(n*sizeof(pthread_t));
for(i=0; i<20; tab[i++]=(rand()%(1000)+1));
Tableau *arg=malloc(atoi(argv[1])*sizeof(Tableau));
for(i=0;i<n;++i){
arg[i].mut=&m;
arg[i].tab=tab;
arg[i].res=&res;
arg[i].deb=(20*i)/n; arg[i].fin=(20*(i+1))/n;
pthread_create(tid+i,0,&cherche,arg+i);
}
int max=1;
for(i=0; i<0;++i){
pthread_join(tid[i],0);
}
printf("%d\\n",res);
free(tab);
free(arg);
free(tid);
return 0;
}
| 0
|
#include <pthread.h>
int count;
pthread_mutex_t mutex;
pthread_cond_t condition_var;
} Semaphore;
pthread_mutex_t mutexP = PTHREAD_MUTEX_INITIALIZER;
Semaphore siA = {0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER};
Semaphore siB = {0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER};
Semaphore siiB = {0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER};
Semaphore siiC = {0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER};
Semaphore siii = {0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER};
Semaphore sP = {1000, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER};
Semaphore sC = {0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER};
char buf[1000];
int ri = 0;
int wi = 0;
void waitSemaphore(Semaphore *s) {
pthread_mutex_lock(&(s->mutex));
if (s->count >= 0) {
s->count--;
}
if (s->count < 0) {
pthread_cond_wait(&(s->condition_var), &(s->mutex));
}
pthread_mutex_unlock(&(s->mutex));
}
void signalSemaphore(Semaphore *s) {
pthread_mutex_lock(&(s->mutex));
s->count++;
if (s->count >= 0) {
pthread_cond_signal(&(s->condition_var));
}
pthread_mutex_unlock(&(s->mutex));
}
void produce(char ch) {
pthread_mutex_lock(&mutexP);
waitSemaphore(&sP);
buf[wi++] = ch;
wi %= 1000;
signalSemaphore(&sC);
pthread_mutex_unlock(&mutexP);
}
void *runPA() {
produce('A');
signalSemaphore(&siA);
signalSemaphore(&siii);
while (1) {
produce('A');
signalSemaphore(&siii);
}
}
void *runPB() {
waitSemaphore(&siii);
produce('B');
signalSemaphore(&siB);
signalSemaphore(&siiC);
while (1) {
waitSemaphore(&siiB);
waitSemaphore(&siii);
produce('B');
signalSemaphore(&siiC);
}
}
void *runPC() {
waitSemaphore(&siA);
waitSemaphore(&siB);
while (1) {
waitSemaphore(&siiC);
waitSemaphore(&siii);
produce('C');
signalSemaphore(&siiB);
}
}
void *runC() {
while (1) {
waitSemaphore(&sC);
putchar(buf[ri++]);
ri %= 1000;
signalSemaphore(&sP);
}
}
int main(int argc, const char * argv[]) {
int rPA, rPB, rPC, rC;
pthread_t threadPA, threadPB, threadPC, threadC;
if ((rPB=pthread_create(&threadPB, 0, runPB, 0))) {
printf("ThreadPB creation failed: %d\\n", rPB);
}
if ((rC=pthread_create(&threadC, 0, runC, 0))) {
printf("ThreadC creation failed: %d\\n", rC);
}
if ((rPC=pthread_create(&threadPC, 0, runPC, 0))) {
printf("ThreadPC creation failed: %d\\n", rPC);
}
if ((rPA=pthread_create(&threadPA, 0, runPA, 0))) {
printf("ThreadPA creation failed: %d\\n", rPA);
}
pthread_join(threadPA, 0);
pthread_join(threadPB, 0);
pthread_join(threadPC, 0);
pthread_join(threadC, 0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t pro_mutex;
unsigned char process_num = 0;
void createpro(char *argname, unsigned short argpri, unsigned short arglen, struct process **arghead)
{
static unsigned char n = 0;
struct process *process_node;
void insert_pro(struct process *, struct process **);
process_node = (struct process *)malloc(sizeof(struct process));
strcpy(process_node->name, argname);
process_node->id = n;
process_node->priority = argpri;
process_node->init_priority = argpri;
process_node->total = arglen;
process_node->rest = arglen;
process_node->start = 0;
srand((unsigned)time(0));
process_node->write_progress = rand() % 10 + 1;
process_node->fp = 0;
process_node->finish_ratio = 0;
process_node->next = 0;
process_num++;
n++;
pthread_mutex_lock(&pro_mutex);
insert_pro(process_node, arghead);
pthread_mutex_unlock(&pro_mutex);
}
void insert_pro(struct process *argnode, struct process **arghead)
{
struct process *p = *arghead, *q;
argnode->next = 0;
if(p == 0)
*arghead = argnode;
else if(p->priority < argnode->priority)
{
*arghead = argnode;
argnode->next = p;
}
else
{
do
{
q = p;
p = p->next;
}while (p != 0 && p->priority >= argnode->priority);
q->next = argnode;
if(p != 0)
argnode->next = p;
}
}
void ps(struct process *arghead)
{
struct process *p = arghead;
pthread_mutex_lock(&pro_mutex);
printf("PID\\tPNAME\\t\\tRATIO\\tINITPRI\\n");
while(p != 0)
{
printf("%3d\\t%s\\t\\t%3d%\\t%5d\\n", p->id, p->name, p->finish_ratio, p->init_priority);
p = p->next;
}
printf("Current process number: %d\\n", process_num);
pthread_mutex_unlock(&pro_mutex);
}
void deletepro(unsigned char argid, struct process **arghead)
{
struct process *p = *arghead, *q;
struct process *search_node(unsigned char, struct process *, struct process **);
p = search_node(argid, p, &q);
if(p == 0)
printf("Process with id %d doesn't exist!\\n", argid);
else
{
rmfile(root_directory, p->fp->file_name, REGULAR_FILE);
process_num--;
if(p == *arghead)
*arghead = p->next;
else
q->next = p->next;
}
}
struct process *search_node(unsigned char argid, struct process *arghead, struct process **pre)
{
struct process *p = arghead;
while(p != 0 && p->id != argid)
{
*pre = p;
p = p->next;
}
return p;
}
void process_schedule(struct process **arghead)
{
struct process *p;
char file_name[20];
unsigned char i;
void wait_pro_pri_incr(struct process *);
while(1)
{
while(*arghead == 0);
pthread_mutex_lock(&pro_mutex);
p = *arghead;
*arghead = p->next;
pthread_mutex_unlock(&pro_mutex);
sleep(1);
if(p->start == 0)
{
strcpy(file_name, "file_");
strcat(file_name, p->name);
p->fp = mkfile(root_directory, file_name, REGULAR_FILE);
p->fp->state = WR;
}
for(i = 0; i < p->write_progress && p->start < p->total; i++, p->start++)
p->fp->content[p->start] = p->start + 1;
p->rest -= p->write_progress;
if(p->rest <= 0)
{
p->fp->content[p->start] = '\\0';
p->fp->state = OK;
process_num--;
continue;
}
p->priority = p->init_priority;
p->finish_ratio = (p->total - p->rest) * 100 / p->total;
wait_pro_pri_incr(*arghead);
pthread_mutex_lock(&pro_mutex);
insert_pro(p, arghead);
pthread_mutex_unlock(&pro_mutex);
}
}
void wait_pro_pri_incr(struct process *arghead)
{
struct process *p = arghead;
while(p != 0)
{
p->priority++;
p = p->next;
}
}
| 0
|
#include <pthread.h>
struct minmax{
int value;
int xpos;
int ypos;
};
pthread_mutex_t maxLock;
pthread_mutex_t minLock;
pthread_mutex_t totalLock;
pthread_mutex_t rowCountLock;
int numWorkers;
int total;
int rowCount;
struct minmax min;
struct minmax max;
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];
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_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
pthread_mutex_init(&minLock, 0);
pthread_mutex_init(&maxLock, 0);
pthread_mutex_init(&totalLock, 0);
pthread_mutex_init(&rowCountLock, 0);
total = 0;
rowCount = 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;
}
}
min.value = matrix[0][0];
min.xpos = 0;
min.ypos = 0;
max.value = matrix[0][0];
max.xpos = 0;
max.ypos = 0;
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("Total:\\t%d\\n",total);
printf("Min value:\\t%d\\t[%d,%d]\\n",min.value,min.xpos,min.ypos);
printf("Max value:\\t%d\\t[%d,%d]\\n",max.value,max.xpos,max.ypos);
printf("The execution time is %g sec\\n", end_time - start_time);
pthread_exit(0);
}
void *Worker(void *arg) {
int localTotal, j, localRow;
localTotal = 0;
pthread_mutex_lock(&rowCountLock);
localRow = rowCount;
rowCount = rowCount + 1;
pthread_mutex_unlock(&rowCountLock);
while(localRow < size){
for (j = 0; j < size; j++){
localTotal += matrix[localRow][j];
if(min.value > matrix[localRow][j]){
pthread_mutex_lock(&minLock);
if(min.value > matrix[localRow][j]){
min.value = matrix[localRow][j];
min.xpos = localRow;
min.ypos = j;
}
pthread_mutex_unlock(&minLock);
}
if(max.value < matrix[localRow][j]){
pthread_mutex_lock(&maxLock);
if(max.value < matrix[localRow][j]){
max.value = matrix[localRow][j];
max.xpos = localRow;
max.ypos = j;
}
pthread_mutex_unlock(&maxLock);
}
}
pthread_mutex_lock(&rowCountLock);
localRow = rowCount;
rowCount = rowCount + 1;
pthread_mutex_unlock(&rowCountLock);
}
pthread_mutex_lock(&totalLock);
total += localTotal;
pthread_mutex_unlock(&totalLock);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
double pi_approx = 0;
double get_term(double n) {
double term = 4.0 / (2 * n + 1);
if ((int)floor(n) & 1) {
term = 0 - term;
}
return term;
}
double start;
double end;
}params;
params * params_new(double start, double end) {
params * this = malloc(sizeof(params));
this->start = start;
this->end = end;
return this;
}
void * leibniz(void* args) {
params * p = (params*) args;
double start = p->start;
double end = p->end;
double sum = 0;
for(; start < end; start++) {
sum += get_term(start);
}
pthread_mutex_lock(&mut);
pi_approx += sum;
pthread_mutex_unlock(&mut);
pthread_exit(0);
}
int main(int argc, char ** argv) {
int num_threads = atoi(argv[1]);
pthread_t threads[num_threads];
double iterations = 5000000;
double it_per_thread = iterations / (double) num_threads;
params ** args = malloc(sizeof(params*) * num_threads);
int t, rc;
for (t=0;t<num_threads;t++) {
double start = (double) t * it_per_thread;
double end = start + it_per_thread;
args[t] = params_new(start, end);
rc = pthread_create(&threads[t],0,
leibniz,(void *)args[t]);
if (rc) {
exit(-1);
}
}
for(t=0;t<num_threads;t++) {
pthread_join( threads[t], 0);
free(args[t]);
}
return 0;
}
| 0
|
#include <pthread.h>
void taSleepingTime(void)
{
int time = rand() % SLEEP_MAX + 1;
sleep(time);
}
void* teachingAssistant()
{
while(1)
{
sem_wait(&studentSemaphore);
pthread_mutex_lock(&mutex);
printf("Teaching Assistant helping student %d\\n",seat[studentSeated]);
seat[studentSeated]=0;
counter--;
printf("Student seating on seats 1-2-3 sequentially : %d %d %d\\n",seat[0],seat[1],seat[2]);
studentSeated = (studentSeated + 1) % MAX_SEAT;
if ( counter == 0)
{
printf(" Teaching Assistant finish helping Student going to sleep.\\n");
taSleepingTime();
}
pthread_mutex_unlock(&mutex);
sem_post(&teachingAssistantSemaphore);
}
}
void* studentRequiredHelp(void* studentIdentification)
{
int identification = *(int*)studentIdentification;
printf(" %d student reached for Teaching Assistant help\\n",identification);
while(1)
{
taSleepingTime();
pthread_mutex_lock(&mutex);
if(MAX_SEAT > counter)
{
seat[seatAvailable] = identification;
printf(" %d students seated at hallway waiting for Teaching Assistant help\\n",identification);
printf(" students waiting outside TA office on seats 1-2-3 : %d %d %d\\n",seat[0],seat[1],seat[2]);
seatAvailable = (seatAvailable+1) % MAX_SEAT;
counter++;
pthread_mutex_unlock(&mutex);
sem_post(&studentSemaphore);
if (counter == 1)
{
printf("Wake sleeping Teaching Assistant for his/her help\\n");
}
sem_wait(&teachingAssistantSemaphore);
}
else
{
pthread_mutex_unlock(&mutex);
printf("No more seats available as TA is busy.Student %d is resuming programing and will be back later\\n",identification);
}
}
}
int main(int argc, char **argv)
{
printf("How many students want to get help from Teaching Assistant ? ");
scanf("%d", &totalStudent);
pthread_t studentThread[totalStudent];
pthread_t teachingAssistantThread;
int studentIdentificationNumber[totalStudent];
for ( in = 0; in < totalStudent; in++ )
{
studentIdentificationNumber[ in ] = in + 1;
}
if (totalStudent==0)
{
printf ("No student are seated..TA going to sleep! \\n");
exit(-1);
}
sem_init(&studentSemaphore,0,0);
sem_init(&teachingAssistantSemaphore,0,1);
srand(time(0));
pthread_mutex_init(&mutex,0);
pthread_create(&teachingAssistantThread,0,teachingAssistant,0);
for(in = 0; in < totalStudent; in++)
{
studentIdentificationNumber[in] = in+1;
pthread_create(&studentThread[in], 0, studentRequiredHelp, (void*) &studentIdentificationNumber[in]);
}
pthread_join(teachingAssistantThread, 0);
for(in = 0; in < totalStudent;in++)
{
pthread_join(studentThread[in],0);
}
return 0;
}
| 1
|
#include <pthread.h>
int handleRouting(struct RoutingInfo senderRtngInfo)
{
int i,j;
if( myNodeNum == senderRtngInfo.originator )
{
free(senderRtngInfo.rt_sender);
return 0;
}
if( senderRtngInfo.counter <= NodeRtngMsgCounter[senderRtngInfo.originator] )
{
for(i=0; i < rt_num_entries; i++)
{
if( (RoutingTable[i].dest == senderRtngInfo.originator) )
{
for(j=0; j< senderRtngInfo.entries; j++)
{
if(senderRtngInfo.rt_sender[j].dest == senderRtngInfo.originator)
{
if( RoutingTable[i].cost <= ((senderRtngInfo.rt_sender[j].cost) +1) )
{
free(senderRtngInfo.rt_sender);
return 0;
}else
break;
}
}
}
}
}
printf("Modifying routing table\\n");
for(j=0; j< senderRtngInfo.entries; j++)
{
for(i=0; i<rt_num_entries; i++)
{
if(senderRtngInfo.rt_sender[j].dest == RoutingTable[i].dest)
{
if(RoutingTable[i].cost > (senderRtngInfo.rt_sender[j].cost +1))
{
RoutingTable[i].cost = (senderRtngInfo.rt_sender[j].cost +1);
RoutingTable[i].nextHop = senderRtngInfo.sender;
}
if(RoutingTable[i].degree < senderRtngInfo.rt_sender[j].degree)
{
RoutingTable[i].degree = senderRtngInfo.rt_sender[j].degree;
}
break;
}
}
if(i == rt_num_entries)
{
RoutingTable[rt_num_entries].dest = senderRtngInfo.rt_sender[j].dest;
RoutingTable[rt_num_entries].cost = senderRtngInfo.rt_sender[j].cost + 1;
RoutingTable[rt_num_entries].nextHop = senderRtngInfo.sender;
RoutingTable[rt_num_entries].degree = senderRtngInfo.rt_sender[j].degree;
rt_num_entries++;
}
}
if( (NodeRtngMsgCounter[senderRtngInfo.originator] < senderRtngInfo.counter) && (senderRtngInfo.init == 1) )
{
printf("This is init so create a packet\\n");
sendRoutingInfo(1,&senderRtngInfo);
}
printf("Forwarding the packet\\n");
sendRoutingInfo(0,&senderRtngInfo);
if(NodeRtngMsgCounter[senderRtngInfo.originator] < senderRtngInfo.counter)
NodeRtngMsgCounter[senderRtngInfo.originator] = senderRtngInfo.counter;
free(senderRtngInfo.rt_sender);
return 0;
}
int handleConnect(int connTo) {
int sockfd, n;
struct sockaddr_in serv_addr;
char recvline[1000];
int remote_node_no = connTo;
printf("\\nConneting to %d -> IP:PORT %s:%d\\n", remote_node_no,
inet_ntoa(nodes[remote_node_no].sin_addr),
(int) ntohs(nodes[remote_node_no].sin_port));
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = nodes[remote_node_no].sin_addr.s_addr;
serv_addr.sin_port = nodes[remote_node_no].sin_port;
if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr))) {
printf(
"\\n Error : Connect Failed, please check if the server at \\"%s\\" is up\\n",
inet_ntoa(nodes[remote_node_no].sin_addr));
return 0;
}
printf("\\nConnected\\n");
nodes_sockfd[remote_node_no] = sockfd;
rt_add_entry(remote_node_no,1,remote_node_no,0);
rt_increment_degree();
neighbour[num_nbrs++] = remote_node_no;
sendto(sockfd, "Hello", 1000, 0,(struct sockaddr *) &serv_addr, sizeof(serv_addr));
printf("\\nSent\\n");
n = recvfrom(sockfd, recvline, sizeof(recvline), 0, 0, 0);
recvline[n] = 0;
printf("\\nReceiving...\\n");
fputs(recvline, stdout);
return 0;
}
int handleEvent(enum eventType type,struct RoutingInfo senderRtngInfo,int connTo)
{
int retval;
printf("Entered handleEvent type:%d \\n",type);
pthread_mutex_lock(&lockHndlEvnt);
retval = 0;
switch(type)
{
case ROUTING:
retval=handleRouting(senderRtngInfo);
break;
case CONNECT:
retval=handleConnect(connTo);
break;
default:
printf("Unknown type in handleEvent %d\\n",type);
retval = -2;
break;
}
pthread_mutex_unlock(&lockHndlEvnt);
printf("Processed message in handleEvent \\n");
return retval;
}
| 0
|
#include <pthread.h>
long timeval_diff(struct timeval *t2, struct timeval *t1)
{
long diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);
return (diff);
}
void error(int err, char *msg)
{
fprintf(stderr,"%s a retourné %d, message d'erreur : %s\\n",msg,err,strerror(errno));
exit(1);
}
void usage(char *arg)
{
printf("Usage : %s percent nthreads\\n\\n",arg);
printf(" percent: 0-100 pourcentage de temps en section critique\\n");
printf(" nthreads : nombre de threads à lancer\\n");
}
int percent;
int nthreads;
pthread_mutex_t mutex;
void critique()
{
long j=0;
for(int i=0;i<(40000*percent)/100;i++) {
j+=i;
}
}
void noncritique()
{
int j=0;
for(int i=0;i<(40000*(100-percent))/100;i++) {
j-=i;
}
}
void *func(void * param)
{
for(int j=0;j<40000/nthreads;j++) {
pthread_mutex_lock(&mutex);
critique();
pthread_mutex_unlock(&mutex);
noncritique();
}
return(0);
}
int main (int argc, char *argv[])
{
int err;
struct timeval tvStart, tvEnd;
long mesures[4];
long sum=0;
if(argc!=3) {
usage(argv[0]);
return(1);
}
char *endptr;
percent=strtol(argv[1],&endptr,10);
if(percent<1 || percent >100) {
usage(argv[0]);
return(1);
}
nthreads=strtol(argv[2],&endptr,10);
if(nthreads<0) {
usage(argv[0]);
return(1);
}
pthread_t thread[nthreads];
err=pthread_mutex_init(&mutex, 0);
if(err!=0)
error(err,"pthread_mutex_init");
for (int j=0;j<4;j++) {
err=gettimeofday(&tvStart, 0);
if(err!=0)
exit(1);
for(int i=0;i<nthreads;i++) {
err=pthread_create(&(thread[i]),0,&func,0);
if(err!=0)
error(err,"pthread_create");
}
for(int i=nthreads-1;i>=0;i--) {
err=pthread_join(thread[i],0);
if(err!=0)
error(err,"pthread_join");
}
err=gettimeofday(&tvEnd, 0);
if(err!=0)
exit(1);
mesures[j]=timeval_diff(&tvEnd, &tvStart);
sum+=mesures[j];
}
printf("%d, %d, %ld\\n",nthreads,percent,sum/4);
err=pthread_mutex_destroy(&mutex);
if(err!=0)
error(err,"pthread_destroy");
return(0);
}
| 1
|
#include <pthread.h>
void *v3_helper(void *path){
char *file, *file_ext, new_path[1000];
DIR *inDir;
struct dirent *inDirent;
struct stat st;
pthread_t thread;
pthread_mutex_lock(&log_mutex);
num_threads++;
pthread_mutex_unlock(&log_mutex);
inDir = opendir(path);
if (!inDir) {
fprintf(stderr, "Error encountered in Variant 3: invalid input path.\\n");
fprintf(stderr, " Unable to open directory at %s\\n", (char *) path);
exit(1);
}
while ( (inDirent = readdir(inDir)) ) {
file = inDirent->d_name;
strcpy(new_path, path);
strcat(new_path, "/");
strcat(new_path, file);
if (!strcmp(file, ".") || !strcmp(file, "..") || !strcmp(file, ".DS_Store")) {
continue;
}
stat(new_path, &st);
if (S_ISDIR(st.st_mode)) {
pthread_mutex_lock(&dir_mutex);
strcpy(dir_list[d_end], new_path);
d_end++;
num_dir++;
pthread_mutex_unlock(&dir_mutex);
continue;
}
pthread_mutex_lock(&log_mutex);
num_files++;
pthread_mutex_unlock(&log_mutex);
file_ext = strrchr(file, '.');
if (!file_ext) {
continue;
}
if (!strcmp(file_ext, ".png") || !strcmp(file_ext, ".bmp") ||
!strcmp(file_ext, ".gif") || !strcmp(file_ext, ".jpg")) {
pthread_create(&thread, 0, v3_anotherhelper, new_path);
pthread_join(thread, 0);
}
}
closedir(inDir);
pthread_exit(0);
}
void *v3_anotherhelper(void *path){
pthread_mutex_lock(&log_mutex);
num_threads++;
pthread_mutex_unlock(&log_mutex);
pthread_mutex_lock(&html_mutex);
generate_html((char *) path);
pthread_mutex_unlock(&html_mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo{
int f_count;
pthread_mutex_t f_lock;
int f_id;
struct foo *f_next;
};
struct foo *foo_alloc(int id)
{
struct foo *fp;
int idx;
if ((fp = malloc(sizeof (struct foo))) != 0){
fp->f_coutn = 1;
fp->f_id = id;
if (pthread_mutex_init(&fp->f_lock, 0) != 0)
{
free(fp);
return 0;
}
idx = HASH[id];
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hash_lock);
pthread_mutex_unlock(&fp->f_lock);
}
return fp;
}
void foo_hold(struct foo *fp)
{
pthread_mutex_lock(&hash_lock);
fp->f_count++;
pthread_mutex_lock(&hash_lock);
}
struct foo *foo_find(int id)
{
struct foo *fp;
pthread_mutex_lock(&hashlock);
for (fp = fh[(((unsigned long)id) % 29)]; fp != 0; fp = fp->next)
{
if (fp->f_id == id)
{
fp->f_coutn++;
break;
}
}
pthread_mutex_unlock(&hashlock);
return fp;
}
void foo_rele(struct foo *fp)
{
struct foo *tfp;
int idx;
pthread_mutex_lock(&hashlock);
if (--fp->f_count == 0)
{
idx = (((unsigned long)fp->f_id) % 29);
tfp = fh[idx];
if (tfp == fp)
{
fh[idx] = fp->f_next;
} else {
while (tfp->f_next != fp)
tfp = tfp->next;
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthead_mutex_destory(&fp->f_lock);
free(fp);
} else {
pthread_mutex_unlock(&hash_lock);
}
}
| 1
|
#include <pthread.h>
int threads = 0;
pthread_mutex_t mutex;
pthread_cond_t cond_pode_ler;
pthread_cond_t cond_pode_escrever;
int lendo = 0;
int escrevendo = 0;
int querendo_escrever = 0;
unsigned long mix(unsigned long a, unsigned long b, unsigned long c);
void entra_leitura()
{
pthread_mutex_lock(&mutex);
while (escrevendo || querendo_escrever)
{
pthread_cond_wait(&cond_pode_ler, &mutex);
}
lendo++;
pthread_mutex_unlock(&mutex);
}
void sai_leitura()
{
pthread_mutex_lock(&mutex);
lendo--;
if (lendo == 0)
{
pthread_cond_signal(&cond_pode_escrever);
}
pthread_mutex_unlock(&mutex);
}
void entra_escrita()
{
pthread_mutex_lock(&mutex);
while (escrevendo || lendo)
{
querendo_escrever++;
pthread_cond_wait(&cond_pode_escrever, &mutex);
querendo_escrever--;
}
escrevendo++;
pthread_mutex_unlock(&mutex);
}
void sai_escrita()
{
pthread_mutex_lock(&mutex);
escrevendo--;
pthread_cond_signal(&cond_pode_escrever);
pthread_cond_broadcast(&cond_pode_ler);
pthread_mutex_unlock(&mutex);
}
void *escrever_varios(void *arg)
{
int tid = *(int *)arg;
int boba1, boba2;
int i;
for (i = 0; i < 5; i++)
{
entra_escrita();
printf("entra_escrita tid=%d => escrevendo=%d, lendo=%d, querendo_escrever=%d\\n", tid, escrevendo, lendo, querendo_escrever);
boba1 = rand()%10000;
boba2 = -rand()%10000;
while (boba2 < boba1)
boba2++;
sai_escrita();
printf("sai_escrita tid=%d => escrevendo=%d, lendo=%d, querendo_escrever=%d\\n", tid, escrevendo, lendo, querendo_escrever);
}
pthread_exit(0);
}
void *ler_varios(void *arg)
{
int tid = *(int *)arg;
int boba1, boba2;
int i;
for (i = 0; i < 5; i++)
{
entra_leitura();
printf("entra_leitura tid=%d => escrevendo=%d, lendo=%d, querendo_escrever=%d\\n", tid, escrevendo, lendo, querendo_escrever);
boba1 = rand()%10000000;
boba2 = -rand()%10000000;
while (boba2 < boba1)
boba2++;
sai_leitura();
printf("sai_leitura tid=%d => escrevendo=%d, lendo=%d, querendo_escrever=%d\\n", tid, escrevendo, lendo, querendo_escrever);
}
pthread_exit(0);
}
void main()
{
srand(mix(clock(), time(0), 12789057));
srand(rand());
pthread_cond_init(&cond_pode_escrever, 0);
pthread_cond_init(&cond_pode_ler, 0);
pthread_mutex_init(&mutex, 0);
pthread_t *tid;
tid = (pthread_t *)malloc(sizeof(pthread_t) * 10);
int *arg = malloc(sizeof(int) * 10);
int k;
for (k = 0; k < 10; k++)
{
arg[k] = k;
}
for (k = 0; k < 7; k++)
{
printf("ler_varios\\n");
if (pthread_create(&tid[k], 0, ler_varios, (void *)&arg[k]) != 0)
{
printf("--ERRO: pthread_create()\\n");
exit(-1);
}
}
for (; k < 10; k++)
{
printf("escrever_varios\\n");
if (pthread_create(&tid[k], 0, escrever_varios, (void *)&arg[k]) != 0)
{
printf("--ERRO: pthread_create()\\n");
exit(-1);
}
}
for (k = 0; k < 10; k++)
{
if (pthread_join(tid[k], 0) != 0)
{
printf("--ERRO: pthread_join() \\n");
exit(-1);
}
}
free(arg);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond_pode_ler);
pthread_cond_destroy(&cond_pode_escrever);
}
unsigned long mix(unsigned long a, unsigned long b, unsigned long c)
{
a=a-b; a=a-c; a=a^(c >> 13);
b=b-c; b=b-a; b=b^(a << 8);
c=c-a; c=c-b; c=c^(b >> 13);
a=a-b; a=a-c; a=a^(c >> 12);
b=b-c; b=b-a; b=b^(a << 16);
c=c-a; c=c-b; c=c^(b >> 5);
a=a-b; a=a-c; a=a^(c >> 3);
b=b-c; b=b-a; b=b^(a << 10);
c=c-a; c=c-b; c=c^(b >> 15);
return c;
}
| 0
|
#include <pthread.h>
void draw_ball(int x, int y, int c)
{
circlefill(screen, x, y, L, c);
}
void print_id_task(int id, int x, int y, int color){
textprintf_ex(screen, font, x, y, color, BGC, "T%d", id);
}
void periodicBall_testParam() {
int i, j = 0;
int dcol = BGC;
int *pun_col;
int color;
int x, ox, xStart;
int y, oy;
float vel = VELX;
float tx = 0.0, dt;
i = ptask_get_index();
pun_col = ptask_get_argument();
color = *pun_col;
x = ox = xStart = XMIN ;
y = oy = BASE -1 + 20 +(i * 4 * L);
dt = ptask_get_period(i, MILLI) / 100.;
pthread_mutex_lock(&mxa);
print_id_task(i, 5, y , color);
pthread_mutex_unlock(&mxa);
sample[i] = 0;
while (1) {
x = xStart + vel * tx;
if (x > XMAX) {
tx = 0.0;
xStart = XMAX;
vel = -vel;
x = xStart;
}
if (x < XMIN) {
tx = 0.0;
xStart = XMIN;
vel = -vel;
x = xStart ;
}
pthread_mutex_lock(&mxa);
draw_ball( ox, y , BGC);
draw_ball( x, y , color );
pthread_mutex_unlock(&mxa);
dt = ptask_get_period(i, MILLI) / 100.;
tx += dt;
ox = x;
if (ptask_deadline_miss()) {
dcol = (dcol + 1) % 15;
pthread_mutex_lock(&mxa);
draw_ball( XMAX + 15, y , dcol );
pthread_mutex_unlock(&mxa);
}
ptask_wait_for_period();
if (j < MAX_SAMPLE) {
start_time[i][j] = ptask_gettime(MILLI);
v_next_at[i][j] = ptask_get_nextactivation(MILLI);
sample[i]++;
j++;
}
}
}
void periodicBall_testParamDEP_PER() {
int i, j = 0;
int dcol = BGC;
int *pun_col;
int color;
int x, ox, xStart ;
int y, oy;
float vel= VELX;
float tx = 0.0;
float dt = 20.0 / 100.0;
i = ptask_get_index();
pun_col = ptask_get_argument();
color = *pun_col;
x = ox = xStart = XMIN ;
y = oy = BASE -1 + 20 +(i * 4 * L);
pthread_mutex_lock(&mxa);
print_id_task(i, 5, y , color);
pthread_mutex_unlock(&mxa);
sample[i] = 0;
while (1) {
x = xStart + vel * tx;
if (x > XMAX) {
tx = 0.0;
xStart = XMAX;
vel = -vel;
x = xStart;
}
if (x < XMIN) {
tx = 0.0;
xStart = XMIN;
vel = -vel;
x = xStart ;
}
pthread_mutex_lock(&mxa);
draw_ball( ox, y , BGC);
draw_ball( x, y , color );
pthread_mutex_unlock(&mxa);
tx += dt;
ox = x;
if (ptask_deadline_miss()) {
dcol = (dcol + 1) % 15;
pthread_mutex_lock(&mxa);
draw_ball( XMAX + 15, y , dcol );
pthread_mutex_unlock(&mxa);
}
ptask_wait_for_period();
if (j < MAX_SAMPLE) {
start_time[i][j] = ptask_gettime(MILLI);
v_next_at[i][j] = ptask_get_nextactivation(MILLI);
sample[i]++;
j++;
}
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_mutex_t lock2;
int value;
int value2;
sem_t sem;
void *functionWithCriticalSection(int* v2) {
pthread_mutex_lock(&(lock));
pthread_mutex_lock(&(lock2));
value = value2 + *v2;
value2 = value;
pthread_mutex_unlock(&(lock2));
pthread_mutex_unlock(&(lock));
sem_post(&sem);
}
void *otherFunctionWithCriticalSection(int* v2) {
if (v2 != 0) {
pthread_mutex_lock(&(lock));
pthread_mutex_lock(&(lock2));
value = value2 + 1;
value2 = value;
pthread_mutex_unlock(&(lock2));
pthread_mutex_unlock(&(lock));
}
sem_post(&sem);
}
int main() {
sem_init(&sem, 0, 0);
value = 0;
value2 = 0;
int v2 = 2;
pthread_mutex_init(&(lock), 0);
pthread_mutex_init(&(lock2), 0);
pthread_t thread1;
pthread_t thread2;
pthread_create (&thread1,0,functionWithCriticalSection,&v2);
pthread_create (&thread2,0,otherFunctionWithCriticalSection,&v2);
sem_wait(&sem);
sem_wait(&sem);
pthread_mutex_destroy(&(lock));
pthread_mutex_destroy(&(lock2));
sem_destroy(&sem);
printf("%d\\n", value);
return 0;
}
| 0
|
#include <pthread.h>
void
cond_wait (pthread_cond_t *cond, pthread_mutex_t *mut)
{
pthread_mutex_lock(mut);
pthread_cond_wait (cond, mut);
pthread_mutex_unlock (mut);
}
void
noreturn (void)
{
pthread_mutex_t mut;
pthread_cond_t cond;
pthread_mutex_init (&mut, 0);
pthread_cond_init (&cond, 0);
cond_wait (&cond, &mut);
}
void *
forever_pthread (void *unused)
{
noreturn ();
}
void
break_me (void)
{
}
int
main (void)
{
pthread_t forever;
const struct timespec ts = { 0, 10000000 };
pthread_create (&forever, 0, forever_pthread, 0);
for (;;)
{
nanosleep (&ts, 0);
break_me();
}
return 0;
}
| 1
|
#include <pthread.h>
void *find_bmp(void *path){
char *file, *file_ext, file_path[1000];
DIR *inDir;
struct dirent *inDirent;
inDir = opendir(path);
if (!inDir) {
fprintf(stderr, "Error while searching for bmp files: invalid file path.\\n");
fprintf(stderr, " Unable to open directory at %s\\n", (char *) path);
pthread_exit(0);
}
while ( (inDirent = readdir(inDir)) ) {
file = inDirent->d_name;
file_ext = strrchr(file, '.');
if (!strcmp(file, ".") || !strcmp(file, "..") || !strcmp(file, ".DS_Store") ||
!file_ext) {
continue;
}
if (!strcmp(file_ext, ".bmp")) {
strcpy(file_path, path);
strcat(file_path, "/");
strcat(file_path, file);
pthread_mutex_lock(&html_mutex);
generate_html(file_path);
pthread_mutex_unlock(&html_mutex);
}
}
closedir(inDir);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
struct queue_root *ALLOC_QUEUE_ROOT()
{
struct queue_root *root =
malloc(sizeof(struct queue_root));
pthread_mutex_init(&root->lock, 0);
root->in_queue = 0;
root->out_queue = 0;
return root;
}
void INIT_QUEUE_HEAD(struct queue_head *head)
{
head->next = ((void*)0xCAFEBAB5);
}
void queue_put(struct queue_head *new,
struct queue_root *root)
{
while (1) {
struct queue_head *in_queue = root->in_queue;
new->next = in_queue;
if (__sync_bool_compare_and_swap(&root->in_queue, in_queue, new)) {
break;
}
}
}
struct queue_head *queue_get(struct queue_root *root)
{
pthread_mutex_lock(&root->lock);
if (!root->out_queue) {
while (1) {
struct queue_head *head = root->in_queue;
if (!head) {
break;
}
if (__sync_bool_compare_and_swap(&root->in_queue, head, 0)) {
while (head) {
struct queue_head *next = head->next;
head->next = root->out_queue;
root->out_queue = head;
head = next;
}
break;
}
}
}
struct queue_head *head = root->out_queue;
if (head) {
root->out_queue = head->next;
}
pthread_mutex_unlock(&root->lock);
return head;
}
| 1
|
#include <pthread.h>
static struct cedrus
{
int fd;
void *regs;
int version;
int ioctl_offset;
struct cedrus_allocator *allocator;
pthread_mutex_t device_lock;
} ve = { .fd = -1, .device_lock = PTHREAD_MUTEX_INITIALIZER };
struct cedrus *cedrus_open(void)
{
if (ve.fd != -1)
return 0;
struct cedarv_env_infomation info;
ve.fd = open("/dev/cedar_dev", O_RDWR);
if (ve.fd == -1)
return 0;
if (ioctl(ve.fd, IOCTL_GET_ENV_INFO, (void *)(&info)) == -1)
goto close;
ve.regs = mmap(0, 0x800, PROT_READ | PROT_WRITE, MAP_SHARED, ve.fd, info.address_macc);
if (ve.regs == MAP_FAILED)
goto close;
{
ve.allocator = cedrus_allocator_ve_new(ve.fd, &info);
if (!ve.allocator)
{
ve.allocator = cedrus_allocator_ion_new();
if (!ve.allocator)
goto unmap;
}
}
ioctl(ve.fd, IOCTL_ENGINE_REQ, 0);
ve.version = readl(ve.regs + VE_VERSION) >> 16;
if (ve.version >= 0x1639)
ve.ioctl_offset = 1;
ioctl(ve.fd, IOCTL_ENABLE_VE + ve.ioctl_offset, 0);
ioctl(ve.fd, IOCTL_SET_VE_FREQ + ve.ioctl_offset, 320);
ioctl(ve.fd, IOCTL_RESET_VE + ve.ioctl_offset, 0);
writel(0x00130007, ve.regs + VE_CTRL);
return &ve;
unmap:
munmap(ve.regs, 0x800);
close:
close(ve.fd);
ve.fd = -1;
return 0;
}
void cedrus_close(struct cedrus *dev)
{
if (dev->fd == -1)
return;
ioctl(dev->fd, IOCTL_DISABLE_VE + dev->ioctl_offset, 0);
ioctl(dev->fd, IOCTL_ENGINE_REL, 0);
munmap(dev->regs, 0x800);
dev->regs = 0;
dev->allocator->free(dev->allocator);
close(dev->fd);
dev->fd = -1;
}
int cedrus_get_ve_version(struct cedrus *dev)
{
if (!dev)
return 0x0;
return dev->version;
}
int cedrus_ve_wait(struct cedrus *dev, int timeout)
{
if (!dev)
return -1;
return ioctl(dev->fd, IOCTL_WAIT_VE_DE, timeout);
}
void *cedrus_ve_get(struct cedrus *dev, enum cedrus_engine engine, uint32_t flags)
{
if (!dev || pthread_mutex_lock(&dev->device_lock))
return 0;
writel(0x00130000 | (engine & 0xf) | (flags & ~0xf), dev->regs + VE_CTRL);
return dev->regs;
}
void cedrus_ve_put(struct cedrus *dev)
{
if (!dev)
return;
writel(0x00130007, dev->regs + VE_CTRL);
pthread_mutex_unlock(&dev->device_lock);
}
struct cedrus_mem *cedrus_mem_alloc(struct cedrus *dev, size_t size)
{
if (!dev || size == 0)
return 0;
return dev->allocator->mem_alloc(dev->allocator, (size + 4096 - 1) & ~(4096 - 1));
}
void cedrus_mem_free(struct cedrus_mem *mem)
{
if (!mem)
return;
ve.allocator->mem_free(ve.allocator, mem);
}
void cedrus_mem_flush_cache(struct cedrus_mem *mem)
{
if (!mem)
return;
ve.allocator->mem_flush(ve.allocator, mem);
}
void *cedrus_mem_get_pointer(const struct cedrus_mem *mem)
{
if (!mem)
return 0;
return mem->virt;
}
uint32_t cedrus_mem_get_phys_addr(const struct cedrus_mem *mem)
{
if (!mem)
return 0x0;
return mem->phys;
}
uint32_t phys2bus(uint32_t phys)
{
if (ve.version == 0x1639)
return phys - 0x20000000;
else
return phys - 0x40000000;
}
uint32_t bus2phys(uint32_t bus)
{
if (ve.version == 0x1639)
return bus + 0x20000000;
else
return bus + 0x40000000;
}
uint32_t cedrus_mem_get_bus_addr(const struct cedrus_mem *mem)
{
if (!mem)
return 0x0;
return phys2bus(mem->phys);
}
| 0
|
#include <pthread.h>
pthread_mutex_t commandCentersList[200];
pthread_t workersList[200];
pthread_mutex_t mapRss_lock;
pthread_mutex_t myRss_lock;
int mapRss = 5000;
int myRss = 0;
int myCommandCenters = 0;
int myWorkers = 0;
int myTroops = 0;
void* workingProcess(void* a){
int workerId = (int64_t)a;
int trylock;
while(101)
{
int i;
printf("SCV %d is mining\\n",workerId +1);
pthread_mutex_lock(&mapRss_lock);
if(mapRss < 8)
{
pthread_mutex_unlock(&mapRss_lock);
printf("Start Map Resources: %d\\n", 5000);
printf("Your Resources: %d\\n", myRss);
int spent = 50 * (myTroops + myWorkers-5) - 400 * (myCommandCenters -1);
printf("Spent Resources: %d\\n", spent);
printf("On Map more: %d\\n",mapRss);
return 0;
}
mapRss = mapRss - 8;
pthread_mutex_unlock(&mapRss_lock);
printf("SCV %d is transporting minerals\\n",workerId +1);
sleep(2);
while(trylock){
for(i=0; i<myCommandCenters; i++){
if (pthread_mutex_trylock(&commandCentersList[i])==0){
pthread_mutex_lock(&myRss_lock);
myRss += 8;
printf("SCV %d delivered minerals to Command Center %d\\n",
workerId+1, i+1);
pthread_mutex_unlock(&myRss_lock);
pthread_mutex_unlock(&commandCentersList[i]);
break;
}else trylock = 1;
}
sleep(1);
}
}
}
void buildCommandCenter(){
if(myCommandCenters != 0)
{
pthread_mutex_lock(&myRss_lock);
if(myRss<400 ){
printf("Not enough minerals.\\n");
pthread_mutex_unlock(&myRss_lock);
return;
}
myRss -= 400;
pthread_mutex_unlock(&myRss_lock);
sleep(2);
}
if(pthread_mutex_init(&commandCentersList[myCommandCenters], 0) != 0)
{
printf("Error with building of new CommandCenter");
exit(1);
}
printf("Command Center %d created\\n", ++myCommandCenters);
}
void learnNewWorker(){
if(myWorkers > 4)
{
pthread_mutex_lock(&myRss_lock);
if(myRss<50){
printf("Not enough minerals.\\n");
pthread_mutex_unlock(&myRss_lock);
return;
}
if(myWorkers > 200){
printf("You can't learn more Workers.\\n");
return;
}
myRss -= 50;
pthread_mutex_unlock(&myRss_lock);
sleep(1);
}
if(pthread_create(&workersList[myWorkers], 0 ,workingProcess,(void*)(int64_t)myWorkers) != 0)
{
printf("Error with learning new Workers\\n");
exit(1);
}
printf("SCV %d good to go, sir\\n", ++myWorkers);
}
void TrainTroop(){
pthread_mutex_lock(&myRss_lock);
if(myRss<50){
printf("Not enough minerals.\\n");
pthread_mutex_unlock(&myRss_lock);
return;
}
myRss -= 50;
pthread_mutex_unlock(&myRss_lock);
sleep(1);
printf("You wanna piece of me, boy? I am %d \\n troop", ++myTroops);
if (myTroops == 20)
{
printf("Start Map Resources: %d\\n", 5000);
printf("Your Resources: %d\\n", myRss);
int spent = 50 * (myTroops + myWorkers-5) - 400 * (myCommandCenters -1);
printf("Spent Resources: %d\\n", spent);
printf("On Map more%d\\n",mapRss);
printf("You win ;)\\n");
exit(0);
}
}
int main (int argc, char *argv[])
{
int i;
if (pthread_mutex_init(&myRss_lock,0) != 0)
{
printf("Error with Mutex_Init");
exit(1);
}
if (pthread_mutex_init(&mapRss_lock,0) != 0)
{
printf("Error with Mutex_Init");
exit(1);
}
buildCommandCenter();
for (i = 0; i < 5; i += 1)
{
learnNewWorker();
}
while (1010)
{
char input;
input = getchar();
switch(input)
{
case 'c':
buildCommandCenter();
break;
case 'm':
TrainTroop();
break;
case 's':
learnNewWorker();
break;
case '\\n':
break;
default:
printf("X>%c<X is not right command!!\\n",input);
}
}
return 0;
}
| 1
|
#include <pthread.h>
struct measurement {
unsigned tid;
long long real_nsec;
long long user_nsec;
struct measurement *next;
};
static pthread_mutex_t measurements_lock = PTHREAD_MUTEX_INITIALIZER;
struct measurement *perfpiece_measurements = 0;
int perfpiece_active_p = 0;
int libppmonitor_loaded_p = 0;
void free_perfpiece_measurements()
{
struct measurement *m, *next;
for (m = perfpiece_measurements; m != 0; m = next) {
next = m->next;
free(m);
}
perfpiece_measurements = 0;
}
void monitor_init_library(void)
{
libppmonitor_loaded_p = 1;
monitor_opt_error = 0;
}
void monitor_init_process(char *process, int *argc, char **argv, unsigned tid)
{
PAPI_library_init(PAPI_VER_CURRENT);
PAPI_thread_init(pthread_self);
}
void *monitor_init_thread(unsigned tid)
{
struct measurement *m;
if (!perfpiece_active_p)
return 0;
PAPI_register_thread();
m = malloc(sizeof(struct measurement));
m->tid = tid;
m->user_nsec = PAPI_get_virt_nsec();
m->real_nsec = PAPI_get_real_nsec();
pthread_mutex_lock(&measurements_lock);
m->next = perfpiece_measurements;
perfpiece_measurements = m;
pthread_mutex_unlock(&measurements_lock);
return m;
}
void monitor_fini_thread(void *ptr)
{
struct measurement *m;
if (!perfpiece_active_p)
return;
m = (struct measurement *) ptr;
m->real_nsec = PAPI_get_real_nsec() - m->real_nsec;
m->user_nsec = PAPI_get_virt_nsec() - m->user_nsec;
PAPI_unregister_thread();
}
| 0
|
#include <pthread.h>
int i = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t *dlock;
void *
fn1(void *arg) {
struct timespec tout;
struct tm *tmp;
clock_gettime(CLOCK_REALTIME, &tout);
tmp = localtime(&tout.tv_sec);
pthread_t tid = pthread_self();
printf("thread1: %lu\\n", tid);
while(i < 10) {
sleep(1);
if (pthread_mutex_timedlock(dlock, &tout) == 0) {
printf("thread1 i=%d\\n", i);
i++;
pthread_mutex_unlock(dlock);
} else {
tout.tv_sec += 1;
printf("thread1 can't get lock: %d\\n", i);
}
}
pthread_exit(((void *)1));
}
void *
fn2(void *arg) {
pthread_t tid = pthread_self();
printf("thread2: %lu\\n", tid);
while(i < 10) {
sleep(1);
if (pthread_mutex_lock(dlock) == 0){
printf("thread2 i=%d\\n", i);
i++;
pthread_mutex_unlock(dlock);
} else {
printf("thread2 can't get lock: %d\\n", i);
}
}
pthread_exit(((void *)2));
}
void *
fn3(void *arg) {
pthread_t tid = pthread_self();
printf("thread3: %lu\\n", tid);
while(i < 10) {
sleep(1);
if (pthread_mutex_trylock(dlock) == 0) {
printf("thread3 i=%d\\n", i);
i++;
pthread_mutex_unlock(dlock);
} else {
printf("thread3 can't get clock: %d\\n", i);
}
}
pthread_exit(((void *)3));
}
int
main(int argc, char *argv[]) {
pthread_t tid1, tid2, tid3;
dlock = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t *));
pthread_mutex_init(dlock, 0);
pthread_create(&tid2, 0, fn2, 0);
pthread_create(&tid1, 0, fn1, 0);
pthread_create(&tid3, 0, fn3, 0);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
pthread_join(tid3, 0);
pthread_mutex_destroy(dlock);
return 0;
}
| 1
|
#include <pthread.h>
struct s_word_object {
char *word;
word_object *next;
};
static word_object *list_head;
static pthread_mutex_t list_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t list_data_ready = PTHREAD_COND_INITIALIZER;
static pthread_cond_t list_data_flush = PTHREAD_COND_INITIALIZER;
static void add_to_list(char *word) {
word_object *last_object, *tmp_object;
char *tmp_string = strdup(word);
tmp_object = malloc(sizeof(word_object));
pthread_mutex_lock(&list_lock);
if (list_head == 0) {
last_object = tmp_object;
list_head = last_object;
} else {
last_object = list_head;
while (last_object->next) {
last_object = last_object->next;
}
last_object->next = tmp_object;
last_object = last_object->next;
}
last_object->word = tmp_string;
last_object->next = 0;
pthread_mutex_unlock(&list_lock);
pthread_cond_signal(&list_data_ready);
}
static word_object *list_get_first(void) {
word_object *first_object;
first_object = list_head;
list_head = list_head->next;
return first_object;
}
static void *print_func(void *arg) {
word_object *current_object;
fprintf(stderr, "Print thread starting\\n");
while(1) {
pthread_mutex_lock(&list_lock);
while (list_head == 0) {
pthread_cond_wait(&list_data_ready, &list_lock);
}
current_object = list_get_first();
pthread_mutex_unlock(&list_lock);
printf("Print thread: %s\\n", current_object->word);
free(current_object->word);
free(current_object);
pthread_cond_signal(&list_data_flush);
}
return arg;
}
static void list_flush(void) {
pthread_mutex_lock(&list_lock);
while (list_head != 0) {
pthread_cond_signal(&list_data_ready);
pthread_cond_wait(&list_data_flush, &list_lock);
}
pthread_mutex_unlock(&list_lock);
}
int main(int argc, char **argv) {
char input_word[256];
int c;
int option_index = 0;
int count = -1;
pthread_t print_thread;
static struct option long_options[] = {
{"count", required_argument, 0, 'c'},
{0, 0, 0, 0 }
};
while (1) {
c = getopt_long(argc, argv, "c:", long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 'c':
count = atoi(optarg);
break;
}
}
pthread_create(&print_thread, 0, print_func, 0);
fprintf(stderr, "Accepting %i input strings\\n", count);
while (scanf("%256s", input_word) != EOF) {
add_to_list(input_word);
if (!--count) break;
}
list_flush();
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t frog_mutex;
const char * const FROG[FROG_HEIGHT] =
{
"@@",
"><"
};
const char * const FROG_CLOSE[FROG_HEIGHT] =
{
"^^",
"=="
};
static bool in_bound(const int x, const int y)
{
if(x <= SCR_RIGHT && x >= SCR_LEFT
&& y <= (SCR_BOTTOM-3) && y >= (SCR_TOP+2))
{
syslog(LOG_WARNING, "x %d - y %d", x, y);
return 1;
}
return 0;
}
void blink_frog(struct frog_t *frog, const int flash_wait)
{
pthread_mutex_lock(&frog_mutex);
pthread_mutex_lock(&console_mutex);
screen_clear_image(frog->y, frog->x,
FROG_WIDTH, FROG_HEIGHT);
screen_draw_image(frog->y, frog->x,
(char**)FROG_CLOSE, FROG_HEIGHT);
pthread_mutex_unlock(&console_mutex);
pthread_mutex_unlock(&frog_mutex);
sleep_ticks(flash_wait);
pthread_mutex_lock(&frog_mutex);
pthread_mutex_lock(&console_mutex);
screen_clear_image(frog->y, frog->x,
FROG_WIDTH, FROG_HEIGHT);
screen_draw_image(frog->y, frog->x,
(char**)FROG, FROG_HEIGHT);
pthread_mutex_unlock(&console_mutex);
pthread_mutex_unlock(&frog_mutex);
sleep_ticks(flash_wait);
}
static void draw_frog(struct frog_t prev_frog, struct frog_t *frog)
{
pthread_mutex_lock(&console_mutex);
screen_clear_image(prev_frog.y, prev_frog.x,
FROG_WIDTH, FROG_HEIGHT);
screen_draw_image(frog->y, frog->x,
(char**)FROG, FROG_HEIGHT);
pthread_mutex_unlock(&console_mutex);
}
void init_frog(struct frog_t *frog)
{
pthread_mutex_lock(&frog_mutex);
draw_frog(*frog, frog);
pthread_mutex_unlock(&frog_mutex);
}
void move_frog(struct frog_t *frog, const char dir, bool is_wood)
{
int frog_x = -1;
int frog_y = -1;
bool move_frog = 0;
struct frog_t prev_frog = {0};
pthread_mutex_lock(&frog_mutex);
prev_frog = *frog;
frog_x = frog->x;
frog_y = frog->y;
move_frog = 1;
switch(dir)
{
case 'h':
frog_x -= 1;
break;
case 'l':
frog_x += 1;
break;
case 'j':
frog_y += 2;
break;
case 'k':
frog_y -= 2;
break;
default:
move_frog = 0;
break;
}
if(move_frog && in_bound(frog_x, frog_y))
{
frog->x = frog_x;
frog->y = frog_y;
if(!is_wood)
{
draw_frog(prev_frog, frog);
}
else
{
draw_frog(*frog, frog);
}
}
pthread_mutex_unlock(&frog_mutex);
}
| 1
|
#include <pthread.h>
char char1[671088640], char2[671088640];
long buffer_size, size_div;
struct timeval t;
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int th;
void file()
{
printf("\\nGenerating data in the memory...");
int i;
for (i = 0; i < 671088640; ++i)
{
char1[i]= 'A';
}
}
void *read_write()
{
long j,k;
pthread_mutex_lock( &mutex1 );
FILE *f = fopen("Disk_Benchmark.txt","w+");
size_div = ((671088640/buffer_size)/th);
for(j=0;j<size_div;j++)
{
fwrite(char1,buffer_size,1,f);
}
fseek(f, 0, 0);
for(int k=0;k<size_div;k++)
{
fread(char2,buffer_size,1,f);
}
fclose (f);
pthread_mutex_unlock( &mutex1 );
}
void *seq_read()
{
pthread_mutex_lock( &mutex1 );
FILE *f = fopen("Disk_Benchmark.txt","r");
size_div = ((671088640/buffer_size)/th);
fseek(f, 0, 0);
for(int l=0;l<size_div;l++)
{
fread(char2, buffer_size, 1, f);
}
fclose (f);
pthread_mutex_unlock( &mutex1 );
}
void *ran_read()
{
long m, rr;
pthread_mutex_lock( &mutex1 );
FILE *f = fopen("Disk_Benchmark.txt","r");
size_div = ((671088640/buffer_size)/th);
for(m=0;m<size_div;m++)
{
rr = rand()%100;
fseek(f,rr,0);
fread(char2, buffer_size, 1, f);
}
fclose (f);
pthread_mutex_unlock( &mutex1 );
}
int main()
{
int a, b, choice, c, d, e, g;
double start_th, stop_th, th_t, x, y, z;
float th_tp[40];
printf("How many Threads you want to Create 1, 2, 4 or 8\\n");
printf("Enter Number of Threads: ");
scanf("%d",&th);
pthread_t threads[th];
printf("\\nSelect Block size: \\n 1. 8B\\t2. 8KB\\t3. 8MB\\t4. 80MB");
printf("\\nEnter Your Choice: ");
scanf("%d", &choice);
if (choice == 1)
{
buffer_size = 8;
}
else if (choice == 2)
{
buffer_size = 8192;
}
else if (choice == 3)
{
buffer_size = 8388608;
}
else if (choice == 4)
{
buffer_size = 83886080;
}
else
{
printf("Wrong Choice\\n");
}
printf ("\\nSelected Thread(s) = %d & Block Size = %li Byte(s)\\n", th, buffer_size);
file();
printf("\\nWriting and Reading File into disk...\\n");
gettimeofday(&t,0);
start_th = t.tv_sec+(t.tv_usec/1000000.0);
for(a = 0; a < th; a++)
{
pthread_create(&threads[a],0, &read_write, 0);
}
for(b =0; b < th; b++)
{
pthread_join(threads[b], 0);
}
gettimeofday(&t,0);
stop_th = t.tv_sec+(t.tv_usec/1000000.0);
th_t = stop_th - start_th;
z = ((671088640)/th_t)/(1024*1024);
printf("\\nThroughput for Disk Read & Write: %lf MB/s\\n", z);
printf("Latency for Disk Read & Write: %lf Micro Sec.\\n", (th_t/671088640)*10000000);
sleep(1);
gettimeofday(&t,0);
start_th = t.tv_sec+(t.tv_usec/1000000.0);
for(c = 0; c < th; c++)
{
pthread_create(&threads[c],0, &seq_read, 0);
}
for(d =0; d < th; d++)
{
pthread_join(threads[d], 0);
}
gettimeofday(&t,0);
stop_th = t.tv_sec+(t.tv_usec/1000000.0);
th_t = stop_th - start_th;
y = ((671088640)/th_t)/(1024*1024);
printf("\\nThroughput for Sequential Disk Read: %lf MB/s\\n", y);
printf("Latency for Sequential Disk Read: %lf Micro Sec.\\n", (th_t/671088640)*10000000);
sleep(1);
gettimeofday(&t,0);
start_th = t.tv_sec+(t.tv_usec/1000000.0);
for(e = 0; e < th; e++)
{
pthread_create(&threads[a],0, &ran_read, 0);
}
for(g =0; g < th; g++)
{
pthread_join(threads[b], 0);
}
gettimeofday(&t,0);
stop_th = t.tv_sec+(t.tv_usec/1000000.0);
th_t = stop_th - start_th;
x = ((671088640)/th_t)/(1024*1024);
printf("\\nThroughput for Random Disk Read: %lf MB/s\\n", x);
printf("Latency for Random Disk Read: %lf Micro Sec.\\n", (th_t/671088640)*10000000);
return 0;
}
| 0
|
#include <pthread.h>
void* handle_clnt(void *arg);
void send_msg(int clnt_sock, char *msg, int len);
void error_handling(char *msg);
int clnt_cnt = 0;
int clnt_socks[256];
pthread_mutex_t mutex;
int main(int argc, char *argv[]){
int serv_sock, clnt_sock;
struct sockaddr_in serv_adr, clnt_adr;
int clnt_adr_sz;
pthread_t t_id;
if(argc != 2){
printf("Usage : %s <port> \\n", argv[0]);
exit(1);
}
pthread_mutex_init(&mutex, 0);
serv_sock = socket(PF_INET, SOCK_STREAM, 0);
memset(&serv_adr, 0, sizeof(serv_adr));
serv_adr.sin_family = AF_INET;
serv_adr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_adr.sin_port = htons(atoi(argv[1]));
if(bind(serv_sock, (struct sockaddr*)&serv_adr, sizeof(serv_adr)) == -1)
error_handling("bind() error");
if(listen(serv_sock, 5) == -1)
error_handling("listen() error");
while(1){
clnt_adr_sz = sizeof(clnt_adr);
clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_adr, &clnt_adr_sz);
pthread_mutex_lock(&mutex);
clnt_socks[clnt_cnt++] = clnt_sock;
pthread_mutex_unlock(&mutex);
pthread_create(&t_id, 0, handle_clnt, (void*)&clnt_sock);
pthread_detach(t_id);
printf("Connected client IP : %s\\n", inet_ntoa(clnt_adr.sin_addr));
}
close(serv_sock);
return 0;
}
void* handle_clnt(void *arg){
int clnt_sock =*((int*)arg);
int str_len = 0, i;
char msg[100];
while((str_len=read(clnt_sock, msg, sizeof(msg))) != 0)
send_msg(clnt_sock, msg, str_len);
pthread_mutex_lock(&mutex);
for(i = 0; i < clnt_cnt; i++){
if(clnt_sock == clnt_socks[i]){
while(i++ < clnt_cnt-1)
clnt_socks[i] = clnt_socks[i+1];
break;
}
}
clnt_cnt--;
pthread_mutex_unlock(&mutex);
close(clnt_sock);
return 0;
}
void send_msg(int clnt_sock, char *msg, int len){
int i;
pthread_mutex_lock(&mutex);
for(i = 0; i < clnt_cnt; i++)
if(clnt_sock != clnt_socks[i])
write(clnt_socks[i], msg, len);
pthread_mutex_unlock(&mutex);
}
void error_handling(char *msg){
fputs(msg, stderr);
fputc('\\n', stderr);
exit(1);
}
| 1
|
#include <pthread.h>
{
int sum;
pthread_mutex_t lock;
}ct_sum;
void *add1(void *cnt)
{
cnt=(ct_sum*)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)
{
cnt=(ct_sum*)cnt;
pthread_mutex_lock(&(((ct_sum*)cnt)->lock));
int i;
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()
{
int i;
pthread_t ptid1,ptid2;
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>extern void __VERIFIER_error();
unsigned int __VERIFIER_nondet_uint();
static int top = 0;
static unsigned int arr[800];
pthread_mutex_t m;
_Bool flag = 0;
void error(void)
{
ERROR:
__VERIFIER_error();
return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
top == 0 ? 1 : 0;
}
int push(unsigned int *stack, int x)
{
if (top == 800)
{
printf("stack overflow\\n");
return -1;
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (top == 0)
{
printf("stack underflow\\n");
return -2;
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for (i = 0; i < 800; i++)
{
__CPROVER_assume(((800 - i) >= 0) && (i >= 0));
{
__CPROVER_assume(((800 - i) >= 0) && (i >= 0));
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint() % 800;
if (push(arr, tmp) == (-1))
error();
pthread_mutex_unlock(&m);
}
}
}
}
void *t2(void *arg)
{
int i;
for (i = 0; i < 800; i++)
{
__CPROVER_assume(((800 - i) >= 0) && (i >= 0));
{
pthread_mutex_lock(&m);
if (top > 0)
{
if (pop(arr) == (-2))
error();
}
pthread_mutex_unlock(&m);
}
}
}
int main(void)
{
pthread_t id1;
pthread_t id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static int last_written;
static int trial;
static int write_locked;
static int done;
static void* thread(void* idp) {
int id = (intptr_t)idp;
int num_loops = 0;
int num_written = 0;
while (1) {
int this_write;
++num_loops;
{
pthread_mutex_lock(&lock);
while (!done && (last_written == trial || write_locked)) {
pthread_cond_wait(&cond, &lock);
}
if (done) {
pthread_mutex_unlock(&lock);
break;
}
write_locked = 1;
this_write = trial;
pthread_mutex_unlock(&lock);
}
atomic_printf("%d:%d(%d)\\n", id, this_write, num_loops);
++num_written;
{
pthread_mutex_lock(&lock);
last_written = this_write;
write_locked = 0;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&lock);
}
}
atomic_printf(" (%d wrote %d)\\n", id, num_written);
pthread_exit((void*)(intptr_t)num_written);
}
int main(int argc, char* argv[]) {
pthread_t threads[10];
int i;
int threads_num_written = 0;
for (i = 0; i < 10; ++i) {
test_assert(0 ==
pthread_create(&threads[i], 0, thread, (void*)(intptr_t)i));
}
for (i = 0; i < 1000; ++i) {
{
pthread_mutex_lock(&lock);
assert(i == trial);
test_assert(last_written == trial);
++trial;
if (i % 2) {
pthread_cond_signal(&cond);
} else {
pthread_cond_broadcast(&cond);
}
pthread_mutex_unlock(&lock);
}
{
pthread_mutex_lock(&lock);
while (last_written < trial) {
pthread_cond_wait(&cond, &lock);
}
pthread_mutex_unlock(&lock);
}
}
{
pthread_mutex_lock(&lock);
done = 1;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&lock);
}
for (i = 0; i < 10; ++i) {
void* ret = 0;
test_assert(0 == pthread_join(threads[i], &ret));
threads_num_written += (intptr_t)ret;
}
atomic_printf(" ... %d threads completed %d out of %d trials\\n", 10,
threads_num_written, 1000);
test_assert(threads_num_written == 1000);
atomic_puts("EXIT-SUCCESS");
return 0;
}
| 0
|
#include <pthread.h>
{
unsigned char valor;
pthread_mutex_t mutex;
pthread_cond_t esperoPar;
} numero_t;
numero_t arreglo[10/2];
pthread_t hilos[10];
int numeroAleatorio(int rango){
return ((rand()) % rango);
}
void arregloAleatorio(){
int i;
for(i = 0; i < (10/2); i++){
arreglo[i].valor = (unsigned char)numeroAleatorio(100);
pthread_mutex_init(&arreglo[i].mutex, 0);
pthread_cond_init(&arreglo[i].esperoPar, 0);
}
}
void *buscoHiloPar(void *args){
int numeroHilo = *(int *)args;
int posicion = numeroHilo % (10 / 2);
printf("Hilo %d tiene número %d.\\n", numeroHilo, arreglo[posicion].valor);
pthread_cond_signal(&arreglo[posicion].esperoPar);
pthread_mutex_lock(&arreglo[posicion].mutex);
pthread_cond_wait(&arreglo[posicion].esperoPar, &arreglo[posicion].mutex);
pthread_mutex_unlock(&arreglo[posicion].mutex);
pthread_cond_signal(&arreglo[posicion].esperoPar);
printf("El número %d está libre (Hilo %d)\\n", arreglo[posicion].valor, numeroHilo);
pthread_exit((void *) 0);
}
int main (void){
srand(getpid());
arregloAleatorio();
int i;
for(i = 0; i < 10; i++){
pthread_create(&hilos[i], 0, &buscoHiloPar, (void *)&i);
usleep(50000 * 5);
}
for(i = 0; i < 10; i++){
pthread_join(hilos[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
char MMAP_NAME[] = "racey-mmap.XXXXXX";
const int mmap_size = sizeof(unsigned) * 33;
int MaxLoop = 50000;
int NumProcs;
volatile int startCounter;
pthread_mutex_t threadLock;
unsigned *sig = 0;
union {
char b[64];
int value;
} m[64];
unsigned mix(unsigned i, unsigned j) {
return (i + j * 103995407) % 103072243;
}
void* ThreadBody(void* tid)
{
int threadId = *(int *) tid;
int i;
for(i=0; i<0x07ffffff; i++) {};
pthread_mutex_lock(&threadLock);
startCounter--;
if(startCounter == 0) {
}
pthread_mutex_unlock(&threadLock);
while(startCounter) {};
for(i = 0 ; i < MaxLoop; i++) {
unsigned num = sig[threadId];
unsigned index1 = num%64;
unsigned index2;
num = mix(num, m[index1].value);
index2 = num%64;
num = mix(num, m[index2].value);
m[index2].value = num;
sig[threadId] = num;
}
return 0;
}
int
InitMmap()
{
int fd, i, ret;
fd = mkstemp(MMAP_NAME);
assert(fd >= 0);
ret = ftruncate(fd, mmap_size);
assert(ret == 0);
sig = mmap(0, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
assert(sig != MAP_FAILED);
for(i = 0; i < 33; i++)
sig[i] = i;
return fd;
}
void
CloseMmap(int fd)
{
munmap(sig, mmap_size);
close(fd);
unlink(MMAP_NAME);
}
int
main(int argc, char* argv[])
{
pthread_t* threads;
int* tids;
pthread_attr_t attr;
int ret;
int mix_sig, i;
int fd;
if(argc < 2) {
fprintf(stderr, "%s <numProcesors> <maxLoop>\\n", argv[0]);
exit(1);
}
NumProcs = atoi(argv[1]);
assert(NumProcs > 0 && NumProcs <= 32);
if (argc >= 3) {
MaxLoop = atoi(argv[2]);
assert(MaxLoop > 0);
}
fd = InitMmap();
for(i = 0; i < 64; i++) {
m[i].value = mix(i,i);
}
startCounter = NumProcs;
threads = (pthread_t *) malloc(sizeof(pthread_t) * NumProcs);
assert(threads != 0);
tids = (int *) malloc(sizeof (int) * NumProcs);
assert(tids != 0);
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
ret = pthread_mutex_init(&threadLock, 0);
assert(ret == 0);
for(i=0; i < NumProcs; i++) {
tids[i] = i+1;
ret = pthread_create(&threads[i], &attr, ThreadBody, &tids[i]);
assert(ret == 0);
}
for(i=0; i < NumProcs; i++) {
ret = pthread_join(threads[i], 0);
assert(ret == 0);
}
mix_sig = sig[0];
for(i = 1; i < NumProcs ; i++) {
mix_sig = mix(sig[i], mix_sig);
}
printf("\\n\\nShort signature: %08x @ %p @ %p\\n\\n\\n",
mix_sig, &mix_sig, (void*)malloc((1 << 10)/5));
fflush(stdout);
usleep(5);
pthread_mutex_destroy(&threadLock);
pthread_attr_destroy(&attr);
CloseMmap(fd);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t s1,s2;
void * thread_func1(void * arg) {
while(1) {
sleep(1);
pthread_mutex_unlock(&s2);
printf("thread1 reached rendezvous point\\n");
pthread_mutex_lock(&s1);
printf("thread1 proceeds\\n");
}
}
void * thread_func2(void * arg) {
while (1) {
sleep(5);
pthread_mutex_unlock(&s1);
printf("thread2 reached rendezvous point\\n");
pthread_mutex_lock(&s2);
printf("thread2 proceeeds\\n");
}
}
int main(int argv, char ** argc){
pthread_t th1,th2;
int res;
pthread_mutex_init(&s1,0); pthread_mutex_lock(&s1);
pthread_mutex_init(&s2,0); pthread_mutex_lock(&s2);
res=pthread_create(&th1,0,thread_func1,0);
if(res) {
printf("ERROR: return code from pthread_create() is %d\\n",res);
exit(-1);
}
res=pthread_create(&th2,0,thread_func2,0);
if (res) {
printf("ERROR: return code from pthread_create() is %d\\n",res);
exit(-1);
}
while(1) {}
}
| 1
|
#include <pthread.h>
enum mode {
MODE_MB,
MODE_MEMBARRIER,
MODE_COMPILER_BARRIER,
MODE_MEMBARRIER_MISSING_REGISTER,
};
enum mode mode;
struct map_test {
int x, y;
int ref;
int r2, r4;
int r2_ready, r4_ready;
int killed;
pthread_mutex_t lock;
};
static void check_parent_regs(struct map_test *map_test, int r2)
{
pthread_mutex_lock(&map_test->lock);
if (map_test->r4_ready) {
if (r2 == 0 && map_test->r4 == 0) {
fprintf(stderr, "Error detected!\\n");
CMM_STORE_SHARED(map_test->killed, 1);
abort();
}
map_test->r4_ready = 0;
map_test->x = 0;
map_test->y = 0;
} else {
map_test->r2 = r2;
map_test->r2_ready = 1;
}
pthread_mutex_unlock(&map_test->lock);
}
static void check_child_regs(struct map_test *map_test, int r4)
{
pthread_mutex_lock(&map_test->lock);
if (map_test->r2_ready) {
if (r4 == 0 && map_test->r2 == 0) {
fprintf(stderr, "Error detected!\\n");
CMM_STORE_SHARED(map_test->killed, 1);
abort();
}
map_test->r2_ready = 0;
map_test->x = 0;
map_test->y = 0;
} else {
map_test->r4 = r4;
map_test->r4_ready = 1;
}
pthread_mutex_unlock(&map_test->lock);
}
static void loop_parent(struct map_test *map_test)
{
int i, r2;
for (i = 0; i < 100000000; i++) {
uatomic_inc(&map_test->ref);
while (uatomic_read(&map_test->ref) < 2 * (i + 1)) {
if (map_test->killed)
abort();
caa_cpu_relax();
}
CMM_STORE_SHARED(map_test->x, 1);
switch (mode) {
case MODE_MB:
cmm_smp_mb();
break;
case MODE_MEMBARRIER:
case MODE_MEMBARRIER_MISSING_REGISTER:
if (-ENOSYS) {
perror("membarrier");
CMM_STORE_SHARED(map_test->killed, 1);
abort();
}
break;
case MODE_COMPILER_BARRIER:
cmm_barrier();
break;
}
r2 = CMM_LOAD_SHARED(map_test->y);
check_parent_regs(map_test, r2);
}
}
static void loop_child(struct map_test *map_test)
{
int i, r4;
switch (mode) {
case MODE_MEMBARRIER:
if (-ENOSYS) {
perror("membarrier");
CMM_STORE_SHARED(map_test->killed, 1);
abort();
}
break;
default:
break;
}
for (i = 0; i < 100000000; i++) {
uatomic_inc(&map_test->ref);
while (uatomic_read(&map_test->ref) < 2 * (i + 1)) {
if (map_test->killed)
abort();
caa_cpu_relax();
}
CMM_STORE_SHARED(map_test->y, 1);
switch (mode) {
case MODE_MB:
cmm_smp_mb();
break;
case MODE_MEMBARRIER:
case MODE_MEMBARRIER_MISSING_REGISTER:
cmm_barrier();
break;
case MODE_COMPILER_BARRIER:
cmm_barrier();
break;
}
r4 = CMM_LOAD_SHARED(map_test->x);
check_child_regs(map_test, r4);
}
}
void print_arg_error(void)
{
fprintf(stderr, "Please specify test mode: <m>: paired mb, <s>: sys-membarrier, <c>: compiler barrier (error), <n>: sys-membarrier with missing registration (error).\\n");
}
int main(int argc, char **argv)
{
char namebuf[PATH_MAX];
pid_t pid;
int fd, ret = 0;
void *buf;
struct map_test *map_test;
pthread_mutexattr_t attr;
if (argc < 2) {
print_arg_error();
return -1;
}
if (!strcmp(argv[1], "-m")) {
mode = MODE_MB;
} else if (!strcmp(argv[1], "-s")) {
mode = MODE_MEMBARRIER;
} else if (!strcmp(argv[1], "-c")) {
mode = MODE_COMPILER_BARRIER;
} else if (!strcmp(argv[1], "-n")) {
mode = MODE_MEMBARRIER_MISSING_REGISTER;
} else {
print_arg_error();
return -1;
}
buf = mmap(0, 4096, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_SHARED, -1, 0);
if (buf == MAP_FAILED) {
perror("mmap");
ret = -1;
goto end;
}
map_test = (struct map_test *)buf;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr, 1);
pthread_mutex_init(&map_test->lock, &attr);
pid = fork();
if (pid < 0) {
perror("fork");
ret = -1;
goto unmap;
}
if (!pid) {
loop_child(map_test);
return 0;
}
loop_parent(map_test);
pid = waitpid(pid, 0, 0);
if (pid < 0) {
perror("waitpid");
ret = -1;
}
unmap:
pthread_mutex_destroy(&map_test->lock);
pthread_mutexattr_destroy(&attr);
if (munmap(buf, 4096)) {
perror("munmap");
ret = -1;
}
end:
return ret;
}
| 0
|
#include <pthread.h>
FILE *fichierEdit;
char *tampon;
int tailleTampon;
int indice;
int fin;
char *nomFichier;
pthread_mutex_t mutex;
}Donne;
void
*saisirLesCaracteres(void *parametre);
void
*modifierLeFichier(void *parametre);
char
*agrandirLeTableau(char *letableau,int taille);
void
ecrireDansLeFichier(Donne *donnelocal);
void
viderTampon(Donne *donne);
void
ecrireDansLeFichier(Donne *donnelocal);
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
int main(int agrc, char*argv[]){
pthread_t threadlecture;
pthread_t threadmodification;
Donne *donne = malloc(sizeof(Donne));
donne->fichierEdit = fopen(argv[1],"w+");
donne->tailleTampon = 200;
donne->tampon = malloc(donne->tailleTampon*sizeof(char));
donne->fin = 1;
donne->nomFichier = argv[1];
if(donne == 0 || donne->tampon == 0 || donne->fichierEdit == 0){
if(donne->fichierEdit == 0)
fprintf(stderr,"Impossible de creer le fichier. \\n");
else
fprintf(stderr,"Impossible d'allouer de la memoire \\n");
exit(1);
}
pthread_mutex_init(&donne->mutex,0);
pthread_create(&threadlecture,0,saisirLesCaracteres,donne);
pthread_create(&threadmodification,0,modifierLeFichier,donne);
pthread_join(threadlecture,0);
pthread_join(threadmodification,0);
free(donne->tampon);
free(donne);
return 0;
}
void
*saisirLesCaracteres(void *parametre){
Donne *donnelocal = parametre;
int ponctuation = 0,indice = 0,slash = 0;
char caractere;
while((caractere = fgetc(stdin))!= EOF){
if(indice == 0){
if((islower(caractere)) && slash == 0)
caractere = toupper(caractere);
}
if(caractere == '.' || caractere == '!' || caractere == '?'){
ponctuation++;
}else if(ponctuation && caractere != ' ' ){
donnelocal->tampon[indice++] = ' ';
if(islower(caractere))
caractere = toupper(caractere);
ponctuation = 0;
}
pthread_mutex_lock(&donnelocal->mutex);
if(indice < donnelocal->tailleTampon){
donnelocal->tampon[indice++] = caractere;
}else{
donnelocal->tampon = agrandirLeTableau(donnelocal->tampon,donnelocal->tailleTampon);
donnelocal->tampon[indice++] = caractere;
donnelocal->tailleTampon = donnelocal->tailleTampon * 2;
}
pthread_mutex_unlock(&donnelocal->mutex);
if(caractere == '\\n'){
donnelocal->indice = indice;
pthread_mutex_lock(&donnelocal->mutex);
pthread_cond_signal(&condition);
pthread_mutex_unlock(&donnelocal->mutex);
indice = 0;
slash++;
}
if(caractere == 0033)
break;
}
donnelocal->fin = 0;
donnelocal->indice = indice;
pthread_mutex_lock(&donnelocal->mutex);
pthread_cond_signal(&condition);
pthread_mutex_unlock(&donnelocal->mutex);
pthread_exit(0);
}
char
*agrandirLeTableau(char *letableau,int taille){
char *ptr_tableau = calloc((taille*2),sizeof(char));
int i ;
for(i = 0; i < taille; i++){
ptr_tableau[i] = letableau[i];
}
return ptr_tableau;
}
void
*modifierLeFichier(void *parametre){
Donne *donnelocal = (Donne *) parametre;
int faire = 1;
while(faire){
pthread_mutex_lock(&donnelocal->mutex);
pthread_cond_wait(&condition,&donnelocal->mutex);
ecrireDansLeFichier(donnelocal);
viderTampon(donnelocal);
pthread_mutex_unlock(&donnelocal->mutex);
faire = donnelocal->fin;
}
return 0;
}
void
ecrireDansLeFichier(Donne *donnelocal){
donnelocal->fichierEdit = fopen(donnelocal->nomFichier,"a");
if(donnelocal->fichierEdit != 0)
fprintf(donnelocal->fichierEdit,"%s",donnelocal->tampon);
else
fprintf(stderr,"Erreur d'ouverture du fichier\\n");
fclose(donnelocal->fichierEdit);
}
void
viderTampon(Donne *donne){
int i = 0;
while(i < donne->indice)
donne->tampon[i++] = '\\0';
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex_leste;
pthread_mutex_t mutex_oeste;
pthread_mutex_t entrada;
pthread_mutex_t turno;
int leste = 0;
int oeste = 0;
void * macaco_leste(void * a){
int i = *((int *) a);
while(1){
pthread_mutex_lock(&turno);
pthread_mutex_lock(&mutex_leste);
leste++;
if(leste == 1){
pthread_mutex_lock(&entrada);
}
pthread_mutex_unlock(&mutex_leste);
pthread_mutex_unlock(&turno);
printf("Macaco %d passado do leste para oeste \\n",i);
sleep(1);
pthread_mutex_lock(&mutex_leste);
leste--;
printf("Macaco %d terminou de passar de leste para oeste ; num: %d\\n" ,i,leste);
if(leste == 0){
pthread_mutex_unlock(&entrada);
}
pthread_mutex_unlock(&mutex_leste);
}
pthread_exit(0);
}
void * macaco_oeste(void * a)
{
int i = *((int *) a);
while(1){
pthread_mutex_lock(&turno);
pthread_mutex_lock(&mutex_oeste);
oeste++;
if(oeste == 1){
pthread_mutex_lock(&entrada);
}
pthread_mutex_unlock(&mutex_oeste);
pthread_mutex_unlock(&turno);
printf("Macaco %d passado do oeste para leste \\n",i);
sleep(1);
pthread_mutex_lock(&mutex_oeste);
oeste--;
printf("Macaco %d terminou de passar de oeste para leste; num: %d\\n" ,i,oeste);
if(oeste == 0){
pthread_mutex_unlock(&entrada);
}
pthread_mutex_unlock(&mutex_oeste);
}
pthread_exit(0);
}
int main(int argc, char * argv[])
{
pthread_t m_o[10 +10];
pthread_mutex_init(&mutex_leste, 0);
pthread_mutex_init(&mutex_oeste, 0);
pthread_mutex_init(&entrada, 0);
pthread_mutex_init(&turno, 0);
int *id;
int i = 0;
for(i = 0; i < 10 +10; ++i)
{
id = (int *) malloc(sizeof(int));
*id = i;
if(i%2 == 0){
if(pthread_create(&m_o[i], 0, &macaco_oeste, (void*)id))
{
printf("Não pode criar a thread %d\\n", i);
return -1;
}
}else{
if(pthread_create(&m_o[i], 0, &macaco_leste, (void*)id))
{
printf("Não pode criar a thread %d\\n", i);
return -1;
}
}
id++;
}
for(i = 0; i < 10 +10; ++i)
{
if(pthread_join(m_o[i], 0))
{
printf("Could not join thread %d\\n", i);
return -1;
}
}
printf("TERMINOU!\\n");
return 0;
}
| 0
|
#include <pthread.h>
int nitems;
struct {
pthread_mutex_t mutex;
int buffer[1000000];
int nput;
int nval;
} shared = { PTHREAD_MUTEX_INITIALIZER };
void *producer(void *param)
{
for(;;) {
pthread_mutex_lock(&shared.mutex);
if (shared.nput >= nitems) {
pthread_mutex_unlock(&shared.mutex);
return 0;
}
shared.buffer[shared.nput] = shared.nval++;
shared.nput++;
pthread_mutex_unlock(&shared.mutex);
*((int *) param) += 1;
}
return 0;
}
void consumer_wait(int n)
{
for(;;) {
pthread_mutex_lock(&shared.mutex);
if (n < shared.nput) {
pthread_mutex_unlock(&shared.mutex);
return ;
}
pthread_mutex_unlock(&shared.mutex);
}
}
void *consumer(void *param)
{
int i;
for (i=0; i<nitems; ++i) {
consumer_wait(i);
if(shared.buffer[i] != i) {
printf("buffer[%d] = %d\\n", i, shared.buffer[i]);
} else {
}
}
return 0;
}
int main(int argc, char* argv[])
{
int i, nthreads = 5;
nitems = 1000000;
int total = 0, count[5];
pthread_t th[5];
pthread_attr_t thattr;
pthread_attr_setdetachstate(&thattr, PTHREAD_CREATE_DETACHED);
for(i=0; i<nthreads; ++i) {
count[i] = 0;
pthread_create(&th[i], 0, producer, &(count[i]));
}
pthread_t consume;
pthread_create(&consume, 0, consumer, 0);
pthread_join(consume, 0);
printf("\\n");
for(i=0; i<nthreads; ++i) {
pthread_join(th[i], 0);
printf("thread[%d] produce %d\\n", i, count[i]);
total += count[i];
}
printf("Total: %d\\n", total);
return 0;
}
| 1
|
#include <pthread.h>
struct farmer_data {
int num, to;
};
int passing, crt_dir;
pthread_mutex_t road;
static void *farmer_thread(void *param)
{
struct farmer_data *farmer = (struct farmer_data *) param;
for (;;) {
pthread_mutex_lock(&road);
printf("[FARMER %d] From %s to %s\\n",
farmer->num,
(1 - farmer->to) == 0 ? "North" : "South",
(farmer->to) == 0 ? "North" : "South");
sleep(1 + rand() % 3);
printf("[FARMER %d] Done\\n", farmer->num);
pthread_mutex_unlock(&road);
farmer->to = 1 - farmer->to;
sleep(1);
}
return 0;
}
static void getval(const char *str, long *val)
{
*val = strtol(str, 0, 10);
if ((errno == ERANGE && (*val == LONG_MAX || *val == LONG_MIN)) ||
(errno != 0 && *val == 0)) {
perror("strtol");
exit(errno);
}
}
static void init(pthread_attr_t *tattr)
{
pthread_attr_init(tattr);
pthread_mutex_init(&road, 0);
srand(time(0));
}
int main(int argc, char **argv)
{
pthread_attr_t tattr;
pthread_t farmer_tid[10 * 2 + 1];
struct farmer_data *farmers[10 * 2 + 1], *farmer;
long nnorth, nsouth, i;
if (argc < 3) {
fprintf(stderr, "usage: %s <nnorth> <nsouth>\\n", argv[0]);
return 1;
}
getval(argv[1], &nnorth);
getval(argv[2], &nsouth);
if (nnorth > 10 || nsouth > 10) {
fprintf(stderr, "max farmers: %d\\n", 10);
return 1;
}
init(&tattr);
for (i = 0; i < nnorth; i++) {
farmer = malloc(sizeof (struct farmer_data));
farmer->num = i + 1;
farmer->to = 0;
farmers[i] = farmer;
pthread_create(&farmer_tid[i], &tattr, farmer_thread, farmers[i]);
}
for (i = nnorth; i < nnorth + nsouth; i++) {
farmer = malloc(sizeof (struct farmer_data));
farmer->num = i + 1;
farmer->to = 1;
farmers[i] = farmer;
pthread_create(&farmer_tid[i], &tattr, farmer_thread, farmers[i]);
}
for (i = 0; i < nnorth + nsouth; i++) {
pthread_join(farmer_tid[i], 0);
free(farmers[i]);
}
return 0;
}
| 0
|
#include <pthread.h>
const int MAX_KEY = 100000000;
const int IN_LIST = 1;
const int EMPTY_LIST = -1;
const int END_OF_LIST = 0;
struct list_node_s {
int data;
pthread_mutex_t mutex;
struct list_node_s* next;
};
struct list_node_s* head = 0;
pthread_mutex_t head_mutex;
int thread_count; int total_ops;
double insert_percent; double search_percent; double delete_percent;
pthread_mutex_t count_mutex;
int member_total=0, insert_total=0, delete_total=0;
void Get_input(int* inserts_in_main_p) {
printf("Cuantas inserciones desea hacer ? \\n");
scanf("%d", inserts_in_main_p);
printf("Cuantas operacones en total desea hacer? \\n");
scanf("%d", &total_ops);
printf("Porcetaje para busquedas: \\n");
scanf("%lf", &search_percent);
printf("Porcentajes de inserciones: \\n");
scanf("%lf", &insert_percent);
delete_percent = 1.0 - (search_percent + insert_percent);
}
int Insert(int value) {
struct list_node_s* curr = head;
struct list_node_s* pred = 0;
struct list_node_s* temp;
while (curr != 0 && curr->data < value) {
pred = curr;
curr = curr->next;
}
if (curr == 0 || curr->data > value) {
temp = malloc(sizeof(struct list_node_s));
temp->data = value;
temp->next = curr;
if (pred == 0)
head = temp;
else
pred->next = temp;
return 1;
} else {
return 0;
}
}
int Member(int value) {
struct list_node_s* temp;
pthread_mutex_lock(&head_mutex);
temp = head;
while (temp != 0 && temp->data < value) {
if (temp->next != 0)
pthread_mutex_lock(&(temp->next->mutex));
if (temp == head)
pthread_mutex_unlock(&head_mutex);
pthread_mutex_unlock(&(temp->mutex));
temp = temp->next;
}
if (temp == 0 || temp->data > value) {
if (temp == head)
pthread_mutex_unlock(&head_mutex);
if (temp != 0)
pthread_mutex_unlock(&(temp->mutex));
return 0;
} else {
if (temp == head)
pthread_mutex_unlock(&head_mutex);
pthread_mutex_unlock(&(temp->mutex));
return 1;
}
}
int Delete(int value) {
struct list_node_s* curr = head;
struct list_node_s* pred = 0;
while (curr != 0 && curr->data < value) {
pred = curr;
curr = curr->next;
}
if (curr != 0 && curr->data == value) {
if (pred == 0) {
head = curr->next;
free(curr);
} else {
pred->next = curr->next;
free(curr);
}
return 1;
} else {
return 0;
}
}
void* Thread_work(void* rank) {
long my_rank = (long) rank;
int i, val;
double which_op;
unsigned seed = my_rank + 1;
int my_member=0, my_insert=0, my_delete=0;
int ops_per_thread = total_ops/thread_count;
for (i = 0; i < ops_per_thread; i++) {
which_op = my_drand(&seed);
val = my_rand(&seed) % MAX_KEY;
if (which_op < search_percent) {
Member(val);
my_member++;
} else if (which_op < search_percent + insert_percent) {
Insert(val);
my_insert++;
} else {
Delete(val);
my_delete++;
}
}
pthread_mutex_lock(&count_mutex);
member_total += my_member;
insert_total += my_insert;
delete_total += my_delete;
pthread_mutex_unlock(&count_mutex);
return 0;
}
int main(int argc, char* argv[]) {
long i;
int key, success, attempts;
pthread_t* thread_handles;
int inserts_in_main;
unsigned seed = 1;
double start, finish;
thread_count = strtol(argv[1], 0, 10);
Get_input(&inserts_in_main);
i = attempts = 0;
pthread_mutex_init(&head_mutex, 0);
while ( i < inserts_in_main && attempts < 2*inserts_in_main ) {
key = my_rand(&seed) % MAX_KEY;
success = Insert(key);
attempts++;
if (success) i++;
}
printf("Inserto %ld nodos en lista\\n", i);
thread_handles = malloc(thread_count*sizeof(pthread_t));
pthread_mutex_init(&count_mutex, 0);
GET_TIME(start);
for (i = 0; i < thread_count; i++)
pthread_create(&thread_handles[i], 0, Thread_work, (void*) i);
for (i = 0; i < thread_count; i++)
pthread_join(thread_handles[i], 0);
GET_TIME(finish);
printf("Tiempo Transcurrido = %e seconds\\n", finish - start);
printf("Operaciones Totales = %d\\n", total_ops);
printf("Ops Busqueda = %d\\n", member_total);
printf("Ops Inserciones = %d\\n", insert_total);
printf("Ops Borrado= %d\\n", delete_total);
pthread_mutex_destroy(&head_mutex);
pthread_mutex_destroy(&count_mutex);
free(thread_handles);
return 0;
}
| 1
|
#include <pthread.h>
int numeroDehilos;
double suma=0.0;
long long n=10000000;
void* sumaDepi(void* rank);
int main(int argc, char* argv[])
{
long hilo;
pthread_t* manejadorDehilos;
numeroDehilos=strtol(argv[1], 0, 10);
manejadorDehilos=malloc(numeroDehilos*sizeof(pthread_t));
for(hilo=0;hilo<numeroDehilos;hilo++){
pthread_create(&manejadorDehilos[hilo], 0, sumaDepi, (void*) hilo);
}
for(hilo=0; hilo<numeroDehilos; hilo++){
pthread_join(manejadorDehilos[hilo], 0);
}
double resultado=4*suma;
printf("Suma %lf\\n", resultado);
return 0;
}
void* sumaDepi(void* rank){
long my_rank=(long)rank;
double factor;
long long i;
long long my_n= n/numeroDehilos;
long long mi_primer_elemento=my_n*my_rank;
long long mi_ultimo_elemento=mi_primer_elemento+my_n;
double my_suma=0.0;
pthread_mutex_t mutex;
pthread_mutex_init (&mutex, 0);
if (mi_primer_elemento%2 == 0)
{
factor=1.0;
}
else{
factor=-1.0;
}
for(i=mi_primer_elemento; i<mi_ultimo_elemento;i++, factor=-factor){
my_suma+=factor/(2*i+1);
}
pthread_mutex_lock(&mutex);
suma+=my_suma;
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
sem_t empty;
sem_t full;
pthread_mutex_t mutex;
int buffer[10] = { 0 };
int producer_index = 0;
int consumer_index = 0;
int sum = 0;
int producer_id = 0;
int consumer_id = 0;
void *produce() {
int pid = ++producer_id;
while(1) {
sleep(1);
if(sum == 50){
printf("producer%d terminate.\\n",pid);
return 0;
}
sem_wait(&empty);
pthread_mutex_lock(&mutex);
producer_index = producer_index % 10;
buffer[producer_index] = 1;
printf("producer%d produced an item at buffer[%d].\\n",pid,producer_index);
producer_index++;
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void *consume() {
int cid = ++consumer_id;
while(1) {
sleep(1);
if(sum == 50){
printf("consumer%d terminate.\\n",cid);
return 0;
}
sem_wait(&full);
pthread_mutex_lock(&mutex);
consumer_index = consumer_index % 10;
buffer[consumer_index] = 0;
printf("consumer%d consumed an item at buffer[%d].\\n",cid,consumer_index);
consumer_index++;
sum++;
printf("sum: %d\\n",sum);
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
int main() {
int i;
pthread_t producer[3];
pthread_t consumer[2];
sem_init(&empty,0,10);
sem_init(&full,0,0);
pthread_mutex_init(&mutex,0);
for(i=0;i<3;i++)
pthread_create(&producer[i],0,produce,&i);
for(i=0;i<2;i++)
pthread_create(&consumer[i],0,consume,&i);
for(i=0;i<3;i++)
pthread_join(producer[i],0);
for(i=0;i<2;i++)
pthread_join(consumer[i],0);
printf("terminate\\n");
return 0;
}
| 1
|
#include <pthread.h>
int saldo_inicial;
pthread_mutex_t mutex_compras;
int main(void) {
pthread_t h1, h2;
saldo_inicial = 100;
pthread_mutex_init(&mutex_compras, 0);
pthread_create(&h1, 0, (void*) compras_mensuales, "Julieta");
pthread_create(&h2, 0, (void*) compras_mensuales, "Leo");
pthread_join(h1, (void **) 0);
pthread_join(h2, (void **) 0);
return 0;
}
void compras_mensuales(void* args) {
char* nombre = (char*) args;
for (int i = 0; i < (100 / 10); i++) {
hacer_compras(10, nombre);
if (consulta_saldo() < 0) {
printf("La cuenta esta en rojo!! El almacenero nos va a matar!\\n");
}
}
}
int consulta_saldo() {
return saldo_inicial;
}
void hacer_compras(int monto, const char* nombre) {
pthread_mutex_lock(&mutex_compras);
if (consulta_saldo() >= monto) {
printf("Hay saldo suficiente %s esta por comprar.\\n", nombre);
usleep(1);
comprar(monto);
printf("%s acaba de comprar.\\n", nombre);
} else
printf("No queda suficiente saldo (%d) para que %s haga las compras.\\n",
consulta_saldo(), nombre);
pthread_mutex_unlock(&mutex_compras);
usleep(1);
}
void comprar(int monto) {
saldo_inicial = saldo_inicial - monto;
}
| 0
|
#include <pthread.h>
struct entry {
int key;
int value;
struct entry *next;
};
struct entry *table[5];
int keys[100000];
int nthread = 1;
volatile int done;
pthread_mutex_t mutexes[5];
double
now()
{
struct timeval tv;
gettimeofday(&tv, 0);
return tv.tv_sec + tv.tv_usec / 1000000.0;
}
static void
print(void)
{
int i;
struct entry *e;
for (i = 0; i < 5; i++) {
printf("%d: ", i);
for (e = table[i]; e != 0; e = e->next) {
printf("%d ", e->key);
}
printf("\\n");
}
}
static void
insert(int key, int value, struct entry **p, struct entry *n)
{
struct entry *e = malloc(sizeof(struct entry));
e->key = key;
e->value = value;
e->next = n;
*p = e;
}
static
void put(int key, int value)
{
struct entry *n, **p;
pthread_mutex_lock(&mutexes[key%5]);
for (p = &table[key%5], n = table[key % 5]; n != 0; p = &n->next, n = n->next) {
if (n->key > key) {
insert(key, value, p, n);
goto done;
}
}
insert(key, value, p, n);
done:
pthread_mutex_unlock(&mutexes[key%5]);
return;
}
static struct entry*
get(int key)
{
struct entry *e = 0;
for (e = table[key % 5]; e != 0; e = e->next) {
if (e->key == key) break;
}
return e;
}
static void *
thread(void *xa)
{
long n = (long) xa;
int i;
int b = 100000/nthread;
int k = 0;
double t1, t0;
t0 = now();
for (i = 0; i < b; i++) {
put(keys[b*n + i], n);
}
t1 = now();
printf("%ld: put time = %f\\n", n, t1-t0);
__sync_fetch_and_add(&done, 1);
while (done < nthread) ;
t0 = now();
for (i = 0; i < 100000; i++) {
struct entry *e = get(keys[i]);
if (e == 0) k++;
}
t1 = now();
printf("%ld: lookup time = %f\\n", n, t1-t0);
printf("%ld: %d keys missing\\n", n, k);
}
int
main(int argc, char *argv[])
{
pthread_t *tha;
void *value;
long i;
double t1, t0;
int k;
if (argc < 2) {
fprintf(stderr, "%s: %s nthread\\n", argv[0], argv[0]);
exit(-1);
}
nthread = atoi(argv[1]);
for (k = 0; k < 5; k++) {
pthread_mutex_init(&mutexes[k], 0);
}
tha = malloc(sizeof(pthread_t) * nthread);
srandom(0);
assert(100000 % nthread == 0);
for (i = 0; i < 100000; i++) {
keys[i] = random();
}
t0 = now();
for(i = 0; i < nthread; i++) {
assert(pthread_create(&tha[i], 0, thread, (void *) i) == 0);
}
for(i = 0; i < nthread; i++) {
assert(pthread_join(tha[i], &value) == 0);
}
t1 = now();
printf("completion time = %f\\n", t1-t0);
}
| 1
|
#include <pthread.h>
struct tmq *
tmq_create ()
{
struct tmq *tmq;
if ((tmq = malloc (sizeof (*tmq))) == 0)
return 0;
tmq->size = 0;
tmq->head = 0;
tmq->tail = 0;
pthread_mutex_init (&tmq->lock, 0);
tmq->state = QUEUE_STOPPED;
return tmq;
}
int
tmq_start (struct tmq *tmq)
{
if (tmq == 0)
return -1;
if (tmq->state != QUEUE_STOPPED)
return -1;
if (pthread_create (&tmq->thread, 0, tmq_thread, (void *)tmq))
return -1;
tmq->state = QUEUE_STARTED;
return 0;
}
int
tmq_stop (struct tmq *tmq)
{
if (tmq == 0)
return -1;
if (tmq->state != QUEUE_STARTED)
return -1;
tmq->state = QUEUE_STOPPED;
if (pthread_cancel (tmq->thread))
return -1;
return 0;
}
struct tmq_element *
tmq_element_create (const void *p_key, unsigned int i_key_size)
{
struct tmq_element *elem;
if (p_key == 0 || i_key_size == 0)
return 0;
if ((elem = malloc (sizeof (*elem))) == 0)
return 0;
if ((elem->key = malloc (i_key_size)) == 0)
{
free (elem);
return 0;
}
memcpy (elem->key, p_key, i_key_size);
elem->prev = 0;
elem->next = 0;
gettimeofday (&elem->time, 0);
return elem;
}
int
tmq_destroy (struct tmq *tmq)
{
if (tmq == 0)
return -1;
if (tmq->state == QUEUE_STARTED)
return -1;
while (tmq->size > 0)
tmq_delete (tmq, tmq->head);
free (tmq);
tmq = 0;
return 0;
}
int
tmq_pop (struct tmq *tmq, struct tmq_element *elem)
{
if (tmq == 0 || tmq->size == 0 || elem == 0)
return -1;
pthread_mutex_lock (&tmq->lock);
if (elem == tmq->head)
{
tmq->head = elem->next;
if (tmq->head == 0)
tmq->tail = 0;
else
tmq->head->prev = 0;
}
else
{
elem->prev->next = elem->next;
if (elem->next == 0)
tmq->tail = elem->prev;
else
elem->next->prev = elem->prev;
}
elem->prev = 0;
elem->next = 0;
tmq->size--;
pthread_mutex_unlock (&tmq->lock);
return 0;
}
int
tmq_delete (struct tmq *tmq, struct tmq_element *elem)
{
if (tmq == 0 || elem == 0 || elem->key == 0)
return -1;
if (tmq_pop (tmq, elem))
return -1;
free (elem->key);
free (elem);
return 0;
}
int
tmq_insert (struct tmq *tmq, struct tmq_element *elem)
{
if (tmq == 0 || elem == 0)
return -1;
pthread_mutex_lock (&tmq->lock);
if (tmq->size == 0)
{
tmq->head = elem;
tmq->tail = elem;
tmq->head->prev = 0;
tmq->head->next = 0;
}
else
{
elem->next = tmq->head;
elem->prev = 0;
tmq->head->prev = elem;
tmq->head = elem;
}
tmq->size++;
gettimeofday (&elem->time, 0);
pthread_mutex_unlock (&tmq->lock);
return 0;
}
int
tmq_bump (struct tmq *tmq, struct tmq_element *elem)
{
if (tmq == 0 || elem == 0)
return -1;
if (tmq_pop (tmq, elem))
return -1;
tmq_insert (tmq, elem);
return 0;
}
struct tmq_element *
tmq_find (struct tmq *tmq, const void *p_key)
{
struct tmq_element *it;
if (tmq == 0 || p_key == 0)
return 0;
for (it = tmq->head; it; it = it->next)
if (tmq->compare (p_key, it->key) == 0)
return it;
return 0;
}
int
tmq_timeout (struct tmq *tmq)
{
struct tmq_element *it;
struct timeval timeout;
int removed = 0;
if (tmq == 0)
return -1;
gettimeofday (&timeout, 0);
timeout.tv_sec -= TIMEOUT;
for (it = tmq->tail; it; it = tmq->tail)
{
if (it->time.tv_sec > timeout.tv_sec)
break;
if (tmq->task != 0)
tmq->task (it->key);
tmq_delete (tmq, it);
removed++;
}
return removed;
}
void *
tmq_thread (void *args)
{
struct tmq *tmq = (struct tmq *)args;
struct timespec timeout;
timeout.tv_sec = TIMEOUT_INTERVAL;
timeout.tv_nsec = 0;
pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, 0);
pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED, 0);
while (1)
{
nanosleep(&timeout, 0);
tmq_timeout (tmq);
}
return (void *)0;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.