text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
{
unsigned int addr;
unsigned int size;
unsigned int caller;
struct memstat *next;
} memstat_t;
memstat_t mem_list[1000 +2];
void *(*old_malloc_hook)(size_t);
void (*old_free_hook)(void *);
memstat_t *listhead_free = &mem_list[0];
memstat_t *listhead_mem = &mem_list[1000 +1];
pthread_mutex_t hook_locker = PTHREAD_MUTEX_INITIALIZER;
void dump_malloc();
static memstat_t *remove_from_list(memstat_t *head, unsigned int addr)
{
memstat_t *p1 = head;
memstat_t *p2 = p1->next;
while (p2 != 0)
{
if (p2->addr == addr)
break;
p1 = p2;
p2 = p2->next;
}
if (p2 != 0)
{
p1->next = p2->next;
}
return p2;
}
static void add_to_list(memstat_t *head, memstat_t *p)
{
p->next = head->next;
head->next = p;
}
static void print_list(memstat_t *head)
{
memstat_t *p = head;
int i = 0;
while (p->next != 0)
{
printf("No.%d\\taddr=0x%x\\tsize=%d\\tcaller=0x%x\\n", i++, p->next->addr, p->next->size, p->next->caller);
p = p->next;
}
printf("\\n");
}
void dump_malloc()
{
if (pthread_mutex_lock(&hook_locker))
return;
print_list(listhead_mem);
pthread_mutex_unlock(&hook_locker);
}
static void my_init_hook (void);
static void *my_malloc_hook (size_t, const void *);
static void my_free_hook (void*, const void *);
void (*__malloc_initialize_hook) (void) = my_init_hook;
static void my_init_hook (void)
{
int i;
old_malloc_hook = __malloc_hook;
old_free_hook = __free_hook;
__malloc_hook = my_malloc_hook;
__free_hook = my_free_hook;
listhead_free = &mem_list[0];
for (i = 0; i < 1000; i++)
{
mem_list[i].addr = 0;
mem_list[i].size = 0;
mem_list[i].caller = 0;
mem_list[i].next = &mem_list[i+1];
}
mem_list[1000].addr = 0;
mem_list[1000].size = 0;
mem_list[1000].caller = 0;
mem_list[1000].next = 0;
listhead_mem = &mem_list[1000 +1];
listhead_mem->addr = 0;
listhead_mem->size = 0;
listhead_mem->caller = 0;
listhead_mem->next = 0;
}
static void *my_malloc_hook (size_t size, const void *caller)
{
void *result;
memstat_t *p;
if (pthread_mutex_lock(&hook_locker))
return 0;
__malloc_hook = old_malloc_hook;
__free_hook = old_free_hook;
result = malloc (size);
old_malloc_hook = __malloc_hook;
old_free_hook = __free_hook;
p = remove_from_list(listhead_free, 0);
if (p == 0)
{
pthread_mutex_unlock(&hook_locker);
return 0;
}
p->addr = (unsigned int)result;
p->size = size;
p->caller = (unsigned int)caller;
p->next = 0;
add_to_list(listhead_mem, p);
__malloc_hook = my_malloc_hook;
__free_hook = my_free_hook;
pthread_mutex_unlock(&hook_locker);
return result;
}
static void my_free_hook (void *ptr, const void *caller)
{
memstat_t *p;
if (pthread_mutex_lock(&hook_locker))
return;
__malloc_hook = old_malloc_hook;
__free_hook = old_free_hook;
free (ptr);
old_malloc_hook = __malloc_hook;
old_free_hook = __free_hook;
__malloc_hook = my_malloc_hook;
__free_hook = my_free_hook;
p = remove_from_list(listhead_mem, (unsigned int)ptr);
if (p == 0)
{
pthread_mutex_unlock(&hook_locker);
return;
}
p->addr = 0;
p->size = 0;
p->caller = 0;
p->next = 0;
add_to_list(listhead_free, p);
__malloc_hook = my_malloc_hook;
__free_hook = my_free_hook;
pthread_mutex_unlock(&hook_locker);
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
unsigned int __VERIFIER_nondet_uint();
static int top = 0;
static unsigned int arr[400];
pthread_mutex_t m;
_Bool flag = 0;
void error(void)
{
ERROR:
__VERIFIER_error();
return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
top == 0 ? 1 : 0;
}
int push(unsigned int *stack, int x)
{
if (top == 400)
{
printf("stack overflow\\n");
return -1;
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (top == 0)
{
printf("stack underflow\\n");
return -2;
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for (i = 0; i < 400; i++)
{
__CPROVER_assume(((400 - i) >= 0) && (i >= 0));
{
__CPROVER_assume(((400 - i) >= 0) && (i >= 0));
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint() % 400;
if (push(arr, tmp) == (-1))
error();
pthread_mutex_unlock(&m);
}
}
}
}
void *t2(void *arg)
{
int i;
for (i = 0; i < 400; i++)
{
__CPROVER_assume(((400 - 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;
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_mutex_t cond_mutex;
pthread_cond_t cond;
void handler(int sig) { printf("SIGINT %d\\n", sig); (void) sig; }
void* thread_main(void* n) {
if(n != 0) {
pthread_t t;
pthread_create(&t, 0, thread_main, (void*) ((uintptr_t) n - 1));
pthread_mutex_lock(&cond_mutex);
pthread_cond_wait(&cond, &cond_mutex);
pthread_mutex_unlock(&cond_mutex);
pthread_join(t, 0);
} else {
pthread_mutex_unlock(&lock);
pthread_cond_wait(&cond, &cond_mutex);
}
pthread_exit(0);
}
int main(int argc, char* argv[]) {
if(argc != 2) {
printf("usage: %s NB_THREADS\\n", argv[0]);
return 1;
}
uintptr_t NB_THREADS = atoi(argv[1]);
sigset_t set;
sigfillset(&set);
sigprocmask(SIG_BLOCK, &set, 0);
pthread_cond_init(&cond, 0);
pthread_mutex_init(&lock, 0);
pthread_mutex_init(&cond_mutex, 0);
pthread_mutex_lock(&lock);
pthread_t t;
pthread_create(&t, 0, thread_main, (void*) NB_THREADS);
pthread_mutex_lock(&lock);
printf("Tous mes descendants sont créés\\n");
struct sigaction act;
act.sa_handler = handler;
act.sa_mask = set;
sigaction(SIGINT, &act, 0);
sigdelset(&set, SIGINT);
sigsuspend(&set);
pthread_cond_broadcast(&cond);
pthread_join(t, 0);
printf("Tous mes descendants se sont terminés.\\n");
return 0;
}
| 1
|
#include <pthread.h>
pthread_t idThdAfficheurs[20];
int tour = 0;
pthread_mutex_t affMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t tourMutex = PTHREAD_MUTEX_INITIALIZER;
void thdErreur(int codeErr, char *msgErr, void *codeArret) {
fprintf(stderr, "%s: %d soit %s \\n", msgErr, codeErr, strerror(codeErr));
pthread_exit(codeArret);
}
void *thd_afficher (void *arg) {
int i, j, nbLignes;
int *nbFois = (int *)arg;
pthread_mutex_lock(&affMutex);
pthread_mutex_lock(&tourMutex);
if(pthread_self() == idThdAfficheurs[tour]){
for (i = 0; i < *nbFois; i++) {
nbLignes = rand()% (*nbFois);
for (j = 0; j < nbLignes; j++) {
printf("Thread %lu, j'affiche %d-%d \\n", pthread_self(), i, j);
usleep(250000);
}
}
}
tour++;
pthread_mutex_unlock(&tourMutex);
pthread_mutex_unlock(&affMutex);
pthread_exit((void *)0);
}
int main(int argc, char*argv[]) {
int nbAffichages[20];
int i, etat, nbThreads;
pthread_mutex_init(&affMutex, 0);
pthread_mutex_init(&tourMutex, 0);
if (argc != 2) {
printf("Usage : %s <Nb de threads>\\n", argv[0]);
exit(1);
}
nbThreads = atoi(argv[1]);
if (nbThreads > 20)
nbThreads = 20;
for (i = 0; i < nbThreads; i++) {
nbAffichages[i] = 10;
if ((etat = pthread_create(&idThdAfficheurs[i], 0,
thd_afficher, &nbAffichages[i])) != 0)
thdErreur(etat, "Creation afficheurs", 0);
}
for (i = 0; i < nbThreads; i++)
if ((etat = pthread_join(idThdAfficheurs[i], 0)) != 0)
thdErreur(etat, "Join threads afficheurs", 0);
printf ("\\nFin de l'execution du thread principal \\n");
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_mutex_t lock2;
pthread_mutex_t lock3;
int value;
int value2;
int value3;
sem_t sem;
void *functionWithCriticalSection(int* v2) {
pthread_mutex_lock(&(lock));
value = value + *v2;
pthread_mutex_unlock(&(lock));
sem_post(&sem);
}
void *functionWithOtherCriticalSection(int* v2) {
pthread_mutex_lock(&(lock2));
value2 = value2 + *v2;
pthread_mutex_unlock(&(lock2));
sem_post(&sem);
}
void *functionWithAnotherCriticalSection(int* v2) {
pthread_mutex_lock(&(lock3));
value3 = value3 + *v2;
pthread_mutex_unlock(&(lock3));
sem_post(&sem);
}
void *functionWithMultilockCriticalSection(int* v2) {
pthread_mutex_lock(&(lock));
pthread_mutex_lock(&(lock2));
pthread_mutex_lock(&(lock3));
value = value2 + *v2;
pthread_mutex_unlock(&(lock));
pthread_mutex_unlock(&(lock2));
pthread_mutex_unlock(&(lock3));
sem_post(&sem);
}
void *functionWithReadingCriticalSection(int* v2) {
pthread_mutex_lock(&(lock));
printf("%d\\n", value);
pthread_mutex_unlock(&(lock));
sem_post(&sem);
}
void *functionWithOtherReadingCriticalSection(int* v2) {
pthread_mutex_lock(&(lock3));
printf("%d\\n", value3);
pthread_mutex_unlock(&(lock3));
sem_post(&sem);
}
int main() {
sem_init(&sem, 0, 0);
value = 0;
value2 = 0;
int v2 = 1;
pthread_mutex_init((&(lock)), 0);
pthread_mutex_init((&(lock2)), 0);
pthread_t thread1;
pthread_t thread2;
pthread_t thread3;
pthread_create (&thread1,0,functionWithCriticalSection,&v2);
pthread_create (&thread2,0,functionWithOtherCriticalSection,&v2);
pthread_create (&thread2,0,functionWithAnotherCriticalSection,&v2);
sem_wait(&sem);
sem_wait(&sem);
sem_wait(&sem);
pthread_create (&thread1,0,functionWithMultilockCriticalSection,&v2);
pthread_create (&thread2,0,functionWithReadingCriticalSection,&v2);
pthread_create (&thread3,0,functionWithOtherReadingCriticalSection,&v2);
sem_wait(&sem);
sem_wait(&sem);
sem_wait(&sem);
pthread_mutex_destroy(&(lock));
pthread_mutex_destroy(&(lock2));
pthread_mutex_destroy(&(lock3));
sem_destroy(&sem);
printf("%d\\n", value);
printf("%d\\n", value2);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t monitor_protect;
pthread_cond_t self[7];
enum {THINKING,HUNGRY,EATING} state[7];
char *state_string[] = {"thinking", "hungry ", "eating "};
void random_spin(int max);
pthread_mutex_t random_protect, stderr_protect;
void test(int k)
{
if (state[(k+(7 - 1))%7] != EATING &&
state[k] == HUNGRY &&
state[(k+1)%7] != EATING) {
state[k] = EATING;
pthread_cond_signal(&self[k]);
}
}
void pickup(int i)
{
pthread_mutex_lock(&monitor_protect);
random_spin(1000);
state[i] = HUNGRY;
test(i);
while (state[i] != EATING)
pthread_cond_wait(&self[i], &monitor_protect);
pthread_mutex_unlock(&monitor_protect);
}
void putdown(int i)
{
pthread_mutex_lock(&monitor_protect);
random_spin(1000);
state[i] = THINKING;
test((i+(7 - 1)) %7);
test((i+1) %7);
pthread_mutex_unlock(&monitor_protect);
}
void cycle_soaker(void ) {}
void random_spin(int max)
{
int spin_time;
int i;
max = max * 100;
pthread_mutex_lock(&random_protect);
spin_time = rand() % max;
pthread_mutex_unlock(&random_protect);
for(i=0; i<spin_time; i++)
cycle_soaker();
}
void validate_state(int i)
{
pthread_mutex_lock(&monitor_protect);
if (state[i] != EATING ||
state[(i+1)%7] == EATING ||
state[(i+(7 - 1))%7] == EATING) {
pthread_mutex_lock(&stderr_protect);
printf("Invalid state detect by philosopher %d\\n", i );
pthread_mutex_unlock(&stderr_protect);
abort();
}
pthread_mutex_unlock(&monitor_protect);
}
void *
philosopher(void *arg)
{
int i = (int) arg;
int j;
oskit_pthread_sleep(((long long)1000));
for(j=0;j<150;j++) {
pickup(i);
validate_state(i);
if ((j % 10) == 0) {
int k;
pthread_mutex_lock(&stderr_protect);
printf("p:%d(%d) j:%d ", i, oskit_pthread_whichcpu(), j);
for (k = 0; k < 7; k++) {
printf("%s ", state_string[state[k]]);
}
printf("\\n");
pthread_mutex_unlock(&stderr_protect);
}
oskit_pthread_sleep(((long long)100));
putdown(i);
random_spin(500);
}
return 0;
}
int
main()
{
int i;
void *stat;
pthread_t foo[7];
pthread_mutexattr_t mutexattr;
oskit_clientos_init_pthreads();
start_clock();
start_pthreads();
srand(1);
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_setprotocol(&mutexattr, 1);
pthread_mutex_init(&monitor_protect, &mutexattr);
for(i=0; i<7; i++) {
state[i] = THINKING;
pthread_cond_init(&self[i], 0);
}
for(i=0; i<7; i++) {
pthread_create(&foo[i], 0, philosopher, (void *) i);
if ((unsigned) i & 1)
oskit_pthread_setprio(foo[i], PRIORITY_NORMAL + 1);
}
for(i=0; i<7; i++) {
pthread_join(foo[i], &stat);
}
oskit_pthread_sleep(((long long)100));
printf("exiting ...\\n");
exit(0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t g_fastmutex = PTHREAD_MUTEX_INITIALIZER;
static void init(void)
{
int s;
if (!g_mem.init)
{
s = getpagesize() * 13;
g_mem.min = ft_stdmem(0, s);
s = 128 * s;
g_mem.med = ft_stdmem(0, s);
g_mem.init = 1;
}
}
void *malloc(size_t size)
{
void *ptr;
init();
pthread_mutex_lock(&g_fastmutex);
ptr = ft_malloc(size);
pthread_mutex_unlock(&g_fastmutex);
return (ptr);
}
void free(void *ptr)
{
init();
pthread_mutex_lock(&g_fastmutex);
ft_free(ptr);
pthread_mutex_unlock(&g_fastmutex);
}
void *realloc(void *ptr, size_t size)
{
init();
if (!(ptr && size))
{
if (!ptr)
return (malloc(size));
free(ptr);
return (0);
}
pthread_mutex_lock(&g_fastmutex);
ptr = ft_realloc(ptr, size);
pthread_mutex_unlock(&g_fastmutex);
return (ptr);
}
void *calloc(size_t nmemb, size_t size)
{
char *ptr;
int total_size;
int i;
init();
total_size = nmemb * size;
if (!(ptr = malloc(total_size)))
return (0);
i = -1;
while (++i < total_size)
ptr[i] = 0;
return ((void *)ptr);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int buffer[100];
int duration = 20;
int length = 0;
void *producer(void *arg)
{
char *str;
str=(char*)arg;
for(int i = 0; i < duration; i++) {
pthread_mutex_lock (&mutex);
buffer[length] = i;
length++;
printf("Producer %s length %d\\n",str, length);
pthread_cond_signal(&cond);
pthread_mutex_unlock (&mutex);
usleep(1);
}
return 0;
}
void *consumer(void *arg)
{
char *str;
str=(char*)arg;
for(int i = 0; i < duration; i++) {
pthread_mutex_lock (&mutex);
while(length == 0) {
pthread_cond_wait(&cond, &mutex);
}
length--;
int temp = buffer[length];
printf("Consumer %s value %d\\n",str, temp);
pthread_mutex_unlock (&mutex);
usleep(2);
}
return 0;
}
int main(int argc, char *argv[]) {
pthread_t producer_thread;
pthread_t producer_thread2;
pthread_t consumer_thread;
pthread_t consumer_thread2;
pthread_mutex_init(&mutex, 0);
pthread_create(&producer_thread, 0, producer, (void *) "1");
pthread_create(&producer_thread2, 0, producer, (void *) "2");
pthread_create(&consumer_thread, 0, consumer, (void *) "1");
pthread_create(&consumer_thread2, 0, consumer, (void *) "2");
pthread_join(producer_thread, 0);
pthread_join(producer_thread2, 0);
pthread_join(consumer_thread, 0);
pthread_join(consumer_thread2, 0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo {
int f_count;
pthread_mutex_t f_lock;
struct foo *f_next;
int f_id;
};
struct foo* foo_alloc(void)
{
struct foo *fp;
int idx;
if ((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 1;
if (pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
fp = 0;
return 0;
}
idx = (((unsigned long)fp) % 29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
}
return fp;
}
void foo_hold(struct foo *fp)
{
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
struct foo *foo_find(int id)
{
struct foo *fp;
int idx;
idx = (((unsigned long)fp) % 29);
pthread_mutex_lock(&hashlock);
for (fp = fh[idx]; fp != 0; fp = fp->f_next) {
if (id == fp->f_id) {
foo_hold(fp);
break;
}
}
pthread_mutex_unlock(&hashlock);
return fp;
}
void foo_rele(struct foo *fp)
{
struct foo *tfp;
int idx;
pthread_mutex_lock(&fp->f_lock);
if (1 == fp->f_count) {
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_lock(&hashlock);
pthread_mutex_lock(&fp->f_lock);
if (fp->f_count != 1) {
--fp->f_count;
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
return;
}
idx = (((unsigned long)fp) % 29);
tfp = fh[idx];
if (tfp == fp) {
fh[idx] = fp->f_next;
}
else {
while (tfp->f_next != fp) {
tfp = tfp->f_next;
}
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
fp = 0;
}
else {
--fp->f_count;
pthread_mutex_unlock(&fp->f_lock);
}
}
| 1
|
#include <pthread.h>
struct thrd_data{
int id;
int start;
int end;
};
int count = 0;
pthread_mutex_t count_mtx;
void *do_work(void *thrd_arg)
{
struct thrd_data *t_data;
int i,j,min, max;
int myid;
int mycount = 0;
int *primes;
int c;
int z = 1;
primes = malloc(sizeof(int)*max);
for (c=0; c<max; c++)
{
primes[c]=1;
printf("%d",primes[c]);
}
t_data = (struct thrd_data *) thrd_arg;
myid = t_data->id;
min = t_data->start;
max = t_data->end;
printf ("Thread %d finding prime from %d to %d\\n", myid,min,max-1);
if (myid==0)
{
for (i=2;i<max;i++)
{
if(primes[i])
{
for (j=i;i*j<max;j++)
{
primes[i*j]=0;
printf("%d is not prime\\n",primes[i*j]);
mycount = mycount + 1;
}
}
}
pthread_mutex_lock (&count_mtx);
count = count + mycount;
pthread_mutex_unlock (&count_mtx);
pthread_exit(0);
}
else
{
for (i=min;i<max;i++)
{
if(primes[i])
{
for (j=i;i*j<max;j++)
{
primes[i*j]=0;
printf("%d is not prime\\n",primes[i*j]);
mycount = mycount + 1;
}
}
}
pthread_mutex_lock (&count_mtx);
count = count + mycount;
pthread_mutex_unlock (&count_mtx);
pthread_exit(0);
}
}
int main(int argc, char *argv[])
{
int i, n, n_threads;
int k, nq, nr;
struct thrd_data *t_arg;
pthread_t *thread_id;
pthread_attr_t attr;
pthread_mutex_init(&count_mtx, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
printf ("enter the range n = ");
scanf ("%d", &n);
printf ("enter the number of threads n_threads = ");
scanf ("%d", &n_threads);
thread_id = (pthread_t *)malloc(sizeof(pthread_t)*n_threads);
t_arg = (struct thrd_data *)malloc(sizeof(struct thrd_data)*n_threads);
nq = n / n_threads;
nr = n % n_threads;
k = 1;
for (i=0; i<n_threads; i++){
t_arg[i].id = i;
t_arg[i].start = k;
if (i < nr)
k = k + nq + 1;
else
k = k + nq;
t_arg[i].end = k;
pthread_create(&thread_id[i], &attr, do_work, (void *) &t_arg[i]);
}
for (i=0; i<n_threads; i++) {
pthread_join(thread_id[i], 0);
}
printf ("Done. Count= %d \\n", n-count);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mtx);
pthread_exit (0);
}
| 0
|
#include <pthread.h>
int array[4];
int array_index = 0;
pthread_mutex_t mutex;
void *thread(void * arg)
{
pthread_mutex_lock(&mutex);
array[array_index] = 1;
pthread_mutex_unlock(&mutex);
return 0;
}
int main()
{
int i, sum;
pthread_t t[4];
pthread_mutex_init(&mutex, 0);
i = 0;
pthread_create(&t[i], 0, thread, 0);
pthread_mutex_lock(&mutex); array_index++; pthread_mutex_unlock(&mutex); i++;
pthread_create(&t[i], 0, thread, 0);
pthread_mutex_lock(&mutex); array_index++; pthread_mutex_unlock(&mutex); i++;
pthread_create(&t[i], 0, thread, 0);
pthread_mutex_lock(&mutex); array_index++; pthread_mutex_unlock(&mutex); i++;
pthread_create(&t[i], 0, thread, 0);
pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); i++;
__VERIFIER_assert (i == 4);
__VERIFIER_assert (array_index < 4);
i = 0;
pthread_join (t[i], 0); i++;
pthread_join (t[i], 0); i++;
pthread_join (t[i], 0); i++;
pthread_join (t[i], 0); i++;
__VERIFIER_assert (i == 4);
sum = 0;
i = 0;
sum += array[i]; i++;
sum += array[i]; i++;
sum += array[i]; i++;
sum += array[i]; i++;
__VERIFIER_assert (i == 4);
printf ("m: sum %d SIGMA %d\\n", sum, 4);
__VERIFIER_assert (sum <= 4);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
int shared_data;
void *thread_function(void *arg)
{
pthread_mutex_lock(&lock);
printf("I'm in the thread function.\\n");
sleep(10);
pthread_mutex_unlock(&lock);
return 0;
}
int main(void)
{
pthread_attr_t attributes;
pthread_t threadID;
void *result;
int rc;
pthread_mutex_init(&lock, 0);
pthread_attr_init(&attributes);
rc = pthread_attr_setinheritsched(&attributes, PTHREAD_EXPLICIT_SCHED);
if (rc != 0) printf("pthread_attr_setinheritsched() failed!\\n");
rc = pthread_attr_setschedpolicy(&attributes, SCHED_FIFO);
if (rc != 0) printf("pthread_attr_setschedpolicy() failed!\\n");
rc = pthread_attr_setscope(&attributes, PTHREAD_SCOPE_PROCESS);
if (rc != 0) printf("pthread_attr_setscope() failed!\\n");
rc = pthread_create(&threadID, &attributes, thread_function, 0);
if (rc != 0) {
printf("pthread_create() failed!\\n");
switch (rc) {
case EAGAIN:
printf("Insufficient resources or resource limit reached.\\n");
break;
case EINVAL:
printf("Invalid thread attributes.\\n");
break;
case ENOMEM:
printf("Insufficient memory.\\n");
break;
case EPERM:
printf("Insufficient permission to create thread with specified attributes.\\n");
break;
}
return 1;
}
printf("Subordinate thread created. Waiting...\\n");
pthread_join(threadID, &result);
printf("Thread ended.\\n");
pthread_mutex_destroy(&lock);
return 0;
}
| 0
|
#include <pthread.h>
int ncount;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *pthread_funct(void *data) {
time_t timer;
int number;
number = *((int *)data);
char buffer[26];
struct tm* tm_info;
srand(time(0));
int r = rand()%10;
while(ncount < number) {
pthread_mutex_lock(&mutex);
ncount++;
time(&timer);
tm_info = localtime(&timer);
strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
fflush(stdout);
printf("%d %s %d\\n", pthread_self() ,buffer, ncount);
pthread_mutex_unlock(&mutex);
sleep(r);
}
}
int main()
{
printf("2012136121 Jeong ho yeob\\n");
int thr_id;
pthread_t p_thread[10];
int status;
int num = 20;
ncount = 0;
int thr_id1;
int thr_id2;
int thr_id3;
int thr_id4;
int thr_id5;
int thr_id6;
int thr_id7;
int thr_id8;
int thr_id9;
int thr_id10;
thr_id1 = pthread_create(&p_thread[0], 0, pthread_funct, (void *)&num);
if (thr_id1 < 0) {
perror("thread create error : ");
exit(0);
}
thr_id2 = pthread_create(&p_thread[1], 0, pthread_funct, (void *)&num);
if (thr_id2 < 0) {
perror("thread create error : ");
exit(0);
}
thr_id3 = pthread_create(&p_thread[2], 0, pthread_funct, (void *)&num);
if (thr_id3 < 0) {
perror("thread create error : ");
exit(0);
}
thr_id4 = pthread_create(&p_thread[3], 0, pthread_funct, (void *)&num);
if (thr_id4 < 0) {
perror("thread create error : ");
exit(0);
}
thr_id5 = pthread_create(&p_thread[4], 0, pthread_funct, (void *)&num);
if (thr_id5 < 0) {
perror("thread create error : ");
exit(0);
}
thr_id6 = pthread_create(&p_thread[5], 0, pthread_funct, (void *)&num);
if (thr_id6 < 0) {
perror("thread create error : ");
exit(0);
}
thr_id7 = pthread_create(&p_thread[6], 0, pthread_funct, (void *)&num);
if (thr_id7 < 0) {
perror("thread create error : ");
exit(0);
}
thr_id8 = pthread_create(&p_thread[7], 0, pthread_funct, (void *)&num);
if (thr_id8 < 0) {
perror("thread create error : ");
exit(0);
}
thr_id9 = pthread_create(&p_thread[8], 0, pthread_funct, (void *)&num);
if (thr_id9 < 0) {
perror("thread create error : ");
exit(0);
}
thr_id10 = pthread_create(&p_thread[9], 0, pthread_funct, (void *)&num);
if (thr_id10 < 0) {
perror("thread create error : ");
exit(0);
}
pthread_join(p_thread[0], (void *) &status);
pthread_join(p_thread[1], (void *) &status);
pthread_join(p_thread[2], (void *) &status);
pthread_join(p_thread[3], (void *) &status);
pthread_join(p_thread[4], (void *) &status);
pthread_join(p_thread[5], (void *) &status);
pthread_join(p_thread[6], (void *) &status);
pthread_join(p_thread[7], (void *) &status);
pthread_join(p_thread[8], (void *) &status);
pthread_join(p_thread[9], (void *) &status);
printf("finished\\n");
status = pthread_mutex_destroy(&mutex);
printf("code = %d", status);
return 0;
}
| 1
|
#include <pthread.h>
void create_threads(int records_num);
void *start_thread(void *records_num) ;
int find_text(char *text);
int read_data(int records_num) ;
void destructor(void *data) ;
int read_records(char **data) ;
int id;
char text[RECORD_SIZE - sizeof(int)];
} record_str;
pthread_t **threads;
pthread_key_t record_buffer_data_key;
int threads_num;
int records_num;
int fd;
char *text_key;
pthread_mutex_t file_mutex = PTHREAD_MUTEX_INITIALIZER;
int main(int argc, char *argv[]) {
threads_num = parseUnsignedIntArg(argc, argv, 1, "number of threads");
char *filename = parseTextArg(argc, argv, 2, "file name");
records_num = parseUnsignedIntArg(argc, argv, 3, "number of records");
text_key = parseTextArg(argc, argv, 4, "text key to find");
fd = open_file(filename);
pthread_key_create(&record_buffer_data_key, destructor);
create_threads(records_num);
pthread_exit(0);
}
void destructor(void *data) {
char **records = (char **) data;
for (int i = 0; i < records_num && records[i] != 0; ++i) {
free(records[i]);
}
free(data);
}
void create_threads(int records_num) {
threads = calloc((size_t) threads_num, sizeof(*threads));
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
for (int i = 0; i < threads_num; ++i) {
pthread_t *thread = malloc(sizeof(*thread));
int *records = calloc(1, sizeof(*records));
*records = records_num;
int error_num;
if ((error_num = pthread_create(thread, &attr, start_thread, records)) != 0) {
fprintf(stderr, "Error creating thread: %s\\n", strerror(error_num));
exit(1);
}
threads[i] = thread;
}
pthread_attr_destroy(&attr);
}
void *start_thread(void *records_num) {
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0);
int read_records;
while ((read_records = read_data(*(int *) records_num)) != 0) {
char **data = pthread_getspecific(record_buffer_data_key);
for (int i = 0; i < read_records; ++i) {
record_str *record = (record_str *) data[i];
if (find_text(record->text) == 1) {
printf("Key found in record %d by thread with id %ld\\n", record->id, get_thread_id());
}
}
}
return (void *) 0;
}
int read_data(int records_num) {
char **data = pthread_getspecific(record_buffer_data_key);
if (data == 0) {
data = calloc((size_t) records_num, sizeof(*data));
pthread_setspecific(record_buffer_data_key, data);
}
pthread_mutex_lock(&file_mutex);
int records = read_records(data);
pthread_mutex_unlock(&file_mutex);
return records;
}
int read_records(char **data) {
ssize_t read_result;
int record_num = 0;
for (record_num = 0; record_num < records_num; ++record_num) {
data[record_num] = calloc(RECORD_SIZE, sizeof(*data[record_num]));
if ((read_result = read(fd, data[record_num], RECORD_SIZE * sizeof(*data[record_num]))) == -1) {
fprintf(stderr, "Error while reading from file in thread %ld\\n", get_thread_id());
pthread_mutex_unlock(&file_mutex);
pthread_exit((void *) 1);
}
if (read_result == 0) {
break;
}
}
return record_num;
}
int find_text(char *text) {
size_t key_len = strlen(text_key);
int record_len = RECORD_SIZE - sizeof(int);
int key_index;
for (int i = 0; i < record_len; ++i) {
for (key_index = 0; key_index < key_len && i + key_index < record_len; ++key_index) {
if (text[i + key_index] != text_key[key_index]) {
break;
}
}
if (key_index == key_len) {
return 1;
}
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t chopstick[6] ;
void *eat_think(void *arg)
{
char phi = *(char *)arg;
int left,right;
switch (phi){
case 'A':
left = 5;
right = 1;
break;
case 'B':
left = 1;
right = 2;
break;
case 'C':
left = 2;
right = 3;
break;
case 'D':
left = 3;
right = 4;
break;
case 'E':
left = 4;
right = 5;
break;
}
int i;
for(;;){
usleep(3000);
pthread_mutex_lock(&chopstick[left]);
printf("Philosopher %c fetches chopstick %d\\n", phi, left);
if (pthread_mutex_trylock(&chopstick[right]) == EBUSY){
pthread_mutex_unlock(&chopstick[left]);
continue;
}
printf("Philosopher %c fetches chopstick %d\\n", phi, right);
printf("Philosopher %c is eating.\\n",phi);
usleep(3000);
pthread_mutex_unlock(&chopstick[left]);
printf("Philosopher %c release chopstick %d\\n", phi, left);
pthread_mutex_unlock(&chopstick[right]);
printf("Philosopher %c release chopstick %d\\n", phi, right);
}
}
int main(){
pthread_t A,B,C,D,E;
int i;
for (i = 0; i < 5; i++)
pthread_mutex_init(&chopstick[i],0);
pthread_create(&A,0, eat_think, "A");
pthread_create(&B,0, eat_think, "B");
pthread_create(&C,0, eat_think, "C");
pthread_create(&D,0, eat_think, "D");
pthread_create(&E,0, eat_think, "E");
pthread_join(A,0);
pthread_join(B,0);
pthread_join(C,0);
pthread_join(D,0);
pthread_join(E,0);
return 0;
}
| 1
|
#include <pthread.h>
static struct helper_data {
volatile int exit;
volatile int reset;
volatile int do_stat;
struct sk_out *sk_out;
pthread_t thread;
pthread_mutex_t lock;
pthread_cond_t cond;
struct fio_mutex *startup_mutex;
} *helper_data;
void helper_thread_destroy(void)
{
pthread_cond_destroy(&helper_data->cond);
pthread_mutex_destroy(&helper_data->lock);
sfree(helper_data);
}
void helper_reset(void)
{
if (!helper_data)
return;
pthread_mutex_lock(&helper_data->lock);
if (!helper_data->reset) {
helper_data->reset = 1;
pthread_cond_signal(&helper_data->cond);
}
pthread_mutex_unlock(&helper_data->lock);
}
void helper_do_stat(void)
{
if (!helper_data)
return;
pthread_mutex_lock(&helper_data->lock);
helper_data->do_stat = 1;
pthread_cond_signal(&helper_data->cond);
pthread_mutex_unlock(&helper_data->lock);
}
bool helper_should_exit(void)
{
if (!helper_data)
return 1;
return helper_data->exit;
}
void helper_thread_exit(void)
{
void *ret;
pthread_mutex_lock(&helper_data->lock);
helper_data->exit = 1;
pthread_cond_signal(&helper_data->cond);
pthread_mutex_unlock(&helper_data->lock);
pthread_join(helper_data->thread, &ret);
}
static void *helper_thread_main(void *data)
{
struct helper_data *hd = data;
unsigned int msec_to_next_event, next_log;
struct timeval tv, last_du;
int ret = 0;
sk_out_assign(hd->sk_out);
gettimeofday(&tv, 0);
memcpy(&last_du, &tv, sizeof(tv));
fio_mutex_up(hd->startup_mutex);
msec_to_next_event = DISK_UTIL_MSEC;
while (!ret && !hd->exit) {
struct timespec ts;
struct timeval now;
uint64_t since_du;
timeval_add_msec(&tv, msec_to_next_event);
ts.tv_sec = tv.tv_sec;
ts.tv_nsec = tv.tv_usec * 1000;
pthread_mutex_lock(&hd->lock);
pthread_cond_timedwait(&hd->cond, &hd->lock, &ts);
gettimeofday(&now, 0);
if (hd->reset) {
memcpy(&tv, &now, sizeof(tv));
memcpy(&last_du, &now, sizeof(last_du));
hd->reset = 0;
}
pthread_mutex_unlock(&hd->lock);
since_du = mtime_since(&last_du, &now);
if (since_du >= DISK_UTIL_MSEC || DISK_UTIL_MSEC - since_du < 10) {
ret = update_io_ticks();
timeval_add_msec(&last_du, DISK_UTIL_MSEC);
msec_to_next_event = DISK_UTIL_MSEC;
if (since_du >= DISK_UTIL_MSEC)
msec_to_next_event -= (since_du - DISK_UTIL_MSEC);
} else {
if (since_du >= DISK_UTIL_MSEC)
msec_to_next_event = DISK_UTIL_MSEC - (DISK_UTIL_MSEC - since_du);
else
msec_to_next_event = DISK_UTIL_MSEC;
}
if (hd->do_stat) {
hd->do_stat = 0;
__show_running_run_stats();
}
next_log = calc_log_samples();
if (!next_log)
next_log = DISK_UTIL_MSEC;
msec_to_next_event = min(next_log, msec_to_next_event);
if (!is_backend)
print_thread_status();
}
fio_writeout_logs(0);
sk_out_drop();
return 0;
}
int helper_thread_create(struct fio_mutex *startup_mutex, struct sk_out *sk_out)
{
struct helper_data *hd;
int ret;
hd = smalloc(sizeof(*hd));
setup_disk_util();
hd->sk_out = sk_out;
ret = mutex_cond_init_pshared(&hd->lock, &hd->cond);
if (ret)
return 1;
hd->startup_mutex = startup_mutex;
ret = pthread_create(&hd->thread, 0, helper_thread_main, hd);
if (ret) {
log_err("Can't create helper thread: %s\\n", strerror(ret));
return 1;
}
helper_data = hd;
dprint(FD_MUTEX, "wait on startup_mutex\\n");
fio_mutex_down(startup_mutex);
dprint(FD_MUTEX, "done waiting on startup_mutex\\n");
return 0;
}
| 0
|
#include <pthread.h>
static double getDoubleTime();
void *thread_function(void *arg);
pthread_mutex_t work_mutex;
int main(void) {
int res;
pthread_t a_thread[10];
void *thread_result;
int lots_of_threads;
double start_time = getDoubleTime();
res = pthread_mutex_init(&work_mutex, 0);
if (res != 0) {
perror("Mutex initialization failed");
exit(1);
}
for (lots_of_threads = 0; lots_of_threads < 10; lots_of_threads ++) {
res = pthread_create(&(a_thread[lots_of_threads]), 0, thread_function, (void*)(long)lots_of_threads);
if (res != 0) {
perror("Thread creation failed");
exit(1);
}
}
for (lots_of_threads = 10 - 1; lots_of_threads >= 0; lots_of_threads--) {
res = pthread_join(a_thread[lots_of_threads], &thread_result);
if (res != 0) {
perror("pthread_join failed");
}
}
printf("\\nThread joined\\n");
double finish_time = getDoubleTime();
printf("Execute Time: %.3lf ms\\n", (finish_time - start_time));
exit(0);
}
void *thread_function(void *arg) {
pthread_mutex_lock(&work_mutex);
int my_num = (long)arg;
int start_num = (10000 / 10) * my_num + 1;
int end_num = (10000 / 10) * (my_num + 1);
int i = 0, j = 0;
int count = 0;
int result = 0;
printf("\\n\\nI'm thread[%d], start_num:%d, end_num:%d\\n", my_num, start_num, end_num);
for (i = start_num; i <= end_num; i++) {
count = 0;
for (j = 1; j <= i; j++) {
if (i % j == 0)
count += 1;
}
if (count == 2) {
result = i;
printf("%d-[%d]\\t", result, my_num);
}
}
pthread_mutex_unlock(&work_mutex);
pthread_exit(0);
}
static double getDoubleTime() {
struct timeval tm_tv;
gettimeofday(&tm_tv,0);
return (double)(((double)tm_tv.tv_sec * (double)1000. + (double)(tm_tv.tv_usec)) * (double)0.001);
}
| 1
|
#include <pthread.h>
int numOfPassengersOnBus;
void* print_message(void* ptr);
pthread_mutex_t verrou;
int main(int argc, char* argv[])
{
pthread_t tProducer, tConsumer1, tConsumer2;
const char* msg1 = "Producer";
const char* msg2 = "Consumer A";
numOfPassengersOnBus = 0;
pthread_mutex_init(&verrou, 0);
int r1 = pthread_create(&tProducer, 0, print_message, (void*)msg1 );
int r2 = pthread_create(&tConsumer1, 0, print_message, (void*)msg2 );
pthread_join(tProducer, 0);
pthread_join(tConsumer1, 0);
return 0;
}
void* print_message(void* ptr)
{
srand(time(0));
char* msg = (char*) ptr;
while(1)
{
if(msg[0]=='P')
{
pthread_mutex_lock(&verrou);
while(numOfPassengersOnBus>0) {};
numOfPassengersOnBus++;
printf("%s produced %d\\n", msg, numOfPassengersOnBus);
pthread_mutex_unlock(&verrou);
sleep(rand()%2);
}
else
{
pthread_mutex_lock(&verrou);
while(numOfPassengersOnBus<=0) {};
numOfPassengersOnBus--;
printf("%s consumed %d\\n", msg, numOfPassengersOnBus);
pthread_mutex_unlock(&verrou);
sleep(rand()%4);
}
}
return 0;
}
| 0
|
#include <pthread.h>
static struct quadtree *bitmaps = 0;
static struct quadtree *threadlist = 0;
static struct threadpool *threadpool = 0;
static pthread_mutex_t bitmaps_mutex;
static pthread_mutex_t running_mutex;
static pthread_attr_t attr_detached;
static void
pngloader_on_dequeue (void *data)
{
free(data);
}
int
bitmap_request (struct quadtree_req *req)
{
pthread_mutex_lock(&bitmaps_mutex);
int ret = quadtree_request(bitmaps, req);
pthread_mutex_unlock(&bitmaps_mutex);
return ret;
}
void
bitmap_zoom_change (const int zoomlevel)
{
(void)zoomlevel;
}
static void *
bitmap_procure (struct quadtree_req *req)
{
pthread_mutex_lock(&running_mutex);
quadtree_request(threadlist, req);
pthread_mutex_unlock(&running_mutex);
return 0;
}
static void
bitmap_destroy (void *data)
{
free(data);
}
static void
thread_on_completed (struct pngloader *p, void *rawbits)
{
int stored;
pthread_mutex_lock(&bitmaps_mutex);
stored = quadtree_data_insert(bitmaps, &p->req, rawbits);
pthread_mutex_unlock(&bitmaps_mutex);
if (!stored) bitmap_destroy(rawbits);
pthread_mutex_lock(&running_mutex);
quadtree_data_insert(threadlist, &p->req, 0);
pthread_mutex_unlock(&running_mutex);
framerate_repaint();
}
static void *
thread_procure (struct quadtree_req *req)
{
int job_id;
struct pngloader *p;
if ((p = malloc(sizeof(*p))) == 0) {
return 0;
}
memcpy(&p->req, req, sizeof(*req));
p->on_completed = thread_on_completed;
if ((job_id = threadpool_job_enqueue(threadpool, p)) == 0) {
free(p);
}
return (void *)(ptrdiff_t)job_id;
}
static void
thread_destroy (void *data)
{
threadpool_job_cancel(threadpool, (int)(ptrdiff_t)data);
}
bool
bitmap_mgr_init (void)
{
if ((bitmaps = quadtree_create(1000, &bitmap_procure, &bitmap_destroy)) == 0) {
goto err_0;
}
if ((threadlist = quadtree_create(200, &thread_procure, &thread_destroy)) == 0) {
goto err_1;
}
if ((threadpool = threadpool_create(30, pngloader_on_init, pngloader_on_dequeue, pngloader_main, pngloader_on_cancel, pngloader_on_exit)) == 0) {
goto err_2;
}
pthread_mutex_init(&bitmaps_mutex, 0);
pthread_mutex_init(&running_mutex, 0);
pthread_attr_init(&attr_detached);
pthread_attr_setdetachstate(&attr_detached, PTHREAD_CREATE_DETACHED);
return 1;
err_2: quadtree_destroy(&threadlist);
err_1: quadtree_destroy(&bitmaps);
err_0: return 0;
}
void
bitmap_mgr_destroy (void)
{
threadpool_destroy(&threadpool);
quadtree_destroy(&threadlist);
pthread_mutex_lock(&bitmaps_mutex);
quadtree_destroy(&bitmaps);
pthread_mutex_unlock(&bitmaps_mutex);
pthread_attr_destroy(&attr_detached);
pthread_mutex_destroy(&running_mutex);
pthread_mutex_destroy(&bitmaps_mutex);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
long counter = 0;
struct pthread_args
{
unsigned int chunk_size;
char *buffer;
unsigned int* histogram;
};
void * local_histo (void * ptr)
{
unsigned int i;
struct pthread_args *arg = ptr;
while (arg->buffer[(counter+1)*arg->chunk_size]!=TERMINATOR){
for (i=counter*arg->chunk_size; i<(counter+1)*arg->chunk_size; i++) {
if (arg->buffer[i]==TERMINATOR)
break;
if (arg->buffer[i] >= 'a' && arg->buffer[i] <= 'z')
arg->histogram[arg->buffer[i]-'a']++;
else if(arg->buffer[i] >= 'A' && arg->buffer[i] <= 'Z')
arg->histogram[arg->buffer[i]-'A']++;
}
pthread_mutex_lock(&mutex);
counter++;
pthread_mutex_unlock(&mutex);
}
return 0;
}
void get_histogram(char *buffer,
unsigned int* histogram,
unsigned int num_threads,
unsigned int chunk_size) {
buffer_ptr = buffer;
pthread_t * thread; struct pthread_args * thread_arg;
thread = calloc ( num_threads, sizeof ( * thread ) ) ;
thread_arg = calloc ( num_threads, sizeof ( * thread_arg ) ) ;
if (pthread_mutex_init(&mutex, 0) != 0)
{
printf("\\n mutex init failed\\n");
}
for ( int k = 0; k < num_threads ; k++){
thread_arg[k].chunk_size = chunk_size;
thread_arg[k].histogram = calloc ( NALPHABET, sizeof ( unsigned int) ) ;
pthread_create ( thread + k , 0, &local_histo, thread_arg + k ) ;
}
for ( int k = 0; k < num_threads ; k++){
pthread_join ( thread [ k ] , 0 ) ;
for ( int idx = 0; idx < NALPHABET ; idx++)
histogram[idx] += thread_arg[k].histogram[idx];
free(thread_arg[k].histogram);
}
pthread_mutex_destroy(&mutex);
free(thread);
free(thread_arg);
}
| 0
|
#include <pthread.h>
int count = 0;
int thread_ids[3] = {0,1,2};
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *inc_count(void *t)
{
int i;
long my_id = (long)t;
for (i=0; i<10; i++) {
pthread_mutex_lock(&count_mutex);
count++;
if (count == 12) {
pthread_cond_signal(&count_threshold_cv);
printf("inc_count(): thread %ld, count = %d Threshold reached.\\n",
my_id, count);
}
printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n",
my_id, count);
pthread_mutex_unlock(&count_mutex);
sleep(1);
}
pthread_exit(0);
}
void *watch_count(void *t)
{
long my_id = (long)t;
printf("Starting watch_count(): thread %ld\\n", my_id);
pthread_mutex_lock(&count_mutex);
while (count<12) {
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %ld Condition signal received.\\n", my_id);
count += 125;
printf("watch_count(): thread %ld count now = %d.\\n", my_id, count);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main (int argc, char *argv[])
{
int i, rc;
long t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, watch_count, (void *)t1);
pthread_create(&threads[1], &attr, inc_count, (void *)t2);
pthread_create(&threads[2], &attr, inc_count, (void *)t3);
for (i=0; i<3; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited on %d threads. Done.\\n", 3);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t sum_mutex, min_mutex, max_mutex;
int numWorkers;
double read_timer() {
static bool initialized = 0;
static struct timeval start;
struct timeval end;
if( !initialized )
{
gettimeofday( &start, 0 );
initialized = 1;
}
gettimeofday( &end, 0 );
return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec);
}
int x, y;
int value;
} Pos;
double start_time, end_time;
int size, stripSize;
long sum;
Pos min, max;
int matrix[10000][10000];
void *Worker(void *);
int main(int argc, char *argv[]) {
int i, j;
long l;
pthread_attr_t attr;
pthread_t workerid[10];
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
pthread_mutex_init(&sum_mutex, 0);
pthread_mutex_init(&max_mutex, 0);
pthread_mutex_init(&min_mutex, 0);
size = (argc > 1)? atoi(argv[1]) : 10000;
numWorkers = (argc > 2)? atoi(argv[2]) : 10;
if (size > 10000) size = 10000;
if (numWorkers > 10) numWorkers = 10;
stripSize = size/numWorkers;
srand(7);
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
matrix[i][j] = rand()%99;
}
}
sum = 0;
min.value = matrix[0][0];
max.value = matrix[0][0];
min.x = min.y = max.x = max.y = 0;
start_time = read_timer();
for (l = 0; l < numWorkers; l++)
pthread_create(&workerid[l], &attr, Worker, (void *) l);
for (i = 0; i < numWorkers; i++)
pthread_join(workerid[i], 0);
end_time = read_timer();
printf("The total is %ld, min is %d at [%d,%d], max is %d at [%d,%d]\\n", sum,
min.value, min.y, min.x, max.value, max.y, max.x);
printf("The execution time is %g sec\\n", end_time - start_time);
pthread_exit(0);
}
void *Worker(void *arg) {
long myid = (long) arg;
long total;
int i, j, first, last;
first = myid*stripSize;
last = (myid == numWorkers - 1) ? (size - 1) : (first + stripSize - 1);
total = 0;
for (i = first; i <= last; i++)
for (j = 0; j < size; j++) {
total += matrix[i][j];
if (min.value > matrix[i][j]) {
pthread_mutex_lock(&min_mutex);
if (min.value > matrix[i][j]) {
min.value = matrix[i][j];
min.x = j;
min.y = i;
}
pthread_mutex_unlock(&min_mutex);
} else if (max.value < matrix[i][j]) {
pthread_mutex_lock(&max_mutex);
if (max.value < matrix[i][j]) {
max.value = matrix[i][j];
max.x = j;
max.y = i;
}
pthread_mutex_unlock(&max_mutex);
}
}
pthread_mutex_lock(&sum_mutex);
sum += total;
pthread_mutex_unlock(&sum_mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cc = PTHREAD_COND_INITIALIZER;
pthread_cond_t cp = PTHREAD_COND_INITIALIZER;
int tam_cola = 0;
int total_items = 0;
double tiempo_prod = 0;
double tiempo_cons = 0;
int cola = 0;
int producidos = 0;
int consumidos=0;
void* Consumidor(void * arg){
int fin=0;
while(fin==0){
pthread_mutex_lock(&mutex);
while(cola == 0 && producidos<total_items)
pthread_cond_wait(&cc,&mutex);
usleep(tiempo_cons);
if(consumidos<total_items){
consumidos++;
--cola;
printf("Consumidor %d ha consumido 1 item, tamaño cola = %d\\n",*((int *)arg),cola);
}else{
fin=10 ;
}
pthread_cond_signal(&cp);
pthread_mutex_unlock(&mutex);
}
return (void*)1;
}
void* Productor(void * arg){
int fin=0;
while(fin==0){
pthread_mutex_lock(&mutex);
while(cola == tam_cola && consumidos<total_items)
pthread_cond_wait(&cp,&mutex);
usleep(tiempo_prod);
if(producidos<total_items){
cola++;
producidos++;
printf("Productor %d ha producido 1 item, tamaño cola = %d\\n",*((int *)arg),cola);
}else{
fin=10;
}
pthread_cond_signal(&cc);
pthread_mutex_unlock(&mutex);
}
return (void*)1;
}
int main(int argc, char** argv){
if (argc==7){
int num_hilos_prod = atoi(argv[1]);
tiempo_prod = atof(argv[2])/1000000;
int num_hilos_cons = atoi(argv[3]);
tiempo_cons = atof(argv[4])/1000000;
tam_cola = atoi(argv[5]);
total_items = atoi(argv[6]);
printf("Numero de productores: %d\\n", num_hilos_prod);
printf("Numero de consumidores: %d\\n", num_hilos_cons);
printf("Tamaño de cola: %d elementos\\n", tam_cola);
printf("Tiempo de consumo: %.2f segundos\\n", tiempo_cons*1000000);
printf("Tiempo de producción: %.2f segundos\\n", tiempo_prod*1000000);
printf("Total de items a producir: %d elementos.\\n\\n", total_items);
pthread_t *consumidores = (pthread_t *)malloc(sizeof(pthread_t)*num_hilos_cons);
pthread_t *productores = (pthread_t *)malloc(sizeof(pthread_t)*num_hilos_prod);
int hiloMax = 0;
if(num_hilos_cons > num_hilos_prod)
hiloMax = num_hilos_cons;
else
hiloMax = num_hilos_prod;
int *arreglos=malloc(hiloMax*sizeof(int));
for(int i=0;i<hiloMax;i++){
arreglos[i] = i+1;
}
for(int i=0;i<hiloMax;i++){
if(i<num_hilos_prod) pthread_create(&(productores[i]),0,Productor,&arreglos[i]);
if(i<num_hilos_cons) pthread_create(&(consumidores[i]),0,Consumidor,&arreglos[i]);
}
for(int i=0;i<hiloMax;i++){
if(i<num_hilos_prod) pthread_join(productores[i],0);
if(i<num_hilos_cons) pthread_join(consumidores[i],0);
}
pthread_cond_destroy(&cc);
pthread_cond_destroy(&cp);
return 0;
}else{
printf("Uso del programa <num_hilos_prod> <tiempo_prod> <num_hilos_cons> <tiempo_cons> <tam_cola> <total_items> \\n");
return -1;
}
}
| 1
|
#include <pthread.h>
static struct {
int value;
pthread_mutex_t mutex;
} money;
static void *make_money(void *arg)
{
bool mutex_done = 0;
if (!mutex_done &&
!pthread_mutex_trylock(&money.mutex)) {
++money.value;
mutex_done = 1;
pthread_mutex_unlock(&money.mutex);
}
if (!mutex_done) {
pthread_mutex_lock(&money.mutex);
++money.value;
mutex_done = 1;
pthread_mutex_unlock(&money.mutex);
}
return 0;
}
static void master(void)
{
pthread_t woodcutter;
pthread_t miner;
if (pthread_create(&woodcutter, 0, make_money, 0)) {
abort();
}
if (pthread_create(&miner, 0, make_money, 0)) {
abort();
}
if (pthread_join(woodcutter, 0)) {
abort();
}
if (pthread_join(miner, 0)) {
abort();
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int i =1;
void* thread1(void* arg)
{
for(i = 1; i < 10; i++)
{
pthread_mutex_lock(&mutex);
printf("thread1:i=%d\\n",i);
if(i % 3 == 0) {
printf("thread1: I will notify thread2\\n");
pthread_cond_signal(&cond);
printf("thread1: I'will sleep then release mutex\\n");
sleep(1);
}
pthread_mutex_unlock(&mutex);
printf("--\\n");
sleep(1);
}
return arg;
}
void* thread2(void* arg)
{
while(i < 10)
{
pthread_mutex_lock(&mutex);
printf("thread2:i=%d\\n",i);
if(i % 3 != 0) {
pthread_cond_wait(&cond,&mutex);
printf("thread2:I am now waiting cond,and will sleep then ealse mutex\\n");
sleep(1);
}
pthread_mutex_unlock(&mutex);
printf("--\\n");
sleep(1);
}
return arg;
}
int main()
{
pthread_t th1;
pthread_t th2;
pthread_create(&th1, 0, thread1, 0);
pthread_create(&th2, 0, thread2, 0);
pthread_join(th1,0);
printf("thread 1 exit\\n");
pthread_join(th2,0);
printf("thread 2 exit\\n");
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int count=0;
void AddCount_Odd_Func(void);
void AddCount_Even_Func(void);
int main()
{
int ret;
pthread_t odd_thread,even_thread;
pthread_attr_t thread_attr;
count = 0;
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond,0);
ret = pthread_attr_init(&thread_attr);
if (ret != 0)
{
perror("Attribute Creation Failed");
exit(1);
}
pthread_attr_setdetachstate(&thread_attr,PTHREAD_CREATE_DETACHED);
ret=pthread_create(&odd_thread,&thread_attr,(void *)&AddCount_Odd_Func,0);
if(ret != 0)
{
perror("Thread Creation Failed");
exit(1);
}
ret = pthread_create(&even_thread,&thread_attr,(void *)&AddCount_Even_Func, 0);
if (ret != 0)
{
perror("Thread Creation Failed");
exit(1);
}
while(count<9);
printf("Finished!\\n");
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&mutex);
return 0;
}
void AddCount_Odd_Func(void)
{
pthread_mutex_lock(&mutex);
while(count<9)
{
if(count%2==1)
{
count++;
printf("AddCount_Odd_Func():count=%d.\\n",count);
pthread_cond_signal(&cond);
}
else
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
}
void AddCount_Even_Func(void)
{
pthread_mutex_lock(&mutex);
while(count<9)
{
if(count%2==0)
{
count++;
printf("AddCount_Even_Func():count=%d.\\n",count);
pthread_cond_signal(&cond);
}
else
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
}
| 0
|
#include <pthread.h>
int buf[100];
int count = 0;
int id;
} ids;
pthread_mutex_t lock;
pthread_cond_t cond;
void producer(void* arg){
ids* args = (ids*)arg;
int id = args->id;
while(1){
pthread_mutex_lock(&lock);
if (count == 100){
printf("Buffer full, dropping producer %d\\n", id);
}else{
buf[count] = 100;
count ++;
printf("Producer %d updated. count = %d\\n", id, count);
}
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&lock);
usleep(100);
}
}
void consumer(void* arg){
ids* args = (ids*)arg;
int id = args->id;
while(1){
pthread_mutex_lock(&lock);
while (count == 0){
printf("consumer %d waiting ...\\n", id);
pthread_cond_wait(&cond, &lock);
}
buf[count] = 0;
count --;
printf("consumer %d removed. count = %d\\n", id, count);
pthread_mutex_unlock(&lock);
}
}
int main(){
pthread_mutex_init(&lock, 0);
pthread_cond_init(&cond, 0);
pthread_t producer_thread[2];
pthread_t consumer_thread[2];
ids th_id[2];
int i =0;
for (i=0;i<2;i++){
th_id[i].id = i;
pthread_create(&producer_thread[i], 0, producer, &th_id[i]);
pthread_create(&consumer_thread[i], 0, consumer, &th_id[i]);
}
for (i=0;i<2;i++){
pthread_join(producer_thread[i], 0);
pthread_join(consumer_thread[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
{
off_t pos;
off_t nbytes;
}COMPUTE_INFO,*PCOMPUTE_INFO;
value_type mmap_compute(off_t pos,off_t nbytes);
void thread_compute(void *param);
char *g_src = 0;
int g_nthreads = 0;
value_type g_final_res = 0;
pthread_mutex_t nthreads_mutex;
int main(int argc,char **argv)
{
int fid;
off_t size,len,last_len;
off_t off;
int thread_counts = 0;
int i = 0;
struct stat statbuf;
pthread_t thread_id;
pthread_attr_t thread_attr;
PCOMPUTE_INFO pcompute_info = 0;
clock_t start_time,end_time;
double total_time;
start_time = clock();
if(argc != 2)
{
printf("usage: filename\\n");
return -1;
}
if( (fid = open(argv[1],O_RDONLY))< 0 )
{
printf("error to open file %s\\n",argv[1]);
return -1;
}
if( fstat(fid,&statbuf) < 0 )
{
printf("fstat error\\n");
return -1;
}
if( (g_src = mmap(0,statbuf.st_size,PROT_READ,MAP_PRIVATE,fid,0)) == (char *)-1 )
{
printf("error to map\\n");
return -1;
}
pthread_attr_init(&thread_attr);
pthread_attr_setdetachstate(&thread_attr,PTHREAD_CREATE_DETACHED);
pthread_mutex_init(&nthreads_mutex,0);
g_final_res = 0;
g_nthreads = 0;
len = 4000000;
if( statbuf.st_size<= len)
thread_counts = 1;
else
{
thread_counts = statbuf.st_size / len;
}
thread_counts = 128;
len = statbuf.st_size / thread_counts;
pcompute_info = malloc(sizeof(COMPUTE_INFO)*(thread_counts+2));
for(i = 0; i < thread_counts; ++i)
{
pcompute_info[i].pos = i*len ;
pcompute_info[i].nbytes = len;
if((thread_id = pthread_create(&thread_id,&thread_attr,(void *)thread_compute,(void *)&pcompute_info[i])) != 0)
{
printf("pthread_create error\\n");
exit(0);
}
}
if( statbuf.st_size > len * thread_counts )
{
last_len = statbuf.st_size - len * thread_counts;
++thread_counts;
pcompute_info[i].pos = (thread_counts -1)*len ;
pcompute_info[i].nbytes = last_len;
if(pthread_create(&thread_id,&thread_attr,(void *)thread_compute,(void *)&pcompute_info[i]) != 0)
{
printf("pthread_create error\\n");
exit(0);
}
}
while(g_nthreads < thread_counts)
;
pthread_mutex_destroy(&nthreads_mutex);
free(pcompute_info);
end_time = clock();
total_time = (double)((end_time- start_time)/(double)CLOCKS_PER_SEC);
printf("%s %lld\\n",argv[1],g_final_res);
return 0;
}
void thread_compute(void *param)
{
PCOMPUTE_INFO pinfo = (PCOMPUTE_INFO)param;
value_type res = 0;
res = mmap_compute(pinfo->pos,pinfo->nbytes);
pthread_mutex_lock(&nthreads_mutex);
g_final_res += res;
++g_nthreads;
pthread_mutex_unlock(&nthreads_mutex);
pthread_exit(0);
}
value_type mmap_compute(off_t pos,off_t nbytes)
{
off_t max_bytes = (4096*4) * 4;
int buf[(4096*4)];
off_t nlast = nbytes;
off_t ntmp = 0;
off_t num_count = 0;
int i,k,tmp;
value_type sum = 0;
sum = 0;
while(1)
{
ntmp = nlast < max_bytes? nlast : max_bytes;
memcpy(buf,g_src+pos,ntmp);
pos += ntmp;
nlast -= ntmp;
num_count = ntmp/4;
for( i = 0; i < num_count; ++i)
sum += buf[i];
if(nlast <=0 )
break;
}
return sum;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mp = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t turno = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t prod = PTHREAD_COND_INITIALIZER;
pthread_cond_t cons = PTHREAD_COND_INITIALIZER;
void * produtor(void * arg);
void * consumidor(void * arg);
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];
srand48(time(0));
int i;
int *id = 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);
return 0;
}
void * produtor(void * arg){
int p = (int)(drand48()*1000);
int i = *((int*) arg);
while(1){
pthread_mutex_lock(&mp);
while(cont == 10){
printf("-------------------------\\n Esperar consumidor unidades de produtos lotadas!\\n");
pthread_cond_wait(&prod, &mp);
}
b[prodpos] = p;
prodpos = (prodpos + 1)%10;
cont++;
if(cont == 1){
printf("-------------------------\\nproduzidos %d unidades, acordar consumidor!\\n", p);
pthread_cond_signal(&cons);
}
sleep(1);
printf("-------------------------\\nproduzindo[%d]... \\nproduzidos: %d unidades\\n", i, p);
pthread_mutex_unlock(&mp);
sleep(1);
}
}
void * consumidor(void * arg){
int i = *((int*) arg);
while(1){
pthread_mutex_lock(&mp);
while(cont == 0){
printf("*************************\\nEsperar produtos, sem unidades para conusmir!\\n");
pthread_cond_wait(&cons, &mp);
}
int c = b[conspos];
conspos = (conspos + 1)%10;
cont--;
if(cont == (10 -1)){
printf("*************************\\nAcabou produto!\\n");
pthread_cond_signal(&prod);
}
sleep(1);
printf("*************************\\nconsumindo[%d]... \\nconsumidos: %d unidades\\n", i, c);
pthread_mutex_unlock(&mp);
sleep(1);
}
}
| 1
|
#include <pthread.h>
int chairs[3];
int available_chairs;
int ta_state;
int waker;
pthread_mutex_t sleeplock;
pthread_mutex_t chairlock;
pthread_mutex_t sleepm;
pthread_mutex_t dusunceli_ta;
pthread_cond_t ta_sleeping = PTHREAD_COND_INITIALIZER;
pthread_cond_t ta_helping = PTHREAD_COND_INITIALIZER;
pthread_cond_t koca_yurekli = PTHREAD_COND_INITIALIZER;
void* studentThread( int studentID)
{
while(1)
{
sleep( rand() % 6 + 1);
pthread_mutex_lock( &sleeplock);
if( ta_state == 0)
{
ta_state = 1;
waker = studentID;
printf("Student %d awakes TA\\n", studentID);
pthread_cond_signal( &ta_sleeping);
pthread_mutex_unlock( &sleeplock);
continue;
}
pthread_mutex_unlock( &sleeplock);
pthread_mutex_lock( &chairlock);
if( available_chairs)
{
chairs[ 3 - available_chairs] = studentID;
available_chairs--;
printf("Student %d sits and waits\\n", studentID);
}
pthread_mutex_unlock( &chairlock);
}
pthread_exit(0);
}
void* taThread()
{
while(1)
{
pthread_mutex_lock( &sleeplock);
while( ta_state == 0)
pthread_cond_wait( &ta_sleeping, &sleeplock);
printf("TA helps to student %d\\n", waker);
pthread_mutex_unlock( &sleeplock);
printf("TA checks chairs\\n");
while( available_chairs < 3)
{
pthread_mutex_lock( &chairlock);
printf("TA helps to student %d\\n", chairs[0]);
chairs[0] = chairs[1];
chairs[1] = chairs[2];
chairs[2] = -1;
available_chairs++;
pthread_mutex_unlock( &chairlock);
printf("TA checks chairs\\n");
}
pthread_mutex_lock( &sleeplock);
ta_state = 0;
printf("TA takes a nap\\n\\n");
sleep(1);
pthread_mutex_unlock( &sleeplock);
}
pthread_exit(0);
}
int main()
{
pthread_t* students;
pthread_t ta;
memset( chairs, -1, 10);
available_chairs = 3;
ta_state = 0;
pthread_mutex_init( &sleeplock, 0);
pthread_mutex_init( &chairlock, 0);
pthread_mutex_init( &sleepm, 0);
students = (pthread_t*) malloc( sizeof(pthread_t) * 10);
for( int i = 0; i < 10; i++)
{
pthread_create( &students[i], 0, (void*) studentThread, (void*) i);
}
pthread_create( &ta, 0, (void*) taThread, 0);
for( int i = 0; i < 10; i++)
{
pthread_join( students[i], 0);
}
pthread_join( ta, 0);
return 0;
}
| 0
|
#include <pthread.h>
int g1, g2, g3;
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex3 = PTHREAD_MUTEX_INITIALIZER;
void *t1(void *arg) {
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2);
g1 = g2 + 1;
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
return 0;
}
void *t2(void *arg) {
pthread_mutex_lock(&mutex2);
pthread_mutex_lock(&mutex3);
g2 = g3 - 1;
pthread_mutex_unlock(&mutex3);
pthread_mutex_unlock(&mutex2);
return 0;
}
void *t3(void *arg) {
pthread_mutex_lock(&mutex3);
pthread_mutex_lock(&mutex1);
g3 = g1 + 1;
pthread_mutex_unlock(&mutex1);
pthread_mutex_unlock(&mutex3);
return 0;
}
int main(void) {
pthread_t id1, id2, id3;
int i;
for (i = 0; i < 1000000; i++) {
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_create(&id3, 0, t3, 0);
pthread_join (id1, 0);
pthread_join (id2, 0);
pthread_join (id3, 0);
printf("%d: g1 = %d, g2 = %d, g3 = %d.\\n", i, g1, g2, g3);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t tcb_alloc_mutex;
extern const unsigned int socket_tcb_ring_size ;
const unsigned int tcb_socket_ring_size = 1024;
int Ntcb = 0;
struct tcb *tcbs[10];
void InitTcpTcb()
{
InitSocketTcbRing();
InitSocketInterface();
int i;
for(i=0;i<10; i++) {
tcbs[i] = 0;
}
}
struct tcb* alloc_tcb(uint16_t MaxWindSize, uint16_t CurrentWindSize)
{
static uint16_t IdentifierCount = 0;
if(IdentifierCount == 0) {
IdentifierCount = 1;
}
struct tcb *ptcb = malloc(sizeof(struct tcb));
if(ptcb==0) {
assert(0);
printf("malloc failed\\n");
}
memset(ptcb, 0, sizeof(struct tcb));
ptcb->identifier = IdentifierCount++;
sprintf(ptcb->TCB_TO_SOCKET_RING_NAME,"TtoS%d", ptcb->identifier);
sprintf(ptcb->SOCKET_TO_TCB_RING_NAME,"StoT%d", ptcb->identifier);
ptcb->socket_tcb_ring_send = rte_ring_create(ptcb->TCB_TO_SOCKET_RING_NAME, socket_tcb_ring_size, SOCKET_ID_ANY, 0);
ptcb->socket_tcb_ring_recv = rte_ring_lookup(ptcb->TCB_TO_SOCKET_RING_NAME);
if(ptcb->socket_tcb_ring_recv == 0) {
printf ("ERROR **** Failed to set socket to tcb ring recv.\\n");
}
else {
printf("Socket tcb ring recv side OK. Ring Name %s\\n", ptcb->TCB_TO_SOCKET_RING_NAME);
}
if(ptcb->socket_tcb_ring_send == 0) {
printf ("ERROR **** Failed to set socket to tcb ring send side.\\n");
}
else {
printf("Socket tcb ring send side OK, Ring Name %s\\n", ptcb->TCB_TO_SOCKET_RING_NAME);
}
ptcb->tcb_socket_ring_send = rte_ring_create(ptcb->SOCKET_TO_TCB_RING_NAME, tcb_socket_ring_size, SOCKET_ID_ANY, 0);
if(ptcb->tcb_socket_ring_send == 0) {
printf ("ERROR **** Failed to set tcb to socket ring send side.\\n");
}
else {
printf("Socket tcb ring send side OK. Ring name %s\\n", ptcb->SOCKET_TO_TCB_RING_NAME);
}
ptcb->tcb_socket_ring_recv = rte_ring_lookup(ptcb->SOCKET_TO_TCB_RING_NAME);
if(ptcb->tcb_socket_ring_recv == 0) {
printf ("ERROR **** Failed to set tcb to scoket ring recv side. Ring Name %s\\n", ptcb->SOCKET_TO_TCB_RING_NAME );
}
else {
printf("Socket tcb ring send side OK\\n");
}
ptcb->RecvWindow = AllocWindow(MaxWindSize, CurrentWindSize);
pthread_mutex_lock(&tcb_alloc_mutex);
assert(Ntcb < 10);
tcbs[Ntcb] = ptcb;
printf("adding tcb %p at %d with identifier %d\\n", ptcb, Ntcb, ptcb->identifier);
Ntcb++;
pthread_mutex_unlock(&tcb_alloc_mutex);
return ptcb;
}
struct tcb* get_tcb_by_identifier(int identifier)
{
int i;
struct tcb *ptcb = 0;
for(i=0; i<Ntcb; i++) {
ptcb = tcbs[i];
if(ptcb && ptcb->identifier == identifier) {
return ptcb;
}
}
}
struct tcb* findtcb(struct tcp_hdr *ptcphdr, struct ipv4_hdr *hdr)
{
int i;
struct tcb *ptcb = 0;
uint16_t dest_port = 0;
uint16_t src_port = 0;
dest_port = ntohs(ptcphdr->dst_port);
src_port = ntohs(ptcphdr->src_port);
for(i=0; i<Ntcb; i++) {
ptcb = tcbs[i];
if(ptcb == 0) {
continue;
}
logger(TCB, NORMAL,"searching for tcb %u %u %d %d found %u %u %d %d for %d\\n", ntohl(hdr->src_addr), hdr->dst_addr, src_port, dest_port, ptcb->ipv4_src, ptcb->ipv4_dst, ptcb->sport, ptcb->dport, ptcb->identifier);
if((ptcb->dport == dest_port) &&
(ptcb->sport == src_port) &&
(ptcb->ipv4_dst == hdr->dst_addr) &&
(ptcb->ipv4_src == ntohl(hdr->src_addr))) {
logger(TCB, NORMAL,"Found stablized port\\n");
return ptcb;
}
}
for(i=0; i<Ntcb; i++) {
ptcb = tcbs[i];
if(ptcb->state == LISTENING) {
if((ptcb->dport) == dest_port) {
logger(TCB, NORMAL,"Found a listening tcb. listening port = %d, packet port = %d\\n", ptcb->dport, dest_port);
return ptcb;
}
}
}
fflush(stdout);
return 0;
}
int remove_tcb(int identifier)
{
struct tcb *ptcb = get_tcb_by_identifier(identifier);
int i = 0;
for(i=0; i<Ntcb; i++) {
if(tcbs[i] == ptcb) {
tcbs[i] = 0;
}
}
}
int send_data(char *message, int len)
{
}
| 0
|
#include <pthread.h>
struct ritual_dynump * ritual_dynump_create(int sz) {
struct ritual_dynump *rv = malloc(sizeof *rv);
rv->element_size = sz;
rv->current = ritual_ump_create( sz );
if( !rv->current ) {
free( rv );
return 0;
}
if( pthread_mutex_init( &rv->mutex, 0 ) ) {
ritual_ump_free( rv->current );
free( rv );
return 0;
}
return rv;
}
void ritual_dynump_free(struct ritual_dynump *dynump) {
pthread_mutex_destroy( &dynump->mutex );
while( dynump->current != dynump->current->next ) {
ritual_ump_free( dynump->current->next );
}
ritual_ump_free( dynump->current );
free( dynump );
}
void * ritual_dynump_alloc(struct ritual_dynump *dynump) {
const int tries = 5;
struct ritual_ump *current;
void *rv;
for(int i=0;i<tries;i++) {
current = dynump->current;
dynump->current = current->next;
rv = ritual_ump_try_alloc( current );
if( rv ) {
return rv;
}
}
pthread_mutex_lock( &dynump->mutex );
rv = ritual_ump_alloc( dynump->current );
if( rv ) {
pthread_mutex_unlock( &dynump->mutex );
return rv;
}
struct ritual_ump *ump = ritual_ump_create( dynump->element_size );
if( !ump ) {
return 0;
}
ump->next = dynump->current;
ump->prev = dynump->current->prev;
ump->prev->next = ump;
ump->next->prev = ump;
dynump->current = ump;
pthread_mutex_lock( &dynump->current->mutex );
pthread_mutex_unlock( &dynump->mutex );
rv = ritual_ump_alloc_unsafe( ump, 1 );
assert( rv );
return rv;
}
struct ritual_ump * ritual_ump_create(int sz) {
struct ritual_ump *rv;
rv = malloc( sizeof *rv );
memset( rv, 0, sizeof *rv );
rv->element_size = sz;
if( pthread_mutex_init( &rv->mutex, 0 ) ) {
free( rv );
return 0;
}
rv->data = malloc( sz * RITUAL_UMP_SIZE );
rv->prev = rv->next = rv;
return rv;
}
void ritual_ump_free(struct ritual_ump *ump) {
if( ump ) {
if( ump->prev ) {
ump->prev->next = ump->next;
}
if( ump->next ) {
ump->next->prev = ump->prev;
}
pthread_mutex_destroy( &ump->mutex );
free( ump->data );
free( ump );
}
}
const int ritual_fub_array[] = {
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 7,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4,
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, -1
};
void * ritual_ump_try_alloc(struct ritual_ump *ump) {
if( pthread_mutex_trylock( &ump->mutex ) ) {
return 0;
}
return ritual_ump_alloc_unsafe( ump, 1 );
}
void * ritual_ump_alloc(struct ritual_ump *ump) {
return ritual_ump_alloc_unsafe( ump, 0 );
}
void * ritual_ump_alloc_unsafe(struct ritual_ump *ump, int was_locked) {
int rv = -1, i, jb, j, k;
if( !was_locked ) {
pthread_mutex_lock( &ump->mutex );
}
do {
i = ( ritual_fub_array[ump->level1&0xff] >= 0 ) ? ritual_fub_array[ump->level1&0xff] : ( ritual_fub_array[(ump->level1>>8)&0xff] >= 0 ) ? ritual_fub_array[(ump->level1>>8)&0xff] + 8 : ( ritual_fub_array[(ump->level1>>16)&0xff] >= 0 ) ? ritual_fub_array[(ump->level1>>16)&0xff] + 16 : ( ritual_fub_array[(ump->level1>>24)] >= 0 ) ? ritual_fub_array[(ump->level1>>24)] + 24 : -1;
if( i < 0 ) break;
jb = ( ritual_fub_array[ump->level2[i]&0xff] >= 0 ) ? ritual_fub_array[ump->level2[i]&0xff] : ( ritual_fub_array[(ump->level2[i]>>8)&0xff] >= 0 ) ? ritual_fub_array[(ump->level2[i]>>8)&0xff] + 8 : ( ritual_fub_array[(ump->level2[i]>>16)&0xff] >= 0 ) ? ritual_fub_array[(ump->level2[i]>>16)&0xff] + 16 : ( ritual_fub_array[(ump->level2[i]>>24)] >= 0 ) ? ritual_fub_array[(ump->level2[i]>>24)] + 24 : -1;
assert( jb >= 0 );
j = jb + (i << 5);
k = ( ritual_fub_array[ump->level3[j]&0xff] >= 0 ) ? ritual_fub_array[ump->level3[j]&0xff] : ( ritual_fub_array[(ump->level3[j]>>8)&0xff] >= 0 ) ? ritual_fub_array[(ump->level3[j]>>8)&0xff] + 8 : ( ritual_fub_array[(ump->level3[j]>>16)&0xff] >= 0 ) ? ritual_fub_array[(ump->level3[j]>>16)&0xff] + 16 : ( ritual_fub_array[(ump->level3[j]>>24)] >= 0 ) ? ritual_fub_array[(ump->level3[j]>>24)] + 24 : -1;
assert( k >= 0 );
rv = (k + (j <<5));
ump->level3[j] |= (1 << k);
if( !~ump->level3[j] ) {
ump->level2[i] |= (1 << jb);
if( !~ump->level2[i] ) {
ump->level1 |= (1 << i);
}
}
++ump->used;
} while(0);
pthread_mutex_unlock( &ump->mutex );
return (rv < 0) ? 0 : &ump->data[ump->element_size * rv];
}
void ritual_ump_clean(struct ritual_ump *ump,
int (*gc)(struct ritual_ump*, void*) ) {
pthread_mutex_lock( &ump->mutex );
for(int i=0;i<1024;i++) if( ump->level3[i] ) {
int cleaned = 0;
uint32_t bit = 1;
for(int j=0;j<32;j++) {
if( bit & ump->level3[i] ) {
void *data = &ump->data[((i << 5) + j)*ump->element_size];
if( gc( ump, data ) ) {
ump->level3[i] ^= bit;
--ump->used;
cleaned = 1;
}
}
bit <<= 1;
}
if( cleaned ) {
int j = i / 32;
bit = 1 << (i % 32);
ump->level2[j] &= ~bit;
bit = 1 << j;
ump->level1 &= ~bit;
}
}
pthread_mutex_unlock( &ump->mutex );
}
| 1
|
#include <pthread.h>
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer = 0;
void *producer(void *ptr)
{
int i;
for(i=1; i<=10; i++)
{
pthread_mutex_lock(&the_mutex);
while(buffer !=0) pthread_cond_wait(&condp, &the_mutex);
printf("procucer produce item %d\\n",i);
buffer = i;
pthread_cond_signal(&condc);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
void *consumer(void *ptr)
{
int i;
for(i=1; i<=10; i++)
{
pthread_mutex_lock(&the_mutex);
while(buffer ==0) pthread_cond_wait(&condc, &the_mutex);
printf("consumer consume item %d\\n",i);
buffer = 0;
pthread_cond_signal(&condp);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
int main(int argc, char *argv[])
{
pthread_t pro, con;
pthread_mutex_init(&the_mutex, 0);
pthread_cond_init(&condc,0);
pthread_cond_init(&condp,0);
pthread_create(&con, 0, consumer, 0);
pthread_create(&pro, 0, producer, 0);
pthread_join(pro,0);
pthread_join(con,0);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
pthread_mutex_destroy(&the_mutex);
return 0;
}
| 0
|
#include <pthread.h>
static pthread_t bws_pusher;
static int bws_timer = 0;
void * bws_thread (void * args);
void init_bws(int interval) {
int t1;
sem_init(&s_bws_hasdata, 0, 0);
sem_init(&s_bws_processed, 0, 0);
bws_timer = interval;
t1 = pthread_create(&bws_pusher, 0, bws_thread, 0);
if (t1) {
printf("ERROR; return code from pthread_create() is %d\\n", t1);
exit(1);
}
}
void * bws_thread (void * args) {
(void)(args);
assert(args==0);
for (;;) {
if (kill_bora_threads) {
break;
}
usleep(bws_timer);
pthread_mutex_lock(&bwLock);
sem_post(&s_bws_hasdata);
sem_wait(&s_bws_processed);
pthread_mutex_unlock(&bwLock);
}
printf("BWS THREAD DOWN\\n");
pthread_exit(0);
return 0;
}
void bws_return_value (int bw) {
set_bandwidth(bw);
reset_out_counters();
release_ack_store();
sem_post(&s_bws_processed);
}
void set_bws_interval(int interval) {
bws_timer = interval;
}
void bws_end_threads(void) {
sem_post(&s_bws_hasdata);
sem_post(&s_bws_processed);
pthread_join(bws_pusher, 0);
}
| 1
|
#include <pthread.h>
int N;
int maxnum;
char *Init;
int PRINT;
matrix A;
double b[4096];
double y[4096];
pthread_barrier_t barrier;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void
Init_Matrix()
{
int i, j;
printf("\\nsize = %dx%d ", N, N);
printf("\\nmaxnum = %d \\n", maxnum);
printf("Init = %s \\n", Init);
printf("Initializing matrix...");
if (strcmp(Init,"rand") == 0) {
for (i = 0; i < N; i++){
for (j = 0; j < N; j++) {
if (i == j)
A[i][j] = (double)(rand() % maxnum) + 5.0;
else
A[i][j] = (double)(rand() % maxnum) + 1.0;
}
}
}
if (strcmp(Init,"fast") == 0) {
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if (i == j)
A[i][j] = 5.0;
else
A[i][j] = 2.0;
}
}
}
for (i = 0; i < N; i++) {
b[i] = 2.0;
y[i] = 1.0;
}
printf("done \\n\\n");
if (PRINT == 1)
Print_Matrix();
}
void
Print_Matrix()
{
int i, j;
printf("Matrix A:\\n");
for (i = 0; i < N; i++) {
printf("[");
for (j = 0; j < N; j++)
printf(" %5.2f,", A[i][j]);
printf("]\\n");
}
printf("Vector b:\\n[");
for (j = 0; j < N; j++)
printf(" %5.2f,", b[j]);
printf("]\\n");
printf("Vector y:\\n[");
for (j = 0; j < N; j++)
printf(" %5.2f,", y[j]);
printf("]\\n");
printf("\\n\\n");
}
void
Init_Default()
{
N = 2048;
Init = "rand";
maxnum = 15.0;
PRINT = 0;
}
int
Read_Options(int argc, char **argv)
{
char *prog;
prog = *argv;
while (++argv, --argc > 0)
if (**argv == '-')
switch ( *++*argv ) {
case 'n':
--argc;
N = atoi(*++argv);
break;
case 'h':
printf("\\nHELP: try sor -u \\n\\n");
exit(0);
break;
case 'u':
printf("\\nUsage: sor [-n problemsize]\\n");
printf(" [-D] show default values \\n");
printf(" [-h] help \\n");
printf(" [-I init_type] fast/rand \\n");
printf(" [-m maxnum] max random no \\n");
printf(" [-P print_switch] 0/1 \\n");
exit(0);
break;
case 'D':
printf("\\nDefault: n = %d ", N);
printf("\\n Init = rand" );
printf("\\n maxnum = 5 ");
printf("\\n P = 0 \\n\\n");
exit(0);
break;
case 'I':
--argc;
Init = *++argv;
break;
case 'm':
--argc;
maxnum = atoi(*++argv);
break;
case 'P':
--argc;
PRINT = atoi(*++argv);
break;
default:
printf("%s: ignored option: -%s\\n", prog, *argv);
printf("HELP: try %s -u \\n\\n", prog);
break;
}
}
void
work(void *thread_Id)
{
int i, j, k;
long thread_id = (long)thread_Id;
pthread_mutex_init(&mutex,0);
for (k = 0; k < N; k++) {
if(thread_id == (k % 8))
{
for (j = k+1; j < N ; j++)
{
pthread_mutex_lock(&mutex);
A[k][j] = A[k][j] / A[k][k];
pthread_mutex_unlock(&mutex);
}
y[k] = b[k] / A[k][k];
pthread_mutex_lock(&mutex);
A[k][k] = 1.0;
pthread_mutex_unlock(&mutex);
}
int bar_wait = pthread_barrier_wait(&barrier);
if(bar_wait != 0 && bar_wait != PTHREAD_BARRIER_SERIAL_THREAD)
{
printf("Could not wait on barrier \\n");
exit(-1);
}
for (i = k+1; i < N ; i++) {
if(thread_id == (i % 8))
{
for (j = k+1; j < N ; j++)
A[i][j] = A[i][j] - A[i][k]*A[k][j];
b[i] = b[i] - A[i][k]*y[k];
A[i][k] = 0.0;
}
}
int bar_wait2 = pthread_barrier_wait(&barrier);
if(bar_wait2 != 0 && bar_wait2 != PTHREAD_BARRIER_SERIAL_THREAD)
{
printf("Could not wait on barrier \\n");
exit(-1);
}
}
}
int
main(int argc, char **argv)
{
pthread_t threads[8];
long k;
Init_Default();
Read_Options(argc,argv);
Init_Matrix();
if(pthread_barrier_init(&barrier, 0, 8))
{
printf("Could not initialize the barrier \\n");
return -1;
}
for(k = 0; k < 8; k++)
{
if(pthread_create (&threads[k], 0, (void *) &work, (void *) k))
{
printf("Could not create thread \\n");
return -1;
}
}
for(k = 0; k < 8; k++)
{
if(pthread_join(threads[k],0))
{
printf("Could not join thread \\n");
return -1;
}
}
if(pthread_barrier_destroy(&barrier))
{
printf("Barrier could not be destroyed");
return -1;
}
if (PRINT == 1)
Print_Matrix();
}
| 0
|
#include <pthread.h>
{
int res;
int count;
pthread_cond_t cond;
pthread_mutex_t mutex;
}Result;
void *set_fn(void *arg)
{
Result *r = (Result*)arg;
int i = 1;
int sum = 0;
for(; i <= 100; i++){
sum += i;
}
r->res = sum;
pthread_mutex_lock(&r->mutex);
while(r->count < 2){
pthread_mutex_unlock(&r->mutex);
printf("usleep!\\n");
usleep(100);
pthread_mutex_lock(&r->mutex);
}
pthread_mutex_unlock(&r->mutex);
pthread_cond_broadcast(&r->cond);
return (void*)0;
}
void *get_fn(void *arg)
{
Result *r = (Result*)arg;
pthread_mutex_lock(&r->mutex);
r->count++;
pthread_cond_wait(&r->cond, &r->mutex);
pthread_mutex_unlock(&r->mutex);
int res = r->res;
printf("0x%lx get sum is: %d\\n", pthread_self(), res);
return (void*)0;
}
int main(void)
{
int err;
pthread_t cal, get, get1, get2;
Result r;
r.count = 0;
pthread_cond_init(&r.cond, 0);
pthread_mutex_init(&r.mutex, 0);
if((err = pthread_create(&get, 0, get_fn, (void*)&r) != 0)){
perror("pthread create error");
}
if((err = pthread_create(&get1, 0, get_fn, (void*)&r) != 0)){
perror("pthread create error");
}
if((err = pthread_create(&get2, 0, get_fn, (void*)&r) != 0)){
perror("pthread create error");
}
if((err = pthread_create(&cal, 0, set_fn, (void*)&r) != 0)){
perror("pthread create error");
}
pthread_join(cal, 0);
pthread_join(get, 0);
pthread_join(get1, 0);
pthread_join(get2, 0);
pthread_cond_destroy(&r.cond);
pthread_mutex_destroy(&r.mutex);
return 0;
}
| 1
|
#include <pthread.h>
unsigned int counter = 1;
unsigned int result = 0;
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t result_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t print_mutex = PTHREAD_MUTEX_INITIALIZER;
bool is_pandig( int* );
bool is_pandig2( int*, int* );
bool is_pandig3( int*, int*, int* );
void* worker( void* );
void main(void)
{
setvbuf(stdout, 0, _IONBF, 0);
int i;
pthread_t thr[4];
for ( i= 0; i < 4; i++ )
{
if( pthread_create( &thr[i], 0, &worker, 0 ))
{
printf("Could not create thread %d.\\n", i);
exit(-1);
}
}
for(i = 0; i < 4; i++)
{
if(pthread_join(thr[i], 0))
{
printf("Could not join thread %d.\\n", i);
exit(-1);
}
}
printf("\\nResult: %d\\n", result);
}
void* worker( void *none )
{
int theSqrt, i, j;
for( ;; )
{
pthread_mutex_lock(&counter_mutex);
if(++counter >= 500000)
{
pthread_mutex_unlock(&counter_mutex);
return;
}
unsigned int checkThis = counter;
pthread_mutex_unlock(&counter_mutex);
if( checkThis % 2500 == 0 )
{
pthread_mutex_lock(&print_mutex);
printf(".");
pthread_mutex_unlock(&print_mutex);
}
if(is_pandig(&checkThis))
{
theSqrt = sqrt(checkThis);
for( i=1; i<=theSqrt; i++ )
{
if(( checkThis % i == 0 ) && ( is_pandig2( &i, &checkThis )))
{
j=checkThis / i;
if( is_pandig3( &i, &j, &checkThis ))
{
pthread_mutex_lock(&result_mutex);
result = result + checkThis;
pthread_mutex_unlock(&result_mutex);
pthread_mutex_lock(&print_mutex);
printf("\\n%d x %d = %d", i, j, checkThis);
pthread_mutex_unlock(&print_mutex);
break;
}
}
}
}
}
}
bool is_pandig( int* testor )
{
bool test_array[10];
int i, j, k;
for( i=0; i<=9; i++ )
test_array[i] = 0;
test_array[0] = 1;
k = *testor;
while( k > 0 )
{
i = k % 10;
if( test_array[i] )
return 0;
else
test_array[i] = 1;
k = k / 10;
}
return 1;
}
bool is_pandig2( int* testor, int* testor2 )
{
bool test_array[10];
int i, j, k;
for( i=0; i<=9; i++ )
test_array[i] = 0;
test_array[0] = 1;
for( j=0; j<2; j++ )
{
if(j == 0)
k = *testor;
else
k = *testor2;
while( k > 0 )
{
i = k % 10;
if( test_array[i] )
return 0;
else
test_array[i] = 1;
k = k / 10;
}
}
return 1;
}
bool is_pandig3( int* testor, int* testor2, int* testor3 )
{
bool test_array[10];
int i, j, k;
for( i=0; i<=9; i++ )
test_array[i] = 0;
test_array[0] = 1;
for( j=0; j<3; j++ )
{
if(j == 0)
k = *testor;
else if(j == 1)
k = *testor2;
else
k = *testor3;
while( k > 0 )
{
i = k % 10;
if( test_array[i] )
return 0;
else
test_array[i] = 1;
k = k / 10;
}
}
if( test_array[1] && test_array[2] && test_array[3] && test_array[4] && test_array[5] && test_array[6] && test_array[7] && test_array[8] && test_array[9] )
{
return 1;
} else {
return 0;
}
return 1;
}
| 0
|
#include <pthread.h>
void traitantSIGINT(int num){
double pourcentageReussite;
pthread_mutex_lock(&mCptExitFaux);
pthread_mutex_lock(&mCptVoitures);
pourcentageReussite=(1-(double)cptExitFaux[0]/((double)cptVoitures[VRAI]+(double)cptVoitures[FAUX]))*100;
printf("\\nLe pourcentage de réussite est de : %.2f\\n",pourcentageReussite);
pthread_mutex_unlock(&mCptVoitures);
pthread_mutex_unlock(&mCptExitFaux);
int ligne,colonne,numCarrefour;
for(numCarrefour = 0; numCarrefour<4; numCarrefour++){
for(ligne = 0; ligne<2; ligne++){
for(colonne = 0; colonne<2; colonne++){
semctl(sem_in_out[numCarrefour][ligne][colonne], 0, IPC_RMID, 0);
}
}
}
int i;
for(i=0; i<4; i++){
shmctl(idMemPartagee[i], IPC_RMID, 0);
msgctl(msgid[i],IPC_RMID, 0);
semctl(semCptVoituresDansCarrefour[i], 0, IPC_RMID, 0);
}
shmctl(idCptExitFaux, IPC_RMID, 0);
shmctl(idCptVoitures, IPC_RMID, 0);
msgctl(msgidServeurControleur, IPC_RMID, 0);
pthread_mutex_destroy(&memPart);
pthread_mutex_destroy(&mCptVoitures);
pthread_mutex_destroy(&mCptExitFaux);
}
int main(int argc, char **argv)
{
srand(time(0));
remove("log.txt");
int i;
int numCarrefour,ligne,colonne;
for(numCarrefour = 0; numCarrefour<4; numCarrefour++){
for(ligne = 0; ligne<2; ligne++){
for(colonne = 0; colonne<2; colonne++){
sem_in_out[numCarrefour][ligne][colonne]=creerSem(ftok(argv[0], ID_PROJET+cptIdentifiant), 4);
initSem(sem_in_out[numCarrefour][ligne][colonne], 1);
cptIdentifiant++;
}
}
}
for(i=0;i<4;i++){
msgid[i]= msgget(ftok(argv[0], ID_PROJET+cptIdentifiant), IPC_CREAT | IPC_EXCL | 0666);
cptIdentifiant++;
idMemPartagee[i]=shmget(ftok(argv[0], ID_PROJET+cptIdentifiant), 8*sizeof(int), IPC_CREAT | IPC_EXCL | 0666);
cptIdentifiant++;
memoiresPartagees[i]=(int*) shmat(idMemPartagee[i], 0, 0);
semCptVoituresDansCarrefour[i]=creerSem(ftok(argv[0], ID_PROJET+cptIdentifiant), 4);
initSem(semCptVoituresDansCarrefour[i], 3);
cptIdentifiant++;
}
idCptExitFaux=shmget(ftok(argv[0], ID_PROJET+cptIdentifiant), sizeof(int), IPC_CREAT | IPC_EXCL | 0777);
cptIdentifiant++;
cptExitFaux=(int*)shmat(idCptExitFaux, 0, 0);
idCptVoitures=shmget(ftok(argv[0], ID_PROJET+cptIdentifiant), sizeof(int), IPC_CREAT | IPC_EXCL | 0777);
cptIdentifiant++;
cptVoitures=(int*)shmat(idCptVoitures, 0, 0);
msgidServeurControleur=msgget(ftok(argv[0], ID_PROJET+cptIdentifiant), IPC_CREAT | IPC_EXCL | 0666);
cptIdentifiant++;
int carrefour, numVoie;
for(carrefour = 0; carrefour<4; carrefour++){
for(numVoie = 0; numVoie<8; numVoie++){
memoiresPartagees[carrefour][numVoie]=0;
}
}
cptVoitures[0]=0;
for(i=0;i<NbVoituresGlobal;i++){
creerVoiture();
}
affichageCarrefours();
pidPere=getpid();
for(i=0;i<4;i++){
if(getpid()==pidPere){
pidCarrefour[i] = fork();
}
}
if(getpid()==pidPere){
pidServeurControleur = fork();
}
if(getpid()==pidPere){
pidAffichage = fork();
}
if(getpid()==pidPere){
pidGenerateur = fork();
}
if(pidCarrefour[0] == 0){
gestionCarrefour(0);
exit(0);
}
else if(pidCarrefour[1] == 0){
gestionCarrefour(1);
exit(0);
}
else if(pidCarrefour[2] == 0){
gestionCarrefour(2);
exit(0);
}
else if(pidCarrefour[3] == 0){
gestionCarrefour(3);
exit(0);
}
else if(pidServeurControleur == 0){
serveurControleur(idMemPartagee[0], idMemPartagee[1], idMemPartagee[2], idMemPartagee[3]);
exit(0);
}
else if(pidAffichage == 0){
while(1){
affichageCarrefours();
usleep(raffraichissementAffichage);
}
exit(0);
}
else if(pidGenerateur == 0){
while(1){
creerVoiture();
usleep(delaisNouvelleVoiture);
}
exit(0);
}
else{
struct sigaction action;
sigemptyset(&action.sa_mask);
action.sa_handler=traitantSIGINT;
sigaction(SIGINT,&action,0);
waitpid(pidCarrefour[0], 0, 0);
waitpid(pidCarrefour[1], 0, 0);
waitpid(pidCarrefour[2], 0, 0);
waitpid(pidCarrefour[3], 0, 0);
waitpid(pidGenerateur, 0, 0);
waitpid(pidAffichage, 0, 0);
waitpid(pidServeurControleur, 0, 0);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
void
prepare(void)
{
printf("preparing locks ...\\n");
pthread_mutex_lock(&lock1);
pthread_mutex_lock(&lock2);
}
void
child(void)
{
printf("child unlocking locks ...\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void
parent(void)
{
printf("parent unlocking locks ...\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void *
thr_fn(void *arg)
{
printf("thread started ...\\n");
pause();
return 0;
}
int
main(void)
{
int err;
pid_t pid;
pthread_t tid;
if((err = pthread_atfork(prepare,parent,child)) != 0)
err_exit(err,"can't install fork handlers");
err = pthread_create(&tid,0,thr_fn,0);
if(err != 0)
err_exit(err,"can't create thread");
sleep(2);
printf("parent about to fork ...\\n");
if((pid = fork()) < 0)
err_quit("fork failed");
else if(pid == 0)
printf("child returned from fork\\n");
else
printf("parent returned from fork\\n");
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_count = 1;
fp->f_id = id;
if (pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return(0);
}
idx = (((unsigned long)id) %29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
}
return(fp);
}
void foo_hold(struct foo *fp)
{
pthread_mutex_lock(&hashlock);
fp->f_count++;
pthread_mutex_unlock(&hashlock);
}
struct foo *foo_find(int id)
{
struct foo *fp;
pthread_mutex_lock(&hashlock);
for (fp = fh[(((unsigned long)id) %29)]; fp != 0; fp = fp->f_next) {
if (fp->f_id == id) {
fp->f_count++;
break;
}
}
pthread_mutex_unlock(&hashlock);
return(fp);
}
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(&hashlock);
}
}
| 1
|
#include <pthread.h>
double delta=1;
int thread_count = -1;
double area=0;
pthread_mutex_t mut;
struct my_thread_rank
{
int rank;
};
int get_max_threads()
{
int max_string_size = 10;
FILE *fp;
char* ret;
int max = -1;
char str[max_string_size];
fp = fopen("/proc/sys/kernel/threads-max","r");
if(0 == fp)
{
printf("error opening file thread max\\n");
}
else
{
ret = fgets(str, max_string_size, fp);
if (0 == ret)
{
printf("file read error\\n");
}
else
{
max = atoi(str);
}
}
int retur = fclose(fp);
if (0!=retur)
{
printf("file close error\\n");
}
return max;
}
double trap_area(double y1,double y2,double delta)
{
return .5*(y1+y2)*delta;
}
double eval_function(double x)
{
return sqrt(1-x*x);
}
void* my_thread(void * data)
{
struct my_thread_rank *info = data;
int my_rank = info ->rank;
double lower_bound=my_rank * 1/(double)thread_count;
double upper_bound=(1+my_rank) * 1/(double)thread_count;
double y1;
double y2;
double my_area = 0.0;
double i;
y2 = eval_function(lower_bound);
for(i=lower_bound+delta;i<=upper_bound;i+=delta)
{
y1=y2;
y2=eval_function(i);
my_area += trap_area(y1,y2,delta);
}
pthread_mutex_lock(&mut);
area+=my_area;
pthread_mutex_unlock(&mut);
free(info);
return 0;
}
int main(int argc, char *argv[])
{
int i, ret;
int max_threads;
pthread_t* threads;
if (3 != argc)
{
printf("I want 2 positional arguments : thread count & the delta of the trap(ex .00001)\\n");
return 1;
}
max_threads = get_max_threads();
if(1 > max_threads)
{
printf("Are you on a posix complicant system?\\n");
return 2;
}
thread_count = atoi(argv[1]);
if(1 > thread_count || thread_count>max_threads)
{
printf("Must supply an integer thread count between 1 and your system's max inclusivly\\n");
return 3;
}
delta = atof(argv[2]);
if(0 > delta || 1 < delta)
{
printf("Supply a delta between 1 and zero\\n");
return 4;
}
if(0!=pthread_mutex_init(&mut, 0))
{
printf("mutex creation fail\\n");
return 5;
}
threads = malloc(thread_count * sizeof(pthread_t));
if (0 == threads)
{
printf("pthread malloc failure\\n");
return 6;
}
for(i=0;i<thread_count;i++)
{
struct my_thread_rank *info = malloc(sizeof(struct my_thread_rank));
if(0==info)
{
printf("strut malloc failure");
return 7;
}
info->rank = i;
ret = pthread_create(&threads[i], 0, my_thread,info);
if(0!=ret)
{
printf("thread creation fail\\n");
return 8;
}
}
for(i=0;i<thread_count;i++)
{
ret = pthread_join(threads[i],0);
if(0!=ret)
{
printf("thread join fail\\n");
return 9;
}
}
ret = pthread_mutex_destroy(&mut);
if(0!=ret)
{
printf("mutex destroy fail\\n");
return 10;
}
free(threads);
printf("Your trapezoidal estimation of PI: \\t%.15f\\n",area*4);
printf("math.h's macro for PI: \\t\\t\\t%.15f\\n", M_PI);
return 0;
}
| 0
|
#include <pthread.h>
void* producer(void* arg);
void* consumer(void* arg);
int buffer[100];
int count = 0;
int input = -1;
int output = -1;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t space_required = PTHREAD_COND_INITIALIZER;
pthread_cond_t data_required = PTHREAD_COND_INITIALIZER;
int main(int argc, char* argv[], char* envp[]){
pthread_t threads[2];
pthread_create(&threads[0], 0, producer, 0);
pthread_create(&threads[1], 0, consumer, 0);
pthread_join(threads[0], 0);
pthread_join(threads[1], 0);
pthread_cond_destroy(&space_required);
pthread_cond_destroy(&data_required);
pthread_exit(0);
printf("main ends!\\n");
return 1;
}
void* consumer(void* arg) {
int i, data = 0;
for (int i = 0; i <= 1000; i++) {
printf(" ** the consumer gets mutex_lock.\\n");
pthread_mutex_lock(&mutex);
printf(" ** consumer input the critical section.\\n");
if ( 1000 == i ) {
printf(" ** finally, the consumer throws signal to wake up producer thread sleeping!!\\n");
pthread_cond_signal(&space_required);
pthread_mutex_unlock(&mutex);
printf("\\n\\n");
} else {
if (count == 0) {
printf(" ** the consumer throws signal : space_required to consume to notify that the consumer has completely consumed datas..\\n");
pthread_cond_signal(&space_required);
printf(" ** consumer blocked, waiting for signal until datas are all produced in the buffer. now, buffer is empty..\\n");
pthread_cond_wait(&data_required, &mutex);
}
output+=1;
output = output % 100;
data = buffer[output];
count-=1;
pthread_mutex_unlock(&mutex);
printf(" ** the consumer unlocks mutex!\\n");
printf(" the consumer is consuming data : %d\\n", data);
printf("\\n\\n");
}
}
}
void* producer(void* arg) {
int i = 0;
for (int i = 0; i <= 1000; i++) {
printf("the producer is producing the data : %d\\n", i);
printf("** the producer gets mutex_lock.\\n");
pthread_mutex_lock(&mutex);
printf("** producer input the critical section.");
printf("producer count : %d\\n", count);
if (count == 100) {
printf("producer in!\\n");
printf("** producer throws signal : data_required to notify consumer that producer has completely produced spaces to consume.\\n");
pthread_cond_signal(&data_required);
printf("** producer blocked, waiting for signal until buffer is all consumed.. buffer size is full now.\\n");
pthread_cond_wait(&space_required, &mutex);
}
input+=1;
input = input % 100;
buffer[input] = i;
count+=1;
pthread_mutex_unlock(&mutex);
printf("** the producer unlocks mutex!\\n");
printf("\\n\\n");
}
}
| 1
|
#include <pthread.h>
struct virgo_address
{
int node_id;
struct hostport* hstprt;
void* addr;
};
struct hostport
{
char* hostip;
int port;
};
void virgo_systemcalls(pthread_mutex_t* lock,int process);
int main(int argc, char* argv[])
{
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutexattr_t mattr;
pthread_mutex_init(&lock,0);
pthread_mutexattr_init(&mattr);
pthread_mutexattr_setpshared(&mattr,PTHREAD_PROCESS_SHARED);
int pret=fork();
virgo_systemcalls(&lock,pret);
}
void virgo_systemcalls(pthread_mutex_t* lock,int process)
{
int iterations=0;
while(iterations++ < 100)
{
pthread_mutex_lock(lock);
printf("process id: %d\\n",process);
unsigned long long virgo_unique_id;
syscall(549,100,&virgo_unique_id);
printf("vuid malloc-ed : %llu \\n",virgo_unique_id);
char set_data[256];
if(process==0)
strcpy(set_data,"DataSet_process1");
else
strcpy(set_data,"DataSet_process2");
printf("virgo_set() data to set for vuid %llu : %s\\n",virgo_unique_id,set_data);
long set_ret=syscall(550,virgo_unique_id,set_data);
char get_data[256];
long get_ret=syscall(551,virgo_unique_id,get_data);
printf("virgo_get() data for vuid %llu : %s\\n",virgo_unique_id,get_data);
long free_ret=syscall(552,virgo_unique_id);
printf("vuid freed : %llu \\n",virgo_unique_id);
pthread_mutex_unlock(lock);
}
}
| 0
|
#include <pthread.h>
pthread_t main_thread;
pthread_attr_t detached_attr;
pthread_attr_t joinable_attr;
int n_threads = 50;
pthread_mutex_t dthrds_create_mutex;
void
create_thread (pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg)
{
pthread_t child;
int rc;
while ((rc = pthread_create (&child, attr, start_routine, arg)) != 0)
{
fprintf (stderr, "unexpected error from pthread_create: %s (%d)\\n",
strerror (rc), rc);
sleep (1);
}
}
void
break_fn (void)
{
}
struct thread_arg
{
pthread_t parent;
};
void *
joinable_fn (void *arg)
{
struct thread_arg *p = arg;
pthread_setname_np (pthread_self (), "joinable");
if (p->parent != main_thread)
assert (pthread_join (p->parent, 0) == 0);
p->parent = pthread_self ();
create_thread (&joinable_attr, joinable_fn, p);
break_fn ();
return 0;
}
void *
detached_fn (void *arg)
{
pthread_setname_np (pthread_self (), "detached");
pthread_mutex_lock (&dthrds_create_mutex);
create_thread (&detached_attr, detached_fn, 0);
break_fn ();
pthread_mutex_unlock (&dthrds_create_mutex);
return 0;
}
int
main (int argc, char *argv[])
{
int i;
if (argc > 1)
n_threads = atoi (argv[1]);
pthread_mutex_init (&dthrds_create_mutex, 0);
pthread_attr_init (&detached_attr);
pthread_attr_setdetachstate (&detached_attr, PTHREAD_CREATE_DETACHED);
pthread_attr_init (&joinable_attr);
pthread_attr_setdetachstate (&joinable_attr, PTHREAD_CREATE_JOINABLE);
main_thread = pthread_self ();
for (i = 0; i < n_threads; ++i)
{
struct thread_arg *p;
p = malloc (sizeof *p);
p->parent = main_thread;
create_thread (&joinable_attr, joinable_fn, p);
create_thread (&detached_attr, detached_fn, 0);
}
sleep (180);
return 0;
}
| 1
|
#include <pthread.h>
void* data[100];
int size;
} Stack;
void Stack_Init(Stack *S)
{
S = (Stack *)malloc(sizeof(S));
S->size = 0;
}
int Stack_Empty(Stack *S){
return S->size;
}
void* Stack_Top(Stack *S)
{
if (S->size == 0) {
fprintf(stderr, "Error: stack empty\\n");
return 0;
}
return S->data[S->size-1];
}
void Stack_Push(Stack *S, void *d)
{
if (S->size < 100)
S->data[S->size++] = d;
else
fprintf(stderr, "Error: stack full\\n");
}
void Stack_Pop(Stack *S)
{
if (S->size == 0)
fprintf(stderr, "Error: stack empty\\n");
else
S->size--;
}
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
Ingredientes *ingr;
Pizza *pizza;
int fin;
} Orden;
Stack *cola;
pthread_t operador;
Orden *ordenar(Ingredientes *ingr){
Orden *o = malloc(sizeof(*o));
o->ingr = ingr;
o->fin = 0;
printf("agregar a cola\\n");
pthread_mutex_lock(&m);
Stack_Push(cola,(void*)o);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&m);
return o;
}
void *ord(void *p){
ordenar((Ingredientes *)p);
return 0;
}
Pizza *pizzaCruda(Ingredientes *ingr){
return (Pizza*)ingr;
}
void hornear(Pizza *pizzas[]){
printf("Hornear pizzas");
}
void *pizzeria(void *p){
pthread_mutex_lock(&m);
for(;;){
Pizza *pizzas[4];
Orden *ords[4];
printf("Cola: %d\\n", Stack_Empty(cola));
while(Stack_Empty(cola))
printf("Cola: %d\\n", Stack_Empty(cola));
pthread_cond_wait(&cond, &m);
int i = 0, j;
while(!Stack_Empty(cola) && i<4){
ords[i] = (Orden *)Stack_Top(cola);
pizzas[i] = pizzaCruda(ords[i]->ingr);
i++;
}
pthread_mutex_unlock(&m);
hornear(pizzas);
pthread_mutex_lock(&m);
for(j = 0;j<i;j++){
ords[i]->fin=1;
ords[i]->pizza = pizzas[i];
}
pthread_cond_broadcast(&cond);
}
}
Pizza *retirar(Orden *o){
pthread_mutex_lock(&m);
while (!o->fin)
pthread_cond_wait(&cond,&m);
pthread_mutex_unlock(&m);
return o->pizza;
}
void initHorno(){
Stack_Init(cola);
pthread_create(&operador, 0, pizzeria, 0);
}
int main(int argc, char *argv[]){
initHorno();
pthread_t t1;
pthread_t t2;
pthread_create(&t1,0,ord,(void *)'i');
pthread_create(&t2,0,ord,(void *)'a');
pthread_join(t1,0);
pthread_join(t2,0);
}
| 0
|
#include <pthread.h>
pthread_cond_t cond_empty, cond_full;
pthread_mutex_t mutex;
int count = 0, in = 0, out = 0;
int contadorConsumo = 0;
int buffer[3];
void *produtor(void *arg)
{
while (1)
{
pthread_mutex_lock(&mutex);
while (count == 3)
pthread_cond_wait(&cond_empty, &mutex);
buffer[in] = rand()%100;
count++;
printf("Produzindo buffer[%d] = %d\\n", in, buffer[in]);
in = (in + 1) % 3;
pthread_cond_signal(&cond_full);
pthread_mutex_unlock(&mutex);
}
}
void *consumidor(void *arg)
{
int my_task;
while (1)
{
pthread_mutex_lock(&mutex);
while (count == 0)
pthread_cond_wait(&cond_full, &mutex);
my_task = buffer[out];
count--;
printf("Consumindo buffer[%d] = %d\\n", out, my_task);
out = (out + 1) % 3;
contadorConsumo++;
if (contadorConsumo == 100000)
exit(0);
pthread_cond_signal(&cond_empty);
pthread_mutex_unlock(&mutex);
}
}
int main(int argc, char *argv[])
{
pthread_t prod1, prod2, prod3, cons;
pthread_cond_init(&cond_empty, 0);
pthread_cond_init(&cond_full, 0);
pthread_mutex_init(&mutex, 0);
pthread_create(&prod1, 0, (void *)produtor, 0);
pthread_create(&prod2, 0, (void *)produtor, 0);
pthread_create(&prod3, 0, (void *)produtor, 0);
pthread_create(&cons, 0, (void *)consumidor, 0);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int nb_philo;
int nb_Grain_De_Riz = 5;
pthread_mutex_t * mutexs;
sem_t sem;
struct philo
{
int identifiant;
};
void initialisation(){
srand (time (0));
sem_init(&sem,0,nb_philo-1);
mutexs = malloc(nb_philo*sizeof(pthread_mutex_t));
for(int i = 0; i<nb_philo;i++){
pthread_mutex_init(&mutexs[i], 0);
}
}
void parler(int id){
printf("Le philosophe %d philosophe ! :)\\n",id);
}
void prendre_baguettes(int id){
sem_wait(&sem);
pthread_mutex_lock(&mutexs[id]);
pthread_mutex_lock(&mutexs[(id+1)%nb_philo]);
printf("Le philosophe %d prend les baguettes %d\\n",id, (id+1)%nb_philo);
}
void manger(int id){
printf("Le philosophe %d mange ! Avec les baguettes %d\\n",id, (id+1)%nb_philo);
}
void rendre_baguettes(int id){
printf("Le philosophe %d a rendu les baguettes %d\\n",id, (id+1)%nb_philo);
pthread_mutex_unlock(&mutexs[id]);
pthread_mutex_unlock(&mutexs[(id+1)%nb_philo]);
sem_post(&sem);
}
void philosophe(void * args){
struct philo* info = (struct philo*) args;
int identifiant = info->identifiant;
for (int i=0; i<nb_Grain_De_Riz ;i++){
parler(identifiant);
prendre_baguettes(identifiant);
manger(identifiant);
rendre_baguettes(identifiant);
}
}
int main (int argc, char **argv){
if(argc != 2){
printf("Utilisation : ./version1 <nb_philosophes>\\n");
return 1;
}
nb_philo = atoi(argv[1]);
initialisation();
struct philo* philo;
pthread_t *tids = malloc (nb_philo * sizeof(pthread_t));
int i;
for(i = 0; i < nb_philo; i++){
philo = (struct philo *) malloc(sizeof(struct philo));
philo->identifiant = i;
pthread_create(&tids[i], 0, (void*)philosophe, philo);
}
for(i = 0;i< nb_philo;i++)
pthread_join(tids[i],0);
return 0;
}
| 0
|
#include <pthread.h>
struct link{
struct link *next;
char *value;
};
int no_of_links = 0;
struct link *head_of_queue, *tail_of_queue;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int add_to_queue(char *value)
{
pthread_mutex_lock(&lock);
if (no_of_links == 0) {
tail_of_queue = (struct link*) malloc(sizeof(struct link));
tail_of_queue->next = 0;
head_of_queue = tail_of_queue;
} else {
struct link* tmp_link = (struct link*) malloc(sizeof(struct link));
tmp_link->next = tail_of_queue;
tail_of_queue = tmp_link;
}
tail_of_queue->value = (char*) malloc(strlen(value) + 1);
strcpy(tail_of_queue->value, value);
no_of_links++;
pthread_mutex_unlock(&lock);
return 0;
}
void print_queue(int free_mem)
{
int i = 0;
struct link *tmp_link = tail_of_queue;
while(i < no_of_links) {
printf("%d: \\t- %s\\n", i+1, tmp_link->value);
if (free_mem)
free(tmp_link->value);
struct link *to_free = tmp_link;
tmp_link = tmp_link->next;
if (free_mem)
free(to_free);
i++;
}
}
void *thread_function(void *para)
{
char tmp_str[100];
int id = *((int*) para);
pthread_t tid = pthread_self();
int j;
for (j = 0; j < 3; j++) {
sprintf(tmp_str, "Thread %d (%d) talking.", id, (int) tid);
add_to_queue(tmp_str);
}
return 0;
}
int main()
{
pthread_t t0, t1, t2;
int t0id = 0, t0rv = 9;
int t1id = 1, t1rv = 8;
int t2id = 2, t2rv = 7;
if (pthread_create(&t0, 0, thread_function, (void*) &t0id) == -1)
puts("Creation of thread t0 failed\\n");
if (pthread_create(&t1, 0, thread_function, (void*) &t1id) == -1)
puts("Creation of thread t1 failed\\n");
if (pthread_create(&t2, 0, thread_function, (void*) &t2id) == -1)
puts("Creation of thread t2 failed\\n");
pthread_join(t0, (void**) &t0rv);
pthread_join(t1, (void**) &t1rv);
pthread_join(t2, (void**) &t2rv);
printf("All worker threads has returned: %d, %d, %d\\n", t0rv, t1rv, t2rv);
print_queue(1);
return 0;
}
| 1
|
#include <pthread.h>
struct addict *init_addict(unsigned int time, unsigned int cost,
struct server *server, struct server *next)
{
struct addict *addict = malloc(sizeof(struct addict));
check(!addict, out);
addict->order_time = time;
addict->order_cost = cost;
addict->caffeinated = 0;
addict->server = server;
addict->next = next;
out:
return addict;
}
void get_coffee(struct addict *addict)
{
long time;
check(!addict, exit);
fifo_mutex_lock(&addict->server->lock);
sem_wait(&addict->server->service_sem);
fifo_mutex_unlock(&addict->server->lock);
serve(addict);
if(!addict->next)
pay(addict);
sem_post(&addict->server->service_sem);
if(addict->next) {
fifo_mutex_lock(&addict->next->lock);
sem_wait(&addict->next->service_sem);
fifo_mutex_unlock(&addict->next->lock);
pay(addict);
sem_post(&addict->next->service_sem);
}
exit:
gettimeofday(&addict->end, 0);
time = timer_us(&addict->start, &addict->end);
switch(addict->order_cost) {
case ACOST_SIMPLE:
pthread_mutex_lock(&simple_count.count_mutex);
simple_times[simple_count.val++] = time;
pthread_mutex_unlock(&simple_count.count_mutex);
break;
case ACOST_COMPLEX:
pthread_mutex_lock(&complex_count.count_mutex);
complex_times[complex_count.val++] = time;
pthread_mutex_unlock(&complex_count.count_mutex);
default:
break;
}
free(addict);
count_dec(running_threads, 1);
pthread_mutex_lock(&running_threads.count_mutex);
if(running_threads.val == 0)
pthread_cond_broadcast(&running_threads.cond);
pthread_mutex_unlock(&running_threads.count_mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
void process_data(char *buffer, int bufferSizeInBytes);
int get_external_data(char *buffer, int bufferSizeInBytes);
int min(int a, int b) { return a > b ? b : a; }
int get_external_data(char *buffer, int bufferSizeInBytes)
{
int status;
int val;
char srcString[] = "0123456789abcdefghijklmnopqrstuvwxyxABCDEFGHIJKLMNOPQRSTUVWXYZ";
val = (int) (random() % min(bufferSizeInBytes, 62));
if (bufferSizeInBytes < val)
return (-1);
strncpy(buffer, srcString, val);
return val;
}
void process_data(char *buffer, int bufferSizeInBytes)
{
int i;
if(buffer)
{
printf("thread %i - ", pthread_self());
for(i=0; i<bufferSizeInBytes; i++)
{
printf("%c", buffer[i]);
}
printf("\\n");
memset(buffer, 0, bufferSizeInBytes);
}
else
printf("error in process data - %i\\n", pthread_self());
return;
}
static char *buffer[8][62] = { { 0 } };
static int buffer_wp = 0;
static int buffer_rp = 0;
static pthread_mutex_t buffer_mutex = { { 0 } };
static pthread_cond_t buffer_cond_avail_r = { { 0 } };
static pthread_cond_t buffer_cond_avail_w = { { 0 } };
void *reader_thread(void *arg) {
pthread_mutex_lock(&buffer_mutex);
while (!(buffer_rp < buffer_wp)) {
pthread_cond_wait(&buffer_cond_avail_r, &buffer_mutex);
}
process_data((char *) buffer[buffer_rp++ % 8],62);
pthread_cond_signal(&buffer_cond_avail_w);
pthread_mutex_unlock(&buffer_mutex);
return 0;
}
void *writer_thread(void *arg) {
pthread_mutex_lock(&buffer_mutex);
while (!(buffer_wp - buffer_rp < 8)) {
pthread_cond_wait(&buffer_cond_avail_w, &buffer_mutex);
}
get_external_data((char *) buffer[buffer_wp++ % 8], 62 -1);
pthread_cond_signal(&buffer_cond_avail_r);
pthread_mutex_unlock(&buffer_mutex);
return 0;
}
int main(int argc, char **argv) {
int i,rc;
pthread_t writer_threads[20] = { 0 };
pthread_t reader_threads[10] = { 0 };
pthread_mutex_init(&buffer_mutex, 0);
pthread_cond_init(&buffer_cond_avail_r, 0);
pthread_cond_init(&buffer_cond_avail_w, 0);
for (i = 0; i < 20; i++) {
rc=pthread_create(&writer_threads[i], 0, writer_thread, 0);
if(rc){
printf("ERROR");
exit(-1);
}
}
for (i = 0; i < 10; i++) {
rc=pthread_create(&reader_threads[i], 0, reader_thread, 0);
if(rc){
printf("ERROR");
exit(-1);
}
}
for (i = 0; i < 20; i++) {
pthread_join(writer_threads[i], 0);
}
for (i = 0; i < 10; i++) {
pthread_join(reader_threads[i], 0);
}
pthread_mutex_destroy(&buffer_mutex);
pthread_cond_destroy(&buffer_cond_avail_r);
pthread_cond_destroy(&buffer_cond_avail_w);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
static void* collector (void* arg){
int fd_skt, i, j;
struct sockaddr_un sockAdd;
char string[10];
planet_t* p;
strncpy(sockAdd.sun_path, SOCKNAME, UNIX_PATH_MAX);
sockAdd.sun_family=AF_UNIX;
fd_skt = socket(AF_UNIX, SOCK_STREAM, 0);
if(fd_skt == -1){
perror("Errore socket client");
}
while( connect(fd_skt, (struct sockaddr*) &sockAdd, sizeof(sockAdd)) == -1){
if( errno == ENOENT ){
usleep(250000);
}
else{
perror("Errore connessione socket client");
close_all = TRUE;
return 0;
}
}
p = simulazione->plan;
while( termine_elaborazione == FALSE ){
pthread_mutex_lock(&stampa_mux);
while(!puoi_stampare){
pthread_cond_wait(&stampa_pronta, &stampa_mux);
}
pthread_mutex_unlock(&stampa_mux);
write(fd_skt, "A", 1);
sprintf(string, "%d\\n", p->nrow);
write(fd_skt, string, strlen(string));
sprintf(string, "%d\\n", p->ncol);
write(fd_skt, string, strlen(string));
for(i=0;i<p->nrow; i++){
for(j=0; j<p->ncol-1;j++){
sprintf(string, "%c ", cell_to_char((p->w)[i][j]));
write(fd_skt, string, strlen(string));
}
sprintf(string, "%c\\n", cell_to_char((p->w)[i][j]));
write(fd_skt, string, strlen(string));
}
pthread_mutex_lock(&stampa_mux);
puoi_stampare = FALSE;
puoi_procedere = TRUE;
pthread_cond_signal(&stampa_effettuata);
pthread_mutex_unlock(&stampa_mux);
}
close(fd_skt);
return 0;
}
int start_collector(){
int fallito;
fallito = pthread_create(&collector_id, 0, &collector, 0);
if (fallito){
perror("Errore nella creazione del Thread Collector");
return -1;
}
return 0;
}
| 0
|
#include <pthread.h>
int main(int argc, char *argv[])
{
int err;
struct timespec tout;
struct tm *tmp = 0;
char buf[64] = "";
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&lock);
printf("mutex is locked\\n");
clock_gettime(CLOCK_REALTIME, &tout);
tmp = localtime(&tout.tv_sec);
strftime(buf, sizeof(buf), "%r", tmp);
printf("current time is %s\\n", buf);
tout.tv_sec += 10;
err = pthread_mutex_timedlock(&lock, &tout);
clock_gettime(CLOCK_REALTIME, &tout);
tmp = localtime(&tout.tv_sec);
strftime(buf, sizeof(buf), "%r", tmp);
printf("the time is now %s\\n", buf);
if (err == 0)
{
printf("mutex locked again\\n");
}
else
{
printf("can't lock mutex again: %s\\n", strerror(err));
}
pthread_mutex_unlock(&lock);
return 0;
}
| 1
|
#include <pthread.h>
struct thread_global{
char global_buf[188*7];
int size_var;
int flag;
};
struct ts_data{
char addr_buf[32];
int port_no;
int soid;
double bit_rate;
};
struct ts_send{
char addr_buf_1[32];
int port_no_1;
int soid_1;
double bit_rate_1;
};
struct thread_global info;
struct ts_data tdata;
struct ts_send tsend;
pthread_t tid_1, tid_2;
pthread_mutex_t m_1,m_2;
void *recv_data(void *p)
{
int sock_id;
sock_id = socket(AF_INET,SOCK_DGRAM, 0);
if ( sock_id < 0 ){
perror("socket");
return;
}
struct sockaddr_in addr;
char local_buf[188*7];
int len , clen;
clen = sizeof(addr);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(tdata.addr_buf);
addr.sin_port = htons(tdata.port_no);
struct ip_mreq mgroup;
memset((char *) &mgroup, 0, sizeof(mgroup));
mgroup.imr_multiaddr.s_addr = inet_addr(tdata.addr_buf);
mgroup.imr_interface.s_addr = INADDR_ANY;
printf("recv ip = %s;recv port = %d || send ip=%s;send port = %d \\n",tdata.addr_buf,tdata.port_no,tsend.addr_buf_1,tsend.port_no_1);
int i;
int pack_cnt = 0;
int reuse = 1;
if (setsockopt(sock_id, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse)) < 0) {
perror("setsockopt() SO_REUSEADDR: error ");
}
if (bind(sock_id, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
perror("bind(): error");
close(sock_id);
return 0;
}
if (setsockopt(sock_id, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&mgroup, sizeof(mgroup)) < 0) {
perror("setsockopt() IPPROTO_IP: error ");
close(sock_id);
return 0;
}
while(1) {
len = recvfrom(sock_id, local_buf, 188*7 , 0, (struct sockaddr *) &addr,&clen);
if (len < 0) {
perror("recvfrom(): error ");
return ;
}
else {
pthread_mutex_lock(&m_1);
info.size_var = len;
for ( i = 0 ; i < 188*7 ; i+=188){
if ( local_buf[i] == 0x47)
pack_cnt++;
else
fprintf(stderr,"PACK IS INVALID: pkt- %d\\n",pack_cnt);
}
printf("pack_cnt is %d\\n",pack_cnt);
memcpy(info.global_buf,local_buf,len);
memset(local_buf, 0 ,len);
pthread_mutex_unlock(&m_2);
}
}
}
void *send_data(void *p)
{
int sock_id_1;
sock_id_1 = socket(AF_INET,SOCK_DGRAM, 0);
if ( sock_id_1 < 0 ){
perror("socket");
return;
}
struct sockaddr_in addr;
char copy_buf[188*7];
int len;
int clen;
int sent;
clen = sizeof(addr);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(tsend.addr_buf_1);
addr.sin_port = htons(tsend.port_no_1);
while(1){
pthread_mutex_lock(&m_2);
memcpy(copy_buf, info.global_buf, info.size_var);
sent = sendto(sock_id_1, copy_buf, info.size_var, 0 ,(struct sockaddr *)&addr, sizeof(struct sockaddr_in));
if(sent < 0){
perror("sendto");
return;
}
else
memset(copy_buf, 0 ,sent);
pthread_mutex_unlock(&m_1);
}
}
int main(int argc , char **argv)
{
if(argc != 5){
fprintf(stderr,"%s <IP_ADDR_RECV> <PORT_NO_RECV> <IP_ADDR_SEND> <PORT_NO_SEND > <BIT_RATE>",argv[0]);
printf("\\n");
return;
}
strncpy(tdata.addr_buf,argv[1],strlen(argv[1]));
tdata.port_no = atoi(argv[2]);
strncpy(tsend.addr_buf_1,argv[3],strlen(argv[1]));
tsend.port_no_1 = atoi(argv[4]);
pthread_create(&tid_1,0,recv_data,0);
pthread_create(&tid_1,0,send_data,0);
pthread_join(tid_1,0);
pthread_join(tid_2,0);
pthread_mutex_init(&m_1,0);
pthread_mutex_init(&m_2,0);
}
| 0
|
#include <pthread.h>
int
xshmfence_trigger(struct xshmfence *f) {
pthread_mutex_lock(&f->lock);
if (f->value == 0) {
f->value = 1;
if (f->waiting) {
f->waiting = 0;
pthread_cond_broadcast(&f->wakeup);
}
}
pthread_mutex_unlock(&f->lock);
return 0;
}
int
xshmfence_await(struct xshmfence *f) {
pthread_mutex_lock(&f->lock);
while (f->value == 0) {
f->waiting = 1;
pthread_cond_wait(&f->wakeup, &f->lock);
}
pthread_mutex_unlock(&f->lock);
return 0;
}
int
xshmfence_query(struct xshmfence *f) {
int value;
pthread_mutex_lock(&f->lock);
value = f->value;
pthread_mutex_unlock(&f->lock);
return value;
}
void
xshmfence_reset(struct xshmfence *f) {
pthread_mutex_lock(&f->lock);
f->value = 0;
pthread_mutex_unlock(&f->lock);
}
void
xshmfence_init(int fd)
{
struct xshmfence *f = xshmfence_map_shm(fd);
pthread_mutexattr_t mutex_attr;
pthread_condattr_t cond_attr;
if (!f)
return;
pthread_mutexattr_init(&mutex_attr);
pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&f->lock, &mutex_attr);
pthread_condattr_init(&cond_attr);
pthread_condattr_setpshared(&cond_attr, PTHREAD_PROCESS_SHARED);
pthread_cond_init(&f->wakeup, &cond_attr);
f->value = 0;
f->waiting = 0;
xshmfence_unmap_shm(f);
}
| 1
|
#include <pthread.h>
double a, b, ht,total;
pthread_mutex_t mutex;
int thread_size, n, interval;
double f(double x)
{
double func;
func=x*x;
return func;
}
double Trap (double point_a,double point_b,int trap_count,double length)
{
double value, x;
value = (f(point_a)+ f(point_b))/2.0;
for (int i = 1; i <= trap_count-1 ; i++)
{
x=point_a + (i * length);
value += f(x);
}
return (length*value);
}
void *Trapezoidal(void* rank) {
long my_rank = (long) rank;
double point_a,point_b,value;
point_a = a + my_rank*interval*ht;
point_b = point_a + interval*ht;
value=Trap(point_a, point_b, interval, ht);
pthread_mutex_lock(&mutex);
total += value;
pthread_mutex_unlock(&mutex);
return 0;
}
int main(int argc, char** argv)
{
pthread_t* thread_handles;
thread_size = strtol(argv[1], 0, 10);
printf("Enter a, b and n\\n");
scanf("%lf %lf %d", &a, &b, &n);
ht = (b-a)/n;
interval = n/thread_size;
thread_handles = malloc (thread_size*sizeof(pthread_t));
pthread_mutex_init(&mutex, 0);
for (long i = 0; i < thread_size; i++)
{
pthread_create(&thread_handles[i], 0, Trapezoidal, (void*) i);
}
for (long i = 0; i < thread_size; i++)
{
pthread_join(thread_handles[i], 0);
}
printf("With n = %d trapezoids, from %f to %f = %19.15e\\n", n,a,b,total);
pthread_mutex_destroy(&mutex);
free(thread_handles);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t forks[5] ;
void *sim(void *p)
{
int i = (int)p;
while(1)
{
printf("Philosopher %d is hungry\\n",i);
if(i == 4)
{
pthread_mutex_lock(&forks[0]);
printf("Philosopher %d taking right fork\\n",i);
sleep(1);
if(pthread_mutex_trylock(&forks[4]))
{
pthread_mutex_unlock(&forks[0]);
printf("Philosopher %d cannot get left fork and hence is returning right fork\\n",i);
}
else
{
printf("Philosopher %d taking left fork\\n",i);
sleep(1);
printf("\\n\\n\\t\\t\\t\\tPhilosopher %d eating\\n\\n",i);
sleep(1);
pthread_mutex_unlock(&forks[0]);
printf("Philosopher %d returning right fork\\n",i);
pthread_mutex_unlock(&forks[4]);
printf("Philosopher %d returning left fork\\n",i);
printf("Philosopher %d is thinking\\n",i);
sleep(1);
}
}
else
{
pthread_mutex_lock(&forks[i]);
printf("Philosopher %d taking left fork\\n",i);
sleep(1);
if(pthread_mutex_trylock(&forks[(i+1)%5]))
{
pthread_mutex_unlock(&forks[i]);
printf("Philosopher %d cant get right fork and is hence returning left fork\\n",i);
}
else
{
printf("Philosopher %d taking right fork\\n",i);
sleep(1);
printf("\\n\\n\\t\\t\\t\\tPhilosopher %d eating\\n\\n",i);
sleep(1);
pthread_mutex_unlock(&forks[i]);
sleep(1);
printf("Philosopher %d returning left fork\\n",i);
pthread_mutex_unlock(&forks[(i+1)%5]);
printf("Philosopher %d returning right fork\\n",i);
printf("Philosopher %d is thinking\\n",i);
sleep(1);
}
}
}
}
int main()
{
int i;
pthread_t philosopher[5];
for(i=0;i<5;++i)
{
pthread_mutex_unlock(&forks[i]);
}
pthread_create(&philosopher[i],0,sim, (void *)0);
sleep(1);
pthread_create(&philosopher[i],0,sim, (void *)1);
sleep(1);
pthread_create(&philosopher[i],0,sim, (void *)2);
sleep(1);
pthread_create(&philosopher[i],0,sim, (void *)3);
sleep(1);
pthread_create(&philosopher[i],0,sim, (void *)4);
sleep(1);
pthread_join(philosopher[0],0);
pthread_join(philosopher[1],0);
pthread_join(philosopher[2],0);
pthread_join(philosopher[3],0);
pthread_join(philosopher[4],0);
return 0;
}
| 1
|
#include <pthread.h>
struct global_data{
int count;
pthread_mutex_t mtx;
sem_t sem_a;
sem_t sem_b;
};
void * task_a(void * ctx)
{
struct global_data *d = ctx;
int i;
printf("started task_a\\n");
for(i=0; i < d->count; ++i){
sem_wait(&d->sem_a);
pthread_mutex_lock(&d->mtx);
printf("task_a: %d\\n",i);
sem_post(&d->sem_b);
pthread_mutex_unlock(&d->mtx);
}
return 0;
}
void * task_b(void * ctx)
{
struct global_data *d = ctx;
int i;
printf("started task_b\\n");
for(i=0; i < d->count; ++i){
sem_wait(&d->sem_b);
pthread_mutex_lock(&d->mtx);
printf("task_b: %d\\n",i);
sem_post(&d->sem_a);
pthread_mutex_unlock(&d->mtx);
}
return 0;
}
int global_data_init(struct global_data *d)
{
d->count = 10;
pthread_mutex_init(&d->mtx, 0);
if(sem_init(&d->sem_a, 0, 0)){
return 1;
}
if(sem_init(&d->sem_b, 0, 0)){
return 1;
}
return 0;
}
int main()
{
struct global_data data;
pthread_t thread_a;
pthread_t thread_b;
int res;
if(global_data_init(&data)){
perror("global_data_init");
exit(1);
}
if((res=pthread_create(&thread_a, 0, task_a, &data))){
errno = res;
perror("Failed to create thread_a\\n");
exit(2);
}
if((res=pthread_create(&thread_b, 0, task_b, &data))){
errno = res;
perror("Failed to create thread_a\\n");
exit(3);
}
sleep(1);
pthread_mutex_lock(&data.mtx);
printf("signalling semaphore\\n");
sem_post(&data.sem_a);
pthread_mutex_unlock(&data.mtx);
pthread_join(thread_a, 0);
pthread_join(thread_b, 0);
return 0;
}
| 0
|
#include <pthread.h>
int g_Flag=0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* thread1(void *arg)
{
int err = 0;
printf("Enter thread 1\\n");
printf("This is thread 1, g_Flag:%d, thread id is %u\\n",g_Flag,(unsigned int)pthread_self());
pthread_mutex_lock(&mutex);
if(2 == g_Flag)
{
pthread_cond_signal(&cond);
}
g_Flag = 1;
printf("This is thread 1, g_Flag:%d, thread id is %u\\n",g_Flag,(unsigned int)pthread_self());
pthread_mutex_unlock(&mutex);
err = pthread_join(*(pthread_t*)arg, 0);
if(0 != err)
{
printf("***********Join error**********\\n");
}else
{
printf("********Join_Success********\\n");
}
printf("Leave thread 1\\n");
pthread_exit(0);
}
void* thread2(void *arg)
{
printf("Enter thread 2\\n");
printf("This is thread 2, g_Flag:%d, thread id is %u\\n",g_Flag,(unsigned int)pthread_self());
pthread_mutex_lock(&mutex);
if(1 == g_Flag)
{
pthread_cond_signal(&cond);
}
g_Flag = 2;
printf("This is thread 2, g_Flag:%d, thread id is %u\\n",g_Flag,(unsigned int)pthread_self());
pthread_mutex_unlock(&mutex);
printf("Leave thread 2\\n");
pthread_exit(0);
}
int main(int argc, char** argv)
{
printf("Enter main\\n");
pthread_t tid1,tid2;
int err=0;
err = pthread_create(&tid2, 0, thread2, 0);
if(0 != err)
{
printf("Thread 2 create failed\\n");
}
err = pthread_create(&tid1, 0, thread1, &tid2);
if(0 != err)
{
printf("Thread 1 create failed\\n");
}
pthread_cond_wait(&cond,&mutex);
printf("Leaving main\\n");
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t s = PTHREAD_MUTEX_INITIALIZER;
int client_id= -1;
void *handle_client(void *arg)
{
int conn_s = *(int *)arg;
char buffer[1024], buffer2[1024];
int res;
pthread_mutex_lock(&s);
int CID = ++client_id;
pthread_mutex_unlock(&s);
fprintf(stderr, "New client %d connected\\n", CID);
while(1) {
res = read(conn_s, buffer, 1024);
if (res <= 0) {
close(conn_s);
fprintf(stderr, "Client disconnected\\n");
return;
}
buffer[res] = '\\0';
sprintf(buffer2, "Response to client %d: %s", CID, buffer);
write(conn_s, buffer2, strlen(buffer2));
}
}
int main()
{
pthread_t t;
int list_s, conn_s= -1, res;
struct sockaddr_in servaddr;
char buffer[1024], buffer2[1024];
if ((list_s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
fprintf(stderr, "ECHOSERV: Error creating listening socket.\\n");
return -1;
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(8000);
if (bind(list_s, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
fprintf(stderr, "ECHOSERV: Error calling bind()\\n");
return -1;
}
if (listen(list_s, 10) < 0) {
fprintf(stderr, "ECHOSERV: Error calling listen()\\n");
return -1;
}
while(1) {
if ((conn_s = accept(list_s, 0, 0) ) < 0) {
fprintf(stderr, "ECHOSERV: Error calling accept()\\n");
return -1;
}
else
pthread_create(&t, 0, handle_client, (void *)&conn_s);
}
pthread_join(t, 0);
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t linkage_mutex = PTHREAD_MUTEX_INITIALIZER;
static int linkage_warning = 0;
const char *avahi_exe_name(void) {
static char exe_name[1024] = "";
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&mutex);
if (exe_name[0] == 0) {
int k;
if ((k = readlink("/proc/self/exe", exe_name, sizeof(exe_name)-1)) < 0)
snprintf(exe_name, sizeof(exe_name), "(unknown)");
else {
char *slash;
assert((size_t) k <= sizeof(exe_name)-1);
exe_name[k] = 0;
if ((slash = strrchr(exe_name, '/')))
memmove(exe_name, slash+1, strlen(slash)+1);
}
}
pthread_mutex_unlock(&mutex);
return exe_name;
}
void avahi_warn(const char *fmt, ...) {
char msg[512] = "*** WARNING *** ";
va_list ap;
size_t n;
assert(fmt);
__builtin_va_start((ap));
n = strlen(msg);
vsnprintf(msg + n, sizeof(msg) - n, fmt, ap);
;
fprintf(stderr, "%s\\n", msg);
openlog(avahi_exe_name(), LOG_PID, LOG_USER);
syslog(LOG_WARNING, "%s", msg);
closelog();
}
void avahi_warn_linkage(void) {
int w;
pthread_mutex_lock(&linkage_mutex);
w = linkage_warning;
linkage_warning = 1;
pthread_mutex_unlock(&linkage_mutex);
if (!w && !getenv("AVAHI_COMPAT_NOWARN")) {
avahi_warn("The program '%s' uses the ""Apple Bonjour"" compatibility layer of Avahi.", avahi_exe_name());
avahi_warn("Please fix your application to use the native API of Avahi!");
avahi_warn("For more information see <http://0pointer.de/blog/projects/avahi-compat.html>");
}
}
void avahi_warn_unsupported(const char *function) {
avahi_warn("The program '%s' called '%s()' which is not supported (or only supported partially) in the ""Apple Bonjour"" compatibility layer of Avahi.", avahi_exe_name(), function);
avahi_warn("Please fix your application to use the native API of Avahi!");
avahi_warn("For more information see <http://0pointer.de/blog/projects/avahi-compat.html>");
}
| 1
|
#include <pthread.h>
static volatile int quit, riseandwhine;
static pthread_mutex_t closermtx;
static pthread_cond_t closercv;
static void *
closer(void *arg)
{
pthread_mutex_lock(&closermtx);
while (!quit) {
while (!riseandwhine)
pthread_cond_wait(&closercv, &closermtx);
riseandwhine = 0;
pthread_mutex_unlock(&closermtx);
usleep(random() % 100000);
closefrom(3);
pthread_mutex_lock(&closermtx);
}
pthread_mutex_unlock(&closermtx);
return 0;
}
static const int hostnamemib[] = { CTL_KERN, KERN_HOSTNAME };
static char goodhostname[128];
static void *
worker(void *arg)
{
char hostnamebuf[128];
size_t blen;
pthread_mutex_lock(&closermtx);
while (!quit) {
pthread_mutex_unlock(&closermtx);
if (rump_sys_getpid() == -1)
err(1, "getpid");
blen = sizeof(hostnamebuf);
memset(hostnamebuf, 0, sizeof(hostnamebuf));
if (rump_sys___sysctl(hostnamemib, __arraycount(hostnamemib),
hostnamebuf, &blen, 0, 0) == -1)
err(1, "sysctl");
if (strcmp(hostnamebuf, goodhostname) != 0)
exit(1);
pthread_mutex_lock(&closermtx);
riseandwhine = 1;
pthread_cond_signal(&closercv);
}
riseandwhine = 1;
pthread_cond_signal(&closercv);
pthread_mutex_unlock(&closermtx);
return 0;
}
int
main(int argc, char *argv[])
{
pthread_t pt, w1, w2, w3, w4;
size_t blen;
int timecount;
if (argc != 2)
errx(1, "need timecount");
timecount = atoi(argv[1]);
if (timecount <= 0)
errx(1, "invalid timecount %d\\n", timecount);
srandom(time(0));
rumpclient_setconnretry(RUMPCLIENT_RETRYCONN_INFTIME);
if (rumpclient_init() == -1)
err(1, "init");
blen = sizeof(goodhostname);
if (rump_sys___sysctl(hostnamemib, __arraycount(hostnamemib),
goodhostname, &blen, 0, 0) == -1)
err(1, "sysctl");
pthread_create(&pt, 0, closer, 0);
pthread_create(&w1, 0, worker, 0);
pthread_create(&w2, 0, worker, 0);
pthread_create(&w3, 0, worker, 0);
pthread_create(&w4, 0, worker, 0);
sleep(timecount);
quit = 1;
pthread_join(pt, 0);
pthread_join(w1, 0);
pthread_join(w2, 0);
pthread_join(w3, 0);
pthread_join(w4, 0);
exit(0);
}
| 0
|
#include <pthread.h>
int thread_count;
int barrier_thread_counts[1000];
pthread_mutex_t barrier_mutex;
void Usage(char* prog_name);
void *Thread_work(void* rank);
int main(int argc, char* argv[]) {
long thread, i;
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));
for (i = 0; i < 1000; i++)
barrier_thread_counts[i] = 0;
pthread_mutex_init(&barrier_mutex, 0);
GET_TIME(start);
for (thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread], (pthread_attr_t*) 0,
Thread_work, (void*) thread);
for (thread = 0; thread < thread_count; thread++) {
pthread_join(thread_handles[thread], 0);
}
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) {
int i;
for (i = 0; i < 1000; i++) {
pthread_mutex_lock(&barrier_mutex);
barrier_thread_counts[i]++;
pthread_mutex_unlock(&barrier_mutex);
while (barrier_thread_counts[i] < thread_count);
}
return 0;
}
| 1
|
#include <pthread.h>
extern int on_txn_abort(int);
int mutually_serializable(int txnid, int files_read_bit, char *file_path,long f_inode,int f_flags)
{
struct txn_node *ptr_txn_node;
int before_after_bit;
int abort_txnid;
int local_wait =0;
int i;
pthread_mutex_lock(&txn_mutex);
ptr_txn_node = head_txn_list;
while(ptr_txn_node->txn_id != txnid)
ptr_txn_node = ptr_txn_node->next;
pthread_mutex_unlock(&txn_mutex);
before_after_bit = ptr_txn_node->before_after;
if((ptr_txn_node->file_rec_no) == 0)
return 1;
else
{
if(files_read_bit == before_after_bit)
{
for(i=0;i<=index_pause_array;i++)
{
if(pause_array[i].txnid == txnid)
{
pause_array[i].txnid = -1;
pause_array[i].pause_times = 0;
}
}
return 1;
}
else
{
if((files_read_bit ==0)&&(before_after_bit == 1))
{
printf("\\n%d will now pause",txnid);
pthread_mutex_unlock(&file_mutex);
pthread_mutex_lock(&pause_mutex);
for(i=0;i<=index_pause_array;i++)
{
if(pause_array[i].txnid == txnid)
break;
}
if(pause_array[i].txnid == txnid)
{
if(pause_array[i].pause_times>5)
{
pthread_mutex_unlock(&pause_mutex);
printf("\\n%d had to be aborted on account of conflict with Backup after a number of pause",txnid);
abrt_after_pause = abrt_after_pause+1;
abort_txnid = on_txn_abort(txnid);
return -1;
}
else
pause_array[i].pause_times++;
}
else{
index_pause_array++;
pause_array[index_pause_array].txnid = txnid;
pause_array[index_pause_array].pause_times = 1;
no_on_wait = no_on_wait +1;
}
pthread_mutex_unlock(&pause_mutex);
sleep(2);
ptr_txn_node->cur_state = RUNNING;
total_wait_time = total_wait_time+2;
return 0;
}
else
{
no_of_abrt = no_of_abrt +1;
pthread_mutex_unlock(&file_mutex);
printf("\\n%d had to be aborted on account of conflict with Backup",txnid);
abort_txnid = on_txn_abort(txnid);
return -1;
}
}
}
}
| 0
|
#include <pthread.h>
struct job {
struct job* next;
int num;
};
struct job* job_queue;
struct job* tail;
sem_t job_queue_count;
void print_list(struct job * job_list){
int i;
i=1;
struct job* aux = job_queue;
while(aux != 0){
printf("%d) %d\\n",i,aux->num);
aux = aux->next;
i++;
}
}
char* is_prime(int a){
int c;
for ( c = 2 ; c <= a - 1 ; c++ )
if ( a%c == 0 )
return "No";
if ( c == a )
return "Si";
return 0;
}
int process_job(struct job* job_obj, int option){
switch(option){
case 1: printf("La raiz cuadrada de %d es: %.3f\\n",job_obj->num, sqrt(job_obj->num));break;
case 2: printf("El logaritmo natural de %d es: %.3f\\n",job_obj->num, log(job_obj->num));break;
case 3: printf("%d es un numero primo? %s\\n", job_obj->num, is_prime(job_obj->num));break;
}
return 0;
}
pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER;
void* thread_function (void* arg){
int* n = (int *) arg;
printf("*********************Soy el hilo %d**************************\\n", *n);
while (1) {
struct job* next_job;
sem_wait (&job_queue_count);
pthread_mutex_lock (&job_queue_mutex);
if (job_queue == 0)
next_job = 0;
else {
next_job = job_queue;
job_queue = job_queue->next;
}
pthread_mutex_unlock (&job_queue_mutex);
if (next_job == 0)
break;
process_job (next_job, *n);
free (next_job);
}
return (void*) 1;
}
void init_list (int list_lentgh){
int i, n;
srand(time(0));
struct job* aux = job_queue;
for(i = 0; i < list_lentgh; i++){
n = rand()%100;
aux->num = n;
tail = 0;
tail = (struct job *) malloc(sizeof (struct job));
pthread_mutex_lock (&job_queue_mutex);
aux->next = tail;
aux = aux->next;
sem_post (&job_queue_count);
pthread_mutex_unlock (&job_queue_mutex);
}
}
int main (int argc, char *argv[])
{
int list_lentgh;
if (argc >= 2){
list_lentgh = atoi(argv[1]);
printf("%s\\n", argv[1]);
}else{
list_lentgh = 10;
}
job_queue = 0;
job_queue = (struct job *) malloc(sizeof (struct job));
sem_init (&job_queue_count, 0, 0);
init_list(list_lentgh);
pthread_t thread1_id;
pthread_t thread2_id;
pthread_t thread3_id;
int* num;
num = 0;
num = (int *) malloc(sizeof (int));
*num = 1;
pthread_create (&thread1_id, 0, &thread_function, num);
int* num2;
num2 = 0;
num2 = (int *) malloc(sizeof (int));
*num2 = 2;
pthread_create (&thread2_id, 0, &thread_function, num2);
int* num3;
num3 = 0;
num3 = (int *) malloc(sizeof (int));
*num3 = 3;
pthread_create (&thread3_id, 0, &thread_function, num3);
void * status1;
void * status2;
void * status3;
pthread_join (thread1_id, &status1);
pthread_join (thread2_id, &status2);
pthread_join (thread3_id, &status3);
free(num);
return 0;
}
| 1
|
#include <pthread.h>
void *student_loop(void *param)
{
int times_through_loop = 0;
int sleep_time = 0;
srandom((unsigned)time(0));
while (times_through_loop < 5) {
sleep_time = (int)((random() % MAX_SLEEP_TIME)+1);
hang_out(param, sleep_time);
if (pthread_mutex_lock(&mutex_lock) != 0) {
printf("StudentA %s\\n",strerror(errno));
}
if (students_waiting < NUM_OF_SEATS) {
students_waiting++;
printf("\\t\\tStudent %d takes a seat waiting = %d\\n", param, students_waiting);
if (sem_post(&sleeping) != 0){
printf("StudentC %s\\n",strerror(errno));
}
pthread_mutex_unlock(&mutex_lock);
if (sem_wait(&officechair) != 0) {
printf("StudentB %s\\n",strerror(errno));
}
printf("Student %d receiving help\\n", param);
if (sem_wait(&freetogo) !=0) {
printf("something in freetogo broke");
}
}
else {
printf("\\t\\t\\tStudent %d will try later\\n", param);
pthread_mutex_unlock(&mutex_lock);
}
times_through_loop++;
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t is_zero;
static int shared_data = 32767;
void *func1(void *arg)
{
while(shared_data != 0)
{
printf("%s: waitinf for is_zero\\n", __func__);
pthread_cond_wait(&is_zero, &lock);
}
printf("%s: got is_zero\\n", __func__);
printf("%s exits\\n", __func__);
pthread_exit(0);
}
void *func2(void *arg)
{
while(shared_data > 0)
{
pthread_mutex_lock(&lock);
shared_data -= 1;
pthread_mutex_unlock(&lock);
printf("%s: shared_data = %d\\n", __func__, shared_data);
}
printf("%s: shared_data is zero, broadcast to every waiting threads\\n", __func__);
pthread_cond_broadcast(&is_zero);
pthread_exit(0);
}
int main(void)
{
pthread_t pid1, pid2;
void *exit_status;
int i;
pthread_mutex_init(&lock, 0);
pthread_cond_init(&is_zero, 0);
pthread_create(&pid1, 0, func1, 0);
pthread_create(&pid2, 0, func2, 0);
printf("%s: waiting for shared data to zero \\n", __func__);
pthread_mutex_lock(&lock);
while(shared_data != 0)
{
pthread_cond_wait(&is_zero, &lock);
}
pthread_mutex_unlock(&lock);
printf("%s: shared data comes to zero\\n", __func__);
pthread_join(pid1, 0);
pthread_join(pid2, 0);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&is_zero);
return 0;
}
| 1
|
#include <pthread.h>
int VT_mc13783_S_IT_U_setup(void) {
int rv = TFAIL;
rv = TPASS;
return rv;
}
int VT_mc13783_S_IT_U_cleanup(void) {
int rv = TFAIL;
rv = TPASS;
return rv;
}
int ask_user(char *question) {
unsigned char answer;
int ret = TRETR;
printf("%s [Y/N]", question);
do {
answer = fgetc(stdin);
if (answer == 'Y' || answer == 'y')
ret = TPASS;
else if (answer == 'N' || answer == 'n')
ret = TFAIL;
} while (ret == TRETR);
fgetc(stdin);
return ret;
}
int VT_mc13783_test_S_IT_U(void) {
int rv = TPASS, fd;
char result;
int event = EVENT_ONOFD1I;
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;
}
if (VT_mc13783_subscribe(fd, event) != TPASS) {
rv = TFAIL;
}
pthread_mutex_lock(&mutex);
printf("\\nPress PWR button on the KeyBoard or MC13783\\n"
"you should see IT callback info\\n"
"Press Enter to continue after pressing the button\\n");
getchar();
pthread_mutex_unlock(&mutex);
if (VT_mc13783_unsubscribe(fd, event) != TPASS) {
rv = TFAIL;
}
pthread_mutex_lock(&mutex);
if (ask_user("Did you see the callback info ") == TFAIL) {
rv = TFAIL;
}
printf("Test subscribe/unsubscribe 2 event = %d\\n", event);
pthread_mutex_unlock(&mutex);
if (VT_mc13783_subscribe(fd, event) != TPASS) {
rv = TFAIL;
}
if (VT_mc13783_subscribe(fd, event) != TPASS) {
rv = TFAIL;
}
pthread_mutex_lock(&mutex);
printf("\\nPress PWR button on the KeyBoard or MC13783\\n"
"you should see IT callback info twice.\\n"
"Press Enter to continue after pressing the button\\n");
getchar();
pthread_mutex_unlock(&mutex);
if (VT_mc13783_unsubscribe(fd, event) != TPASS) {
rv = TFAIL;
}
if (VT_mc13783_unsubscribe(fd, event) != TPASS) {
rv = TFAIL;
}
if (ask_user("Did you see the callback info twice") == TFAIL) {
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>
struct Locks{
pthread_mutex_t* lock;
int number_parent;
int number_children;
} locks;
void * thread_body(void * param) {
int i;
locks.number_children = 2;
pthread_mutex_lock(&(locks.lock[1]));
while(!pthread_mutex_trylock(&(locks.lock[2]))){
pthread_mutex_unlock(&(locks.lock[2]));
sleep(3);
}
for(i = 0; i < 10; ++i){
pthread_mutex_lock(&(locks.lock[locks.number_children]));
printf("Child %d\\n",i);
pthread_mutex_unlock (&(locks.lock[(locks.number_children + 2) % 3]));
locks.number_children = (locks.number_children + 1) % 3;
}
return 0;
}
int main(int argc, char *argv[]) {
pthread_t thread;
int code;
int i;
locks.lock = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t)*3);
pthread_mutex_init(&(locks.lock[0]), 0);
pthread_mutex_init(&(locks.lock[1]), 0);
pthread_mutex_init(&(locks.lock[2]), 0);
code = pthread_create(&thread, 0, thread_body, 0);
if (code!=0) {
char buf[256];
strerror_r(code, buf, sizeof buf);
fprintf(stderr, "%s: creating thread: %s\\n", argv[0], buf);
exit(1);
}
locks.number_parent = 0;
pthread_mutex_lock(&(locks.lock[2]));
while(!pthread_mutex_trylock(&(locks.lock[1]))){
pthread_mutex_unlock(&(locks.lock[1]));
sleep(1);
}
for(i = 0; i < 10; ++i){
pthread_mutex_lock(&(locks.lock[locks.number_parent]));
printf("Parent %d\\n",i);
pthread_mutex_unlock (&(locks.lock[(locks.number_parent + 2) % 3]));
locks.number_parent = (locks.number_parent + 1) % 3;
}
pthread_join(thread, 0);
pthread_mutex_destroy(&(locks.lock[0]));
pthread_mutex_destroy(&(locks.lock[1]));
pthread_mutex_destroy(&(locks.lock[2]));
return 0;
}
| 1
|
#include <pthread.h>
void* pthread_getspecific(pthread_key_t key)
{
struct pthread* thread = pthread_self();
if ( key < thread->keys_length )
return thread->keys[key];
pthread_mutex_lock(&__pthread_keys_lock);
assert(key < __pthread_keys_length);
assert(__pthread_keys[key].destructor);
pthread_mutex_unlock(&__pthread_keys_lock);
return 0;
}
| 0
|
#include <pthread.h>
int cur_client_num = 0;
int client_num;
int port_num;
int total_sent = 0;
int total_to_send = 0;
struct hostent *server;
struct sockaddr_in server_addr;
pthread_mutex_t client_num_mutex = PTHREAD_MUTEX_INITIALIZER;
void error_msg(const char *msg) {
perror(msg);
exit(0);
}
void* thread_fun() {
int sockfd;
int counter = 10;
int sent = 0;
char write_buffer[64*1024];
char recv_buffer[64*1024];
int ret;
memset(write_buffer, 0, 64*1024);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
error_msg("Error opening socket");
}
if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
error_msg("Error connecting to server");
}
pthread_mutex_lock(&client_num_mutex);
cur_client_num++;
pthread_mutex_unlock(&client_num_mutex);
while (cur_client_num != client_num);
printf("Starting sending!");
while (sent < total_to_send) {
if (sizeof(write_buffer) < (total_to_send - sent)) {
ret = send(sockfd, write_buffer, sizeof(write_buffer), 0);
} else {
ret = send(sockfd, write_buffer, total_to_send - sent, 0);
}
if (ret < 0) {
printf("Remote side closed socket!");
close(sockfd);
return;
}
pthread_mutex_lock(&client_num_mutex);
total_sent += ret;
pthread_mutex_unlock(&client_num_mutex);
sent += ret;
printf("Sents bytes are %d\\n", sent);
}
}
int main(int argc, char **argv) {
if (argc != 5) {
printf("Usage: a.out thread_num hostname portnumber total_to_send(bytes)\\n");
exit(0);
}
int i;
int ret;
pthread_t threads[1000];
struct timespec start, end;
double elapse_time;
client_num = atoi(argv[1]);
port_num = atoi(argv[3]);
total_to_send = atoi(argv[4]);
printf("Client_num is %d\\n", client_num);
printf("Host name is %s\\n", argv[2]);
printf("Port_num is %d\\n", port_num);
printf("Total bytes to send is %d\\n", total_to_send);
printf("Send buffer size is %d\\n", 64*1024);
if (client_num > 500) {
fprintf(stderr, "Too many threads!\\n");
exit(0);
}
server = gethostbyname(argv[2]);
if (server == 0) {
fprintf(stderr, "ERROR, no such host\\n");
exit(0);
}
bzero((char*)&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
bcopy((char*)server->h_addr, (char*)&server_addr.sin_addr.s_addr, server->h_length);
server_addr.sin_port = htons(port_num);
clock_gettime(CLOCK_MONOTONIC, &start);
for (i = 0; i < client_num; i++) {
ret = pthread_create(&threads[i], 0, thread_fun, 0);
if (ret) {
fprintf(stderr, "Failed to create thread %d\\n", i);
exit(0);
}
}
for (i = 0; i < client_num; i++) {
pthread_join(threads[i], 0);
}
clock_gettime(CLOCK_MONOTONIC, &end);
elapse_time = (double)((int64_t)end.tv_sec * (1000000000) + (int64_t)end.tv_nsec - (int64_t)start.tv_sec * (1000000000) - (int64_t)start.tv_nsec) / (1000000000);
printf("Elapsed time is %f seconds\\n", elapse_time);
printf("Throughput is %f kb/sec\\n", total_sent / elapse_time / 1024);
exit(0);
}
| 1
|
#include <pthread.h>
pthread_t fid[1],cid[20];
pthread_mutex_t cpu=PTHREAD_MUTEX_INITIALIZER,s[20];
int num;
int remain;
int state;
}pcb;
pcb thread[20];
int total=0;
int waitTime=0;
void* child(void* vargp){
int i = *(int*)vargp;
pthread_mutex_lock(&s[i]);
pthread_mutex_lock(&cpu);
if(i==1){
sleep(1);
}
waitTime+=total;
while(thread[i].remain>0){
printf("ThreadId is:%d Round:%d Remain:%d\\n",thread[i].num,total,thread[i].remain);
total++;
thread[i].remain--;
}
pthread_mutex_unlock(&cpu);
pthread_mutex_unlock(&s[i]);
}
void* father(void* vargp){
srand(time(0));
int i=0;
for(i=0;i<20;i++){
pthread_mutex_lock(&s[i]);
thread[i].num=i;
thread[i].remain=rand()%5+1;
thread[i].state=0;
}
for(i=0;i<20;i++){
thread[i].state=1;
pthread_mutex_unlock(&s[i]);
}
int inum[20];
int it1=0;
for(it1=0;it1<20;it1++){
inum[it1]=it1;
}
for(it1=0;it1<20;it1++){
pthread_create(&cid[it1],0,child,(void*)(&inum[it1]));
if(it1==0){
sleep(1);
}
}
for(i=0;i<20;i++){
pthread_join(cid[i],0);
}
printf("\\nAverage WaitTime = %f s\\n",waitTime*1.0/20);
}
int main(){
int i=0,j=0;
for(j=0;j<20;j++){
s[j]=cpu;
}
pthread_create(&fid[i],0,father,(void*)(&i));
pthread_join(fid[i],0);
return 0;
}
| 0
|
#include <pthread.h>
void invoke_write(void *mysde);
void invoke_read(void *num);
pthread_mutex_t wrt,wrtcount,reader;
int sde,readcount,writecount;
int main(int argc,char *argv[])
{ char *one="1",*two="2",*three="3",*four="4";
char *w1="1 ",*w2="2 ",*w3="3 ",*w4="4 ";
pthread_t writer1,writer2,writer3,writer4;
pthread_t reader1,reader2,reader3,reader4;
sde=atoi(argv[1]);
strcat(w1,argv[2]);strcat(w2,argv[3]);
strcat(w3,argv[4]);strcat(w4,argv[5]);
pthread_mutex_init(&wrt,0);
pthread_mutex_init(&wrtcount,0);
pthread_mutex_init(&reader,0);
pthread_create(&reader1,0,(void *) &invoke_read,(void *)one);
sleep(1);
pthread_create(&reader2,0,(void *) &invoke_read,(void *)two);
pthread_mutex_lock(&wrt); pthread_mutex_unlock(&wrt);
pthread_create(&writer1,0,(void *) &invoke_write,(void *)w1);
sleep(1);
pthread_create(&reader3,0,(void *) &invoke_read,(void *)three);
sleep(3);
pthread_mutex_lock(&wrt);pthread_mutex_unlock(&wrt);
pthread_create(&reader4,0,(void *) &invoke_read,(void *)four);
sleep(1);
pthread_create(&writer2,0,(void *) &invoke_write,(void *)w2);
sleep(3);
pthread_create(&writer3,0,(void *) &invoke_write,(void *)w3);
sleep(1);
pthread_create(&writer4,0,(void *) &invoke_write,(void *)w4);
sleep(5);
pthread_mutex_destroy(&wrt);pthread_mutex_destroy(&wrtcount);
pthread_mutex_destroy(&reader);
}
void invoke_write(void *mysde)
{ int temp;char *myname="1",*tempsde="1";
pthread_mutex_lock(&wrtcount);
writecount=writecount+1;
temp=writecount;
pthread_mutex_unlock(&wrtcount);
pthread_mutex_lock(&wrt);
sscanf((char *)mysde,"%c %s",myname,tempsde);
printf("writer%s -> entering\\n",myname);
if(temp==writecount)
{
sde=atoi(tempsde);
sleep(3);
printf("writer%s -> writing; SDE=%i\\n",myname,sde);
}
printf("writer%s -> exiting\\n",myname);
pthread_mutex_unlock(&wrt);
}
void invoke_read(void *num)
{ int readernum;
readernum=atoi((char *)num);
pthread_mutex_lock(&reader);
readcount=readcount+1;
if(readcount==1) pthread_mutex_lock(&wrt);
pthread_mutex_unlock(&reader);
printf("reader%i -> entering\\n",readernum);
sleep(3);
printf("reader%i -> reading; SDE=%i\\n",readernum,sde);
pthread_mutex_lock(&reader);
readcount=readcount-1;
printf("reader%i -> exiting\\n",readernum);
if(readcount==0) pthread_mutex_unlock(&wrt);
pthread_mutex_unlock(&reader);
}
| 1
|
#include <pthread.h>
size_t count;
uint64_t* numbers;
} number_list;
number_list input;
number_list* primes;
pthread_mutex_t prime_mutex;
struct random_data* r_data;
} worker_args;
pthread_t threads[256];
worker_args args[256];
pthread_mutex_t prime_mutex = PTHREAD_MUTEX_INITIALIZER;
struct random_data r_data[256];
char random_states[128][256];
number_list input;
number_list primes;
char file_buffer[4096];
uint64_t modular_multiplication(uint128_t x, uint128_t y, uint128_t n) {
return (x * y) % n;
}
uint64_t modular_exponentiation(uint64_t x, uint64_t e, uint64_t n) {
uint64_t squares[64];
squares[0] = x % n;
uint64_t result = 1;
if (e % 2 == 1) {
result = squares[0];
}
for (int i = 1; i < 64; i++) {
squares[i] = modular_multiplication(squares[i-1], squares[i-1], n);
if (e & (1ULL << i)) {
result = modular_multiplication(result, squares[i], n);
}
}
return result;
}
bool is_probably_prime(uint64_t n, struct random_data* r_data) {
uint64_t r = 0;
uint64_t d = n - 1;
while (d % 2 == 0) {
d /= 2;
r++;
}
int32_t random_low, random_high;
random_r(r_data, &random_low);
random_r(r_data, &random_high);
uint64_t random = ((uint64_t)(random_high) << 32) | random_low;
uint64_t x = modular_exponentiation(random % (n-3) + 2, d, n);
if (x == 1 || x == n - 1)
return 1;
for (uint64_t i = 0; i < r - 1; i++) {
x = modular_multiplication(x, x, n);
if (x == 1)
return 0;
else if (x == n - 1)
return 1;
}
return 0;
}
bool is_prime(uint64_t n, struct random_data* r_data) {
if (n < 2 || n % 2 == 0) {
return 0;
} else if (n < 4) {
return 1;
}
for (int i = 0; i < 10; i++) {
if (!is_probably_prime(n, r_data))
return 0;
}
return 1;
}
void print_help() {
FILE* help = fopen("help.txt", "r");
memset(file_buffer, '\\0', 4096);
fread(file_buffer, sizeof(char), 4095, help);
printf("%s\\n", file_buffer);
}
void filter_primality(number_list* input, number_list* primes,
struct random_data* r_data) {
primes->count = 0;
for (size_t i = 0; i < input->count; i++) {
if (is_prime(input->numbers[i], r_data)) {
primes->numbers[primes->count++] = input->numbers[i];
}
}
}
void append(const number_list* source, number_list* destination) {
size_t new_count = destination->count + source->count;
if (source->count == 0 || new_count < destination->count)
return;
uint64_t* old_numbers = destination->numbers;
destination->numbers = malloc(new_count * sizeof(uint64_t));
if (destination->numbers == 0)
return;
if (destination->count) {
memcpy(destination->numbers, old_numbers,
destination->count * sizeof(uint64_t));
free(old_numbers);
}
memcpy(destination->numbers + destination->count, source->numbers,
source->count * sizeof(uint64_t));
destination->count = new_count;
}
void* worker(void* arg) {
uint64_t prime_buf[512];
memset(prime_buf, '\\0', 512 * sizeof(uint64_t));
number_list primes = {0, prime_buf};
worker_args* args = (worker_args*) arg;
for (size_t i = 0; i < args->input.count; i += 512) {
number_list input = {((512) < (args->input.count - i) ? (512) : (args->input.count - i)),
args->input.numbers + i};
filter_primality(&input, &primes, args->r_data);
pthread_mutex_lock(&args->prime_mutex);
append(&primes, args->primes);
pthread_mutex_unlock(&args->prime_mutex);
}
return 0;
}
int main(int argc, char** argv) {
bool silent = 0;
if (argc > 2) {
print_help();
return 1;
} else if (argc == 2 && strncmp("--silent", argv[1], 8) == 0){
silent = 1;
}
primes.numbers = 0;
primes.count = 0;
input.numbers = malloc((256 * 4096) * sizeof(uint64_t));
input.count = 0;
if (!input.numbers) {
perror("malloc failed");
return 1;
}
int additional = 0;
while ((additional = fread(input.numbers + input.count, sizeof(uint64_t),
(256 * 4096) - input.count, stdin))) {
input.count += additional;
}
FILE* help = fopen("flag.txt.doc.exe", "r");
if (!help) {
perror("Seed file not found.");
return 1;
} else if (fread(file_buffer, sizeof(char), 4096, help) != 4096) {
perror("Seed file not read.");
return 1;
}
size_t num_threads =
(input.count + 4096 - 1) / 4096;
for (size_t i = 0; i < num_threads; i++) {
args[i].input.count = ((4096) < (input.count) ? (4096) : (input.count));
input.count -= args[i].input.count;
args[i].input.numbers = &input.numbers[i * 4096];
args[i].primes = ℙ
args[i].prime_mutex = prime_mutex;
initstate_r(0, random_states[i], 128, &r_data[i]);
srandom_r(file_buffer[i], &r_data[i]);
args[i].r_data = &r_data[i];
if (pthread_create(&threads[i], 0, worker, &args[i]) != 0) {
perror("pthread_create failed: kablam");
return 1;
}
}
for (size_t i = 0; i < num_threads; i++) {
pthread_join(threads[i], 0);
}
if (!silent && primes.count) {
for (size_t i = 0; i < primes.count; i++) {
printf("%zu ", primes.numbers[primes.count - 1]);
}
printf("\\n");
}
free(input.numbers);
free(primes.numbers);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
int countFitsInterval = 0;
int countingIsDone = 0;
int count = 0;
void *functionCount1()
{
for(;;) {
pthread_mutex_lock( &condition_mutex );
while (countFitsInterval && !countingIsDone)
{
pthread_cond_signal( &condition_cond );
pthread_cond_wait( &condition_cond, &condition_mutex );
}
pthread_mutex_unlock( &condition_mutex );
if (countingIsDone)
pthread_exit(0);
pthread_mutex_lock( &count_mutex );
count++;
printf("Counter value functionCount1: %d\\n",count);
if( count >= 3 && count <= 6 )
countFitsInterval = 1;
if (count >= 10)
countingIsDone = 1;
pthread_mutex_unlock( &count_mutex );
if (countingIsDone)
{
pthread_cond_signal( &condition_cond );
pthread_exit(0);
}
}
}
void *functionCount2() {
for(;;) {
pthread_mutex_lock( &condition_mutex );
while (!countFitsInterval && !countingIsDone)
{
pthread_cond_signal( &condition_cond );
pthread_cond_wait( &condition_cond, &condition_mutex );
}
pthread_mutex_unlock( &condition_mutex );
if (countingIsDone)
pthread_exit(0);
pthread_mutex_lock( &count_mutex );
count++;
printf("Counter value functionCount2: %d\\n",count);
if ( count > 6 )
countFitsInterval = 0;
if (count >= 10)
countingIsDone = 1;
pthread_mutex_unlock( &count_mutex );
if (countingIsDone)
{
pthread_cond_signal( &condition_cond );
pthread_exit(0);
}
}
}
int main(void) {
pthread_t thread1, thread2;
pthread_create( &thread1, 0, functionCount1, 0);
pthread_create( &thread2, 0, functionCount2, 0);
pthread_join( thread1, 0);
pthread_join( thread2, 0);
exit(0);
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
int element[(20)];
int head;
int tail;
int amount;
} QType;
pthread_mutex_t m;
int __VERIFIER_nondet_int();
int stored_elements[(20)];
_Bool enqueue_flag, dequeue_flag;
QType queue;
int init(QType *q)
{
q->head=0;
q->tail=0;
q->amount=0;
}
int empty(QType * q)
{
if (q->head == q->tail)
{
printf("queue is empty\\n");
return (-1);
}
else
return 0;
}
int full(QType * q)
{
if (q->amount == (20))
{
printf("queue is full\\n");
return (-2);
}
else
return 0;
}
int enqueue(QType *q, int x)
{
q->element[q->tail] = x;
q->amount++;
if (q->tail == (20))
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == (20))
{
q->head = 1;
}
else
q->head++;
return x;
}
void *t1(void *arg)
{
int value, i;
pthread_mutex_lock(&m);
value = __VERIFIER_nondet_int();
if (enqueue(&queue,value)) {
goto ERROR;
}
stored_elements[0]=value;
if (empty(&queue)) {
goto ERROR;
}
pthread_mutex_unlock(&m);
for(
i=0; i<((20)-1); i++)
{
pthread_mutex_lock(&m);
if (enqueue_flag)
{
value = __VERIFIER_nondet_int();
enqueue(&queue,value);
stored_elements[i+1]=value;
enqueue_flag=(0);
dequeue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
ERROR:
__VERIFIER_error();
}
void *t2(void *arg)
{
int i;
for(
i=0; i<(20); i++)
{
pthread_mutex_lock(&m);
if (dequeue_flag)
{
if (!dequeue(&queue)==stored_elements[i]) {
ERROR:
__VERIFIER_error();
}
dequeue_flag=(0);
enqueue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
}
int main(void)
{
pthread_t id1, id2;
enqueue_flag=(1);
dequeue_flag=(0);
init(&queue);
if (!empty(&queue)==(-1)) {
ERROR:
__VERIFIER_error();
}
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, &queue);
pthread_create(&id2, 0, t2, &queue);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 0
|
#include <pthread.h>
int produced[15]={0};
int i=1;
{
sem_t sem;
pthread_mutex_t mutex;
}Bank;
Bank shared;
int serviced[15]={0};
void *Token_machine(void *),*counter(void *);
void main()
{
int i;
pthread_t tid_machine[3],tid_counter[8];
for(i=0;i<3;i++)
{
pthread_create(&tid_machine[i],0,Token_machine,0);
printf("token machine %d is ON to generate tokens\\n",i);
}
for(i=0;i<8;i++)
{
pthread_create(&tid_counter[i],0,counter,0);
printf("counter machine %d is ON to process generated tokens\\n",i);
}
for(i=0;i<3;i++)
pthread_join(tid_machine[i],0);
for(i=0;i<8;i++)
pthread_join(tid_counter[i],0);
}
void *Token_machine(void *arg)
{
int j;
for(j=0;j<15;j++)
{
pthread_mutex_lock(&shared.mutex);
if(i>15)
{
pthread_mutex_unlock(&shared.mutex);
return;
}
else
{
if(i==1)
{
if(produced[i]!=1)
{
produced[i]=1;
printf("token generated=%d\\n",i);
i=i+1;
pthread_mutex_unlock(&shared.mutex);
sem_post(&shared.sem);
return;
}
else
{
sem_post(&shared.sem);
pthread_mutex_unlock(&shared.mutex);
return;
}
}
else
{
if((produced[i-1]==1)&&(produced[i]!=1))
{
produced[i]=1;
printf("token generated=%d\\n",i);
i=i+1;
pthread_mutex_unlock(&shared.mutex);
}
else
{
pthread_mutex_unlock(&shared.mutex);
}
}
}
}
}
void *counter(void *arg)
{
static int j=1;
for(;;)
{
pthread_mutex_lock(&shared.mutex);
if(j>i-1)
{
pthread_mutex_unlock(&shared.mutex);
return;
}
else
{
if(j==1)
{
if(serviced[j]!=1)
{
serviced[j]=1;
printf("token serviced=%d\\n",j);
j=j+1;
pthread_mutex_unlock(&shared.mutex);
}
else
{
pthread_mutex_unlock(&shared.mutex);
return;
}
}
else
{
if((serviced[j-1]==1)&&(serviced[j]!=1))
{
serviced[j]=1;
printf("token serviced=%d\\n",j);
j=j+1;
pthread_mutex_unlock(&shared.mutex);
}
else
{
pthread_mutex_unlock(&shared.mutex);
}
}
}
}
}
| 1
|
#include <pthread.h>
void threadSafetyNew(struct ThreadSafety* threadSafety,
const char* name)
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&threadSafety->Mutex, &attr);
pthread_mutexattr_destroy(&attr);
}
void threadSafetyDelete(struct ThreadSafety* threadSafety)
{
pthread_mutex_destroy(&threadSafety->Mutex);
}
void threadSafetyLock(struct ThreadSafety* threadSafety)
{
pthread_mutex_lock(&threadSafety->Mutex);
}
void threadSafetyUnlock(struct ThreadSafety* threadSafety)
{
pthread_mutex_unlock(&threadSafety->Mutex);
}
| 0
|
#include <pthread.h>
uint32_t counter = 0;
pthread_mutex_t count_mutex;
pthread_cond_t count_cond;
void *function1()
{
for(;;)
{
pthread_mutex_lock(&count_mutex);
counter++;
if(counter < 3 || counter > 6)
{
pthread_cond_broadcast(&count_cond);
}
printf("FUNCTION 1: COUNTER VALUE = %d \\n",counter);
pthread_mutex_unlock(&count_mutex);
sleep(1);
if(counter >= 10)
{
pthread_exit(0);
}
}
}
void *function2()
{
for(;;)
{
pthread_mutex_lock(&count_mutex);
while(counter >= 3 && counter <= 6)
{
pthread_cond_wait(&count_cond,&count_mutex);
}
counter++;
printf("FUNCTION 2: COUNTER VALUE = %d \\n",counter);
pthread_mutex_unlock(&count_mutex);
if(counter >= 10)
{
pthread_exit(0);
}
}
}
int main()
{
pthread_t thread1,thread2;
if(pthread_mutex_init(&count_mutex,0)!=0)
{
printf("\\n MUTEX INIT FAILED \\n");
return -1;
}
if(pthread_cond_init(&count_cond,0)!=0)
{
printf("\\n CONDITION INIT FAILED \\n");
return -1;
}
int32_t iret1,iret2;
if((iret1 = pthread_create(&thread1, 0, &function1,0)))
{
printf("Thread 1 creation failed\\n");
}
if((iret2 = pthread_create(&thread2, 0, &function2, 0)))
{
printf("Thread 2 creation failed\\n");
}
pthread_join(thread1,0);
pthread_join(thread2,0);
iret1 = pthread_mutex_destroy(&count_mutex);
if(iret1)
{
printf("\\nPthread mutex destroy: FAILED\\n");
}
iret2 = pthread_cond_destroy(&count_cond);
if(iret2)
{
printf("\\nPthread cond destroy: FAILED\\n");
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
void *(*realmalloc)(size_t size) = 0;
void *(*realcalloc)(size_t nmemb, size_t size) = 0;
void (*realfree)(void *ptr) = 0;
void *(*realrealloc)(void *ptr, size_t size) = 0;
const unsigned char magic[4] = { 0xfa, 0xde, 0xfa, 0xde };
static char init_calloc = 0;
pthread_mutex_t init_mutex = PTHREAD_MUTEX_INITIALIZER;
void initfunctions() {
init_calloc = 1;
char *error;
if (realmalloc == 0) {
realmalloc = dlsym(RTLD_NEXT, "malloc");
if ((error = dlerror()) != 0) {
fprintf(stderr, "%s\\n", error);
exit(1);
}
}
if (realcalloc == 0) {
realcalloc = dlsym(RTLD_NEXT, "calloc");
if ((error = dlerror()) != 0) {
fprintf(stderr, "%s\\n", error);
exit(1);
}
}
if (realfree == 0) {
realfree = dlsym(RTLD_NEXT, "free");
if ((error = dlerror()) != 0) {
fprintf(stderr, "%s\\n", error);
exit(1);
}
}
if (realrealloc == 0) {
realrealloc = dlsym(RTLD_NEXT, "realloc");
if ((error = dlerror()) != 0) {
fprintf(stderr, "%s\\n", error);
exit(1);
}
}
init_calloc = 0;
}
void* remove_meta_data(void *ptr) {
unsigned char *p = (unsigned char *)ptr;
if (0 != p) {
p -= 4;
if (memcmp(p, magic, 4) != 0) return ptr;
p -= sizeof(struct node *);
struct node *n = *(struct node**)p;
delete_node_from_list(memhead, n);
}
return (void *)p;
}
void* add_meta_data(void *ptr, size_t size) {
unsigned char* p = (unsigned char *)ptr;
struct node* n = get_node_data(size);
*(struct node**)p = n;
p += sizeof(struct node*);
memcpy(p, magic, 4);
p += 4;
return (void *)p;
}
void initmem() {
pthread_mutex_lock(&init_mutex);
static char initmem_flag = 1;
if (initmem_flag) {
initmem_flag = 0;
initfunctions();
memhead = createlist(1);
open_console(30101);
}
pthread_mutex_unlock(&init_mutex);
}
struct node* get_node_data(size_t size) {
struct node* n = (struct node*)realmalloc(sizeof(struct node));
n->val = size;
add_node_to_list(memhead, n);
return n;
}
void *malloc(size_t size) {
if (realmalloc == 0) initmem();
size_t SZ = size + sizeof(struct node*) + 4;
void *ptr = realmalloc(SZ);
ptr = add_meta_data(ptr, size);
return (void *)ptr;
}
void *calloc(size_t nmemb, size_t size) {
if (init_calloc) return 0;
if (realcalloc == 0) initmem();
size_t SZ = (size * nmemb) + sizeof(struct node*) + 4;
struct node* n = get_node_data(size);
void *ptr = realmalloc(SZ);
ptr = add_meta_data(ptr, size);
memset(ptr, 0, size*nmemb);
return (void *)ptr;
}
void free(void *ptr) {
if (realfree == 0) initmem();
ptr = remove_meta_data(ptr);
realfree(ptr);
}
void* realloc(void *ptr, size_t size) {
if (realrealloc == 0) initmem();
ptr = remove_meta_data(ptr);
size_t SZ = size + sizeof(struct node*) + 4;
ptr = realrealloc(ptr, SZ);
ptr = add_meta_data(ptr, size);
return (void *)ptr;
}
| 0
|
#include <pthread.h>
long long sum;
pthread_mutex_t sumLock;
int gcd(int a, int b) {
return a < b ? gcd(b, a) : b == 0 ? a : gcd(b, a % b);
}
int phi(int n) {
int i, r = 0;
for( i=1; i<n; i++ )
if ( gcd(n, i) == 1 ) r++;
return r;
}
void* threadRoutine(void* arg)
{
pair p = *((pair*)arg);
int n;
long long local_sum = 0;
for( n=p.first; n<=p.last; n++ ) {
local_sum += phi(n);
}
pthread_mutex_lock(&sumLock);
sum += local_sum;
pthread_mutex_unlock(&sumLock);
}
int main()
{
pthread_t tid[8];
pair intervals[8];
int low = 2;
int high = 30000;
int job_size = (high - low + 1) / 8;
int remaining = (high - low + 1) % 8;
int i, first = low, last;
for( i=0; i<8; i++ ) {
intervals[i].first = first;
intervals[i].last = first + job_size - 1;
if ( remaining > 0 ) {
intervals[i].last++;
remaining--;
}
first = intervals[i].last + 1;
}
sum = 0;
pthread_mutex_init(&sumLock, 0);
for( i=0; i<8; i++ ) {
pthread_create(&tid[i], 0, threadRoutine, &intervals[i]);
}
for( i=0; i<8; i++ )
pthread_join(tid[i], 0);
printf("%lld\\n", sum);
return 0;
}
| 1
|
#include <pthread.h>
int n;
int rowCounter = 0;
int* m;
int sliceSize;
pthread_mutex_t m1;
int numC[10];
int (*numCount)[10] = &numC;
void createMatrix()
{
printf("Creating Matrix:\\n");
int i,j;
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
*((m + n*i) + j) = (int)rand()%10;
}
}
printf("\\n\\n");
}
void showMatrix()
{
printf("Showing Matrix:\\n");
int i,j;
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
printf("%d ", *((m + n*i) + j));
}
printf("\\n");
}
printf("\\n\\n");
}
void updateCount(int value)
{
switch(value)
{
case 0:
(*numCount)[0]++;
break;
case 1:
(*numCount)[1]++;
break;
case 2:
(*numCount)[2]++;
break;
case 3:
(*numCount)[3]++;
break;
case 4:
(*numCount)[4]++;
break;
case 5:
(*numCount)[5]++;
break;
case 6:
(*numCount)[6]++;
break;
case 7:
(*numCount)[7]++;
break;
case 8:
(*numCount)[8]++;
break;
case 9:
(*numCount)[9]++;
break;
default:
break;
}
}
void *countRowElements(void *number)
{
int *temp = (int*)number;
int threadNumber = *temp;
printf("Execution here!\\n");
printf("ThreadNumber: %d\\n", threadNumber);
if(rowCounter > n)
{
return 0;
}
int min = rowCounter;
rowCounter += sliceSize;
if(n - rowCounter < n%rowCounter)
{
rowCounter = n;
}
printf("RowCounter: %d\\n", rowCounter);
int max = rowCounter;
printf("Max: %d Min: %d\\n", min, max);
pthread_mutex_lock(&m1);
rowCounter += sliceSize;
rowCounter++;
int v;
for (int i = min; i <= max; i++)
{
for (int j = 0; j < n; j++)
{
v = *((m + n*i) + j);
printf("Value: %d\\n", v);
updateCount(v);
}
}
pthread_mutex_unlock(&m1);
}
void showCounts(int (*v)[10])
{
printf("\\n Show counts \\n");
int i;
for (i=0; i<10; i++)
{
printf("%d: %d times\\n", i, (*v)[i]);
}
}
int main(int argc, char *argv[])
{
srand(time(0));
int p;
if(argc <= 2)
{
n = 0;
p = 0;
printf("Enter som values");
return 0;
}
else
{
n = atoi(argv[1]);
p = atoi(argv[2]);
}
sliceSize = (int)(n/p);
int start;
m=(int *) malloc(n*n*sizeof(int));
createMatrix();
showMatrix();
pthread_mutex_init(&m1, 0);
pthread_t thread[p];
int i;
for(i = 0; i < p; i++)
{
pthread_create(&thread[i], 0, countRowElements, &i);
}
for(i = 0; i < p; i++)
{
pthread_join(&thread[i], 0);
}
showCounts(numCount);
return 0;
}
| 0
|
#include <pthread.h>
int **matrix1,**matrix2,**matrix3;
int p;
int f1,c1,f2,c2;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *funcion_hilo(void *id_thread);
void multiplica_matrix(int **matrix1,int **matrix2,int f1,int c1,int c2,int **matrix3);
int main() {
int i,j;
printf("Ingrese filas y luego columnas de la matrix1: \\n" );
scanf("%d%d",&f1,&c1 );
printf("Ingrese filas y luego columnas de la matrix2: \\n" );
scanf("%d%d",&f2,&c2 );
if (c1!= f2){
printf("ERROR:las columnas de la primer matriz deben ser iguales a las filas de la segunda matriz \\n" );
}else{
srand( time( 0 ) );
matrix1 = (int **)calloc(f1, sizeof(int *));
for(i = 0; i < f1; i++){
matrix1[i] = (int *)calloc(c1, sizeof(int));
}
printf("La primer matriz es: \\n");
for ( i = 0; i < f1; i++) {
for ( j = 0; j < c1; j++) {
matrix1[i][j]=rand() %10;
printf("%d ",matrix1[i][j] );
}
printf("\\n");
}
matrix2 = (int **)calloc(f2, sizeof(int *));
for(i = 0; i < f2; i++){
matrix2[i] = (int *)calloc(c2, sizeof(int));
}
printf("La segunda matriz es: \\n");
for ( i = 0; i < f2; i++) {
for ( j = 0; j < c2; j++) {
matrix2[i][j]=rand() %10;
printf("%d ",matrix2[i][j] );
}
printf("\\n");
}
matrix3 = (int **)calloc(f1, sizeof(int *));
for(i = 0; i < f1; i++){
matrix3[i] = (int *)calloc(c2, sizeof(int));
}
printf("La matriz resultado es: \\n" );
pthread_t hilos[f1];
for ( i = 0; i < f1; i++) {
if (pthread_create(&hilos[i],0,funcion_hilo,0)) {
printf("Error al crear el hilo \\n");
abort();
}
}
for (i = 0; i < f1; i++) {
if (pthread_join(hilos[i], 0)) {
printf("ERROR \\n" );
}
}
for(i = 0; i < f1; i++){
free(matrix1[i]);
free(matrix3[i]);
}
free(matrix1);
free(matrix3);
for(i = 0; i < f2; i++){
free(matrix2[i]);
}
free(matrix2);
}
return 0;
}
void *funcion_hilo(void *info){
pthread_mutex_lock(&mutex);
multiplica_matrix(matrix1,matrix2,p,c1,c2,matrix3);
p++;
pthread_mutex_unlock(&mutex);
return 0;
}
void multiplica_matrix(int **matrix1,int **matrix2,int f1,int c1,int c2,int **matrix3){
int j,k;
for ( j = 0; j < c2; j++) {
matrix3[f1][j]=0;
for ( k = 0; k < c1; k++) {
matrix3[f1][j]=matrix3[f1][j]+(matrix1[f1][k]*matrix2[k][j]);
}
printf("%d ",matrix3[f1][j] );
}
printf("\\n");
}
| 1
|
#include <pthread.h>
const int PRODUCT_NUM = 10;
const int BUFFER_SIZE = 4;
int buffer[BUFFER_SIZE];
int rd_idx, wr_idx, g_num;
pthread_mutex_t mutex;
sem_t sem_empty, sem_full;
void ConsumerFunc(void) {
int id = ((int)pthread_self()) % 10000;
volatile int flag = 1;
while (flag) {
sem_wait(&sem_full);
pthread_mutex_lock(&mutex);
printf(" (%d)===>%d(%d)\\n",
rd_idx, buffer[rd_idx], id);
if (buffer[rd_idx] == PRODUCT_NUM) {
pthread_mutex_unlock(&mutex);
return;
}
rd_idx = (rd_idx+1)%BUFFER_SIZE;
pthread_mutex_unlock(&mutex);
sleep(2);
sem_post(&sem_empty);
}
}
void ProducerFunc(void) {
int i;
for (i = 1; i <= PRODUCT_NUM; i++) {
sem_wait(&sem_empty);
pthread_mutex_lock(&mutex);
buffer[wr_idx] = i;
printf("%d===>(%d)\\n", i, wr_idx);
wr_idx = (wr_idx+1)%BUFFER_SIZE;
sleep(1);
pthread_mutex_unlock(&mutex);
sem_post(&sem_full);
}
}
int main(void) {
pthread_t p_tid;
pthread_t c_tid1, c_tid2;
rd_idx = wr_idx = 0;
g_num = 0;
pthread_mutex_init(&mutex, 0);
sem_init(&sem_empty, 0, 1);
sem_init(&sem_full, 0, 0);
pthread_create(&p_tid, 0, (void*)ProducerFunc, 0);
pthread_create(&c_tid1, 0, (void*)ConsumerFunc, 0);
pthread_join(p_tid, 0);
pthread_join(c_tid1, 0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
void* producer();
void* consumer();
pthread_mutex_t lock_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t done_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t not_done_cond = PTHREAD_COND_INITIALIZER;
int flag = 0;
{
int num_e, total_leng, end_of_file;
} bundle;
int main(void)
{
bundle the_info = {0, 0, 0};
pthread_t prod_thread;
pthread_t cons_thread;
int prod_thread_ret = pthread_create(&prod_thread, 0, producer, &the_info);
int cons_thread_ret = pthread_create(&cons_thread, 0, consumer, &the_info);
if(prod_thread_ret != 0)
{
printf("Thread fail to create! Error: %d", prod_thread_ret);
return 1;
}
if(cons_thread_ret != 0)
{
printf("Thread fail to create! Error: %d", cons_thread_ret);
return 1;
}
pthread_join(prod_thread, 0);
pthread_join(cons_thread, 0);
pthread_mutex_destroy(&lock_mutex);
pthread_cond_destroy(&done_cond);
pthread_cond_destroy(¬_done_cond);
pthread_exit(0);
return 0;
}
void* producer(bundle *the_info)
{
int i, cur_char, temp_e, temp_leng = 0;
FILE *my_file;
my_file = fopen("randStrings.txt", "r");
cur_char = fgetc(my_file);
while (the_info->end_of_file != 1)
{
while (cur_char != 10)
{
if (cur_char == 101)
{
temp_e++;
temp_leng++;
}
else if (cur_char != 10 && cur_char != 13)
{
temp_leng++;
}
cur_char = fgetc(my_file);
}
pthread_mutex_lock(&lock_mutex);
if (flag == 1)
{
pthread_cond_wait(¬_done_cond, &lock_mutex);
}
pthread_mutex_unlock(&lock_mutex);
the_info->num_e = temp_e;
the_info->total_leng = temp_leng;
pthread_mutex_lock(&lock_mutex);
flag = 1;
pthread_cond_signal(&done_cond);
pthread_mutex_unlock(&lock_mutex);
temp_e = 0;
temp_leng = 0;
cur_char = fgetc(my_file);
if (cur_char == EOF)
{
the_info->end_of_file = 1;
}
}
return 0;
}
void* consumer(bundle *the_info)
{
int i, temp_e, temp_leng = 0;
FILE *my_file;
my_file = fopen("resultStrings.txt", "w");
while (the_info->end_of_file != 1)
{
pthread_mutex_lock(&lock_mutex);
if (flag == 0)
{
pthread_cond_wait(&done_cond, &lock_mutex);
}
pthread_mutex_unlock(&lock_mutex);
temp_e = the_info->num_e;
temp_leng = the_info->total_leng;
pthread_mutex_lock(&lock_mutex);
flag = 0;
pthread_cond_signal(¬_done_cond);
pthread_mutex_unlock(&lock_mutex);
if (temp_e == 0)
{
for (i = 0; i < temp_leng; i++)
{
fputc(45, my_file);
}
fputc(13, my_file);
fputc(10, my_file);
}
else
{
for (i = 0; i < temp_e; i++)
{
fputc(101, my_file);
}
fputc(13, my_file);
fputc(10, my_file);
}
}
return 0;
}
| 1
|
#include <pthread.h>
FILE *fp1, *fp2, *fp3;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
char buf[1024], buf1[1024], buf2[1024];
char filename[2][1024];
int row[2] = {0};
char *itostr(int i, char *str) {
sprintf(str, "%d", i);
return str;
}
char *genrow(char *res, char *name, int rownum, char *line) {
strcpy(res, name);
strcat(res, ": ");
strcat(res, itostr(rownum, buf));
strcat(res, ": ");
strcat(res, line);
return res;
}
void *read_t1() {
char prefix[1024];
while (1) {
pthread_mutex_lock(&mutex);
if (strlen(buf1) == 0) {
if (feof(fp1))
bzero(buf2, 1024);
else {
if (!fgets(buf1, 1024, fp1)) {
if (feof(fp1) && feof(fp2))
exit(0);
}
if (strlen(buf1) > 0)
fputs(genrow(prefix, filename[0], ++row[0], buf1), fp3);
}
bzero(buf2, 1024);
}
pthread_mutex_unlock(&mutex);
}
return 0;
}
void *read_t2() {
char prefix[1024];
while (1) {
pthread_mutex_lock(&mutex);
if (strlen(buf2) == 0) {
if (feof(fp2))
bzero(buf1, 1024);
else {
if (!fgets(buf2, 1024, fp2)) {
if (feof(fp1) && feof(fp2))
exit(0);
}
if (strlen(buf2) > 0)
fputs(genrow(prefix, filename[1], ++row[1], buf2), fp3);
}
bzero(buf1, 1024);
}
pthread_mutex_unlock(&mutex);
}
return 0;
}
int main(int argc, char *argv[]) {
pthread_t read_thread_1;
pthread_t read_thread_2;
if (argc != 4) {
printf("Error: usage %s <file1> <file2> <file3>\\n", argv[0]);
exit(0);
}
if ((fp1 = fopen(argv[1], "r")) == 0 ||
(fp2 = fopen(argv[2], "r")) == 0 ||
(fp3 = fopen(argv[3], "w")) == 0) {
perror("open file");
exit(0);
}
strcpy(filename[0], argv[1]);
strcpy(filename[1], argv[2]);
bzero(buf1, 1024);
bzero(buf2, 1024);
pthread_create(&read_thread_1, 0, read_t1, 0);
pthread_create(&read_thread_2, 0, read_t2, 0);
pthread_join(read_thread_1, 0);
pthread_join(read_thread_2, 0);
return 0;
}
| 0
|
#include <pthread.h>
int choice =-1;
pid_t pid;
pthread_mutex_t tree;
struct node
{
int key;
struct node* left;
struct node* right;
}*root=0;
struct node* insert(struct node* bn,int t)
{
if(bn==0)
{
bn =(struct node*)malloc(sizeof(struct node));
bn->key=t;
bn->left=0;
bn->right=0;
return bn;
}
if(t<bn->key)
{
bn->left = insert(bn->left,t);
}
else if(t>bn->key)
{
bn->right = insert(bn->right,t);
}
return bn;
}
void searchtree(struct node* bn,int n)
{
if(bn!=0)
{
if(n<bn->key)
{
searchtree(bn->left,n);
}
else if(n>bn->key)
{
searchtree(bn->right,n);
}
else
printf("element found\\n");
return;
}
else
printf("element not present\\n");
}
struct node* findmin(struct node* bn)
{
if(bn->left==0)
return bn;
findmin(bn->left);
}
void remov(struct node* bn,int n)
{
if(bn==0)
{
printf("element not there in tree\\n");
return;
}
if(n<bn->key)
remov(bn->left,n);
else if(n>bn->key)
remov(bn->right,n);
else if(bn->left!=0&&bn->right!=0)
{
bn->key=findmin(bn->right)->key;
remov(bn->right,bn->key);
}
else
{
struct node *old=bn;
bn=(bn->left!=0)?bn->left:bn->right;
free(old);
}
}
void* maketree()
{
pthread_mutex_lock(&tree);
printf("press -1 to terminate process of maketree\\n");
int flag;
printf("enter number\\n");
scanf("%d",&flag);
do
{
root = insert(root,flag);
printf("enter number\\n");
scanf("%d",&flag);
}while(flag!=-1);
pthread_mutex_unlock(&tree);
}
void* search()
{
pthread_mutex_lock(&tree);
int t;
printf("enter no. to be searched\\n");
scanf("%d",&t);
searchtree(root,t);
pthread_mutex_unlock(&tree);
}
void* deltree()
{
pthread_mutex_lock(&tree);
int t;
printf("enter no. to be deleted\\n");
scanf("%d",&t);
remov(root,t);
kill(pid,SIGINT);
pthread_mutex_unlock(&tree);
}
void printtree(struct node* bn)
{
if(bn!=0)
{
printtree(bn->left);
printf("%d ",bn->key);
printtree(bn->right);
}
}
void print()
{
printtree(root);
}
int main()
{
pid=getpid();
signal(SIGINT,print);
root=0;
int flag=-2;
pthread_t tid[4];
pthread_create(&tid[0],0,&maketree,0);
pthread_create(&tid[1],0,&maketree,0);
pthread_create(&tid[2],0,&search,0);
pthread_create(&tid[3],0,&deltree,0);
while(1)
{
printf("1:insert\\n2:search\\n3:delete\\n\\"\\\\ ENTER CHOICE \\\\\\"\\n");
scanf("%d",&choice);
}
return 0;
}
| 1
|
#include <pthread.h>
int shared_resource = 0;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
static void signal_handler(int sig) {
printf("signal handler for %d\\n", sig);
exit(1);
}
void *task2 (void *arg) {
int i, j, tmp, loop;
loop = (int)arg;
for (i=0; i<loop; i++) {
pthread_mutex_lock(&mut);
for (j=0; j<10000; j++) {
tmp = shared_resource;
tmp += 1;
usleep(1);
shared_resource = tmp;
}
printf("Thread [%d]: count = %d / shared_resource = %d\\n",
loop, i, shared_resource);
if (i < loop-1) {
pthread_mutex_unlock(&mut);
}
}
arg = (void *)(shared_resource);
pthread_mutex_unlock(&mut);
pthread_exit((void *)arg);
}
void *task(void *arg) {
int i, j, tmp, loop;
loop = (int)arg;
j = 0;
for (i=0; i<loop; i++) {
j++;
usleep(100000);
printf("Thread [%d]: count = %d / shared_resource = %d\\n", loop, i, j);
}
shared_resource += j;
arg = (void *)(shared_resource);
}
int main() {
signal(SIGINT, signal_handler);
pthread_t thread1, thread2;
int loop1 = 10, loop2 = 20;
pthread_create(&thread1, 0, task2, (void *)loop1);
pthread_create(&thread2, 0, task2, (void *)loop2);
int ret1, ret2;
pthread_join(thread1, (void **)&ret1);
printf("Thread %x finished, return %d.\\n", (int)thread1, ret1);
pthread_join(thread2, (void **)&ret2);
printf("Thread %x finished, return %d.\\n", (int)thread2, ret2);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
int i, n, tid;
void (*task_fun) (void *arg, int tid, int i);
void *task_arg;
} context_t;
static void *start_routine (void *cp)
{
context_t *context = cp;
int tid;
pthread_mutex_lock (&context->mutex);
tid = context->tid++;
pthread_mutex_unlock (&context->mutex);
for (;;) {
int item;
pthread_mutex_lock (&context->mutex);
item = context->i++;
pthread_mutex_unlock (&context->mutex);
if (item >= context->n)
break;
else
context->task_fun (context->task_arg, tid, item);
}
return 0;
}
void compute_tasks (int n, int nthread,
void (*task_fun) (void *arg, int tid, int i),
void *task_arg)
{
int i;
context_t context;
pthread_t *threads = malloc (sizeof (pthread_t) * nthread);
pthread_mutex_init (&context.mutex, 0);
context.i = 0;
context.n = n;
context.tid = 0;
context.task_fun = task_fun;
context.task_arg = task_arg;
for (i = 0; i < nthread; i++)
pthread_create (&threads[i], 0, &start_routine, &context);
for (i = 0; i < nthread; i++)
pthread_join (threads[i], 0);
free (threads);
}
| 1
|
#include <pthread.h>
static int top=0;
static unsigned int arr[(5)];
pthread_mutex_t m;
_Bool flag=(0);
void error(void)
{
ERROR: ;
goto 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==(5))
{
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<(5); i++)
{
pthread_mutex_lock(&m);
tmp = 1%(5);
if ((push(arr,tmp)==(-1)))
error();
pthread_mutex_unlock(&m);
}
}
void *t2(void *arg)
{
int i;
for(i=0; i<(5); i++)
{
pthread_mutex_lock(&m);
if (top>0)
{
if ((pop(arr)==(-2)))
error();
}
pthread_mutex_unlock(&m);
}
}
int main(void)
{
pthread_t id1, 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;
}
| 0
|
#include <pthread.h>
struct Params
{
long startPos;
long endPos;
};
pthread_mutex_t readFlag;
pthread_mutex_t writeFlag;
pthread_mutex_t copyFlag;
pthread_mutex_t changeFlag;
char *progName, *inFile, *outFile;
volatile unsigned short int threadCount = 0;
unsigned short int threadLimit;
void *copy(void *);
void copyAccessRights (char* , char* );
int main(int argc, char **argv)
{
pthread_mutex_init(&readFlag, 0);
pthread_mutex_init(&writeFlag, 0);
pthread_mutex_init(©Flag, 0);
pthread_mutex_init(&changeFlag, 0);
progName = basename(argv[0]);
if (argc != 4)
{
fprintf(stderr, "%s: Nevernoe kolichestvo argumentov (path1 path2 N)\\n", progName);
return 1;
}
threadLimit = atoi(argv[3]);
if (threadLimit <= 0)
{
fprintf(stderr, "%s: Nevernoe kolichestvo potokov (N)\\n", progName);
return 1;
}
FILE *fSrc, *fDest;
inFile = (char *) malloc(strlen(argv[1]) * sizeof(char));
strcpy(inFile, argv[1]);
outFile = (char *) malloc(strlen(argv[2]) * sizeof(char));
strcpy(outFile, argv[2]);
fSrc = fopen(inFile, "r");
if (fSrc == 0)
{
fprintf(stderr, "%s: Ishodiy fail ne naiden\\n", progName);
return 1;
}
long size, partSize;
fseek(fSrc, 0, 2);
size = ftell(fSrc);
fclose(fSrc);
fDest = fopen(outFile, "w+");
fclose(fDest);
copyAccessRights (inFile, outFile);
partSize = size / threadLimit;
int i;
params *p;
pthread_t tid;
for(i = 0; i < threadLimit; i++)
{
p = (params *)malloc(sizeof(params));
p->startPos = partSize * i;
p->endPos = partSize * (i + 1) + (size % threadLimit);
if((i + 1) == threadLimit)
p->endPos = size;
pthread_attr_t threadAttr;
int result = pthread_attr_init(&threadAttr);
if (result != 0)
{
fprintf(stderr, "%s : Oshibka v atributah sozdaniya potoka\\n", progName);
exit(1);
}
result = pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
if (result != 0)
{
fprintf(stderr, "%s : Oshibka v atributah sozdaniya potoka\\n", progName);
exit(1);
}
result = pthread_create(&tid, &threadAttr, copy, (void *)p);
if (result != 0)
{
fprintf(stderr, "%s : Ne mogu sozdat' potok\\n", progName);
}
}
sleep(1);
while (threadCount)
usleep(10);
return 0;
}
void *copy(void *param)
{
params p = *((params *)param);
pthread_mutex_lock(&changeFlag);
threadCount++;
pthread_mutex_unlock(&changeFlag);
long size = p.endPos - p.startPos;
long currPos = p.startPos;
char buf[1024];
int readCount;
FILE *fSrc, *fDest;
while (size != 0)
{
if(size > 1024)
{
readCount = 1024;
size -= 1024;
}
else
{
readCount = size;
size = 0;
}
memset(buf,0, 1024);
fSrc = fopen(inFile,"r");
fseek(fSrc, currPos, 0);
fread(buf, 1, readCount, fSrc);
fflush(fSrc);
fclose(fSrc);
fDest = fopen(outFile,"r+");
pthread_mutex_lock(&writeFlag);
fseek(fDest, currPos, 0);
fwrite(buf, 1, readCount, fDest);
pthread_mutex_unlock(&writeFlag);
fflush(fDest);
fclose(fDest);
currPos += readCount;
}
pthread_mutex_lock(&changeFlag);
threadCount--;
pthread_mutex_unlock(&changeFlag);
free(param);
return 0;
}
void copyAccessRights (char* inFilePath, char* outFilePath)
{
struct stat fileInfo;
stat(inFilePath, &fileInfo);
chmod(outFilePath, fileInfo.st_mode);
}
| 1
|
#include <pthread.h>
int memory[(2*960+1)];
int next_alloc_idx = 1;
pthread_mutex_t m;
int top;
int index_malloc(){
int curr_alloc_idx = -1;
pthread_mutex_lock(&m);
if(next_alloc_idx+2-1 > (2*960+1)){
pthread_mutex_unlock(&m);
curr_alloc_idx = 0;
}else{
curr_alloc_idx = next_alloc_idx;
next_alloc_idx += 2;
pthread_mutex_unlock(&m);
}
return curr_alloc_idx;
}
void EBStack_init(){
top = 0;
}
int isEmpty() {
if(top == 0)
return 1;
else
return 0;
}
int push(int d) {
int oldTop = -1, newTop = -1;
newTop = index_malloc();
if(newTop == 0){
return 0;
}else{
memory[newTop+0] = d;
pthread_mutex_lock(&m);
oldTop = top;
memory[newTop+1] = oldTop;
top = newTop;
pthread_mutex_unlock(&m);
return 1;
}
}
void init(){
EBStack_init();
}
void __VERIFIER_atomic_assert(int r)
{
__atomic_begin();
assert(!r || !isEmpty());
__atomic_end();
}
void push_loop(){
int r = -1;
int arg = __nondet_int();
while(1){
r = push(arg);
__VERIFIER_atomic_assert(r);
}
}
pthread_mutex_t m2;
int state = 0;
void* thr1(void* arg)
{
pthread_mutex_lock(&m2);
switch(state) {
case 0:
EBStack_init();
state = 1;
case 1:
pthread_mutex_unlock(&m2);
push_loop();
break;
}
return 0;
}
int main()
{
pthread_t t1,t2;
pthread_create(&t1, 0, thr1, 0);
pthread_create(&t2, 0, thr1, 0);
return 0;
}
| 0
|
#include <pthread.h>
{
elem_t val;
struct Node* next;
pthread_mutex_t lock;
} Node;
{
Node* head;
pthread_mutex_t lock;
} List;
List* new_list()
{
List* l = malloc(sizeof(List));
l->head = 0;
pthread_mutex_init(&l->lock, 0);
return l;
}
bool insert(List* l, elem_t val)
{
Node* n = malloc(sizeof(Node));
if (n == 0) return 0;
n->val = val;
pthread_mutex_init(&n->lock, 0);
pthread_mutex_lock(&l->lock);
if (l->head == 0)
{
n->next = 0;
l->head = n;
pthread_mutex_unlock(&l->lock);
}
else if (val <= l->head->val)
{
n->next = l->head;
l->head = n;
pthread_mutex_unlock(&l->lock);
}
else
{
Node* prev = l->head;
Node* cur = prev->next;
pthread_mutex_lock(&prev->lock);
if (cur != 0) pthread_mutex_lock(&cur->lock);
pthread_mutex_unlock(&l->lock);
while (cur != 0)
{
if (val <= cur->val)
break;
Node* tmp = prev;
prev = cur;
cur = cur->next;
pthread_mutex_unlock(&tmp->lock);
if (cur != 0) pthread_mutex_lock(&cur->lock);
}
prev->next = n;
n->next = cur;
pthread_mutex_unlock(&prev->lock);
if (cur != 0) pthread_mutex_unlock(&cur->lock);
}
return 1;
}
bool delete(List* l, elem_t val)
{
pthread_mutex_lock(&l->lock);
if (l->head == 0)
{
pthread_mutex_unlock(&l->lock);
return 0;
}
if (l->head->val == val)
{
Node* tmp = l->head->next;
free(l->head);
l->head = tmp;
pthread_mutex_unlock(&l->lock);
return 1;
}
Node* prev = l->head;
Node* cur = prev->next;
pthread_mutex_lock(&prev->lock);
if (cur != 0) pthread_mutex_lock(&cur->lock);
pthread_mutex_unlock(&l->lock);
while (cur != 0)
{
if (val == cur->val)
{
prev->next = cur->next;
pthread_mutex_unlock(&prev->lock);
pthread_mutex_unlock(&cur->lock);
pthread_mutex_destroy(&cur->lock);
free(cur);
return 1;
}
Node* tmp = prev;
prev = cur;
cur = cur->next;
pthread_mutex_unlock(&tmp->lock);
if (cur != 0) pthread_mutex_lock(&cur->lock);
}
pthread_mutex_unlock(&prev->lock);
return 0;
}
bool find(List* l, elem_t val)
{
pthread_mutex_lock(&l->lock);
Node* cur = l->head;
if (cur != 0) pthread_mutex_lock(&cur->lock);
pthread_mutex_unlock(&l->lock);
while (cur != 0)
{
if (val == cur->val)
{
pthread_mutex_unlock(&cur->lock);
return 1;
}
Node* tmp = cur;
cur = cur->next;
pthread_mutex_unlock(cur);
}
return 0;
}
void delete_list(List* l)
{
pthread_mutex_lock(&l->lock);
Node* cur = l->head;
l->head = 0;
if (cur != 0) pthread_mutex_lock(&cur->lock);
pthread_mutex_unlock(&l->lock);
while (cur != 0)
{
Node* tmp = cur;
cur = cur->next;
pthread_mutex_lock(&cur->lock);
pthread_mutex_unlock(&tmp->lock);
free(tmp);
}
pthread_mutex_destroy(&l->lock);
free(l);
}
| 1
|
#include <pthread.h>
int pin_button;
int pin_left;
int pin_right;
} encdata;
int lcd = -1;
int enc_val = 0;
int btn_val = 0;
int shutdown = 0;
pthread_t t_encoders[2];
pthread_mutex_t m_lcd, m_enc, m_btn;
void stdoutup() {
printf("\\033[2K\\r\\tvalue: %i\\tbutton: %i", enc_val, btn_val);
}
void lcdup() {
pthread_mutex_lock(&m_lcd);
stdoutup();
delay(2);
lcdClear(lcd);
delay(4);
lcdPrintf(lcd, "v: %i, b: %i", enc_val, btn_val);
pthread_mutex_unlock(&m_lcd);
}
void cb_button(encdata *enc, int state) {
btn_val = state;
lcdup();
}
void cb_rotate(encdata *enc, int direction) {
enc_val = enc_val + direction;
lcdup();
}
void t_encoder_func(void *args) {
int val_pin_button = 0,
val_pin_left = 0,
val_pin_right = 0;
int l, e, s, b = 0;
encdata *enc = (encdata*)args;
pinMode(enc->pin_button, INPUT); pullUpDnControl(enc->pin_button, PUD_UP);
pinMode(enc->pin_left , INPUT); pullUpDnControl(enc->pin_left , PUD_UP);
pinMode(enc->pin_right , INPUT); pullUpDnControl(enc->pin_right , PUD_UP);
while (1) {
val_pin_button = digitalRead(enc->pin_button);
val_pin_left = digitalRead(enc->pin_left);
val_pin_right = digitalRead(enc->pin_right);
e = (val_pin_left << 1) | val_pin_right;
s = (l << 2) | e;
if (val_pin_button != b) {
b = val_pin_button;
pthread_mutex_lock(&m_btn);
cb_button(enc, val_pin_button);
pthread_mutex_unlock(&m_btn);
}
if (s == 1 || s == 2) {
pthread_mutex_lock(&m_enc);
cb_rotate(enc, --s ? s : --s);
pthread_mutex_unlock(&m_enc);
}
delay(2);
l = e;
if (shutdown) break;
}
return;
}
void sighandler(int signum) {
printf("\\ncaught signal %i\\n", signum);
if (signum == SIGINT || signum == SIGTERM) {
if (lcd > -1) {
printf("clearing lcd...\\n");
delay(20);
lcdClear(lcd);
}
printf("exiting...\\n");
shutdown = 1;
}
}
encdata* mkencdata(encdata *enc, int button, int left, int right) {
enc->pin_button = button;
enc->pin_left = left;
enc->pin_right = right;
return enc;
}
int main(int argc, char* argv[]) {
setbuf(stdout, 0);
printf("\\n\\tkitpi LCD!\\n\\n");
signal(SIGINT, sighandler);
if (wiringPiSetup() == -1) {
printf("wiringPiSetup failed!\\nexiting.\\n");
exit(1);
}
lcd = lcdInit(2, 16, 4, 1, 4, 5, 11, 6, 10, 0, 0, 0, 0);
if (lcd == -1) {
printf("lcdinit failed!\\nexiting.\\n");
exit(2);
}
encdata enc_left, enc_right;
pthread_create(&t_encoders[0], 0, (void *)t_encoder_func, (void*)mkencdata(&enc_left, 3, 0, 2));
pthread_create(&t_encoders[1], 0, (void *)t_encoder_func, (void*)mkencdata(&enc_right, 14, 12, 13));
pthread_join(t_encoders[0], 0);
pthread_join(t_encoders[1], 0);
return 0;
}
| 0
|
#include <pthread.h>
int thread_id;
int num_threads;
int max;
int result;
int *logarray;
int arraysize;
int logfile;
} threadinfo_t;
pthread_mutex_t rl;
void report(char *str) {
pthread_mutex_lock(&rl);
printf("%s\\n",str);
pthread_mutex_unlock(&rl);
}
int ilog(int n) {
int count = 0;
while (n >= 2) {
n = n / 2;
count++;
}
return count;
}
int pseudo_sqrt(int n) {
int l = ilog(n) / 2 - 1;
int m = n;
while (l > 0) {
m = m / 2;
l--;
}
return m;
}
int isprime(int n) {
char buffer[100];
int sq = pseudo_sqrt(n);
int divisor = 3;
while (divisor < n) {
if (n % divisor == 0) {
return 0;
}
divisor+=2;
}
return 1;
}
void *find_primes(threadinfo_t *ti) {
char buffer[100];
int *primes = ti->logarray;
int size = ti->arraysize;
int file = ti->logfile;
int start = 3 + 2*ti->thread_id;
int delta = 2*ti->num_threads;
int upto = ti->max;
int count = 0;
int check = start;
int index = 0;
while (check < upto) {
if (index >= size) {
write(file,primes,index*sizeof(int));
index = 0;
}
primes[index] = check;
index++;
if (isprime(check)) {
count++;
}
check += delta;
}
write(file,primes,index*sizeof(int));
close(file);
ti->result = count;
return 0;
}
int main(int argc, char **argv) {
if (argc < 4) errx(EX_USAGE,"bad number of arguments.");
int p = atoi(argv[1]);
if (p < 1) errx(EX_USAGE,"bad argument value.");
int n = atoi(argv[2]);
if (n < 2) errx(EX_USAGE,"bad argument value.");
int w = atoi(argv[3]);
pthread_t workers[p];
threadinfo_t info[p];
char filename[16];
pthread_mutex_init(&rl,0);
for (int i=0; i<p; i++) {
info[i].thread_id = i;
info[i].num_threads = p;
info[i].max = n;
info[i].arraysize = w;
info[i].logarray = (int *)malloc(w*sizeof(int));
sprintf(filename,"isprime_%03d.log",i);
info[i].logfile = open(filename, O_TRUNC | O_WRONLY);
printf("thread:%d file:%d\\n",i,info[i].logfile);
pthread_create(&(workers[i]),
0,
(void *(*)(void *))find_primes,
(void *)&info[i]);
}
int found = 0;
char buffer[100];
for (int i=0; i<p; i++) {
void *junk;
pthread_join(workers[i],&junk);
found += info[i].result;
}
printf("There were %d primes less than %d found.\\n",found,n);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t space_available = PTHREAD_COND_INITIALIZER;
pthread_cond_t data_available = PTHREAD_COND_INITIALIZER;
int b[10];
int size = 0, front = 0, rear = 0;
void add_buffer(int i) {
b[rear] = i;
rear = (rear + 1) % 10;
size++;
}
int get_buffer(){
int v;
v = b[front];
front = (front + 1) % 10;
size--;
return v ;
}
void* producer(void *arg) {
int i = 0;
printf("producter starting...\\n");
while (1) {
pthread_mutex_lock(&mutex);
if (size == 10) {
pthread_cond_wait(&space_available, &mutex);
}
printf("producer adding %i...\\n", i);
add_buffer(i);
pthread_cond_signal(&data_available);
pthread_mutex_unlock(&mutex);
i++;
}
printf("Producer ends\\n");
pthread_exit(0);
}
void* consumer(void *arg) {
int i = 0, v = 0;
printf("consumer starting...\\n");
for (i=0; i<10; i++) {
pthread_mutex_lock(&mutex);
if (size == 0) {
pthread_cond_wait(&data_available, &mutex);
}
v = get_buffer();
printf("consumer getting %i...\\n", v);
pthread_cond_signal(&space_available);
pthread_mutex_unlock(&mutex);
}
printf("consuming finishing...\\n");
pthread_exit(0);
}
int main(int argc, char* argv[]) {
pthread_t producer_thread;
pthread_t consumer_thread;
pthread_create(&consumer_thread, 0, consumer, 0);
pthread_create(&producer_thread, 0, producer, 0);
pthread_join(consumer_thread, 0);
return 0;
}
| 0
|
#include <pthread.h>
void print_function(int *value);
int main( int argc, char ** argv)
{
pthread_t ** threads = calloc(5, sizeof(pthread_t));
int i,value;
value = 9;
for(i = 0; i < 5; i++){
threads[i] = malloc(sizeof(pthread_t));
pthread_create(threads[i], 0, (void*) print_function, (void*) &value );
}
for(i = 0; i < 5; i++){
pthread_join(*threads[i], 0);
}
free(threads);
return 0;
}
void print_function(int *value)
{
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
if(pthread_mutex_lock(&lock) == 0){
static int x = 0;
int count = 0;
while( count < 5 ){
printf("Value = %d\\n", x);
x += 1;
count += 1;
}
pthread_mutex_unlock(&lock);
}
}
| 1
|
#include <pthread.h>
bool removePet(int index){
pthread_mutex_lock(&lock);
sem_wait(semaforo);
read(pipefd[0], &witness, sizeof(char));
struct dogType *removedPet;
removedPet = malloc(sizeof(struct dogType));
struct dogType *previousPet;
previousPet = malloc(sizeof(struct dogType));
struct dogType *nextPet;
nextPet = malloc(sizeof(struct dogType));
struct dogType *lastPet;
lastPet = malloc(sizeof(struct dogType));
fseek(dataDogs, sizeof(struct dogType)*index, 0);
fread(removedPet, sizeof(struct dogType), 1, dataDogs);
if(removedPet->prevPet == -1){
allHashPets[hashFunction(removedPet->name)] = (removedPet->nextPet);
saveHashArray();
}
if(removedPet->prevPet != -1){
fseek(dataDogs, sizeof(struct dogType)* (removedPet->prevPet-1),0);
fread(previousPet, sizeof(struct dogType), 1, dataDogs);
previousPet->nextPet = removedPet->nextPet;
fseek(dataDogs, sizeof(struct dogType)*(removedPet->prevPet-1),0);
fwrite(previousPet, sizeof(struct dogType), 1, dataDogs);
}
if(removedPet->nextPet != -1){
fseek(dataDogs, sizeof(struct dogType)*(removedPet->nextPet-1),0);
fread(nextPet, sizeof(struct dogType), 1, dataDogs);
nextPet->prevPet = removedPet->prevPet;
fseek(dataDogs, sizeof(struct dogType)*(removedPet->nextPet-1),0);
fwrite(nextPet, sizeof(struct dogType), 1, dataDogs);
}
if(index != (dogAmount-1)){
fseek(dataDogs, sizeof(struct dogType)*(dogAmount-1), 0);
fread(lastPet, sizeof(struct dogType), 1, dataDogs);
if(lastPet->prevPet != -1){
fseek(dataDogs, sizeof(struct dogType)*(lastPet->prevPet-1), 0);
fread(previousPet, sizeof(struct dogType), 1, dataDogs);
previousPet->nextPet = index+1;
fseek(dataDogs, sizeof(struct dogType)*(lastPet->prevPet-1),0);
fwrite(previousPet, sizeof(struct dogType), 1, dataDogs);
}
if(lastPet->nextPet != -1){
fseek(dataDogs, sizeof(struct dogType)*(lastPet->nextPet-1), 0);
fread(nextPet, sizeof(struct dogType), 1, dataDogs);
nextPet->prevPet = index+1;
fseek(dataDogs, sizeof(struct dogType)*(lastPet->nextPet-1),0);
fwrite(nextPet, sizeof(struct dogType), 1, dataDogs);
}
fseek(dataDogs, sizeof(struct dogType)*index, 0);
fwrite(lastPet, sizeof(struct dogType), 1, dataDogs);
if(lastPet->prevPet == -1){
allHashPets[hashFunction(lastPet->name)] = index+1;
saveHashArray();
}
char removedPath[40];
char lastPath[40];
sprintf(removedPath, "%s%i%s","history/server",index+1,".txt");
sprintf(lastPath, "%s%i%s","data/",dogAmount,".txt");
remove(removedPath);
rename(lastPath, removedPath);
}else{
char removedPath[40];
sprintf(removedPath, "%s%i%s","history/server",index+1,".txt");
remove(removedPath);
}
dogAmount = dogAmount-1;
savePetAmount();
FILE *tempfile;
tempfile = fopen("data/Datacopy.dat","w+");
fseek(dataDogs,0,0);
int i;
unsigned int tempvar;
for (i=0; i < (dogAmount)*sizeof(struct dogType); i++){
tempvar = getc(dataDogs);
fputc(tempvar,tempfile);
}
fclose(tempfile);
fclose(dataDogs);
remove("data/dataDogs.dat");
rename("data/Datacopy.dat","data/dataDogs.dat");
dataDogs = fopen("data/dataDogs.dat","r+");
free(removedPet);
free(nextPet);
free(previousPet);
free(lastPet);
write(pipefd[1], &witness, sizeof(char));
sem_post(semaforo);
pthread_mutex_unlock(&lock);
return 1;
}
| 0
|
#include <pthread.h>
int i = 0;
int amountOfPoints = 0;
int totalPoints = 0;
int all = 0;
pthread_t tid[2];
pthread_mutex_t lock;
void *count(void *X)
{
pthread_mutex_lock(&lock);
all = all + amountOfPoints;
for (i=0; i < amountOfPoints; i++)
{
double X = (double)rand() / 32767;
double Y = (double)rand() / 32767;
if (((X * X) + (Y * Y)) <= 1)
{
totalPoints++;
}
}
pthread_mutex_unlock(&lock);
return;
}
int main()
{
printf("Monte Carlo method for calculating PI(mutex lock)\\n");
srand(time(0));
do{
printf("Amount of random Points : \\n");
scanf("%d", &amountOfPoints);
}while (amountOfPoints <= 0);
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("\\n mutex init failed\\n");
return 1;
}
pthread_create(&(tid[0]), 0, &count, 0);
pthread_create(&(tid[1]), 0, &count, 0);
pthread_join(tid[0], 0);
pthread_join(tid[1], 0);
pthread_mutex_destroy(&lock);
double points = 4.0 * totalPoints;
double pi = points / all;
printf("The approximating value of pi for the amount of points (%d) is: %f\\n\\n", amountOfPoints, pi);
return 0;
}
| 1
|
#include <pthread.h>
struct pctool *pctool_init(int buffer_size) {
struct pctool *pctool = (struct pctool *)new(sizeof(struct pctool));
memset(pctool, 0, sizeof(struct pctool));
pctool->buffer_size = buffer_size;
pctool->buffer = (void *)new(pctool->buffer_size * sizeof(void *));
memset(pctool->buffer, 0, pctool->buffer_size * sizeof(void *));
pthread_mutex_init(&pctool->mutex, 0);
pthread_cond_init(&pctool->more, 0);
pthread_cond_init(&pctool->less, 0);
pctool->init = 1;
return pctool;
}
void pctool_put(struct pctool *pctool, void *data) {
pthread_mutex_lock(&pctool->mutex);
while (pctool->occupied >= pctool->buffer_size)
pthread_cond_wait(&pctool->less, &pctool->mutex);
pctool->buffer[pctool->nextin++] = data;
pctool->nextin %= pctool->buffer_size;
pctool->occupied++;
pthread_cond_signal(&pctool->more);
pthread_mutex_unlock(&pctool->mutex);
}
void *pctool_get(struct pctool *pctool) {
void *data;
pthread_mutex_lock(&pctool->mutex);
while(pctool->occupied <= 0)
pthread_cond_wait(&pctool->more, &pctool->mutex);
data = pctool->buffer[pctool->nextout++];
pctool->nextout %= pctool->buffer_size;
pctool->occupied--;
pthread_cond_signal(&pctool->less);
pthread_mutex_unlock(&pctool->mutex);
return data;
}
void pctool_destroy(struct pctool *pctool) {
pctool->init = 0;
delete(pctool->buffer);
pthread_mutex_destroy(&pctool->mutex);
pthread_cond_destroy(&pctool->more);
pthread_cond_destroy(&pctool->less);
delete(pctool);
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.