text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
pthread_mutex_t mutex;
unsigned int counter;
char *buffer_ptr;
struct pthread_args
{
unsigned int tid;
unsigned int chunk_size;
unsigned int* histogram;
};
void * local_histo (void * ptr)
{
unsigned int i;
struct pthread_args *arg = ptr;
while (buffer_ptr[(counter+1)*arg->chunk_size]!=TERMINATOR){
for (i=counter*arg->chunk_size; i<(counter+1)*arg->chunk_size; i++) {
if (buffer_ptr[i]==TERMINATOR)
break;
if (buffer_ptr[i] >= 'a' && buffer_ptr[i] <= 'z')
arg->histogram[buffer_ptr[i]-'a']++;
else if(buffer_ptr[i] >= 'A' && buffer_ptr[i] <= 'Z')
arg->histogram[buffer_ptr[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) {
counter = 0;
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].tid = k;
thread_arg[k].chunk_size = chunk_size;
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];
}
pthread_mutex_destroy(&mutex);
free(thread);
free(thread_arg);
}
| 1
|
#include <pthread.h>
{
double *a;
double *b;
double sum;
int veclen;
} DOTDATA;
DOTDATA dotstr;
pthread_t callThd[4];
pthread_mutex_t mutexsum;
void *dotprod(void *arg)
{
int i, start, end, len ;
long offset;
double mysum, *x, *y;
offset = (long)arg;
len = dotstr.veclen;
start = offset*len;
end = start + len;
x = dotstr.a;
y = dotstr.b;
mysum = 0;
for (i=start; i<end ; i++)
{
mysum += (x[i] * y[i]);
}
pthread_mutex_lock (&mutexsum);
dotstr.sum += mysum;
pthread_mutex_unlock (&mutexsum);
pthread_exit((void*) 0);
}
int main (int argc, char *argv[])
{
long i;
double *a, *b;
void *status;
pthread_attr_t attr;
a = (double*) malloc (4*100*sizeof(double));
b = (double*) malloc (4*100*sizeof(double));
for (i=0; i<100*4; i++) {
a[i]=1;
b[i]=a[i];
}
dotstr.veclen = 100;
dotstr.a = a;
dotstr.b = b;
dotstr.sum=0;
pthread_mutex_init(&mutexsum, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i=0;i<4;i++)
{
pthread_create(&callThd[i], &attr, dotprod, (void *)i);
}
pthread_attr_destroy(&attr);
for(i=0;i<4;i++) {
pthread_join(callThd[i], &status);
}
printf ("Sum = %f \\n", dotstr.sum);
free (a);
free (b);
pthread_mutex_destroy(&mutexsum);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
struct prodcons{
int buffer[8];
pthread_mutex_t lock;
int readpos,writepos;
pthread_cond_t notempty;
pthread_cond_t notfull;
};
void init(struct prodcons *b)
{
pthread_mutex_init(&b->lock,0);
pthread_cond_init(&b->notempty,0);
pthread_cond_init(&b->notfull,0);
b->readpos = 0;
b->writepos = 0;
}
void put_data(struct prodcons * b,int data)
{
pthread_mutex_lock(&b->lock);
while((b->writepos+1)%8==b->readpos)
{
printf("wait for notfull signal\\n");
pthread_cond_wait(&b->notfull,&b->lock);
}
b->buffer[b->writepos] = data;
printf("put-->%d at buffer[%d]\\n",data,b->writepos);
b->writepos++;
if(b->writepos >= 8)
b->writepos = 0;
pthread_cond_signal(&b->notempty);
pthread_mutex_unlock(&b->lock);
}
int get_data(struct prodcons * b)
{
int data;
pthread_mutex_lock(&b->lock);
while(b->writepos==b->readpos)
{
printf("wait for notempty signal\\n");
pthread_cond_wait(&b->notempty,&b->lock);
}
data = b->buffer[b->readpos];
printf(" get-->%d from buffer[%d]\\n",data,b->readpos);
b->readpos++;
if(b->readpos >= 8)
b->readpos = 0;
pthread_cond_signal(&b->notfull);
pthread_mutex_unlock(&b->lock);
return data;
}
struct prodcons buffer;
void * producer(void * data)
{
int n;
for(n = 0;n < 27;n++)
{
put_data(&buffer,n);
if(n==3)
sleep(2);
}
put_data(&buffer,(-1));
printf("producer stopped!\\n");
return 0;
}
void * consumer(void * data)
{
int d;
while(1)
{
d = get_data(&buffer);
if(d == (-1))
break;
}
printf("consumer stopped!\\n");
return 0;
}
int main ( int argc, char *argv[] )
{
pthread_t th_a,th_b;
void * retval;
init(&buffer);
pthread_create(&th_a,0,producer,0);
sleep(1);
pthread_create(&th_b,0,consumer,0);
pthread_join(th_a,&retval);
pthread_join(th_b,&retval);
return 0;
}
| 1
|
#include <pthread.h>
struct prodcons
{
int buffer[2];
pthread_mutex_t lock;
int readpos;
int writepos;
pthread_cond_t notempty;
pthread_cond_t notfull;
};
void init(struct prodcons *prod)
{
pthread_mutex_init(&prod->lock, 0);
pthread_cond_init(&prod->notempty, 0);
pthread_cond_init(&prod->notfull, 0);
prod->readpos = 0;
prod->writepos = 0;
}
void put(struct prodcons *prod, int data)
{
pthread_mutex_lock(&prod->lock);
while((prod->writepos + 1) % 2 == prod->readpos){
printf("producer wait for not full\\n");
pthread_cond_wait(&prod->notfull, &prod->lock);
}
prod->buffer[prod->writepos] = data;
prod->writepos = (prod->writepos + 1)% 2;
pthread_cond_signal(&prod->notempty);
pthread_mutex_unlock(&prod->lock);
}
int get(struct prodcons *prod)
{
int data;
pthread_mutex_lock(&prod->lock);
while(prod->writepos == prod->readpos){
printf("consumer wait for not empty\\n");
pthread_cond_wait(&prod->notempty, &prod->lock);
}
data = prod->buffer[prod->readpos];
prod->readpos = (prod->readpos + 1) % 2;
pthread_cond_signal(&prod->notfull);
pthread_mutex_unlock(&prod->lock);
return data;
}
struct prodcons buffer;
void *producer()
{
int n;
for(n = 0; n <= 5; n++){
printf("producer sleep 1 second ... \\n");
sleep(1);
printf("put the %d product\\n", n);
put(&buffer, n);
}
for(n = 6; n <= 10; n++){
printf("producer sleep 3 second ... \\n");
sleep(3);
printf("put the %d product\\n", n);
put(&buffer, n);
}
put(&buffer, (-1));
printf("producer stopped\\n");
return 0;
}
void *consumer()
{
int d = 0;
while(1){
printf("consumer sleep 2 second ...\\n");
sleep(2);
d = get(&buffer);
printf("get the %d product\\n", d);
if(d == (-1))
break;
}
printf("consumer stopped!\\n");
return 0;
}
int main(int argc, char *argv[])
{
pthread_t th_a, th_b;
void *retval;
init(&buffer);
pthread_create(&th_a, 0, producer, 0);
pthread_create(&th_b, 0, consumer, 0);
pthread_join(th_a, &retval);
pthread_join(th_b, &retval);
return 0;
}
| 0
|
#include <pthread.h>
int counter = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *lock_worker(void *arg) {
for (size_t i = 0; i < 100000; ++i) {
pthread_mutex_lock(&mutex);
++counter;
pthread_mutex_unlock(&mutex);
}
return arg;
}
void *trylock_worker(void *arg) {
for (size_t i = 0; i < 100000; ++i) {
while (pthread_mutex_trylock(&mutex) != 0) {
}
++counter;
pthread_mutex_unlock(&mutex);
}
return arg;
}
void bench(void (*f)(void)) {
clock_t begin = clock();
for (size_t i = 0; i < 100; ++i) {
f();
}
clock_t end = clock();
double time = (double)(end - begin) / CLOCKS_PER_SEC;
double avg_time = time / 100;
printf("Average time spent: %f\\n", avg_time);
}
void bench_lock_workers() {
pthread_t t[10];
int result = 0;
counter = 0;
for (size_t i = 0; i < 10; ++i) {
result = pthread_create(&t[i], 0, lock_worker, 0);
if (result) {
}
}
for (size_t i = 0; i < 10; ++i) {
pthread_join(t[i], 0);
}
}
void bench_trylock_workers() {
pthread_t t[10];
int result = 0;
counter = 0;
for (size_t i = 0; i < 10; ++i) {
result = pthread_create(&t[i], 0, trylock_worker, 0);
if (result) {
}
}
for (size_t i = 0; i < 10; ++i) {
pthread_join(t[i], 0);
}
}
int main(int argc, char *argv[]) {
printf("Benchmarking lock workers...\\n");
bench(bench_lock_workers);
printf("Benchmarking trylock workers...\\n");
bench(bench_trylock_workers);
return 0;
}
| 1
|
#include <pthread.h>
void findPet(char searchName[32], int clientfd, int r){
pthread_mutex_lock(&lock);
sem_wait(semaforo);
read(pipefd[0], &witness, sizeof(char));
char petName[32];
int founds = 0;
int headHash = allHashPets[hashFunction(searchName)];
struct dogType *petFound;
petFound = malloc(sizeof(struct dogType));
while(headHash != -1){
fseek(dataDogs, sizeof(struct dogType)*(headHash-1), 0);
fread(petFound, sizeof(struct dogType), 1, dataDogs);
strcpy(petName,petFound->name);
int i;
for(i = 0; petName[i]; i++){
petName[i] = tolower(petName[i]);
}
for(i = 0; searchName[i]; i++){
searchName[i] = tolower(searchName[i]);
}
if(strcmp(petName, searchName) == 0){
founds = founds +1;
r = send(clientfd, &headHash, sizeof(int), 0);
r = send(clientfd, petFound, sizeof(struct dogType), 0);
}
headHash = petFound->nextPet;
}
if(founds == 0){
headHash = -1;
r = send(clientfd, &headHash, sizeof(int), 0);
}
headHash = -2;
r = send(clientfd, &headHash, sizeof(int), 0);
free(petFound);
write(pipefd[1], &witness, sizeof(char));
sem_post(semaforo);
pthread_mutex_unlock(&lock);
}
| 0
|
#include <pthread.h>
NEW,
PROCESSING,
DONE
}statuses;
int duration;
int id;
statuses status;
pthread_t worker;
} task_t;
pthread_mutex_t lock;
task_t tasks[100];
void* my_thread(void* var){
int frag = 0, k = *((int*)(var + 4));
long long unsigned worker = *((pthread_t*)(var + 8 + sizeof(statuses)));
while(k <= 100){
pthread_mutex_lock(&lock);
while((*(statuses*)(var + 8)) != NEW ){
var += sizeof(task_t);
k++;
}
*((statuses*)(var + 8)) = PROCESSING;
pthread_mutex_unlock(&lock);
if (k >= 100){
break;
}
printf("Task No %d is putting thread No %llu to sleep for %d mks\\n",*((int*)(var + 4)), worker, *((int*)var));
usleep(*((int*)var));
frag++;
pthread_mutex_lock(&lock);
*((statuses*)(var + 8)) = DONE;
pthread_mutex_unlock(&lock);
}
printf("Worker No %llu has fragged %d tasks\\n",worker,frag);
return 0;
}
int main(){
statuses status;
pthread_t thread_id[10];
int result , i;
for (i = 0; i < 100; i++){
tasks[i].id = i;
tasks[i].duration = abs(random() % 1000);
}
for (i = 0; i < 10; i++){
pthread_create(&(tasks[i].worker), 0, my_thread, (void*)(&(tasks[i])));
}
for(i = 0; i < 10; i++){
pthread_join(tasks[i].worker,0);
}
printf("END\\n");
pthread_mutex_destroy(&lock);
return 0;
}
| 1
|
#include <pthread.h>
int stoj = 0;
int dar_od_lovcov = 0;
int dar_od_zberacov = 0;
pthread_mutex_t mutex_dari_lovcov = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_dari_zberacov = PTHREAD_MUTEX_INITIALIZER;
sem_t l_controll, z_controll;
int l_count = 0;
int z_count = 0;
sem_t room_empty;
sem_t l_in_room, z_in_room;
sem_t z_turnstile;
void lov(int id) {
printf("%d lovi\\n", id);
sleep(6);
}
void dar_lov(int id) {
printf("%d daruje lov v chrame\\n", id);
pthread_mutex_lock(&mutex_dari_lovcov);
dar_od_lovcov++;
pthread_mutex_unlock(&mutex_dari_lovcov);
sleep(2);
}
void *lovec( void *ptr ) {
int id = (long) ptr;
while(!stoj) {
lov(id);
sem_wait(&l_controll);
if(l_count == 0) {
printf("Prvy lovec%d\\n", id);
sem_wait(&z_turnstile);
printf("PL zab turn %d\\n", id);
sem_post(&z_controll);
printf("PL odblok controll %d\\n", id);
sem_wait(&room_empty);
printf("PL room_emp %d\\n", id);
}
l_count++;
sem_post(&l_controll);
sem_wait(&l_in_room);
dar_lov(id);
sem_post(&l_in_room);
sem_wait(&l_controll);
l_count--;
if(l_count == 0) sem_post(&room_empty);
sem_post(&l_controll);
}
return 0;
}
void zber(int id) {
printf("%d zbera\\n", id);
}
void dar_zber(int id) {
printf("%d daruje zber\\n", id);
pthread_mutex_lock(&mutex_dari_zberacov);
dar_od_zberacov++;
pthread_mutex_unlock(&mutex_dari_zberacov);
sleep(1);
}
void *zberac( void *ptr ) {
int id = (long) ptr;
while(!stoj) {
zber(id);
sem_wait(&z_turnstile);
sem_post(&z_turnstile);
sem_wait(&z_controll);
if(z_count == 0) sem_wait(&room_empty);
z_count++;
sem_post(&z_controll);
sem_wait(&z_in_room);
dar_zber(id);
sem_post(&z_in_room);
sem_wait(&z_controll);
z_count--;
if(z_count == 0) sem_post(&room_empty);
sem_post(&z_controll);
}
return 0;
}
int main(void) {
long i;
pthread_t lovci[6];
pthread_t zberaci[12];
sem_init(&l_controll, 0, 1);
sem_init(&z_controll, 0, 1);
sem_init(&room_empty, 0, 1);
sem_init(&l_in_room, 0, 4);
sem_init(&z_in_room, 0, 6);
sem_init(&z_turnstile, 0, 1);
for (i=0;i<6;i++) pthread_create( &lovci[i], 0, &lovec, (void*)i);
for (i=0;i<12;i++) pthread_create( &zberaci[i], 0, &zberac, (void*)i);
sleep(30);
stoj = 1;
for (i=0;i<6;i++) pthread_join( lovci[i], 0);
for (i=0;i<12;i++) pthread_join( zberaci[i], 0);
printf("Zberaci darovali %d darov\\n", dar_od_zberacov);
printf("Lovci darovali %d darov\\n", dar_od_lovcov);
exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
int *blink;
} params_t;
void cleanup() {
gpio_unexport(17);
gpio_unexport(18);
}
void sigint_handler(int sig) {
printf("Detected CTROL+C, cleaning up and exiting...\\n");
cleanup();
exit(0);
}
void *blink_function(void *arg) {
struct timespec request;
request.tv_sec = 0;
request.tv_nsec = 1e9 / 5;
params_t params = *((params_t *) arg);
pthread_mutex_t mutex = params.mutex;
int *blink = params.blink;
if (gpio_export(18) == -1) {
cleanup();
exit(1);
}
if (gpio_direction(18, OUT) == -1) {
cleanup();
exit(1);
}
int led_status = LOW;
while (1) {
pthread_mutex_lock(&mutex);
int blink_val = *blink;
pthread_mutex_unlock(&mutex);
if (blink_val) {
led_status = led_status == LOW ? HIGH : LOW;
if (gpio_write(18, led_status) == -1) {
cleanup();
exit(1);
}
}
clock_nanosleep(CLOCK_REALTIME, 0, &request, 0);
}
}
int main() {
params_t params;
pthread_mutex_t mutex;
int blink;
pthread_t tid;
signal(SIGINT, sigint_handler);
pthread_mutex_init(&mutex, 0);
blink = 1;
params.mutex = mutex;
params.blink = &blink;
if (pthread_create(&tid, 0, &blink_function, ¶ms)) {
fprintf(stderr, "Error creating thread\\n");
return 1;
}
if (gpio_export(17) == -1) {
cleanup();
return 1;
}
if (gpio_direction(17, IN) == -1) {
cleanup();
return 1;
}
struct timespec request;
request.tv_sec = 0;
request.tv_nsec = 500 * 1000000;
while (1) {
int button_val = gpio_read(17);
if (button_val == -1) {
cleanup();
return 1;
} else if (button_val == 0) {
printf("Button pressed, toggling blinking...\\n");
pthread_mutex_lock(&mutex);
blink = !blink;
pthread_mutex_unlock(&mutex);
}
clock_nanosleep(CLOCK_REALTIME, 0, &request, 0);
}
}
| 1
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t wait = PTHREAD_COND_INITIALIZER;
void *thr_fn(void *arg)
{
int err, signo;
for (;;) {
err = sigwait(&mask, &signo);
if (err != 0)
err_exit(err, "sigwait failed");
switch (signo) {
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&wait);
return 0;
default:
printf("unexpected signal %d\\n", signo);
exit(1);
}
}
}
int main(void)
{
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0)
err_exit(err, "SIG_BLOCK error");
err = pthread_create(&tid, 0, thr_fn, 0);
if (err != 0)
err_exit(err, "can't create thread");
pthread_mutex_lock(&lock);
while (quitflag == 0)
pthread_cond_wait(&wait, &lock);
pthread_mutex_unlock(&lock);
quitflag = 0;
if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0)
err_sys("SIG_SETMASK err");
exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
static void *increment(void *arg)
{
long *counter = arg;
for(long i=0; i<1000000; i++)
{
pthread_mutex_lock(&mutex);
*counter = *counter+1;
pthread_mutex_unlock(&mutex);
}
return 0;
}
static void *decrement(void *arg)
{
long *counter = arg;
for(long i=0; i<1000000; i++)
{
pthread_mutex_lock(&mutex);
*counter = *counter-1;
pthread_mutex_unlock(&mutex);
}
return 0;
}
int main(void)
{
printf("Hello World\\n");
long *counter = malloc(sizeof(long));
*counter = 0;
printf("in main before threads ds.counter=%ld\\n", *counter);
pthread_t *threads = malloc(2*sizeof(pthread_t));
pthread_mutex_t *mutex;
int rc;
rc = pthread_create(&threads[0], 0, increment, counter);
assert(0 == rc);
rc = pthread_create(&threads[1], 0, decrement, counter);
assert(0 == rc);
for (int i=0; i<2; ++i)
{
rc = pthread_join(threads[i], 0);
printf("Thread number %d is complete\\n", i);
assert(0 == rc);
}
printf("in main after threads counter=%ld\\n", *counter);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
long long int N,i_global;
int n_threads;
int * total_primos;
int ehPrimo(long long int n) {
int i;
if (n<=1) return 0;
if (n==2) return 1;
if (n%2==0) return 0;
for (i=3; i<sqrt(n)+1; i+=2)
if(n%i==0) return 0;
return 1;
}
void * contraPrimosConcorrente(void* t) {
int* tid;
tid = (int *) t;
long long int i_local = 0,n_primos = 0;
pthread_mutex_lock(&mutex);
i_local = i_global;
i_global++;
pthread_mutex_unlock(&mutex);
while(i_local < N){
if(ehPrimo(i_local)){
n_primos++;
}
pthread_mutex_lock(&mutex);
i_local = i_global;
i_global++;
pthread_mutex_unlock(&mutex);
}
total_primos[*tid] = n_primos;
pthread_exit(0);
}
long long int contaPrimos(){
long long int i;
long long n_primos = 0;
for ( i = 0; i < N; ++i)
{
if(ehPrimo(i)) n_primos++;
}
return n_primos;
}
long long int somaArray(int* array){
int i;
long long int total = 0;
for (i = 0; i < n_threads; ++i)
{
total += total_primos[i];
}
return total;
}
void imprimeArray(int * array){
int i;
for (i = 0; i < n_threads; ++i)
{
printf("Total primos[%d]: [%d]\\n",i,array[i] );
}
}
int main(int argc, char *argv[]) {
pthread_t *tid_sistema;
int *tid;
int i;
long long int total_primos_sequencial;
double ini, fim, inicioS, fimS;
if(argc != 3){
printf("--ERRO: Número de argumentos errados. Uso ./lab5.exe n_primo n_threads\\n"); exit(-1);
}
N = atoi(argv[1]);
n_threads = atoi(argv[2]);
GET_TIME(ini);
pthread_mutex_init(&mutex, 0);
total_primos = (int *) malloc(sizeof(int) * n_threads);
if(total_primos==0) {
printf("--ERRO: malloc()\\n"); exit(-1);
}
tid_sistema = (pthread_t *) malloc(sizeof(pthread_t) * n_threads);
if(tid_sistema==0) {
printf("--ERRO: malloc()\\n"); exit(-1);
}
for(i=0; i<n_threads; i++) {
tid = (int *) malloc(sizeof(int));
if(tid == 0) {
printf("--ERRO: malloc()\\n");
exit(-1);
}
*tid = i;
if(pthread_create(&tid_sistema[i], 0, contraPrimosConcorrente, (void *) tid) ){
printf("--ERRO: pthread_create()\\n"); exit(-1);
}
}
for (i=0; i<n_threads; i++) {
if (pthread_join(tid_sistema[i], 0)) {
printf("--ERRO: pthread_join() \\n"); exit(-1);
}
}
GET_TIME(fim);
pthread_mutex_destroy(&mutex);
GET_TIME(inicioS);
total_primos_sequencial = contaPrimos();
GET_TIME(fimS);
printf("Versão Sequencial : Total de primos:[%lld]\\n", total_primos_sequencial);
printf("Versão Concorrente: Total de primos:[%lld]\\n",somaArray(total_primos));
printf("Tempo Sequencial = %lf\\n", fimS-inicioS);
printf("Tempo Concorrente = %lf\\n", fim-ini);
free(tid);
free(tid_sistema);
free(total_primos);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
struct libpthreadpool_heap_t *libpthreadpool_create_heap()
{
struct libpthreadpool_heap_t *ret;
ret = xmalloc(sizeof(struct libpthreadpool_heap_t));
ret->arr = xmalloc(8 * sizeof(struct libpthreadpool_task_t));
ret->len = 8;
ret->occ = 0;
if(pthread_mutex_init(&ret->mtx, 0))
{
perror("[FATAL] unable to initialize heap mtx");
exit(1);
}
if(pthread_cond_init(&ret->cond, 0))
{
perror("[FATAL] unable to initialize heap cond");
exit(1);
}
return ret;
}
static void swim_up(struct libpthreadpool_heap_t *heap)
{
unsigned int i;
unsigned int parent;
struct libpthreadpool_task_t temp;
i = heap->occ - 1;
while(i)
{
if(i & 1)
{
parent = i >> 1;
}
else
{
parent = (i >> 1) - 1;
}
if(heap->arr[i].prio <= heap->arr[parent].prio)
{
return;
}
temp = heap->arr[i];
heap->arr[i] = heap->arr[parent];
heap->arr[parent] = temp;
i = parent;
}
}
static void sink_down(struct libpthreadpool_heap_t *heap)
{
unsigned int i;
unsigned int l_child;
unsigned int r_child;
unsigned int swap_child;
struct libpthreadpool_task_t temp;
i = 0;
while(i < heap->occ)
{
l_child = (i << 1) + 1;
r_child = (i << 1) + 2;
if(l_child < heap->occ && r_child < heap->occ)
{
if(heap->arr[l_child].prio > heap->arr[r_child].prio)
{
swap_child = l_child;
}
else
{
swap_child = r_child;
}
}
else if(l_child < heap->occ)
{
swap_child = l_child;
}
else if(r_child < heap->occ)
{
swap_child = r_child;
}
else
{
return;
}
if(heap->arr[i].prio >= heap->arr[swap_child].prio)
{
return;
}
temp = heap->arr[i];
heap->arr[i] = heap->arr[swap_child];
heap->arr[swap_child] = temp;
i = swap_child;
}
}
void libpthreadpool_add_to_heap(struct libpthreadpool_heap_t *heap, struct libpthreadpool_task_t task)
{
pthread_mutex_lock(&heap->mtx);
if(heap->len == heap->occ)
{
heap->len <<= 1;
heap->arr = realloc(heap->arr, heap->len * sizeof(struct libpthreadpool_task_t));
}
heap->arr[heap->occ] = task;
++heap->occ;
swim_up(heap);
pthread_mutex_unlock(&heap->mtx);
pthread_cond_signal(&heap->cond);
}
struct libpthreadpool_task_t *libpthreadpool_remove_from_heap(struct libpthreadpool_heap_t *heap)
{
struct libpthreadpool_task_t *ret;
pthread_mutex_lock(&heap->mtx);
while(heap->occ == 0)
{
pthread_cond_wait(&heap->cond, &heap->mtx);
}
ret = xmalloc(sizeof(struct libpthreadpool_task_t));
memcpy(ret, &heap->arr[0], sizeof(struct libpthreadpool_task_t));
--heap->occ;
heap->arr[0] = heap->arr[heap->occ];
if(heap->len > 8 && heap->occ <= (heap->len >> 2))
{
heap->len >>= 1;
heap->arr = realloc(heap->arr, heap->len * sizeof(struct libpthreadpool_task_t));
}
sink_down(heap);
pthread_mutex_unlock(&heap->mtx);
return ret;
}
| 1
|
#include <pthread.h>
volatile unsigned int value = 0;
pthread_mutex_t value_mtx = PTHREAD_MUTEX_INITIALIZER;
char* program_name = 0;
void *not_synchronized(void *ntimes)
{
unsigned int i;
for (i = *(unsigned int *)ntimes; i > 0; i--) {
value--;
}
pthread_exit(0);
}
void *synchronized(void *ntimes)
{
unsigned int i;
for (i = *(unsigned int *)ntimes; i > 0; i--) {
pthread_mutex_lock(&value_mtx);
value--;
pthread_mutex_unlock(&value_mtx);
}
pthread_exit(0);
}
void usage()
{
printf("Usage: %s number_of_threads initial_value\\n", program_name);
}
int main(int argc, char **argv)
{
unsigned int initial_value;
unsigned int nthreads;
program_name = argv[0];
if (argc == 3) {
initial_value = abs(atoi(argv[1]));
nthreads = abs(atoi(argv[2]));
if (initial_value == 0 || nthreads == 0) {
usage();
return -1;
}
} else if (argc == 1) {
printf("Using default initial value and number of threads.\\n\\n");
initial_value = 500000;
nthreads = 50;
} else {
usage();
return -1;
}
unsigned int quotient = initial_value / nthreads;
unsigned int remainder = initial_value - (quotient * nthreads);
unsigned int i;
pthread_t* threads = calloc(nthreads, sizeof(pthread_t));
printf("Using initial value %d with %d threads. Each thread will decrement\\n"
"the global value %d times (initial value / number of threads).\\n"
"Resulting value should be %d.\\n\\n",
initial_value,
nthreads,
quotient,
remainder);
value = initial_value;
for (i = 0; i < nthreads; i++) {
if (pthread_create(&threads[i], 0, not_synchronized, "ient) != 0) {
perror("pthread_create");
return -1;
}
}
for (i = 0; i < nthreads; i++) {
if (pthread_join(threads[i], 0) != 0) {
perror("pthread_join");
return -1;
}
}
printf("%i threads, not synchronized; Resulting value is %i\\n", nthreads, value);
value = initial_value;
for (i = 0; i < nthreads; i++) {
if (pthread_create(&threads[i], 0, synchronized, "ient) != 0) {
perror("pthread_create");
return -1;
}
}
for (i = 0; i < nthreads; i++) {
if (pthread_join(threads[i], 0) != 0) {
perror("pthread_join");
return -1;
}
}
printf("%i threads, synchronized; Resulting value is %i\\n", nthreads, value);
free(threads);
return 0;
}
| 0
|
#include <pthread.h>
int nitems;
int buff[100000];
struct {
pthread_mutex_t mutex;
int nput;
int nval;
} put = {
PTHREAD_MUTEX_INITIALIZER
};
struct {
pthread_mutex_t mutex;
pthread_cond_t cond;
int nready;
} nready = {
PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER
};
void * produce(void *);
void * consume(void *);
int main(int argc, char ** argv) {
int i, nthreads, count[100];
pthread_t tid_produce[100], tid_consume;
if (argc != 3) {
return -1;
}
nitems = min(atoi(argv[1]), 100000);
nthreads = min(atoi(argv[2]), 100);
pthread_setconcurrency(nthreads + 1);
for (i = 0; i < nthreads; ++i) {
count[i] = 0;
pthread_create(&tid_produce[i], 0, produce, &count[i]);
}
pthread_create(&tid_consume, 0, consume, 0);
for (i = 0; i < nthreads; ++i) {
pthread_join(tid_produce[i], 0);
printf("count[%d] = %d\\n", i, count[i]);
}
pthread_join(tid_consume, 0);
return 0;
}
void * produce(void * arg) {
for (;;) {
pthread_mutex_lock(&put.mutex);
if (put.nput >= nitems) {
pthread_mutex_unlock(&put.mutex);
return 0;
}
buff[put.nput] = put.nval;
put.nput++;
put.nval++;
pthread_mutex_unlock(&put.mutex);
pthread_mutex_lock(&nready.mutex);
if (nready.nready == 0) {
pthread_cond_signal(&nready.cond);
}
nready.nready++;
pthread_mutex_unlock(&nready.mutex);
*((int*)arg) += 1;
}
return 0;
}
void * consume(void * arg) {
int i;
for (i = 0; i < nitems; ++i) {
pthread_mutex_lock(&nready.mutex);
while (nready.nready == 0) {
pthread_cond_wait(&nready.cond, &nready.mutex);
}
nready.nready--;
pthread_mutex_unlock(&nready.mutex);
if (buff[i] != i) {
printf("buff[%d] = %d\\n", i, buff[i]);
}
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
sem_t full, empty;
buffer_type buffer[5];
int counter;
pthread_t thread_id;
pthread_attr_t attr;
void *producer_thread(void *param);
void *consumer_thread(void *param);
void initializi() {
pthread_mutex_init(&mutex, 0);
sem_init(&full, 0, 0);
sem_init(&empty, 0, 5);
pthread_attr_init(&attr);
counter = 0;
}
void *producer_thread(void *param) {
buffer_type item;
while(1) {
int rNum = rand() / 100000000;
sleep(rNum);
item = rand();
sem_wait(&empty);
pthread_mutex_lock(&mutex);
if(produce_item(item)) {
fprintf(stderr, " Producer report error condition\\n");
}
else {
printf("Producer working %d\\n", item);
}
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void *consumer_thread(void *param) {
buffer_type item;
while(1) {
int rNum = rand() / 100000000;
sleep(rNum);
sem_wait(&full);
pthread_mutex_lock(&mutex);
if(consume_item(&item)) {
fprintf(stderr, "Consumer report error condition\\n");
}
else {
printf("Consumer working %d\\n", item);
}
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
int produce_item(buffer_type item) {
if(counter < 5) {
buffer[counter] = item;
counter++;
return 0;
}
else {
return -1;
}
}
int consume_item(buffer_type *item) {
if(counter > 0) {
*item = buffer[(counter-1)];
counter--;
return 0;
}
else {
return -1;
}
}
int main(int argc, char *argv[]) {
if(argc != 4) {
fprintf(stderr, "./a.out <total sleep time> <no of produce thread> <no of consumer threads>");
}
int totalsleep = atoi(argv[1]),nConsumer = atoi(argv[3]),nProducer = atoi(argv[2]);
initializi();
int i;
for(i = 0; i < nConsumer; i++) {
pthread_create(&thread_id,&attr,consumer_thread,0);
}
for( i = 0; i < nProducer; i++) {
pthread_create(&thread_id,&attr,producer_thread,0);
}
sleep(totalsleep);
printf("finished sleep time of main \\t%d\\t seconds \\n",totalsleep);
exit(0);
}
| 0
|
#include <pthread.h>
static time_t update_config_time;
static time_t update_sector_time;
extern pthread_mutex_t ourMutex;
void elf_update_timer_init(void)
{
update_config_time = time(0);
update_sector_time = time(0);
}
void elf_update_timer_handler(void)
{
time_t now = time(0);
if ((now - update_config_time) >= elf_get_config(CFG_UPDATE_CONFIG_TIMEOUT))
{
update_config_time = time(0);
log_printf(LOG_INFO, "Update Configuration");
pthread_mutex_lock(&ourMutex);
config_refresh_site();
pthread_mutex_unlock(&ourMutex);
pthread_mutex_lock(&ourMutex);
data_refresh_for_site();
pthread_mutex_unlock(&ourMutex);
}
if ((now - update_sector_time) >= elf_get_config(CFG_UPDATE_SECTOR_TIMEOUT))
{
update_sector_time = time(0);
log_printf(LOG_INFO, "Update Area/Zone/Energy Manager/Switches");
pthread_mutex_lock(&ourMutex);
data_refresh_for_site();
pthread_mutex_unlock(&ourMutex);
}
}
| 1
|
#include <pthread.h>
int ringbuffer_empty(struct ringbuffer_s *rb)
{
if (0 == rb->fill) {
return 1;
}else {
return 0;
}
}
int ringbuffer_full(struct ringbuffer_s *rb)
{
if (rb->size == rb->fill) {
return 1;
}else {
return 0;
}
}
int ringbuffer_currentSize(struct ringbuffer_s *rb)
{
return rb->fill;
}
int ringbuffer_read(struct ringbuffer_s *rb, unsigned char* buf, unsigned int len)
{
pthread_mutex_lock( &(rb->mutex));
if (rb->fill >= len) {
if (rb->write > rb->read) {
memcpy(buf, rb->read, len);
rb->read += len;
}else if (rb->write < rb->read) {
int len1 = rb->buffer + rb->size - 1 - rb->read + 1;
if (len1 >= len) {
memcpy(buf, rb->read, len);
rb->read += len;
} else {
int len2 = len - len1;
memcpy(buf, rb->read, len1);
memcpy(buf + len1, rb->buffer, len2);
rb->read = rb->buffer + len2;
}
}
rb->fill -= len;
pthread_mutex_unlock( &(rb->mutex));
return len;
} else {
pthread_mutex_unlock( &(rb->mutex));
return 0;
}
}
int ringbuffer_clear(struct ringbuffer_s *rb)
{
pthread_mutex_lock( &(rb->mutex));
rb->size = RINGBUFFER_SIZE;
memset(rb->buffer, 0, rb->size);
rb->fill = 0;
rb->read = rb->buffer;
rb->write = rb->buffer;
pthread_mutex_unlock( &(rb->mutex));
return 0;
}
int ringbuffer_write(struct ringbuffer_s *rb, unsigned char* buf, unsigned int len)
{
pthread_mutex_lock( &(rb->mutex));
if (rb->size - rb->fill < len) {
pthread_mutex_unlock( &(rb->mutex));
return 0;
}
else {
if (rb->write >= rb->read) {
int len1 = rb->buffer + rb->size - rb->write;
if (len1 >= len) {
memcpy(rb->write, buf, len);
rb->write += len;
} else {
int len2 = len - len1;
memcpy(rb->write, buf, len1);
memcpy(rb->buffer, buf+len1, len2);
rb->write = rb->buffer + len2;
}
} else {
memcpy(rb->write, buf, len);
rb->write += len;
}
rb->fill += len;
pthread_mutex_unlock( &(rb->mutex));
return len;
}
}
struct ringbuffer_s * ringbuffer_init(void)
{
struct ringbuffer_s *rb = 0;
rb = (struct ringbuffer_s *)malloc(sizeof(struct ringbuffer_s));
if(0 == rb){
printf("error\\n");
}
rb->size = RINGBUFFER_SIZE;
memset(rb->buffer, 0, rb->size);
rb->fill = 0;
rb->read = rb->buffer;
rb->write = rb->buffer;
pthread_mutex_init(&(rb->mutex),0);
return rb;
}
| 0
|
#include <pthread.h>
int count = 0;
pthread_t t;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *thread_func(void *p)
{
while (count < 50)
{
pthread_mutex_lock(&mutex);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("----- thread: i = %d\\n", i+1);
}
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
}
int main(int argc, char *argv[])
{
int firstrun = 1;
while (count < 50)
{
pthread_mutex_lock(&mutex);
if (firstrun)
{
pthread_create(&t, 0, thread_func, 0);
firstrun = 0;
}
pthread_cond_wait(&cond, &mutex);
int i = 0;
for (i = 0; i < 100; i++)
{
printf("==%d== main: i = %d\\n", count+1, i+1);
}
pthread_mutex_unlock(&mutex);
count++;
}
pthread_join(t, 0);
return 0;
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
unsigned int __VERIFIER_nondet_uint();
static int top=0;
static unsigned int arr[(800)];
pthread_mutex_t m;
_Bool flag=(0);
void error(void)
{
ERROR: __VERIFIER_error(); return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
return (top==0) ? (1) : (0);
}
int push(unsigned int *stack, int x)
{
if (top==(800))
{
printf("stack overflow\\n");
return (-1);
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (top==0)
{
printf("stack underflow\\n");
return (-2);
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for(i=0; i<(800); i++)
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint()%(800);
if ((push(arr,tmp)==(-1)))
error();
pthread_mutex_unlock(&m);
}
return 0;
}
void *t2(void *arg)
{
int i;
for(i=0; i<(800); i++)
{
pthread_mutex_lock(&m);
if (top>0)
{
if ((pop(arr)==(-2)))
error();
}
pthread_mutex_unlock(&m);
}
return 0;
}
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>
extern pthread_mutex_t public_crc16_mutex;
extern pthread_mutex_t public_crccheck_mutex;
unsigned short crc16_ccitt_table[256] ={
0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,
0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,
0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,
0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,
0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,
0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,
0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,
0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,
0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,
0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,
0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78
};
unsigned short crc16_calc(unsigned char* ptr, unsigned int len)
{
unsigned short crc_reg = 0x0;
pthread_mutex_lock(&public_crc16_mutex);
while (len--)
crc_reg = (crc_reg >> 8) ^ crc16_ccitt_table[(crc_reg ^ *ptr++) & 0xff];
pthread_mutex_unlock(&public_crc16_mutex);
return crc_reg;
}
unsigned char crc16_check(unsigned char *data, unsigned short datalen)
{
unsigned short calced_crc_val = 0, recved_crc_val = 0;
unsigned char check_result = 0;
pthread_mutex_lock(&public_crccheck_mutex);
if(data == 0 || datalen == 0 || datalen > 2048){
check_result = 0;
pthread_mutex_unlock(&public_crccheck_mutex);
return check_result;
}
recved_crc_val = data[datalen-3] | data[datalen-2] << 8;
calced_crc_val = crc16_calc(&data[1], datalen - 4);
if(calced_crc_val == recved_crc_val){
check_result = 1;
}else{
check_result = 0;
}
pthread_mutex_unlock(&public_crccheck_mutex);
return check_result;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
int cnt;
void espera_activa( int tiempo) {
time_t t;
t = time(0) + tiempo;
while(time(0) < t);
}
void *tareaA( void * args) {
printf("tareaA::voy a dormir\\n");
sleep(3);
printf("tareaA::me despierto y pillo mutex\\n");
pthread_mutex_lock(&mutex);
printf("tareaA::incremento valor\\n");
++cnt;
printf("tareaA::desbloqueo mutex\\n");
pthread_mutex_unlock(&mutex);
printf("tareaA::FINISH\\n");
}
void *tareaM( void * args) {
printf("\\ttareaM::me voy a dormir\\n");
sleep(5);
printf("\\ttareaM::me despierto y hago espera activa\\n");
espera_activa(15);
printf("\\ttareaM::FINSIH\\n");
}
void *tareaB( void * args) {
printf("\\t\\ttareaB::me voy a dormir\\n");
sleep(1);
printf("\\t\\ttareaB::me despierto y pillo mutex\\n");
pthread_mutex_lock(&mutex);
printf("\\t\\ttareaB::espera activa\\n");
espera_activa(7);
printf("\\t\\ttareaB::incremento cnt\\n");
++cnt;
printf("\\t\\ttareaB::suelto mutex\\n");
pthread_mutex_unlock(&mutex);
printf("\\t\\ttareaB::FINISH\\n");
}
int main() {
pthread_t hebraA, hebraM, hebraB;
pthread_attr_t attr;
pthread_mutexattr_t attrM;
struct sched_param prio;
cnt = 0;
pthread_mutexattr_init(&attrM);
if( pthread_mutexattr_setprotocol(&attrM, PTHREAD_PRIO_NONE) != 0) {
printf("ERROR en __set_protocol\\n");
exit(-1);
}
pthread_mutex_init(&mutex, &attrM);
if( pthread_attr_init( &attr) != 0) {
printf("ERROR en __attr_init\\n");
exit(-1);
}
if( pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED) != 0){
printf("ERROR __setinheritsched\\n");
exit(-1);
}
if( pthread_attr_setschedpolicy( &attr, SCHED_FIFO) != 0) {
printf("ERROR __setschedpolicy\\n");
exit(-1);
}
int error;
prio.sched_priority = 1;
if( pthread_attr_setschedparam(&attr, &prio) != 0) {
printf("ERROR __attr_setschedparam %d\\n", error);
exit(-1);
}
if( (error=pthread_create(&hebraB, &attr, tareaB, 0)) != 0) {
printf("ERROR __pthread_create \\ttipo: %d\\n", error);
exit(-1);
}
prio.sched_priority = 2;
if( pthread_attr_setschedparam(&attr, &prio) != 0) {
printf("ERROR __attr_setschedparam\\n");
exit(-1);
}
if( pthread_create(&hebraM, &attr, tareaM, 0) != 0) {
printf("ERROR __pthread_create\\n");
exit(-1);
}
prio.sched_priority = 3;
if( pthread_attr_setschedparam(&attr, &prio) != 0) {
printf("ERROR __attr_setschedparam\\n");
exit(-1);
}
if( pthread_create(&hebraA, &attr, tareaA, 0) != 0) {
printf("ERROR __pthread_create\\n");
exit(-1);
}
pthread_join(hebraA, 0);
pthread_join(hebraM, 0);
pthread_join(hebraB, 0);
return 0;
}
| 0
|
#include <pthread.h>
void initializeData(struct ElevatorData *ed);
int main(){
struct ElevatorData x;
initializeData(&x);
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, 0);
pthread_t threads[4];
struct ArgumentData ad;
ad.ed = &x;
ad.mutex = &mutex;
int error;
error = pthread_create(&threads[0], 0, &irTimeoutFunction, &ad);
error = pthread_create(&threads[1], 0, &irInterruptFunction, &ad);
error = pthread_create(&threads[2], 0, &reachFloorInterruptFunction, &ad);
error = pthread_create(&threads[3], 0, &keyInterruptFunction, &ad);
while(1){
pthread_mutex_lock(&mutex);
if(x.reachedFloorFlag == 1){
logString("Reached Floor Flag Hit", LOG_LEVEL_DEBUG);
if(x.nextFloor > x.currentFloor) {
logString("Moving up a floor", LOG_LEVEL_DEBUG);
x.currentFloor = x.currentFloor + 1;
}
else if(x.nextFloor < x.currentFloor) {
logString("Moving down a floor", LOG_LEVEL_DEBUG);
x.currentFloor = x.currentFloor - 1;
}
if(x.nextFloor == x.currentFloor) {
logString("Opening Door", LOG_LEVEL_DEBUG);
openDoorRoutine(&x);
x.nextFloor = dequeueFloor(&x);
if(x.nextFloor == QUEUE_ERROR){
logString("QUEUE_ERROR", LOG_LEVEL_ERROR);
x.nextFloor = x.currentFloor;
}
}
logString("Reached floor flag end", LOG_LEVEL_DEBUG);
x.reachedFloorFlag = 0;
}
if(x.nextFloor < x.currentFloor) {
logString("MovingDown", LOG_LEVEL_SUPERDEBUG);
toggleMotorDown(ELEVATOR_DEFAULT_SPEED_DOWN);
}
if(x.nextFloor > x.currentFloor) {
logString("MovingUp", LOG_LEVEL_SUPERDEBUG);
toggleMotorUp(ELEVATOR_DEFAULT_SPEED_UP);
}
if(x.nextFloor == x.currentFloor){
logString("Not Moving", LOG_LEVEL_SUPERDEBUG);
toggleMotorOff();
}
pthread_mutex_unlock(&mutex);
}
pthread_mutex_destroy(&mutex);
return 0;
}
void initializeData(struct ElevatorData *ed){
int i = 0;
ed->internalFloorRequests = (int*) malloc(sizeof(int) * (2 + ((NUMBER_OF_FLOORS - 2) * 2)));
for(i = 0; i < (2 + ((NUMBER_OF_FLOORS - 2) * 2)); i++){
ed->internalFloorRequests[i] = 0;
}
ed->externalFloorRequests = (int*) malloc(sizeof(int) * NUMBER_OF_FLOORS);
for(i = 0; i < NUMBER_OF_FLOORS; i++){
ed->externalFloorRequests[i] = 0;
}
ed->queueSize = INITIAL_QUEUE_SIZE;
ed->floorQueue = (int*) malloc(sizeof(int) * ed->queueSize);
for(i = 0; i < ed->queueSize; i++){
ed->floorQueue[i] = QUEUE_EMPTY_FLAG;
}
ed->reachedFloorFlag = 0;
ed->stopProgramFlag = 0;
ed->doorFlag = 0;
ed->lastIRTime = 0;
ed->doorOpenFlag = 0;
ed->initialDoorWaitOverFlag = 0;
ed->currentFloor = 1;
ed->nextFloor = 1;
}
| 1
|
#include <pthread.h>
struct stack {
char x[PTHREAD_STACK_MIN];
};
static pthread_mutex_t mutex[(503)];
static int data[(503)];
static struct stack stacks[(503)];
static void* thread(void *num)
{
int l = (int)num;
int r = (l+1) % (503);
int token;
while(1) {
pthread_mutex_lock(mutex + l);
token = data[l];
if (token) {
data[r] = token - 1;
pthread_mutex_unlock(mutex + r);
}
else {
printf("%i\\n", l+1);
exit(0);
}
}
}
int main(int argc, char **argv)
{
int i;
pthread_t cthread;
pthread_attr_t stack_attr;
if (argc != 2)
exit(255);
data[0] = atoi(argv[1]);
pthread_attr_init(&stack_attr);
for (i = 0; i < (503); i++) {
pthread_mutex_init(mutex + i, 0);
pthread_mutex_lock(mutex + i);
pthread_attr_setstack(&stack_attr, &stacks[i], sizeof(struct stack));
pthread_create(&cthread, &stack_attr, thread, (void*)i);
}
pthread_mutex_unlock(mutex + 0);
pthread_join(cthread, 0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t m[5];
void *tfn(void *arg)
{
int i,l,r;
srand(time(0));
i=(int)arg;
if(i==4)
l=0,r=i;
else
l=i;r=i+1;
for(;;)
{
pthread_mutex_lock(&m[l]);
if(pthread_mutex_trylock(&m[r])==0)
{
printf("\\t%c is eating \\n",'A'+i);
pthread_mutex_unlock(&m[r]);
}
pthread_mutex_unlock(&m[l]);
sleep(rand()%5);
}
return 0;
}
int main()
{
int i;
pthread_t tid[5];
for(i=0;i<5;++i)
{
pthread_mutex_init(&m[i],0);
}
for(i=0;i<5;++i)
pthread_create(&tid[i],0,tfn,(void *)i);
for(i=0;i<5;++i)
pthread_join(tid[i],0);
for(i=0;i<5;++i)
pthread_mutex_destroy(&m[i]);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t cnt_mutex = PTHREAD_MUTEX_INITIALIZER;
int shmid;
key_t key;
int SHMSZ = sizeof(int);
struct Stuff {
int* shm_ptr;
};
void * Count(void * stuff)
{
int i, tmp;
for(i = 0; i < 1000000; i++)
{
int* ptr = ((struct Stuff*) stuff)->shm_ptr;
pthread_mutex_lock (&cnt_mutex);
tmp = *ptr;
tmp = tmp+1;
*ptr = tmp;
pthread_mutex_unlock (&cnt_mutex);
}
pthread_exit(0);
}
int main(int argc, char * argv[])
{
pthread_t tid1, tid2, tid3, tid4, tid5;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_mutex_init(&cnt_mutex, 0);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
key = IPC_PRIVATE;
if ((shmid = shmget(key, SHMSZ, IPC_PRIVATE | IPC_CREAT | 0666 )) < 0) {
perror("shmget");
exit(1);
}
int* shm;
shm = (int *) shmat(shmid, 0, 0);
*shm = 0;
struct Stuff stuffs;
stuffs.shm_ptr = shm;
if(pthread_create(&tid1, &attr, Count, &stuffs))
{
printf("\\n ERROR creating thread 1");
exit(1);
}
if(pthread_create(&tid2, &attr, Count, &stuffs))
{
printf("\\n ERROR creating thread 2");
exit(1);
}
if(pthread_create(&tid3, &attr, Count, &stuffs))
{
printf("\\n ERROR creating thread 3");
exit(1);
}
if(pthread_create(&tid4, &attr, Count, &stuffs))
{
printf("\\n ERROR creating thread 4");
exit(1);
}
if(pthread_create(&tid5, &attr, Count, &stuffs))
{
printf("\\n ERROR creating thread 5");
exit(1);
}
if(pthread_join(tid1, 0))
{
printf("\\n ERROR joining thread");
exit(1);
}
if(pthread_join(tid2, 0))
{
printf("\\n ERROR joining thread");
exit(1);
}
if(pthread_join(tid3, 0))
{
printf("\\n ERROR joining thread");
exit(1);
}
if(pthread_join(tid4, 0))
{
printf("\\n ERROR joining thread");
exit(1);
}
if(pthread_join(tid5, 0))
{
printf("\\n ERROR joining thread");
exit(1);
}
if (*shm < 5 * 1000000)
printf("\\n BOOM! cnt is [%d], should be %d\\n", *shm, 5*1000000);
else
printf("\\n OK! cnt is [%d]\\n", *shm);
shmctl(shmid, IPC_RMID, 0);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
char **memoryTrace;
int lastIndex = 1024 - 1;
int memoryIndex = 0;
void markMemory(char *data);
pthread_mutex_t writeMutex;
void initMyMalloc()
{
memoryTrace = malloc(1024*sizeof(char *));
memset(memoryTrace,0,1024*sizeof(char *));
pthread_mutex_init(&writeMutex,0);
}
char *myNewDebug(int length,char *memoryName)
{
struct LOCAL_MALLOC_DATA *localdata = (struct LOCAL_MALLOC_DATA*)malloc(sizeof(struct LOCAL_MALLOC_DATA));
memset(localdata,0,sizeof(struct LOCAL_MALLOC_DATA));
localdata->data = malloc(length);
memset(localdata->data, 0, length);
memcpy(localdata->name, memoryName, 31);
markMemory((char *)localdata);
return localdata->data;
}
char *myNew(int length)
{
char *data = malloc(length);
memset(data,0,length);
}
void markMemory(char *data)
{
pthread_mutex_lock(&writeMutex);
memoryTrace[memoryIndex] = data;
memoryIndex++;
if(memoryIndex > lastIndex)
{
char **temp = malloc((lastIndex + 1)*2*sizeof(char *));
memcpy(temp, memoryTrace,(lastIndex + 1) * sizeof(char *));
free(memoryTrace);
memoryTrace = temp;
lastIndex = (lastIndex + 1)*2 - 1;
}
pthread_mutex_unlock(&writeMutex);
}
void myFreeDebug(char *data)
{
pthread_mutex_lock(&writeMutex);
int count = memoryIndex - 1;
for (; count >= 0; count--)
{
struct LOCAL_MALLOC_DATA *p = (struct LOCAL_MALLOC_DATA *)memoryTrace[count];
if(p->data == data)
{
if(p->data != 0)
{
free(p->data);
}
free(p);
if(count != memoryIndex - 1)
{
memcpy(&memoryTrace[count], &memoryTrace[count + 1],(memoryIndex - count - 1)*sizeof(char *));
}
memoryIndex--;
pthread_mutex_unlock(&writeMutex);
return;
}
}
pthread_mutex_unlock(&writeMutex);
}
void dumpMemory()
{
pthread_mutex_lock(&writeMutex);
int count = memoryIndex - 1;
for (; count >= 0; count--)
{
struct LOCAL_MALLOC_DATA *p = (struct LOCAL_MALLOC_DATA *)memoryTrace[count];
if(p != 0)
{
printf("memory[%s] is still used!!! \\n",p->name);
}
}
pthread_mutex_unlock(&writeMutex);
}
| 1
|
#include <pthread.h>
pthread_t threads[4];
pthread_mutex_t lock;
int pearls = 1000;
double A=0;
double B=0;
double C=0;
double D=0;
void * takePearlsAB(void *arg){
double ten= 0.10;
while(pearls > 0){
if(threads[0]){
pthread_mutex_lock(&lock);
printf("Pirate A took: %.2lf pearls...\\n", ceil(pearls*ten));
A += ceil(pearls*ten);
pearls = pearls - ceil(pearls*ten);
pthread_mutex_unlock(&lock);
}
if(threads[1]){
pthread_mutex_lock(&lock);
printf("Pirate B took: %.2lf pearls...\\n", ceil(pearls*ten));
B += ceil(pearls*ten);
pearls = pearls - ceil(pearls*ten);
pthread_mutex_unlock(&lock);
}
sleep(2);
}
}
void * takePearlsCD(void *arg){
double fifteen= 0.15;
while(pearls > 0){
if(threads[2]){
pthread_mutex_lock(&lock);
printf("Pirate C took: %.2lf pearls...\\n", ceil(pearls*fifteen));
C += ceil(pearls*fifteen);
pearls = pearls - ceil(pearls*fifteen);
pthread_mutex_unlock(&lock);
}
if(threads[3]){
pthread_mutex_lock(&lock);
printf("Pirate D took: %.2lf pearls...\\n", ceil(pearls*fifteen));
D += ceil(pearls*fifteen);
pearls = pearls - ceil(pearls*fifteen);
pthread_mutex_unlock(&lock);
}
sleep(1);
}
}
void printTotal(double A, double B, double C, double D){
int sum = 0;
sum = A+B+C+D;
printf("\\nPirate A: %.2lf Pearls\\n", A);
printf("Pirate B: %.2lf Pearls\\n", B);
printf("Pirate C: %.2lf Pearls\\n", C);
printf("Pirate D: %.2lf Pearls\\n", D);
printf("Amount of Pearls: %d\\n", sum);
}
int main(void){
pthread_setconcurrency(4);
if(pthread_mutex_init(&lock, 0) != 0){
printf("ERROR: Failed to create Lock\\n");
return 1;
}
pthread_create(&(threads[0]), 0, &takePearlsAB, 0);
pthread_create(&(threads[1]), 0, &takePearlsAB, 0);
pthread_create(&(threads[2]), 0, &takePearlsCD, 0);
pthread_create(&(threads[3]), 0, &takePearlsCD, 0);
sleep(10);
printTotal(A, B, C, D);
pthread_mutex_destroy(&lock);
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
int len;
char data[0];
}QueueNode;
int size;
int head;
int tail;
int num;
pthread_mutex_t lock;
char buffer[0];
}Queue;
Queue* queue_init( int size){
Queue *p;
p = (Queue*)malloc(size);
memset(p, 0, sizeof(Queue));
size -= (int)(((Queue*)0)->buffer);
p->size = size;
p->num = p->head = p->tail = 0;
pthread_mutex_init(&p->lock, 0);
return p;
}
void queue_release(void *h){
Queue *p = (Queue*)h;
pthread_mutex_destroy(&p->lock);
}
int queue_get(void *h, char *data, int *data_len){
Queue *queue = (Queue*)h;
int ret = 0;
assert(queue && queue->size);
pthread_mutex_lock(&queue->lock);
if(queue->num > 0){
int head = queue->head;
int maxlen = *data_len;
QueueNode *node;
if(queue->size - head < 4 || *(int*)(queue->buffer + head) == 0){
head = 0;
}
node = (QueueNode*)(queue->buffer + head);
*data_len = node->len;
if(maxlen < node->len || data == 0){
ret = -2;
}else{
memmove(data, node->data, node->len);
head += (int)(((QueueNode*)0)->data) + node->len;
if(head == queue->size){
head = 0;
}
queue->head = head;
queue->num --;
if(queue->num == 0){
queue->head = queue->tail = 0;
}
}
}else{
ret = -1;
}
pthread_mutex_unlock(&queue->lock);
return ret;
}
int queue_fetch(void* h, char* data, int* data_len){
Queue* queue = (Queue*)h;
int ret = 0;
assert(queue && queue->size);
if (queue->num > 0){
int head = queue->head;
int maxlen = *data_len;
QueueNode* node;
if(queue->size - head < 4 || *(int*)(queue->buffer + head) == 0){
head = 0;
}
node = (QueueNode*)(queue->buffer + head);
*data_len = node->len;
if(maxlen < node->len || data == 0){
ret = -2;
}else{
memmove(data, node->data, node->len);
}
}else{
return -1;
}
return ret;
}
int queue_set(void *h, char *data, int data_len){
Queue *queue = (Queue*)h;
int ret = 0;
assert(queue && queue->size);
pthread_mutex_lock(&queue->lock);
if(data_len > 0){
int size = (int)(((QueueNode*)0)->data) + data_len;
int tail = queue->tail;
if(tail >= queue->head){
if(queue->size - tail < size){
tail = 0;
if(queue->head - tail < size){
ret = -1;
}else if(queue->size - queue->tail >= 4){
*(int*)(queue->buffer + queue->tail) = 0;
}
}
}else{
if(queue->head - tail < size){
ret = -1;
}
}
if(ret == 0){
QueueNode *node = (QueueNode*)(queue->buffer + tail);
node->len = data_len;
memmove(node->data, data, data_len);
tail += size;
queue->tail = tail;
queue->num ++;
}
}
pthread_mutex_unlock(&queue->lock);
return ret;
}
int queue_size(void *h){
Queue *queue = (Queue*)h;
int size;
pthread_mutex_lock(&queue->lock);
size = queue->num;
pthread_mutex_unlock(&queue->lock);
return size;
}
| 1
|
#include <pthread.h>
struct rtpp_pcount_priv {
struct rtpp_pcount pub;
struct rtpps_pcount cnt;
pthread_mutex_t lock;
};
static void rtpp_pcount_dtor(struct rtpp_pcount_priv *);
static void rtpp_pcount_reg_reld(struct rtpp_pcount *);
static void rtpp_pcount_reg_drop(struct rtpp_pcount *);
static void rtpp_pcount_reg_ignr(struct rtpp_pcount *);
static void rtpp_pcount_get_stats(struct rtpp_pcount *, struct rtpps_pcount *);
struct rtpp_pcount *
rtpp_pcount_ctor(void)
{
struct rtpp_pcount_priv *pvt;
struct rtpp_refcnt *rcnt;
pvt = rtpp_rzmalloc(sizeof(struct rtpp_pcount_priv), &rcnt);
if (pvt == 0) {
goto e0;
}
pvt->pub.rcnt = rcnt;
if (pthread_mutex_init(&pvt->lock, 0) != 0) {
goto e1;
}
pvt->pub.reg_reld = &rtpp_pcount_reg_reld;
pvt->pub.reg_drop = &rtpp_pcount_reg_drop;
pvt->pub.reg_ignr = &rtpp_pcount_reg_ignr;
pvt->pub.get_stats = &rtpp_pcount_get_stats;
CALL_SMETHOD(pvt->pub.rcnt, attach, (rtpp_refcnt_dtor_t)&rtpp_pcount_dtor,
pvt);
return ((&pvt->pub));
e1:
CALL_SMETHOD(pvt->pub.rcnt, decref);
free(pvt);
e0:
return (0);
}
static void
rtpp_pcount_dtor(struct rtpp_pcount_priv *pvt)
{
rtpp_pcount_fin(&(pvt->pub));
pthread_mutex_destroy(&pvt->lock);
free(pvt);
}
static void
rtpp_pcount_reg_reld(struct rtpp_pcount *self)
{
struct rtpp_pcount_priv *pvt;
pvt = ((struct rtpp_pcount_priv *)((char *)(self) - offsetof(struct rtpp_pcount_priv, pub)));
pthread_mutex_lock(&pvt->lock);
pvt->cnt.nrelayed++;
pthread_mutex_unlock(&pvt->lock);
}
static void
rtpp_pcount_reg_drop(struct rtpp_pcount *self)
{
struct rtpp_pcount_priv *pvt;
pvt = ((struct rtpp_pcount_priv *)((char *)(self) - offsetof(struct rtpp_pcount_priv, pub)));
pthread_mutex_lock(&pvt->lock);
pvt->cnt.ndropped++;
pthread_mutex_unlock(&pvt->lock);
}
static void
rtpp_pcount_reg_ignr(struct rtpp_pcount *self)
{
struct rtpp_pcount_priv *pvt;
pvt = ((struct rtpp_pcount_priv *)((char *)(self) - offsetof(struct rtpp_pcount_priv, pub)));
pthread_mutex_lock(&pvt->lock);
pvt->cnt.nignored++;
pthread_mutex_unlock(&pvt->lock);
}
static void
rtpp_pcount_get_stats(struct rtpp_pcount *self, struct rtpps_pcount *ocnt)
{
struct rtpp_pcount_priv *pvt;
pvt = ((struct rtpp_pcount_priv *)((char *)(self) - offsetof(struct rtpp_pcount_priv, pub)));
pthread_mutex_lock(&pvt->lock);
memcpy(ocnt, &pvt->cnt, sizeof(struct rtpps_pcount));
pthread_mutex_unlock(&pvt->lock);
}
| 0
|
#include <pthread.h>
void search_by_thread( void* ptr);
{
char* start_ptr;
char* end_ptr;
int slice_id;
} slice_data;
{
char* start_ptr;
char* end_ptr;
int thread_id;
int num_slices;
int slice_size;
char match_str[15];
char* array_address;
slice_data* slice_struct_address;
} thread_data;
int slice_counter = 0;
pthread_mutex_t mutex;
pthread_mutex_t mutex2;
int main(int argc, char* argv[])
{
FILE* fRead;
char line[15];
char search_str[15];
char* array_ptr;
char* temp_ptr;
int i = 0;
int j = 0;
int fchar;
int num_inputs = 0;
int num_threads;
int num_slices;
int slice_size = 0;
char file_name[] = "fartico_aniketsh_input_partB.txt";
char alt_file[128];
printf("\\n(fartico_aniketsh_input_partB.txt)\\n");
printf("ENTER ALT FILENAME OR (ENTER TO RUN): ");
gets(alt_file);
if(strcmp(alt_file, "") != 0)
{
strcpy(file_name, alt_file);
}
fRead = fopen(file_name, "r");
if(fRead == 0)
{
perror("FILE OPEN FAILED\\n");
exit(1);
}
while(EOF != (fchar = fgetc(fRead)))
{if ( fchar == '\\n'){++num_inputs;}}
if ( fchar != '\\n' ){++num_inputs;}
fclose(fRead);
if ( num_inputs > 4 ) { num_inputs = num_inputs -3; }
fRead = fopen(file_name, "r");
if(fRead == 0)
{
perror("FILE OPEN FAILED\\n");
exit(1);
}
fgets(line, sizeof(line), fRead);
num_threads = atoi(line);
fgets(line, sizeof(line), fRead);
num_slices = atoi(line);
fgets(search_str, sizeof(search_str), fRead);
array_ptr = malloc(num_inputs * sizeof(line));
memset(array_ptr, '\\0', num_inputs * sizeof(line));
if(array_ptr == 0)
{
perror("Memory Allocation Failed\\n");
exit(1);
}
temp_ptr = array_ptr;
slice_size = num_inputs / num_slices;
if( num_inputs%num_slices != 0 ){slice_size = slice_size + 1;}
while(fgets(line, sizeof(line), fRead))
{
strcpy(&temp_ptr[i*15], line);
i++;
}
printf("\\n");
pthread_t thread_array[num_threads];
thread_data data_array[num_threads];
slice_data slice_array[num_slices];
int k;
for( k = 0; k < num_threads; ++k)
{
data_array[k].start_ptr = &array_ptr[k * slice_size * 15];
data_array[k].end_ptr = &array_ptr[(k+1) * slice_size * 15];
data_array[k].thread_id = k;
strcpy(data_array[k].match_str, search_str);
data_array[k].array_address = array_ptr;
data_array[k].slice_struct_address = slice_array;
data_array[k].num_slices = num_slices;
data_array[k].slice_size = slice_size;
}
for ( k = 0; k < num_slices; ++k)
{
slice_array[k].start_ptr = &array_ptr[k * slice_size * 15];
slice_array[k].end_ptr = &array_ptr[(k+1) * slice_size * 15];
slice_array[k].slice_id = k;
}
pthread_mutex_init(&mutex, 0);
pthread_mutex_init(&mutex2, 0);
for( k = 0; k < num_threads; ++k)
{
pthread_create(&thread_array[k], 0, (void *) & search_by_thread, (void *) &data_array[k]);
}
for( k =0; k < num_threads; ++k)
{
pthread_join(thread_array[k], 0);
}
pthread_mutex_destroy(&mutex);
printf("\\n");
return 0;
}
void search_by_thread( void* ptr)
{
thread_data* data;
data = (thread_data *) ptr;
int temp_slice;
char* temp_ptr;
int i=0;
int j;
int position_i = -1;
int slice_i = -1;
char found_i[] = "no";
while(1)
{
pthread_mutex_lock(&mutex2);
if ( slice_counter < data->num_slices)
{
temp_slice = slice_counter;
slice_counter = slice_counter + 1;
}
else {temp_slice = -1;}
pthread_mutex_unlock(&mutex2);
if (temp_slice == -1){break;}
j =0;
temp_ptr = data->slice_struct_address[temp_slice].start_ptr;
while( &temp_ptr[j * 15] < data->slice_struct_address[temp_slice].end_ptr)
{
if (strcmp(&temp_ptr[j*15], data->match_str) == 0)
{
position_i = (data->slice_struct_address[temp_slice].slice_id *data->slice_size) + j;
slice_i = temp_slice;
strcpy(found_i, "yes");
}
j = j + 1;
}
i++;
usleep(1);
}
pthread_mutex_lock(&mutex);
printf("thread %d, found %s, slice %d, position %d\\n", data->thread_id, found_i, slice_i, position_i);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int threads = 0;
pthread_mutex_t mutex;
pthread_cond_t cond_pode_ler;
pthread_cond_t cond_pode_escrever;
int lendo = 0;
int escrevendo = 0;
unsigned long mix(unsigned long a, unsigned long b, unsigned long c);
void entra_leitura()
{
pthread_mutex_lock(&mutex);
while (escrevendo)
{
pthread_cond_wait(&cond_pode_ler, &mutex);
}
lendo++;
pthread_mutex_unlock(&mutex);
}
void sai_leitura()
{
pthread_mutex_lock(&mutex);
lendo--;
if (lendo == 0)
{
pthread_cond_signal(&cond_pode_escrever);
}
pthread_mutex_unlock(&mutex);
}
void entra_escrita()
{
pthread_mutex_lock(&mutex);
while (escrevendo || lendo)
{
pthread_cond_wait(&cond_pode_escrever, &mutex);
}
escrevendo++;
pthread_mutex_unlock(&mutex);
}
void sai_escrita()
{
pthread_mutex_lock(&mutex);
escrevendo--;
pthread_cond_signal(&cond_pode_escrever);
pthread_cond_broadcast(&cond_pode_ler);
pthread_mutex_unlock(&mutex);
}
void *escrever_varios(void *arg)
{
int tid = *(int *)arg;
int boba1, boba2;
int i;
for (i = 0; i < 5; i++)
{
entra_escrita();
printf("entra_escrita tid=%d => escrevendo=%d, lendo=%d\\n", tid, escrevendo, lendo);
boba1 = rand()%10000;
boba2 = -rand()%10000;
while (boba2 < boba1)
boba2++;
sai_escrita();
printf("sai_escrita tid=%d => escrevendo=%d, lendo=%d\\n", tid, escrevendo, lendo);
}
pthread_exit(0);
}
void *ler_varios(void *arg)
{
int tid = *(int *)arg;
int boba1, boba2;
int i;
for (i = 0; i < 5; i++)
{
entra_leitura();
printf("entra_leitura tid=%d => escrevendo=%d, lendo=%d\\n", tid, escrevendo, lendo);
boba1 = rand()%10000000;
boba2 = -rand()%10000000;
while (boba2 < boba1)
boba2++;
sai_leitura();
printf("sai_leitura tid=%d => escrevendo=%d, lendo=%d\\n", tid, escrevendo, lendo);
}
pthread_exit(0);
}
void main()
{
srand(mix(clock(), time(0), 12789057));
srand(rand());
pthread_cond_init(&cond_pode_escrever, 0);
pthread_cond_init(&cond_pode_ler, 0);
pthread_mutex_init(&mutex, 0);
pthread_t *tid;
tid = (pthread_t *)malloc(sizeof(pthread_t) * 10);
int *arg = malloc(sizeof(int) * 10);
int k;
for (k = 0; k < 10; k++)
{
arg[k] = k;
}
for (k = 0; k < 10 - 7; k++)
{
printf("escrever_varios\\n");
if (pthread_create(&tid[k], 0, escrever_varios, (void *)&arg[k]) != 0)
{
printf("--ERRO: pthread_create()\\n");
exit(-1);
}
}
for (; k < 10; k++)
{
printf("ler_varios\\n");
if (pthread_create(&tid[k], 0, ler_varios, (void *)&arg[k]) != 0)
{
printf("--ERRO: pthread_create()\\n");
exit(-1);
}
}
for (k = 0; k < 10; k++)
{
if (pthread_join(tid[k], 0) != 0)
{
printf("--ERRO: pthread_join() \\n");
exit(-1);
}
}
free(arg);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond_pode_ler);
pthread_cond_destroy(&cond_pode_escrever);
}
unsigned long mix(unsigned long a, unsigned long b, unsigned long c)
{
a=a-b; a=a-c; a=a^(c >> 13);
b=b-c; b=b-a; b=b^(a << 8);
c=c-a; c=c-b; c=c^(b >> 13);
a=a-b; a=a-c; a=a^(c >> 12);
b=b-c; b=b-a; b=b^(a << 16);
c=c-a; c=c-b; c=c^(b >> 5);
a=a-b; a=a-c; a=a^(c >> 3);
b=b-c; b=b-a; b=b^(a << 10);
c=c-a; c=c-b; c=c^(b >> 15);
return c;
}
| 0
|
#include <pthread.h>
pthread_mutex_t counter_clock=PTHREAD_MUTEX_INITIALIZER;
int total_words=0;
int main(int ac,char* av[])
{
int pc;
pthread_t t1,t2;
void*count_words(void*);
if(ac!=3)
{
printf("Usage:%s file1 file\\n",av[0]);
exit(1);
}
pc=pthread_create(&t1,0,count_words,av[1]);
if(pc!=0)
{
printf("thread created error!\\n");
exit(0);
}
pc=pthread_create(&t2,0,count_words,av[2]);
if(pc!=0)
{
printf("thread created error!\\n");
exit(0);
}
pc = pthread_join(t1,0);
pc = pthread_join(t1,0);
printf("total words in %s and %s are %d\\n",av[1],av[2],total_words);
}
void* count_words(void* f)
{
char*filename=(char*)f;
FILE*fp;
int c,prevc='\\0';
if((fp=fopen(filename,"r"))!=0)
{
while( (c = fgetc(fp))!=EOF)
{
if(!isalnum(c) && isalnum(prevc))
{
pthread_mutex_lock(&counter_clock);
total_words++;
pthread_mutex_unlock(&counter_clock);
}
prevc=c;
}
fclose(fp);
}
else
{
printf("open file %s error!\\n",filename);
}
return 0;
}
| 1
|
#include <pthread.h>
int num=0;
pthread_mutex_t mylock=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t qready=PTHREAD_COND_INITIALIZER;
void * thread_func(void *arg)
{
int i=(int)arg;
int ret;
sleep(5-i);
pthread_mutex_lock(&mylock);
while(i!=num)
{
printf("thread %d waiting\\n",i);
ret=pthread_cond_wait(&qready,&mylock);
if(ret==0)
{
printf("thread %d wait success\\n",i);
}else
{
printf("thread %d wait failed:%s\\n",i,strerror(ret));
}
}
printf("thread %d is running \\n",i);
num++;
pthread_mutex_unlock(&mylock);
pthread_cond_broadcast(&qready);
return (void *)0;
}
int main(int argc, char** argv) {
int i=0,err;
pthread_t tid[4];
void *tret;
for(;i<4;i++)
{
err=pthread_create(&tid[i],0,thread_func,(void *)i);
if(err!=0)
{
printf("thread_create error:%s\\n",strerror(err));
exit(-1);
}
}
for (i = 0; i < 4; i++)
{
err = pthread_join(tid[i], &tret);
if (err != 0)
{
printf("can not join with thread %d:%s\\n", i,strerror(err));
exit(-1);
}
}
return 0;
}
| 0
|
#include <pthread.h>
struct Msg{
struct Msg *next;
int data;
};
struct Msg *workq;
pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;
void process_msg(void)
{
struct Msg *mp;
for( ; ;){
pthread_mutex_lock(&qlock);
while(workq != 0){
pthread_cond_wait(&qready,&qlock);
}
mp = workq;
workq = mp->next;
pthread_mutex_unlock(&qlock);
}
}
void enqueue_msg(struct Msg *mp){
pthread_mutex_lock(&qlock);
mp->data = 2;
mp->next = workq;
workq = mp;
pthread_mutex_unlock(&qlock);
pthread_cond_signal(&qready);
}
int main()
{
struct Msg msg;
msg.data = 1;
enqueue_msg(&msg);
process_msg();
return 0;
}
| 1
|
#include <pthread.h>
int p_id;
int p_fila;
int p_columna;
int p_weapon;
}people;
char** board;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void move_people(people *persona, char** board){
printf("Pifia1\\n");
int i, j;
i = persona->p_fila;
j = persona->p_columna;
int contador = 0;
int mov;
while(contador < 8){
mov = (int) random()%8;
if (mov == 0){
if(board[i][j-1] == '0'){
printf("Pifia2\\n");
persona->p_columna = j-1;
board[i][j-1] = 'P';
}
contador = contador + 1;
}
if (mov == 1){
printf("Pifia3\\n");
if(board[i][j+1] == '0'){
persona->p_columna = j+1;
board[i][j+1] = 'P';
}
contador = contador + 1;
}
if (mov == 2){
printf("Pifia4\\n");
if(board[i+1][j] == '0'){
persona->p_fila = i+1;
board[i+1][j] = 'P';
}
contador = contador + 1;
}
if (mov == 3){
printf("Pifia5\\n");
if(board[i-1][j] == '0'){
persona->p_fila = i-1;
board[i-1][j] = 'P';
}
contador = contador + 1;
}
if (mov == 4){
printf("Pifia6\\n");
if(board[i+1][j-1] == '0'){
persona->p_fila = i+1;
persona->p_columna = j-1;
board[i+1][j-1] = 'P';
}
contador = contador + 1;
}
if (mov == 5){
printf("Pifia7\\n");
if(board[i-1][j-1] == '0'){
persona->p_fila = i-1;
persona->p_columna = j-1;
board[i-1][j-1] = 'P';
}
contador = contador + 1;
}
if (mov == 6){
printf("Pifia8\\n");
if(board[i+1][j+1] == '0'){
persona->p_fila = i+1;
persona->p_columna = j+1;
board[i+1][j+1] = 'P';
}
contador = contador + 1;
}
if (mov == 7){
printf("Pifia9\\n");
if(board[i-1][j+1] == '0'){
persona->p_fila = i-1;
persona->p_columna = j+1;
board[i-1][j+1] = 'P';
}
contador = contador + 1;
}
}
}
void *create_people(void *arg){
people *p = (people*) arg;
pthread_mutex_lock(&mutex);
move_people(p, board);
pthread_mutex_unlock(&mutex);
}
void threads_peoples(int n_people, int N, int M){
int i;
pthread_t *threads_peoples = (pthread_t*) malloc(n_people*sizeof(pthread_t));
people *array_p = (people*)malloc(sizeof(people)*n_people);
for(i=0; i< n_people; i++){
array_p[i].p_id = i;
array_p[i].p_fila = (int) random()%N;
array_p[i].p_columna = (int) random()%M;
printf("Las filas son: %i\\n", array_p[i].p_fila);
printf("Las columnas son %i\\n", array_p[i].p_columna );
array_p[i].p_weapon = 0;
}
for (i=0; i < n_people; i++) {
pthread_create( &(threads_peoples[i]), 0, create_people, (void*) &(array_p[i]));
}
}
char** spaceForBoard(int n, int m){
char *boardAux = (char*)calloc(n*m, sizeof(char));
char **board = (char**)calloc(n*m, sizeof(char*));
for (int i = 0; i < n; i++){
board[i] = boardAux + i*m;
}
return board;
}
char** board_created(char** board, int ancho, int largo){
int i, j;
for(i=0; i < ancho; i++){
for(j=0; j < largo; j++){
board[i][j] = '0';
}
}
return board;
}
void printBoard(int n, int m, char** board){
for(int j = 0; j < m; j++){
printf("\\n");
for(int i = 0; i < n; i++){
printf("%c",board[i][j]);
}
}
printf("\\n\\n");
}
int main (int argc, char *argv[]){
int n,m,p;
n = atoi(argv[1]);
m = atoi(argv[2]);
p = atoi(argv[3]);
char **board = spaceForBoard(n,m);
board = board_created(board, n, m);
threads_peoples(p, n, m);
printBoard(n, m, board);
}
| 0
|
#include <pthread.h>
static int reader_count = 0;
static pthread_mutex_t reader_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t new_op_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t writer_mutex = PTHREAD_MUTEX_INITIALIZER;
void justice_reader(int num, int duration) {
pthread_mutex_lock(&new_op_mutex);
pthread_mutex_lock(&reader_mutex);
++reader_count;
if (reader_count == 1)
pthread_mutex_lock(&writer_mutex);
pthread_mutex_unlock(&reader_mutex);
pthread_mutex_unlock(&new_op_mutex);
doread(num, duration);
pthread_mutex_lock(&reader_mutex);
--reader_count;
if (reader_count == 0)
pthread_mutex_unlock(&writer_mutex);
pthread_mutex_unlock(&reader_mutex);
}
void justice_writer(int num, int duration) {
pthread_mutex_lock(&new_op_mutex);
pthread_mutex_lock(&writer_mutex);
dowrite(num, duration);
pthread_mutex_unlock(&writer_mutex);
pthread_mutex_unlock(&new_op_mutex);
}
| 1
|
#include <pthread.h>
char alphabet[26] = "abcdefghijklmnopqrstuvwxyz";
pthread_t t[2];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void print_alphabet(){
for (int i = 0; i < 26; i++) {
printf("%c", alphabet[i]);
}
printf("\\n");
}
void *reverse(void *arg){
(void) arg;
while (1) {
pthread_mutex_lock(&mutex);
for (int i = 0; i < 26 / 2; i++) {
char t = alphabet[i];
alphabet[i] = alphabet[26 - i - 1];
alphabet[26 - i - 1] = t;
}
pthread_mutex_unlock(&mutex);
usleep(500000);
}
return 0;
}
void *changecase(void *arg)
{
(void) arg;
while (1) {
pthread_mutex_lock(&mutex);
for (int i = 0; i < 26; i++) {
alphabet[i] += (alphabet[i] - 'A') < 26 ? 32 : -32;
}
pthread_mutex_unlock(&mutex);
usleep(500000);
}
return 0;
}
int main()
{
pthread_create(&t[0], 0, reverse, 0);
pthread_create(&t[1], 0, changecase, 0);
while (1) {
pthread_mutex_lock(&mutex);
print_alphabet();
pthread_mutex_unlock(&mutex);
usleep(500000);
}
return 0;
}
| 0
|
#include <pthread.h>
int usage;
char buf[MESSAGE_SIZE];
char* next;
}chain;
struct send {
int index;
char* smsg;
pthread_t p_send;
};
struct receive {
int index;
char* rmsg;
pthread_t p_receive;
};
chain* messages;
struct send sends[MAXSEND_T];
struct receive receives[MAXRECEIVE_T];
pthread_mutex_t send_wait, receive_wait;
pthread_mutex_t main_wait;
int demo_time = 10;
int MESSAGE_C_SIZE = 0;
int main()
{
pthread_mutex_lock(&main_wait);
int i;
printf("Please input the capability:");
scanf("%d", &MESSAGE_C_SIZE);
messages = (chain*)malloc(sizeof(chain)*MESSAGE_C_SIZE);
initialize();
for(i=0; i<MESSAGE_C_SIZE; i++)
{
char input[MESSAGE_SIZE];
printf("Please input the test message %d:", i);
scanf("%s", input);
if(strlen(input) <= MESSAGE_SIZE)
{
strcpy(messages[i].buf, input);
messages[i].usage = MESSAGE_SIZE - strlen(input);
}
}
showBlocks();
printf("\\n\\n\\n");
pthread_mutex_lock(&send_wait);
for(i=0; i<MAXSEND_T; i++)
{
pthread_create(&sends[i].p_send, 0, (void*)send_msg, &sends[i].index);
}
pthread_mutex_lock(&receive_wait);
for(i=0; i<MAXRECEIVE_T; i++)
{
pthread_create(&receives[i].p_receive, 0, (void*)receive_msg, &receives[i].index);
}
srand((unsigned)time(0));
for(i=0; i<demo_time; i++)
{
printf("\\n\\n");
system("date");
int j = rand() % 10;
if(j >= 5 && j < 10)
{
pthread_mutex_unlock(&receive_wait);
pthread_mutex_lock(&main_wait);
}
else if(j >= 0 && j < 5)
{
pthread_mutex_unlock(&send_wait);
pthread_mutex_lock(&main_wait);
}
else
{
printf("the selected index is %d, invalid!", j);
exit(1);
}
sleep(5);
}
free(messages);
exit(0);
};
void initialize()
{
int i;
for(i=0; i<MESSAGE_C_SIZE; i++)
{
strcpy(messages[i].buf, "");
messages[i].usage = MESSAGE_SIZE;
if(i != MESSAGE_C_SIZE - 1)
messages[i].next = messages[i+1].buf;
else
messages[i].next = 0;
}
pthread_mutex_init(&main_wait, 0);
for(i=0; i<MAXSEND_T; i++)
{
sends[i].index = i;
char smsgBuf[MESSAGE_SIZE];
sends[i].smsg = smsgBuf;
}
pthread_mutex_init(&send_wait, 0);
for(i=0; i<MAXRECEIVE_T; i++)
{
receives[i].index = i;
char rmsgBuf[MESSAGE_SIZE];
receives[i].rmsg = rmsgBuf;
}
pthread_mutex_init(&receive_wait, 0);
};
void send_msg(int* index)
{
while(*index <= MAXSEND_T)
{
pthread_mutex_lock(&send_wait);
int k;
printf("********************************\\n");
for(k=0; k<MESSAGE_C_SIZE; k++)
if(messages[k].next == 0)
{
int t;
if(!strcmp(messages[k].buf, ""))
t = k;
else
t = k + 1;
if(t < MESSAGE_C_SIZE)
{
sprintf(messages[t].buf, "send %d message", *index);
messages[k].next = messages[t].buf;
messages[t].next = 0;
printf("Send Process %d send %d message. \\n", *index, *index);
break;
}
else
{
printf("There is not space for Send Process %d to add message! \\n", *index);
break;
}
}
printf("********************************\\n");
showBlocks();
pthread_mutex_unlock(&main_wait);
}
};
void receive_msg(int* index)
{
while(*index <= MAXRECEIVE_T)
{
pthread_mutex_lock(&receive_wait);
int k;
printf("********************************\\n");
for(k=0; k<MESSAGE_C_SIZE; k++)
if(messages[k].next == 0)
{
if(strcmp(messages[k].buf, ""))
{
strcpy(receives[*index].rmsg, messages[k].buf);
strcpy(messages[k].buf, "");
if(k-1 >= 0) messages[k-1].next = 0;
printf("Receive Process %d get %s. \\n", *index, receives[*index].rmsg);
break;
}
else
{
printf("Though the buf is empty, the order 'receive' of calling is wrong! \\n");
break;
}
}
printf("********************************\\n");
showBlocks();
pthread_mutex_unlock(&main_wait);
}
};
void showBlocks()
{
printf("===============================\\n");
int k;
for(k=0; k<MESSAGE_C_SIZE; k++)
printf("Message %d: %s \\n", k, messages[k].buf);
printf("===============================\\n");
};
| 1
|
#include <pthread.h>
{
unsigned char status;
char data[1024];
}Block_Info;
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
Block_Info memory_block_arr[2];
static int initindicator = 0;
int init()
{
if (0 == initindicator)
{
pthread_mutex_lock(&gmutex);
if (0 == initindicator)
{
memset(memory_block_arr, 0, 2*sizeof(Block_Info));
initindicator = 1;
}
pthread_mutex_unlock(&gmutex);
}
}
char * mymalloc(int size)
{
int lindex;
if(size > 1024)
{
return (0);
}
init();
pthread_mutex_lock(&gmutex);
for(lindex = 0; lindex< 2; lindex++)
{
if(0 == memory_block_arr[lindex].status)
{
memory_block_arr[lindex].status = 1;
pthread_mutex_unlock(&gmutex);
return((char *)&memory_block_arr[lindex].data);
}
else
{
if((2 - 1) == lindex)
{
pthread_mutex_unlock(&gmutex);
return(0);
}
}
}
}
void myfree(char * address)
{
int lindex;
for(lindex = 0; lindex< 2; lindex++)
{
if(address == (char *)&memory_block_arr[lindex].data)
memory_block_arr[lindex].status = 0;
}
}
| 0
|
#include <pthread.h>
int q[2];
int qsiz;
pthread_mutex_t mq;
void queue_init ()
{
pthread_mutex_init (&mq, 0);
qsiz = 0;
}
void queue_insert (int x)
{
int done = 0;
printf ("prod: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz < 2)
{
done = 1;
q[qsiz] = x;
qsiz++;
}
pthread_mutex_unlock (&mq);
}
}
int queue_extract ()
{
int done = 0;
int x = -1, i = 0;
printf ("consumer: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz > 0)
{
done = 1;
x = q[0];
qsiz--;
for (i = 0; i < qsiz; i++) q[i] = q[i+1];
__VERIFIER_assert (qsiz < 2);
q[qsiz] = 0;
}
pthread_mutex_unlock (&mq);
}
return x;
}
void swap (int *t, int i, int j)
{
int aux;
aux = t[i];
t[i] = t[j];
t[j] = aux;
}
int findmaxidx (int *t, int count)
{
int i, mx;
mx = 0;
for (i = 1; i < count; i++)
{
if (t[i] > t[mx]) mx = i;
}
__VERIFIER_assert (mx >= 0);
__VERIFIER_assert (mx < count);
t[mx] = -t[mx];
return mx;
}
int source[3];
int sorted[3];
void producer ()
{
int i, idx;
for (i = 0; i < 3; i++)
{
idx = findmaxidx (source, 3);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 3);
queue_insert (idx);
}
}
void consumer ()
{
int i, idx;
for (i = 0; i < 3; i++)
{
idx = queue_extract ();
sorted[i] = idx;
printf ("m: i %d sorted = %d\\n", i, sorted[i]);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 3);
}
}
void *thread (void * arg)
{
(void) arg;
producer ();
return 0;
}
int main ()
{
pthread_t t;
int i;
__libc_init_poet ();
for (i = 0; i < 3; i++)
{
source[i] = __VERIFIER_nondet_int(0,20);
printf ("m: init i %d source = %d\\n", i, source[i]);
__VERIFIER_assert (source[i] >= 0);
}
queue_init ();
pthread_create (&t, 0, thread, 0);
consumer ();
pthread_join (t, 0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER(count_mutex);
pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER(condition_mutex);
pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER(condition_cond);
void *functionCount1();
void *functionCount2();
int count = 0;
main()
{
pthread_t thread1, thread2;
printf("init\\n");
pthread_init();
pthread_self()->pt_name = "main";
PTHREAD_MUTEX_DBGSTART(condition_mutex,"cond-mutex");
PTHREAD_MUTEX_DBGSTART(count_mutex,"count-mutex");
PTHREAD_COND_DBGSTART(condition_cond,"cond");
printf("create1\\n");
pthread_create( &thread1, 0, &functionCount1, 0);
printf("create2\\n");
pthread_create( &thread2, 0, &functionCount2, 0);
printf("join1\\n");
pthread_join( thread1, 0);
printf("join2\\n");
pthread_join( thread2, 0);
}
void *functionCount1()
{
pthread_self()->pt_name = "c1";
for(;;)
{
pthread_mutex_lock( &condition_mutex );
while( count >= 3 && count <= 6 )
{
pthread_cond_wait( &condition_cond, &condition_mutex );
}
pthread_mutex_unlock( &condition_mutex );
pthread_mutex_lock( &count_mutex );
count++;
printf("Counter value functionCount1: %d\\n",count);
pthread_mutex_unlock( &count_mutex );
if(count >= 10) {
printf("Return 1\\n");
return(0);
}
}
}
void *functionCount2()
{
pthread_self()->pt_name = "c2";
for(;;)
{
pthread_mutex_lock( &condition_mutex );
if( count < 3 || count > 6 )
{
pthread_cond_signal( &condition_cond );
}
pthread_mutex_unlock( &condition_mutex );
pthread_mutex_lock( &count_mutex );
count++;
printf("Counter value functionCount2: %d\\n",count);
pthread_mutex_unlock( &count_mutex );
if(count >= 10) {
printf("Return 2\\n");
return(0);
}
}
}
| 0
|
#include <pthread.h>
statusThinking,
statusWaiting,
statusEating
} status;
status states[5];
int eatCount[5];
pthread_t philosophers[5];
pthread_mutex_t chopsticks[5];
pthread_mutex_t mutex;
void printStatus() {
fprintf(stdout, "\\nPrinting the status of all 5 philosophers:\\n");
fflush(stdout);
int i;
for (i = 0; i < 5; ++i) {
switch (states[i]) {
case statusThinking:
fprintf(stdout, "\\nPhilosopher %d is thinking.", i);
break;
case statusWaiting:
fprintf(stdout, "\\nPhilosopher %d is waiting to eat.", i);
break;
case statusEating:
fprintf(stdout, "\\nPhilosopher %d is eating.", i);
break;
}
fflush(stdout);
}
}
void think(int n) {
states[n] = statusThinking;
usleep(25);
}
void eatIfPossible(int n) {
printStatus();
if (states[n] == statusWaiting && states[(n + 5 - 1) % 5] != statusEating && states[(n + 1) % 5] != statusEating) {
states[n] = statusEating;
eatCount[n]++;
fprintf(stdout, "\\nPhilosopher %d has started eating now.\\n", n);
fflush(stdout);
pthread_mutex_unlock(&chopsticks[n]);
}
}
void takeChopsticks(int n) {
pthread_mutex_lock(&mutex);
states[n] = statusWaiting;
eatIfPossible(n);
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&chopsticks[n]);
}
void putChopsticks(int n) {
pthread_mutex_lock(&mutex);
states[n] = statusThinking;
eatIfPossible((n + 5 - 1) % 5);
eatIfPossible((n + 1) % 5);
pthread_mutex_unlock(&mutex);
}
void *thinkAndEat(int n) {
while (eatCount[n] < 365) {
think(n);
takeChopsticks(n);
putChopsticks(n);
}
fprintf(stdout, "\\nPhilosopher %d finished eating %d times\\n", n, 365);
fflush(stdout);
return(0);
}
void cleanStates() {
int i;
for (i = 0; i < 5; ++i) {
states[i] = statusThinking;
eatCount[i] = 0;
}
}
int main(int argc, char *argv[]) {
cleanStates();
int i;
for (i = 0; i < 5; i++) {
pthread_mutex_init(&chopsticks[i], 0);
}
pthread_mutex_init(&mutex, 0);
for (i = 0; i < 5; ++i) {
pthread_create(&philosophers[i], 0, (void *)thinkAndEat, (void *)i);
}
for (i = 0; i < 5; ++i) {
pthread_join(philosophers[i],0);
}
for (i = 0; i < 5; ++i) {
pthread_mutex_destroy(&chopsticks[i]);
}
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
{
int id;
char name[20];
}STU_T;
{
STU_T st;
struct stu * next;
}NODE;
NODE * H = 0;
void *handler(void *arg)
{
NODE *p = 0;
while(1)
{
pthread_mutex_lock(&lock);
if(H != 0)
{
p = H;
H = H->next;
printf("recv student message: id = %d, name = %s\\n",ntohl(p->st.id),p->st.name);
}
free(p);
}
pthread_mutex_unlock(&lock);
sleep(1);
}
int main(int argc,char **argv)
{
int ret;
if(argc != 2)
{
printf("para error1\\n");
return -1;
}
int epollFd;
pthread_mutex_init(&lock,0);
pthread_t pid;
ret = pthread_create(&pid,0,handler,0);
epollFd = epoll_create(1000);
if(epollFd < 0)
{
perror("epoll_create");
return -1;
}
int listenFd;
listenFd = socket(AF_INET,SOCK_STREAM,0);
if(listenFd < 0)
{
perror("socket");
return -1;
}
struct epoll_event ev;
ev.data.fd = listenFd;
ev.events = EPOLLIN | EPOLLET;
epoll_ctl(epollFd,EPOLL_CTL_ADD,listenFd,&ev);
struct sockaddr_in serverAddr;
memset(&serverAddr,0,sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(atoi(argv[1]));
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = bind(listenFd,(struct sockaddr *)&serverAddr,sizeof(serverAddr));
if(ret < 0)
{
perror("bind");
return -1;
}
ret = listen(listenFd,1000);
struct epoll_event events[1000];
struct sockaddr_in clientAddr;
int clilen = sizeof(clientAddr);
char buff[1024] = {0};
int nfds;
int i;
int clientFd;
int sockFd;
NODE *p = 0;
STU_T st;
while(1)
{
nfds = epoll_wait(epollFd,events,1000,500);
for(i = 0;i < nfds;i++);
{
if(events[i].data.fd == listenFd)
{
clientFd = accept(listenFd,(struct sockaddr *)&clientAddr,&clilen);
ev.data.fd = clientFd;
ev.events = EPOLLIN | EPOLLET;
epoll_ctl(epollFd,EPOLL_CTL_ADD,clientFd,&ev);
}
else if(events[i].events & EPOLLIN)
{
sockFd = events[i].data.fd;
memset(&st,0,sizeof(st));
ret = read(sockFd,buff,sizeof(buff));
if(ret <= 0)
{
perror("read");
continue;
}
p = (NODE *)malloc(sizeof(NODE));
memset(p,0,sizeof(NODE));
memcpy(&(p->st),buff,sizeof(STU_T));
pthread_mutex_lock(&lock);
if(H == 0)
{
H = p;
}
else
{
p->next = H;
H = p;
}
pthread_mutex_unlock(&lock);
ev.data.fd = sockFd;
ev.events = EPOLLIN | EPOLLET;
epoll_ctl(epollFd,EPOLL_CTL_MOD,sockFd,&ev);
}
}
}
pthread_join(pid,0);
close(epollFd);
close(listenFd);
close(sockFd);
return 0;
}
| 0
|
#include <pthread.h>
void statistic_reset_r(struct Statistic *s, struct Statistic *d, int flag) {
if (s && 0 == pthread_mutex_lock(&s->mutex)) {
int f = flag ? flag : STAT_RESET_ALL;
if (d) {
d->value = s->value;
d->count = s->count;
d->total = s->total;
if (f & STAT_CALCULATE_MINMAX) {
if (d->min > s->value)
d->min = s->value;
if (d->max < s->value)
d->max = s->value;
} else {
d->min = s->min;
d->max = s->max;
}
}
if (f & STAT_RESET_VALUE)
s->value = 0;
if (f & STAT_RESET_COUNT)
s->count = 0;
if (f & STAT_RESET_TOTAL)
s->total = 0;
if (f & STAT_RESET_MINMAX) {
s->min = LONG_MAX;
s->max = LONG_MIN;
}
pthread_mutex_unlock(&s->mutex);
}
}
void statistic_reset(struct Statistic *s) {
statistic_reset_r(s, 0, STAT_RESET_ALL);
}
| 1
|
#include <pthread.h>
struct vehicles{
char* vPlate;
int id;
pthread_t tid;
int arrDelay;
int vWeight;
int crossTime;
struct vehicles *next;
struct vehicles *prev;
};
static int totalVehicles;
static int bridgeload;
static pthread_mutex_t access;
static pthread_cond_t ok=PTHREAD_COND_INITIALIZER;
int maxWeight;
struct vehicles *carInfo;
struct vehicles *firstCar;
struct vehicles *createVehicle(int id,char *plate,int delay,int weight,int cTime){
struct vehicles *temp=(struct vehicles*)malloc(sizeof(struct vehicles));
temp->vPlate=(char *)malloc(7);
strcpy(temp->vPlate,plate);
temp->id=id;
temp->arrDelay=delay;
temp->vWeight=weight;
temp->crossTime=cTime;
temp->next=0;
temp->prev=0;
return temp;
}
void insertEnd(int id,char*plate,int delay,int weight,int cTime){
struct vehicles *node=createVehicle(id,plate,delay,weight,cTime);
if(firstCar==0){
printf("---inserted first car in list \\n");
firstCar=node;
carInfo=firstCar;
}
else{
carInfo->next=node;
node->prev=carInfo;
carInfo=node;
}
printf("---inserted plate %s to list \\n",node->vPlate);
}
void enterBridge(struct vehicles *car){
int weight=car->vWeight;
printf("Vehicle %s arrives at bridge. \\nThe current bridge load is %d tons \\n",car->vPlate,bridgeload);
pthread_mutex_lock(&access);
while((weight+bridgeload)>maxWeight){
pthread_cond_wait(&ok,&access);
}
bridgeload=bridgeload+weight;
printf("Vehicle %s goes on bridge. \\nThe current bridge load is %d tons. \\n",car->vPlate,bridgeload);
pthread_cond_signal(&ok);
pthread_mutex_unlock(&access);
}
void leaveBridge(struct vehicles *car){
int weight=car->vWeight;
pthread_mutex_lock(&access);
bridgeload=bridgeload-weight;
pthread_cond_signal(&ok);
pthread_mutex_unlock(&access);
printf("Vehicle %s leaves the bridge. \\nThe current bridge load is %d tons. \\n",car->vPlate,bridgeload);
}
int isHeavy(int weight){
if(weight>maxWeight){
printf("---too heavy weight: %d maxweight: %d \\n",weight,maxWeight);
return 1;
}
else{
return 0;
}
}
void *vehicle(void *info){
struct vehicles *cpyInfo=(struct vehicles*)info;
if(!isHeavy(cpyInfo->vWeight)){
printf("---thread created with plate '%s' \\n",cpyInfo->vPlate);
enterBridge(cpyInfo);
sleep(cpyInfo->crossTime);
leaveBridge(cpyInfo);
}
else{
printf("Vehicle %s arrives at bridge \\n",cpyInfo->vPlate);
printf("The current bridge load is %d tons.\\n",bridgeload);
printf("Vehicle %s exceeds maximum bridge load. \\n",cpyInfo->vPlate);
}
return 0;
}
int isNum(char* strCpy){
while((*strCpy)!='\\0'){
if(!isdigit(*strCpy)&&(*strCpy)!='\\0'){
printf("---string not number \\n");
return -1;
}
++strCpy;
}
return 0;
}
int readCarInfo(){
char *plate=0;
char *vWait=0;
char *vWeight=0;
char *vTime=0;
char *copy=0;
char *line;
size_t n=0;
int code=0;
int someError=0;
int wait,weight,cTime;
long int count=0;
plate=(char*)malloc(1024);
copy=(char*)malloc(1024);
while((getdelim(&line,&n,'\\n',stdin))!=-1){
line=strtok(line,"\\n");
printf("---read line %s \\n",line);
if(line!=0){
strcpy(copy,line);
strcpy(plate,strtok(copy,"' ',\\t"));
vWait=strtok(0,"' ',\\t");
if(vWait!=0){
wait=atoi(vWait);
vWeight=strtok(0,"' ',\\t");
if(vWeight!=0){
weight=atoi(vWeight);
vTime=strtok(0,"' ',\\t");
if(vTime!=0){
cTime=atoi(vTime);
}
else{
printf("---some error reading wait cross time\\n");
someError=1;
}
}
else{
printf("---some error reading weight\\n");
someError=1;
}
}
else{
printf("---some error reading delay time \\n");
someError=1;
}
if(someError!=1){
printf("---plate: '%s' wait: '%d' weight: '%d' cTime: '%d' \\n",plate,wait,weight,cTime);
insertEnd(count,plate,wait,weight,cTime);
++count;
}
else{
printf("--skipped line\\n");
}
someError=0;
}
}
totalVehicles=count;
printf("---successful stdin read \\n");
return code;
}
int main(int argc,char *argv[]){
carInfo=0;
char *plate;
char *line=0;
size_t n;
FILE *keys;
int i;
if(isNum(argv[1])==0){
maxWeight=atoi(argv[1]);
readCarInfo();
carInfo=firstCar;
printf("Maximum bridge load is %d tons \\n",maxWeight);
while(carInfo!=0){
if(carInfo->prev!=0){
sleep((carInfo->arrDelay));
}
pthread_create(&(carInfo->tid),0,vehicle,carInfo);
carInfo=carInfo->next;
}
carInfo=firstCar;
while(carInfo!=0){
pthread_join(carInfo->tid,0);
carInfo=carInfo->next;
}
printf("\\nTotal number of vehicles: %d \\n",totalVehicles);
}
else{
printf("---argv[1] is not a number! %s \\n",argv[1]);
}
free(carInfo);
return 0;
}
| 0
|
#include <pthread.h>
void *watch_resources(void *t)
{
long my_id = (long)t;
printf("Starting watch_count(): thread %ld\\n", my_id);
while(not_quit)
{
pthread_mutex_lock(&remaining_resources_mutex);
printf("watch_resources(): thread %ld Remaining resources= %d. Going into wait...\\n", my_id,remaining_resources);
while((not_quit && remaining_resources-WRKR_SIZE>0))
pthread_cond_wait(&res_empty, &remaining_resources_mutex);
if(not_quit)
{
printf("watch_resources(): thread %ld Condition signal received. Remaining resources= %d\\n", my_id,remaining_resources);
printf("watch_resources(): thread %ld Updating the amount of remaining resources...\\n", my_id);
remaining_resources += RESOURCES_RENEW_SIZE;
printf("watch_resources(): thread %ld Remaining resources now = %d.\\n", my_id, remaining_resources);
pthread_cond_broadcast(&resources_available_cv);
}
pthread_mutex_unlock(&remaining_resources_mutex);
}
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
static char *l_trim(char * szOutput, const char *szInput)
{
assert(szInput != 0);
assert(szOutput != 0);
assert(szOutput != szInput);
while(*szInput != '\\0' && isspace(*szInput))
{
++szInput;
}
return strcpy(szOutput, szInput);
}
static char * a_trim(char * szOutput, const char * szInput)
{
char *p = 0;
assert(szInput != 0);
assert(szOutput != 0);
l_trim(szOutput, szInput);
for(p = szOutput + strlen(szOutput) - 1;p >= szOutput && isspace(*p); --p);
*(++p) = '\\0';
return szOutput;
}
int GetProfileString(char *profile, char *AppName, char *KeyName, char *KeyVal )
{
char appname[32],keyname[32];
char *buf,*c;
char buf_i[256], buf_o[256];
FILE *fp;
int found=0;
if( (fp=fopen( profile,"r" ))==0 )
{
printf( "openfile [%s] error [%s]\\n",profile,strerror(errno) );
return(-1);
}
fseek( fp, 0, 0 );
memset( appname, 0, sizeof(appname) );
sprintf( appname,"[%s]", AppName );
while( !feof(fp) && fgets( buf_i, 256, fp )!=0 )
{
l_trim(buf_o, buf_i);
if( strlen(buf_o) <= 0 )
continue;
buf = 0;
buf = buf_o;
if( found == 0 )
{
if( buf[0] != '[' )
{
continue;
}
else if ( strncmp(buf,appname,strlen(appname))==0 )
{
found = 1;
continue;
}
}
else if( found == 1 )
{
{
continue;
}
else if ( buf[0] == '[' )
{
break;
}
else
{
if( (c = (char*)strchr(buf, '=')) == 0 )
continue;
memset( keyname, 0, sizeof(keyname) );
sscanf( buf, "%[^=|^ |^\\t]", keyname );
if( strcmp(keyname, KeyName) == 0 )
{
sscanf( ++c, "%[^\\n]", KeyVal );
char *KeyVal_o = (char *)malloc(strlen(KeyVal) + 1);
if(KeyVal_o != 0)
{
memset(KeyVal_o, 0, sizeof(strlen(KeyVal) + 1));
a_trim(KeyVal_o, KeyVal);
if(KeyVal_o && strlen(KeyVal_o) > 0)
{
strcpy(KeyVal, KeyVal_o);
}
free(KeyVal_o);
KeyVal_o = 0;
}
found = 2;
break;
}
else
{
continue;
}
}
}
}
fclose(fp);
if( found == 2 )
return(0);
else
return(-1);
}
pthread_mutex_t WriteCfgMutex = PTHREAD_MUTEX_INITIALIZER;
void SetProfileString(char *profile, char *KeyName, char *OldKeyVal, char *NewKeyVal)
{
char buf[128];
sprintf(buf,"sed -i 's/%s = %s/%s = %s/' %s", KeyName, OldKeyVal, KeyName, NewKeyVal, profile);
printf("buf:%s\\n",buf);
pthread_mutex_lock(&WriteCfgMutex);
system(buf);
pthread_mutex_unlock(&WriteCfgMutex);
}
| 0
|
#include <pthread.h>
pthread_t philosopher[5];
pthread_mutex_t chopstick[5] = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER};
struct philosopher_t {
int nr;
int left;
int right;
};
int threadError(char *msg, int nr) {
printf(msg, nr);
exit(1);
}
void *philosopher_deadlock(void *p) {
struct philosopher_t philosopher = *((struct philosopher_t *) (p));
while (1) {
if (!pthread_mutex_lock(&chopstick[philosopher.left])) {
printf("%d pick up's left chopstick \\n", philosopher.nr);
while (1) {
if (!pthread_mutex_lock(&chopstick[philosopher.right])) {
printf("%d pick up's right chopstick, happy bastard, EAT \\n", philosopher.nr);
pthread_mutex_unlock(&chopstick[philosopher.left]);
pthread_mutex_unlock(&chopstick[philosopher.right]);
break;
}
}
}
}
}
int main() {
struct philosopher_t *p0_t, *p1_t, *p2_t, *p3_t, *p4_t;
p0_t = malloc(sizeof(struct philosopher_t));
p1_t = malloc(sizeof(struct philosopher_t));
p2_t = malloc(sizeof(struct philosopher_t));
p3_t = malloc(sizeof(struct philosopher_t));
p4_t = malloc(sizeof(struct philosopher_t));
p0_t->nr = 0;
p0_t->left = 0;
p0_t->right = 1;
p1_t->nr = 1;
p1_t->left = 1;
p1_t->right = 2;
p2_t->nr = 2;
p2_t->left = 2;
p2_t->right = 3;
p3_t->nr = 3;
p3_t->left = 3;
p3_t->right = 4;
p4_t->nr = 4;
p4_t->left = 4;
p4_t->right = 0;
if (pthread_create(&philosopher[p0_t->nr], 0, philosopher_deadlock, p0_t)) {
threadError("Error while creating philosopher %d\\n", p0_t->nr);
}
if (pthread_create(&philosopher[p1_t->nr], 0, philosopher_deadlock, p1_t)) {
threadError("Error while creating philosopher %d\\n", p1_t->nr);
}
if (pthread_create(&philosopher[p2_t->nr], 0, philosopher_deadlock, p2_t)) {
threadError("Error while creating philosopher %d\\n", p2_t->nr);
}
if (pthread_create(&philosopher[p3_t->nr], 0, philosopher_deadlock, p3_t)) {
threadError("Error while creating philosopher %d\\n", p4_t->nr);
}
if (pthread_create(&philosopher[p4_t->nr], 0, philosopher_deadlock, p4_t)) {
threadError("Error while creating philosopher %d\\n", p4_t->nr);
}
if (pthread_join(philosopher[p0_t->nr], 0)) {
threadError("Error while ending philosopher %d\\n", p0_t->nr);
}
if (pthread_join(philosopher[p1_t->nr], 0)) {
threadError("Error while ending philosopher %d\\n", p1_t->nr);
}
if (pthread_join(philosopher[p2_t->nr], 0)) {
threadError("Error while ending philosopher %d\\n", p2_t->nr);
}
if (pthread_join(philosopher[p3_t->nr], 0)) {
threadError("Error while ending philosopher %d\\n", p3_t->nr);
}
if (pthread_join(philosopher[p4_t->nr], 0)) {
threadError("Error while ending philosopher %d\\n", p4_t->nr);
}
return 0;
}
| 1
|
#include <pthread.h>
struct pid_data{
pthread_mutex_t pid_mutex;
pid_t pid;
};
struct thread_args{
char message[100];
int priority;
};
static int server_PID;
int set_priority(int priority){
int policy;
struct sched_param param;
if (priority < 1 || priority > 63) return -1;
pthread_getschedparam(pthread_self(), &policy, ¶m);
param.sched_priority = priority;
return pthread_setschedparam(pthread_self(), policy, ¶m);
}
int get_priority(){
int policy;
struct sched_param param;
pthread_getschedparam(pthread_self(), &policy, ¶m);
return param.sched_curpriority;
}
void *send_message(struct thread_args *args){
set_priority(args->priority);
char data_buffer[100];
int channel_id = ConnectAttach(0,server_PID,1,0,0);
int message_status = MsgSend(channel_id,args->message, 100*sizeof(char),&data_buffer, 100*sizeof(char));
printf("Server reply from %s: %s\\n", args->message ,data_buffer);
ConnectDetach(channel_id);
}
int main(int argc, char *argv[]) {
set_priority(10);
printf("Welcome to Program2, we are reading memory\\n");
int fd = shm_open("/sharepid", O_RDWR, S_IRWXU);
struct pid_data *ptr = (struct pid_data*)mmap(0,sizeof(struct pid_data),PROT_READ | PROT_WRITE,MAP_SHARED,fd,0);
pthread_mutexattr_t myattr;
pthread_mutexattr_setpshared(&myattr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&ptr->pid_mutex, &myattr );
pthread_mutex_lock(&ptr->pid_mutex);
server_PID = ptr->pid;
printf("PID read: %i\\n",ptr->pid);
pthread_mutex_unlock(&ptr->pid_mutex);
int data = 42;
int data_buffer;
int channel_id = ConnectAttach(0,server_PID,1,0,0);
int message_status = MsgSend(channel_id,&data, sizeof(int),&data_buffer, sizeof(int));
ConnectDetach(channel_id);
printf("Data buffer received from Server: %i\\n", data_buffer);
struct thread_args t1 = {"thread1", 2};
struct thread_args t2 = {"thread2", 3};
struct thread_args t3 = {"thread3", 5};
struct thread_args t4 = {"thread4", 6};
pthread_t thread1;
pthread_create(&thread1,0,send_message,&t1);
pthread_t thread2;
pthread_create(&thread2,0,send_message,&t2);
pthread_t thread3;
pthread_create(&thread3,0,send_message,&t3);
pthread_t thread4;
pthread_create(&thread4,0,send_message,&t4);
pthread_join(thread1,0);
pthread_join(thread2,0);
pthread_join(thread3,0);
pthread_join(thread4,0);
return 0;
}
| 0
|
#include <pthread.h>
void reader_read(int divider);
void writer_write();
pthread_mutex_t readers_waiting_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t readers_waiting_cond = PTHREAD_COND_INITIALIZER;
int readers_waiting = 0;
pthread_mutex_t writer_locked_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t writer_locked_cond = PTHREAD_COND_INITIALIZER;
bool writer_locked = 0;
void* reader_thread(void* args)
{
int divider = *((int*) args);
log_debug("Created reader, divider: %d", divider);
pthread_mutex_lock(&threads_creating_mutex);
while(!threads_created) {
pthread_cond_wait(&threads_creating_cond, &threads_creating_mutex);
}
pthread_mutex_unlock(&threads_creating_mutex);
for(int cur_read = 0; cur_read < reads_to_do; cur_read++) {
pthread_mutex_lock(&readers_waiting_mutex);
readers_waiting++;
log_debug("Reader: Waiting readers: %d", readers_waiting);
pthread_cond_broadcast(&readers_waiting_cond);
pthread_mutex_unlock(&readers_waiting_mutex);
pthread_mutex_lock(&writer_locked_mutex);
while(writer_locked) {
log_debug("Trying to read, but writer is writing.");
pthread_cond_wait(&writer_locked_cond, &writer_locked_mutex);
}
pthread_mutex_unlock(&writer_locked_mutex);
reader_read(divider);
pthread_mutex_lock(&readers_waiting_mutex);
readers_waiting--;
pthread_cond_broadcast(&readers_waiting_cond);
pthread_mutex_unlock(&readers_waiting_mutex);
}
pthread_exit(0);
}
void* writer_thread(void* args)
{
(void) args;
log_debug("Created writer");
pthread_mutex_lock(&threads_creating_mutex);
while(!threads_created) {
pthread_cond_wait(&threads_creating_cond, &threads_creating_mutex);
}
pthread_mutex_unlock(&threads_creating_mutex);
for(int cur_write = 0; cur_write < writes_to_do; cur_write++) {
pthread_mutex_lock(&readers_waiting_mutex);
while(readers_waiting > 0) {
log_debug("Writer: Readers waiting: %d", readers_waiting);
pthread_cond_wait(&readers_waiting_cond, &readers_waiting_mutex);
}
pthread_mutex_unlock(&readers_waiting_mutex);
pthread_mutex_lock(&writer_locked_mutex);
while(writer_locked) {
pthread_cond_wait(&writer_locked_cond, &writer_locked_mutex);
}
writer_locked = 1;
pthread_cond_broadcast(&writer_locked_cond);
pthread_mutex_unlock(&writer_locked_mutex);
log_debug("writing...");
writer_write();
pthread_mutex_lock(&writer_locked_mutex);
writer_locked = 0;
pthread_cond_broadcast(&writer_locked_cond);
pthread_mutex_unlock(&writer_locked_mutex);
}
pthread_exit(0);
}
void init_threads() {}
void deinit_threads() {}
| 1
|
#include <pthread.h>
struct msg {
int len;
int seq;
char data[20];
};
struct rbuff *rbuff = 0;
pthread_mutex_t iolock = PTHREAD_MUTEX_INITIALIZER;
void *
func_enqueue(void *arg)
{
struct msg msg;
void *buffer = 0;
int i, writen = 0, left = 0;
int num = atoi((char *)arg);
srandom(time(0));
for (i = 1; i <= num; i++) {
msg.len = random()%20;
msg.seq = i;
buffer = &msg;
left = msg.len + ((int)((long)(&(((struct msg *)0)->data))));
while (left > 0) {
writen = rbuff_write(rbuff, buffer, left);
buffer += writen;
left = left - writen;
}
pthread_mutex_lock(&iolock);
printf("write message %d, length %d\\n", msg.seq, msg.len);
pthread_mutex_unlock(&iolock);
}
return 0;
}
void *
func_dequeue(void *arg)
{
struct msg msg;
void *buffer = 0;
int i, readn = 0, left = 0;
int num = atoi((char *)arg);
for (i = 1; i <= num; i++) {
buffer = &msg;
left = (int)(long)(&(((struct msg *)0)->data));
while(left > 0){
readn = rbuff_read(rbuff, buffer, left);
buffer += readn;
left -= readn;
}
buffer = &msg.data;
left = msg.len;
while(left > 0) {
readn = rbuff_read(rbuff, buffer, left);
buffer += readn;
left -= readn;
}
pthread_mutex_lock(&iolock);
printf("read message %d, length %d\\n", msg.seq, msg.len);
pthread_mutex_unlock(&iolock);
}
return 0;
}
int main(int argc, char *argv[])
{
pthread_t thd1, thd2;
assert(argc == 3);
assert(atoi(argv[1]) >= atoi(argv[2]));
rbuff = rbuff_init(1024);
printf ("enqueue %d\\n", atoi(argv[1]));
printf ("dequeue %d\\n", atoi(argv[2]));
pthread_create(&thd1, 0, func_enqueue, argv[1]);
pthread_create(&thd2, 0, func_dequeue, argv[2]);
pthread_join(thd1, 0);
pthread_join(thd2, 0);
return printf("\\n==>remain %u-%u %u\\n", (unsigned int)(rbuff->head), (unsigned int)(rbuff->tail), (unsigned int)(rbuff->head - rbuff->tail));
}
| 0
|
#include <pthread.h>
static int capture_fd = -1;
static pthread_mutex_t captureMutex ;
static char capture_fd_opened = -1;
void capture_init()
{
pthread_mutex_init(&captureMutex, 0);
}
void capture_term()
{
pthread_mutex_destroy(&captureMutex);
}
int capture_open()
{
unsigned int capture_fd_now = 0;
pthread_mutex_lock(&captureMutex);
capture_fd_now = open("/dev/video0", O_RDWR);
if(-1 != capture_fd_now)
{
capture_fd_opened = 1;
}
capture_fd = capture_fd_now;
pthread_mutex_unlock(&captureMutex);
return capture_fd_now;
}
void capture_close()
{
pthread_mutex_lock(&captureMutex);
if(capture_fd_opened)
{
close(capture_fd);
capture_fd = -1;
capture_fd_opened = 0;
}
pthread_mutex_unlock(&captureMutex);
}
void capture_setfd( int fd)
{
pthread_mutex_lock(&captureMutex);
if(capture_fd_opened)
{
close(capture_fd);
capture_fd = -1;
capture_fd_opened = 0;
}
capture_fd = fd;
pthread_mutex_unlock(&captureMutex);
}
int capture_getfd()
{
int capture_fd_now = -1;
pthread_mutex_lock(&captureMutex);
capture_fd_now = capture_fd;
pthread_mutex_unlock(&captureMutex);
return capture_fd_now ;
}
int capture_detect(int index)
{
unsigned char reg=0x10;
unsigned char status1=0;
i2c_read(0x20,®,1,&status1,1);
if((status1&0x05)!=0x05)
{
printf("adv7180:video src no lock %02x\\n",status1);
DeviceStatus.VideoSourceLock=0;
return -1;
}
DeviceStatus.VideoSourceLock=1;
switch (status1 & 0x70)
{
case 0x00:
{
return VideoStd_D1_NTSC;
}
case 0x10:
{
return VideoStd_D1_NTSC;
}
case 0x20:
{
return VideoStd_D1_PAL;
}
case 0x30:
{
return VideoStd_D1_PAL;
}
case 0x40:
{
return VideoStd_D1_PAL;
}
case 0x50:
{
return VideoStd_D1_PAL;
}
case 0x60:
{
return VideoStd_D1_PAL;
}
case 0x70:
{
return VideoStd_D1_PAL;
}
default:
return -1;
}
}
| 1
|
#include <pthread.h>
static Display *dpy;
void close_dpy(void) { XCloseDisplay(dpy); }
char* data;
size_t maxlen;
} lazystr;
void lazystr_init(lazystr* s) {
s->data = malloc(16*sizeof(char));
s->data[0]='\\0';
s->maxlen = 16 -1;
}
void lazystr_fitatleast(lazystr* s, size_t len) {
if (len > s->maxlen) {
size_t newsize = (s->maxlen+1)<<1;
while (newsize-1 < len) {
newsize <<=1;
}
s->data = realloc(s->data,newsize*sizeof(char));
s->maxlen = newsize-1;
}
}
void lazystr_set(lazystr* s, char const* o) {
size_t olen = strlen(o);
lazystr_fitatleast(s,olen);
assert(s->maxlen >= olen);
strncpy(s->data, o, olen);
s->data[olen] = '\\0';
}
pthread_t threads[(sizeof(writer_thread_functions) / sizeof(ptfunc_t))];
lazystr buffers[(sizeof(writer_thread_functions) / sizeof(ptfunc_t))];
lazystr output_buffer;
pthread_mutex_t update_lock;
void destroy_update_lock(void) { pthread_mutex_destroy(&update_lock); }
void setstatus(char const *str) {
XStoreName(dpy, DefaultRootWindow(dpy), str);
XSync(dpy, False);
}
void notify_update(size_t id, char const* str) {
pthread_mutex_lock(&update_lock);
if (id >= (sizeof(writer_thread_functions) / sizeof(ptfunc_t))) {
return;
}
lazystr_set(buffers+id, str);
size_t len = 0;
for (size_t i=0; i<(sizeof(writer_thread_functions) / sizeof(ptfunc_t)); i++) {
len += strlen(buffers[i].data);
}
lazystr_fitatleast(&output_buffer, len);
int pos = 0;
for (size_t i=0; i<(sizeof(writer_thread_functions) / sizeof(ptfunc_t)); i++) {
pos += sprintf(output_buffer.data+pos, "%s", buffers[i].data);
}
assert(pos <= output_buffer.maxlen);
setstatus(output_buffer.data);
pthread_mutex_unlock(&update_lock);
}
int main (int argc, char** argv) {
int rv;
if (argc != 1) {
fprintf(stderr,"There are no command line switches available. Configuration is done at compile-time.\\n");
exit(1);
}
if (!(dpy = XOpenDisplay(0))) {
fprintf(stderr, "cannot open display.\\n");
exit(1);
}
atexit(close_dpy);
lazystr_init(&output_buffer);
rv = pthread_mutex_init(&update_lock, 0);
if (rv != 0) {
exit(3);
}
atexit(destroy_update_lock);
for (size_t i=0; i<(sizeof(writer_thread_functions) / sizeof(ptfunc_t)); i++) {
lazystr_init(&buffers[i]);
}
for (size_t i=0; i<(sizeof(writer_thread_functions) / sizeof(ptfunc_t)); i++) {
rv = pthread_create(&threads[i], 0, writer_thread_functions[i], (void*)i);
if (rv != 0) {
exit(4);
}
}
while(1) {
pause();
}
exit(5);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mx, my;
int x=2, y=2;
void *thread1() {
int a;
pthread_mutex_lock(&mx);
a = x;
pthread_mutex_lock(&my);
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
pthread_mutex_unlock(&my);
a = a + 1;
pthread_mutex_lock(&my);
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
pthread_mutex_unlock(&my);
x = x + x + a;
pthread_mutex_unlock(&mx);
assert(x!=47);
}
void *thread2() {
pthread_mutex_lock(&mx);
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
pthread_mutex_unlock(&mx);
}
void *thread3() {
pthread_mutex_lock(&my);
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
pthread_mutex_unlock(&my);
}
int main() {
pthread_t t1, t2, t3;
pthread_mutex_init(&mx, 0);
pthread_mutex_init(&my, 0);
pthread_create(&t1, 0, thread1, 0);
pthread_create(&t2, 0, thread2, 0);
pthread_create(&t3, 0, thread3, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_join(t3, 0);
pthread_mutex_destroy(&mx);
pthread_mutex_destroy(&my);
return 0;
}
| 1
|
#include <pthread.h>
void add_to_queue(struct list *e, int local)
{
pthread_mutex_lock(&access_queues);
if(local==0)
{
queue_local->next = e;
queue_local = queue_local->next;
num_elem_local++;
}
else
{
queue_ext->next = e;
queue_ext = queue_ext->next;
num_elem_ext++;
}
pthread_mutex_unlock(&access_queues);
sem_post(mutex);
}
struct list * send_to_thread (int local)
{
struct list* consume;
pthread_mutex_lock(&access_queues);
if(local==0)
{
consume = queue_local;
init_local->next = queue_local->next;
if(init_local->next!=0)
queue_local = init_local->next;
else
queue_local = init_local;
num_elem_local--;
}
else
{
consume = queue_ext;
init_ext->next = queue_ext->next;
if(init_ext->next!=0)
queue_ext = init_ext->next;
else
queue_ext = init_ext;
num_elem_ext--;
}
pthread_mutex_unlock(&access_queues);
return consume;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
void *another(void *arg)
{
printf("child thread\\n");
pthread_mutex_lock(&mutex);
sleep(3);
pthread_mutex_unlock(&mutex);
}
void prepare()
{
pthread_mutex_lock(&mutex);
}
void parent()
{
pthread_mutex_unlock(&mutex);
}
void child()
{
pthread_mutex_unlock(&mutex);
}
int main()
{
pthread_mutex_init(&mutex,0);
pthread_t id;
pthread_create(&id,0,another,0);
sleep(1);
pthread_atfork(&prepare,&parent,&child);
int pid = fork();
if(pid < 0)
{
pthread_join(id,0);
pthread_mutex_destroy(&mutex);
return 1;
}
else if(pid == 0)
{
printf("child process\\n");
pthread_mutex_lock(&mutex);
printf("i can not run\\n");
pthread_mutex_unlock(&mutex);
exit(0);
}
else
{
wait(0);
}
pthread_join(id,0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
static int num = 0;
static pthread_mutex_t mut_num = PTHREAD_MUTEX_INITIALIZER;
static void *thr_primer(void *p);
int main()
{
int i,err;
pthread_t tid[3];
for(i = 0; i < 3; i++)
{
err = pthread_create(tid+i,0,thr_primer,(void *)i);
if(err)
{
fprintf(stderr,"pthread_create():%s\\n",strerror(err));
exit(1);
}
}
for(i = 30000000; i <= 30000200; i++)
{
pthread_mutex_lock(&mut_num);
while(num != 0)
{
pthread_mutex_unlock(&mut_num);
sched_yield();
pthread_mutex_lock(&mut_num);
}
num = i;
pthread_mutex_unlock(&mut_num);
}
pthread_mutex_lock(&mut_num);
while(num != 0)
{
pthread_mutex_unlock(&mut_num);
sched_yield();
pthread_mutex_lock(&mut_num);
}
num = -1;
pthread_mutex_unlock(&mut_num);
for(i = 0; i < 3; i++)
pthread_join(tid[i],0);
pthread_mutex_destroy(&mut_num);
exit(0);
}
static void *thr_primer(void *p)
{
int i,j,mark;
while(1)
{
pthread_mutex_lock(&mut_num);
while(num == 0)
{
pthread_mutex_unlock(&mut_num);
sched_yield();
pthread_mutex_lock(&mut_num);
}
if(num == -1)
{
pthread_mutex_unlock(&mut_num);
break;
}
i = num;
num = 0;
pthread_mutex_unlock(&mut_num);
mark = 1;
for(j = 2; j < i/2 ; j++)
{
if(i % j == 0)
{
mark = 0;
break;
}
}
if(mark)
printf("[%d]%d is a primer.\\n",(int)p,i);
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int argv[];
pthread_mutex_t mutex= PTHREAD_MUTEX_INITIALIZER;
int numero_lineas(char *ruta, int *tam_lineas){
if(ruta != 0){
FILE* ar = fopen(ruta, "r");
int lineas = 0;
int tam_linea;
while(!feof(ar)){
tam_linea++;
char c = getc(ar);
if(c == '\\n'){
if(tam_lineas != 0){
tam_lineas[lineas] = tam_linea;
}
lineas++;
tam_linea = 0;
}
}
fclose(ar);
return lineas;
}
return -1;
}
int LineasPorHilo(char* ruta){
int c;
int totalLineas;
int *tam_lineas;
c=numero_lineas(ruta,tam_lineas);
totalLineas=(c/argv[3]);
return totalLineas;
}
void funcionHilo(char* palabras[]){
int j;
int a;
int i;
int cont=0;
int num_palabras[sizeof*(palabras)];
char *pal;
FILE* fp = fopen("/root/taller12/final.txt","r");
a=LineasPorHilo("/root/taller12/final.txt");
if(fp == 0)
printf("Error al abrir el archivo");
while(!feof(fp)){
for(i=0; i<argv[3]; i++){
for(j=0; j<sizeof*(palabras);j++){
pthread_mutex_lock(&mutex);
int p= fseek(fp,(a+1),0);
char* linea=fgets(linea,p,fp);
pal=strtok(linea," ");
if(pal==palabras[j]){
cont++;
num_palabras[cont];
pthread_mutex_unlock(&mutex);
}
}
}
}
}
int main(int argc, char argv[]){
int i;
for(i=4;i<argc;i++){
char palabras[argv[i]];
}
pthread_t threads[argv[3]];
int rc;
int t;
for(t=0; t<argv[3]; t++){
rc=pthread_create(&threads[t],0,(void*)funcionHilo,(void*)t);
if(rc){
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
struct msg
{
int num;
struct msg *next;
} ;
struct msg *head;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
void *producer(void *p);
void *consumer(void *p);
int main(int argc, const char *argv[])
{
pthread_t pid, cid;
srand(time(0));
pthread_create(&pid, 0, producer, 0);
pthread_create(&cid, 0, consumer, 0);
pthread_join(pid, 0);
pthread_join(cid, 0);
return 0;
}
void *producer(void *p)
{
struct msg *mp;
struct msg *tmp;
for (; ; )
{
mp = malloc(sizeof(struct msg));
mp->num = rand() % 1000 + 1;
printf("Produce %d\\n", mp->num);
pthread_mutex_lock(&lock);
tmp = head;
while ((head != 0) && (tmp->next != head))
{
tmp = tmp->next;
}
if (head != 0)
{
tmp->next = mp;
}
else
{
head = mp;
}
mp->next = head;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&has_product);
usleep(rand() % 5);
}
}
void *consumer(void *p)
{
struct msg *mp;
for (; ; )
{
pthread_mutex_lock(&lock);
while (head == 0)
{
pthread_cond_wait(&has_product, &lock);
}
mp = head;
if (head->next == mp)
{
head = 0;
}
else
{
head = mp->next;
}
pthread_mutex_unlock(&lock);
printf("Consume %d\\n", mp->num);
free(mp);
usleep(rand() % 5);
}
}
| 0
|
#include <pthread.h>
int buffer[3];
int size;
int error;
pthread_mutex_t lock;
pthread_t threads[1 + 1];
void * produce (void *arg) {
int i;
for(i = 0; i < 5; i++) {
pthread_mutex_lock(&lock);
if (size < 3) {
buffer[size] = 1;
size++;
}
pthread_mutex_unlock(&lock);
}
return 0;
}
void * consume (void *arg) {
int i;
for(i = 0; i < 5; i++) {
pthread_mutex_lock(&lock);
if (size > 0) {
buffer[size-1]++;
size--;
}
pthread_mutex_unlock(&lock);
}
return 0;
}
void setup() {
int i, err;
size = 0;
if (pthread_mutex_init(&lock, 0) != 0)
printf("\\n mutex init failed\\n");
for (i = 0; i < 1; i++) {
err = pthread_create(&threads[i], 0, produce, 0);
if (err != 0)
printf("\\ncan't create thread :[%s]", strerror(err));
}
for (i = 0; i < 1; i++) {
err = pthread_create(&threads[i+1], 0, consume, 0);
if (err != 0)
printf("\\ncan't create thread :[%s]", strerror(err));
}
}
int run() {
int i;
for (i = 0; i < 1 +1; i++)
pthread_join(threads[i], 0);
return (size >= 0 && size <= 3);
}
int main() {
setup();
return !run();
}
| 1
|
#include <pthread.h>
int cartas = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_pombo = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_user = PTHREAD_COND_INITIALIZER;
void* pombo() {
while(1) {
pthread_mutex_lock(&lock);
if (cartas >= 0) {
printf("Vai dar o wait no pombo\\n");
pthread_cond_wait(&cond_pombo, &lock);
}
cartas = 0;
printf("Valor de cartas após o pombo: %d\\n", cartas);
sleep(3);
pthread_cond_broadcast(&cond_user);
pthread_mutex_unlock(&lock);
}
}
void* user() {
while(1) {
pthread_mutex_lock(&lock);
if (cartas >= 30) {
printf("Entrou no if do user com %d cartas\\n", cartas);
pthread_cond_broadcast(&cond_pombo);
pthread_cond_wait(&cond_user, &lock);
}
cartas++;
pthread_mutex_unlock(&lock);
}
}
int main() {
pthread_t users[2];
pthread_t pombos;
pthread_create(&pombos, 0, pombo, 0);
for (int i = 0; i < 2; ++i) {
pthread_create(&users[i], 0, user, 0);
}
pthread_join(pombos, 0);
for (int i = 0; i < 2; ++i) {
pthread_join(users[i], 0);
}
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutexattr_t mp_mutex_attr;
static pthread_mutex_t mp_mutex;
extern struct fuse_lwext4_options fuse_lwext4_options;
static void mp_lock()
{
pthread_mutex_lock(&mp_mutex);
}
static void mp_unlock()
{
pthread_mutex_unlock(&mp_mutex);
}
static struct ext4_lock mp_lock_func = {
.lock = mp_lock,
.unlock = mp_unlock
};
void *op_init(struct fuse_conn_info *info)
{
int rc;
struct ext4_blockdev *bdev = get_current_blockdev();
if (fuse_lwext4_options.debug)
ext4_dmask_set(DEBUG_ALL);
rc = LWEXT4_CALL(ext4_device_register, bdev, "ext4_fs");
if (rc) {
routine_failed("ext4_device_register", rc);
return 0;
}
rc = LWEXT4_CALL(ext4_mount, "ext4_fs", "/", 0);
if (rc) {
routine_failed("ext4_mount", rc);
return 0;
}
pthread_mutexattr_init(&mp_mutex_attr);
pthread_mutexattr_settype(&mp_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mp_mutex, &mp_mutex_attr);
LWEXT4_CALL(ext4_mount_setup_locks, "/", &mp_lock_func);
rc = LWEXT4_CALL(ext4_recover, "/");
if (rc && rc != -ENOTSUP) {
routine_failed("ext4_recover", rc);
EMERG("In concern for consistency, please run e2fsck against the filesystem.");
return 0;
}
if (fuse_lwext4_options.journal)
assert(!LWEXT4_CALL(ext4_journal_start, "/"));
if (fuse_lwext4_options.cache)
assert(!LWEXT4_CALL(ext4_cache_write_back, "/", 1));
return bdev;
}
| 1
|
#include <pthread.h>
void AC_init(struct arp_cache *AC)
{
AC->length=0;
int i;
for(i=0; i<MAX_AC_LEN; i++)
{
AC->list[i].ip_addr=0;
}
pthread_mutex_init(&(AC->AC_mutex), 0);
pthread_create(&(AC->thread), 0, AC_update, AC);
}
void AC_insert(struct arp_cache* AC, uint32_t ip_addr, unsigned char* mac_addr)
{
int full=1;
int i;
pthread_mutex_lock(&(AC->AC_mutex));
{
for(i=0; i<MAX_AC_LEN; i++)
{
if(AC->list[i].ip_addr==0)
{
full=0;
break;
}
if(AC->list[i].ip_addr==ip_addr)
return;
}
if(full)
i=0;
AC->length++;
AC->list[i].ip_addr = ip_addr;
memcpy(AC->list[i].mac_addr, mac_addr, ETHER_ADDR_LEN);
AC->list[i].age=time(0);
}
pthread_mutex_unlock(&(AC->AC_mutex));
}
struct arp_cache_item *AC_search(struct arp_cache *AC, uint32_t ip_addr)
{
int i;
struct arp_cache_item* temp=0;
pthread_mutex_lock(&(AC->AC_mutex));
{
for(i=0; i<MAX_AC_LEN; i++)
{
if(AC->list[i].ip_addr == ip_addr){
temp= &AC->list[i];
break;
}
}
}
pthread_mutex_unlock(&(AC->AC_mutex));
return temp;
}
int AC_erase(struct arp_cache *AC, uint32_t ip_addr)
{
int i;
int success=0;
pthread_mutex_lock(&(AC->AC_mutex));
{
for(i=0; i<MAX_AC_LEN; i++)
{
if(AC->list[i].ip_addr==ip_addr)
{
AC->list[i].ip_addr=0;
success= 1;
}
}
}
pthread_mutex_unlock(&(AC->AC_mutex));
return success;
}
void* AC_update(void *arg)
{
struct arp_cache *AC=(struct arp_cache*)arg;
time_t current;
int i;
while(1)
{
sleep(1);
current=time(0);
pthread_mutex_lock(&(AC->AC_mutex));
{
for(i=0; i<MAX_AC_LEN; i++)
{
if(AC->list[i].ip_addr!=0)
{
if(current - AC->list[i].age > 15){
AC->list[i].ip_addr=0;
AC->length--;
}
}
}
}
pthread_mutex_unlock(&(AC->AC_mutex));
}
}
| 0
|
#include <pthread.h>
double sumPi( int startN, int count ) {
double s = 0;
int n;
for( n = startN; n<startN+count; n++ ) {
s += pow( -1, n + 1 ) * 4 / ( 2*n -1 );
}
return s;
}
int epp;
int len;
} tdata;
double pi = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void * start_thread1 ( void *data ) {
tdata *t = (tdata*)data;
double s = sumPi( t->epp, t->len );
printf("Child with params %d, %d result: %f\\n", t->epp, t->len, s);
pthread_mutex_lock (&mutex);
pi += s;
pthread_mutex_unlock (&mutex);
}
int main(int argc, char **argv) {
if ( argc != 3 ) {
printf("You should enter number of sum elements and number of processes\\n");
return 1;
}
int K = strtol(argv[1], 0, 10);
int N = strtol(argv[2], 0, 10);
int i;
int elementsPerProcess = K/N;
pthread_t tids[N];
tdata t[N];
for( i=0; i<N; i++ ) {
t[i].epp = (i * elementsPerProcess) + 1;
t[i].len = elementsPerProcess;
printf("tdata: %d, %d\\n", t[i].epp, t[i].len);
pthread_create( &tids[i], 0, start_thread1, (void *) &t[i] );
}
for( i=0; i<N; i++ ) {
pthread_join( tids[i], 0 );
}
printf("\\nTotal pi: %f\\n", pi);
}
| 1
|
#include <pthread.h>
enum {
eUndefinedId,
};
int id;
EvCallback onEvent;
} Listener;
static Listener NullLis = {.id = eUndefinedId, .onEvent = 0};
static Listener gListeners[6] = {{eUndefinedId, 0}};
static pthread_mutex_t gLisMutex;
void initListenerGroup() {
pthread_mutex_init(&gLisMutex, 0);
}
void finiListenerGroup() {
pthread_mutex_destroy(&gLisMutex);
}
int repListener(Listener lis0, Listener lis1) {
int ret = 0;
int i;
pthread_mutex_lock(&gLisMutex);
for (i = 0; i != 6; i++) {
if (gListeners[i].id == lis0.id) {
gListeners[i] = lis1;
ret = 1;
goto final;
}
}
final:
pthread_mutex_unlock(&gLisMutex);
return ret;
}
void notifyListener(void *msg) {
int i;
for (i = 0; i != 6; i++) {
if (gListeners[i].id != eUndefinedId) {
pthread_mutex_lock(&gLisMutex);
Listener lis = gListeners[i];
pthread_mutex_unlock(&gLisMutex);
lis.onEvent(lis.id, msg);
}
}
}
int attachListener(Listener lis) {
{if (lis.id == eUndefinedId) { return 0; }};
{if (lis.onEvent == 0) { return 0; }};
return repListener(NullLis, lis);
}
int detachListener(Listener lis) {
{if (lis.id == eUndefinedId) { return 0; }};
return repListener(lis, NullLis);
}
int SilentListener(int id, void *msg) {
printf("silent lis=%04d recv msg=%p\\n", id, msg);
return 0;
}
int OneTimeListener(int id, void *msg) {
printf("onetime lis=%04d recv msg=%p\\n", id, msg);
Listener self = {.id = id, 0};
int r = detachListener(self);
if (!r) {
printf("cannot remove listener id=%d\\n", id);
}
return 0;
}
int ChaosListener(int id, void *msg) {
printf("chaos lis=%04d recv msg=%p\\t", id, msg);
if (msg != 0) {
char *str = msg;
printf("msg=[%s]\\n", str);
}
Listener self = {.id = id, 0};
Listener lis0 = {.id = id * 2, ChaosListener};
Listener lis1 = {.id = id * 2 + 1, OneTimeListener};
detachListener(self);
attachListener(lis0);
attachListener(lis1);
return 0;
}
void *notifyTask(void *args) {
char msg[16];
int i;
for (i = 0; i != 5; i++) {
sleep(1);
sprintf(msg, "msg=%d", i);
notifyListener(msg);
}
return 0;
}
int main() {
initListenerGroup();
pthread_t t0;
pthread_create(&t0, 0, notifyTask, 0);
Listener silent = {1, SilentListener};
Listener chaos = {2, ChaosListener};
Listener one = {3, OneTimeListener};
attachListener(silent);
attachListener(chaos);
attachListener(one);
pthread_join(t0, 0);
finiListenerGroup();
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);
return 0;
}
idx = (((unsigned long)fp)%29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp->f_next;
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;
int idx;
idx = (((unsigned long)fp)%29);
pthread_mutex_lock(&hashlock);
for ( fp = fh[idx];fp!=0;fp=fp->f_next ) {
if ( fp->f_id == id ) {
fp->f_count++;
break;
}
}
pthread_mutex_unlock(&hashlock);
return fp;
}
void foo_release(struct foo *fp) {
struct foo *tfp;
int idx;
pthread_mutex_lock(&hashlock);
if (--fp->f_count == 1 ){
idx = (((unsigned long)fp)%29);
tfp = fh[idx];
if ( tfp == fp ){
fh[idx] = fp->f_next;
} else {
while ( tfp->f_next != fp )
tfp = tfp->f_next;
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
} else {
pthread_mutex_unlock(&fp->f_lock);
}
}
int main(int argc,char *argv[]){
return 0;
}
| 1
|
#include <pthread.h>
int primes[10000];
int pflag[10000];
int total = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int is_prime(int v)
{
int i;
int bound = floor(sqrt(v)) + 1;
for (i = 2; i < bound; i++) {
if (!pflag[i])
continue;
if (v % i == 0) {
pflag[v] = 0;
return 0;
}
}
return (v > 1);
}
void *work(void *arg)
{
int start;
int end;
int i;
start = (10000/4) * ((int)arg) ;
end = start + 10000/4;
for (i = start; i < end; i++) {
if ( is_prime(i) ) {
pthread_mutex_lock(&mutex);
primes[total] = i;
total++;
pthread_mutex_unlock(&mutex);
}
}
return 0;
}
int main(int argn, char **argv)
{
int i;
pthread_t tids[4 -1];
for (i = 0; i < 10000; i++) {
pflag[i] = 1;
}
for (i = 0; i < 4 -1; i++) {
pthread_create(&tids[i], 0, work, (void *)i);
}
i = 4 -1;
work((void *)i);
for (i = 0; i < 4 -1; i++) {
pthread_join(tids[i], 0);
}
printf("Number of prime numbers between 2 and %d: %d\\n",
10000, total);
return 0;
}
| 0
|
#include <pthread.h>
int num = 0, switch_count = 0;
int child_status;
float thread_switching_times[1000];
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
double timespec_to_ns(struct timespec *ts)
{
return ts->tv_nsec;
}
void func_call()
{
int i;
struct timespec start_time, end_time;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_time);
for(i = 0; i < 5000000; i++);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_time);
printf("Cost of minimal function call: %f ns\\n", (timespec_to_ns(&end_time) - timespec_to_ns(&start_time)) / 5000000.0);
return;
}
void sys_call()
{
int i;
struct timespec start_time, end_time;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_time);
for(i = 0; i < 5000000; i++)
syscall(SYS_getpid);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_time);
printf("Cost of minimal system call: %f ns\\n", (timespec_to_ns(&end_time) - timespec_to_ns(&start_time)) / 5000000.0);
return;
}
void process_switching()
{
int retval, n;
struct timespec start_time, end_time;
int parent_to_child[2];
int child_to_parent[2];
char buf[2];
char *msg = "a";
float process_switch_times[500];
float avg_time;
pid_t childpid;
if (pipe(parent_to_child) == -1) {
perror("pipe");
exit(0);
}
if (pipe(child_to_parent) == -1) {
perror("pipe");
exit(0);
}
childpid = fork();
if (childpid >= 0) {
if (childpid == 0) {
for (n = 0; n < 500; n++) {
close(parent_to_child[1]);
close(child_to_parent[0]);
retval = read(parent_to_child[0], buf, 1);
if (retval == -1) {
perror("Error reading in child");
exit(0);
}
retval = write(child_to_parent[1], msg, strlen(msg));
if (retval == -1) {
perror("Error writing in child");
exit(0);
}
}
if (close(child_to_parent[1]) == -1)
perror("close");
exit(0);
}
else {
for (n = 0; n < 500; n++) {
close(parent_to_child[0]);
close(child_to_parent[1]);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_time);
retval = write(parent_to_child[1], msg, strlen(msg));
if (retval == -1) {
perror("Error writing in parent");
break;
}
retval = read(child_to_parent[0], buf, 1);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_time);
process_switch_times[n] = timespec_to_ns(&end_time) - timespec_to_ns(&start_time);
if (retval == -1) {
perror("Error reading in parent");
break;
}
}
if (close(parent_to_child[1]) == -1) {
perror("close");
exit(0);
}
waitpid(childpid, &child_status, 0);
for (n = 0; n < 500; n++)
avg_time += process_switch_times[n];
printf("Cost of process switching: %f ns\\n", avg_time / 1000.0);
}
}
else {
perror("fork");
exit(0);
}
return;
}
void *thread1()
{
int i;
struct timespec start_time, end_time;
for (i = 0; i < 500; i++) {
pthread_mutex_lock(&lock);
while (num == 0) {
pthread_cond_wait(&cond1, &lock);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_time);
thread_switching_times[switch_count] = timespec_to_ns(&end_time) - timespec_to_ns(&start_time);
switch_count++;
}
num = 0;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_time);
pthread_cond_signal(&cond2);
pthread_mutex_unlock(&lock);
}
return 0;
}
void *thread2()
{
int i;
struct timespec start_time, end_time;
for (i = 0; i < 500; i++) {
pthread_mutex_lock(&lock);
while (num == 1) {
pthread_cond_wait(&cond2, &lock);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_time);
thread_switching_times[switch_count] = timespec_to_ns(&end_time) - timespec_to_ns(&start_time);
switch_count++;
}
num = 1;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_time);
pthread_cond_signal(&cond1);
pthread_mutex_unlock(&lock);
}
return 0;
}
void thread_switching()
{
int i;
float avg_time;
pthread_t t1, t2;
pthread_create(&t1, 0, thread1, 0);
pthread_create(&t2, 0, thread2, 0);
pthread_join(t1,0);
pthread_join(t2,0);
for (i = 0; i < switch_count; i++)
avg_time += thread_switching_times[i];
printf("Cost of thread switching: %f ns\\n", avg_time / switch_count);
return;
}
int main()
{
func_call();
sys_call();
process_switching();
thread_switching();
return 0;
}
| 1
|
#include <pthread.h>
struct target {
unsigned long ip;
unsigned short port;
struct target *next;
} *targets = 0;
char *progname;
pthread_mutex_t lock;
void
error (char *err)
{
fprintf (stderr, "%s: %s\\n", progname, err);
exit (1);
}
unsigned long
host_resolve (char *host)
{
struct in_addr addr;
struct hostent *host_ent;
addr.s_addr = inet_addr (host);
if (addr.s_addr == -1)
{
host_ent = gethostbyname (host);
if (host_ent == 0)
addr.s_addr = 0;
else
bcopy (host_ent->h_addr, (char *)&addr.s_addr, host_ent->h_length);
}
return addr.s_addr;
}
void
put_target (char *str)
{
struct target *t;
char *host, *startport, *endport;
unsigned long ip;
int port;
host = strtok (str, ":");
startport = strtok (0, "-");
if (startport == 0)
error ("invalid host:port");
endport = strtok (0, "-");
if (endport == 0)
endport = startport;
ip = host_resolve (host);
if (ip == 0)
fprintf (stderr, "can't resolve %s\\n", host);
else
for (port = atoi (startport); port <= atoi (endport); port++)
{
t = (struct target *)malloc (sizeof (struct target));
if (t == 0)
error ("malloc()");
t->ip = ip;
t->port = port;
t->next = targets;
targets = t;
}
}
struct target *
get_target (void)
{
struct target *tmp;
pthread_mutex_lock (&lock);
if (targets == 0)
tmp = 0;
else
{
tmp = targets;
targets = targets->next;
}
pthread_mutex_unlock (&lock);
return tmp;
}
int
can_connect (unsigned long ip, unsigned short port)
{
int fd, result;
struct sockaddr_in addr;
fd = socket (AF_INET, SOCK_STREAM, 0);
if (fd == -1)
{
perror ("socket()");
return 0;
}
addr.sin_addr.s_addr = ip;
addr.sin_port = htons (port);
addr.sin_family = AF_INET;
result = connect (fd, (struct sockaddr *)&addr, sizeof (struct sockaddr));
close (fd);
return (result == 0);
}
void *scan (void *data)
{
struct target *t;
struct in_addr addr;
while ((t = get_target ()) != 0)
if (can_connect (t->ip, t->port))
{
addr.s_addr = t->ip;
printf ("%s:%d\\n", inet_ntoa (addr), t->port);
}
return 0;
}
int main (int argc, char *argv[])
{
int thread_num = 20, i, optnum = 0;
char buf[1000];
pthread_t threads[255];
void *retval;
struct servent *se;
progname = argv[0];
if (argc == 1)
{
printf ("threaded tcp port scanner - <mirage@hackers-pt.org>\\n");
printf ("usage: %s [options] [host:startport-endport | host:port (...)]\\n", argv[0]);
printf ("options are:\\n");
printf (" -t <threads to use> (default 20)\\n");
printf (" -s <host> scan this host for the ports in /etc/services\\n");
return 1;
}
while ((i = getopt(argc, argv, "t:s:")) != EOF)
switch (i)
{
case 't':
thread_num = atoi (optarg);
if (thread_num > 255)
error ("too many threads requested");
optnum += 2;
break;
case 's':
setservent (1);
while ((se = getservent ()) != 0)
if (strcasecmp ("tcp", se->s_proto) == 0)
{
if (strlen (optarg) > 64)
optarg[64] = 0;
sprintf (buf, "%s:%d", optarg, ntohs (se->s_port));
put_target (buf);
}
endservent ();
optnum += 2;
break;
default:
return 1;
}
for (i = optnum+1; i < argc; i++)
put_target (argv[i]);
pthread_mutex_init (&lock, 0);
for (i = 0; i < thread_num; i++)
if (pthread_create (&threads[i], 0, scan, 0) != 0)
error ("pthread_create()");
for (i = 0; i < thread_num; i++)
pthread_join (threads[i], &retval);
return 0;
}
| 0
|
#include <pthread.h>
THREAD_STATE_RUNNING,
THREAD_STATE_WAIT,
} DbgCpuThrStateType;
static pthread_mutex_t dbg_mutex;
static pthread_cond_t dbg_cv;
static pthread_cond_t cpu_cv;
static volatile DbgCpuThrStateType dbgthr_state = THREAD_STATE_RUNNING;
static volatile DbgCpuThrStateType cputhr_state = THREAD_STATE_WAIT;
void cputhr_control_init(void)
{
pthread_mutex_init(&dbg_mutex, 0);
pthread_cond_init(&dbg_cv, 0);
pthread_cond_init(&cpu_cv, 0);
return;
}
void cputhr_control_start(void *(*cpu_run) (void *))
{
pthread_t thread;
cputhr_state = THREAD_STATE_RUNNING;
pthread_create(&thread , 0 , cpu_run , 0);
}
void cputhr_control_cpu_wait(void)
{
pthread_mutex_lock(&dbg_mutex);
cputhr_state = THREAD_STATE_WAIT;
pthread_cond_wait(&cpu_cv, &dbg_mutex);
cputhr_state = THREAD_STATE_RUNNING;
pthread_mutex_unlock(&dbg_mutex);
return;
}
void cputhr_control_dbg_wait(void)
{
pthread_mutex_lock(&dbg_mutex);
dbgthr_state = THREAD_STATE_WAIT;
pthread_cond_wait(&dbg_cv, &dbg_mutex);
dbgthr_state = THREAD_STATE_RUNNING;
pthread_mutex_unlock(&dbg_mutex);
return;
}
void cputhr_control_dbg_wakeup_cpu_and_wait_for_cpu_stopped(void)
{
pthread_mutex_lock(&dbg_mutex);
if (cputhr_state == THREAD_STATE_WAIT) {
cputhr_state = THREAD_STATE_RUNNING;
pthread_cond_signal(&cpu_cv);
}
while (cputhr_state == THREAD_STATE_RUNNING) {
pthread_mutex_unlock(&dbg_mutex);
Sleep(50);
pthread_mutex_lock(&dbg_mutex);
}
pthread_mutex_unlock(&dbg_mutex);
return;
}
void cputhr_control_dbg_waitfor_cpu_stopped(void)
{
pthread_mutex_lock(&dbg_mutex);
while (cputhr_state == THREAD_STATE_RUNNING) {
pthread_mutex_unlock(&dbg_mutex);
Sleep(50);
pthread_mutex_lock(&dbg_mutex);
}
pthread_mutex_unlock(&dbg_mutex);
return;
}
void cputhr_control_dbg_wakeup_cpu(void)
{
pthread_mutex_lock(&dbg_mutex);
pthread_cond_signal(&cpu_cv);
pthread_mutex_unlock(&dbg_mutex);
}
void cputhr_control_cpu_wakeup_dbg(void)
{
pthread_mutex_lock(&dbg_mutex);
pthread_cond_signal(&dbg_cv);
pthread_mutex_unlock(&dbg_mutex);
}
| 1
|
#include <pthread.h>
char buffer[1024];
int bytesReceived = 1;
int bytesInBuffer = 0;
pthread_mutex_t mutex;
void *interfaceThread( void *arg ) {
short terminated = 0;
int bytesPrinted = 0;
int lines_count = 0;
while (1) {
pthread_mutex_lock(&mutex);
if ((0 == bytesReceived) && (bytesInBuffer == 0)) {
pthread_mutex_unlock(&mutex);
break;
}
pthread_mutex_unlock(&mutex);
if ( terminated ) {
char user_input = 0;
scanf("%c",&user_input);
lines_count = 0;
terminated = 0;
}
pthread_mutex_lock(&mutex);
for (int i = bytesPrinted; i < bytesInBuffer; i++) {
printf("%c", buffer[i]);
if ('\\n' == buffer[i]) {
lines_count++;
if (lines_count > 25) {
printf("Enter to scroll down\\n");
bytesPrinted = i + 1;
terminated = 1;
break;
}
}
}
if ( !terminated ) {
bytesInBuffer = 0;
bytesPrinted = 0;
}
pthread_mutex_unlock(&mutex);
}
return 0;
}
int main( int argc, char ** argv ) {
pthread_t thread;
if ( 0 != pthread_mutex_init(&mutex, 0)) {
perror("Could not init mutex\\n");
return 1;
}
if ( argc < 2 ) {
fprintf(stderr, "No URL entered\\n");
return 1;
}
int server_fd = 0;
struct sockaddr_in server_address = {0};
server_address.sin_family = AF_INET;
server_address.sin_port = htons(80);
server_address.sin_addr.s_addr = inet_addr(argv[1]);
server_fd = socket(AF_INET, SOCK_STREAM,0);
if (-1 == server_fd) {
perror("Could not create socket\\n");
return 1;
}
if (0 != connect( server_fd,
(struct sockaddr *) &server_address,
sizeof(server_address))
) {
perror("Could not connect to server\\n");
return 1;
}
if ( 0 != pthread_create(&thread, 0, interfaceThread, 0) ) {
perror("Could not create routine\\n");
return 1;
}
write(server_fd, "GET / HTTP/1.0\\n\\n", sizeof("GET / HTTP/1.0\\n\\n"));
while (0 != bytesReceived) {
if (bytesInBuffer + 16 < 1024) {
pthread_mutex_lock(&mutex);
bytesReceived = read(server_fd, buffer + bytesInBuffer, 16);
bytesInBuffer += bytesReceived;
pthread_mutex_unlock(&mutex);
}
}
if ( 0 != pthread_join(thread,0) ) {
perror("Could not cancel thread\\n");
return 1;
}
if ( 0 != pthread_mutex_destroy(&mutex) ) {
perror("Could not destroy mutex\\n");
return 1;
}
return 0;
}
| 0
|
#include <pthread.h>
int addHrac(int c_socket, char* nazev);
int removeHrac(int id);
int removeHracSoc(int clie_soc);
int getHracIndex(int socket);
int broadcastHraci(char *text);
int broadcastToLobby(int *hraciX, int SocketHraceVynechat, char *text);
struct Hrac* boostHraci();
struct Hrac* reduceHraci();
int initHraci();
int uvolniHrace();
struct Hrac *hraci;
int length_hraci = 5;
int obsazeny_hraci = 0;
int id_plus = 1;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int initHraci()
{
hraci = (struct Hrac*)malloc(sizeof(struct Hrac) * length_hraci);
for(int i = 0; i < length_hraci; i++)
{
hraci[i].init = 0;
}
}
struct Hrac* boostHraci()
{
struct Hrac *doubleHraci;
doubleHraci = (struct Hrac*)malloc(sizeof(struct Hrac) * (length_hraci * 2));
for(int i = 0; i < length_hraci; i++)
{
doubleHraci[i].client_socket = hraci[i].client_socket;
doubleHraci[i].id = hraci[i].id;
doubleHraci[i].stav = hraci[i].stav;
strcpy(doubleHraci[i].jmeno, hraci[i].jmeno);
doubleHraci[i].init = hraci[i].init;
}
for(int i = length_hraci; i < length_hraci * 2; i++)
{
hraci[i].init = 0;
}
free(hraci);
length_hraci *= 2;
return doubleHraci;
}
struct Hrac* reduceHraci()
{
struct Hrac *halfHraci;
halfHraci = (struct Hrac*)malloc(sizeof(struct Hrac) * (length_hraci * 2));
for(int i = 0; i < length_hraci; i++)
{
halfHraci[i].client_socket = hraci[i].client_socket;
halfHraci[i].id = hraci[i].id;
halfHraci[i].stav = hraci[i].stav;
strcpy(halfHraci[i].jmeno, hraci[i].jmeno);
halfHraci[i].init = hraci[i].init;
}
free(hraci);
length_hraci /= 2;
return halfHraci;
}
int uvolniHrace()
{
free(hraci);
}
int getHracIndex(int socket)
{
int ind = -1;
for(int i = 0;i < length_hraci; i++)
{
if(hraci[i].init == 1)
{
if(hraci[i].client_socket == socket)
{
ind = i;
break;
}
}
}
return ind;
}
int addHrac(int c_socket, char *nazev)
{
pthread_mutex_lock(&lock);
if(obsazeny_hraci == length_hraci)
{
hraci = boostHraci();
}
int ind = -1;
for(int i = 0; i < length_hraci; i++)
{
if(hraci[i].init == 0)
{
ind = i;
break;
}
}
if(ind == -1)
{
printf("CHYBA - nenasel misto v poli, nebo neinicializovane pole.\\n");
return 1;
}
hraci[ind].client_socket = c_socket;
memset(&hraci[ind].jmeno, 0, sizeof(hraci[ind].jmeno));
memcpy(hraci[ind].jmeno, nazev, sizeof(nazev));
hraci[ind].id = id_plus++;
hraci[ind].init = 1;
hraci[ind].stav = 1;
obsazeny_hraci++;
pthread_mutex_unlock(&lock);
return 0;
}
int removeHrac(int id)
{
pthread_mutex_lock(&lock);
int ind = -1;
for(int i = 0; i < length_hraci; i++)
{
if(hraci[i].id == id)
{
ind = i;
break;
}
}
if(ind == -1)
{
pthread_mutex_unlock(&lock);
printf("CHYBA - nenasel hrace s ID:%d v poli hracu!\\n", ind);
return 1;
}
hraci[ind].client_socket = -1;
memset(&hraci[ind].jmeno, 0, sizeof(hraci[ind].jmeno));
hraci[ind].id = -1;
hraci[ind].stav = 0;
hraci[ind].init = 0;
obsazeny_hraci--;
if((obsazeny_hraci * 2) == length_hraci)
{
hraci = reduceHraci();
}
pthread_mutex_unlock(&lock);
return 0;
}
int removeHracSoc(int clie_soc)
{
pthread_mutex_lock(&lock);
int ind = -1;
for(int i = 0; i < length_hraci; i++)
{
if(hraci[i].client_socket == clie_soc)
{
ind = i;
break;
}
}
if(ind == -1)
{
pthread_mutex_unlock(&lock);
printf("CHYBA - nenasel hrace s SOCKETEM:%d v poli hracu!\\n", ind);
return 1;
}
hraci[ind].client_socket = -1;
memset(&hraci[ind].jmeno, 0, sizeof(hraci[ind].jmeno));
hraci[ind].id = -1;
hraci[ind].stav = 0;
hraci[ind].init = 0;
obsazeny_hraci--;
if((obsazeny_hraci * 2) == length_hraci)
{
hraci = reduceHraci();
}
pthread_mutex_unlock(&lock);
return 0;
}
int broadcastHraci(char *text)
{
pthread_mutex_lock(&lock);
char text1[1000] = "";
strcpy(text1, text);
for(int i = 0; i < length_hraci; i++)
{
if(hraci[i].init == 1)
{
send(hraci[i].client_socket, &text1, strlen(text1), 0);
}
}
pthread_mutex_unlock(&lock);
}
int broadcastToLobby(int *hraciX, int SocketHraceVynechat, char *text)
{
pthread_mutex_lock(&lock);
char text1[1000] = "";
strcpy(text1, text);
printf("broadcast: %s", text1);
for(int i = 0; i < 4; i++)
{
if(hraciX[i] != -1 && hraci[hraciX[i]].client_socket != SocketHraceVynechat)
{
send(hraci[hraciX[i]].client_socket, &text1, strlen(text1), 0);
}
}
pthread_mutex_unlock(&lock);
}
| 1
|
#include <pthread.h>
int udp_init_client(struct udp_conn *udp, int port, char *ip)
{
struct hostent *host;
if ((host = gethostbyname(ip)) == 0) return -1;
if (pthread_mutex_init(&udp->lock, 0) != 0) return -2;
udp->client_len = sizeof(udp->client);
memset((char *)&(udp->server), 0, sizeof(udp->server));
udp->server.sin_family = AF_INET;
udp->server.sin_port = htons(port);
bcopy((char *)host->h_addr, (char *)&(udp->server).sin_addr.s_addr, host->h_length);
if ((udp->sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) return udp->sock;
return 0;
}
int udp_send(struct udp_conn *udp, char *buf, int len)
{
return sendto(udp->sock, buf, len, 0, (struct sockaddr *)&(udp->server), sizeof(udp->server));
}
int udp_receive(struct udp_conn *udp, char *buf, int len)
{
int res = recvfrom(udp->sock, buf, len, 0, (struct sockaddr *)&(udp->client), &(udp->client_len));
return res;
}
void udp_close(struct udp_conn *udp)
{
pthread_mutex_lock(&udp->lock);
close(udp->sock);
pthread_mutex_unlock(&udp->lock);
return;
}
int clock_nanosleep(struct timespec *next)
{
struct timespec now;
struct timespec sleep;
clock_gettime(CLOCK_REALTIME, &now);
sleep.tv_sec = next->tv_sec - now.tv_sec;
sleep.tv_nsec = next->tv_nsec - now.tv_nsec;
if (sleep.tv_nsec < 0)
{
sleep.tv_nsec += 1000000000;
sleep.tv_sec -= 1;
}
nanosleep(&sleep, 0);
return 0;
}
void timespec_add_us(struct timespec *t, long us)
{
t->tv_nsec += us*1000;
if (t->tv_nsec > 1000000000)
{
t->tv_nsec -= 1000000000;
t->tv_sec += 1;
}
}
| 0
|
#include <pthread.h>
int reader_cnt = 0;
pthread_mutex_t read_cnt_mutex,rw_mutex;
int cnt = 3;
void *write_handle(void *arg);
void *read_handle(void *arg);
int main(void)
{
int type;
pthread_t tid_r, tid_w;
srand(getpid());
pthread_mutex_init(&read_cnt_mutex, 0);
pthread_mutex_init(&rw_mutex, 0);
while(1)
{
type = rand();
if(type %2 == 0)
{
pthread_create(&tid_w, 0, write_handle, 0);
}
else
{
pthread_create(&tid_r, 0, read_handle, 0);
}
sleep(1);
}
pthread_mutex_destroy(&read_cnt_mutex);
pthread_mutex_destroy(&rw_mutex);
return 0;
}
void *write_handle(void *arg)
{
pthread_detach(pthread_self());
pthread_mutex_lock(&rw_mutex);
printf("a writer in\\n");
++cnt;
sleep(5);
printf("a writer out\\n");
pthread_mutex_unlock(&rw_mutex);
}
void *read_handle(void *arg)
{
pthread_detach(pthread_self());
pthread_mutex_lock(&read_cnt_mutex);
++reader_cnt;
if(reader_cnt == 1)
pthread_mutex_lock(&rw_mutex);
pthread_mutex_unlock(&read_cnt_mutex);
printf("a reader in\\n");
printf("%d\\n",cnt);
sleep(3);
pthread_mutex_lock(&read_cnt_mutex);
--reader_cnt;
printf("a reader out\\n");
if(reader_cnt == 0)
pthread_mutex_unlock(&rw_mutex);
pthread_mutex_unlock(&read_cnt_mutex);
}
| 1
|
#include <pthread.h>
static int num = 0;
static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static int next(int n)
{
if (n+1 == 4) {
return 0;
}
return n+1;
}
void* func(void *p)
{
int i = (int)p;
int c= 'a'+ i;
while (1) {
pthread_mutex_lock(&mut);
if (num==i) {
write(1, &c, 1);
num = next(num);
pthread_cond_broadcast(&cond);
}else {
pthread_cond_wait(&cond, &mut);
}
pthread_mutex_unlock(&mut);
}
pthread_exit(0);
}
int main(int argc, const char *argv[])
{
static pthread_t tid[4];
int i, err;
for (i = 0; i < 4; i++) {
err = pthread_create(tid+i, 0, func, (void *)i);
if (err) {
fprintf(stderr, "pthread_create():\\n",strerror(err));
exit(1);
}
}
alarm(5);
for (i = 0; i < 4; i++) {
pthread_join(tid[i], 0);
}
pthread_mutex_destroy(&mut);
pthread_cond_destroy(&cond);
exit(0);
}
| 0
|
#include <pthread.h>
pthread_t thread[20];
pthread_mutex_t mut;
{
int num;
int money;
}red_Packet;
static red_Packet redPacket = {0};
void *woker()
{
int money = 0;
pthread_mutex_lock(&mut);
if(redPacket.num <= 0)
{
pthread_mutex_unlock(&mut);
pthread_exit(0);
}
else if(redPacket.num == 1)
{
money = redPacket.money;
}
else
{
money = redPacket.money * (rand() % ((199) - (1)) + (1)) / 100 / redPacket.num;
}
redPacket.money -= money;
-- redPacket.num;
pthread_mutex_unlock(&mut);
pthread_exit(0);
}
void thread_create(void)
{
memset(&thread, 0, sizeof(thread));
for(int i = 0; i < 20; ++ i)
{
if((pthread_create(&thread[i], 0, woker, 0)) != 0)
{
printf("线程%d创建失败!\\n", i);
}
else
{
}
}
}
void thread_wait(void)
{
for(int i = 0; i < 20; ++ i)
{
if(thread[i] != 0)
{
pthread_join(thread[i], 0);
}
}
}
int main(int argc, char *argv[])
{
pthread_mutex_init(&mut, 0);
srand((unsigned)time(0));
float num = 0;
float money = 0;
while(1)
{
printf("Input: <number> <money>\\n");
if(fscanf(stdin, "%f %f", &num, &money) == EOF)
{
break;
}
if(num <= 0 || num > 20)
{
printf("Package number out of range: [1, %d]\\n", 20);
continue;
}
if(money <= 1 || money > 500)
{
printf("Total money out of range: [1, %d]\\n", 500);
continue;
}
redPacket.num = num;
redPacket.money = 100 * money;
printf("Init: [%d个红包, %d.%02d元]\\n", redPacket.num, redPacket.money / 100, redPacket.money % 100);
thread_create();
thread_wait();
}
pthread_mutex_destroy(&mut);
return 0;
}
| 1
|
#include <pthread.h>
struct mbox mbox_sort_recv, mbox_sort_send;
struct mbox mbox_mmul_recv, mbox_mmul_send;
struct reconos_hwt hwt[11];
struct reconos_resource sort_res[2];
struct reconos_resource mmul_res[2];
struct reconos_configuration sort_cfg[11];
struct reconos_configuration mmul_cfg[11];
pthread_t ctrl_sort, ctrl_mmul;
pthread_t generate;
pthread_t monitor;
pthread_mutex_t sched_mutex;
int sort_data[16][2048];
int sort_request_count, sort_request_count_active;;
int sort_thread_count;
int sort_done_count;
int matrix_data[3 * 16][64][64];
int *matrix_ptr[3 * 16];
int matrix_done_count;
struct reconos_configuration *schedule(struct reconos_hwt *hwt) {
pthread_mutex_lock(&sched_mutex);
if (sort_request_count > 0) {
sort_request_count--;
if (!strcmp("mmul", hwt->cfg->name)) {
sort_thread_count++;
}
pthread_mutex_unlock(&sched_mutex);
return &sort_cfg[hwt->slot];
} else {
if (!strcmp("sort", hwt->cfg->name)) {
sort_thread_count--;
}
pthread_mutex_unlock(&sched_mutex);
return &mmul_cfg[hwt->slot];
}
}
void *ctrl_sort_thread(void *data) {
int i;
int m;
for (i = 0; i < 11; i++) {
printf("putting into sort mbox: %x\\n", (unsigned int)&sort_data[i][0]);
mbox_put(&mbox_sort_recv, (unsigned int)&sort_data[i][0]);
}
while (1) {
m = mbox_get(&mbox_sort_send);
sort_request_count_active--;
sort_done_count++;
m = (m - (int)&sort_data) / (4 * 2048);
mbox_put(&mbox_sort_recv, (unsigned int)&sort_data[m][0]);
}
}
void *ctrl_mmul_thread(void *data) {
int i;
int m;
for (i = 0; i < 11; i++) {
printf("putting into mmul mbox: %x\\n", (unsigned int)&matrix_ptr[3 * i]);
mbox_put(&mbox_mmul_recv, (unsigned int)&matrix_ptr[3 * i]);
}
while (1) {
m = mbox_get(&mbox_mmul_send);
matrix_done_count++;
m = (m - (int)&matrix_data[0][0][0]) / (4 * 64 * 64);
mbox_put(&mbox_mmul_recv, (unsigned int)&matrix_ptr[m % 2]);
}
}
void *generate_thread(void *data) {
int wait, count;
while (1) {
wait = rand() % 10000 + 60000;
count = rand() % 20 + 1;
usleep(wait);
pthread_mutex_lock(&sched_mutex);
sort_request_count += count;
sort_request_count_active += count;
pthread_mutex_unlock(&sched_mutex);
}
}
void *monitor_thread(void *data) {
unsigned int time = 0;
while (1) {
time++;
printf("%d %d %d %d %d %d\\n",
time,
sort_thread_count,
11 - sort_thread_count,
sort_done_count,
matrix_done_count,
sort_request_count_active);
usleep(10000);
}
}
void init_sort_data() {
int i, j;
int data;
sort_request_count = 0;
sort_request_count_active = 0;
sort_thread_count = 0;
sort_done_count = 0;
data = 0xFFFFFFFF;
for (i = 0; i < 16; i ++) {
for (j = 0; j < 2048; j++) {
sort_data[i][j] = data;
data--;
}
}
}
void init_mmul_data() {
int m, i, j;
matrix_done_count = 0;
for (m = 0; m < 3 * 16; m++) {
matrix_ptr[m] = (int *)&matrix_data[m][0][0];
for (i = 0; i < 64; i++) {
for (j = 0; j < 64; j++) {
matrix_data[m][i][j] = rand() % 128;
}
}
}
}
int main(int argc, char **argv) {
int i;
char filename[256];
mbox_init(&mbox_sort_recv, 16);
mbox_init(&mbox_sort_send, 16);
mbox_init(&mbox_mmul_recv, 16);
mbox_init(&mbox_mmul_send, 16);
pthread_mutex_init(&sched_mutex, 0);
init_sort_data();
init_mmul_data();
sort_res[0].type = RECONOS_RESOURCE_TYPE_MBOX;
sort_res[0].ptr = &mbox_sort_recv;
sort_res[1].type = RECONOS_RESOURCE_TYPE_MBOX;
sort_res[1].ptr = &mbox_sort_send;
mmul_res[0].type = RECONOS_RESOURCE_TYPE_MBOX;
mmul_res[0].ptr = &mbox_mmul_recv;
mmul_res[1].type = RECONOS_RESOURCE_TYPE_MBOX;
mmul_res[1].ptr = &mbox_mmul_send;
for (i = 0; i < 11; i++) {
reconos_configuration_init(&sort_cfg[i], "sort", i);
reconos_configuration_setresources(&sort_cfg[i], sort_res, 2);
snprintf(filename, sizeof(filename), "system_hwt_reconf_%d_hwt_sort_demo_partial.bin", i);
reconos_configuration_loadbitstream(&sort_cfg[i], filename);
reconos_configuration_init(&mmul_cfg[i], "mmul", i);
reconos_configuration_setresources(&mmul_cfg[i], mmul_res, 2);
snprintf(filename, sizeof(filename), "system_hwt_reconf_%d_hwt_matrixmul_partial.bin", i);
reconos_configuration_loadbitstream(&mmul_cfg[i], filename);
}
reconos_init();
reconos_set_scheduler(schedule);
pthread_create(&ctrl_sort, 0, ctrl_sort_thread, 0);
pthread_create(&ctrl_mmul, 0, ctrl_mmul_thread, 0);
pthread_create(&monitor, 0, monitor_thread, 0);
pthread_create(&generate, 0, generate_thread, 0);
for (i = 0; i < 11; i++) {
reconos_hwt_create_reconf(&hwt[i], i, &mmul_cfg[i], 0);
}
while(1) {
}
return 0;
}
| 0
|
#include <pthread.h>
struct game_state master_state;
pthread_mutex_t master_state_mutex = PTHREAD_MUTEX_INITIALIZER;
void game_state_initialize()
{
pthread_mutex_lock(&master_state_mutex);
int row, column;
for (row = 0; row < 6; ++row)
{
for (column = 0; column < 7; ++column)
{
master_state.board[row][column] = 0;
}
}
master_state.activePlayer = 1;
master_state.moveNumber = 0;
pthread_mutex_unlock(&master_state_mutex);
}
struct game_state get_current_game_state()
{
pthread_mutex_lock(&master_state_mutex);
struct game_state ret = master_state;
pthread_mutex_unlock(&master_state_mutex);
return ret;
}
int record_move(int player, int column, int moveNumber)
{
if (player != 1 && player != 2) return ERR_INVALID_PLAYER;
if (column < 1 || column > 7) return ERR_INVALID_COLUMN;
pthread_mutex_lock(&master_state_mutex);
int returnValue;
if (moveNumber != master_state.moveNumber)
{
returnValue = ERR_BAD_SEQUENCE;
goto CLEANUP;
}
if (moveNumber != 0 && player != master_state.activePlayer)
{
returnValue = ERR_NOT_YOUR_TURN;
goto CLEANUP;
}
int row;
for (row = 5; row >= 0; --row)
{
if (master_state.board[row][column - 1] == 0)
{
master_state.board[row][column - 1] = player;
break;
}
}
if (row < 0)
{
returnValue = ERR_COLUMN_FULL;
goto CLEANUP;
}
++(master_state.moveNumber);
returnValue = master_state.moveNumber;
if (player == 1)
{
master_state.activePlayer = 2;
}
else if (player == 2)
{
master_state.activePlayer = 1;
}
CLEANUP:
pthread_mutex_unlock(&master_state_mutex);
return returnValue;
}
int check_win_above(int row, int column)
{
if (row < 3) return 0;
int r;
for (r = row - 1; r > row - 4; --r)
{
if (master_state.board[r][column] != master_state.board[row][column]) return 0;
}
return master_state.board[row][column];
}
int check_win_right(int row, int column)
{
if (column > 3) return 0;
int c;
for (c = column + 1; c < column + 4; ++c)
{
if (master_state.board[row][c] != master_state.board[row][column]) return 0;
}
return master_state.board[row][column];
}
int check_win_diagonal_up_and_right(int row, int column)
{
if (row < 3 || column > 3) return 0;
int r, c;
for (r = row - 1, c = column + 1; r > row - 4; --r, ++c)
{
if (master_state.board[r][c] != master_state.board[row][column]) return 0;
}
return master_state.board[row][column];
}
int check_win_diagonal_up_and_left(int row, int column)
{
if (row < 3 || column < 3) return 0;
int r, c;
for (r = row - 1, c = column - 1; r > row - 4; --r, --c)
{
if (master_state.board[r][c] != master_state.board[row][column]) return 0;
}
return master_state.board[row][column];
}
int game_won()
{
int row, column, winner;
pthread_mutex_lock(&master_state_mutex);
for (column = 0; column <= 6; ++column)
{
for (row = 5; row >= 0; --row)
{
if (master_state.board[row][column] != 0)
{
winner = check_win_above(row, column);
if (winner != 0) goto CLEANUP;
winner = check_win_right(row, column);
if (winner != 0) goto CLEANUP;
winner = check_win_diagonal_up_and_right(row, column);
if (winner != 0) goto CLEANUP;
winner = check_win_diagonal_up_and_left(row, column);
if (winner != 0) goto CLEANUP;
}
else
{
break;
}
}
}
CLEANUP:
pthread_mutex_unlock(&master_state_mutex);
return winner;
}
| 1
|
#include <pthread.h>
double *a;
double *b;
double sum;
int veclen;
} DOTDATA;
DOTDATA dotstr;
pthread_t callThd[4];
pthread_mutex_t mutexsum;
void *dotprod(void *arg) {
int i, start, end, offset;
double mysum;
offset = (int) arg;
start = offset * dotstr.veclen;
end = start + dotstr.veclen;
mysum = 0;
for (i = start; i < end; i++) {
mysum += (dotstr.a[i] * dotstr.b[i]);
}
pthread_mutex_lock (&mutexsum);
dotstr.sum += mysum;
pthread_mutex_unlock (&mutexsum);
pthread_exit((void *)0);
}
int main (int argc, char *argv[]) {
int i;
int status;
dotstr.a = (double*) malloc (4*100*sizeof(double));
dotstr.b = (double*) malloc (4*100*sizeof(double));
for (i=0; i<100*4; i++) {
dotstr.a[i]=1;
dotstr.b[i]=1;
}
dotstr.veclen = 100;
dotstr.sum=0;
pthread_mutex_init(&mutexsum, 0);
for(i=0;i<4;i++) {
pthread_create(&callThd[i], 0, dotprod, (void *)i);
}
for(i=0;i<4;i++) {
pthread_join( callThd[i], (void **)&status);
}
printf ("Sum = %f \\n", dotstr.sum);
free (dotstr.a);
free (dotstr.b);
pthread_mutex_destroy(&mutexsum);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t condc, condp;
int buffer[100000000] = {-2};
int buffercount = 0;
int sum = 0;
int count = 0;
FILE *inputfile = 0;
void* consumer(void *ptr)
{
ptr = ptr;
int localbuffer = 0;
while(buffer[0] != -1)
{
pthread_cond_wait(&condc,&mutex);
while(localbuffer-1 != buffercount && buffer[localbuffer] != -2)
{
pthread_mutex_lock(&mutex);
if(buffer[localbuffer] != -2)
sum = sum + buffer[localbuffer];
buffer[localbuffer] = -2;
localbuffer++;
count++;
if(localbuffer -1 == 100000000)
localbuffer = 0;
pthread_mutex_unlock(&mutex);
}
pthread_cond_signal(&condp);
}
pthread_cond_signal(&condp);
pthread_exit(0);
}
int main (int argc,char * argv[])
{
int cpu_cores = 1;
pthread_t con[cpu_cores];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&condc, 0);
pthread_cond_init(&condp, 0);
for(int i =0;i<cpu_cores;i++)
{
pthread_create(&con[i], 0, consumer, 0);
}
pthread_mutex_lock(&mutex);
if(argc <= 1)
{
while(scanf("%d",&buffer[buffercount]) == 1)
{
buffercount++;
pthread_cond_broadcast(&condc);
if(buffercount == 100000000)
buffercount = 0;
}
}
else
{
FILE *inputfile = fopen(argv[1],"r");
while(fscanf(inputfile,"%d",&buffer[buffercount]) == 1)
{
buffercount++;
pthread_cond_broadcast(&condc);
if(buffercount == 100000000)
buffercount = 0;
}
}
pthread_cond_wait(&condp,&mutex);
buffer[0] = -1;
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&mutex);
fprintf(stdout,"The sum of %d numbers is %d\\n",--count,sum);
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
return 0;
}
| 1
|
#include <pthread.h>
float foo(float x) {
return x*x + 2*x + 3;
}
float sum;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *function(void *argv) {
float a = ((float*)argv)[0];
float b = ((float*)argv)[1];
float h = (b-a)*4/1000000;
float tmp = 0.0;
int i;
for(i = 0; i < 1000000/4; i++) tmp += foo(a + i*h);
pthread_mutex_lock(&mutex);
sum += tmp*h;
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int integrate_smp(float a, float b) {
int res;
float len = b-a;
float arg[4][2];
pthread_t thread[4];
int i;
for(i = 0; i < 4; ++i) {
arg[i][0] = a + (len*i)/4;
arg[i][1] = a + (len*(i+1))/4;
res = pthread_create(&thread[i], 0, function, (void*)arg[i]);
if (res != 0) {
printf("thread creation failed. Error: %d\\n", res);
exit(1);
}
}
for(i = 0; i < 4; ++i) {
res = pthread_join(thread[i], 0);
if (res != 0) printf("can’t join with thread\\n");
}
return 0;
}
int main(void) {
sum = 0;
integrate_smp(0, 100);
printf("%.3f\\n", sum);
return 0;
}
| 0
|
#include <pthread.h>
char* network = "192.168.250.";
pthread_mutex_t bloqueo;
int status=0;
int total=0;
int ping(char *ipaddr) {
char *command = 0;
char buffer[1024];
FILE *fp;
int stat = 0;
asprintf (&command, "%s %s -c 1", "ping", ipaddr);
printf("%s\\n", command);
fp = popen(command, "r");
if (fp == 0) {
fprintf(stderr, "Failed to execute fping command\\n");
free(command);
return -1;
}
while(fread(buffer, sizeof(char), 1024, fp)) {
if (strstr(buffer, "1 received"))
return 0;
}
stat = pclose(fp);
free(command);
return 1;
}
void *do_ping(void *tid)
{
char ip [25];
pthread_mutex_lock (&bloqueo);
total++;
sprintf(ip, "192.168.250.%d",total);
printf("%s\\n",ip );
status = ping(ip);
if (status == 0) {
printf("Could ping %s successfully, status %d\\n", ip, status);
} else {
printf("Machine not reachable, status %d\\n", status);
}
pthread_mutex_unlock(&bloqueo);
}
int main(int argc, char *argv[]){
int i, tids[40];
pthread_t threads[40];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_mutex_init(&bloqueo, 0);
printf("TODO BIEn\\n");
for (i=0; i<40; i++) {
tids[i] = i;
pthread_create(&threads[i], &attr, do_ping,(void *) &tids[i]);
}
for (i=0; i<40; i++) {
pthread_join(threads[i], 0);
}
pthread_attr_destroy (&attr);
pthread_mutex_destroy (&bloqueo);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
buffer_item *buffer;
int rear=0;
int front=0;
pthread_mutex_t mutex;
sem_t empty;
sem_t full;
pthread_mutex_t m1,m2;
int cnt, ack;
int error_semWait;
int error_mutexLock;
int error_mutexUnlock;
int error_semPost;
int insert_item(buffer_item *item){
error_semWait=sem_wait(&empty);
error_mutexLock=pthread_mutex_lock(&mutex);
if(error_semWait!=0 || error_mutexLock!=0)
return -1;
buffer[rear]=*item;
rear=(rear+1)%10;
printf("insert : %d\\n", rear);
cnt++;
error_mutexUnlock=pthread_mutex_unlock(&mutex);
error_semPost=sem_post(&full);
if(error_mutexUnlock!=0 || error_semPost!=0)
return -1;
return 0;
}
int remove_item(buffer_item *item){
error_semWait=sem_wait(&full);
error_mutexLock=pthread_mutex_lock(&mutex);
if(error_semWait!=0 || error_mutexLock!=0)
return -1;
*item=buffer[front];
buffer[front]=-1;
front=(front+1)%10;
printf("remove : %d\\n", front);
cnt--;
error_mutexUnlock=pthread_mutex_unlock(&mutex);
error_semPost=sem_post(&empty);
if(error_mutexUnlock!=0 || error_semPost!=0)
return -1;
return 0;
}
void *monitoring()
{
while(1){
pthread_mutex_lock(&m2);
printf("Ack num : %d, size of buffer : %d\\n", ack, cnt);
ack++;
pthread_mutex_unlock(&m1);
}
}
void *producer(void *param)
{
buffer_item item;
while(1){
pthread_mutex_lock(&m1);
int r=rand()%3;
sleep(r);
item=rand();
insert_item(&item);
pthread_mutex_unlock(&m2);
}
}
void *consumer(void *param)
{
buffer_item item;
while(1){
pthread_mutex_lock(&m1);
int r=rand()%3;
sleep(r);
remove_item(&item);
pthread_mutex_unlock(&m2);
}
}
int main(int argc,char *argv[]){
int iSleep=atoi(argv[1]);
int iNpro=atoi(argv[2]);
int iNcons=atoi(argv[3]);
buffer=(buffer_item*)malloc(sizeof(buffer_item)*10);
int i=0;
for(i=0;i<10;i++)
buffer[i]=-1;
sem_init(&empty,0,10);
sem_init(&full,0,0);
pthread_mutex_init(&m1,0);
pthread_mutex_init(&m2,0);
pthread_mutex_init(&mutex,0);
pthread_t idP,idC,idM;
for(i=0;i<iNpro;i++)
{
pthread_create(&idP,0,producer,0);
}
for(i=0;i<iNcons;i++)
{
pthread_create(&idC,0,consumer,0);
}
pthread_mutex_lock(&m2);
pthread_create(&idM, 0,monitoring,0);
sleep(iSleep);
return 0;
}
| 0
|
#include <pthread.h>
extern pthread_mutex_t __sfp_mutex;
extern pthread_cond_t __sfp_cond;
extern int __sfp_state;
FILE *fdopen(int fd, const char *mode)
{
register FILE *fp;
int flags, oflags, fdflags, tmp;
if ((flags = __sflags(mode, &oflags)) == 0)
return (0);
if ((fdflags = fcntl(fd, F_GETFL, 0)) < 0)
return (0);
tmp = fdflags & O_ACCMODE;
if (tmp != O_RDWR && (tmp != (oflags & O_ACCMODE))) {
errno = EINVAL;
return (0);
}
pthread_once(&__sdidinit, __sinit);
pthread_mutex_lock(&__sfp_mutex);
while (__sfp_state) {
pthread_cond_wait(&__sfp_cond, &__sfp_mutex);
}
if (fp = __sfp()) {
fp->_flags = flags;
if ((oflags & O_APPEND) && !(fdflags & O_APPEND))
fp->_flags |= __SAPP;
fp->_file = fd;
}
pthread_mutex_unlock(&__sfp_mutex);
return (fp);
}
| 1
|
#include <pthread.h>
semaphore mutex=1;
semaphore empty=100;
semaphore full=0;
void producer(void){
int item;
while(true){
item=produce_item;
down(&empty);
down(&mutex);
insert_item(item);
up(&mutex);
up(&full);
}
}
void consumer(void){
int item;
while(true){
down(&full);
down(&mutex);
remove_item(item);
up(&mutex);
up(&empty);
consume_item(item);
}
}
pthread_mutex_t the_mutex;
pthread_cond_t condc,condp;
int buffer=0;
void * producer(void *ptr){
for(int i=1;i<1000000000;i++){
pthread_mutex_lock(&the_mutex);
while(buffer!=0)
pthread_cond_wait(&condp,&the_mutex);
buffer=i;
pthread_cond_signal(&condc);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
void * consumer(void *ptr){
for(int i=1;i<1000000000;i++){
pthread_mutex_lock(&the_mutex);
while(buffer==0)
pthread_cond_wait(&condc,&the_mutex);
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);
}
| 0
|
#include <pthread.h>
pthread_mutex_t thread_mutex;
int id = 0 ;
void send(){
int dev_id = -1;
pthread_mutex_lock(&thread_mutex);
dev_id = id;
++id;
pthread_mutex_unlock(&thread_mutex);
struct timespec starttime;
struct timespec endtime;
char *data_buffer = fifty_char_msg;
int dataLength= strlen(data_buffer);
if(dev_id == 0){
printf("Data in the buffer %s with length %d\\n",data_buffer,dataLength);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID,&starttime);
Hyb_Send(dev_id,data_buffer,dataLength);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID,&endtime);
printf("Time taken in nano secs %lu for message length %d\\n",(endtime.tv_nsec-starttime.tv_nsec),dataLength);
}else{
Hyb_Send(dev_id,data_buffer,dataLength);
}
}
int main(){
pthread_t threads[NO_OF_THREADS];
int i ;
void *status;
pthread_mutex_init(&thread_mutex,0);
for(i =0 ; i < NO_OF_THREADS; ++i){
pthread_create(&threads[i],0,(void*)send,0);
}
for(i =0 ; i < NO_OF_THREADS; ++i){
pthread_join(threads[i],&status);
}
pthread_mutex_destroy(&thread_mutex);
return 0;
}
| 1
|
#include <pthread.h>
const int image_width = 512;
const int image_height = 512;
const int image_size = 512*512;
const int color_depth = 255;
int n_threads;
unsigned char* image;
unsigned char* output_image;
int* histogram;
float *transfer_function;
int counter = 0;
pthread_mutex_t barrier_mutex;
pthread_cond_t cond_var;
pthread_mutex_t histogram_mutex;
void barrier() {
pthread_mutex_lock(&barrier_mutex);
counter++;
if (counter == n_threads){
counter = 0;
pthread_cond_broadcast(&cond_var);
} else {
while (pthread_cond_wait(&cond_var, &barrier_mutex)!=0);
}
pthread_mutex_unlock(&barrier_mutex);
}
void *thread_loops(void *arg) {
int rank = (long)arg;
printf("Thread %d\\n", rank);
int *local_histogram = (int *)calloc(sizeof(int), color_depth);
for (int i = rank; i < image_size; i+= n_threads) {
local_histogram[image[i]]++;
}
pthread_mutex_lock(&histogram_mutex);
for (int i = 0; i < color_depth; i++) {
histogram[i] += local_histogram[i];
}
pthread_mutex_unlock(&histogram_mutex);
barrier();
for (int i = rank; i < color_depth; i += n_threads) {
for (int j = 0; j < i+1; j++) {
transfer_function[i] += color_depth*((float)histogram[j])/(image_size);
}
}
barrier();
for (int i = rank; i < image_size; i += n_threads) {
output_image[i] = transfer_function[image[i]];
}
printf("Finished thread %d\\n", rank);
return 0;
}
int main(int argc, char** argv){
if (argc != 3) {
printf("Useage: %s image n_threads\\n", argv[0]);
exit(-1);
}
n_threads = atoi(argv[2]);
image = read_bmp(argv[1]);
output_image = malloc(sizeof(unsigned char) * image_size);
histogram = (int *)calloc(sizeof(int), color_depth);
transfer_function = (float *)calloc(sizeof(float), color_depth);
pthread_t threads[n_threads-1];
for (long i = 0; i < n_threads - 1; i++) {
pthread_create(&threads[i], 0, thread_loops, (void*)i+1);
}
thread_loops(0);
for (int i = 0; i < n_threads - 1; i++) {
pthread_join(threads[i], 0);
}
write_bmp(output_image, image_width, image_height);
printf("finished\\n");
}
| 0
|
#include <pthread.h>
pthread_mutex_t x;
pthread_mutex_t wsem;
FILE *fp;
int readcount=0;
char str[20];
char txt;
void *writer(void *thread)
{
int t=*(int *)thread;
pthread_mutex_lock(&wsem);
printf("\\nEnter the name of file to open\\n");
scanf("%s",str);
fp=fopen(str,"a");
printf("Enter the character to be inserted in file(to exit entering,press 'q'):\\n");
do
{
scanf("%c",&txt);
if(txt!='q')
{
fputc(txt,fp);
}
}while(txt!='q');
fclose(fp);
sleep(1);
pthread_mutex_unlock(&wsem);
}
void *reader(void *thread)
{
int t=*(int *)thread;
pthread_mutex_lock(&x);
readcount++;
if(readcount==1)
pthread_mutex_lock(&wsem);
pthread_mutex_unlock(&x);
printf("Enter the file name to open\\n");
scanf("%s",str);
fp=fopen(str,"r");
while(!feof(fp))
{
txt=fgetc(fp);
printf("%c",txt);
}
fclose(fp);
sleep(1);
pthread_mutex_lock(&x);
readcount--;
if(readcount==0)
pthread_mutex_unlock(&wsem);
pthread_mutex_unlock(&x);
}
int main()
{
pthread_t tid[10];
int i,tnum[10];
pthread_mutex_init(&x,0);
pthread_mutex_init(&wsem,0);
for(i=0;i<10;i++)
{
tnum[i]=i;
pthread_create(&tid[i],0,writer,&tnum[i]);
i++;
tnum[i]=i;
pthread_create(&tid[i],0,reader,&tnum[i]);
}
for(i=0;i<10;i++)
{
pthread_join(tid[i],0);
}
pthread_mutex_destroy(&x);
pthread_mutex_destroy(&wsem);
return 0;
}
| 1
|
#include <pthread.h>
{
char ip[100];
int port;
char name[64];
int age ;
int numId;
}ThreadInfo;
int g_num = 0;
int nNum, nLoop;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *thread_routine(void* arg)
{
int i = 0;
ThreadInfo *tmp = (ThreadInfo *)arg;
pthread_mutex_lock(&mutex);
printf("g_num:%d \\n", g_num);
sleep(1);
printf("numid:%d \\n", tmp->numId);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main()
{
int i = 0;
nNum= 10;
nLoop = 10;
ThreadInfo tmpArray[200];
pthread_t tidArray[200];
g_num = 11;
printf("\\n请输入线程数:");
scanf("%d", &nNum);
printf("\\n请输入线程圈数:");
scanf("%d", &nLoop);
for (i=0; i<nNum; i++)
{
tmpArray[i].numId = i+1;
pthread_create(&tidArray[i], 0, thread_routine, (void *)&(tmpArray[i]));
}
for (i=0; i<nNum; i++)
{
pthread_join(tidArray[i], 0);
}
printf("进程也要结束1233\\n");
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int barrier_call = 0;
void barrier(void)
{
pthread_mutex_lock(&mutex);
barrier_call++;
while(barrier_call < 16){
pthread_cond_wait(&cond, &mutex);
}
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
void* thread_routine(void* arg)
{
unsigned long id = (unsigned long)arg;
printf("thread %lu at the barrier\\n", id);
barrier();
printf("\\t thread %lu after the barrier\\n", id);
return 0;
}
int main(void)
{
pthread_t tids[16];
unsigned long i=0;
for(i=0; i<16; i++){
if(pthread_create (&tids[i], 0, thread_routine, (void*)i) != 0){
fprintf(stderr,"Failed to create thread %lu\\n", i);
return 1;
}
}
for (i = 0; i < 16; i++){
pthread_join (tids[i], 0) ;
}
return 0;
}
| 1
|
#include <pthread.h>
buffer_item START_NUMBER;
buffer_item buffer[8];
pthread_mutex_t mutex;
sem_t empty;
sem_t full;
int insertPointer = 0, removePointer = 0;
int insert_item(buffer_item item);
int remove_item(buffer_item *item);
void *producer(void *param);
void *consumer(void *param);
int insert_item(buffer_item item)
{
buffer[insertPointer] = item;
insertPointer = (insertPointer + 1) % 8;
return 0;
}
int remove_item(buffer_item *item)
{
*item = buffer[removePointer];
removePointer = (removePointer + 1) % 8;
return 0;
}
void *producer(void *param)
{
buffer_item item;
while(1) {
sleep(2);
sem_wait(&full);
pthread_mutex_lock(&mutex);
item = START_NUMBER++;
insert_item(item);
printf("Producer %u produced %d \\n", (unsigned int)pthread_self(), item);
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
void *consumer(void *param)
{
buffer_item item;
while(1){
sleep(2);
sem_wait(&empty);
pthread_mutex_lock(&mutex);
remove_item(&item);
printf("Consumer %u consumed %d \\n", (unsigned int)pthread_self(), item);
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
int main(int argc, char *argv[])
{
int sleepTime, producerThreads, consumerThreads;
int i, j;
if(argc != 5)
{
fprintf(stderr, "Useage: <sleep time> <producer threads> <consumer threads> <start number>\\n");
return -1;
}
sleepTime = atoi(argv[1]);
producerThreads = atoi(argv[2]);
consumerThreads = atoi(argv[3]);
START_NUMBER = atoi(argv[4]);
pthread_mutex_init(&mutex, 0);
sem_init(&full, 0, 8);
sem_init(&empty, 0, 0);
pthread_t pid, cid;
for(i = 0; i < producerThreads; i++){
pthread_create(&pid,0,&producer,0);
}
for(j = 0; j < consumerThreads; j++){
pthread_create(&cid,0,&consumer,0);
}
sleep(sleepTime);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t m[1];
pthread_cond_t c[1];
volatile long x, y;
void produce(long n_producers, long n_consumers, long buffer_size) {
(void)n_producers;
(void)n_consumers;
pthread_mutex_lock(m);
while (!(y - x < buffer_size)) {
pthread_cond_wait(c, m);
}
y++;
pthread_cond_broadcast(c);
pthread_mutex_unlock(m);
}
void consume(long batch_id, long n_consumers) {
(void)batch_id;
(void)n_consumers;
pthread_mutex_lock(m);
while (y == x) {
pthread_cond_wait(c, m);
}
x++;
pthread_cond_broadcast(c);
pthread_mutex_unlock(m);
}
long n;
long n_consumers;
long n_producers;
long buffer_size;
} arg_t;
void * producer(void * arg_) {
arg_t * arg = (arg_t *)arg_;
long n = arg->n;
long n_consumers = arg->n_consumers;
long buffer_size = arg->buffer_size;
long i;
for (i = 0; i < n; i++) {
produce(i, n_consumers, buffer_size);
}
return 0;
}
void * consumer(void * arg_) {
arg_t * arg = (arg_t *)arg_;
long n = arg->n;
long n_consumers = arg->n_consumers;
long i;
for (i = 0; i < n; i++) {
consume(i, n_consumers);
}
return 0;
}
int main(int argc, char ** argv) {
long n = (argc > 1 ? atoi(argv[1]) : 1000);
long n_producers = (argc > 2 ? atoi(argv[2]) : 100);
long n_consumers = (argc > 3 ? atoi(argv[3]) : 100);
long buffer_size = (argc > 4 ? atoi(argv[4]) : 10);
pthread_mutex_init(m, 0);
pthread_cond_init(c, 0);
x = y = 0;
arg_t arg[1] = { { n, n_producers, n_consumers, buffer_size } };
pthread_t prod_tids[n_producers];
pthread_t cons_tids[n_consumers];
long i;
for (i = 0; i < n_consumers; i++) {
pthread_create(&cons_tids[i], 0, consumer, arg);
}
for (i = 0; i < n_producers; i++) {
pthread_create(&prod_tids[i], 0, producer, arg);
}
for (i = 0; i < n_consumers; i++) {
pthread_join(cons_tids[i], 0);
}
for (i = 0; i < n_producers; i++) {
pthread_join(prod_tids[i], 0);
}
if (n * n_producers == x && y == x) {
printf("OK: n * n_producers == x == y == %ld\\n", x);
return 0;
} else {
printf("NG: n * n_producers == %ld, x == %ld, y == %ld\\n",
n * n_producers, x, y);
return 1;
}
}
| 1
|
#include <pthread.h>
char dictionary[] = "abcdefghijklmnoprstv";
pthread_mutex_t mutex;
struct thread_config {
char color[8];
char position[11];
int print_times;
};
void _log(char *);
void thread1_3(void *args){
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0);
char buff[255];
struct thread_config *config = args;
for (int i = 0; i < 20; i++){
if(i == 13){
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
pthread_testcancel();
}
pthread_mutex_lock(&mutex);
sprintf(buff, config->position, i + 1);
printf("%s", buff);
printf("%s", config->color);
for (int j = 0; j < config->print_times; j++){
printf("%c", dictionary[i]);
}
printf("\\n");
pthread_mutex_unlock(&mutex);
usleep(1000000);
}
}
void thread2(void *arg){
for (int i = 0; i < 20; i++){
pthread_mutex_lock(&mutex);
printf("\\033[%d;15H", i + 1);
for (int j = 0; j < (int) arg * 2; j++){
get_warning_alert("%c", dictionary[i]);
}
printf("\\n");
pthread_mutex_unlock(&mutex);
usleep(1000000);
}
}
void main(){
pthread_t tid1, tid2, tid3;
int rc;
struct thread_config config1;
struct thread_config config3;
strcpy(config1.color, "\\x1B[32m");
strcpy(config1.position, "\\033[%d;5H");
config1.print_times = 4;
strcpy(config3.color, "\\x1B[31m");
strcpy(config3.position, "\\033[%d;30H");
config3.print_times = 8;
pthread_mutex_init(&mutex, 0);
rc = pthread_create(&tid1, 0, (void*)thread1_3, (void *) &config1);
rc = pthread_create(&tid2, 0, (void*)thread2, (void *) 3);
rc = pthread_create(&tid3, 0, (void*)thread1_3, (void *) &config3);
printf("\\033[2J\\n");
for (int i = 0; i < 20; i++){
if(i == 6){
_log("Trying to cancel the first thread on step 6");
int a = pthread_cancel(tid1);
}
if(i == 11){
_log("Trying to cancel the third thread on step 11");
pthread_cancel(tid3);
}
pthread_mutex_lock(&mutex);
printf("\\033[%d;1H", i + 1);
printf("\\x1B[0m");
printf("%c\\n", dictionary[i]);
pthread_mutex_unlock(&mutex);
usleep(1000000);
}
getchar();
}
void _log(char *message)
{
pthread_mutex_lock(&mutex);
printf("\\033[0;50H");
printf("\\x1B[0m");
printf("%s", message);
pthread_mutex_unlock(&mutex);
}
| 0
|
#include <pthread.h>
struct Table {
sem_t agent_sem;
sem_t pusher_sems[3];
sem_t smoker_sems[3];
bool ingredients[3];
pthread_mutex_t table_lock;
};
struct TableIngredient {
struct Table *table;
ingredient_t ing;
};
int rand_range(int min, int max)
{
return rand() % (max - min + 1) + min;
}
ingredient_t rand_ingredient()
{
return rand_range(0, 2);
}
void *agent_thread_routine(void *table_ptr)
{
struct Table *table = (struct Table *)table_ptr;
ingredient_t ing1, ing2;
while (1) {
sem_wait(&table->agent_sem);
ing1 = rand_ingredient();
do {
ing2 = rand_ingredient();
} while (ing1 == ing2);
sem_post(&table->pusher_sems[ing1]);
sem_post(&table->pusher_sems[ing2]);
sleep(1);
}
return 0;
}
void *pusher_thread_routine(void *pusher_ptr)
{
struct TableIngredient *ti = (struct TableIngredient *)pusher_ptr;
ingredient_t ing1, ing2;
char *ing_name;
if (ti->ing == 0) {
ing1 = 1;
ing2 = 2;
ing_name = "TOBACCO";
} else if (ti->ing == 1) {
ing1 = 0;
ing2 = 2;
ing_name = "PAPER";
} else if (ti->ing == 2) {
ing1 = 1;
ing2 = 0;
ing_name = "a MATCH";
}
while (1) {
sem_wait(&ti->table->pusher_sems[ti->ing]);
pthread_mutex_lock(&ti->table->table_lock);
printf("Agent is adding %s to the table\\n", ing_name);
if (ti->table->ingredients[ing1]) {
ti->table->ingredients[ing1] = 0;
sem_post(&ti->table->smoker_sems[ing2]);
} else if (ti->table->ingredients[ing2]) {
ti->table->ingredients[ing2] = 0;
sem_post(&ti->table->smoker_sems[ing1]);
} else {
ti->table->ingredients[ti->ing] = 1;
}
pthread_mutex_unlock(&ti->table->table_lock);
sleep(1);
}
return 0;
}
void *smoker_thread_routine(void *smoker_ptr)
{
struct TableIngredient *ti = (struct TableIngredient *)smoker_ptr;
while (1) {
sem_wait(&ti->table->smoker_sems[ti->ing]);
printf("Smoker %d is making a cigarette\\n", ti->ing);
sleep(1);
sem_post(&ti->table->agent_sem);
printf("Smoker %d is smoking their cigarette\\n", ti->ing);
sleep(1);
}
return 0;
}
struct Table *new_table()
{
struct Table *table = malloc(sizeof(struct Table));
int i;
sem_init(&table->agent_sem, 0, 1);
for(i = 0; i < 3; i++) {
sem_init(&table->pusher_sems[i], 0, 0);
sem_init(&table->smoker_sems[i], 0, 0);
}
pthread_mutex_init(&table->table_lock, 0);
return table;
}
struct TableIngredient *new_ingredient(struct Table *table, ingredient_t ing)
{
struct TableIngredient *ti = malloc(sizeof(struct TableIngredient));
ti->table = table;
ti->ing = ing;
return ti;
}
int main()
{
pthread_t threads[7];
int j;
struct Table *table = new_table();
struct TableIngredient *tobacco = new_ingredient(table, 0);
struct TableIngredient *paper = new_ingredient(table, 1);
struct TableIngredient *match = new_ingredient(table, 2);
pthread_create(&threads[0], 0, agent_thread_routine, table);
pthread_create(&threads[1], 0, pusher_thread_routine, tobacco);
pthread_create(&threads[2], 0, pusher_thread_routine, paper);
pthread_create(&threads[3], 0, pusher_thread_routine, match);
pthread_create(&threads[4], 0, smoker_thread_routine, tobacco);
pthread_create(&threads[5], 0, smoker_thread_routine, paper);
pthread_create(&threads[6], 0, smoker_thread_routine, match);
for (j = 0; j < 7; j++) {
pthread_join(threads[j], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t _internal_lock;
void _bb_init_internal(){
if(pthread_mutex_init(&_internal_lock, 0) != 0){
puts("Failed to initialize mutex.");
exit(1);
}
}
struct bb_QueueItem* curQueue = 0;
void _bb_run_queue(){
pthread_mutex_lock(&_internal_lock);
long int cT = _bb_curtime();
if((cT - irc_last_msg) > BB_MSG_DEBUF){
if(curQueue){
struct bb_QueueItem* oldItem = curQueue;
curQueue = oldItem->next;
blox_sendDirectly(oldItem->line);
free(oldItem->line);
free(oldItem);
irc_last_msg = cT;
}
}
pthread_mutex_unlock(&_internal_lock);
}
void _bb_push_queue(char* line){
if(!line){
return;
}
pthread_mutex_lock(&_internal_lock);
struct bb_QueueItem* qi = malloc(sizeof(struct bb_QueueItem));
if(!qi){
puts("Out of memory");
exit(1);
}
bzero(qi, sizeof(struct bb_QueueItem));
qi->next = 0;
qi->line = strdup(line);
if(!curQueue){
curQueue = qi;
pthread_mutex_unlock(&_internal_lock);
return;
}
struct bb_QueueItem* qii = curQueue;
while(qii->next != 0){
qii = qii->next;
}
if(qii){
qii->next = qi;
}
pthread_mutex_unlock(&_internal_lock);
}
long int _bb_curtime(){
struct timeval tv;
gettimeofday(&tv, 0);
return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
{
pthread_t thread;
int idNum;
int delay;
} threadData;
void * threadLogic(void * arg)
{
threadData d = *(threadData *)arg;
for (;;)
{
pthread_mutex_lock(&mut);
printf ("in %d critical section (delay is %d)....\\n", d.idNum, d.delay);
pthread_mutex_unlock(&mut);
sleep (d.delay);
}
return 0;
}
int getNumThreads (int argc, char ** argv)
{
if (argc <= 1) return 10;
int r = atoi (argv[1]);
return (r < 1) ? 10 : r;
}
int main(int argc, char ** argv)
{
const int TCOUNT = getNumThreads (argc, argv);
threadData threads[TCOUNT];
int x;
for (x = 0; x < TCOUNT; x++)
{
threads[x].idNum = x;
threads[x].delay = x + 2;
pthread_create(&(threads[x].thread), 0, threadLogic, &(threads[x]));
}
for (x = 0; x < TCOUNT; x++)
pthread_join(threads[x].thread, 0);
return 0;
}
| 1
|
#include <pthread.h>
FILE *fp1,*fp2;
int file_size;
char buf[100];
volatile char read_size=0;
volatile char buf_ready =0;
volatile char end_file =0;
pthread_mutex_t pthread_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t pthread_cond = PTHREAD_COND_INITIALIZER;
int buf_compare(char *buf1, char *buf2, int size){
int i;
for(i=0;i<size;i++){
if(buf1[i] != buf2[i]){
printf("Failed \\n");
return 1;
}
}
return 0;
}
int compare(FILE *file1, FILE *file2, int file_size)
{
printf(">>compare\\n");
int readp=0,rest = 0, nread1 =0, nread2 =0;
char buf1[1024];
char buf2[1024];
while(1){
if(nread1 = fread(buf1,1024,1,file1) !=1){
printf("fead file1 failed\\n");
break;
}
if(nread2 = fread(buf2,1024,1,file2) !=1){
printf("fead file2 failed\\n");
break;
}
readp += 1024;
if( buf_compare(buf1, buf2, 1024) == 1){
printf("FAILED\\n");
return 1;
}
if((file_size - readp) < 1024){
break;
}
}
if(feof(file1))
printf("end of file1 \\n");
if(feof(file2))
printf("end of file2 \\n");
rest = (file_size - readp);
if (rest > 1024){
printf("FAILED on file size: rest = %d \\n", rest);
return 1;
}
if(nread1 = fread(buf1,rest,1,file1) != 1)
printf("file1 failed \\n");
if(nread2 = fread(buf2,rest,1,file2) !=1)
printf("file2 failed \\n");
if(buf_compare(buf1, buf2, rest) == 1){
printf("FAILED\\n");
return 1;
}else{
printf("PASS\\n");
}
printf("<<compare\\n");
return 0;
}
void * thread_write(void *arg)
{
int rp = 0,rest,i;
int nWrite =0 ;
printf(">>write_thread\\n");
pthread_mutex_lock(&pthread_mutex);
while(1){
while(( buf_ready == 0)){
pthread_cond_wait(&pthread_cond, &pthread_mutex);
}
if(buf_ready == 1){
fwrite(buf,read_size,1,fp2);
nWrite += read_size;
buf_ready = 0;
}
if(end_file == 1 ) {
break;
}
}
pthread_mutex_unlock(&pthread_mutex);
printf("write_thread: total write = %d\\n",nWrite);
return 0;
}
int main(int argc, char * argv[])
{
int i,n,rest,nread=0,rp=0,status;
pthread_t a_thread;
pthread_t b_thread;
struct stat file_stat;
if((fp1 = fopen(argv[1],"r+")) == 0)
perror("fopen error");
if((fp2 = fopen(argv[2],"w+")) == 0)
perror("fopen error");
if(stat(argv[1],&file_stat) != 0)
perror("stat error");
printf("file_size = %d\\n",file_stat.st_size);
file_size = file_stat.st_size;
pthread_create(&a_thread,0,thread_write,0);
end_file = 0;
while(1){
pthread_mutex_lock(&pthread_mutex);
if(buf_ready ==0){
while((read_size = rand()%100) == 0);
if((nread = fread(buf,read_size,1,fp1)) != 1){
buf_ready = 1;
break;
}
buf_ready = 1;
rp += read_size;
}
pthread_cond_signal(&pthread_cond);
if (status = pthread_mutex_unlock(&pthread_mutex) != 0)
printf("error unlock \\n");
}
printf("main_thread: near end of file1, total read size now is %d\\n", rp);
read_size = file_size -rp;
printf("main_thread: rest read = %d\\n", read_size);
end_file = 1;
pthread_cond_signal(&pthread_cond);
pthread_mutex_unlock(&pthread_mutex);
pthread_join(a_thread,0);
rewind(fp1);
rewind(fp2);
if(compare(fp1, fp2, file_size)){
printf("FAILED\\n");
return 1;
}else{
printf("PASS\\n");
return 0;
}
}
| 0
|
#include <pthread.h>
int shm_int;
int array[100];
int portion[4];
void* thread_sum();
pthread_mutex_t portion_lock;
pthread_mutex_t sum_lock;
main (int argc, char** argv) {
int input_value;
int index;
if(argc != 2) {
fprintf(stderr, "Error: Incorrect number of arguments.\\n");
exit(-2);
}
if((input_value = atoi(argv[1])) == 0 && *(argv[1]) != '0') {
fprintf(stderr, "Error: Incorrect parameter, please enter an integer.\\n");
exit(-2);
}
for(index = 0; index < 100; index++) {
array[index] = input_value + index;
}
for(index = 0; index < 4; index++) {
portion[index] = index;
}
if(pthread_mutex_init(&portion_lock, 0) == -1)
fprintf(stderr, "Error: Failed to create portion mutex lock.\\n");
if(pthread_mutex_init(&sum_lock, 0) == -1)
fprintf(stderr, "Error: Failed to create portion mutex lock.\\n");
pthread_t threads[4];
for(index = 0; index < 4; index++) {
if(pthread_create(&threads[index], 0, thread_sum, 0) != 0)
fprintf(stderr, "Error: Failed to create thread %d", index);
}
for(index = 0; index <4; index++) {
if(pthread_join(threads[index], 0) != 0) {
fprintf(stderr, "Error: Failed to join thread %d", index);
}
}
printf("The sum from %d to %d is %d.\\n", input_value, input_value+99, shm_int);
exit(0);
}
void* thread_sum() {
int low_range = get_portion() *25;
int high_range = low_range + 25;
int sum = 0;
int index;
for(index = low_range; index < high_range; index++) {
sum += array[index];
}
pthread_mutex_lock(&sum_lock);
shm_int += sum;
pthread_mutex_unlock(&sum_lock);
}
int get_portion() {
int index = 0;
int return_portion;
pthread_mutex_lock(&portion_lock);
while(portion[index] == -1) {
index++;
}
return_portion = index;
portion[index] = -1;
pthread_mutex_unlock(&portion_lock);
return return_portion;
}
| 1
|
#include <pthread.h>
void * serverthread(void * parm);
pthread_mutex_t mut;
int visits = 0;
main (int argc, char *argv[])
{
struct hostent *ptrh;
struct protoent *ptrp;
struct sockaddr_in sad;
struct sockaddr_in cad;
int sd, sd2;
int port;
int alen;
pthread_t tid;
pthread_mutex_init(&mut, 0);
memset((char *)&sad,0,sizeof(sad));
sad.sin_family = AF_INET;
sad.sin_addr.s_addr = INADDR_ANY;
if (argc > 1) {
port = atoi (argv[1]);
} else {
port = 5193;
}
if (port > 0)
sad.sin_port = htons((u_short)port);
else {
fprintf (stderr, "bad port number %s/n",argv[1]);
exit (1);
}
if ( ((int)(ptrp = getprotobyname("tcp"))) == 0) {
fprintf(stderr, "cannot map \\"tcp\\" to protocol number");
exit (1);
}
sd = socket (PF_INET, SOCK_STREAM, ptrp->p_proto);
if (sd < 0) {
fprintf(stderr, "socket creation failed\\n");
exit(1);
}
if (bind(sd, (struct sockaddr *)&sad, sizeof (sad)) < 0) {
fprintf(stderr,"bind failed\\n");
exit(1);
}
if (listen(sd, 6) < 0) {
fprintf(stderr,"listen failed\\n");
exit(1);
}
alen = sizeof(cad);
fprintf( stderr, "Server up and running.\\n");
while (1) {
printf("SERVER: Waiting for contact ...\\n");
if ( (sd2=accept(sd, (struct sockaddr *)&cad, &alen)) < 0) {
fprintf(stderr, "accept failed\\n");
exit (1);
}
pthread_create(&tid, 0, serverthread, (void *) sd2 );
}
close(sd);
}
void * serverthread(void * parm)
{
int tsd, tvisits;
char buf[100];
tsd = (int) parm;
pthread_mutex_lock(&mut);
tvisits = ++visits;
pthread_mutex_unlock(&mut);
sprintf(buf,"This server has been contacted %d time%s\\n",
tvisits, tvisits==1?".":"s.");
printf("SERVER thread: %s", buf);
send(tsd,buf,strlen(buf),0);
close(tsd);
pthread_exit(0);
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.