text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
static pthread_key_t key;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;
extern char ** environ;
static void thread_init (void );
char * getenv (const char * name);
static void thread_init (void )
{
pthread_key_create (&key, free);
}
char *getenv (const char * name)
{
int len;
char * envbuf;
pthread_once (&init_done, thread_init);
pthread_mutex_lock (&env_mutex);
envbuf = (char *) pthread_getspecific (key);
if (envbuf == 0)
{
envbuf = (char *) malloc (4096);
if (envbuf == 0)
{
pthread_mutex_unlock (&env_mutex);
return 0;
}
pthread_setspecific (key, envbuf);
}
len = strlen (name);
for (int i = 0; environ[i] != 0; i++)
{
if ((strncmp (environ[i], name, len) == 0) && (environ[i][len] == '='))
{
strncpy (envbuf, &environ[i][len + 1], 4096 - 1);
pthread_mutex_unlock (&env_mutex);
return envbuf;
}
}
pthread_mutex_unlock (&env_mutex);
return 0;
}
| 1
|
#include <pthread.h>
{
uint64_t num;
int nb_factors;
uint64_t factors[50];
} decomp;
static int nb_decomp = 0;
static decomp *known_decomp[2000000];
static pthread_mutex_t decomp_mutex = PTHREAD_MUTEX_INITIALIZER;
int is_known(uint64_t n )
{
printf("hu\\n");
if(nb_decomp)
{
printf("wow");
int i=nb_decomp/2;
int sortir =0;
int avant;
while(!sortir)
{
avant=i;
if(known_decomp[i]->num == n)
{
return i;
}
else if(n<known_decomp[i]->num)
{
i-=(i/2);
}
else
{
i+=i/2;
}
if(!(avant-i))
sortir=1;
}
}
return -1;
}
void addDecompTriee(decomp *d)
{
int i=1;
for (i; i<=nb_decomp;i++)
{
if(d->num<known_decomp[i-1]->num)
{
int j=nb_decomp;
for(j;j>i;j--)
{
known_decomp[j]=known_decomp[j-1];
}
known_decomp[i]=d;
nb_decomp++;
break;
}
}
}
unsigned short int is_prime(uint64_t p)
{
uint64_t i;
if(p<=1)
return 0;
for(i=2;i*i<=p;i++)
{
if(!(p % i))
return 0;
}
return 1;
}
int get_prime_factors(uint64_t n, uint64_t *dest)
{
uint8_t i = 0;
uint8_t pas = 1;
uint64_t div = 2;
decomp *d = (decomp*)malloc(sizeof(decomp));
d->num = n;
while(div*div<=n)
{
if(n%div)
{
div += pas;
if(div > 2)
{
pas = 2;
}
}
else
{
n = n/div;
dest[i] = div;
d->factors[i] = div;
i++;
if(n==1)
break;
}
}
d->nb_factors = i;
pthread_mutex_lock(&decomp_mutex);
addDecompTriee(d);
nb_decomp++;
pthread_mutex_unlock(&decomp_mutex);
return i;
}
void print_prime_factors(uint64_t n)
{
uint64_t *factors;
int j,k;
int n_known = 0;
pthread_mutex_lock(&decomp_mutex);
if((k = is_known(n)) >= 0)
{
n_known = 1;
factors = known_decomp[k]->factors;
k = known_decomp[k]->nb_factors;
pthread_mutex_unlock(&decomp_mutex);
}
else
{
pthread_mutex_unlock(&decomp_mutex);
factors = (uint64_t *)malloc(50*sizeof(uint64_t));
k = get_prime_factors(n,factors);
}
printf("%llu: ",n);
for(j=0;j<k;j++)
{
printf("%llu ",factors[j]);
}
if(!n_known)
free(factors);
}
void *printer_thread(void *n)
{
print_prime_factors(*((uint64_t*)n));
printf("\\n");
}
{
FILE *file;
pthread_mutex_t *mutex;
} threadFile;
void *reader_thread(void *threadfile)
{
uint64_t num;
threadFile *tf = (threadFile*)threadfile;
pthread_mutex_lock(tf->mutex);
while(fscanf(tf->file,"%llu\\n",&num) != EOF)
{
pthread_mutex_unlock(tf->mutex);
print_prime_factors(num);
printf("\\n");
pthread_mutex_lock(tf->mutex);
}
pthread_mutex_unlock(tf->mutex);
}
int main(int argc, const char **argv)
{
FILE *numbers = fopen("numbers","r");
if(numbers == 0)
{
printf("Fichier numbers introuvable\\n");
exit(1);
}
uint8_t is_parallel = 1;
if(argc > 1 && !strcmp(argv[1],"-s"))
{
is_parallel = 0;
printf("Runs in sequential mode\\n");
}
else
{
printf("Runs in multithreaded mode\\n");
}
uint64_t num1;
uint64_t num2;
pthread_t thread1;
pthread_t thread2;
pthread_t thread3;
pthread_t thread4;
if(is_parallel)
{
pthread_mutex_t fileMutex = PTHREAD_MUTEX_INITIALIZER;
threadFile tf;
tf.file = numbers;
tf.mutex = &fileMutex;
pthread_create(&thread1,0,reader_thread,&tf);
pthread_create(&thread2,0,reader_thread,&tf);
pthread_create(&thread3,0,reader_thread,&tf);
pthread_create(&thread4,0,reader_thread,&tf);
pthread_join(thread4,0);
pthread_join(thread3,0);
pthread_join(thread2,0);
pthread_join(thread1,0);
}
else
{
while(fscanf(numbers,"%llu\\n",&num1) != EOF)
{
print_prime_factors(num1);
printf("\\n");
}
}
fclose(numbers);
int i;
for(i=0;i<nb_decomp;i++)
{
free(known_decomp[i]);
}
return 0;
}
| 0
|
#include <pthread.h>
sem_t customers;
sem_t chair;
sem_t sit;
sem_t end;
void mutex_semaphore_main() {
pthread_t barber_t;
int iret;
iret = pthread_create(&barber_t, 0, barber_semmutex, 0);
if( iret ) {
fprintf( stderr, "Error - pthread_create(barber_t) return code: %d\\n", iret );
exit(1);
}
sem_init(&customers, 0, 0);
sem_init(&chair, 0, 0);
sem_init(&end, 0, 0);
sem_init(&sit, 0, 0);
srand(time(0));
while( 1 ) {
pthread_t customer_t;
int *number = malloc(sizeof(int));
*number = client_counter;
iret = pthread_create(&customer_t, 0, customer_semmutex, (void *) number);
if( iret ) {
fprintf( stderr, "Error - pthread_create(customer_t, i:%d) return code: %d\\n", client_counter, iret );
exit(1);
}
++client_counter;
usleep(1000 * random_as_possible(4)* 250);
}
}
void *barber_semmutex(void *ptr) {
while(1) {
sem_post(&chair);
sem_wait(&customers);
sem_wait(&sit);
logger();
int time_to_sleep = 1000*random_as_possible(4)*400;
usleep(time_to_sleep);
sem_post(&end);
current_in = -1;
if( current_waiting == 0)
logger();
}
}
void *customer_semmutex(void *ptr) {
int number = *((int *) ptr);
free( ptr );
pthread_mutex_lock(&waiting_room);
if(current_waiting >= chairs) {
add_resigned(number);
logger();
pthread_mutex_unlock(&waiting_room);
pthread_exit(0);
}
++current_waiting;
Enqueue(number);
logger();
pthread_mutex_unlock(&waiting_room);
sem_post(&customers);
while(1) {
sem_wait(&chair);
if(FrontQueue() == number)
break;
sem_post(&chair);
}
pthread_mutex_lock(&waiting_room);
current_in = (unsigned int) number;
--current_waiting;
Dequeue();
pthread_mutex_unlock(&waiting_room);
sem_post(&sit);
sem_wait(&end);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
const int DATA_COUNT = 10;
int shared[DATA_COUNT] = {0};
pthread_mutex_t lock[DATA_COUNT];
void *work(void *arg) {
for (int i = 0; i < 100; i++) {
for (int j = 0; j < DATA_COUNT; j++) {
pthread_mutex_lock(&lock[j]);
++shared[j];
usleep(1000);
pthread_mutex_unlock(&lock[j]);
}
}
return arg;
}
int main() {
int ret;
const int THREAD_COUNT = 10;
pthread_t thread[THREAD_COUNT];
for (int i = 0; i < DATA_COUNT; i++) {
ret = pthread_mutex_init(&lock[i], 0);
if (ret) {
fprintf(stderr, "pthred_mutex_init, error: %d\\n", ret);
return ret;
}
}
for (int i = 0; i < THREAD_COUNT; i++) {
ret = pthread_create(&thread[i], 0, work, 0);
if (ret) {
fprintf(stderr, "pthread_create, error: %d\\n", ret);
return ret;
}
}
for (int i = 0; i < THREAD_COUNT; i++) {
ret = pthread_join(thread[i], 0);
if (ret) {
fprintf(stderr, "pthread_join, error: %d\\n", ret);
return ret;
}
}
for (int i = 0; i < DATA_COUNT; i++) {
ret = pthread_mutex_destroy(&lock[i]);
if (ret) {
fprintf(stderr, "pthread_mutex_destroy, error: %d\\n", ret);
return ret;
}
}
printf("data: ");
for (int i = 0; i < DATA_COUNT; i++) {
printf("%d, ", shared[i]);
}
printf("\\n");
return 0;
}
| 0
|
#include <pthread.h>
int NR_THREADS = 10;
pthread_mutex_t count_mutex;
double circleCount=0;
int NR_PTS = 1000000;
void * threadFunction(){
double x =0, y=0, threadPi =0, inCircle =0;
int counter =0;
pthread_t thrID = pthread_self();
unsigned seed = getpid() * time(0) * (thrID + 1);
while(counter<(NR_PTS/NR_THREADS)){
x =(rand_r(&seed)/(32767 +2.0));
y =(rand_r(&seed)/(32767 +2.0));
if((pow(x,2.0))+(pow(y,2.0)) <=1){
inCircle++;
pthread_mutex_lock(&count_mutex);
circleCount++;
pthread_mutex_unlock(&count_mutex);
}
counter++;
}
threadPi = 4 *inCircle/(NR_PTS/NR_THREADS);
printf("Thread estimate for PI is : %f\\n",threadPi);
}
int main(){
int i =0;
double piEst=0;
int err;
pthread_t tid[NR_THREADS];
if (pthread_mutex_init(&count_mutex, 0) != 0)
{
printf("\\n mutex init failed\\n");
return 1;
}
while(i<NR_THREADS){
err = pthread_create(&(tid[i]),0,&threadFunction,0);
if(err !=0){
printf("\\ncan't create thread : %d\\n",err);
}
i++;
}
i =0;
while(i<NR_THREADS){
pthread_join(tid[i], 0);
i++;
}
pthread_mutex_destroy(&count_mutex);
piEst = 4 *circleCount / (NR_PTS);
printf("The estimate for PI after combining all threads is: %f\\n", piEst);
printf("%d points were used in this estimation\\n",NR_PTS);
return 0;
}
| 1
|
#include <pthread.h>
char** buffer;
pthread_mutex_t myMutex;
int input_pointer;
int output_pointer;
int initFIFO() {
printf("init fifo...\\n");
buffer = malloc(sizeof (char*)*200);
for (int i = 0; i < 200; i++) {
buffer[i] = malloc(sizeof (char)*30);
}
if (pthread_mutex_init(&myMutex, 0)) {
if (DEBUG) printf("init mutex\\n");
printf("init mutex failed\\n");
return -1;
}
return 0;
}
void freeFIFO() {
free(buffer);
}
void fifo_write(char* input) {
pthread_mutex_lock(&myMutex);
printf("FIFO: safing %s", input);
strncpy(buffer[input_pointer++], input, strlen(input));
if (input_pointer >= FIFO_SIZE - 1) {
input_pointer = 0;
}
printf("FIFO: INPUTPOINTER %d\\n", input_pointer);
pthread_mutex_unlock(&myMutex);
}
char* fifo_read(void) {
pthread_mutex_lock(&myMutex);
char* buf = malloc(sizeof (char)*50);
buf = buffer[output_pointer];
if(buf[0] == '\\n'){
pthread_mutex_unlock(&myMutex);
return buf;
}else{
output_pointer++;
}
if (output_pointer >= FIFO_SIZE - 1) {
output_pointer = 0;
}
printf("FIFO: OUTPUTPOINTER: %d\\n", output_pointer);
if (output_pointer == input_pointer) {
printf("FIFO: ZURÜCKGESETZT\\n");
output_pointer = 0;
input_pointer = 0;
}
pthread_mutex_unlock(&myMutex);
return buf;
}
| 0
|
#include <pthread.h>
int count = 0;
pthread_mutex_t mutex;
void * ThreadAdd (void * a) {
int i, tmp;
for (i = 0; i < 1000000; i++) {
pthread_mutex_lock (&mutex);
tmp = count;
tmp = tmp+1;
count = tmp;
pthread_mutex_unlock (&mutex);
}
return 0;
}
int main(int argc, char * argv[]) {
pthread_t tid1, tid2;
pthread_mutex_init (&mutex, 0);
if (pthread_create(&tid1, 0, ThreadAdd, 0)) {
printf("\\n ERROR creating thread 1");
exit(1);
}
if (pthread_create(&tid2, 0, ThreadAdd, 0)) {
printf("\\n ERROR creating thread 2");
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 (count < 2 * 1000000)
printf("\\n BOOM! count is [%d], should be %d\\n", count, 2*1000000);
else
printf("\\n OK! count is [%d]\\n", count);
pthread_mutex_destroy (&mutex);
pthread_exit(0);
return(0);
}
| 1
|
#include <pthread.h>
void *start_producer(void *);
int *shared_buffer;
int buffer_size, producer_index, consumer_index, number_of_items;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t prod_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t cons_cond = PTHREAD_COND_INITIALIZER;
int main (int argc, char* argv[]){
pthread_t prod_thread;
int result, item;
int loop_num;
if(argc != 2){
return -1;
}
loop_num = 500000;
buffer_size = atoi(argv[1]);
shared_buffer = malloc(sizeof(int) * buffer_size);
result = pthread_create(&prod_thread, 0, start_producer, 0);
if (result != 0){
printf("Error: Cannot create producer thread. Exiting...\\n");
return result;
}
producer_index = consumer_index = number_of_items = 0;
while(loop_num){
pthread_mutex_lock(&mutex);
if(number_of_items == 0){
pthread_cond_wait(&cons_cond, &mutex);
}
item = shared_buffer[consumer_index];
consumer_index = (consumer_index+1) % buffer_size;
number_of_items--;
printf("- - - - Consumer consumed: %d\\n", item);
if(number_of_items == buffer_size-1){
pthread_cond_signal(&prod_cond);
}
pthread_mutex_unlock(&mutex);
}
return 0;
}
void *start_producer(void *args){
int seq_ints;
seq_ints=-1;
while(1){
pthread_mutex_lock(&mutex);
if(number_of_items == buffer_size){
pthread_cond_wait(&prod_cond, &mutex);
}
seq_ints++;
printf("Producer produced: %d\\n", seq_ints);
shared_buffer[producer_index] = seq_ints;
producer_index = (producer_index+1) % buffer_size;
number_of_items++;
if(number_of_items == 1){
pthread_cond_signal(&cons_cond);
}
pthread_mutex_unlock(&mutex);
}
}
| 0
|
#include <pthread.h>
static struct cannon cn;
static struct cannon cn2;
void setupCannon(int players) {
int col;
if (players == 1) {
col = ((0 + COLS-1)/2);
} else {
col = ((0 + COLS-1)/4);
strncpy(cn2.message, CANNON, CANNON_LEN);
cn2.length = CANNON_LEN;
cn2.col = col;
cn2.hit = 0;
cn2.delay = 1;
col *= 3;
}
strncpy(cn.message, CANNON, CANNON_LEN);
cn.length = CANNON_LEN;
cn.col = col;
cn.hit = 0;
cn.delay = 1;
}
int getCannonCol(int player) {
if (player == 1) {
return cn.col;
} else {
return cn2.col;
}
}
int getCannonHit(int player) {
if (player == 1) {
return cn.hit;
} else {
return cn2.hit;
}
}
void setCannonHit(int player) {
if (player == 1) {
cn.hit = 1;
} else {
cn2.hit = 1;
}
}
void moveCannon(int dir, int player) {
if (player == 1) {
cn.col += dir;
if (cn.col >= COLS || cn.col <= 0)
cn.col -= dir;
} else {
cn2.col += dir;
if (cn2.col >= COLS || cn2.col <= 0)
cn2.col -= dir;
}
displayCannon(player);
}
void displayCannon(int player) {
usleep(cn.delay*20000);
pthread_mutex_lock(&mx);
if (player == 1) {
move(LINES-2, cn.col-1);
addch(' ');
addstr(cn.message);
addch(' ');
} else {
move(LINES-2, cn2.col-1);
addch(' ');
addstr(cn2.message);
addch(' ');
}
move(LINES-1, COLS-1);
refresh();
pthread_mutex_unlock(&mx);
}
| 1
|
#include <pthread.h>
void * other(void * unused){
while(1)
kitsune_update("testkick");
}
void * testwait(void * unused){
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
while(1)
{
kitsune_update("testwait");
pthread_mutex_lock( &mutex );
printf("\\n\\n*********1: thread waiting forever....*********************\\n\\n");
fflush(stdout);
ktthreads_pthread_cond_wait( &cond, &mutex );
pthread_mutex_unlock( &mutex );
}
return 0;
}
int main(void){
pthread_t t;
pthread_t k;
int init = 0;
int limitprint = 0;
while(1){
kitsune_update("main");
if(!init){
kitsune_pthread_create(&t, 0, &testwait, 0);
kitsune_pthread_create(&k, 0, &other, 0);
init = 1;
}
limitprint++;
ktthreads_ms_sleep(100);
if(limitprint%500 == 0){
printf("1: main loop ");
fflush(stdout);
}
}
return 0;
}
| 0
|
#include <pthread.h>
int task = 10;
pthread_mutex_t task_mutex;
pthread_cond_t task_cond;
void *say_hello2( void *args )
{
pthread_t pid = pthread_self();
printf("pthread %d run sayhello2 with %d \\n", pid, *( ( int *) args ) );
while(1)
{
pthread_mutex_lock( &task_mutex );
if( task > 5 )
printf("before pthread %d with %d subtract one task is %d\\n", pid, *( ( int *) args ), task-- );
else
{
printf("no __ pthread %d pthread_cond_signal other thread %d\\n", pid, *( ( int *) args ));
pthread_cond_signal( &task_cond );
}
pthread_mutex_unlock( &task_mutex );
if( task == 0 )
break;
}
return 0;
}
void *say_hello1( void *args )
{
pthread_t pid = pthread_self();
printf("pthread %d run sayhello1 with %d \\n", pid, *( ( int *) args ) );
int is_send_signal = 0;
while(1)
{
pthread_mutex_lock( &task_mutex );
if( task > 5 )
{
printf("pthread %d with %d pthread_cond_wait when task is %d \\n", pid, *( ( int *) args ), task );
pthread_cond_wait( &task_cond, &task_mutex );
}
else
printf("before pthread %d with %d subtract one task is %d\\n", pid, *( ( int *) args ), task-- );
pthread_mutex_unlock( &task_mutex );
if( task == 0 )
break;
}
return 0;
}
int main(int argc, char const *argv[]) {
int state;
pthread_t pthread1, pthread2;
pthread_attr_t attr;
pthread_attr_init( &attr );
pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
pthread_mutex_init( &task_mutex, 0 );
pthread_cond_init( &task_cond, 0 );
int index1 = 1;
if(( state = pthread_create( &pthread1, &attr, say_hello1, (void *)&index1 ) ) != 0 )
printf("pthread_create error !\\n");
int index2 = 1;
if(( state = pthread_create( &pthread2, &attr, say_hello2, (void *)&index2 ) ) != 0 )
printf("pthread_create error !\\n");
pthread_join( pthread1, 0 );
pthread_join( pthread2, 0 );
pthread_mutex_destroy( &task_mutex );
pthread_cond_destroy( &task_cond );
pthread_attr_destroy( &attr );
return 0;
}
| 1
|
#include <pthread.h>
struct node
{
pthread_mutex_t mutex;
int data;
struct node *next;
};
struct node *_head;
int Member(int _value)
{
int is_in = 0;
pthread_mutex_lock(&(_head->mutex));
struct node *cursor = _head;
while(cursor != 0 && (*cursor).data < _value)
{
pthread_mutex_lock(&(cursor->next->mutex));
pthread_mutex_unlock(&(cursor->mutex));
cursor = cursor->next;
}
if (cursor != 0 && cursor->data == _value)
{
is_in = 1;
}
pthread_mutex_unlock(&(cursor->mutex));
return is_in;
}
void printList(void)
{
struct node *cursor = _head;
while (cursor != 0)
{
printf("%d\\n", cursor->data);
cursor = cursor->next;
}
}
void* Inserter(void* rank);
void listInsert(int _data)
{
pthread_mutex_lock(&(_head->mutex));
struct node *cursor = _head;
struct node *prev = 0;
while(1)
{
if (cursor->next != 0)
{
pthread_mutex_lock(&(cursor->next->mutex));
if (cursor->next->data < _data)
{
prev = cursor;
cursor = cursor->next;
pthread_mutex_unlock(&(prev->mutex));
}
else
{
pthread_mutex_unlock(&(cursor->next->mutex));
break;
}
}
else
{
break;
}
}
struct node* inserted = malloc(sizeof(struct node));
pthread_mutex_init(&(inserted->mutex), 0);
inserted->data = _data;
inserted->next = cursor->next;
cursor->next = inserted;
pthread_mutex_unlock(&(cursor->mutex));
return;
}
int main(void)
{
_head = malloc(sizeof(struct node));
pthread_mutex_init(&(_head->mutex), 0);
_head->data = 0;
_head->next = 0;
long threads = 4;
pthread_t thread_handles[4];
for (long thread = 0; thread < threads; thread++)
{
pthread_create(&thread_handles[thread], 0, Inserter, (void*) thread);
}
for (long thread = 0; thread < threads; thread++)
{
pthread_join(thread_handles[thread], 0);
}
printList();
return 0;
}
void* Inserter(void* rank)
{
long my_rank = (long) rank;
int idx = my_rank + 1;
for(;idx < 101; idx = idx+4)
{
listInsert(idx);
}
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t mtio_lock = PTHREAD_MUTEX_INITIALIZER;
void ubik_mtprintf(char *fmt, ...)
{
va_list ap;
__builtin_va_start((ap));
pthread_mutex_lock(&mtio_lock);
vprintf(fmt, ap);
pthread_mutex_unlock(&mtio_lock);
}
| 1
|
#include <pthread.h>
int n_threads=1;
int myid=0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void do_something()
{
int id,i,j;
pthread_mutex_lock(&mutex);
id=myid;
myid++;
printf("This is ult %d\\n", id);
if(n_threads<6){
n_threads++;
pthread_mutex_unlock(&mutex);
uthread_create(do_something);
} else {
pthread_mutex_unlock(&mutex);
}
if(id%2==0)
for(j=0;j<100;j++)
for(i=0;i<1000000;i++) sqrt(i*119.89);
printf("This is ult %d again\\n", id);
uthread_yield();
printf("This is ult %d once more\\n", id);
if(id%2==0)
for(j=0;j<100;j++)
for(i=0;i<1000000;i++) sqrt(i*119.89);
printf("This is ult %d exit\\n", id);
uthread_exit();
}
int main(int argc, char* argv[])
{
int i;
system_init(1);
setbuf(stdout,0);
int pid = uthread_create(do_something);
uthread_exit();
puts("Ending test program.\\n");
}
| 0
|
#include <pthread.h>
static const char* input_paths[] =
{
"out/1",
"out/2",
"out/3",
"out/4",
"out/5"
};
static const char* output_path = "out/out";
size_t bufsize = 0;
char buffer[20971520];
void asio_read (pthread_mutex_t*);
void* asio_write (void*);
void asio_read( pthread_mutex_t* mutex )
{
int fd, ret;
struct aiocb aio_info = {0};
aio_info.aio_buf = &buffer;
aio_info.aio_nbytes = 20971520;
for (int i = 0; i < 5; ++i)
{
fd = open(input_paths[i], O_RDONLY);
if (fd < 0)
{
fprintf(stderr, "Opening file %s error", input_paths[i]);
exit(1);
}
pthread_mutex_lock(mutex);
aio_info.aio_fildes = fd;
ret = aio_read( &aio_info );
if (ret < 0)
{
perror("aio_read");
close(fd);
exit(1);
}
printf("File %s is reading.", input_paths[i]);
while (aio_error( &aio_info ) == EINPROGRESS)
{
putchar('.');
fflush(stdout);
usleep(100000);
}
if ( (ret = aio_return(&aio_info)) < 0)
{
perror("aio_read");
close(fd);
exit(1);
}
puts("Success");
bufsize = ret;
pthread_mutex_unlock(mutex);
close(fd);
usleep(500000);
}
}
void* asio_write (void* mutex)
{
int fd, ret;
struct aiocb aio_info = {0};
aio_info.aio_buf = buffer;
fd = open(output_path, O_CREAT | O_WRONLY);
if (fd < 0)
{
fputs("Opening output file error", stderr);
exit(1);
}
aio_info.aio_fildes = fd;
while (bufsize == 0)
;
usleep(500000);
for (int i = 0; i < 5; ++i)
{
pthread_mutex_lock( (pthread_mutex_t*) mutex );
aio_info.aio_nbytes = bufsize;
ret = aio_write(&aio_info);
if (ret < 0)
{
perror("aio_write");
close(fd);
exit(1);
}
printf("Writing to file %s.", output_path);
while (aio_error( &aio_info ) == EINPROGRESS)
{
putchar('.');
fflush(stdout);
usleep(100000);
}
if ( (ret = aio_return( &aio_info )) < 0)
{
perror("aio_write");
close(fd);
exit(1);
}
puts("Success");
pthread_mutex_unlock(mutex);
aio_info.aio_offset += ret;
usleep(500000);
}
close(fd);
return 0;
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
unsigned int __VERIFIER_nondet_uint();
static int top=0;
static unsigned int arr[(400)];
pthread_mutex_t m;
_Bool flag=(0);
void error(void)
{
ERROR:
__VERIFIER_error(); return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
(top==0) ? (1) : (0);
}
int push(unsigned int *stack, int x)
{
if (top==(400))
{
printf("stack overflow\\n");
return (-1);
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (top==0)
{
printf("stack underflow\\n");
return (-2);
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for(
i=0; i<(400); i++)
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint()%(400);
if ((push(arr,tmp)==(-1)))
error();
pthread_mutex_unlock(&m);
}
}
void *t2(void *arg)
{
int i;
for(
i=0; i<(400); i++)
{
pthread_mutex_lock(&m);
if (top>0)
{
if ((pop(arr)==(-2)))
error();
}
pthread_mutex_unlock(&m);
}
}
int main(void)
{
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 0
|
#include <pthread.h>
static double POS_Steer_Scale_Left;
static double POS_Steer_Scale_Right;
static double POS_Steer_Current_Setting;
static double POS_Steer_Current_Abstract_Setting;
static pthread_mutex_t POS_Steer_Write_Lock = PTHREAD_MUTEX_INITIALIZER;
void Init_POS_Steer(void)
{
pthread_mutex_unlock(&POS_Steer_Write_Lock);
POS_Steer_Scale_Right = (MOTOR_STEER_SERVO_CENTER-MOTOR_STEER_SERVO_MAX_RIGHT)/100.0;
POS_Steer_Scale_Left = (MOTOR_STEER_SERVO_CENTER-MOTOR_STEER_SERVO_MAX_LEFT)/100.0;
POS_Steer_Current_Setting = MOTOR_STEER_SERVO_CENTER;
POS_Steer_Current_Abstract_Setting = 0;
}
int Get_Steer_Angle(void)
{
return abs(POS_Steer_Current_Setting * 1);
}
void Set_Steer_Angle(int rawdata)
{
while(pthread_mutex_lock(&POS_Steer_Write_Lock) != 0)
{
usleep(1087+(rawdata%10));
}
POS_Steer_Current_Abstract_Setting = (STEER_ANGLE_INVERTED*rawdata);
if(rawdata < -100){
rawdata = -100;
}
if(rawdata > 100){
rawdata = 100;
}
if(rawdata == 0)
{
POS_Steer_Current_Setting = MOTOR_STEER_SERVO_CENTER;
}else{
if(rawdata > 0)
{
}else{
POS_Steer_Current_Abstract_Setting *=(-1.0);
}
}
pthread_mutex_unlock(&POS_Steer_Write_Lock);
}
| 1
|
#include <pthread.h>
pthread_mutex_t g_mutex;
pthread_cond_t g_cond;
{
char buf[5];
int count;
} buffer_t;
buffer_t g_share = {"", 0};
char g_ch = 'A';
void* producer( void *arg )
{
printf("Producer starting.\\n");
while(g_ch != 'Z')
{
pthread_mutex_lock(&g_mutex);
if(g_share.count < 5)
{
g_share.buf[g_share.count++] = g_ch++;
printf("Prodcuer got char[%c]\\n", g_ch - 1);
if( 5 == g_share.count )
{
printf("Producer signaling full.\\n");
pthread_cond_signal(&g_cond);
}
}
pthread_mutex_unlock(&g_mutex);
}
printf("Producer exit.\\n");
return 0;
}
void* consumer( void *arg )
{
int i;
printf("Consumer starting.\\n");
while(g_ch != 'Z')
{
pthread_mutex_lock(&g_mutex);
printf("Consumer waiting\\n");
pthread_cond_wait(&g_cond, &g_mutex);
printf("Consumer writing buffer\\n");
for(i = 0; g_share.buf[i] && g_share.count; ++i)
{
putchar(g_share.buf[i]);
--g_share.count;
}
putchar('\\n');
pthread_mutex_unlock(&g_mutex);
}
printf("Consumer exit.\\n");
return 0;
}
int main(int argc, char *argv[])
{
pthread_t ppth, cpth;
pthread_mutex_init(&g_mutex, 0);
pthread_cond_init(&g_cond, 0);
pthread_create(&cpth, 0, consumer, 0);
pthread_create(&ppth, 0, producer, 0);
pthread_join(ppth, 0);
pthread_join(cpth, 0);
pthread_mutex_destroy(&g_mutex);
pthread_cond_destroy(&g_cond);
return 0;
}
| 0
|
#include <pthread.h>
struct thread_barrier *barrier(int max){
if (max < 2)
max = 2;
struct thread_barrier *barrier = ALLOC(*barrier, 1);
barrier->max = max;
barrier->arrived = 0;
pthread_mutex_init(&barrier->mutex);
barrier->blockers = ALLOC(*barrier->blockers, max - 1);
return barrier;
}
void enter(struct thread_barrier *barrier){
if (!barrier)
return;
int i;
pthread_mutex_lock(&barrier->mutex);
barrier->arrived++;
if (barrier->arrived < barrier->max){
pthread_mutex_t *lock = ALLOC(*lock, 1);
pthread_mutex_init(lock);
pthread_mutex_lock(lock);
barrier->blockers[barrier->arrived - 1] = lock;
pthread_mutex_unlock(&barrier->mutex);
pthread_mutex_lock(lock);
pthread_mutex_unlock(lock);
pthread_mutex_destroy(lock);
} else {
barrier->arrived = 0;
for (i = 0; i < barrier->max - 1; i++){
pthread_mutex_unlock(barrier->blockers[i]);
barrier->blockers[i] = 0;
}
pthread_mutex_unlock(&barrier->mutex);
}
}
void destroy_barrier(void *p){
if (!p)
return;
struct thread_barrier *barrier = p;
free(barrier->blockers);
free(barrier);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond_portal;
pthread_cond_t cond_readers;
char news_buf[1024];
bool read[5];
} news_t;
int thread_num;
news_t *shared_news;
} thread_info;
void* portal(void *arg) {
news_t *shared_news = (news_t*)arg;
int i, sock;
bool allread;
struct sockaddr_in server;
char message[1024] , server_reply[1024];
printf("Portal Thread Started.\\n");
sock = socket(AF_INET , SOCK_STREAM , 0);
if (sock == -1)
{
printf("Could not create socket");
exit(1);
}
printf("Socket created\\n");
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons( 8080 );
if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
{
printf("connect failed. Error\\n");
exit(1);
}
printf("Connected to News Producer\\n");
while(1) {
pthread_mutex_lock(&shared_news->mutex);
allread = 1;
for (i=0; i<5; i++) {
if (shared_news->read[i] == 0) {
allread = 0;
break;
}
}
if(allread == 0) {
pthread_cond_wait(&shared_news->cond_portal, &shared_news->mutex);
}
memset(message, '\\0', 1024);
sprintf(message, "send");
if( send(sock , message , strlen(message) , 0) < 0)
{
printf("Send failed. Error\\n");
exit(1);
}
memset(server_reply, '\\0', 1024);
if( recv(sock , server_reply , 1024 , 0) <= 0)
{
printf("recv failed. Error.\\n");
exit(1);
}
printf("\\nPortal received a new news - %s\\n",server_reply);
strcpy(shared_news->news_buf, server_reply);
for (i=0; i<5; i++) {
shared_news->read[i] = 0;
}
pthread_cond_broadcast(&shared_news->cond_readers);
pthread_mutex_unlock(&shared_news->mutex);
}
return 0;
}
void* reader(void *arg) {
thread_info *this_thread = (thread_info*)arg;
news_t *shared_news = this_thread->shared_news;
int thread_num = this_thread->thread_num;
int i;
bool allread = 1;
char news[1024];
printf("Reader %d Thread Started.\\n", thread_num);
while(1) {
pthread_mutex_lock(&shared_news->mutex);
if(shared_news->read[thread_num] == 1) {
pthread_cond_wait(&shared_news->cond_readers, &shared_news->mutex);
}
strcpy(news, shared_news->news_buf);
shared_news->read[thread_num] = 1;
printf("Thread %d: Consumed news - %s\\n", thread_num, news);
allread = 1;
for (i=0; i<5; i++) {
if (shared_news->read[i] == 0) {
allread = 0;
break;
}
}
sleep(((float)rand()/(float)(32767)) * 2);
if (allread == 1) {
memset(shared_news->news_buf, '\\0', 1024);
pthread_cond_signal(&shared_news->cond_portal);
}
pthread_mutex_unlock(&shared_news->mutex);
}
return 0;
}
int main(int argc, char *argv[]) {
int i;
news_t shared_news = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER};
thread_info reader_threads[5];
pthread_t threads[5 +1];
for (i=0; i<5; i++) {
shared_news.read[i] = 1;
}
printf("About to create portal thread\\n");
pthread_create(&threads[0], 0, portal, (void*)&shared_news);
printf("About to create reader threads\\n");
for (i=0; i<5; i++) {
reader_threads[i].thread_num = i;
reader_threads[i].shared_news = &shared_news;
pthread_create(&threads[i+1], 0, reader, (void*)&(reader_threads[i]));
}
for (i=0; i<=5; i++) {
pthread_join(threads[i], 0);
}
return 0;
}
| 0
|
#include <pthread.h>
struct keyValue_struct* endpointConfiguration=0;
char* initialize(struct keyValue_struct** endpointConfig);
void* handler(void* args);
char* getUrl(char* key);
pthread_t tid[1];
pthread_mutex_t lock;
int main(){
int err;
initialize(&endpointConfiguration);
while (FCGI_Accept() >= 0) {
printf("Content-type: text/html\\n\\n");
int i=atoi(getenv("CONTENT_LENGTH"));
char *requestBody;
requestBody=malloc(i+2);
int lenOfRead=fread(requestBody,i,1,stdin);
if(lenOfRead==0){
printf("{error:\\"true\\",message:\\"%s-Request body has been corrupted\\"}\\n",getenv("REQUEST_METHOD"));
return 0;
}
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("{error:\\"true\\",message:\\"Internal server error-a thread initialization error\\"}\\n");
return 0;
}
err = pthread_create(&(tid[0]), 0, &handler,(void*)requestBody);
if (err != 0){
printf("{error:\\"true\\",message:\\"Internal server error- thread creation error due to not enough storage\\"}\\n");
}
pthread_join(tid[0], 0);
pthread_mutex_destroy(&lock);
}
return 0;
}
char* getUrl(char* key) {
struct keyValue_struct *s;
for(s=endpointConfiguration; s != 0; s=(struct keyValue_struct*)(s->hh.next)) {
if(strcmp(key,s->key)==0){
return s->value;
}
}
return 0;
}
char* initialize(struct keyValue_struct** endpointConfig){
FILE *fp;
char initInfo[2000];
fp = fopen("./endpointConfig.txt", "r");
if (fp != 0)
{
size_t newLen = fread(initInfo, sizeof(char), 2000, fp);
if (newLen == 0) {
printf("{error:\\"true\\",message:\\"Internal server error-cannot read configuration file\\"}\\n");
} else {
initInfo[newLen-1] = '\\0';
}
fclose(fp);
}
else
{
printf("{error:\\"true\\",message:\\"Internal server error-configuration file does not exist\\"}\\n");
return 0;
}
char* res=str_replace(initInfo,"\\"","");
add_toList(&endpointConfiguration,res,',','=');
if(endpointConfiguration==0)
{
return 0;
}
return "Ok";
}
void* handler(void* args){
pthread_mutex_lock(&lock);
char* requestBody=(char*)args;
struct keyValue_struct *reqData = 0;
add_toList(&reqData,requestBody,'&','=');
struct keyValue_struct *action=getValue("action",&reqData);
char* actionMethod=action->value;
if(strcmp(actionMethod,"addUser")==0)
{
signUp(requestBody,getUrl("signUp"),200);
}
else if(strcmp(actionMethod,"login")==0)
{
action=getValue("tag",&reqData);
actionMethod=action->value;
if(strcmp(actionMethod,"api")!=0)
{
login(requestBody,getUrl("login"),200);
}
else
{
apiLogin(requestBody,getUrl("loginAPI"),1000);
}
}
else if(strcmp(actionMethod,"addApplication")==0)
{
addApplication(requestBody,getUrl("addApplication"),1200);
}
else if(strcmp(actionMethod,"addAPISubscription")==0)
{
addSubscription(requestBody,getUrl("addSubscription"),4096);
}
else if(strcmp(actionMethod,"generateApplicationKey")==0)
{
generateApplicationKey(requestBody,getUrl("generateApplicationKey"),4096);
}
else if(strcmp(actionMethod,"addAPI")==0)
{
addAPI(requestBody,getUrl("addAPI"),1000);
}
else if(strcmp(actionMethod,"updateStatus")==0)
{
publishAPI(requestBody,getUrl("publishAPI"),4000);
}
pthread_mutex_unlock(&lock);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
sem_t fillCount;
sem_t emptyCount;
int item;
int sharedBuffer[100];
int index1 = 0;
int index2 = 0;
int productionCount = 0;
int consumptionCount = 0;
int X=0;
int produceItem(){
return X++;
}
void putItemIntoBuffer(int arg_item){
sharedBuffer[index1] = item;
printf("%d added at index=%d of buffer \\n", arg_item, index1);
}
int removeItemFromBuffer(){
return sharedBuffer[index2];
}
void consumeItem(int arg_item){
printf("Consumed item:%d\\n", arg_item);
}
void *producer() {
while(productionCount < 1000) {
item = produceItem();
sem_wait(&emptyCount);
pthread_mutex_lock(&mutex);
putItemIntoBuffer(item);
index1 = (index1 + 1) % 100;
pthread_mutex_unlock(&mutex);
sem_post(&fillCount);
productionCount++;
}
pthread_exit(0);
}
void *consumer() {
while (consumptionCount < 1000) {
sem_wait(&fillCount);
pthread_mutex_lock(&mutex);
item = removeItemFromBuffer();
index2= ((index2 + 1) % 100);
pthread_mutex_unlock(&mutex);
sem_post(&emptyCount);
consumeItem(item);
consumptionCount++;
}
pthread_exit(0);
}
int main(){
pthread_t producers[4], consumers[4];
pthread_mutex_init(&mutex, 0);
sem_init(&fillCount,0,1);
sem_init(&emptyCount,0,100);
int i;
for(i=0;i<4;i++){
pthread_create(&producers[i],0,producer,0);
}
for(i=0;i<4;i++){
pthread_create(&consumers[i],0,consumer,0);
}
for(i=0;i<4;i++){
pthread_join(producers[i],0);
}
for(i=0;i<4;i++){
pthread_join(consumers[i],0);
}
pthread_mutex_destroy(&mutex);
sem_destroy(&fillCount);
sem_destroy(&emptyCount);
return 0;
}
| 0
|
#include <pthread.h>
static FILE *logfilefp;
static pthread_mutex_t mutex;
void logfile_write_data(char *buf, long length);
void get_time(char *sTime, int length)
{
time_t ct;
struct tm *currtime;
time(&ct);
currtime = (struct tm *)localtime(&ct);
memset(sTime,0x00,length);
sprintf(sTime, "%04d-%02d-%02d.%02d:%02d:%02d", (currtime->tm_year+1900), (currtime->tm_mon+1), currtime->tm_mday, currtime->tm_hour, currtime->tm_min, currtime->tm_sec);
return;
}
void logfile_config(void)
{
char *home;
char time[32];
GString *gfilepath;
struct stat configdir_stat;
home = getenv("HOME");
printf("home=%s\\n",home);
gfilepath = g_string_new(home);
g_string_append(gfilepath, "/.gtkminicom");
if(stat(gfilepath->str, &configdir_stat) != 0)
{
mkdir(gfilepath->str, 0777);
}
get_time(time, sizeof(time));
g_string_append_printf(gfilepath, "/gtkminicom%s.log", time);
strcpy(filepath, gfilepath->str);
g_string_free(gfilepath, TRUE);
printf("%s\\n",filepath);
logfilefp = fopen(filepath, "w");
fprintf(logfilefp, "\\n\\n");
fprintf(logfilefp, "/********************************************/\\n");
fprintf(logfilefp, "/****** %s ******/\\n", time);
fprintf(logfilefp, "/********************************************/\\n");
fprintf(logfilefp, "\\n\\n");
fflush(logfilefp);
pthread_mutex_init(&mutex, 0);
register_callback(logfile_write_data, "logfile");
}
int clear_logfile(void)
{
int err;
char time[32];
pthread_mutex_lock(&mutex);
fflush(logfilefp);
err = ftruncate(fileno(logfilefp), 0);
if (err)
{
pthread_mutex_unlock(&mutex);
return err;
}
rewind(logfilefp);
get_time(time, sizeof(time));
fprintf(logfilefp, "\\n\\n");
fprintf(logfilefp, "/********************************************/\\n");
fprintf(logfilefp, "/****** %s ******/\\n", time);
fprintf(logfilefp, "/********************************************/\\n");
fprintf(logfilefp, "\\n\\n");
pthread_mutex_unlock(&mutex);
fflush(logfilefp);
return 0;
}
void logfile_refresh(void)
{
fflush(logfilefp);
}
void logfile_close(void)
{
pthread_mutex_destroy(&mutex);
fclose(logfilefp);
}
void logfile_write_data(char *buf, long length)
{
pthread_mutex_lock(&mutex);
fwrite(buf, sizeof(char), length, logfilefp);
pthread_mutex_unlock(&mutex);
}
| 1
|
#include <pthread.h>
pthread_mutex_t puente_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t izq_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t der_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t izq_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t der_cond = PTHREAD_COND_INITIALIZER;
int gente_cruzando = 0;
int gente_izq = 0;
int gente_der = 0;
int estado = 0;
void *cruzar_izquierda();
void *cruzar_derecha();
int main(){
pthread_t izq_t;
pthread_t der_t[2];
int i;
for (i = 0; i<2; ++i){
pthread_create(der_t+i,0,cruzar_derecha,0);
}
pthread_create(&izq_t,0,cruzar_izquierda,0);
sleep(2);
pthread_t izq_f,der_f;
pthread_create(&izq_f,0,cruzar_izquierda,0);
pthread_create(&der_f,0,cruzar_derecha,0);
pthread_join(der_t[0],0);
pthread_join(der_t[1],0);
pthread_join(izq_t,0);
pthread_join(izq_f,0);
pthread_join(der_f,0);
return 0;
}
void* cruzar_izquierda(){
pthread_mutex_lock(&izq_mutex);
++gente_izq;
pthread_mutex_unlock(&izq_mutex);
printf("Cruzando hacia la izquierda\\n");
int entro = 0;
while (!entro){
pthread_mutex_lock(&puente_mutex);
if (estado == 1){
printf("Me toca esperar para cruzar a la izquierda\\n");
pthread_cond_wait(&izq_cond,&puente_mutex);
}
if (estado == 0){
estado = 1;
++gente_cruzando;
entro = 1;
}
else if (estado == 1) {
++gente_cruzando;
entro = 1;
}
pthread_mutex_unlock(&puente_mutex);
}
printf("Estoy cruzando el puente hacia la izquierda\\n");
sleep(2);
pthread_mutex_lock(&puente_mutex);
--gente_cruzando;
printf("Termine de cruzar hacia la izquierda\\n");
if (gente_cruzando == 0){
estado = 0;
printf("El puente quedo vacio\\n");
pthread_cond_broadcast(&der_cond);
}
pthread_mutex_unlock(&puente_mutex);
pthread_exit(0);
}
void* cruzar_derecha(){
pthread_mutex_lock(&der_mutex);
++gente_der;
pthread_mutex_unlock(&der_mutex);
printf("Cruzando hacia la derecha\\n");
int entro = 0;
while (!entro){
pthread_mutex_lock(&puente_mutex);
if (estado == 1){
printf("Me toca esperar para cruzar a la derecha\\n");
pthread_cond_wait(&der_cond,&puente_mutex);
}
if (estado == 0){
estado = 1;
++gente_cruzando;
entro = 1;
}
else if (estado == 1) {
++gente_cruzando;
entro = 1;
}
pthread_mutex_unlock(&puente_mutex);
}
printf("Estoy cruzando el puente hacia la derecha\\n");
sleep(2);
pthread_mutex_lock(&puente_mutex);
--gente_cruzando;
printf("Termine de cruzar hacia la derecha\\n");
if (gente_cruzando == 0){
estado = 0;
printf("El puente quedo vacio\\n");
pthread_cond_broadcast(&izq_cond);
}
pthread_mutex_unlock(&puente_mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t cond;
int num;
struct _ProdInfo *next;
} ProdInfo;
ProdInfo *head = 0;
int beginnum = 1000;
void *productor( void *arg ) {
while ( 1 ) {
ProdInfo *ptr = (ProdInfo *) malloc( sizeof( ProdInfo ) );
ptr->num = beginnum++;
pthread_mutex_lock( &lock );
ptr->next = head;
head = ptr;
printf( "%s------tid:%lu-------num---%d\\n", __FUNCTION__, pthread_self(), ptr->num );
pthread_mutex_unlock( &lock );
pthread_cond_signal( &cond );
sleep( rand() % 3 );
}
}
void *customer( void *arg ) {
ProdInfo *ptr = 0;
while ( 1 ) {
pthread_mutex_lock( &lock );
while ( head == 0 ) {
pthread_cond_wait( &cond, &lock );
}
ptr = head;
head = head->next;
printf( "--------%s------tid:%lu-------num---%d\\n", __FUNCTION__, pthread_self(), ptr->num );
pthread_mutex_unlock( &lock );
free( ptr );
sleep( rand() % 3 );
}
}
int main() {
pthread_mutex_init( &lock, 0 );
pthread_cond_init( &cond, 0 );
pthread_t tid[3];
pthread_create( &tid[0], 0, productor, 0 );
pthread_create( &tid[1], 0, customer, 0 );
pthread_create( &tid[2], 0, customer, 0 );
pthread_join( tid[0], 0 );
pthread_join( tid[1], 0 );
pthread_join( tid[2], 0 );
pthread_mutex_destroy( &lock );
pthread_cond_destroy( &cond );
return 0;
}
| 1
|
#include <pthread.h>
void * thread_function(void *);
int Counter=0;
pthread_mutex_t mutex_id;
int main(void)
{
pthread_t tid1, tid2;
void *thread_result;
if(pthread_mutex_init(&mutex_id, 0) != 0){
perror("pthread_mutex_init");
exit(errno);
}
if(pthread_create(&tid1, 0, thread_function, "thread1")!=0) {
perror("pthread_create");
exit(1);
}
if(pthread_create(&tid2, 0, thread_function, "thread2")!=0) {
perror("pthread_create");
exit(1);
}
if(pthread_join(tid1, &thread_result)!=0) {
perror("pthread_join");
exit(1);
}
if(pthread_join(tid2, &thread_result)!=0) {
perror("pthread_join");
exit(1);
}
pthread_mutex_destroy(&mutex_id);
printf(" thread result : %s\\n", (char *) thread_result);
return 0;
}
void * thread_function(void * arg)
{
int temp;
int i, j;
char buffer[80];
for(i=0; i<8; i++) {
pthread_mutex_lock(&mutex_id);
sprintf(buffer, "%s: CountRelay: from %d to ", (char*)arg, Counter);
write(1, buffer, strlen(buffer));
temp=Counter;
temp = temp+1;
for(j=0; j<5000000; j++);
Counter=temp;
sprintf(buffer, "\\e[31m%d\\e[0m\\n", Counter);
write(1, buffer, strlen(buffer));
pthread_mutex_unlock(&mutex_id);
}
pthread_exit("thread end");
}
| 0
|
#include <pthread.h>
struct job {
struct job* next;
int dato;
};
struct job* job_queue;
pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t job_queue_count;
void initialize_job_queue (){
job_queue = 0;
sem_init (&job_queue_count, 0, 0);
}
void* raiz_cuadrada (void* arg){
while (1){
struct job* next_job;
sem_wait(&job_queue_count);
pthread_mutex_lock (&job_queue_mutex);
if (job_queue == 0){
next_job = 0;
}
else {
next_job = job_queue;
job_queue = job_queue->next;
}
pthread_mutex_unlock (&job_queue_mutex);
if (next_job == 0){
break;
}
printf("Raiz %d = %f\\n",next_job->dato,sqrt(next_job->dato));
free (next_job);
}
return 0;
}
void* logaritmo (void* arg){
while (1){
struct job* next_job;
sem_wait (&job_queue_count);
pthread_mutex_lock (&job_queue_mutex);
if (job_queue == 0){
next_job = 0;
}
else {
next_job = job_queue;
job_queue = job_queue->next;
}
pthread_mutex_unlock (&job_queue_mutex);
if (next_job == 0){
break;
}
printf("Logaritmo %d = %f\\n",next_job->dato,log(next_job->dato));
free (next_job);
}
return 0;
}
void* exponencia (void* arg){
while (1){
struct job* next_job;
sem_wait (&job_queue_count);
pthread_mutex_lock (&job_queue_mutex);
if (job_queue == 0){
next_job = 0;
}
else {
next_job = job_queue;
job_queue = job_queue->next;
}
pthread_mutex_unlock (&job_queue_mutex);
if (next_job == 0){
break;
}
printf("Exponencial %d = %f\\n",next_job->dato,exp(next_job->dato));
free (next_job);
}
return 0;
}
void enqueue_job (int dato){
struct job* new_job;
new_job = (struct job*) malloc (sizeof (struct job));
pthread_mutex_lock (&job_queue_mutex);
new_job->next = job_queue;
job_queue = new_job;
job_queue->dato = dato;
sem_post(&job_queue_count);
pthread_mutex_unlock (&job_queue_mutex);
}
int main(int argc, char const *argv[]){
int i;
pthread_t hilo1, hilo2, hilo3;
for (i = 1; i < 101; i++){
enqueue_job(i);
}
pthread_create (&hilo1, 0, &raiz_cuadrada,0);
pthread_create (&hilo2, 0, &logaritmo,0);
pthread_create (&hilo3, 0, &exponencia,0);
pthread_join (hilo1,0);
pthread_join (hilo2,0);
pthread_join (hilo3,0);
return 0;
}
| 1
|
#include <pthread.h>
void *compute_pi (void *);
double intervalWidth, intervalMidPoint, area = 0.0;
int numberOfIntervals, interval, iCount,iteration, num_threads;
double distance=0.5,four=4.0;
pthread_mutex_t area_mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t pi_mutex=PTHREAD_MUTEX_INITIALIZER;
void myPartOfCalc(int myID)
{
int myInterval;
double myIntervalMidPoint, myArea = 0.0, result;
for (myInterval = myID + 1; myInterval <= numberOfIntervals; myInterval += numberOfIntervals)
{
myIntervalMidPoint = ((double) myInterval - distance) * intervalWidth;
myArea += (four / (1.0 + myIntervalMidPoint * myIntervalMidPoint));
}
result = myArea * intervalWidth;
pthread_mutex_lock(&area_mutex);
area += result;
pthread_mutex_unlock(&area_mutex);
}
main(int argc, char *argv[])
{
int i,Iteration,ret_count;
pthread_t p_threads[8];
pthread_t * threads;
pthread_attr_t pta;
pthread_attr_t attr;
double computed_pi,diff;
double time_start, time_end;
struct timeval tv;
struct timezone tz;
FILE *fp;
int CLASS_SIZE,THREADS;
char * CLASS;
ret_count=pthread_mutex_init(&area_mutex,0);
if (ret_count)
{
printf("ERROR; return code from pthread_mutex_init() is %d\\n", ret_count);
exit(-1);
}
gettimeofday(&tv, &tz);
time_start = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
printf("\\n\\t\\t---------------------------------------------------------------------------");
printf("\\n\\t\\t Centre for Development of Advanced Computing (C-DAC)");
printf("\\n\\t\\t Email : RarchK");
printf("\\n\\t\\t---------------------------------------------------------------------------");
printf("\\n\\t\\t Objective : PI Computations");
printf("\\n\\t\\t Computation of PI using Numerical Integration Method ");
printf("\\n\\t\\t..........................................................................\\n");
if( argc != 2 ){
printf("\\t\\t Very Few Arguments\\n ");
printf("\\t\\t Syntax : exec <Number of Intervals>\\n");
return;
}
else {
numberOfIntervals = atoi(argv[1]);
}
if(numberOfIntervals > 8) {
printf("\\n Number Of Intervals should be less than or equal to 8.Aborting\\n");
return;
}
num_threads = numberOfIntervals ;
printf("\\n\\t\\t Input Parameters :");
printf("\\n\\t\\t Number Of Intervals : %d ",numberOfIntervals);
ret_count=pthread_attr_init(&pta);
if(ret_count)
{
printf("\\n ERROR : Return code from pthread_attr_init() is %d ",ret_count);
exit(-1);
}
if (numberOfIntervals == 0)
{
printf("\\nNumber of Intervals are assumed to be 8");
numberOfIntervals = 8;
}
threads = (pthread_t *) malloc(sizeof(pthread_t) * numberOfIntervals);
intervalWidth = 1.0 / (double) numberOfIntervals;
for (iCount = 0; iCount < num_threads; iCount++)
{
ret_count=pthread_create(&threads[iCount], &pta, (void *(*) (void *)) myPartOfCalc, (void *) iCount);
if (ret_count)
{
printf("ERROR; return code from pthread_create() is %d\\n", ret_count);
exit(-1);
}
}
for (iCount = 0; iCount < numberOfIntervals; iCount++)
{
ret_count=pthread_join(threads[iCount], 0);
if (ret_count)
{
printf("ERROR; return code from pthread_join() is %d\\n", ret_count);
exit(-1);
}
}
ret_count=pthread_attr_destroy(&pta);
if (ret_count)
{
printf("ERROR; return code from pthread_attr_destroy() is %d\\n", ret_count);
exit(-1);
}
gettimeofday(&tv, &tz);
time_end = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
printf("\\n\\t\\t Computation Of PI value Using Numerical Integration Method ......Done\\n");
printf("\\n\\t\\t Computed Value Of PI : %lf", area);
printf("\\n\\t\\t Time in Seconds (T) : %lf", time_end - time_start);
printf("\\n\\t\\t..........................................................................\\n");
free(threads);
}
| 0
|
#include <pthread.h>
int fd;
pthread_mutex_t m;
bool running;
} server_t;
int peer_fd;
pthread_t thread;
server_t* server;
} connection_t;
void server_init(const char* port, server_t* server) {
struct addrinfo hints;
struct addrinfo *ptr;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
getaddrinfo(0, port, &hints, &ptr);
server->fd = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
bind(server->fd, ptr->ai_addr, ptr->ai_addrlen);
freeaddrinfo(ptr);
listen(server->fd, 20);
pthread_mutex_init(&(server->m), 0);
server->running = 1;
}
bool server_running(server_t* server) {
bool ans;
pthread_mutex_lock(&(server->m));
ans = server->running;
pthread_mutex_unlock(&(server->m));
return ans;
}
void server_halt(server_t* server) {
pthread_mutex_lock(&(server->m));
server->running = 0;
pthread_mutex_unlock(&(server->m));
}
bool eoc(char* buffer) {
for (int i = 0; i < 513; i++)
if (buffer[i] != 'Q') return 0;
return 1;
}
void* run(void* arg) {
connection_t* connection = (connection_t*) arg;
char buffer[513 + 1];
memset(buffer, '\\0', 513);
while (server_running(connection->server) && eoc(buffer)) {
recv(connection->peer_fd, buffer, 513, MSG_NOSIGNAL);
send(connection->peer_fd, buffer, 513, MSG_NOSIGNAL);
}
return 0;
}
void accept_connections(server_t* server) {
connection_t* connections = malloc(sizeof(connection_t) * 30);
int i;
for (i = 0; server_running(server) && i < 30; i++) {
connections[i].peer_fd = accept(server->fd, 0, 0);
connections[i].server = server;
pthread_create(&(connections[i].thread), 0, run, &(connections[i]));
}
for (int j = 0; j < i; j++) {
shutdown(connections[j].peer_fd, SHUT_RDWR);
close(connections[j].peer_fd);
pthread_join(connections[j].thread, 0);
}
free(connections);
}
void server_shutdown(server_t* server) {
shutdown(server->fd, SHUT_RDWR);
close(server->fd);
pthread_mutex_destroy(&(server->m));
}
int main(int arg, char* argv[]) {
server_t server;
server_init("283", &server);
accept_connections(&server);
server_shutdown(&server);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t gm;
unsigned long long chunk_size;
void* t(void *args) {
int sec = 3;
char *ptr = (char*)malloc(chunk_size);
pthread_mutex_lock(&gm);
printf("allocated\\n");
pthread_mutex_unlock(&gm);
free(ptr);
pthread_exit(0);
}
int main() {
pthread_mutex_init(&gm, 0);
pthread_t tid1;
chunk_size = 1024;
chunk_size = chunk_size * chunk_size;
chunk_size = chunk_size * chunk_size;
chunk_size = chunk_size * 4;
printf("Program did not crash before, continue normal execution.\\n");
pthread_create(&tid1, 0, t, 0);
char *ptr = (char*)malloc(chunk_size);
pthread_mutex_lock(&gm);
printf("allocated\\n");
pthread_mutex_unlock(&gm);
pthread_join(tid1, 0);
printf("-------------main exits-------------------\\n");
free(ptr);
return 0;
}
| 0
|
#include <pthread.h>
int nbThreads;
pthread_t idThdAfficheurs[20];
int tour = 0;
pthread_mutex_t affMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t tourMutex = PTHREAD_MUTEX_INITIALIZER;
void thdErreur(int codeErr, char *msgErr, void *codeArret) {
fprintf(stderr, "%s: %d soit %s \\n", msgErr, codeErr, strerror(codeErr));
pthread_exit(codeArret);
}
void *thd_afficher (void *arg) {
int i, j, nbLignes;
int *nbFois = (int *)arg;
i = 0;
while (i < *nbFois) {
nbLignes = rand() % (*nbFois);
pthread_mutex_lock(&tourMutex);
if(pthread_self() == idThdAfficheurs[tour]){
tour = (tour+1) % nbThreads;
i++;
pthread_mutex_lock(&affMutex);
pthread_mutex_unlock(&tourMutex);
for (j = 0; j < nbLignes; j++) {
printf("Thread %lu, j'affiche %d-%d \\n", pthread_self(), i, j);
usleep(250000);
}
pthread_mutex_unlock(&affMutex);
}
}
pthread_exit((void *)0);
}
int main(int argc, char*argv[]) {
int nbAffichages[20];
int i, etat;
pthread_mutex_init(&affMutex, 0);
pthread_mutex_init(&tourMutex, 0);
if (argc != 2) {
printf("Usage : %s <Nb de threads>\\n", argv[0]);
exit(1);
}
nbThreads = atoi(argv[1]);
if (nbThreads > 20)
nbThreads = 20;
for (i = 0; i < nbThreads; i++) {
nbAffichages[i] = 10;
if ((etat = pthread_create(&idThdAfficheurs[i], 0,
thd_afficher, &nbAffichages[i])) != 0)
thdErreur(etat, "Creation afficheurs", 0);
}
for (i = 0; i < nbThreads; i++)
if ((etat = pthread_join(idThdAfficheurs[i], 0)) != 0)
thdErreur(etat, "Join threads afficheurs", 0);
printf ("\\nFin de l'execution du thread principal \\n");
}
| 1
|
#include <pthread.h>
int baguette_dispo[5];
pthread_mutex_t mutex;
pthread_cond_t cond[5];
int indice_philo;
int nbr_portion;
}philo_t;
void prendre_baguettes(int i){
pthread_mutex_lock(&mutex);
while(!baguette_dispo[i] || !baguette_dispo[(i+1)%5]){
if(!baguette_dispo[i]){
pthread_cond_wait(&cond[i],&mutex);
}
else if(!baguette_dispo[(i+1)%5]){
pthread_cond_wait(&cond[(i+1)%5],&mutex);
}
else if(!baguette_dispo[i] && !baguette_dispo[(i+1)%5]){
pthread_cond_wait(&cond[i],&mutex);
pthread_cond_wait(&cond[(i+1)%5],&mutex);
}
}
baguette_dispo[i] = 0;
baguette_dispo[(i+1)%5] = 0;
pthread_mutex_unlock(&mutex);
}
void poser_baguettes(int i){
pthread_mutex_lock(&mutex);
baguette_dispo[i] = 1;
baguette_dispo[(i+1)%5] = 1;
pthread_cond_broadcast(&cond[i]);
pthread_cond_broadcast(&cond[(i+1)%5]);
pthread_mutex_unlock(&mutex);
}
int manger(int i){
return i = i - 1;
}
void *philosophe(void *arg){
philo_t *p = (philo_t *)arg;
pthread_t tid;
tid = pthread_self();
while(p->nbr_portion){
srand ((int) tid) ;
usleep (rand() / 32767 * 1000000.);
prendre_baguettes(p->indice_philo);
printf("philosophe %d mange\\n", p->indice_philo);
p->nbr_portion = manger(p->nbr_portion);
poser_baguettes(p->indice_philo);
}
printf("Thread %x indice %d a FINI !\\n", (unsigned int)tid, p->indice_philo);
return (void *) tid;
}
int main(int argc, char const *argv[]){
philo_t *philos;
if(pthread_mutex_init(&mutex,0) != 0){
fprintf(stderr, "Mutex init error\\n");
exit(1);
}
for(int i=0; i<5; i++){
pthread_cond_init(&cond[i],0);
}
for(int i=0; i<5; i++){
baguette_dispo[i] = 1;
}
pthread_t *tids ;
tids = malloc(sizeof(pthread_t)*5);
if(tids == 0){
fprintf(stderr, "Malloc pthread_t error\\n");
exit(2);
}
philos = malloc(sizeof(philo_t)*5);
if (philos == 0){
fprintf(stderr, "Malloc philo_t error\\n");
exit(3);
}
for(int i = 0 ;i <5 ;i++){
philos[i].indice_philo = i;
philos[i].nbr_portion = 10;
pthread_create(&tids[i],0,philosophe,&philos[i]);
}
for(int j = 0;j <5 ; j++){
pthread_join(tids[j],0);
}
free(tids);
return 0;
}
| 0
|
#include <pthread.h>
int n;
unsigned *ugarfoLivre;
pthread_cond_t *garfoLivre;
pthread_mutex_t *mutex;
pthread_mutex_t mutexStatus;
char *status;
void atualizarStatus(char novoStatus, int id)
{
pthread_mutex_lock(&mutexStatus);
*(status + id) = novoStatus;
int i;
for(i = 0; i < n; i++)
{
if(i == n-1)
printf("%c\\n", *(status+i));
else
printf("%c ", *(status+i));
}
pthread_mutex_unlock(&mutexStatus);
}
void *filosofar(void *arg)
{
int id = *(int *) arg;
int esquerda, direita;
if(id == 0)
{
esquerda = 1;
direita = 0;
}
else
{
esquerda = id;
direita = (id + 1) % n;
}
sleep(rand() % (10 + 1));
while(1)
{
atualizarStatus('H', id);
pthread_mutex_lock(mutex + esquerda);
if(*(ugarfoLivre + esquerda))
*(ugarfoLivre + esquerda) = 0;
else
{
pthread_cond_wait(garfoLivre + esquerda, mutex + esquerda);
*(ugarfoLivre + esquerda) = 0;
}
pthread_mutex_lock(mutex + direita);
if(*(ugarfoLivre + direita))
*(ugarfoLivre + direita) = 0;
else
{
pthread_cond_wait(garfoLivre + direita, mutex + direita);
*(ugarfoLivre + direita) = 0;
}
atualizarStatus('E', id);
sleep(rand() % (10 + 1));
*(ugarfoLivre + esquerda) = 1;
*(ugarfoLivre + direita) = 1;
pthread_cond_signal(garfoLivre + esquerda);
pthread_mutex_unlock(mutex + esquerda);
pthread_cond_signal(garfoLivre + direita);
pthread_mutex_unlock(mutex + direita);
atualizarStatus('T', id);
sleep(rand() % (10 + 1));
}
}
int main(int argc, char *argv[])
{
if(argc < 2)
{
printf("\\nInforme o numero de filosofos.\\n\\n");
exit(-1);
}
n = atoi(argv[1]);
if(n <= 1)
{
printf("\\nE preciso ter no minimo dois filosofos.\\n\\n");
exit(-1);
}
pthread_t filosofo[n];
garfoLivre = (pthread_cond_t *)malloc(n * sizeof(pthread_cond_t));
mutex = (pthread_mutex_t *)malloc(n * sizeof(pthread_mutex_t));
status = (char *)malloc(n * sizeof(char));
ugarfoLivre = (unsigned*)malloc(n * sizeof(unsigned));
pthread_mutex_init(&mutexStatus, 0);
int i, id[n];
for(i = 0; i < n; i++)
{
pthread_cond_init(garfoLivre + i, 0);
pthread_mutex_init(mutex + i, 0);
*(status + i) = 'T';
id[i] = i;
*(ugarfoLivre + i) = 1;
}
for(i = 0; i < n; i++)
pthread_create(filosofo+i, 0, filosofar, id+i);
while(1);
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
long count1;
long count2;
void* work(void* v) {
for (int i = 0; i < 500000; i++) {
count1++;
}
for (int i = 0; i < 500000; i++) {
pthread_mutex_lock(&lock);
count2++;
pthread_mutex_unlock(&lock);
}
return 0;
}
int main(void) {
pthread_t thread[10];
for(int i = 0; i < 10; i++) {
pthread_mutex_init(&lock, 0);
}
for(int i = 0; i < 10; i++) {
pthread_create(&thread[i], 0, work, (void*) 0);
}
for(int i = 0; i < 10; i++) {
pthread_join(thread[i], 0);
}
printf("count1 = %li\\n", count1);
printf("count2 = %li\\n", count2);
}
| 0
|
#include <pthread.h>
pthread_mutex_t debug_file_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t notice_file_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t warn_file_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t error_file_mutex = PTHREAD_MUTEX_INITIALIZER;
void request_mutex(pthread_mutex_t* p_mutex) {
if (OPEN_LOCK ) {
pthread_mutex_lock(p_mutex);
}
}
void release_mutex(pthread_mutex_t* p_mutex) {
if (OPEN_LOCK) {
pthread_mutex_unlock(p_mutex);
}
}
void DEBUG(const char* buffer) {
FILE * fp;
if (!OPEN_DEBUG) {
return;
}
request_mutex(&debug_file_mutex);
fp = fopen(DEBUG_FNAME, "a+");
if (fp == 0) {
printf("open file failed");
release_mutex(&debug_file_mutex);
return;
}
fputs(buffer, fp);
fputc('\\n', fp);
fflush(fp);
fclose(fp);
release_mutex(&debug_file_mutex);
}
void NOTICE(const char* buffer) {
FILE * fp;
if (!OPEN_NOTICE) {
return;
}
request_mutex(¬ice_file_mutex);
fp = fopen(NOTICE_FNAME, "a+");
if (fp == 0) {
printf("open file failed");
release_mutex(¬ice_file_mutex);
return;
}
fputs(buffer, fp);
fputc('\\n', fp);
fflush(fp);
fclose(fp);
release_mutex(¬ice_file_mutex);
}
void WARNING(const char* buffer) {
FILE * fp;
if (!OPEN_WARNING) {
return;
}
request_mutex(&warn_file_mutex);
fp = fopen(WARNING_FNAME, "a+");
if (fp == 0) {
printf("open file failed");
release_mutex(&warn_file_mutex);
return;
}
fputs(buffer, fp);
fputc('\\n', fp);
fflush(fp);
fclose(fp);
release_mutex(&warn_file_mutex);
}
void ERROR(const char* buffer) {
FILE * fp;
if (!OPEN_ERROR) {
return;
}
request_mutex(&error_file_mutex);
fp = fopen(ERROR_FNAME, "a+");
if (fp == 0) {
printf("open file failed");
release_mutex(&error_file_mutex);
return;
}
fputs(buffer, fp);
fputc('\\n', fp);
fflush(fp);
fclose(fp);
release_mutex(&error_file_mutex);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_t tidP[20], tidC[20];
sem_t full, empty;
int counter;
int buffer[10];
void initialize()
{
pthread_mutex_init(&mutex,0);
sem_init(&full, 1, 0);
sem_init(&empty, 1, 10);
counter=0;
}
void write(int item)
{
buffer[counter++]=item;
}
int read()
{
return(buffer[--counter]);
}
void * producer (void * param)
{
int waittime, item, i;
item=rand()%5;
waittime=rand()%5;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
printf("Producer has produced item: %d\\n",item);
write(item);
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
void * consumer (void * param)
{
int waittime, item;
waittime=rand()%5;
sem_wait(&full);
pthread_mutex_lock(&mutex);
item=read();
printf("Consumer has consumed item: %d\\n",item);
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
int main()
{
int n1, n2, i;
initialize();
printf("Enter the no of producers: ");
scanf("%d", &n1);
printf("Enter the no of consumers: ");
scanf("%d", &n2);
for(i=0; i<n1; i++)
pthread_create(&tidP[i], 0, producer, 0);
for(i=0; i<n2; i++)
pthread_create(&tidC[i], 0, consumer, 0);
for(i=0; i<n1; i++)
pthread_join(tidP[i], 0);
for(i=0; i<n2; i++)
pthread_join(tidC[i], 0);
exit(0);
}
| 0
|
#include <pthread.h>
int iters;
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int count = 0;
char bufdata[CHUNK*SLOTS];
void * produce(void *arg) {
int dev = open(DEV, O_RDONLY);
char buf[CHUNK];
for (int i = 0; i < iters; i++) {
read(dev, buf, CHUNK);
pthread_mutex_lock(&the_mutex);
while (count == SLOTS)
pthread_cond_wait(&condp, &the_mutex);
memcpy(bufdata+(count*CHUNK), buf, CHUNK);
count += 1;
pthread_cond_signal(&condc);
pthread_mutex_unlock(&the_mutex);
}
close(dev);
pthread_exit(0);
}
void * consume(void *arg) {
char rbuf[CHUNK];
for (int i = 0; i < iters; i++) {
pthread_mutex_lock(&the_mutex);
while (count == 0)
pthread_cond_wait(&condc, &the_mutex);
memcpy(rbuf, bufdata+(count*CHUNK), CHUNK);
count -= 1;
pthread_cond_signal(&condp);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
int main(int argc, char **argv) {
if (argc < 2) {
fprintf(stderr, "usage: %s <iters>\\n", argv[0]);
return 1;
}
iters = atoi(argv[1]);
pthread_mutex_init(&the_mutex, 0);
pthread_cond_init(&condc, 0);
pthread_cond_init(&condp, 0);
pthread_t producer, consumer;
pthread_create(&producer, 0, produce, 0);
pthread_create(&consumer, 0, consume, 0);
pthread_join(consumer, 0);
pthread_join(producer, 0);
return 0;
}
| 1
|
#include <pthread.h>
struct msg
{
struct msg *next;
int num;
};
struct msg *head;
pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void *consumer( void *p )
{
struct msg *mp;
for(;; )
{
pthread_mutex_lock( &lock );
while( head == 0 )
{
pthread_cond_wait( &has_product, &lock );
}
mp = head;
head = mp->next;
pthread_mutex_unlock( &lock );
printf( "Consume %d\\n", mp->num );
free( mp );
sleep( rand( ) % 5 );
}
}
void *producer( void *p )
{
struct msg *mp;
for(;; )
{
mp = malloc( sizeof( struct msg ) );
mp->num = rand( ) % 1000 + 1;
printf( "Produce %d\\n", mp->num );
pthread_mutex_lock( &lock );
mp->next = head;
head = mp;
pthread_mutex_unlock( &lock );
pthread_cond_signal( &has_product );
sleep( rand( ) % 5 );
}
}
int main( int argc, 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;
}
| 0
|
#include <pthread.h>
int G_CHUNK_SIZE;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
large_uint G_current_start;
large_uint G_subset_count;
int G_terminated_flag;
large_uint G_steps;
void increment_step() {
pthread_mutex_lock(&mutex);
G_steps++;
pthread_mutex_unlock(&mutex);
}
struct solution {
large_int* subset;
int size;
};
large_uint get_next_start() {
pthread_mutex_lock(&mutex);
large_uint start = G_current_start;
G_current_start = start + G_CHUNK_SIZE;
pthread_mutex_unlock(&mutex);
return start;
}
void print_set(large_int* set, int size, FILE* out) {
int i;
fprintf(out, "{");
for (i = 0; i < size; i++) {
if (i > 0) {
fprintf(out, ", ");
}
fprintf(out, "%lld", set[i]);
}
fprintf(out, "}\\n");
}
large_int* generate_subset(large_int* set, large_uint elements, int* subset_size) {
large_uint max_elements = round(log(elements) / log(2)) + 1;
large_int* subset = malloc(sizeof(large_int) * max_elements);
int i;
int current_index = 0;
for (i = 0; i < max_elements; i++) {
large_uint val = (elements >> i) & 1;
if (val == 1) {
subset[current_index] = set[i];
current_index++;
}
}
*subset_size = current_index;
return subset;
}
large_int calculate_set_sum(large_int* set, int size) {
large_int sum = 0;
int i;
for (i = 0; i < size; i++) {
sum += set[i];
}
return sum;
}
void* find_zero_subset(void* data) {
large_int* set = (large_int*) data;
while (1) {
large_uint start = get_next_start();
large_uint i;
for (i = start; i < start + G_CHUNK_SIZE; i++) {
if (i >= G_subset_count || G_terminated_flag == 1) {
return 0;
}
int size;
large_int* subset = generate_subset(set, i, &size);
large_int sum = calculate_set_sum(subset, size);
if (sum == 0) {
struct solution* sol = (struct solution*) malloc(sizeof(struct solution));
sol->subset = subset;
sol->size = size;
printf("Solution found!\\n");
pthread_mutex_lock(&mutex);
G_terminated_flag = 1;
pthread_mutex_unlock(&mutex);
return ((void*) sol);
}
free(subset);
}
}
return 0;
}
large_int* generate_set(unsigned int set_size, large_int range) {
int i;
large_int* set = malloc(sizeof(large_int) * set_size);
for (i = 0; i < set_size; i++) {
double val = (((double) pcg32_boundedrand(range)) / (range / 2.0)) - 1;
large_int value = val * range;
set[i] = value;
}
return set;
}
void test_multithread(FILE* file, int num_threads, int set_size, large_int range, int chunk_size) {
G_CHUNK_SIZE = chunk_size;
pthread_t threads[num_threads];
clock_t start = clock();
large_int* set = generate_set(set_size, range);
G_subset_count = round(pow(2, set_size));
G_current_start = 1;
G_terminated_flag = 0;
G_steps = 0;
int i;
for (i = 0; i < num_threads; i++) {
pthread_create(&threads[i], 0, find_zero_subset, (void*) set);
}
struct solution* sol = 0;
for (i = 0; i < num_threads; i++) {
void* ret;
pthread_join(threads[i], &ret);
if (ret != 0) {
printf("Thread %d found a solution!\\n", i);
sol = ret;
} else {
printf("Thread %d was not able to find a solution.\\n", i);
}
}
clock_t end = clock();
double delta = (((double) (end - start)) / CLOCKS_PER_SEC);
printf("%.5f\\n", delta);
printf("Joined with result %x and %d executions\\n", sol, G_steps);
if (sol != 0) {
print_set(sol->subset, sol->size, stdout);
free(sol);
}
fprintf(file, "%d,%d,%d,%.6f\\n", G_CHUNK_SIZE, num_threads, set_size, delta);
fflush(file);
}
void test_single(FILE* file, int set_size, large_int range) {
G_CHUNK_SIZE = 32767;
clock_t start = clock();
large_int* set = generate_set(set_size, range);
G_subset_count = round(pow(2, set_size));
G_current_start = 1;
G_terminated_flag = 0;
G_steps = 0;
struct solution* sol = find_zero_subset((void*) set);
if (sol != 0) {
print_set(sol->subset, sol->size, stdout);
free(sol);
}
clock_t end = clock();
double delta = (((double) (end - start)) / CLOCKS_PER_SEC);
fprintf(file, "%d,%.6f\\n", set_size, delta);
fflush(file);
}
int main(int argc, char** argv) {
int rounds = atoi(argv[0]);
unsigned int seed = 1478456124;
FILE* file = fopen("out_single_seeded.csv", "w");
fprintf(file, "setsize,time\\n");
int ch, th, k, it;
pcg32_srandom(seed, (intptr_t) &rounds);
for (k = 0; k < 13; k++) {
for (it = 0; it < 30; it++) {
int set_size = (k + 1) * 4;
large_int range = round(pow(2, set_size / 2));
printf("k = %d, it = %d\\n", k, it);
test_single(file, set_size, range);
}
}
return 0;
}
| 1
|
#include <pthread.h>
long long int size;
char* D1;
char* D2;
int* bitr;
pthread_mutex_t* D1_lock;
pthread_mutex_t* D2_lock;
int STATE;
} database;
database global_db;
int is_finished = 0;
long long int throughput = 0;
long long int active0=0;
long long int active1=0;
int peroid=0;
int* sec_throughput;
long long int run_count = 0;
int ckp_fd;
void load_db(long long int size) {
global_db.size = size;
global_db.STATE = 0;
global_db.D1 = (char *) malloc(global_db.size * 4096);
global_db.D2 = (char *) malloc(global_db.size * 4096);
global_db.bitr = (int *) malloc(global_db.size * sizeof(int));
global_db.D1_lock = (pthread_mutex_t *) malloc(global_db.size * sizeof(pthread_mutex_t));
global_db.D2_lock = (pthread_mutex_t *) malloc(global_db.size * sizeof(pthread_mutex_t));
long long int i = 0;
while(i < global_db.size) {
pthread_mutex_init(&(global_db.D1_lock[i]),0);
pthread_mutex_init(&(global_db.D2_lock[i]),0);
i++;
}
}
void work0()
{
long long int index1 = rand() % (global_db.size); int value1 = rand();
pthread_mutex_lock(&(global_db.D1_lock[index1]));
int k =0;
while(k++ < 1024)
{
memcpy( global_db.D1 + 4096 * index1 + 4*k , &value1, 4);
}
pthread_mutex_unlock(&(global_db.D1_lock[index1]));
global_db.bitr[index1] = 1;
sec_throughput[run_count++] = get_mtime();
}
void work1(){
long long int index1 = rand() % (global_db.size); int value1 = rand();
pthread_mutex_lock(&(global_db.D2_lock[index1]));
int k =0;
while(k++ < 1024)
{
memcpy( global_db.D2 + 4096 * index1 + 4*k , &value1, 4);
}
pthread_mutex_unlock(&(global_db.D2_lock[index1]));
global_db.bitr[index1] = 2;
sec_throughput[run_count++] = get_mtime();
}
void* transaction(void* info) {
while(is_finished==0)
{
int p = peroid;
if(p%2==0)
{
__sync_fetch_and_add(&active0,1);
work0();
__sync_fetch_and_sub(&active0,1);
}else{
__sync_fetch_and_add(&active1,1);
work1();
__sync_fetch_and_sub(&active1,1);
}
}
}
void checkpointer(int num) {
char* temp;
int * temp2;
sleep(5);
while(num--) {
sleep(1);
peroid++;
int p = peroid;
long long int i;
if(p%2==1){
while(active0>0);
ckp_fd = open("./dump.dat", O_WRONLY | O_TRUNC | O_SYNC | O_CREAT, 666);
i = 0;
while(i < global_db.size) {
if(global_db.bitr[i]==2)
{
pthread_mutex_lock(&(global_db.D1_lock[i]));
memcpy(global_db.D1 + i * 4096, global_db.D2 + i * 4096, 4096);
pthread_mutex_unlock(&(global_db.D1_lock[i]));
global_db.bitr[i] = 0;
}
write(ckp_fd, global_db.D1 + i * 4096,4096);
lseek(ckp_fd, 0, 2);
i++;
}
}
else{
while(active1>0);
i = 0;
ckp_fd = open("./dump.dat", O_WRONLY | O_TRUNC | O_SYNC | O_CREAT, 666);
while(i < global_db.size) {
if(global_db.bitr[i]==1)
{
pthread_mutex_lock(&(global_db.D2_lock[i]));
memcpy(global_db.D2 + i * 4096, global_db.D1 + i * 4096, 4096);
pthread_mutex_unlock(&(global_db.D2_lock[i]));
global_db.bitr[i] = 0;
}
write(ckp_fd, global_db.D2 + i * 4096,4096);
lseek(ckp_fd, 0, 2);
i++;
}
}
}
is_finished = 1;
}
int main(int argc, char const *argv[]) {
srand((unsigned)time(0));
load_db(atoi(argv[1]));
sec_throughput = (int*) malloc(10000000000 * sizeof(int));
throughput = atoi(argv[2]);
for (int i = 0; i < throughput; ++i)
{
pthread_t pid_t;
pthread_create(&pid_t,0,transaction,0);
}
checkpointer(10);
int max,min;
max_min(sec_throughput,run_count,&max,&min);
int duration = max-min+1;
int* result = (int*) malloc(sizeof(int) * (duration));
for (long long int i = 0; i < run_count; ++i)
{
result[ (sec_throughput[i] - min) ] +=1;
}
printf("%f\\n", 1.0*run_count / duration);
return 0;
}
| 0
|
#include <pthread.h>
pthread_t t1,t2;
pthread_mutex_t m1,m2;
pthread_cond_t c;
void* r1(void* d){
while(1){
pthread_mutex_lock(&m1);
printf("wait..............\\n");
pthread_cond_wait(&c,&m2);
pthread_mutex_unlock(&m1);
}
}
void* r2(void* d){
while(1){
pthread_mutex_lock(&m1);
printf("not wait..........\\n");
pthread_cond_signal(&c);
pthread_mutex_unlock(&m1);
}
}
int main(){
pthread_cond_init(&c,0);
pthread_mutex_init(&m1,0);
pthread_mutex_init(&m2,0);
pthread_create(&t1,0,r1,0);
pthread_create(&t2,0,r2,0);
pthread_join(t1,0);
pthread_join(t2,0);
pthread_mutex_destroy(&m2);
pthread_mutex_destroy(&m1);
pthread_cond_destroy(&c);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex_count=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_mutex= PTHREAD_COND_INITIALIZER;
int count = 0;
void * thread1(void *ptr){
while(1){
pthread_mutex_lock(&mutex_count);
if((count%2) != 0){
pthread_cond_wait(&cond_mutex,&mutex_count);
}
count++;
printf("%d\\n", count);
pthread_cond_signal(&cond_mutex);
if(count >= 10){
pthread_mutex_unlock(&mutex_count);
return;
}
pthread_mutex_unlock(&mutex_count);
}
return ;
}
void *thread2(void* ptr){
while(1){
pthread_mutex_lock(&mutex_count);
if(count%1 != 0){
pthread_cond_wait(&cond_mutex,&mutex_count);
}
count++;
printf("%d\\n", count);
pthread_cond_signal(&cond_mutex);
if(count >= 10){
pthread_mutex_unlock(&mutex_count);
return ;
}
pthread_mutex_unlock(&mutex_count);
}
return ;
}
int main(void){
pthread_t pid1, pid2;
void *ptr;
int ret;
ret = pthread_create(&pid1,0,&thread1,0);
ret = pthread_create(&pid2,0,&thread2,0);
pthread_join(pid1,&ptr);
return 0;
}
| 0
|
#include <pthread.h>
void* send_frame(void* args) {
int i = (int)args;
int wait;
struct timeval now;
struct timespec limit;
pthread_mutex_lock(&network);
gettimeofday(&now, 0);
limit.tv_nsec = now.tv_usec*1000 + TIMEOUT_MS*1000000;
limit.tv_sec = now.tv_sec + limit.tv_nsec/1000000000;
limit.tv_nsec %= 1000000000;
sendto(data.sock, buf_send[i], len_send[i], 0, (struct sockaddr*)&data.sock_addr, data.sock_len);
report_frame("tx", buf_send[i], "sent");
wait = pthread_cond_timedwait(&received, &network, &limit);
pthread_mutex_unlock(&network);
if (wait != 0) {
report_frame("tx", buf_send[i], "timeout");
} else {
pthread_mutex_lock(&time_lock);
timeout = 0;
pthread_mutex_unlock(&time_lock);
if (i < WINDOW_SIZE) {
}
}
return 0;
}
void* recv_loop(void* args) {
uint8_t control, info[MAX_BUFFER/2];
bool disc = 0;
while (!disc) {
recv_frame(&control, info);
if (len_recv >= 0) {
report_frame("rx", buf_recv, "OK");
pthread_cond_signal(&received);
}
pthread_mutex_lock(&disc_lock);
disc = disconnect;
pthread_mutex_unlock(&disc_lock);
}
return 0;
}
void run_client() {
bool time;
pthread_t send[WINDOW_SIZE+1], recv;
pthread_create(&recv, 0, &recv_loop, 0);
pthread_mutex_lock(&time_lock);
timeout = 1;
pthread_mutex_unlock(&time_lock);
len_send[WINDOW_SIZE] = build_sabm(buf_send[WINDOW_SIZE]);
do {
pthread_create(&send[0], 0, &send_frame, (void*)WINDOW_SIZE);
pthread_join(send[0], 0);
pthread_mutex_lock(&time_lock);
time = timeout;
pthread_mutex_unlock(&time_lock);
} while(time);
}
| 1
|
#include <pthread.h>
struct monitor {
int count;
int sleep;
int quit;
pthread_t * pids;
pthread_cond_t cond;
pthread_mutex_t mutex;
};
static struct monitor *m = 0;
void create_thread(pthread_t *thread, void *(*start_routine) (void *), void *arg) {
if (pthread_create(thread,0, start_routine, arg)) {
skynet_logger_error(0, "Create thread failed");
exit(1);
}
}
void wakeup(struct monitor *m, int busy) {
if (m->sleep >= m->count - busy) {
pthread_cond_signal(&m->cond);
}
}
void * thread_socket(void *p) {
struct monitor * m = p;
while (!m->quit) {
int r = skynet_socket_poll();
if (r==0)
break;
if (r<0) {
continue;
}
wakeup(m,0);
}
return 0;
}
void * thread_timer(void *p) {
struct monitor * m = p;
while (!m->quit) {
skynet_updatetime();
wakeup(m,m->count-1);
usleep(1000);
}
return 0;
}
void * thread_worker(void *p) {
struct monitor *m = p;
while (!m->quit) {
if (skynet_message_dispatch()) {
if (pthread_mutex_lock(&m->mutex) == 0) {
++ m->sleep;
if (!m->quit)
pthread_cond_wait(&m->cond, &m->mutex);
-- m->sleep;
if (pthread_mutex_unlock(&m->mutex)) {
skynet_logger_error(0, "unlock mutex error");
exit(1);
}
}
}
}
return 0;
}
void skynet_start(unsigned harbor, unsigned thread) {
unsigned i;
m = skynet_malloc(sizeof(*m));
memset(m, 0, sizeof(*m));
m->count = thread;
m->sleep = 0;
m->quit = 0;
m->pids = skynet_malloc(sizeof(*m->pids) * (thread+2));
if (pthread_mutex_init(&m->mutex, 0)) {
skynet_logger_error(0, "Init mutex error");
exit(1);
}
if (pthread_cond_init(&m->cond, 0)) {
skynet_logger_error(0, "Init cond error");
exit(1);
}
for (i=0;i<thread;i++) {
create_thread(m->pids+i, thread_worker, m);
}
create_thread(m->pids+i, thread_timer, m);
create_thread(m->pids+i+1, thread_socket, m);
skynet_logger_notice(0, "skynet start, harbor:%u workers:%u", harbor, thread);
for (i=0;i<thread;i++) {
pthread_join(*(m->pids+i), 0);
}
skynet_logger_notice(0, "skynet shutdown, harbor:%u", harbor);
pthread_mutex_destroy(&m->mutex);
pthread_cond_destroy(&m->cond);
skynet_free(m->pids);
skynet_free(m);
}
void skynet_shutdown(int sig) {
skynet_logger_notice(0, "recv signal:%d", sig);
m->quit = 1;
skynet_socket_exit();
pthread_mutex_lock(&m->mutex);
pthread_cond_broadcast(&m->cond);
pthread_mutex_unlock(&m->mutex);
}
void skynet_coredump(int sig) {
unsigned i;
skynet_shutdown(sig);
for (i=0;i<m->count;i++) {
pthread_join(*(m->pids+i), 0);
}
skynet_service_releaseall();
signal(sig, SIG_DFL);
raise(sig);
}
void skynet_signal_init() {
struct sigaction actTerminate;
actTerminate.sa_handler = skynet_shutdown;
sigemptyset(&actTerminate.sa_mask);
actTerminate.sa_flags = 0;
sigaction(SIGTERM, &actTerminate, 0);
struct sigaction actCoredump;
actCoredump.sa_handler = skynet_coredump;
sigemptyset(&actCoredump.sa_mask);
actCoredump.sa_flags = 0;
sigaction(SIGSEGV, &actCoredump, 0);
sigaction(SIGILL, &actCoredump, 0);
sigaction(SIGFPE, &actCoredump, 0);
sigaction(SIGABRT, &actCoredump, 0);
sigaction(SIGKILL, &actCoredump, 0);
sigaction(SIGXFSZ, &actCoredump, 0);
sigset_t bset, oset;
sigemptyset(&bset);
sigaddset(&bset, SIGINT);
pthread_sigmask(SIG_BLOCK, &bset, &oset);
}
int main(int argc, char *argv[]) {
int harbor, thread, concurrent;
char * service_name = 0;
char * service_args = skynet_malloc(1024);
char * service_list = skynet_malloc(1024);
char * service_path = skynet_malloc(1024);
char * logger_args = skynet_malloc(1024);
skynet_config_init(argv[1]);
skynet_config_int("skynet", "harbor", &harbor);
skynet_config_int("skynet", "thread", &thread);
skynet_config_string("skynet", "logger_args", logger_args, 1024);
skynet_config_string("skynet", "service_path", service_path, 1024);
skynet_config_string("skynet", "service_list", service_list, 1024);
skynet_mq_init();
skynet_signal_init();
skynet_service_init(service_path);
skynet_logger_init(harbor, logger_args);
skynet_timer_init();
skynet_socket_init();
service_name = strtok(service_list, ",");
while (service_name != 0) {
skynet_config_int(service_name, "concurrent", &concurrent);
skynet_config_string(service_name, "args", service_args, 1024);
skynet_service_create(service_name, harbor, service_args, concurrent);
service_name = strtok(0, ",");
}
skynet_start(harbor, thread);
skynet_service_releaseall();
skynet_socket_free();
skynet_config_free();
skynet_free(logger_args);
skynet_free(service_list);
skynet_free(service_args);
skynet_free(service_path);
printf("skynet exit.");
return 0;
}
| 0
|
#include <pthread.h>
int dato = 4;
int n_lectores = 0;
pthread_mutex_t mutex;
pthread_mutex_t mutex_lectores;
void* Lector(void* args);
void* Escritor(void* args);
int main(){
pthread_mutex_init(&mutex, 0);
pthread_mutex_init(&mutex_lectores, 0);
pthread_t escritor[10];
pthread_t lector[10];
srand(time(0));
int i;
for(i=0;i<3; i++){
printf("Creando escritor %d\\n", i+1);
pthread_create(&escritor[i], 0, (void*)Escritor, 0);
printf("Creando lector %d\\n", i+1);
pthread_create(&lector[i], 0, (void*)Lector, 0);
}
for(i=0;i<3; i++){
pthread_join(escritor[i], 0);
pthread_join(lector[i], 0);
}
pthread_mutex_destroy(&mutex);
pthread_mutex_destroy(&mutex_lectores);
pthread_exit(0);
}
void* Escritor(void* args){
FILE* f;
pthread_mutex_lock(&mutex);
if((f=fopen("ficheroAct4.txt", "a"))==0){
printf("ERROR. Al abrir el fichero para escribir.\\n\\n");
exit(-1);
}
printf("El escritor va a modificar el dato %d\\n", dato);
fprintf(f, "Escribo con dato %d \\n", dato);
dato=dato+2;
printf("El escritor ha modificado el dato %d\\n", dato);
fclose(f);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void* Lector(void* args){
FILE * f;
char c;
pthread_mutex_lock(&mutex_lectores);
n_lectores++;
if(n_lectores == 1){
pthread_mutex_lock(&mutex);
}
if((f=fopen("ficheroAct4.txt", "r"))==0){
printf("ERROR. Al abrir el fichero para escribir.\\n\\n");
exit(-1);
}
printf("\\nEL FICHERO ES ASI:\\n\\n");
while((c=fgetc(f))!=EOF){
printf("%c", c);
}
printf("\\nFIN DEL FICHERO\\n\\n");
fclose(f);
printf("EL lector ha leido el dato %d\\n", dato);
n_lectores--;
if(n_lectores == 0){
pthread_mutex_unlock(&mutex);
}
pthread_mutex_unlock(&mutex_lectores);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int waitCars[2];
int NumOfCars;
int counter;
pthread_mutex_t waitCars_mtx;
pthread_mutex_t enter_bridge_mtx[2];
void enter_bridge ( int dir ) {
NumOfCars++;
waitCars[dir]--;
counter++;
if ( waitCars[dir] > 0 && counter < 50 && NumOfCars < 100 ) {
pthread_mutex_unlock ( &enter_bridge_mtx[dir] );
}
}
void exit_bridge ( int dir ) {
int ndir;
NumOfCars--;
if ( waitCars[dir] > 0 && counter < 50 ) {
pthread_mutex_unlock ( &enter_bridge_mtx[dir] );
}else if ( NumOfCars == 0 ) {
counter = 0;
ndir = dir^1;
if ( waitCars[ndir] > 0 ) {
pthread_mutex_unlock( &enter_bridge_mtx[ndir] );
}else if ( waitCars[dir] > 0 ) {
pthread_mutex_unlock ( &enter_bridge_mtx[dir] );
}
}
}
void *car ( void *arg ) {
int dir;
dir = *(int *)arg;
pthread_mutex_lock ( &waitCars_mtx );
waitCars[dir]++;
if ( NumOfCars > 0 ) {
pthread_mutex_unlock ( &waitCars_mtx );
pthread_mutex_lock ( &enter_bridge_mtx[dir] );
}
enter_bridge ( dir );
pthread_mutex_unlock ( &waitCars_mtx );
sleep(1);
printf("On bridge with dir: %d,NumOfCars: %d\\n", dir, NumOfCars);
pthread_mutex_lock ( &waitCars_mtx );
exit_bridge ( dir );
pthread_mutex_unlock ( &waitCars_mtx );
return 0;
}
int init () {
int i;
for ( i = 0; i < 2; i++ ) {
waitCars[i] = 0;
}
NumOfCars = 0;
counter = 0;
for ( i = 0; i < 2; i++ ) {
if ( pthread_mutex_init ( &enter_bridge_mtx[i], 0 ) != 0 ) {
printf("\\n create_mutex init failed\\n");
return 1;
}else {
pthread_mutex_lock ( &enter_bridge_mtx[i] );
}
}
if ( pthread_mutex_init ( &waitCars_mtx, 0 ) != 0 ) {
printf("\\n create_mutex init failed\\n");
return 1;
}
return 0;
}
int main ( int argc, char *argv[] ) {
pthread_t thread;
int check_init,left_dir,right_dir;
char ch[2];
left_dir = 1;
right_dir = 0;
check_init = init();
if ( check_init == 1 ) {
printf("Init Stop With Error.\\n");
return 1;
}
ch[1] = '\\0';
do {
ch[0] = getchar();
if ( ch[0] == '1' ){
pthread_create ( &thread, 0, car, (void *)&left_dir );
}else if ( ch[0] == '0' ) {
pthread_create ( &thread, 0, car, (void *)&right_dir );
}
}while ( 1 );
return 0;
}
| 0
|
#include <pthread.h>
{
unsigned char valor;
unsigned char tomado;
pthread_mutex_t mutex;
pthread_cond_t esperoPar;
} numero_t;
numero_t arreglo[20/2];
pthread_t hilos[20];
int numeroAleatorio(int rango){
return ((rand()) % rango);
}
void arregloAleatorio(){
int i;
for(i = 0; i < (20/2); i++){
arreglo[i].valor = i;
arreglo[i].tomado = 0;
pthread_mutex_init(&arreglo[i].mutex, 0);
pthread_cond_init(&arreglo[i].esperoPar, 0);
}
}
void *buscoHiloPar(void *args){
int numeroHilo = *(int *)args;
int posicion = numeroAleatorio(20/2);
while(arreglo[posicion].tomado >= 2){
posicion = numeroAleatorio(20/2);
}
arreglo[posicion].tomado++;
printf("Hilo %d tiene número %d.\\n", numeroHilo, arreglo[posicion].valor);
pthread_cond_signal(&arreglo[posicion].esperoPar);
pthread_mutex_lock(&arreglo[posicion].mutex);
pthread_cond_wait(&arreglo[posicion].esperoPar, &arreglo[posicion].mutex);
pthread_mutex_unlock(&arreglo[posicion].mutex);
pthread_cond_signal(&arreglo[posicion].esperoPar);
printf("El número %d está libre (Hilo %d)\\n", arreglo[posicion].valor, numeroHilo);
pthread_exit((void *) 0);
}
int main (void){
srand(getpid());
arregloAleatorio();
int i;
for(i = 0; i < 20; i++){
pthread_create(&hilos[i], 0, &buscoHiloPar, (void *)&i);
usleep(500000);
}
for(i = 0; i < 20; i++){
pthread_join(hilos[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
struct pub {
unsigned int mugs;
unsigned int clients;
};
struct pub my_pub;
pthread_mutex_t mug_mutex;
pthread_mutex_t bar_mutex;
pthread_cond_t mugs_cond;
void *visit_pub_cond(unsigned int *arg) {
unsigned int th_num = *arg;
int k;
printf("Moje ID %d; Wchodze do pubu\\n", th_num);
for (k = 1; k < 3; k++) {
printf("Moje ID %d; Chce pobrac kufel %d \\n", th_num, k);
for (;;) {
pthread_mutex_lock(&mug_mutex);
while (my_pub.mugs == 0) {
pthread_cond_wait(&mugs_cond, &mug_mutex);
printf("Moje ID %d; Nie ma kufli, poczekam\\n", th_num);
}
my_pub.mugs--;
printf("Moje ID %d; Mam kufel, ide do kranu\\n", th_num);
pthread_mutex_unlock(&mug_mutex);
pthread_mutex_lock(&bar_mutex);
printf("Moje ID %d; Mam kran, nalewam piwo\\n", th_num);
sleep(1);
pthread_mutex_unlock(&bar_mutex);
printf("Moje ID %d; Pije piwo\\n", th_num);
sleep(6);
printf("Moje ID %d; Wypilem. oddaje kufel\\n", th_num);
pthread_mutex_lock(&mug_mutex);
my_pub.mugs++;
pthread_cond_broadcast(&mugs_cond);
pthread_mutex_unlock(&mug_mutex);
break;
}
}
printf("Moje ID %d; Upilem sie. Wychodze z baru.\\n", th_num);
return 0;
}
void *visit_pub(unsigned int *arg) {
unsigned int th_num = *arg;
int success = 0;
int k;
printf("Moje ID %d; Wchodze do pubu\\n", th_num);
for (k = 1; k < 3; k++) {
printf("Moje ID %d; Chce pobrac kufel %d \\n", th_num, k);
for (;;) {
pthread_mutex_lock(&mug_mutex);
if (my_pub.mugs > 0) {
success = 1;
my_pub.mugs--;
}
pthread_mutex_unlock(&mug_mutex);
if (success == 1) {
success = 0;
printf("Moje ID %d; Mam kufel, czekam na kran\\n", th_num);
pthread_mutex_lock(&bar_mutex);
printf("Moje ID %d; Mam kran, nalewam piwo\\n", th_num);
sleep(3);
pthread_mutex_unlock(&bar_mutex);
printf("Moje ID %d; Pije piwo\\n", th_num);
sleep(10);
printf("Moje ID %d; Wypilem. oddaje kufel\\n", th_num);
pthread_mutex_lock(&mug_mutex);
my_pub.mugs++;
pthread_mutex_unlock(&mug_mutex);
break;
} else {
}
}
}
printf("Moje ID %d; Upilem sie. Wychodze z baru.\\n", th_num);
return 0;
}
int main() {
int * tab_clients;
unsigned int i;
printf("\\nLiczba klientow: "); scanf("%d", &my_pub.clients);
printf("\\nLiczba kufli: "); scanf("%d", &my_pub.mugs);
pthread_t tid_vector[my_pub.clients];
pthread_mutex_init(&mug_mutex, 0);
tab_clients = (int *) malloc(my_pub.clients*sizeof(int));
for (i = 0; i < my_pub.clients; i++) {
tab_clients[i] = i;
}
for (i = 0; i < my_pub.clients; i++) {
pthread_create(&tid_vector[i], 0, visit_pub_cond, &tab_clients[i]);
}
for (i = 0; i < my_pub.clients; i++) {
pthread_join(tid_vector[i], 0);
}
pthread_mutex_destroy(&mug_mutex);
return 0;
}
| 0
|
#include <pthread.h>
void print_sched(int policy){
switch(policy){
case SCHED_FIFO:
printf("SCHED_FIFO\\n");
break;
case SCHED_RR:
printf("SCHED_RR\\n");
break;
case SCHED_OTHER:
printf("SCHED_OTHER\\n");
break;
default:
printf("unknown\\n");
}
}
int int_sched(char* policy){
if (!strcmp("SCHED_FIFO", policy)) return SCHED_FIFO;
if (!strcmp("SCHED_RR", policy)) return SCHED_RR;
if (!strcmp("SCHED_NORMAL", policy)) return SCHED_NORMAL;
printf("Invalid policy");
return -1;
}
void setpriority(pthread_t *thr, int newpolicy, int newpriority){
int policy, ret;
struct sched_param param;
if(newpriority > sched_get_priority_max(newpolicy) ||
newpriority < sched_get_priority_min(newpolicy)){
printf("Invalid priority: MIN: %d, MAX: %d", sched_get_priority_min(newpolicy), sched_get_priority_max(newpolicy));
}
pthread_getschedparam(*thr, &policy, ¶m);
param.sched_priority = newpriority;
ret = pthread_setschedparam(*thr, newpolicy, ¶m);
pthread_getschedparam(*thr, &policy, ¶m);
print_sched(policy);
if (ret != 0){
perror("perror(): ");
}
}
char *pointer;
pthread_mutex_t lock;
struct threadParameters {
char letter;
int numberCharacters;
int policy;
int priority;
};
void *thread_func(void *context) {
struct threadParameters *args = (struct threadParameters*)context;
pthread_t *t = (pthread_t*)pthread_self();
setpriority(t, args->policy, args->priority);
while(args->numberCharacters != 0) {
pthread_mutex_lock(&lock);
*pointer = args->letter;
pointer ++;
pthread_mutex_unlock(&lock);
args->numberCharacters --;
}
free(context);
return 0;
}
char* removeDup(char * str, int n) {
int len = n;
int k = 0;
int i=1;
for (i; i< len; i++){
if (str[i-1] != str[i]) {
str[k++] = str[i-1];
}
}
str[k++] = str[i-1];
str[k] = '\\0';
return str;
}
int main(int argc, char **argv){
char letters[10] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};
if (argc < 4){
printf("Missing parameters");
exit(0);
}
int numberThreads = atoi(argv[1]);
int bufferSize = atoi(argv[2])*1024;
int policy = int_sched(argv[3]);
printf("%d", policy);
char priority = atoi(argv[4]);
int numberCharacters = bufferSize/numberThreads;
char *buffer = malloc(bufferSize*sizeof(char));
pointer = buffer;
if (pthread_mutex_init(&lock, 0) != 0) {
printf("\\n mutex init failed\\n");
return 1;
}
pthread_t threads[numberThreads];
struct threadParameters *context;
for(int i=0; i<numberThreads; i++) {
context = malloc(sizeof(struct threadParameters));
context->letter = letters[i];
context->numberCharacters = numberCharacters;
context->priority = priority;
context->policy = policy;
pthread_create(&(threads[i]), 0, thread_func, (void*) context);
}
for(int i=0; i<numberThreads; i++) {
pthread_join(threads[i], 0);
}
pthread_mutex_destroy(&lock);
buffer[bufferSize-1] = '\\0';
printf("%s \\n", buffer);
char *noDuplicates = removeDup(buffer, bufferSize);
printf("%s \\n", noDuplicates);
int counts[numberThreads];
memset(counts, 0, numberThreads*sizeof(int));
int i;
size_t len = strlen(noDuplicates);
for (i = 0; i < len; i++) {
counts[noDuplicates[i]-65]++;
}
for (i = 0; i < numberThreads; i++) {
printf("%c = %d \\n", letters[i], counts[i]);
}
free(buffer);
return 0;
}
| 1
|
#include <pthread.h>
void *odd_func();
void *even_func();
pthread_mutex_t num_mutex;
int buf;
int flag=0;
int main()
{
pthread_t odd_th,even_th;
void *thread_result;
pthread_mutex_init(&num_mutex, 0);
pthread_create(&odd_th, 0, odd_func, 0);
pthread_create(&even_th, 0, even_func, 0);
pthread_mutex_lock(&num_mutex);
printf("Input number. Enter 999 to finish\\n");
while(!flag)
{
scanf("%d",&buf);
pthread_mutex_unlock(&num_mutex);
printf("main mutex unlock\\n");
while(1)
{
pthread_mutex_lock(&num_mutex);
if(buf != 0)
{
pthread_mutex_unlock(&num_mutex);
sleep(1);
}
else
break;
}
}
pthread_mutex_unlock(&num_mutex);
printf("\\nWaiting for thread to finish...\\n");
pthread_join(odd_th, &thread_result);
pthread_join(even_th, &thread_result);
printf("thread joined\\n");
pthread_mutex_destroy(&num_mutex);
exit(0);
}
void *odd_func()
{
sleep(1);
pthread_mutex_lock(&num_mutex);
{
while(buf != 999)
{
if(buf%2==1 && buf !=0)
{
printf("odd number! %d + 1 = %d\\n",buf, buf+1);
buf = 0;
pthread_mutex_unlock(&num_mutex);
sleep(1);
pthread_mutex_lock(&num_mutex);
while(buf == 0)
{
pthread_mutex_unlock(&num_mutex);
sleep(1);
pthread_mutex_lock(&num_mutex);
}
buf = 0;
pthread_mutex_unlock(&num_mutex);
}
else
{
pthread_mutex_unlock(&num_mutex);
}
}
}
flag = 1;
pthread_exit(0);
}
void *even_func()
{
sleep(1);
pthread_mutex_lock(&num_mutex);
while(buf != 999)
{
if(buf%2==0 && buf !=0)
{
printf("even number! %d + 1 = %d\\n",buf, buf+1);
buf = 0;
pthread_mutex_unlock(&num_mutex);
sleep(1);
pthread_mutex_lock(&num_mutex);
while(buf == 0)
{
pthread_mutex_unlock(&num_mutex);
sleep(1);
pthread_mutex_lock(&num_mutex);
}
buf = 0;
pthread_mutex_unlock(&num_mutex);
}
else
{
pthread_mutex_unlock(&num_mutex);
}
}
flag = 1;
pthread_exit(0);
}
| 0
|
#include <pthread.h>
char *matrica;
int m,n;
int pocetak, kraj, stupac;
} thr_struct;
thr_struct *nova;
pthread_mutex_t lock;
pthread_barrier_t barijera;
void* thr_f( void* arg )
{
int pocetak = ( (thr_struct*) arg )->pocetak;
int kraj = ( (thr_struct*) arg )->kraj;
int stupac = ( (thr_struct*) arg )->stupac;
int k,l;
for(k=pocetak; k<=kraj; ++k)
if(matrica[k] == 'o')
{
pthread_mutex_lock(&lock);
printf("(%d,%d)\\n", k/stupac,k%stupac);
pthread_mutex_unlock(&lock);
}
pthread_barrier_wait(&barijera);
return 0;
}
void ucitaj (int redci, int stupci, char *ime_datoteke, char *x)
{
int i, k=0;
char znak;
FILE *matrice_file;
matrice_file = fopen(ime_datoteke, "r");
for (i=0; i<redci*stupci+stupci-1; ++i)
{
fscanf(matrice_file, "%c", &znak);
if(znak == '.' || znak == 'o')
x[k++]=znak;
}
fclose(matrice_file);
}
int main(int argc, char **argv)
{
struct timeval stop, start;
struct timeval stop1, start1;
gettimeofday(&start, 0);
if (argc != 5)
{
fprintf(stderr, "Greska pri upisu komandne linije:\\n%s \\n", argv[0]);
exit(1);
}
char *ime_datoteke;
int i, broj_dretvi, duljina;
broj_dretvi = atoi(argv[1]);
m = atoi(argv[2]);
n = atoi(argv[3]);
ime_datoteke = argv[4];
duljina = m*n;
matrica = (char*)malloc(duljina*sizeof(char));
ucitaj(m, n, ime_datoteke, matrica);
pthread_t *thr_idx;
pthread_barrier_init(&barijera, 0, broj_dretvi);
if ((thr_idx = (pthread_t *) calloc(broj_dretvi, sizeof(pthread_t))) == 0)
{
fprintf(stderr, "%s: memory allocation error (greska kod alokacije dretvi)\\n", argv[0]);
exit(1);
}
nova = (thr_struct*)malloc(broj_dretvi*sizeof(thr_struct));
gettimeofday(&start1, 0);
for (i = 0; i < broj_dretvi; ++i)
{
nova[i].pocetak = ((i*m*n)/broj_dretvi);
nova[i].kraj = (((i+1)*m*n)/broj_dretvi)-1;
nova[i].stupac = n;
if (pthread_create(&thr_idx[i], 0, thr_f,(void*)&nova[i]))
{
printf( "%s: error creating thread %d\\n", argv[0], i);
exit(1);
}
}
if (pthread_join(thr_idx[0], 0))
{
fprintf(stderr, "%s: error joining thread 0\\n", argv[0]);
exit(1);
}
gettimeofday(&stop1, 0);
pthread_barrier_destroy(&barijera);
free(thr_idx);
free(matrica);
free(nova);
gettimeofday(&stop, 0);
long unsigned sec = stop.tv_sec-start.tv_sec, usec;
if(stop.tv_usec > start.tv_usec)
usec = stop.tv_usec - start.tv_usec;
else
{
usec = 1000000-start.tv_usec+stop.tv_usec;
sec--;
}
printf("\\nukupan program sec: %lu, usec: %lu\\n", sec, usec);
long unsigned sec1 = stop1.tv_sec-start1.tv_sec, usec1;
if(stop1.tv_usec > start1.tv_usec)
usec1 = stop1.tv_usec - start1.tv_usec;
else
{
usec1 = 1000000-start1.tv_usec+stop1.tv_usec;
sec1--;
}
printf("dretve sec: %lu, usec: %lu\\n", sec1, usec1);
return 0;
}
| 1
|
#include <pthread.h>
char* prog_name;
int thread_count;
int max_thread_count;
char* key;
int key_length;
pthread_mutex_t lock;
long get_file_size(FILE* f){
long current_position = ftell(f);
fseek(f, 0, 2);
int result = ftell(f);
fseek(f, current_position, 0);
return result;
}
void read_key(char* key_file){
FILE* f = fopen(key_file, "rb");
key_length = get_file_size(f);
key = (char*) malloc(key_length);
fread(key, 1, key_length, f);
fclose(f);
}
void* cipher_file(void *arg){
char* file_name = (char*) arg;
FILE* f = fopen(file_name, "rb");
int file_size = get_file_size(f);
if(file_size == -1)
return 0;
char* buffer;
buffer = (char*) calloc(file_size, 1);
fread(buffer, 1, file_size, f);
fclose(f);
int i = 0;
int j = 0;
while(i < file_size){
buffer[i++] ^= key[j++];
if(j == key_length)
j = 0;
}
f = fopen(file_name, "wb");
fwrite(buffer, 1, file_size, f);
fclose(f);
printf("%u %s %d\\n", syscall(SYS_gettid), file_name, file_size);
pthread_mutex_lock(&lock);
thread_count--;
pthread_mutex_unlock(&lock);
return 0;
}
int cipher_dir(char* path)
{
DIR* dir;
struct dirent* dir_rec;
struct stat file_stat;
if ((dir = opendir(path)) == 0 )
{
fprintf(stderr, "%s: %s (%s)\\n", prog_name, strerror(errno), path);
return 2;
}
while ((dir_rec = readdir(dir)) != 0)
{
char* temp_path = (char*) calloc(PATH_MAX, 1);
strcpy(temp_path, path);
if (strlen(temp_path) != 1)
strcat(temp_path, "/");
strcat(temp_path, dir_rec->d_name);
if (lstat(temp_path, &file_stat) == -1)
{
fprintf(stderr, "%s: %s (%s)\\n", prog_name, strerror(errno), temp_path);
continue;
}
if (!(strcmp(dir_rec->d_name, "..")) || !(strcmp(dir_rec->d_name, ".")))
continue;
switch (file_stat.st_mode & S_IFMT)
{
case S_IFREG:
while(thread_count >= max_thread_count);
pthread_t thread;
int error_number;
if((error_number = pthread_create(&thread, 0, cipher_file, temp_path)) > 0){
fprintf(stderr, "%s: %s (%s)\\n", prog_name, strerror(error_number), path);
return 1;
}
else{
pthread_mutex_lock(&lock);
thread_count++;
pthread_mutex_unlock(&lock);
}
break;
case S_IFDIR:
if (cipher_dir(temp_path) == 1)
return 1;
break;
default:
break;
}
}
if (closedir(dir) == -1)
{
perror(prog_name);
}
return 0;
}
int main(int argc, char* argv[])
{
thread_count = 1;
prog_name = basename(argv[0]);
if (argc < 4)
{
fprintf(stderr, "%s: Too few arguments\\n", prog_name);
return 1;
}
read_key(argv[2]);
max_thread_count = atoi(argv[3]);
char full_path[PATH_MAX];
realpath(argv[1], full_path);
pthread_mutex_init(&lock, 0);
if (cipher_dir(full_path) == 1)
{
fprintf(stderr, "%s: Error in cipher\\n", prog_name);
return 1;
}
sleep(1);
pthread_mutex_destroy(&lock);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gateaux_prets = PTHREAD_COND_INITIALIZER;
int gateaux = 0;
int stop = 0;
void* enfant(void *arg) {
int id = *((int*) arg);
int mange = 0;
while(1) {
pthread_mutex_lock(&mutex);
while(gateaux == 0) {
if (stop == 1) {
pthread_mutex_unlock(&mutex);
goto fin;
}
pthread_mutex_unlock(&mutex);
usleep(100000);
pthread_mutex_lock(&mutex);
}
if (gateaux > 0) {
gateaux--;
mange++;
printf("L'enfant %d a mangé un gateau\\n", id);
} else {
printf("L'enfant %d n'a pas eu de gateau\\n", id);
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
fin :
return *((void**) &mange);
}
void* parent(void *arg) {
int i;
for (i = 0; i < 4; i++) {
pthread_mutex_lock(&mutex);
gateaux += 4;
printf("Le parent a préparé des gateaux\\n");
pthread_mutex_unlock(&mutex);
sleep(2);
}
pthread_mutex_lock(&mutex);
stop = 1;
pthread_mutex_unlock(&mutex);
return 0;
}
int main() {
int i, nb[5];
void* ret[5];
pthread_t tid[5 + 1];
for (i = 0; i < 5; i++) {
nb[i] = i;
pthread_create(&tid[i], 0, enfant, (void*) &nb[i]);
}
pthread_create(&tid[i], 0, parent, 0);
for (i = 0; i < 5; i++) {
pthread_join(tid[i], &ret[i]);
printf("L'enfant %d a mangé %d gateaux\\n", i, *((int*) &ret[i]));
}
pthread_join(tid[i], 0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
pthread_t tid[6];
int global_count = 0;
int counter;
pthread_mutex_t lock;
void calculate(){
double pi;
pi = 4* (double)global_count/(double)3500;
printf("\\nglobal count = %d , rand times = %d\\n",global_count,3500);
printf("\\n\\033[1;41mpi is %2.6f\\033[m\\n",pi);
exit(1);
}
void* doSomeThing(void *arg){
pthread_mutex_lock(&lock);
int i,s;
int count = 0;
counter = counter + 1;
printf("\\n\\033[1;33mWaiting for Thread %d ....\\033[m\\n",counter);
sleep(1);
printf("\\n\\033[1;34mThread %d starting ...\\033[m\\n",counter);
sleep(1);
for(i=0;i<3500;i++){
double x,y,dist;
int radius = 1;
x = ((double)rand()/(32767));
y = ((double)rand()/(32767));
dist = pow(x-0,2) + pow(y-0,2);
if(dist <= radius)
count++;
}
printf("\\n\\033[1;33mWainting for Thread %d random ... \\033[m\\n",counter);
sleep(1);
printf("\\n\\033[1;32mThread %d count = %d\\033[m\\n",counter,count);
sleep(1);
global_count = count;
for(s = 3; s >= 1; s--){
if(s >= 1)
sleep(1);
printf("\\n\\033[1;31mPress Ctrl-C? sec:%d\\033[m\\n",s);
}
printf("\\n\\033[1;34mThread %d finished\\033[m\\n",counter);
pthread_mutex_unlock(&lock);
return 0;
}
int main(void){
int error;
int i=0,j=0;
signal(SIGINT,calculate);
if(pthread_mutex_init(&lock, 0) != 0){
printf("\\nmutex init failed\\n");
return 1;
}
printf("\\033[1;41m -------------- This is 6 Threads program --------------\\033[m\\n");
while(i < 6){
error = pthread_create(&(tid[i]), 0, &doSomeThing, 0);
if(error != 0)
printf("can't create thread\\n");
else
printf("\\nThread %d create sucessfully\\n",i+1);
i++;
}
while(j < 6){
pthread_join(tid[j], 0);
j++;
}
pthread_mutex_destroy(&lock);
calculate();
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
void * writer(void *p)
{
printf("\\n %s: \\n",__func__);
if(pthread_mutex_lock(&mutex)==0)
{
printf(" Writer: lock acquired\\n");
if(pthread_mutex_lock(&mutex)==0)
printf("\\n Recursive lock attempt succeded \\n");
printf(" updating commits .......\\n");
sleep(2);
printf(" Done : exit from mutex block\\n");
pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void * reader(void *p)
{
printf("\\n %s: \\n",__func__);
sleep(2);
if(pthread_mutex_lock(&mutex)==0)
{
printf(" Reader : lock acquired\\n");
printf(" Reading updates ...... \\n");
sleep(2);
printf(" Done: exit from mutex block \\n");
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main ()
{
pthread_t tcb1,tcb2;
pthread_mutexattr_t attr;
int rv;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutex,&attr);
rv = pthread_create(&tcb1, 0, writer, 0);
if(rv)
puts("Failed to create thread");
rv = pthread_create(&tcb2, 0, reader, 0);
if(rv)
puts("Failed to create thread");
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
int data = 0;
void *thread1(void *arg)
{
pthread_mutex_lock(&mutex);
data++;
printf ("t1: data %d\\n", data);
pthread_mutex_unlock(&mutex);
return 0;
}
void *thread2(void *arg)
{
pthread_mutex_lock(&mutex);
data+=2;
printf ("t2: data %d\\n", data);
pthread_mutex_unlock(&mutex);
return 0;
}
void *thread3(void *arg)
{
pthread_mutex_lock(&mutex);
printf ("t3: data %d\\n", data);
__VERIFIER_assert (0 <= data);
__VERIFIER_assert (data < 10 + 3);
pthread_mutex_unlock(&mutex);
return 0;
}
int main()
{
pthread_mutex_init(&mutex, 0);
pthread_t t1, t2, t3;
data = __VERIFIER_nondet_int (0, 10);
printf ("m: MIN %d MAX %d data %d\\n", 0, 10, data);
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(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
static float * polygon_x;
static float * polygon_y;
static pthread_mutex_t * polygon_lock;
static int * contact_p1;
static int * contact_p2;
static float * contact_n_x;
static float * contact_n_y;
static float * contact_penetration;
static int * contact_used_flag;
static int num_contacts, num_polygons, num_threads;
static void * updateBodies(void * r) {
register int i;
register long rank = (long) r;
for(i = rank; i < num_contacts; i += num_threads) {
if(contact_used_flag[i] == 1) {
float half_pen = contact_penetration[i]/2;
float dx = contact_n_x[i] * half_pen;
float dy = contact_n_y[i] * half_pen;
int p1 = contact_p1[i];
int p2 = contact_p2[i];
pthread_mutex_lock(&polygon_lock[p1]);
polygon_x[p1] += dx;
polygon_y[p1] += dy;
pthread_mutex_unlock(&polygon_lock[p1]);
pthread_mutex_lock(&polygon_lock[p2]);
polygon_x[p2] -= dx;
polygon_y[p2] -= dy;
pthread_mutex_unlock(&polygon_lock[p2]);
}
}
return 0;
}
extern void pthread_init(float * p_x, float * p_y, int * c_p1, int * c_p2, float * c_n_x, float * c_n_y, float * c_p, int * c_u_f, int n_polygons, int n_contacts, int n_threads){
register int i;
pthread_t * update_threads;
polygon_x = p_x;
polygon_y = p_y;
contact_p1 = c_p1;
contact_p2 = c_p2;
contact_n_x = c_n_x;
contact_n_y = c_n_y;
contact_penetration = c_p;
contact_used_flag = c_u_f;
num_polygons = n_polygons;
num_contacts = n_contacts;
num_threads = n_threads;
polygon_lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t*) * num_polygons);
update_threads = malloc((num_threads - 1) * sizeof(pthread_t));
for(i = 0; i < num_polygons; i++){
pthread_mutex_init(&polygon_lock[i], 0);
}
for(i = 0; i < num_threads-1; i++) {
long rank = i+1;
pthread_create(&update_threads[i], 0, updateBodies, (void *)(rank));
}
updateBodies(0);
if(num_threads > 1)
for(i = 0; i < num_threads-1; i++) {
pthread_join(update_threads[i], 0);
}
}
| 1
|
#include <pthread.h>
int
explor(char *dirname, bool top) {
char *lom = "/";
DIR *d;
struct dirent *de;
char *name;
struct stat stats;
if ((d = opendir(dirname)) == 0) {
warn("%s", dirname);
exit(-1);
}
errno = 0;
while ((de = readdir(d)) != 0) {
if (de->d_name[0] == '.')
continue;
name = (char *)
malloc(2 + strlen(dirname) + strlen(de->d_name));
strcpy(name, dirname);
strcat(name, lom);
strcat(name, de->d_name);
if (stat(name, &stats) < 0)
errx(2, "problem with stat on file %s\\n", name);
if (S_ISDIR(stats.st_mode))
explor(name, 0);
else {
pthread_mutex_lock(arrmut);
add(name);
pthread_cond_broadcast(empty);
pthread_mutex_unlock(arrmut);
}
if (errno != 0)
warn("%s", name);
}
if (top) {
end = 1;
pthread_cond_broadcast(empty);
}
closedir(d);
return (1);
}
void *
thr_run(void *x) {
pthread_mutex_lock(arrmut);
while (!(end && (ind == -1))) {
while ((ind < 0) && !end)
pthread_cond_wait(empty, arrmut);
if (ind < 0) {
pthread_mutex_unlock(arrmut);
break;
}
char *src = get_src();
pthread_mutex_unlock(arrmut);
if (mapon)
msearch(src);
else
search(src);
free(src);
pthread_mutex_lock(arrmut);
}
pthread_mutex_unlock(arrmut);
return (0);
}
void
add(char *name) {
++ind;
names = (char **) realloc(names, (ind+1)*(sizeof (char *)));
names[ind] = name;
}
char *
get_src() {
char *result = names[ind];
--ind;
return (result);
}
| 0
|
#include <pthread.h>
pthread_mutex_t ANS_mutex;
int ANS[4][4];
int X[4][4] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
int Y[4][4] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
void *mul(void *index)
{
long i=(long)index;
long j,k;
for(j=0;j<4;j++)
{
ANS[i][j]=0;
for(k=0;k<4;k++)
{
if(pthread_mutex_lock(&ANS_mutex)==0)
{
ANS[i][j]+=X[i][k]*Y[k][j];
pthread_mutex_unlock(&ANS_mutex);
}
}
}
pthread_exit(0);
}
int main()
{
long i,j;
pthread_t th[4];
for(i=0;i<4;i++)
{
pthread_create(&th[i],0,&mul,(void*)i);
}
for(i=0;i<4;i++)
{
pthread_join(th[i],0);
}
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
printf("%d\\t",ANS[i][j]);
}
printf("\\n");
}
exit(0);
}
| 1
|
#include <pthread.h>
const char * thread_outgoing_reader_tslogid = "outgoing_reader";
void * thread_outgoing_reader (void * arg)
{
tslog(0, thread_outgoing_reader_tslogid, "Started.");
struct thread_outgoing_synchroblock * synchroblock = arg;
int code;
do
{
tslog(0, thread_outgoing_reader_tslogid, "Signalling that we are a ready and waiting for socket fd.");
pthread_mutex_lock(&(synchroblock->mutex));
synchroblock->ready_reader = 1;
pthread_cond_broadcast(&(synchroblock->ready_cond));
while (!synchroblock->socket_ready)
{
pthread_cond_wait(&(synchroblock->socket_cond), &(synchroblock->mutex));
}
int fd = synchroblock->socket_fd;
pthread_mutex_unlock(&(synchroblock->mutex));
tslog(0, thread_outgoing_reader_tslogid, "typa, rabotaem...");
code = -1; usleep(7000000);
if (code == -1)
{
tslog(0, thread_outgoing_reader_tslogid, "typa, error...");
pthread_cond_broadcast(&(synchroblock->error_cond));
usleep(1000000);
continue;
}
} while (1);
}
| 0
|
#include <pthread.h>
pthread_mutex_t barrier;
pthread_cond_t go;
int numWorkers;
int numArrived = 0;
void Barrier() {
pthread_mutex_lock(&barrier);
numArrived++;
if (numArrived == numWorkers) {
numArrived = 0;
pthread_cond_broadcast(&go);
} else
pthread_cond_wait(&go, &barrier);
pthread_mutex_unlock(&barrier);
}
int size, stripSize;
int sums[4];
int matrix[10000][10000];
void *Worker(void *);
int main(int argc, char *argv[]) {
int i, j;
pthread_attr_t attr;
pthread_t workerid[4];
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
pthread_mutex_init(&barrier, 0);
pthread_cond_init(&go, 0);
size = atoi(argv[1]);
numWorkers = atoi(argv[2]);
stripSize = size/numWorkers;
for (i = 0; i < size; i++)
for (j = 0; j < size; j++)
matrix[i][j] = 1;
for (i = 0; i < numWorkers; i++)
pthread_create(&workerid[i], &attr, Worker, (void *) i);
pthread_exit(0);
}
void *Worker(void *arg) {
int myid = (int) arg;
int total, i, j, first, last;
printf("worker %d (pthread id %d) has started\\n", myid, pthread_self());
first = myid*stripSize;
last = first + stripSize - 1;
total = 0;
for (i = first; i <= last; i++)
for (j = 0; j < size; j++)
total += matrix[i][j];
sums[myid] = total;
Barrier();
if (myid == 0) {
total = 0;
for (i = 0; i < numWorkers; i++)
total += sums[i];
printf("the total is %d\\n", total);
}
}
| 1
|
#include <pthread.h>
int
rw_init(struct rw_lock_t *rw)
{
struct rw_lock_t temp={0,0,PTHREAD_MUTEX_INITIALIZER,PTHREAD_MUTEX_INITIALIZER,PTHREAD_COND_INITIALIZER,PTHREAD_MUTEX_INITIALIZER,PTHREAD_COND_INITIALIZER};
*rw=temp;
if (rw->readers == 0 && rw->writers == 0)
return 0;
else
return 1;
}
int
rw_destroy(struct rw_lock_t *rw)
{
pthread_cond_destroy(&rw->WriterCondition);
pthread_cond_destroy(&rw->ReaderCondition);
pthread_mutex_destroy(&rw->WriterConditionMutex);
pthread_mutex_destroy(&rw->WriterMutex);
pthread_mutex_destroy(&rw->ReaderConditionMutex);
free(rw);
return 0;
}
int
rw_readlock(struct rw_lock_t *rw)
{
if (rw->readers < 0) {
printf("READER PANIC: %d\\n", rw->readers);
exit(2);
}
pthread_mutex_lock(&rw->WriterConditionMutex);
while(rw->writers > 0) {
pthread_cond_wait(&rw->WriterCondition, &rw->WriterConditionMutex);
}
pthread_mutex_unlock(&rw->WriterConditionMutex);
pthread_mutex_lock(&rw->ReaderConditionMutex);
rw->readers++;
pthread_mutex_unlock(&rw->ReaderConditionMutex);
return 0;
}
int
rw_readunlock(struct rw_lock_t *rw)
{
if (rw->readers < 0) {
printf("READER PANIC\\n");
exit(2);
}
pthread_mutex_lock(&rw->ReaderConditionMutex);
rw->readers--;
if (rw->readers == 0) {
pthread_cond_broadcast(&rw->ReaderCondition);
}
pthread_mutex_unlock(&rw->ReaderConditionMutex);
return 0;
}
int
rw_writelock(struct rw_lock_t *rw)
{
pthread_mutex_lock(&rw->WriterConditionMutex);
rw->writers++;
if (rw->writers > 2) {
printf("WRITER PANIC\\n");
exit(2);
}
pthread_mutex_unlock(&rw->WriterConditionMutex);
pthread_mutex_lock(&rw->ReaderConditionMutex);
while(rw->readers > 0) {
pthread_cond_wait(&rw->ReaderCondition, &rw->ReaderConditionMutex);
}
pthread_mutex_unlock(&rw->ReaderConditionMutex);
pthread_mutex_lock(&rw->WriterMutex);
return 0;
}
int
rw_writeunlock(struct rw_lock_t *rw)
{
pthread_mutex_lock(&rw->WriterConditionMutex);
rw->writers--;
pthread_mutex_unlock(&rw->WriterConditionMutex);
pthread_mutex_lock(&rw->WriterConditionMutex);
if (rw->writers == 0) {
pthread_cond_broadcast(&rw->WriterCondition);
}
pthread_mutex_unlock(&rw->WriterConditionMutex);
pthread_mutex_unlock(&rw->WriterMutex);
return 0;
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error();
unsigned int __VERIFIER_nondet_uint();
static int top = 0;
static unsigned int arr[400];
pthread_mutex_t m;
_Bool flag = 0;
void error(void)
{
ERROR:
__VERIFIER_error();
return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
top == 0 ? 1 : 0;
}
int push(unsigned int *stack, int x)
{
if (top == 400)
{
printf("stack overflow\\n");
return -1;
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (top == 0)
{
printf("stack underflow\\n");
return -2;
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for (i = 0; i < 400; i++)
{
__CPROVER_assume(((400 - i) >= 0) && (i >= 0));
{
__CPROVER_assume(((400 - i) >= 0) && (i >= 0));
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint() % 400;
if (push(arr, tmp) == (-1))
error();
pthread_mutex_unlock(&m);
}
}
}
}
void *t2(void *arg)
{
int i;
for (i = 0; i < 400; i++)
{
__CPROVER_assume(((400 - i) >= 0) && (i >= 0));
{
pthread_mutex_lock(&m);
if (top > 0)
{
if (pop(arr) == (-2))
error();
}
pthread_mutex_unlock(&m);
}
}
}
int main(void)
{
pthread_t id1;
pthread_t id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 1
|
#include <pthread.h>
struct targs{
int *arr;
ssize_t size;
int *dest;
pthread_mutex_t *write_lock;
pthread_t *id;
bool final;
};
int gcd(int x, int y){
while (x != y){
if (x < y) {
y -= x;
}
else {
x = x - y;
}
}
return x;
}
int lcm(int x, int y){
return (x/gcd(x,y))*y;
}
void *work_thread(void *arg){
struct targs *targs = (struct targs*) arg;
if (targs->size == 1){
*(targs->dest) = targs->arr[0];
}
else {
int acc = lcm(targs->arr[0], targs->arr[1]);
int i;
for (i = 2; i < targs->size; ++i) {
acc = lcm(acc, targs->arr[i]);
}
*(targs->dest) = acc;
}
pthread_mutex_lock(targs->write_lock);
int i;
if (targs->final) {
printf("Final ");
}
printf("Thread %lu: (", *(targs->id));
--targs->size;
for (i = 0; i < targs->size; ++i) {
printf("%i, ", targs->arr[i]);
}
printf("%i)", targs->arr[i]);
printf(" : %s%i\\n", !targs->final ? "LCM = " : "", *(targs->dest));
pthread_mutex_unlock(targs->write_lock);
return 0;
}
int main(int argc, char *argv[]){
if (argc != 3){
printf("Usage: lcm_skeleton <filename>\\n");
return -1;
}
FILE *nums = fopen(argv[1], "r");
int *args = malloc(sizeof(int)*10);
ssize_t args_size = 10;
int i = 0;
while (fscanf(nums, "%d", args + i++) > 0){
if (i >= args_size){
args_size *= 2;
args = realloc(args, sizeof(int)*args_size);
}
}
args_size = --i;
args = realloc(args, sizeof(int)*args_size);
int nthreads;
if (sscanf(argv[2], "%d", &nthreads) <= 0) {
exit(2);
}
pthread_t threads[nthreads];
int perthread = args_size/nthreads;
perthread += nthreads*perthread != args_size;
int result[nthreads];
struct targs *targs[nthreads];
pthread_mutex_t write_lock;
pthread_mutex_init(&write_lock, 0);
for (i = 0; i < nthreads; ++i) {
targs[i] = malloc(sizeof(struct targs));
*targs[i] = (struct targs){args + perthread*i,
perthread,
result + i,
&write_lock,
threads + i,
0};
if (i == (nthreads - 1)) {
targs[i]->size = args_size - perthread*i;
}
pthread_create(threads + i, 0, work_thread, targs[i]);
}
for (i = 0; i < nthreads; ++i) {
pthread_join(threads[i], 0);
free(targs[i]);
}
free(args);
int final;
struct targs final_args = {
result,
nthreads,
&final,
&write_lock,
threads,
1};
pthread_create(threads, 0, work_thread, &final_args);
pthread_join(threads[0], 0);
printf("Final Least Common Multiple: %i\\n", final);
return 0;
}
| 0
|
#include <pthread.h>
int buffer;
int number;
void* consumer(void*);
void* producer(void*);
pthread_mutex_t the_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t signalConsumer = PTHREAD_COND_INITIALIZER;
pthread_cond_t signalProducer = PTHREAD_COND_INITIALIZER;
int main(int argc, char *argv[]) {
if(argv[1] != 0) buffer = atoi(argv[1]);
else {
printf("Enter buffer size as an argument when launching program\\n");
return(0);
}
pthread_t first;
pthread_t secnd;
number = 0;
pthread_create(&first, 0, consumer, 0);
pthread_create(&secnd, 0, producer, 0);
pthread_join(first, 0);
pthread_join(secnd, 0);
printf("All done!\\n");
}
void* producer(void *x) {
while(1) {
pthread_mutex_lock(&the_mutex);
number ++;
printf("Producer: %d\\n", number);
pthread_cond_signal(&signalConsumer);
if (number < buffer) {
pthread_cond_wait(&signalProducer, &the_mutex);
}
pthread_mutex_unlock(&the_mutex);
sleep(1);
if(number >= buffer) {
printf("Producer done\\n");
break;
}
}
}
void* consumer(void *x) {
int printed = 0;
while(1) {
pthread_mutex_lock(&the_mutex);
pthread_cond_signal(&signalProducer);
pthread_cond_wait(&signalConsumer, &the_mutex);
printf("Consumer: %d\\n", number);
pthread_mutex_unlock(&the_mutex);
if(number >= buffer) {
printf("Consumer done\\n");
break;
}
}
}
| 1
|
#include <pthread.h>
static pthread_t thread_handle[YAB_NUM_THREADS];
static pthread_mutex_t thread_mutex[YAB_NUM_THREADS];
static pthread_cond_t thread_cond[YAB_NUM_THREADS];
int YabThreadStart(unsigned int id, void (*func)(void *), void *arg)
{
if (thread_handle[id])
{
fprintf(stderr, "YabThreadStart: thread %u is already started!\\n", id);
return -1;
}
pthread_mutex_init(&thread_mutex[id], 0);
if (pthread_cond_init(&thread_cond[id], 0) != 0)
{
perror("pthread_cond_init");
return -1;
}
if ((errno = pthread_create(&thread_handle[id], 0, (void *)func, arg)) != 0)
{
perror("pthread_create");
return -1;
}
return 0;
}
void YabThreadWait(unsigned int id)
{
if (!thread_handle[id])
return;
pthread_join(thread_handle[id], 0);
thread_handle[id] = 0;
}
void YabThreadYield(void)
{
sched_yield();
}
void YabThreadSleep(void)
{
pthread_t thread;
unsigned int i, id;
id = YAB_NUM_THREADS;
thread = pthread_self();
for(i = 0;i < YAB_NUM_THREADS;i++)
{
if(thread_handle[i] == thread) {
id = i;
}
}
if (id == YAB_NUM_THREADS) return;
pthread_mutex_lock(&thread_mutex[id]);
pthread_cond_wait(&thread_cond[id], &thread_mutex[id]);
pthread_mutex_unlock(&thread_mutex[id]);
}
void YabThreadRemoteSleep(unsigned int id)
{
}
void YabThreadWake(unsigned int id)
{
if (!thread_handle[id])
return;
pthread_mutex_lock(&thread_mutex[id]);
pthread_cond_signal(&thread_cond[id]);
pthread_mutex_unlock(&thread_mutex[id]);
}
| 0
|
#include <pthread.h>
inline void* fetch_mmap(char* file_path)
{
int fd = open(file_path, O_RDWR | O_CREAT);
ftruncate(fd, 512);
void* mem =
mmap(0, 512, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (mem == MAP_FAILED)
printf("Error Mapping !");
printf("Mapped Memory Adrress : %ld \\n", (unsigned long) mem);
close(fd);
return mem;
}
pthread_mutex_t lock;
uint64_t num = 0;
uint64_t MAX = 65535L*65535L*65535L;
void* thread_fun(void* c)
{
int use_less = 1;
while(1) {
pthread_mutex_lock(&lock);
use_less++;
pthread_mutex_unlock(&lock);
if (use_less == 100000000)
break;
}
return 0;
}
struct fd_vector {
uint32_t num;
};
int main()
{
int i = 0;
signal(SIGUSR1, SIG_IGN);
time_t t = time(0);
pthread_mutex_init(&lock,0);
pthread_t tid[2];
for (;i!=2;i++)
pthread_create(&tid[i],0,thread_fun,0);
i = 0;
for (;i!=2;i++)
pthread_join(tid[i],0);
printf("Use[%lus] Every This OK ...",time(0)-t);
printf("\\n%s\\n", "Done !");
return 0;
}
| 1
|
#include <pthread.h>
static const char servoDir[] = "/var/servoDaemon";
int const frequency_hz = 50;
int const servo_range = 1200;
int const servo_mid = 1500;
pthread_t servoThread;
pthread_mutex_t lock;
volatile sig_atomic_t done = 0;
struct listener_struct {
pthread_t tid;
int pipeHandle;
int servo_pulse_width_us;
};
struct listener_struct listener_data[8 + 1];
void term(int signum) {
printf("Signal!");
done = 1;
}
int main() {
printf("servoDaemon\\n");
printf("listens on named pipes %s/servo1 etc\\n", servoDir);
umask(0);
createServoDir();
rc_initialize();
rc_enable_servo_power_rail();
rc_disable_signal_handler();
signal(SIGTERM, term);
signal(SIGINT, term);
int err;
int i;
for (i = 1; i <= 8; i++) {
createServoPipes(i);
listener_data[i].pipeHandle = openPipe(i);
int *arg = malloc(sizeof(*arg));
if (arg == 0) {
fprintf(stderr, "Couldn't allocate memory for thread arg.\\n");
exit(1);
}
*arg = i;
err = pthread_create(&(listener_data[i].tid), 0, servoListener, arg);
if (err != 0)
printf("Can't create listener thread :[%s]\\n", strerror(err));
}
err = pthread_create(&(servoThread), 0, servoRunner, 0);
if (err != 0)
printf("Can't create runner thread :[%s]\\n", strerror(err));
while (!done) {
rc_usleep(1000);
}
for (i = 1; i <= 8; i++) {
close(listener_data[i].pipeHandle);
rollbackPipes(i);
}
pthread_mutex_destroy(&lock);
rc_disable_servo_power_rail();
rc_cleanup();
return 0;
}
void createServoDir() {
DIR *pDir;
pDir = opendir(servoDir);
if (pDir == 0) {
printf("Create servo folder\\n");
int status;
status = mkdir(servoDir, 0755);
}
return;
}
void createServoPipes(int channel) {
char servoChildDir[255];
char servoPosition[255];
sprintf(servoChildDir, "%s/servo%d", servoDir, channel);
sprintf(servoPosition, "%s/servo%d/position", servoDir, channel);
DIR *pDir;
pDir = opendir(servoChildDir);
if (pDir == 0) {
printf("Create folder %s\\n", servoChildDir);
int status;
status = mkdir(servoChildDir, 0755);
}
mkfifo(servoPosition, 0766);
}
void rollbackPipes(int channel) {
char servoChildDir[20];
char servoPosition[30];
sprintf(servoChildDir, "%s/servo%d", servoDir, channel);
sprintf(servoPosition, "%s/servo%d/position", servoDir, channel);
DIR *pDir;
pDir = opendir(servoChildDir);
if (pDir != 0) {
unlink(servoPosition);
rmdir(servoChildDir);
}
}
int openPipe(int channel) {
char servoPosition[255];
sprintf(servoPosition, "%s/servo%d/position", servoDir, channel);
printf("Listening on %s\\n", servoPosition);
return open(servoPosition, O_RDONLY | O_NONBLOCK);
}
void *servoListener(void *i) {
int channel = *((int *) i);
free(i);
char rd_buffer[1024];
memset(rd_buffer, 0, sizeof(rd_buffer));
while(!done) {
if (read(listener_data[channel].pipeHandle, rd_buffer, sizeof(rd_buffer)) > 0)
processCommand(channel, rd_buffer);
}
printf("Shutting down listener\\n");
return;
}
void processCommand(int channel, char *buffer) {
double servo_pos = 0;
printf("Received: %s\\n", buffer);
servo_pos = atof(buffer);
if (servo_pos <= 1.5 && servo_pos >= -1.5) {
printf("Moving servo %d to %f\\n",channel,servo_pos);
pthread_mutex_lock(&lock);
listener_data[channel].servo_pulse_width_us = servo_mid + (servo_pos*(servo_range/2));
pthread_mutex_unlock(&lock);
}
return;
}
void* servoRunner(void *a) {
int toggle = 0;
int pulse_width[8 +1];
int i;
while (!done) {
if (pthread_mutex_trylock(&lock) == 0)
{
for (i = 1; i <= 8; i++) {
pulse_width[i] = listener_data[i].servo_pulse_width_us;
}
pthread_mutex_unlock (&lock);
}
for (i = 1; i <= 8; i++) {
if (pulse_width[i] != 0) {
rc_send_servo_pulse_us(i, pulse_width[i]);
}
}
rc_set_led(GREEN, toggle);
toggle = !toggle;
rc_usleep(1000000 / frequency_hz);
}
printf("Shutting down runner\\n");
return;
}
| 0
|
#include <pthread.h>
pthread_mutex_t t_lock;
pthread_cond_t t_cond;
int *data_array;
int sum_array[4];
struct data_info
{
int *d_point;
int idx;
};
void *t_func(void *data)
{
struct data_info d_info;
int i = 0;
int sum = 0;
d_info = *((struct data_info*)data);
pthread_mutex_lock(&t_lock);
pthread_cond_wait(&t_cond, &t_lock);
printf("Start %d thread\\n", d_info.idx);
pthread_mutex_unlock(&t_lock);
for(i=0; i<25; i++)
{
sum += d_info.d_point[(d_info.idx*25)+i];
}
printf("(%d) %d\\n", d_info.idx, sum);
sum_array[d_info.idx] = sum;
return 0;
}
int main(int argc, char *argv[])
{
int i=0;
int sum=0;
struct data_info d_info;
pthread_t thread_id[4];
if((data_array = malloc(sizeof(int)*100)) == 0)
perr(err_failed);
pthread_mutex_init(&t_lock, 0);
pthread_cond_init(&t_cond, 0);
for(i = 0; i < 4; i++)
{
d_info.d_point = data_array;
d_info.idx = i;
pthread_create(&thread_id[i], 0, t_func, (void*)&d_info);
usleep(100);
}
for(i=0; i<100; i++)
{
*data_array = i;
data_array++;
}
pthread_cond_broadcast(&t_cond);
for(i=0; i<4; i++)
{
pthread_join(thread_id[i], 0);
sum += sum_array[i];
}
printf("SUM (0-99) L %d\\n",sum);
return 0;
}
| 1
|
#include <pthread.h>
void *malloc(unsigned size);
int nondet_int();
int x, y, z;
int balance;
pthread_mutex_t lock;
} ACCOUNT, *PACCOUNT;
PACCOUNT create(int b)
{
PACCOUNT acc = (PACCOUNT) malloc(sizeof(ACCOUNT));
acc->balance = b;
pthread_mutex_init(&acc->lock, 0);
return acc;
}
int read(PACCOUNT acc)
{
return acc->balance;
}
void deposit(PACCOUNT acc)
{
pthread_mutex_lock(&acc->lock);
acc->balance = acc->balance + y;
pthread_mutex_unlock(&acc->lock);
}
void withdraw(PACCOUNT acc)
{
int r;
pthread_mutex_lock(&acc->lock);
r = read(acc);
acc->balance = r - z;
pthread_mutex_unlock(&acc->lock);
}
void* deposit_thread(void* arg)
{
deposit(arg);
}
void* withdraw_thread(void* arg)
{
withdraw(arg);
}
int main()
{
pthread_t t1, t2;
PACCOUNT acc;
x = nondet_int();
y = nondet_int();
z = nondet_int();
acc = create(x);
pthread_create(&t1, 0, deposit_thread, acc);
pthread_create(&t2, 0, withdraw_thread, acc);
assert(read(acc) == x + y - z);
return 0;
}
| 0
|
#include <pthread.h>
int forks[] = {2, 2, 2, 2, 2};
pthread_mutex_t dp_mutex;
pthread_cond_t both_free[5];
int right[] = {1, 2, 3, 4, 0};
int left[] = {4, 0, 1, 2, 3};
int iters;
void getforks(int i)
{
pthread_mutex_lock(&dp_mutex);
if (forks[i] < 2) pthread_cond_wait(&both_free[i], &dp_mutex);
forks[right[i]]--;
forks[left[i]]--;
pthread_mutex_unlock(&dp_mutex);
}
void relforks(int i)
{
pthread_mutex_lock(&dp_mutex);
forks[right[i]]++;
forks[left[i]]++;
if (forks[right[i]] == 2) pthread_cond_signal(&both_free[right[i]]);
if (forks[left[i]] == 2) pthread_cond_signal(&both_free[left[i]]);
pthread_mutex_unlock(&dp_mutex);
}
void *philosopher(void *arg)
{
int id = (int) arg, i;
struct timespec delay = {0, 0};
for (i = 0; i < iters; i++) {
delay.tv_nsec = rand(); nanosleep(&delay, 0);
getforks(id);
printf("Philosopher %d eating\\n", id);
delay.tv_nsec = rand(); nanosleep(&delay, 0);
relforks(id);
printf("Philosopher %d thinking\\n", id);
}
}
int main(int argc, char **argv)
{
int i;
pthread_t t[5];
if (argc != 2) {
printf("usage: %s <iters>\\n", argv[0]); exit(1);
}
iters = atoi(argv[1]);
srand(getpid());
pthread_mutex_init(&dp_mutex, 0);
for (i = 0; i < 5; i++) {
pthread_cond_init(&both_free[i], 0);
}
for (i = 0; i < 5; i++) {
pthread_create(&t[i], 0, philosopher, (void *) i);
}
for (i = 0; i < 5; i++) {
pthread_join(t[i], 0);
}
}
| 1
|
#include <pthread.h>
int buffer[8];
int bufin = 0;
int bufout = 0;
pthread_mutex_t buffer_lock = PTHREAD_MUTEX_INITIALIZER;
unsigned long sum = 0;
sem_t hay_datos;
sem_t hay_sitio;
void obten_dato(int *itemp)
{
pthread_mutex_lock(&buffer_lock);
*itemp = buffer[bufout];
bufout = (bufout + 1) % 8;
printf("bufout %d\\n", bufout);
pthread_mutex_unlock(&buffer_lock);
return;
}
void pon_dato(int item)
{
pthread_mutex_lock(&buffer_lock);
buffer[bufin] = item;
bufin = (bufin + 1) % 8;
pthread_mutex_unlock(&buffer_lock);
return;
}
void *productor(void *arg1)
{
int i;
for (i = 1; i <= 100; i++) {
sem_wait(&hay_sitio);
pon_dato(i*i);
sem_post(&hay_datos);
}
pthread_exit( 0 );
}
void *consumidor(void *arg2)
{
int i, midato;
for (i = 1; i<= 100; i++) {
sem_wait(&hay_datos);
obten_dato(&midato);
sem_post(&hay_sitio);
sum += midato;
}
pthread_exit( 0 );
}
main()
{
printf("main\\n");
pthread_t tidprod, tidcons;
unsigned long i, total;
total = 0;
for (i = 1; i <= 100; i++)
total += i*i;
printf("El resultado debeasdasdasdria ser %u\\n", total);
sem_init(&hay_datos, 0, 0);
sem_init(&hay_sitio, 0, 8);
pthread_create(&tidprod, 0, productor, 0);
pthread_create(&tidcons, 0, consumidor, 0);
pthread_join(tidprod, 0);
pthread_join(tidcons, 0);
printf("Los hilos produjeron el valor %u\\n", sum);
}
| 0
|
#include <pthread.h>
int packetNum;
int numOfPacks;
char * packets[100];
pthread_mutex_t packetNumMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t packetsMutex = PTHREAD_MUTEX_INITIALIZER;
{
char * ip;
int port;
}SERVER;
void * getPackets(void * serv)
{
SERVER * myserv = serv;
int bytesRead = 1;
while(1)
{
char * buffer = malloc(1024 +1);
int mySocket;
int myPackNum;
char blockReq[150];
struct sockaddr_in serv_addr;
pthread_mutex_lock(&packetNumMutex);
myPackNum = packetNum;
packetNum++;
pthread_mutex_unlock(&packetNumMutex);
if((mySocket = socket(AF_INET,SOCK_STREAM,IPPROTO_IP)) < 0)
{
perror("Socket");
exit(errno);
}
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(myserv->port);
serv_addr.sin_addr.s_addr = inet_addr(myserv->ip);
if((connect(mySocket, (struct sockaddr*)&serv_addr, sizeof(serv_addr)))!=0)
{
printf("Couldn't connect to port %d\\n",myserv->port);
exit(errno);
}
bzero(buffer,1024);
sprintf(blockReq,"%d",myPackNum);
if(send(mySocket,blockReq,sizeof(blockReq),0)<0)
{
perror("Couldn't write to socket");
exit(errno);
}
bytesRead = recv(mySocket,buffer,1024,0);
if(bytesRead <= 0)
{
free(myserv);
free(buffer);
close(mySocket);
return (void*)1;
}
pthread_mutex_lock(&packetsMutex);
packets[myPackNum] = buffer;
numOfPacks++;
pthread_mutex_unlock(&packetsMutex);
close(mySocket);
}
}
int main(int argc,char *argv[])
{
FILE *output;
int i;
int numServers;
if(argc < 3 || !argc%2)
{
printf("Usage: ./client2 <ip addr1> <port1> <ip addr2> <port2>....");
exit(-1);
}
numServers = (argc-1)/2;
pthread_t threads[numServers];
void * threadSuc[numServers];
for(i = 1; i <= numServers; i++)
{
SERVER * serv = malloc(sizeof(SERVER));
serv->ip = argv[(i*2)-1];
serv->port = atoi(argv[i*2]);
pthread_create(&threads[i-1], 0, getPackets, serv);
}
for(i = 0; i < numServers; i++)
{
pthread_join(threads[i], &threadSuc[i]);
}
output = fopen("output.txt","w");
for(i = 0; i < numOfPacks; i++)
{
fwrite(packets[i],1,strlen(packets[i]),output);
free(packets[i]);
}
fclose(output);
return 0;
}
| 1
|
#include <pthread.h>
int makethread(void *(*)(void *), void *);
struct to_info{
void (*to_fun)(void *);
void *to_arg;
struct timespec to_wait;
};
void *timeout_helper(void *arg)
{
struct to_info *tip;
tip = (struct to_info *)arg;
nanosleep(&tip->to_wait, 0);
(*tip->to_fun)(tip->to_arg);
return(0);
}
void timeout(const struct timespec *when, void(*func)(void *), void *arg)
{
struct timespec now;
struct timeval tv;
struct to_info *tip;
int err;
gettimeofday(&tv, 0);
now.tv_sec = tv.tv_sec;
now.tv_nsec = tv.tv_usec * 1000;
if((when->tv_sec > now.tv_sec) ||
(when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)){
tip = malloc(sizeof(struct to_info));
if(tip != 0){
tip->to_fun = func;
tip->to_arg = arg;
tip->to_wait.tv_sec = when->tv_sec - now.tv_nsec;
if(when->tv_sec >= now.tv_sec){
tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec;
}else{
tip->to_wait.tv_sec--;
tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec +
when->tv_nsec;
}
err = makethread(timeout_helper, (void *)tip);
if(err == 0)
return;
}
}
(*func)(arg);
}
pthread_mutexattr_t attr;
pthread_mutex_t mutex;
void retry(void *arg)
{
printf("in retry1\\n");
pthread_mutex_lock(&mutex);
printf("in retry2\\n");
pthread_mutex_unlock(&mutex);
}
int main(void)
{
int err, condition, arg;
struct timespec when;
if((err = pthread_mutexattr_init(&attr)) != 0)
err_exit(err, "can't pthread_mutexattr_init failed");
if((err = pthread_mutexattr_settype(&attr,
PTHREAD_MUTEX_RECURSIVE)) != 0)
err_exit(err, "can't set recursive type");
if((err = pthread_mutex_init(&mutex, &attr)) != 0)
err_exit(err, "can't create recursive mutex");
pthread_mutex_lock(&mutex);
when.tv_sec = 5;
condition = 1;
arg = 0;
if(condition)
timeout(&when, retry, (void*)arg);
pthread_mutex_unlock(&mutex);
exit(0);
}
int makethread(void *(* fn)(void *), void *arg)
{
int err;
pthread_t tid;
pthread_attr_t attr;
err = pthread_attr_init(&attr);
if(err != 0)
return err;
err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
if(err == 0)
pthread_create(&tid, &attr, fn, arg);
pthread_attr_destroy(&attr);
return(err);
}
| 0
|
#include <pthread.h>
int (*grid)[9];
int max_threads;
char *filename;
int *thread_number;
int errors;
pthread_mutex_t mutex_error;
int load_grid(char *filename) {
grid = (int (*)[9])malloc(sizeof(*grid)*9);
FILE *input_file = fopen(filename, "r");
if (input_file != 0) {
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
fscanf(input_file, "%d", &grid[i][j]);
fclose(input_file);
return 1;
}
return 0;
}
void *calculate(void *t_number) {
int tn = *(int*)t_number;
int mult_line, mult_column, mult_region, initial_point;
for(int i = tn; i < 27; i = i+max_threads){
switch(i/9){
case 0:
mult_line = 1;
for(int j = 0; j < 9; j++)
{
mult_line *= grid[i][j];
if(j == 8){
if( mult_line != 362880){
printf("Thread %d: erro na linha %d.\\n", tn+1, i+1);
pthread_mutex_lock(&mutex_error);
errors += 1;
pthread_mutex_unlock(&mutex_error);
}
}
}
break;
case 1:
mult_column = 1;
for(int j = 0; j < 9; j++){
mult_column *= grid[j][i-9];
if(j == 8){
if( mult_column != 362880){
printf("Thread %d: erro na coluna %d.\\n", tn+1, i-8);
pthread_mutex_lock(&mutex_error);
errors += 1;
pthread_mutex_unlock(&mutex_error);
}
}
}
break;
case 2:
mult_region = 1;
initial_point = ((int)((i-18)/3)*27)+(((i-18)%3)*3);
for(int j = 0; j < 3; j++){
mult_region *= *(grid[0]+initial_point);
mult_region *= *(grid[0]+initial_point+1);
mult_region *= *(grid[0]+initial_point+2);
initial_point += 9;
}
if( mult_region != 362880){
printf("Thread %d: erro na regiao %d.\\n", tn+1, i-17);
pthread_mutex_lock(&mutex_error);
errors += 1;
pthread_mutex_unlock(&mutex_error);
}
break;
}
}
return 0;
}
static void start_threads(void){
pthread_t threads[max_threads];
for (int i = 0; i < max_threads; i++) {
pthread_create(&threads[i], 0, calculate, (void*)(&thread_number[i]));
}
for (int i = 0; i < max_threads; i++) {
pthread_join(threads[i], 0);
}
}
void initialize_variables(int m_threads){
thread_number = (int*)malloc(m_threads*sizeof(int));
pthread_mutex_init(&mutex_error, 0);
errors = 0;
for(int i = 0; i < max_threads; i++){
thread_number[i] = i;
}
}
void initialize_grid(int (*p_grid)[9]){
grid = p_grid;
}
int initialize_grid_file(){
if(load_grid(filename)) {
printf("Quebra-cabecas fornecido:\\n");
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++)
printf("%d ", grid[i][j]);
printf("\\n");
}
printf("\\n");
return 1;
}
return 0;
}
int main(int argc, char *argv[]) {
if(argc != 3) {
printf("Erro: informe o arquivo de entrada e o número de threads!\\nUso: %s <arquivo de entrada>\\n\\n", argv[0]);
return 1;
}
max_threads = atoi(argv[2]);
filename = argv[1];
initialize_variables(max_threads);
initialize_grid_file();
start_threads();
printf("Erros encontrados: %d.\\n", errors);
return 0;
}
| 1
|
#include <pthread.h>
int f_count;
int f_id;
pthread_mutex_t f_lock;
}foo;
foo * foo_alloc(int id);
void foo_hold(foo *fp);
void foo_free(foo *fp);
void * start_routine(void *);
foo *
foo_alloc(int id)
{
foo *fp;
if ((fp = (foo *)malloc(sizeof(foo))) != 0) {
if (pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return 0;
}
}
return fp;
}
void
foo_hold(foo *fp)
{
if(fp == 0) {
printf("fp error");
exit(1);
}
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
void
foo_free(foo *fp)
{
if(fp == 0) {
printf("fp error");
exit(1);
}
pthread_mutex_lock(&fp->f_lock);
if (--fp->f_count == 0) {
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
}else {
pthread_mutex_unlock(&fp->f_lock);
}
}
int
main(int argc, char const *argv[])
{
int err;
pthread_t tid;
foo *fp;
fp = foo_alloc(1);
srand(time(0));
err = pthread_create(&tid, 0, start_routine, (void *)fp);
if (err != 0) {
printf("pthread_create error\\n");
exit(1);
}
err = pthread_detach(tid);
if (err != 0) {
printf("pthread_detach error\\n");
exit(1);
}
while(1) {
foo_hold(fp);
printf("main thread: f_count = %d\\n", fp->f_count);
sleep(rand() % 3);
}
return 0;
}
void *
start_routine(void *arg)
{
foo *fp = (foo *)arg;
while(1) {
foo_hold(fp);
printf("child thread: f_count = %d\\n", fp->f_count);
sleep(rand() % 3);
}
return (void *)(0);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t s_mutex;
static FILE *s_fileHandler;
void LOGGER_PL_init(int isPrintToLogFile)
{
s_fileHandler = 0;
if (isPrintToLogFile)
s_fileHandler = fopen("log.log", "w");
pthread_mutex_init(&s_mutex, 0);
}
static void printToConsole(char *logMsgBuffer)
{
printf("%s", logMsgBuffer);
}
static size_t printToLogFile(char *logMsgBuffer, size_t logMsgBufferSize)
{
size_t ret = fwrite(logMsgBuffer, 1, logMsgBufferSize, s_fileHandler);
fflush(s_fileHandler);
return ret;
}
static void createLogBuffer (const char *format, va_list args)
{
size_t stringLen = 0;
static char msgBuf[2048];
size_t prefixLen = 0 , msgBufLen = 2048;
size_t stringEnd = 0;
stringLen = (size_t)vsnprintf(&msgBuf[prefixLen], msgBufLen, format, args);
stringLen += prefixLen;
if (stringLen > 0)
{
stringEnd = stringLen < 2048 - 1 ? stringLen : 2048 - 3;
msgBuf[stringEnd + 1] = '\\0';
printToConsole(msgBuf);
if (s_fileHandler)
printToLogFile(msgBuf, stringEnd);
}
}
void LOGGER_PL_log(char *format, ...)
{
va_list args;
pthread_mutex_lock(&s_mutex);
__builtin_va_start((args));
createLogBuffer(format, args);
;
pthread_mutex_unlock(&s_mutex);
}
void LOGGER_PL_term()
{
fclose(s_fileHandler);
s_fileHandler = 0;
pthread_mutex_destroy(&s_mutex);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t gGetmntentMutex = PTHREAD_MUTEX_INITIALIZER;
struct mntent *getmntent(FILE *fp) {
static struct mntent mnt;
static char *buf = 0;
struct mntent *ret;
pthread_mutex_lock(&gGetmntentMutex);
if (buf == 0) {
buf = malloc(4096);
if (buf == 0) {
return 0;
}
}
ret = getmntent_r(fp, &mnt, buf, 4096);
pthread_mutex_unlock(&gGetmntentMutex);
return ret;
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
void
prepare(void)
{
printf("preparing locks...\\n");
pthread_mutex_lock(&lock1);
pthread_mutex_lock(&lock2);
}
void
parent(void)
{
printf("parent unlocking locks...\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void
child(void)
{
printf("child unlocking locks...\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void *
thr_fn(void *arg)
{
printf("thread started...\\n");
pause();
return(0);
}
int
main(void)
{
int err;
pid_t pid;
pthread_t tid;
if ((err = pthread_atfork(prepare, parent, child)) != 0)
err_exit(err, "can't install fork handlers");
err = pthread_create(&tid, 0, thr_fn, 0);
if (err != 0)
err_exit(err, "can't create thread");
sleep(2);
printf("parent about to fork...\\n");
if ((pid = fork()) < 0)
err_quit("fork failed");
else if (pid == 0)
printf("child returned from fork\\n");
else
printf("parent returned from fork\\n");
exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutexLock;
sem_t oddSem;
sem_t evenSem;
void *print_even_nums(void *param) {
int even_num_to_print;
for(even_num_to_print = 2; even_num_to_print <= 100;) {
sem_wait(&oddSem);
pthread_mutex_lock(&mutexLock);
printf("%4d", even_num_to_print);
pthread_mutex_unlock(&mutexLock);
even_num_to_print += 2;
sem_post(&evenSem);
}
}
void *print_odd_nums(void *param) {
int odd_num_to_print;
for(odd_num_to_print = 1; odd_num_to_print < 100;) {
sem_wait(&evenSem);
pthread_mutex_lock(&mutexLock);
printf("%4d", odd_num_to_print);
pthread_mutex_unlock(&mutexLock);
odd_num_to_print += 2;
sem_post(&oddSem);
}
}
int main() {
pthread_t even_thread;
pthread_t odd_thread;
sem_init(&evenSem,0,1);
sem_init(&oddSem,0,0);
pthread_mutex_init(&mutexLock,0);
pthread_create(&even_thread, 0, print_even_nums, 0);
pthread_create(&odd_thread, 0, print_odd_nums, 0);
pthread_join(even_thread, 0);
pthread_join(odd_thread, 0);
printf("\\n");
return 0;
}
| 0
|
#include <pthread.h>
unsigned short X_data_trace[512 * 512];
unsigned short X_data_retrace[512 * 512];
unsigned short Y_data_trace[512 * 512];
void readHugeData(void)
{
int len;
DEBUG0("IN readHugeData");
len = recv(connect_socket_fd, (char *)X_data_trace, 512 * 512 * 2, MSG_WAITALL);
len = recv(connect_socket_fd, (char *)X_data_retrace, 512 * 512 * 2, MSG_WAITALL);
len = recv(connect_socket_fd, (char *)Y_data_trace, 512 * 512 * 2, MSG_WAITALL);
DEBUG0("ALL DATA RECEIVED");
}
unsigned short sendBuf[8];
void* laserThread(void* para)
{
int i, laserA, laserB, laserC, laserD;
int currentTask;
pthread_detach(pthread_self());
bzero(sendBuf, 8 * sizeof(unsigned short));
sendBuf[0] = GET_LASER_POS;
sendBuf[1] = 4;
DEBUG0("in laser thread");
while(1)
{
pthread_mutex_lock(&g_current_task_mutex);
currentTask = g_current_task;
pthread_mutex_unlock(&g_current_task_mutex);
if(currentTask == STOP) break;
pid_func();
for (i = 0; i < 50; i++)
{
pid_func();
}
laserA = 0;
laserB = 0;
laserC = 0;
laserD = 0;
for (i = 0; i < 50; i++)
{
laserA += read_AD(AD_LASER_A);
laserB += read_AD(AD_LASER_B);
laserC += read_AD(AD_LASER_C);
laserD += read_AD(AD_LASER_D);
}
sendBuf[2] = laserA / 50;
sendBuf[3] = laserB / 50;
sendBuf[4] = laserC / 50;
sendBuf[5] = laserD / 50;
sendBuf[7] = pid_func();
sendBuf[6] = (short)g_DA_z;
send(connect_socket_fd, (char*)sendBuf, 16, 0);
usleep(10000);
}
DEBUG0("leave laser thread");
return 0;
}
| 1
|
#include <pthread.h>
int number;
pthread_mutex_t mu= PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t sig_consumer= PTHREAD_COND_INITIALIZER;
pthread_cond_t sig_producer= PTHREAD_COND_INITIALIZER;
void *consumer(void *dummy)
{
int printed= 0;
" now\\"\\n", pthread_self());
while (1)
{
pthread_mutex_lock(&mu);
pthread_cond_signal(&sig_producer);
pthread_cond_wait(&sig_consumer, &mu);
printf("Consumer : %d\\n", number);
pthread_mutex_unlock(&mu);
if (number == 10)
{
printf("Consumer done.. !!\\n");
break;
}
}
}
void *producer(void *dummy)
{
" now\\"\\n", pthread_self());
while (1)
{
pthread_mutex_lock(&mu);
number ++;
printf("Producer : %d\\n", number);
pthread_cond_signal(&sig_consumer);
if (number != 10)
pthread_cond_wait(&sig_producer, &mu);
pthread_mutex_unlock(&mu);
if (number == 10)
{
printf("Producer done.. !!\\n");
break;
}
}
}
void main()
{
int rc, i;
pthread_t t[2];
number= 0;
if ((rc= pthread_create(&t[0], 0, consumer, 0)))
printf("Error creating the consumer thread..\\n");
if ((rc= pthread_create(&t[1], 0, producer, 0)))
printf("Error creating the producer thread..\\n");
for (i= 0; i < 2; i ++)
pthread_join(t[i], 0);
printf("Done..\\n");
}
| 0
|
#include <pthread.h>
struct shared
{
int sum;
pthread_mutex_t mut;
int global_index;
};
struct matrix
{
int nbLines;
int nbColumns;
int** elements;
struct shared *psh;
};
static void *sum_array (void *p);
int main(int argc, char *argv[])
{
srand(time(0));
int i = 0, j = 0;
if (argc != 3)
{
fprintf(stderr, "USAGE: ./main <lines> <columns>\\n");
exit(1);
}
struct shared sh =
{
.sum = 0,
.mut = PTHREAD_MUTEX_INITIALIZER,
.global_index = 0,
};
struct matrix mat =
{
.nbLines = atoi(argv[1]),
.nbColumns = atoi(argv[2]),
.psh = &sh,
};
mat.elements = (int**)malloc(mat.nbLines * sizeof(int *));
for(i = 0; i < mat.nbLines; ++i)
mat.elements[i] = (int *)calloc(mat.nbColumns, sizeof(int));
pthread_t thread_id[mat.nbColumns];
for(i = 0; i < mat.nbLines; ++i)
for(j = 0; j < mat.nbColumns; ++j)
mat.elements[i][j] = rand()%10;
for(i = 0; i < mat.nbLines; ++i)
{
for(j = 0; j < mat.nbColumns; ++j)
printf("%d ",mat.elements[i][j]);
printf("\\n");
}
puts ("main init");
for(i = 0; i < mat.nbLines; ++i)
if (pthread_create( &thread_id[i], 0, &sum_array, &mat) != 0)
{
perror("pthread_create");
exit(1);
}
for(i = 0; i < mat.nbLines; ++i)
pthread_join( thread_id[i], 0);
printf("Final Sum : %d\\n", mat.psh->sum);
puts ("main end");
for(i = 0; i < mat.nbLines; ++i)
free(mat.elements[i]);
free(mat.elements);
return 0;
}
static void *sum_array(void *p)
{
if(p != 0){
struct matrix *p_matrix = p;
int local_index, partial_sum = 0;
do {
pthread_mutex_lock(&p_matrix->psh->mut);
local_index = p_matrix->psh->global_index;
p_matrix->psh->global_index ++;
pthread_mutex_unlock(&p_matrix->psh->mut);
if (local_index < p_matrix->nbLines) {
for (int i = 0; i < p_matrix->nbColumns; ++i) {
partial_sum += p_matrix->elements[local_index][i];
}
}
}
while (local_index < p_matrix->nbLines);
pthread_mutex_lock(&p_matrix->psh->mut);
p_matrix->psh->sum += partial_sum;
pthread_mutex_unlock(&p_matrix->psh->mut);
}
return 0;
}
| 1
|
#include <pthread.h>
{
pthread_t thread;
char* name;
int id;
int isDancing;
int isEating;
} customer_t;
customer_t customers[12];
int dancing_status;
int eating_status;
int isCurfew;
pthread_mutex_t dance_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t eat_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t barrier_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t barrier_cv = PTHREAD_COND_INITIALIZER;
int barrier_counter = 0;
void declareDancing(int custid)
{
pthread_mutex_lock(&barrier_mutex);
if(barrier_counter == 2)
barrier_counter = 1;
else
barrier_counter += 1;
while(barrier_counter < 2 && !isCurfew)
pthread_cond_wait(&barrier_cv, &barrier_mutex);
pthread_mutex_unlock(&barrier_mutex);
pthread_cond_broadcast(&barrier_cv);
if(isCurfew)
return;
pthread_mutex_lock(&dance_mutex);
int i;
int counter = 0;
char* friends[2 -1];
for(i = 0; i < 12; i++)
{
if(customers[i].isDancing && i != custid)
{
if(counter > 0)
printf("Wait? Why are you here %s?\\n", customers[i].name);
else
friends[counter] = customers[i].name;
counter++;
}
}
if(counter == 1)
printf("%s is dancing with %s.\\n", customers[custid].name, friends[0]);
else
printf("Your synchronization implementation is incorrect.\\n");
pthread_mutex_unlock(&dance_mutex);
usleep(10);
}
void declareEating(int custid)
{
if(isCurfew)
return;
pthread_mutex_lock(&eat_mutex);
int i;
int counter = 0;
char* friends[3 -1];
for(i = 0; i < 12; i++)
{
if(customers[i].isEating && i != custid)
{
if (counter > 1)
printf("Wait? Why are you here %s?\\n", customers[i].name);
else
friends[counter] = customers[i].name;
counter++;
}
}
if(counter == 2)
printf("%s is eating with %s and %s.\\n", customers[custid].name,
friends[0],
friends[1]);
else
printf("Your synchronization implementation is incorrect.\\n");
pthread_mutex_unlock(&eat_mutex);
usleep(5);
}
void* fridayNight(void* customer_info)
{
customer_t* thisCust = (customer_t*)(customer_info);
printf("customer name: %s\\n", thisCust->name);
while(!isCurfew)
{
pthread_mutex_lock(&dance_mutex);
dancing_status++;
thisCust->isDancing = 1;
pthread_mutex_unlock(&dance_mutex);
declareDancing(thisCust->id);
pthread_mutex_lock(&dance_mutex);
dancing_status--;
thisCust->isDancing = 0;
pthread_mutex_unlock(&dance_mutex);
pthread_mutex_lock(&eat_mutex);
eating_status++;
thisCust->isEating = 1;
pthread_mutex_unlock(&eat_mutex);
declareEating(thisCust->id);
pthread_mutex_lock(&eat_mutex);
eating_status--;
thisCust->isEating = 0;
pthread_mutex_unlock(&eat_mutex);
usleep(10);
}
return 0;
}
int main()
{
customer_t *currCustomer;
int i;
int failed;
isCurfew = 0;
for(i = 0; i < 12; i++)
{
currCustomer = &(customers[i]);
currCustomer->name = malloc(sizeof(char));
currCustomer->id = i;
*(currCustomer->name) = (char)(65+i);
currCustomer->isDancing = 0;
currCustomer->isEating = 0;
pthread_create(&currCustomer->thread, 0, fridayNight, currCustomer);
}
sleep(10);
isCurfew = 1;
printf("Time to clean up!\\n");
for(i = 0; i < 12; i++)
{
currCustomer = &customers[i];
if(pthread_join(currCustomer->thread, 0))
{
printf("error joining thread for %s\\n", currCustomer->name);
exit(1);
}
}
for(i = 0; i < 12; i++)
free(customers[i].name);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t cond_var_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_var_odd_done = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_var_even_done = PTHREAD_COND_INITIALIZER;
int evenDone = 0;
int oddDone = 0;
void* thread_Even(void* args)
{
printf("thread_Even +\\n");
int i = 0;
while(i < 20)
{
pthread_mutex_lock( &cond_var_lock);
printf("EVEN = %d\\n", i);
i += 2;
evenDone = 1;
pthread_cond_signal( &cond_var_even_done );
printf("Even Lock\\n");
while(!oddDone)
pthread_cond_wait( &cond_var_odd_done, &cond_var_lock);
oddDone = 0;
pthread_mutex_unlock( &cond_var_lock);
}
pthread_cond_signal( &cond_var_even_done );
return 0;
}
void* thread_Odd(void* args)
{
printf("thread_Odd +\\n");
int i = 1;
while(i < 20)
{
pthread_mutex_lock( &cond_var_lock);
printf("Odd Lock\\n");
while(!evenDone)
pthread_cond_wait( &cond_var_even_done, &cond_var_lock);
evenDone = 0;
printf("ODD = %d\\n", i);
i += 2;
oddDone = 1;
pthread_cond_signal( &cond_var_odd_done );
pthread_mutex_unlock( &cond_var_lock);
}
pthread_cond_signal( &cond_var_odd_done );
return 0;
}
void main()
{
pthread_t tid_2;
pthread_t tid_1;
pthread_create(&tid_1, 0, thread_Even, 0);
pthread_create(&tid_2, 0, thread_Odd, 0);
pthread_join(tid_2, 0);
printf("tid_2 done\\n");
pthread_join(tid_1, 0);
printf("tid_1 done\\n");
}
| 1
|
#include <pthread.h>
struct board {
unsigned int width;
unsigned int queens;
unsigned int left, down, right;
};
struct task {
board board;
struct task *next;
};
static pthread_mutex_t tasks_mutex = PTHREAD_MUTEX_INITIALIZER;
static task *tasks;
static board *
get_task()
{
task *t;
pthread_mutex_lock(&tasks_mutex);
t = tasks;
if (t)
tasks = t->next;
pthread_mutex_unlock(&tasks_mutex);
return &t->board;
}
static void
put(board *b, const board *orig, unsigned int bit)
{
b->width = orig->width;
b->queens = orig->queens - 1;
b->left = (orig->left | bit) >> 1;
b->down = orig->down | bit;
b->right = (orig->right | bit) << 1;
}
static unsigned int
solve(board *b)
{
unsigned int i, mask, bits, sum;
board board;
if (b->queens == 0)
return 1;
bits = b->left | b->down | b->right;
sum = 0;
for (i = 0, mask = 1; i < b->width; i++, mask <<= 1) {
if (!(bits & mask)) {
put(&board, b, mask);
sum += solve(&board);
}
}
return sum;
}
static task *
step(const task *t)
{
unsigned int i, mask, bits;
task *ret = 0, *t2;
for (; t; t = t->next) {
if (t->board.queens == 0)
continue;
bits = t->board.left | t->board.down | t->board.right;
for (i = 0, mask = 1; i < t->board.width; i++, mask <<= 1) {
if (!(bits & mask)) {
t2 = malloc(sizeof(task));
put(&t2->board, &t->board, mask);
t2->next = ret;
ret = t2;
}
}
}
return ret;
}
static unsigned int
length(const task *t)
{
unsigned int n = 0;
while (t) {
n++;
t = t->next;
}
return n;
}
static void
gen_tasks(unsigned int width, unsigned int nthreads)
{
struct task t0;
t0.board.width = width;
t0.board.queens = width;
t0.board.left = 0;
t0.board.down = 0;
t0.board.right = 0;
t0.next = 0;
tasks = &t0;
while (length(tasks) < nthreads * 3)
tasks = step(tasks);
}
void *
solve_para(void *arg)
{
board *b;
unsigned int sum = 0;
while ((b = get_task()))
sum += solve(b);
return (void*)((uintptr_t)sum);
}
int
nqueen_main(int argc, char **argv)
{
unsigned int width = atoi(argv[1]);
unsigned int nthreads = atoi(argv[2]);
pthread_t *threads;
unsigned int i, sum;
int err;
void *result;
gen_tasks(width, nthreads);
threads = malloc(sizeof(pthread_t) * nthreads);
for (i = 0; i < nthreads; i++) {
err = pthread_create(&threads[i], 0, solve_para, 0);
if (err != 0) {
perror("pthread_create");
abort();
}
}
sum = 0;
for (i = 0; i < nthreads; i++) {
pthread_join(threads[i], &result);
sum += (uintptr_t)result;
}
printf("%d\\n", sum);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
void recover(void)
{
printf("\\n Performing Recovery by Thread : %u \\n",syscall(SYS_gettid));
printf("\\n Recovery completed by Thread : %u \\n",syscall(SYS_gettid));
pthread_mutex_lock(&mutex);
}
void * write_thread (void *p)
{
printf("\\n In Write thread\\n");
if(pthread_mutex_lock(&mutex)==0)
{
printf("\\nWrite thread: Writing....\\n");
pthread_exit(0);
}
}
void * read_thread1(void *p)
{
int rv;
sleep(1);
rv = pthread_mutex_lock(&mutex);
if(rv==EOWNERDEAD)
{
printf("\\n Owner Dead identified by : %u\\n",syscall(SYS_gettid));
recover();
}
printf(" Lock aquaired by : %u\\n",syscall(SYS_gettid));
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void * read_thread2(void *p)
{
int rv;
sleep(2);
rv = pthread_mutex_lock(&mutex);
if(rv==EOWNERDEAD)
{
printf("\\n Owner Dead identified by : %u\\n",syscall(SYS_gettid));
recover();
}
printf(" Lock aquaired by : %u\\n",syscall(SYS_gettid));
sleep(4);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void * read_thread3(void *p)
{
int rv;
rv = pthread_mutex_lock(&mutex);
if(rv==EOWNERDEAD)
{
printf("\\n Owner Dead identified by : %u\\n",syscall(SYS_gettid));
recover();
}
printf(" Lock aquaired by : %u\\n",syscall(SYS_gettid));
sleep(2);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main ()
{
pthread_t tid1,tid2,tid3,tid4;
pthread_mutexattr_t attr;
int rv;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_ROBUST_NP);
pthread_mutexattr_setrobust_np(&attr, PTHREAD_MUTEX_ROBUST_NP);
pthread_mutex_init(&mutex,&attr);
rv = pthread_create(&tid1, 0, write_thread, 0);
if(rv)
puts("Failed to create thread");
rv = pthread_create(&tid2, 0, read_thread1, 0);
if(rv)
puts("Failed to create thread");
rv = pthread_create(&tid3, 0, read_thread2, 0);
if(rv)
puts("Failed to create thread");
rv = pthread_create(&tid4, 0, read_thread3, 0);
if(rv)
puts("Failed to create thread");
pthread_join(tid1,0);
pthread_join(tid2,0);
pthread_join(tid3,0);
pthread_join(tid4,0);
puts(" Exit Main");
return 0;
}
| 1
|
#include <pthread.h>
void *writeIps(void *pa)
{
int check,fwrite_check,i;
int flag;
FILE *fp;
long double tempVal = 0.0;
float value = 0.0;
check = 0;
while(check==0)
{
semaphore_p(sem_fft3);
check = fft3Status[4];
semaphore_v(sem_fft3);
pthread_mutex_lock(&ipsStop_mutex);
flag = ipsStop;
pthread_mutex_unlock(&ipsStop_mutex);
if(flag!=1) return;
}
printf("file to be open \\n");
fp = fopen(ips->filename,"a+");
if(fp == 0)
{
printf("cannot open the file %s " ,ifilename);
exit(0);
}
chown(ifilename,1000,1000);
pthread_mutex_lock(&ipsStop_mutex);
flag = ipsStop;
pthread_mutex_unlock(&ipsStop_mutex);
while(flag==1)
{
pthread_mutex_lock(&spec_mutex);
check = specVal;
pthread_mutex_unlock(&spec_mutex);
pthread_mutex_lock(&ipsStop_mutex);
flag = ipsStop;
pthread_mutex_unlock(&ipsStop_mutex);
if(flag!=1)
{
fclose(fp);
return;
}
if(check==1)
{
for(i=0;i<nfft/2;i++)
{
tempVal+= ur[i];
}
value = (float) (tempVal/(nfft/2));
tempVal=0.0;
fprintf(fp,"%f \\n",value);
value = 0.0;
pthread_mutex_lock(&spec_mutex);
specVal=0;
pthread_mutex_unlock(&spec_mutex);
}
}
printf("%d \\n",flag);
return;
}
| 0
|
#include <pthread.h>
extern FILE *fileout_basicmath_sqrt;
extern pthread_mutex_t mutex_print;
int main_basicmath_sqrt(void)
{
double a1 = 1.0, b1 = -10.5, c1 = 32.0, d1 = -30.0;
double a2 = 1.0, b2 = -4.5, c2 = 17.0, d2 = -30.0;
double a3 = 1.0, b3 = -3.5, c3 = 22.0, d3 = -31.0;
double a4 = 1.0, b4 = -13.7, c4 = 1.0, d4 = -35.0;
double x[3];
double X;
int solutions;
int i;
unsigned long l = 0x3fed0169L;
struct int_sqrt q;
long n = 0;
pthread_mutex_lock(&mutex_print);
fprintf(fileout_basicmath_sqrt,"********* INTEGER SQR ROOTS ***********\\n");
for (i = 0; i < 501; ++i)
{
usqrt(i, &q);
fprintf(fileout_basicmath_sqrt,"sqrt(%3d) = %2d\\n",
i, q.sqrt);
}
pthread_mutex_unlock(&mutex_print);
usqrt(l, &q);
pthread_mutex_lock(&mutex_print);
fprintf(fileout_basicmath_sqrt,"\\nsqrt(%lX) = %X\\n", l, q.sqrt);
pthread_mutex_unlock(&mutex_print);
return 0;
}
| 1
|
#include <pthread.h>
void* clnt_connection(void *arg);
void send_msg(char* msg, int len);
void matching_seq();
void error_handling(char *msg);
void signal_handler(int signo);
int clnt_no = 0;
int clnt_socks[10][2];
int matched = 0;
int defender_selected = 0;
int role[10];
struct sigaction sigact;
pthread_mutex_t mutx;
int main(int argc, char* argv[])
{
int serv_sock_r;
int serv_sock_w;
int clnt_sock_r;
int clnt_sock_w;
struct sockaddr_in serv_addr_r;
struct sockaddr_in serv_addr_w;
struct sockaddr_in clnt_addr_r;
struct sockaddr_in clnt_addr_w;
int clnt_addr_r_size;
int clnt_addr_w_size;
pthread_t thread;
signal(SIGPIPE, SIG_IGN);
if(pthread_mutex_init(&mutx, 0))
error_handling("mutex init error");
serv_sock_r = socket(PF_INET, SOCK_STREAM, 0);
if(serv_sock_r < 0)
error_handling("socket error");
serv_sock_w = socket(PF_INET, SOCK_STREAM, 0);
if(serv_sock_w < 0)
error_handling("socket error");
memset(role, 0, sizeof(int)*10);
memset(&serv_addr_r, 0, sizeof(serv_addr_r));
serv_addr_r.sin_family = AF_INET;
serv_addr_r.sin_addr.s_addr= htonl(INADDR_ANY);
serv_addr_r.sin_port = htons(6003);
memset(&serv_addr_w, 0, sizeof(serv_addr_w));
serv_addr_w.sin_family = AF_INET;
serv_addr_w.sin_addr.s_addr= htonl(INADDR_ANY);
serv_addr_w.sin_port = htons(6004);
if(bind(serv_sock_r, (struct sockaddr*)&serv_addr_r, sizeof(serv_addr_r)) == -1)
error_handling("bind() error");
if(bind(serv_sock_w, (struct sockaddr*)&serv_addr_w, sizeof(serv_addr_w)) == -1)
error_handling("bind() error");
if(listen(serv_sock_r, 5) == -1)
error_handling("listen() error");
if(listen(serv_sock_w, 5) == -1)
error_handling("listen() error");
srand((unsigned)time(0));
while(1){
clnt_addr_r_size = sizeof(clnt_addr_r);
clnt_sock_r = accept(serv_sock_r, (struct sockaddr *)&clnt_addr_r, &clnt_addr_r_size);
clnt_addr_w_size = sizeof(clnt_addr_w);
clnt_sock_w = accept(serv_sock_w, (struct sockaddr *)&clnt_addr_w, &clnt_addr_w_size);
pthread_mutex_lock(&mutx);
clnt_socks[clnt_no][0] = clnt_sock_r;
pthread_mutex_unlock(&mutx);
pthread_create(&thread, 0, clnt_connection, (void*) clnt_sock_r);
pthread_mutex_lock(&mutx);
clnt_socks[clnt_no++][1] = clnt_sock_w;
pthread_mutex_unlock(&mutx);
printf("game %dth client, IP : %s\\n", clnt_no, inet_ntoa(clnt_addr_r.sin_addr));
}
return 0;
}
void *clnt_connection(void *arg)
{
int clnt_sock_r = (int)arg;
int str_len = 0;
char msg[64];
int i;
while((str_len = read(clnt_sock_r, msg, 5)) != 0){
str_len = strlen(msg);
send_msg(msg, str_len);
}
pthread_mutex_lock(&mutx);
for(i = 0 ; i < clnt_no ; i++){
for(; i < clnt_no-1 ; i++){
clnt_socks[i][0] = clnt_socks[i+1][0];
clnt_socks[i][1] = clnt_socks[i+1][1];
break;
}
}
clnt_no--;
pthread_mutex_unlock(&mutx);
close(clnt_sock_r);
return 0;
}
void send_msg(char *msg, int len)
{
int i;
pthread_mutex_lock(&mutx);
for(i = 0 ; i < clnt_no ; i++){
if(msg[0] != i+48){
write(clnt_socks[i][1], msg, 5);
}
}
pthread_mutex_unlock(&mutx);
}
void error_handling(char * msg)
{
fputs(msg, stderr);
fputc('\\n', stderr);
exit(1);
}
void signal_handling(int signo)
{
}
| 0
|
#include <pthread.h>
{
int id;
int noproc;
int dim;
} parm;
{
int cur_count;
pthread_mutex_t barrier_mutex;
pthread_cond_t barrier_cond;
} barrier_t;
barrier_t mybarrier;
double row[45];
} DATAITEM;
DATAITEM column[45 +1];
int NO_PROC;
void barrier_init(barrier_t * mybarrier)
{
pthread_mutexattr_t attr;
pthread_mutex_init(&(mybarrier->barrier_mutex), 0);
pthread_cond_init(&(mybarrier->barrier_cond), 0);
mybarrier->cur_count = 0;
}
void barrier(int numproc, barrier_t * mybarrier)
{
pthread_mutex_lock(&(mybarrier->barrier_mutex));
mybarrier->cur_count++;
if (mybarrier->cur_count!=numproc) {
pthread_cond_wait(&(mybarrier->barrier_cond), &(mybarrier->barrier_mutex));
}
else
{
mybarrier->cur_count=0;
pthread_cond_broadcast(&(mybarrier->barrier_cond));
}
pthread_mutex_unlock(&(mybarrier->barrier_mutex));
}
void *gesimple(void *arg)
{
parm *p = (parm *) arg;
int me_no=p->id;
int k,j,bcastno;
if (me_no==0) {
begin_userprog();
}
barrier(NO_PROC, &mybarrier);
for(k=0; k<45; k++){
if((bcastno=get_location(k,45 +1,2))== me_no){
task_Tkk(k, &column[k]);
}
barrier(NO_PROC, &mybarrier);
for(j=k+1; j<=45; j++)
if(get_location(j,45 +1,2)== me_no)
task_Tkj(k,j, &column[k],&column[j]);
}
if(get_location(45,45 +1,2)== me_no){
for(k=45 -1; k>= 0; k--)
task_S(k,&column[k], &column[45]);
}
barrier(NO_PROC, &mybarrier);
end_userprog(me_no);
return 0;
}
main(argc,argv)
int argc;
char *argv[];
{
int i;
parm *arg;
pthread_t *threads;
pthread_attr_t pthread_custom_attr;
if (argc != 2)
{
printf("Usage: %s n\\n where n is no. of thread\\n", argv[0]);
exit(1);
}
NO_PROC = atoi(argv[1]);
if ((NO_PROC < 1) || (NO_PROC > 20))
{
printf("The no of thread should between 1 and %d.\\n", 20);
exit(1);
}
threads = (pthread_t *) malloc(NO_PROC * sizeof(*threads));
pthread_attr_init(&pthread_custom_attr);
arg=(parm *)malloc(sizeof(parm)*NO_PROC);
barrier_init(&mybarrier);
for (i = 0; i < NO_PROC; i++)
{
arg[i].id = i;
arg[i].noproc = NO_PROC;
pthread_create(&threads[i], &pthread_custom_attr, gesimple, (void *)(arg+i));
}
for (i = 0; i < NO_PROC; i++)
{
pthread_join(threads[i], 0);
}
free(arg);
exit(0);
}
begin_userprog()
{
gen_test_data(45);
}
end_userprog(int me_no)
{
if(get_location(45,45 +1,2)== me_no)
print_solution(45);
}
gen_test_data(n)
int n;
{
int i,j;
for(j=0;j<n;j++)
for(i=0;i<n; i++)
column[j].row[i] =1;
for(i=0;i<n;i++)
column[i].row[i]=n;
for(i=0;i<n;i++)
column[n].row[i]=2*n-1;
}
print_matrix(n)
int n;
{
register int i,j;
printf("The %d * %d matrix is\\n", n,n+1);
for(i=0;i<n;i++){
for(j=0;j<n+1;j++)
printf("%lf ", column[j].row[i]);
printf("\\n");
}
}
print_solution(n)
int n;
{
register int i;
printf("The solution is :\\n");
for(i=0;i<45;i++){
printf("%lf ", column[n].row[i]);
}
printf("\\n");
}
task_Tkk(k, colk)
int k;
DATAITEM *colk;
{
int i;
double temp;
temp = colk->row[k];
for(i=k+1;i<45;i++)
colk->row[i] /= temp;
}
task_Tkj(k,j, colk, colj)
int k,j;
DATAITEM *colk, *colj;
{
int i;
for(i=k+1;i<45;i++)
colj->row[i] -= colk->row[i]*colj->row[k];
}
task_S(k,colk,colb)
int k;
DATAITEM *colk,*colb;
{
int i;
double temp;
colb->row[k] /= colk->row[k];
temp= colb->row[k];
for (i=k-1;i>=0; i--)
colb->row[i] -= colk->row[i]*temp;
}
broadcast( type,msgbuf,size, x)
char *msgbuf ;
int type,size, x;
{
}
int get_location(j, n,selemap)
int j,n,selemap;
{
return(mapproc(j, selemap, n, NO_PROC));
}
int mapproc(j, selemap, n, p)
int j, selemap, n, p;
{
int r;
double ceil(),floor();
switch(selemap){
case 1:
r = (int) ceil( (double) n/ (double) p);
return((int) floor((double) j/ (double)r));
case 2:
return( j%p);
}
}
| 1
|
#include <pthread.h>
int counter;
int count;
pthread_mutex_t train_mtx;
pthread_mutex_t enter_passenger_mtx;
pthread_mutex_t *exit_passenger_mtx;
pthread_mutex_t counter_mtx;
pthread_mutex_t end_mtx;
void StartTtrip () {
pthread_mutex_lock ( &train_mtx ) ;
printf("Starting...!!!\\n");
}
void EndTrip () {
counter = 0;
while ( count > 0 ) {
pthread_mutex_unlock ( &exit_passenger_mtx[count] );
count--;
}
if ( 100 % 2 == 0 ) {
counter++;
}
pthread_mutex_lock ( &end_mtx );
pthread_mutex_unlock ( &enter_passenger_mtx );
}
void *Train ( void *arg ) {
while ( 1 ) {
StartTtrip ();
printf("On Trip\\n");
EndTrip ();
printf("The trip is finished...\\n");
printf("Preaparing for the next trip....Let's fun..!!\\n");
}
return 0;
}
void *Passengers ( void *arg ) {
int i;
int control_num = 2;
pthread_mutex_lock ( &enter_passenger_mtx );
if ( count < 100 - 1 ) {
count++;
i=count;
pthread_mutex_unlock ( &enter_passenger_mtx );
}else {
count++;
i = count;
pthread_mutex_unlock ( &train_mtx );
}
pthread_mutex_lock ( &exit_passenger_mtx[i] );
printf("Yeahhhhh..It's awesomeeee.....\\n");
pthread_mutex_lock ( &counter_mtx );
counter++;
control_num = 100 % 2;
if ( counter == 100 && control_num == 1) {
pthread_mutex_unlock ( &end_mtx );
}else if ( control_num == 0 ) {
if ( counter == 100 + 1 ) {
pthread_mutex_unlock ( &end_mtx );
}
}
pthread_mutex_unlock ( &counter_mtx );
return(0);
}
int init () {
int i;
pthread_t thread;
count = 0;
if ( pthread_mutex_init ( &train_mtx, 0 ) != 0 ) {
printf("\\n create_mutex init failed\\n");
return 1;
}else {
pthread_mutex_lock( &train_mtx );
}
if ( pthread_mutex_init ( &end_mtx, 0 ) != 0 ) {
printf("\\n create_mutex init failed\\n");
return 1;
}else {
pthread_mutex_lock( &end_mtx );
}
if ( pthread_mutex_init ( &enter_passenger_mtx, 0 ) != 0 ) {
printf("\\n create_mutex init failed\\n");
return 1;
}
if ( pthread_mutex_init ( &counter_mtx, 0 ) != 0 ) {
printf("\\n create_mutex init failed\\n");
return 1;
}
exit_passenger_mtx = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t)*(100 +1));
for(i=0; i<100 +1; i++){
if ( pthread_mutex_init ( &exit_passenger_mtx[i], 0 ) != 0 ) {
printf("\\n create_mutex init failed\\n");
return 1;
}else {
pthread_mutex_lock( &exit_passenger_mtx[i]);
}
}
pthread_create ( &thread, 0, Train, 0 );
return (0);
}
int main ( int argc, char *argv[] ) {
int check_init,NumOfPassengers;
pthread_t thread;
check_init = init();
if ( check_init == 1 ) {
printf("Error in init.\\n");
return 1;
}
while ( 1 ) {
printf("Enter the number of the passengers\\n");
scanf(" %d", &NumOfPassengers );
while ( NumOfPassengers > 0 ) {
pthread_create ( &thread, 0, Passengers, 0 );
NumOfPassengers--;
}
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
void *protected_fun(void *ptr)
{
char *message;
pthread_mutex_lock( &mutex1 );
message = (char *)ptr;
int i;
for(i = 0; i < 5; i++)
{
printf("%s = %d\\n", message, i);
sleep(1);
}
pthread_mutex_unlock( &mutex1 );
}
int main()
{
pthread_t thread1, thread2;
const char *message1 = "Thread 1";
const char *message2 = "Thread 2";
int iret1, iret2;
iret1 = pthread_create(&thread1, 0, protected_fun, (void*)message1);
if(iret1)
{
fprintf(stderr,"Error - pthread_create() return code: %d\\n",iret1);
return iret1;
}
iret2 = pthread_create(&thread2, 0, protected_fun, (void*)message2);
if(iret2)
{
fprintf(stderr,"Error - pthread_create() return code: %d\\n",iret2);
return iret2;
}
printf("pthread_create() for thread 1 returns: %d\\n",iret1);
printf("pthread_create() for thread 2 returns: %d\\n",iret2);
pthread_join( thread1, 0);
pthread_join( thread2, 0);
return 0;
}
| 1
|
#include <pthread.h>
double const delta = 1.0 / 1000000000;
int sliceSize ;
double sum;
pthread_mutex_t sumMutex;
void * partialSum(void *const arg ) {
int const start = 1 + ((long)arg) * sliceSize;
int const end = (((long)arg) + 1) * sliceSize;
double localSum = 0.0;
for (int i = start; i <= end; ++i) {
double const x = (i - 0.5) * delta;
localSum += 1.0 / (1.0 + x * x);
}
pthread_mutex_lock(&sumMutex);
sum += localSum;
pthread_mutex_unlock(&sumMutex);
pthread_exit((void *) 0);
return 0;
}
void execute (const int numberOfThreads) {
long long const startTimeMicros = microsecondTime();
sum = 0.0;
sliceSize = 1000000000 / numberOfThreads;
pthread_mutex_init(&sumMutex, 0);
pthread_attr_t attributes;
pthread_attr_init(&attributes);
pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_JOINABLE);
pthread_t threads[numberOfThreads];
for (long i = 0; i < numberOfThreads; ++i) {
if (pthread_create (&threads[i], &attributes, partialSum, (void *)i) != 0) { exit(1); }
}
pthread_attr_destroy(&attributes);
int status;
for (int i = 0; i < numberOfThreads; ++i) { pthread_join (threads[i], (void **)&status); }
double const pi = 4.0 * delta * sum;
double const elapseTime = (microsecondTime() - startTimeMicros) / 1e6;
outn("PThread Global", pi, 1000000000, elapseTime, numberOfThreads, sysconf(_SC_NPROCESSORS_ONLN));
}
int main() {
execute(1);
execute(2);
execute(8);
execute(32);
return 0;
}
| 0
|
#include <pthread.h>
int g_buffer[10];
unsigned short in = 0;
unsigned short out = 0;
unsigned short produce_id = 0;
unsigned short consume_id = 0;
sem_t g_sem_full;
sem_t g_sem_empty;
pthread_mutex_t g_mutex;
pthread_t g_thread[1 +5];
void *consume(void *arg)
{
int i;
while(1)
{
printf("%d wait buffer not empty\\n", (int)arg);
sem_wait(&g_sem_empty);
pthread_mutex_lock(&g_mutex);
for(i=0; i<10; i++)
{
printf("%02d", i);
if(g_buffer[i] == -1)
printf("%s", "null");
else printf("%d", g_buffer[i]);
if(i == out)
printf("\\t<--consume");
printf("\\n");
}
consume_id = g_buffer[out];
printf("%d begin consume product %d\\n",(int)arg, consume_id);
g_buffer[out] = -1;
out = (out+1)%10;
printf("%d end consume product %d\\n", (int)arg,consume_id);
pthread_mutex_unlock(&g_mutex);
sem_post(&g_sem_full);
sleep(5);
}
return 0;
}
void *produce(void *arg)
{
int i;
while(1)
{
printf("%d wait buffer not full\\n", (int)arg);
sem_wait(&g_sem_full);
pthread_mutex_lock(&g_mutex);
for(i=0; i<10; i++)
{
printf("%02d", i);
if(g_buffer[i] == -1)
printf("%s", "null");
else printf("%d", g_buffer[i]);
if(i == in)
printf("\\t<--produce");
printf("\\n");
}
printf("%d begin produce product %d\\n", (int)arg, produce_id);
g_buffer[in] = produce_id;
in = (in+1)%10;
printf("%d end produce product %d\\n", (int)arg, produce_id++);
pthread_mutex_unlock(&g_mutex);
sem_post(&g_sem_full);
pthread_mutex_unlock(&g_mutex);
sem_post(&g_sem_empty);
sleep(1);
}
return 0;
}
int main()
{
int i;
for(i=0; i<10; i++)
g_buffer[i]= -1;
sem_init(&g_sem_full, 0, 10);
sem_init(&g_sem_empty, 0, 0);
pthread_mutex_init(&g_mutex, 0);
for(i=0; i<1; ++i)
pthread_create(&g_thread[i], 0, consume, (void*)i);
for(i=0; i<5; ++i)
pthread_create(&g_thread[i+1], 0, produce, (void*)i);
for(i=0; i<5 +1; ++i)
pthread_join(g_thread[i], 0);
sem_destroy(&g_sem_full);
sem_destroy(&g_sem_empty);
pthread_mutex_destroy(&g_mutex);
return 0;
}
| 1
|
#include <pthread.h>
pthread_t id;
int loop_time;
struct tm *time;
}item;
item buffer[8];
sem_t empty, full;
pthread_mutex_t mutex;
int in = 0, out = 0;
void Producer(void *arg);
void Consumer(void *arg);
int main(int argc, char *argv[])
{
pthread_t producer[3];
pthread_t consumer[5];
if(sem_init(&full,0,0) != 0 || sem_init(&empty,0,8) != 0) {
printf("Semaphore initialization failed!");
exit(1);
}
if(pthread_mutex_init(&mutex,0) != 0){
printf("Mutex initialization failed!");
exit(1);
}
pthread_create(&producer[0],0,(void *)Producer, 0);
pthread_create(&producer[1],0,(void *)Producer, 0);
pthread_create(&producer[2],0,(void *)Producer, 0);
pthread_create(&consumer[0],0,(void *)Consumer, 0);
pthread_create(&consumer[1],0,(void *)Consumer, 0);
pthread_create(&consumer[2],0,(void *)Consumer, 0);
pthread_create(&consumer[3],0,(void *)Consumer, 0);
pthread_create(&consumer[4],0,(void *)Consumer, 0);
pthread_join(producer[0],0);
pthread_join(producer[1],0);
pthread_join(producer[2],0);
pthread_join(consumer[0],0);
pthread_join(consumer[1],0);
pthread_join(consumer[2],0);
pthread_join(consumer[3],0);
pthread_join(consumer[4],0);
sem_destroy(&full);
sem_destroy(&empty);
pthread_mutex_destroy(&mutex);
exit(0);
}
void Producer(void *arg)
{
int i;
time_t ltime;
item nextProduced;
for(i = 1 ; i <= 5 ; i++ ){
usleep(750000);
sem_wait(&empty);
pthread_mutex_lock(&mutex);
nextProduced.loop_time = i;
time(<ime);
nextProduced.time = localtime(<ime);
nextProduced.id = pthread_self();
buffer[in] = nextProduced;
in = (in+1) % 8;
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void Consumer(void *arg)
{
int i;
item nextConsumed;
for(i=1;i<=3;i++){
usleep(750000);
sem_wait(&full);
pthread_mutex_lock(&mutex);
nextConsumed = buffer[out];
out = (out + 1) % 8;
printf("ID为%lu的生产者线程在第%d次循环产生这条消息,消息时间为%d年%d月%d日,%d:%d:%d\\n",nextConsumed.id,nextConsumed.loop_time,1900+nextConsumed.time->tm_year,1+nextConsumed.time->tm_mon,1+nextConsumed.time->tm_mday,nextConsumed.time->tm_hour,nextConsumed.time->tm_min,nextConsumed.time->tm_sec);
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
| 0
|
#include <pthread.h>
int count = 0;
int thread_ids[3] = {0,1,2};
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *inc_count(void *t)
{
int i;
long my_id = (long)t;
for (i=0; i<10; i++) {
pthread_mutex_lock(&count_mutex);
count++;
if (count == 12) {
pthread_cond_signal(&count_threshold_cv);
printf("inc_count(): thread %ld, count = %d Threshold reached.\\n",
my_id, count);
}
printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n",
my_id, count);
pthread_mutex_unlock(&count_mutex);
sleep(1);
}
pthread_exit(0);
}
void *watch_count(void *t)
{
long my_id = (long)t;
printf("Starting watch_count(): thread %ld\\n", my_id);
pthread_mutex_lock(&count_mutex);
while (count<12) {
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %ld Condition signal received.\\n", my_id);
count += 125;
printf("watch_count(): thread %ld count now = %d.\\n", my_id, count);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main (int argc, char *argv[])
{
int i, rc;
long t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, watch_count, (void *)t1);
pthread_create(&threads[1], &attr, inc_count, (void *)t2);
pthread_create(&threads[2], &attr, inc_count, (void *)t3);
for (i=0; i<3; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited on %d threads. Done.\\n", 3);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int recordSize = 1024;
int threadsNr;
char *fileName;
int fd;
int numOfRecords;
int creatingFinished = 0;
char *word;
int rc;
int someonefound = 0;
int detachedNr = 0;
pthread_key_t key;
pthread_t *threads;
int *wasJoin;
pthread_mutex_t mutexForRecords = PTHREAD_MUTEX_INITIALIZER;
long gettid()
{
return syscall(SYS_gettid);
}
void* threadFun(void *oneArg)
{
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
pthread_t threadHandle = pthread_self();
pthread_t threadID = gettid();
printf("new thread with handle: %ld with tid: %ld\\n", threadHandle,threadID);
char **readRecords = calloc(numOfRecords, sizeof(char*));
for(int i = 0;i<numOfRecords;i++)
readRecords[i] = calloc(1024, sizeof(char));
pthread_setspecific(key, readRecords);
readRecords = pthread_getspecific(key);
while(!creatingFinished);
int finish = 0;
int moreBytesToRead = 1;
int numOfReadedBytes;
while(!finish && moreBytesToRead)
{
pthread_mutex_lock(&mutexForRecords);
for(int i=0;i<numOfRecords;i++)
{
numOfReadedBytes = read(fd, readRecords[i], 1024);
if(numOfReadedBytes==-1)
{
perror("error while reading in threadFun");
exit(1);
}
if(numOfReadedBytes<1024)
moreBytesToRead = 0;
}
pthread_mutex_unlock(&mutexForRecords);
for(int i = 0; i<numOfRecords; i++)
{
if(strstr(readRecords[i], word) != 0)
{
char recID[10];
strncpy(recID, readRecords[i], 10);
printf("%ld: found word in record number %d\\n", threadID, atoi(recID));
}
}
}
if(pthread_detach(threadHandle) != 0)
{
perror("pthread_detach error");
exit(1);
}
detachedNr++;
pthread_exit(0);
}
int openFile(char *fileName)
{
int fd = open(fileName, O_RDONLY);
if(fd == -1)
{
perror("file open error");
exit(-1);
}
else
return fd;
}
void createThread(pthread_t *thread)
{
rc = pthread_create(thread, 0, threadFun, 0);
if(rc != 0)
{
perror("thread create error");
exit(-1);
}
}
void readArgs(int argc, char *argv[])
{
if(argc!=5)
{
puts("Bad number of arguments");
puts("Appropriate arguments:");
puts("[program] [threads nr] [file] [records nr] [word to find]");
exit(-1);
}
threadsNr = atoi(argv[1]);
fileName = calloc(1,sizeof(argv[2]));
fileName = argv[2];
numOfRecords = atoi(argv[3]);
word = calloc(1,sizeof(argv[4]));
word = argv[4];
fd = openFile(fileName);
return;
}
void makeClean()
{
close(fd);
free(threads);
pthread_key_delete(key);
pthread_mutex_destroy(&mutexForRecords);
}
int main(int argc, char *argv[])
{
readArgs(argc,argv);
char **readRecords = calloc(numOfRecords, sizeof(char*));
for(int i = 0;i<numOfRecords;i++)
readRecords[i] = calloc(1024, sizeof(char));
pthread_key_create(&key, 0);
threads = calloc(threadsNr, sizeof(pthread_t));
wasJoin = calloc(threadsNr, sizeof(int));
for(int i=0; i<threadsNr; i++)
createThread(&threads[i]);
creatingFinished = 1;
while(detachedNr != threadsNr)
usleep(100);
printf("End of program\\n\\n");
makeClean();
return 0;
}
| 0
|
#include <pthread.h>
static void thread_create(pthread_t *tid,void *(*fun)(void *));
static void thread_wait(pthread_t tid);
static void maketimeout(struct timespec *tsp,long min);
void * fun1(void *arg);
void * fun2(void *arg);
pthread_mutex_t lock;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
struct timespec tsp;
int sum = 0;
int main(int argc, char const *argv[])
{
pthread_mutex_init(&lock,0);
pthread_t tid1;
pthread_t tid2;
thread_create(&tid1,fun1);
thread_create(&tid2,fun2);
thread_wait(tid1);
thread_wait(tid2);
return 0;
}
static void thread_create(pthread_t *tid,void *(*fun)(void *))
{
int res = 0;
res = pthread_create(tid,0,fun,0);
if (res == 0)
printf("successfully create");
sleep(1);
}
static void thread_wait(pthread_t tid)
{
int res = 0;
int status = 0;
res = pthread_join(tid,(void *)&status);
if (res == 0){
printf("wait thread %lu successfully\\n",tid);
printf("the return val:%d\\n",status );
}
else
perror("join thread");
}
void * fun1(void *arg)
{
printf(" thread 1\\n");
int i = 0;
for (; ; ) {
pthread_mutex_lock(&lock);
sum +=i;
pthread_mutex_unlock(&lock);
i++;
pthread_mutex_lock(&lock);
printf("thread 1 sum:%d\\n",sum );
if (sum >100) {
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&lock);
sleep(1);
}
pthread_exit((void *)0);
}
static void maketimeout(struct timespec *tsp,long min)
{
struct timeval now;
gettimeofday(&now, 0);
tsp->tv_sec = now.tv_sec;
tsp->tv_nsec = now.tv_usec * 1000;
tsp->tv_sec += min * 60;
}
void * fun2(void *arg)
{
int i =0;
printf(" thread 2\\n");
pthread_mutex_lock(&lock);
maketimeout(&tsp,1);
pthread_cond_timedwait(&cond,&lock,&tsp);
while(sum >0)
{
sum -=i;
i++;
printf("thread 2 sum:%d\\n", sum);
}
pthread_mutex_unlock(&lock);
sleep(3);
pthread_exit((void *)0);
}
| 1
|
#include <pthread.h>
struct job {
struct job* next;
int dato;
};
struct job* job_queue;
pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER;
void* raiz_cuadrada (void* arg){
while (1){
struct job* next_job;
pthread_mutex_lock (&job_queue_mutex);
if (job_queue == 0){
next_job = 0;
}
else {
next_job = job_queue;
job_queue = job_queue->next;
}
pthread_mutex_unlock (&job_queue_mutex);
if (next_job == 0){
break;
}
printf("Raiz %d = %f\\n",next_job->dato,sqrt(next_job->dato));
free (next_job);
}
return 0;
}
void* logaritmo (void* arg){
while (1){
struct job* next_job;
pthread_mutex_lock (&job_queue_mutex);
if (job_queue == 0){
next_job = 0;
}
else {
next_job = job_queue;
job_queue = job_queue->next;
}
pthread_mutex_unlock (&job_queue_mutex);
if (next_job == 0){
break;
}
printf("Logaritmo %d = %f\\n",next_job->dato,log(next_job->dato));
free (next_job);
}
return 0;
}
void* exponencia (void* arg){
while (1){
struct job* next_job;
pthread_mutex_lock (&job_queue_mutex);
if (job_queue == 0){
next_job = 0;
}
else {
next_job = job_queue;
job_queue = job_queue->next;
}
pthread_mutex_unlock (&job_queue_mutex);
if (next_job == 0){
break;
}
printf("Exponencial %d = %f\\n",next_job->dato,exp(next_job->dato));
free (next_job);
}
return 0;
}
void enqueue_job (int dato){
struct job* new_job;
new_job = (struct job*) malloc (sizeof (struct job));
pthread_mutex_lock (&job_queue_mutex);
new_job->next = job_queue;
job_queue = new_job;
job_queue->dato = dato;
pthread_mutex_unlock (&job_queue_mutex);
}
int main(int argc, char const *argv[]){
int i;
pthread_t hilo1, hilo2, hilo3;
for (i = 1; i < 101; i++){
enqueue_job(i);
}
pthread_create (&hilo1, 0, &raiz_cuadrada,0);
pthread_create (&hilo2, 0, &logaritmo,0);
pthread_create (&hilo3, 0, &exponencia,0);
pthread_join (hilo1,0);
pthread_join (hilo2,0);
pthread_join (hilo3,0);
return 0;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.