text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
int SHARED_GLOBAL_VAR = -1;
int count = 0;
int readers = 0;
pthread_mutex_t mux = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c_reader = PTHREAD_COND_INITIALIZER;
pthread_cond_t c_writer = PTHREAD_COND_INITIALIZER;
void *writer(void* param);
void *reader(void* param);
void randomWait();
int main() {
srand(time(0));
int num_threads = 5;
int ints[num_threads];
pthread_t writer_threads[num_threads];
pthread_t reader_threads[num_threads];
for (int i=0; i<num_threads; ++i) {
ints[i] = i;
pthread_create(&writer_threads[i], 0, writer, &ints[i]);
randomWait();
pthread_create(&reader_threads[i], 0, reader, 0);
readers++;
}
for (int i=0; i<num_threads; ++i) {
pthread_join(writer_threads[i], 0);
pthread_join(reader_threads[i], 0);
}
}
void *writer(void* param) {
uint64_t tid;
pthread_threadid_np(0, &tid);
randomWait();
pthread_mutex_lock(&mux);
int i = *((int *) param);
while (readers > 0) {
pthread_cond_signal(&c_reader);
pthread_cond_wait(&c_writer, &mux);
}
SHARED_GLOBAL_VAR = i;
fflush(stdout);
pthread_mutex_unlock(&mux);
pthread_cond_signal(&c_reader);
pthread_cond_signal(&c_writer);
return 0;
}
void *reader(void* param) {
uint64_t tid;
pthread_threadid_np(0, &tid);
randomWait();
pthread_mutex_lock(&mux);
while (readers == 0) {
pthread_cond_wait(&c_reader, &mux);
}
readers--;
pthread_mutex_unlock(&mux);
pthread_cond_signal(&c_writer);
return 0;
}
void randomWait() {
int r = rand();
r = 50 * (r % 10000);
usleep(r);
float ms = r / 1000.0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
static void * func_add( void *arg){
volatile mytype *p = (mytype *) arg;
for( int i = 0; i < 100000000 ; i++){
pthread_mutex_lock(&mut);
(*p)++;
pthread_mutex_unlock(&mut);
}
return 0;
}
static void * func_sub( void *arg){
volatile mytype *p = (mytype *) arg;
for( int i = 0; i < 100000000 ; i++){
pthread_mutex_lock(&mut);
(*p)--;
pthread_mutex_unlock(&mut);
}
return 0;
}
int main( int argc, char** argv){
mytype tmp = 0;
pthread_t tinfo[2];
long long time_start = __rdtsc();
pthread_create( &tinfo[0], 0 , &func_add, (void*)&tmp );
pthread_create( &tinfo[1], 0 , &func_sub, (void*)&tmp );
pthread_join( tinfo[0], 0 );
pthread_join( tinfo[1], 0 );
printf("time = %lld result = %lld\\n", __rdtsc() - time_start , (long long int) tmp);
return 0;
}
| 0
|
#include <pthread.h>
clock_t timeInsert;
clock_t timeMember;
clock_t timeDelete;
float timeInsertTotal,timeMemberTotal,timeDeleteTotal = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct list_node_s{
int data;
struct list_node_s* next;
};
int Member(int value, struct list_node_s* head_p){
struct list_node_s* curr_p = head_p;
while(curr_p != 0 && curr_p->data < value){
curr_p = curr_p->next;
}
if(curr_p == 0 || curr_p->data > value){
return 0;
}
else {
return 1;
}
}
int Insert(int value, struct list_node_s** head_p){
struct list_node_s* curr_p = *head_p;
struct list_node_s* pred_p = 0;
struct list_node_s* temp_p;
while(curr_p != 0 && curr_p->data < value){
pred_p = curr_p;
curr_p = curr_p->next;
}
if(curr_p == 0 || curr_p->data > value){
temp_p = malloc(sizeof(struct list_node_s));
temp_p->data = value;
temp_p->next = curr_p;
if(pred_p == 0)
*head_p = temp_p;
else pred_p->next = temp_p;
return 1;
}
else return 0;
}
int Delete(int value, struct list_node_s** head_p){
struct list_node_s* curr_p = *head_p;
struct list_node_s* pred_p = 0;
while(curr_p != 0 && curr_p->data < value){
pred_p = curr_p;
curr_p = curr_p->next;
}
if(curr_p != 0 && curr_p->data == value){
if(pred_p == 0){
*head_p = curr_p->next;
free(curr_p);
}
else{
pred_p->next = curr_p->next;
free(curr_p);
}
return 1;
}
else{
return 0;
}
}
struct list_node_s* list = 0;
void Cant_Insert(int cant){
int i;
for(i = 0; i < cant; i++) {
pthread_mutex_lock(&mutex);
Insert(1000,&list);
pthread_mutex_unlock(&mutex);
}
return;
}
void Cant_Member(int cant){
int i;
for(i = 0; i < cant; i++) {
pthread_mutex_lock(&mutex);
Member(1000,list);
pthread_mutex_unlock(&mutex);
}
return;
}
void Cant_Delete(int cant){
int i;
for(i = 0; i < cant; i++) {
pthread_mutex_lock(&mutex);
Delete(1000,&list);
pthread_mutex_unlock(&mutex);
}
return;
}
void* Operaciones(void* rank){
long my_rank = (long) rank;
timeMember = clock();
Cant_Member(998);
timeMember = clock() - timeMember;
timeMemberTotal+= (((float)timeMember)/CLOCKS_PER_SEC);
timeInsert = clock();
Cant_Insert(1);
timeInsert = clock() - timeInsert;
timeInsertTotal+= (((float)timeInsert)/CLOCKS_PER_SEC);
timeDelete = clock();
Cant_Delete(2);
timeDelete = clock() - timeDelete;
timeDeleteTotal+= (((float)timeDelete)/CLOCKS_PER_SEC);
return 0;
}
int main(int argc, char* argv[]){
long thread;
double thread_count;
pthread_t *thread_handles;
struct list_node_s* list = 0;
thread_count = strtol(argv[1],0,10);
thread_handles = malloc(thread_count* sizeof(pthread_t));
for(thread=0;thread<thread_count;thread++)
{
pthread_create(&thread_handles[thread],0,Operaciones,(void*)thread);
}
for(thread=0;thread<thread_count;thread++)
{
pthread_join(thread_handles[thread],0);
}
printf("Insert Total %lf\\n", timeInsertTotal);
printf("Member Total %lf\\n", timeMemberTotal);
printf("Delete Total %lf\\n", timeDeleteTotal);
return 0;
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
void __VERIFIER_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error();}; return; }
char *v;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
void *thread1(void * arg)
{
v = malloc(sizeof(char));
return 0;
}
void *thread2(void *arg)
{
pthread_mutex_lock (&m);
v[0] = 'X';
pthread_mutex_unlock (&m);
return 0;
}
void *thread3(void *arg)
{
pthread_mutex_lock (&m);
v[0] = 'Y';
pthread_mutex_unlock (&m);
return 0;
}
void *thread0(void *arg)
{
pthread_t t1, t2, t3, t4, t5;
pthread_create(&t1, 0, thread1, 0);
pthread_join(t1, 0);
pthread_create(&t2, 0, thread2, 0);
pthread_create(&t3, 0, thread3, 0);
pthread_create(&t4, 0, thread2, 0);
pthread_create(&t5, 0, thread2, 0);
pthread_join(t2, 0);
pthread_join(t3, 0);
pthread_join(t4, 0);
pthread_join(t5, 0);
return 0;
}
int main(void)
{
pthread_t t;
pthread_create(&t, 0, thread0, 0);
pthread_join(t, 0);
__VERIFIER_assert(v[0] == 'X' || v[0] == 'Y');
return 0;
}
| 0
|
#include <pthread.h>
struct task * generate_task(void (*func)(void *, struct task *), void *arg) {
struct task *t = dsm_malloc(sizeof(struct task));
t->func = func;
t->arg = arg;
t->next = 0;
t->deps = 0;
t->parent = 0;
return t;
}
struct task * enqueue_task(struct task *t) {
while (pthread_mutex_trylock(SCHED_LOCK) == EBUSY);
t->next = (*(struct task **)(SCHED_PAGE + 0x88));
if(!(*(struct task **)(SCHED_PAGE + 0x88))) (*(struct task ***)(SCHED_PAGE + 0x90)) = &t->next;
(*(struct task **)(SCHED_PAGE + 0x88)) = t;
pthread_mutex_unlock(SCHED_LOCK);
return t;
}
struct task * enqueue(void (*func)(void *, struct task *), void *arg) {
return enqueue_task(generate_task(func, arg));
}
int totaldeps = 0;
void print_task(struct task *t) {
DEBUG_LOG("%p {func: %p, deps: %d, parent %p}", t, t->func, t->deps, t->parent);
}
void whats_goin_on() {
struct task *n = (*(struct task **)(SCHED_PAGE + 0x88));
DEBUG_LOG("totaldeps: %d", totaldeps);
printf("[");
while(n) {
printf("%p, ", n);
n = n->next;
}
printf("]\\n");
n = (*(struct task **)(SCHED_PAGE + 0x88));
while(n) {
print_task(n);
n = n->next;
}
}
void task_dependency(struct task *parent, struct task *child) {
while (pthread_mutex_trylock(SCHED_LOCK) == EBUSY);
if(child->parent) {
DEBUG_LOG("say what?! %p", child);
whats_goin_on();
}
child->parent = parent;
if(parent->deps++ > 10) {
DEBUG_LOG("a what's going on");
whats_goin_on();
}
totaldeps++;
pthread_mutex_unlock(SCHED_LOCK);
}
int has_task() {
return ((*(struct task **)(SCHED_PAGE + 0x88)) != 0);
}
void dequeue_and_run_task() {
while (pthread_mutex_trylock(SCHED_LOCK) == EBUSY);
if(!(*(struct task **)(SCHED_PAGE + 0x88))) goto end;
struct task *n;
n = (*(struct task **)(SCHED_PAGE + 0x88));
(*(struct task **)(SCHED_PAGE + 0x88)) = (*(struct task **)(SCHED_PAGE + 0x88))->next;
struct task *first = n;
int bored = 0;
while(n->deps) {
*(*(struct task ***)(SCHED_PAGE + 0x90)) = n;
n->next = 0;
(*(struct task ***)(SCHED_PAGE + 0x90)) = &n->next;
if(!(*(struct task **)(SCHED_PAGE + 0x88))) (*(struct task **)(SCHED_PAGE + 0x88)) = n;
pthread_mutex_unlock(SCHED_LOCK);
pthread_yield();
while (pthread_mutex_trylock(SCHED_LOCK) == EBUSY);
if((*(struct task **)(SCHED_PAGE + 0x88))) {
n = (*(struct task **)(SCHED_PAGE + 0x88));
(*(struct task **)(SCHED_PAGE + 0x88)) = (*(struct task **)(SCHED_PAGE + 0x88))->next;
}
else goto end;
}
pthread_mutex_unlock(SCHED_LOCK);
n->func(n->arg, n);
while (pthread_mutex_trylock(SCHED_LOCK) == EBUSY);
if (n->parent) {
n->parent->deps--;
totaldeps--;
}
dsm_free(n, sizeof(struct task));
end:
pthread_mutex_unlock(SCHED_LOCK);
}
| 1
|
#include <pthread.h>
bool done = 0;
int size = 0;
pthread_mutex_t count_mutex;
pthread_cond_t count_cond;
int number;
struct LList *next;
} LList;
void *T1(void *t);
void *T2(void *t);
int randGen();
int getFactorial(int toFact);
int getEntry(LList *head_loc);
void AddEntry(LList *head_loc, int num);
void * T1(void *t) {
printf("Producer Started\\n");
struct LList *ll = (struct LList*) t;
int value;
while (!done) {
usleep(randSleep());
pthread_mutex_lock(&count_mutex);
if (size == 10) {
printf("Queue is full\\n");
} else {
value = randGen();
AddEntry(ll, value);
size++;
printf("Producer added %d to queue, size = %d\\n", value, size);
pthread_cond_broadcast(&count_cond);
}
pthread_mutex_unlock(&count_mutex);
}
pthread_exit(0);
}
void *T2(void *t) {
printf("Consumer Started\\n");
struct LList *ll = (struct LList*) t;
int queue_value;
while (!done) {
usleep(randSleep());
pthread_mutex_lock(&count_mutex);
if (size != 0) {
queue_value = getEntry(ll);
size--;
printf("Consumer removed %d, computed %d! = %d, queue size = %d\\n",
queue_value, queue_value, getFactorial(queue_value), size);
} else {
pthread_cond_wait(&count_cond, &count_mutex);
}
pthread_mutex_unlock(&count_mutex);
}
pthread_exit(0);
}
int randGen() {
int random_int = rand();
random_int = (random_int % 10) + 1;
return random_int;
}
int randSleep() {
int factor = 100000;
int sleep_time = 1;
while (factor != 1) {
sleep_time += factor * (randGen() - 1);
factor /= 10;
}
return sleep_time;
}
int getFactorial(int input) {
if (input <= 1) {
return 1;
} else {
return (input * getFactorial(input - 1));
}
return 0;
}
void AddEntry(LList *head_loc, int val) {
LList *newNode;
LList *head;
head = head_loc;
newNode = (LList *) malloc(sizeof(LList));
if (newNode == 0) {
fprintf(stderr,"Error: Node Could Not Be Allocated -> Exiting\\n");
exit(1);
}
if (size == 10) {
return;
}
newNode->number = val;
newNode->next = 0;
while (head->next != 0) {
head = head->next;
}
head->next = newNode;
}
int getEntry(LList *head_loc) {
int newHead = 0;
LList *head;
head = head_loc;
LList *prev;
prev = head;
head = head->next;
newHead = head->number;
prev->next = head->next;
head->next = 0;
free(head);
return newHead;
}
int main(int argc, char *argv[]) {
int cons = 0, prods = 0;
if (argc <= 2) {
exit(0);
}
cons = atoi(argv[2]);
prods = atoi(argv[1]);
if (argc > 3) {
fprintf(stderr, "Error: Too Many Arguments\\n");
} else {
if (prods > 5 || prods <= 0) {
fprintf(stderr, "Error: Producer Value Invalid\\n");
exit(0);
} else {
if (cons > 5 || cons <= 0) {
fprintf(stderr, "Error: Consumer Value Invalid\\n");
exit(0);
}
}
}
pthread_t thread[prods + cons];
pthread_attr_t attr;
int t;
void *status;
LList *queue_list;
queue_list = (LList*) malloc(sizeof(LList));
queue_list->next = 0;
pthread_mutex_init(&count_mutex, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (t = 0; t < prods; t++) {
pthread_create(&thread[t], &attr, T1, (void *) queue_list);
}
for (t = 0; t < cons; t++) {
pthread_create(&thread[prods + t], &attr, T2, (void *) queue_list);
}
sleep(30);
done = 1;
for (t = 0; t < prods + cons; t++)
pthread_join(thread[t], &status);
printf("Main program completed. Exiting. Count = %d\\n", size);
struct LList *ll = queue_list;
while(size!=0){
getEntry(ll);
size--;
}
free(queue_list);
return(0);
}
| 0
|
#include <pthread.h>
int var = 0;
int var2 = 100000;
pthread_mutex_t mutex_1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_2 = PTHREAD_MUTEX_INITIALIZER;
void* sumar();
void* restar();
int main(){
pthread_t suma;
pthread_t resta;
pthread_create(&suma,0,sumar,0);
pthread_create(&resta,0,restar,0);
pthread_join(suma,0);
pthread_join(resta,0);
printf("El valor de var es: %d \\n",var);
printf("El valor de resta es: %d \\n",var2);
return 0;
}
void* sumar(){
int i;
int temp;
for (i=0;i<100000;++i){
pthread_mutex_lock(&mutex_1);
temp = var;
var += 3;
while (pthread_mutex_trylock(&mutex_2)){
pthread_mutex_unlock(&mutex_1);
pthread_mutex_lock(&mutex_1);
}
var2 = var2 + 1;
pthread_mutex_unlock(&mutex_2);
pthread_mutex_unlock(&mutex_1);
}
pthread_exit(0);
}
void* restar(){
int i;
int temp;
for (i=0;i<100000;++i){
pthread_mutex_lock(&mutex_2);
temp = var;
var -= 3;
while (pthread_mutex_trylock(&mutex_1)){
pthread_mutex_unlock(&mutex_2);
pthread_mutex_lock(&mutex_2);
}
var2 = var2 - 1;
pthread_mutex_unlock(&mutex_2);
pthread_mutex_unlock(&mutex_1);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
void init_serial_comm(){
pthread_mutex_init(&m_analizza_pacchetto, 0);
int i;
tty_open(PIC_DEVICE);
for(i=0;i<N_PIC_MES_BUFF;i++){*(pic_message_buffer+i)=malloc(MAX_PIC_MES_LENGHT*sizeof(unsigned char));}
current_pic_packet_slot=0;
}
void signal_handler_IO (int status) {
pthread_mutex_lock (&m_analizza_pacchetto);
flag=1;
pthread_cond_signal (&cv_analizza_pacchetto);
pthread_mutex_unlock (&m_analizza_pacchetto);
}
int tty_open(char* tty_dev) {
struct termios new_attributes;
pic_fd = open(tty_dev,O_RDWR| O_NOCTTY | O_NONBLOCK);
if (pic_fd<0) {
return -1;
}
else {
tcgetattr(pic_fd,&oldtio);
tcgetattr(pic_fd,&new_attributes);
fcntl(pic_fd, F_SETFL, 0);
new_attributes.c_cflag |= CREAD;
new_attributes.c_cflag |= B115200;
new_attributes.c_cflag |= CS8;
new_attributes.c_iflag |= IGNPAR;
new_attributes.c_lflag &= ~(ICANON);
new_attributes.c_lflag &= ~(ECHO);
new_attributes.c_lflag &= ~(ECHOE);
new_attributes.c_lflag &= ~(ISIG);
new_attributes.c_cc[VMIN]=5;
new_attributes.c_cc[VTIME]=10;
new_attributes.c_oflag = 0;
new_attributes.c_oflag &= ~OPOST;
tcsetattr(pic_fd, TCSANOW, &new_attributes);
}
return pic_fd;
}
void close_serial_comm()
{
int i;
for(i=0;i<N_PIC_MES_BUFF;i++)
{
free(pic_message_buffer[i]);
}
pthread_mutex_destroy(&m_analizza_pacchetto);
}
| 0
|
#include <pthread.h>
pthread_mutex_t count_mutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t count_mutex3 = PTHREAD_MUTEX_INITIALIZER;
pthread_t tID[3];
int resultMatrix [3][3];
int array [3][3];
void *solveMatrix (void *arg){
long tid, i, j;
tid = (long) arg;
if(tid == 0){
printf("Thread 1\\n");
for(i = 0; i < 3; i++){
int sum = 0;
printf("%d ", array[0][i]);
for(j =0; j < 3; j++){
sum = sum + (array[0][j] * array[j][i]);
}
resultMatrix[0][i] = sum;
}
printf("\\n");
pthread_mutex_unlock( &count_mutex2);
pthread_exit(0);
}
if(tid == 1){
printf("Thread 2 Befor\\n");
pthread_mutex_lock( &count_mutex2 );
printf("Thread 2 After\\n");
for(i = 0; i < 3; i++){
int sum = 0;
printf("%d ", array[1][i]);
for(j =0; j < 3; j++){
sum = sum + (array[1][j] * array[j][i]);
}
resultMatrix[1][i] = sum;
}
printf("\\n");
pthread_mutex_unlock( &count_mutex3);
pthread_exit(0);
}
if(tid == 2){
printf("Thread 3 Before\\n");
pthread_mutex_lock( &count_mutex3 );
printf("Thread 3 After\\n");
for(i = 0; i < 3; i++){
int sum = 0;
printf("%d ", array[2][i]);
for(j =0; j < 3; j++){
sum = sum + (array[2][j] * array[j][i]);
}
resultMatrix[2][i] = sum;
}
printf("\\n");
pthread_exit(0);
}
}
void assignValuesToMatrix(){
array[0][0] = 1;
array[0][1] = 2;
array[0][2] = 3;
array[1][0] = 4;
array[1][1] = 5;
array[1][2] = 6;
array[2][0] = 7;
array[2][1] = 8;
array[2][2] = 9;
}
int main(void){
long i = 0, j;
pthread_mutex_lock( &count_mutex2 );
pthread_mutex_lock( &count_mutex3 );
assignValuesToMatrix();
for(i = 0; i < 3; i++){
int error = pthread_create(&tID[i],0,solveMatrix,(void *) i);
if(error == 0){
}else{
}
}
sleep(3);
printf("\\n\\nResult:\\n");
for(i = 0; i < 3; i++){
for(j = 0; j < 3; j++){
printf("%d ", resultMatrix[i][j]);
}
printf("\\n");
}
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
FILE*file;
int num;
}ph;
int count=0;
char array[1000];
int process=0;
pthread_mutex_t mutex;
int mut;
ph one;
ph two;
void *read_thread(void *ptr);
int main(void) {
pthread_mutex_init(&mutex, 0);
FILE*file1;
FILE*file2;
file1=fopen("data1.txt", "r");
file2=fopen("data2.txt", "r");
one.file=file1;
two.file=file2;
one.num=0;
two.num=1;
pthread_t thread1;
pthread_t thread2;
pthread_create(&thread1, 0, (void*)&read_thread, (void*)&one);
pthread_create(&thread2, 0, (void*)&read_thread, (void*)&two);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
fclose(file1);
fclose(file2);
printf("THE MESSAGE IS: ");
int y;
for(y=0; y<48; y++) {
printf("%c", array[y]);
}
return 0;
}
void *read_thread(void *arg) {
char c;
int end=1;
ph *point;
point=((ph*)(arg));
while(!feof(point->file)) {
pthread_mutex_lock(&mutex);
if(process%2!=point->num) {
}
else {
pthread_mutex_unlock(&mutex);
c=fgetc(point->file);
if(c!='\\n'&&c!='\\r'&&c!='\\0') {
array[count] = c;
count++;
process++;
}
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(&end);
}
| 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 startted....\\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 not 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 = fork()) == 0)
printf("child returned from fork\\n");
else
printf("parent returned from fork\\n");
exit(0);
}
| 1
|
#include <pthread.h>
int end;
int i,j;
char buffer[5];
pthread_mutex_t mutex;
pthread_cond_t empty,full;
int thread_num;
int par_count;
} thdata;
void Producer(FILE *fp)
{
char s1;
s1 = fgetc(fp);
while(1)
{
pthread_mutex_lock(&mutex);
buffer[i] = s1;
i = (i+1)%5;
if((i-1)%5 == j)
{
pthread_cond_signal(&empty);
}
if(i == j)
{
pthread_cond_wait(&full, &mutex);
}
pthread_mutex_unlock(&mutex);
s1=fgetc(fp);
if(feof(fp))
{
pthread_mutex_lock(&mutex);
end = 1;
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
break;
}
}
}
void Consumer(void *ptr)
{
while(1)
{
pthread_mutex_lock(&mutex);
if(i == j)
{
if(end) break;
else
{
pthread_cond_wait(&empty, &mutex);
if(i == j && end) break;
}
}
printf("%c",buffer[j]);
j = (j+1)%5;
if(i == (j-1)%5)
{
pthread_cond_signal(&full);
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main(int argc, char *argv[])
{
pthread_t p, c;
FILE *fp;
i = 0;
j = 0;
if((fp=fopen("strings.txt", "r"))==0)
{
printf("ERROR: within string.txt!\\n");
return -1;
}
pthread_mutex_init(&mutex, 0);
pthread_cond_init (&empty, 0);
pthread_cond_init (&full, 0);
end = 0;
pthread_create (&p, 0, (void *) &Producer, (FILE *) fp);
pthread_create (&c, 0, (void *) &Consumer, 0);
pthread_join(p, 0);
pthread_join(c, 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&empty);
pthread_cond_destroy(&full);
return 1;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int curThread = 0;
int timecount = 0;
void *createThread(void *input) {
pthread_mutex_lock(&mutex);
curThread++;
int actual = curThread;
printf("Hello from thread No. %d!\\n", curThread);
pthread_mutex_unlock(&mutex);
int tcount = 0;
timecount += (*(int*) input);
pthread_t p1, p2;
sleep(*(int*)input);
while(tcount < 2) {
pthread_mutex_lock(&mutex);
if(curThread < 10) {
pthread_mutex_unlock(&mutex);
int num = (int) rand()%10;
if (tcount == 0){
pthread_create(&p1, 0, createThread, &num);
}
else {
pthread_create(&p2, 0, createThread, &num);
}
}
pthread_mutex_unlock(&mutex);
tcount++;
}
pthread_join(p1, 0);
pthread_join(p2, 0);
printf("Bye from thread No. %d!\\n", actual);
}
int main() {
int start = 3;
createThread(&start);
printf("Die Threads haben zusammen %d Sekunden gewartet.\\n", timecount);
}
| 1
|
#include <pthread.h>
int N;
int *vetorPrefixosSeq;
int *vetorPrefixosPar;
int threads = 0;
pthread_mutex_t mutex, mutex_bar;
pthread_cond_t cond_bar;
void barreira(int NTHREADS) {
pthread_mutex_lock(&mutex_bar);
threads++;
if (threads < NTHREADS) {
pthread_cond_wait(&cond_bar, &mutex_bar);
} else {
threads=0;
pthread_cond_broadcast(&cond_bar);
}
pthread_mutex_unlock(&mutex_bar);
}
void somaPrefixosSequencial(){
int i;
for (i = 1; i < N; ++i) {
vetorPrefixosSeq[i] = vetorPrefixosSeq[i - 1] + vetorPrefixosSeq[i];
}
}
void *somaPrefixosParalela(void *threadid){
int i, j, pot;
int *tid = (int*) threadid;
int aux;
for (i = 0; i < log2(N); i++){
pot = pow(2, i);
if(*tid >= pot){
aux = vetorPrefixosPar[*tid] + vetorPrefixosPar[(*tid - pot)];
barreira(N-pot);
vetorPrefixosPar[*tid] = aux;
barreira(N-pot);
}
}
}
void compararVetor(){
int i;
for (i = 0; i < N; i++){
if(vetorPrefixosSeq[i] != vetorPrefixosPar[i]){
printf("NAO SAO IGUAIS !!!\\n");
break;
}
}
printf("SAO IGUAIS !!!\\n");
}
void imprimirVetor(int *vetorPrefixos){
int i;
for (i = 0; i < N; ++i){
if(i == N-1)
printf("%d\\n", vetorPrefixos[i]);
else
printf("%d, ", vetorPrefixos[i]);
}
}
void popularVetorSeq(){
int i;
for (i = 0; i < N; ++i){
vetorPrefixosSeq[i] = i + 1;
}
}
void popularVetorPar(){
int i;
for (i = 0; i < N; ++i){
vetorPrefixosPar[i] = i + 1;
}
}
int main(int argc, char *argv[]){
printf("\\nDigite o numero de elementos N: ");scanf("%d", &N);
pthread_t tid[N-1];
int t, *id;
double start, finish, elapsed;
pthread_mutex_init(&mutex, 0);
pthread_mutex_init(&mutex_bar, 0);
pthread_cond_init(&cond_bar, 0);
vetorPrefixosSeq = malloc(N * sizeof(int));
vetorPrefixosPar = malloc(N * sizeof(int));
popularVetorSeq();
popularVetorPar();
GET_TIME(start);
somaPrefixosSequencial();
GET_TIME(finish);
elapsed = finish - start;
printf("TEMPO GASTO SEQUENCIAL: %lf segundos\\n", elapsed);
start = 0;
finish = 0;
GET_TIME(start);
for(t = 0; t < N-1; t++){
if ((id = malloc(sizeof(int))) == 0) {
pthread_exit(0); return 1;
}
*id=t+1;
if (pthread_create(&tid[t], 0, somaPrefixosParalela, (void *)id)) {
printf("--ERRO: pthread_create()\\n"); exit(-1);
}
}
for (t = 0; t < N-1; t++) {
if (pthread_join(tid[t], 0)) {
printf("--ERRO: pthread_join() \\n"); exit(-1);
}
}
GET_TIME(finish);
elapsed = finish - start;
printf("TEMPO GASTO PARALELA: %lf segundos\\n", elapsed);
compararVetor();
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int main(int argc, char *argv[]) {
int parentfd;
int childfd;
int port = DEFAULT_PORT;
unsigned int clientlen;
struct sockaddr_in serveraddr;
struct sockaddr_in clientaddr;
struct hostent *hostp;
char *h_name;
int optval = 1;
pthread_t thread_id;
clientcount = 0;
clientlatest = 0;
params = 0;
if (argc > 1) {
if (strcmp(argv[1], "-h") == 0 ||
strcmp(argv[1], "--help") == 0 ||
argc > 2) {
printf("Usage: %s <Port>\\n", argv[0]);
exit(1);
}
port = atoi(argv[1]);
}
pthread_mutex_init(&mutex, 0);
if ((parentfd = socket(PF_INET, SOCK_STREAM, 0)) < 0)
error("socket() opening ERROR");
memset((char *) &serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons(port);
if (setsockopt(parentfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) < 0)
error("setsockopt() ERROR");
if (bind(parentfd, (struct sockaddr *) &serveraddr, sizeof(serveraddr)) < 0)
error("bind() ERROR. Not enough privilleges(<1024) or already in use");
if (listen(parentfd, BACKLOG) < 0)
error("listen() ERROR");
printf("Listening on %d\\n", port);
clientlen = sizeof(clientaddr);
while (1) {
if ((childfd = accept(parentfd, (struct sockaddr *) &clientaddr, &clientlen)) < 0)
error("accept() ERROR");
if ((hostp = gethostbyaddr(
(const char *) &clientaddr.sin_addr.s_addr,
sizeof(clientaddr.sin_addr.s_addr),
AF_INET)) == 0) {
h_name = "";
} else {
h_name = hostp->h_name;
}
pthread_mutex_lock(&mutex);
clientcount++;
clientlatest++;
clientlatest,
h_name, inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port),
clientcount);
pthread_mutex_unlock(&mutex);
params = malloc(sizeof(thread_param_t));
params->client_id = clientlatest;
params->client_sock = childfd;
pthread_create(&thread_id, 0, handle_client, (void *) params);
pthread_detach(thread_id);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t mx, my;
int x=2, y=2;
void *thread1() {
int a;
pthread_mutex_lock(&mx);
a = x;
pthread_mutex_lock(&my);
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
pthread_mutex_unlock(&my);
a = a + 1;
pthread_mutex_lock(&my);
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
pthread_mutex_unlock(&my);
x = x + x + a;
pthread_mutex_unlock(&mx);
assert(x!=27);
return 0;
}
void *thread2() {
pthread_mutex_lock(&mx);
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
pthread_mutex_unlock(&mx);
return 0;
}
void *thread3() {
pthread_mutex_lock(&my);
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
pthread_mutex_unlock(&my);
y=2;
return 0;
}
int main() {
pthread_t t1, t2, t3;
pthread_mutex_init(&mx, 0);
pthread_mutex_init(&my, 0);
pthread_create(&t1, 0, thread1, 0);
pthread_create(&t2, 0, thread2, 0);
pthread_create(&t3, 0, thread3, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_join(t3, 0);
pthread_mutex_destroy(&mx);
pthread_mutex_destroy(&my);
return 0;
}
| 0
|
#include <pthread.h>
static int count = 0;
static int i;
static pthread_mutex_t countlock = PTHREAD_MUTEX_INITIALIZER;
void *threadcompilereturn(void *arg){
char *filename;
int error;
i = 1;
filename = (char *)(arg);
if(compile(PATH, filename) == 1){
perror("Compiled");
if(error = pthread_mutex_lock(&countlock)){
perror("Failed to lock");
return;
}
i = 0;
pthread_mutex_unlock(&countlock);
return &i;
}
return &i;
}
void *threadcompile(void *arg){
char *filename;
int error;
filename = (char *)(arg);
if(compile(PATH, filename) == 1){
perror("Compiled");
if(error = pthread_mutex_lock(&countlock)){
perror("Failed to lock");
return;
}
count++;
pthread_mutex_unlock(&countlock);
}
return 0;
}
int compile(const char *str1, const char *str2){
pid_t child;
pid_t childpid;
int status;
char *str_name;
if((str_name = malloc(strlen(str2) + 3)) == 0)
return 0;
strcpy(str_name, str2);
strcat(str_name, ".c");
fprintf(stderr, "%s %s\\n", str1, str2);
child = fork();
if(child < 0){
perror("Fail to fork");
return 0;
}
if(child == 0){
execl(str1, "gcc", "-c", str_name, 0);
perror("Child failed to execl the command");
return 0;
}
free(str_name);
childpid = r_wait(&status);
if(childpid == -1)
perror("Parent failed to wait");
else if(WIFEXITED(status) && !WEXITSTATUS(status)){
fprintf(stderr,"The child process %d exit normally.\\n", childpid);
return 1;
}
else{
fprintf(stderr, "Child %ld terminated with return status %d\\n", (long)childpid, WEXITSTATUS(status));
return 0;
}
}
pid_t r_wait(int *stat_loc){
int retval;
while (((retval = wait(stat_loc)) == -1) && (errno == EINTR)) ;
return retval;
}
int clearcount(){
int error;
if (error = pthread_mutex_lock(&countlock))
return error;
count = 0;
return pthread_mutex_unlock(&countlock);
}
int getcount(int *countp){
int error;
if (error = pthread_mutex_lock(&countlock))
return error;
*countp = count;
return pthread_mutex_unlock(&countlock);
}
| 1
|
#include <pthread.h>
struct mlx5_db_page {
struct mlx5_db_page *prev, *next;
struct mlx5_buf buf;
int num_db;
int use_cnt;
unsigned long free[0];
};
static struct mlx5_db_page *__add_page(struct mlx5_context *context)
{
struct mlx5_db_page *page;
int ps = to_mdev(context->ibv_ctx.device)->page_size;
int pp;
int i;
int nlong;
pp = ps / context->cache_line_size;
nlong = (pp + 8 * sizeof(long) - 1) / (8 * sizeof(long));
page = malloc(sizeof *page + nlong * sizeof(long));
if (!page)
return 0;
if (mlx5_alloc_buf(&page->buf, ps, ps)) {
free(page);
return 0;
}
page->num_db = pp;
page->use_cnt = 0;
for (i = 0; i < nlong; ++i)
page->free[i] = ~0;
page->prev = 0;
page->next = context->db_list;
context->db_list = page;
if (page->next)
page->next->prev = page;
return page;
}
uint32_t *mlx5_alloc_dbrec(struct mlx5_context *context)
{
struct mlx5_db_page *page;
uint32_t *db = 0;
int i, j;
pthread_mutex_lock(&context->db_list_mutex);
for (page = context->db_list; page; page = page->next)
if (page->use_cnt < page->num_db)
goto found;
page = __add_page(context);
if (!page)
goto out;
found:
++page->use_cnt;
for (i = 0; !page->free[i]; ++i)
;
j = ffsl(page->free[i]);
--j;
page->free[i] &= ~(1UL << j);
db = page->buf.buf + (i * 8 * sizeof(long) + j) * context->cache_line_size;
out:
pthread_mutex_unlock(&context->db_list_mutex);
return db;
}
void mlx5_free_db(struct mlx5_context *context, uint32_t *db)
{
struct mlx5_db_page *page;
uintptr_t ps = to_mdev(context->ibv_ctx.device)->page_size;
int i;
pthread_mutex_lock(&context->db_list_mutex);
for (page = context->db_list; page; page = page->next)
if (((uintptr_t) db & ~(ps - 1)) == (uintptr_t) page->buf.buf)
break;
if (!page)
goto out;
i = ((void *) db - page->buf.buf) / context->cache_line_size;
page->free[i / (8 * sizeof(long))] |= 1UL << (i % (8 * sizeof(long)));
if (!--page->use_cnt) {
if (page->prev)
page->prev->next = page->next;
else
context->db_list = page->next;
if (page->next)
page->next->prev = page->prev;
mlx5_free_buf(&page->buf);
free(page);
}
out:
pthread_mutex_unlock(&context->db_list_mutex);
}
| 0
|
#include <pthread.h>
void msgu_event_map_init(struct msgs_event_map *map, struct msgu_handlers *h, void *a) {
pthread_mutex_init(&map->map_mutex, 0);
msgu_map_init(&map->data, msgu_uint32_hash, msgu_uint32_cmp, sizeof(uint32_t), sizeof(union msgu_any_event));
msgu_map_alloc(&map->data, 256);
map->next_id = 1;
map->hdl = *h;
map->arg = a;
}
int msgu_event_copy(struct msgs_event_map *map, uint32_t id, union msgu_any_event *data) {
union msgu_any_event *any = msgu_map_get(&map->data, &id);
if (any) {
memcpy(data, any, sizeof(union msgu_any_event));
return 1;
}
else {
return 0;
}
}
void msgu_event_notify(struct msgs_event_map *map, uint32_t type, union msgu_any_event *data) {
switch (type) {
case msgu_connect_id:
map->hdl.connect_event(map->arg, &data->conn);
break;
case msgu_recv_id:
map->hdl.recv_event(map->arg, &data->recv);
break;
case msgu_mount_id:
map->hdl.mount_event(map->arg, &data->mount);
break;
default:
printf("unknown event type\\n");
break;
}
}
void msgs_event_recv(struct msgs_event_map *map, uint32_t ev, uint32_t type, uint32_t id) {
union msgu_any_event data;
pthread_mutex_lock(&map->map_mutex);
int count = msgu_event_copy(map, id, &data);
pthread_mutex_unlock(&map->map_mutex);
if (count) {
msgu_event_notify(map, type, &data);
}
else {
printf("event %d, %d not found\\n", type, id);
}
}
void msgs_event_recv_mount(struct msgs_event_map *map, struct msgu_mount_event *me) {
map->hdl.mount_event(map->arg, me);
}
int msgu_add_connect_handler(struct msgs_event_map *map) {
struct msgu_connect_event ce;
pthread_mutex_lock(&map->map_mutex);
uint32_t id = map->next_id++;
ce.id = id;
int count = msgu_map_insert(&map->data, &id, &ce);
if (count == 0) {
return -1;
}
pthread_mutex_unlock(&map->map_mutex);
return id;
}
int msgu_add_recv_handler(struct msgs_event_map *map) {
struct msgu_recv_event re;
pthread_mutex_lock(&map->map_mutex);
uint32_t id = map->next_id++;
re.id = id;
msgu_map_insert(&map->data, &id, &re);
pthread_mutex_unlock(&map->map_mutex);
return id;
}
int msgu_add_share_handler(struct msgs_event_map *map) {
struct msgu_share_event fe;
pthread_mutex_lock(&map->map_mutex);
uint32_t id = map->next_id++;
fe.id = id;
msgu_map_insert(&map->data, &id, &fe);
pthread_mutex_unlock(&map->map_mutex);
return id;
}
int msgu_remove_handler(struct msgs_event_map *map, uint32_t id) {
pthread_mutex_lock(&map->map_mutex);
int result = msgu_map_erase(&map->data, &id);
pthread_mutex_unlock(&map->map_mutex);
return result;
}
| 1
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t wait = PTHREAD_COND_INITIALIZER;
void *thr_fn(void *arg)
{
int err, signo;
for(;;) {
err = sigwait(&mask, &signo);
if(err != 0) {
printf("sigwait error\\n");
}
switch(signo) {
case SIGINT:
printf("interrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&wait);
return 0;
default:
printf("unexpected signal %d\\n", signo);
exit(1);
}
}
}
int main(int argc, char const *argv[])
{
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) {
printf("SIG_BLOCK error\\n");
}
if((err = pthread_create(&tid, 0, thr_fn, 0)) != 0) {
printf("can't create thread\\n");
}
pthread_mutex_lock(&lock);
while(quitflag == 0) {
pthread_cond_wait(&wait, &lock);
}
pthread_mutex_unlock(&lock);
quitflag = 0;
if(sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) {
printf("SIG_SETMASK error\\n");
}
return 0;
}
| 0
|
#include <pthread.h>
struct flash_info {
struct block_manager *blk_mgr;
uint32_t init_called;
struct bm_operation_option operation_option;
struct bm_operate_prepare_info* prepare_info;
uint32_t block_size;
uint32_t page_size;
int64_t capacity;
pthread_mutex_t mutex_lock;
};
static struct flash_info flash_info;
static int32_t flash_init(void) {
int32_t ret;
struct flash_info *info = &flash_info;
if (info->init_called > 0) {
LOGE("Flash init had been called before\\n");
goto out;
}
pthread_mutex_init(&info->mutex_lock, 0);
info->blk_mgr = mtd_manager_init();
ret = info->blk_mgr->get_blocksize(info->blk_mgr, 0);
if (ret < 0) {
LOGE("Failed to get flash block size\\n");
goto out;
}
info->block_size = ret;
ret = info->blk_mgr->get_iosize(info->blk_mgr, 0);
if (ret < 0) {
LOGE("Failed to get flash block size\\n");
goto out;
}
info->page_size = ret;
if ((info->capacity
= info->blk_mgr->get_capacity(info->blk_mgr)) < 0) {
LOGE("Cannot get flash capacity\\n");
goto out;
}
info->init_called++;
return 0;
out:
info->blk_mgr = 0;
pthread_mutex_destroy(&info->mutex_lock);
return -1;
}
static int32_t flash_deinit(void) {
struct flash_info *info = &flash_info;
if (info->init_called <= 0) {
LOGE("Flash has not been initialed yet\\n");
goto out;
}
if (--info->init_called == 0) {
info->block_size = 0;
memset(&info->operation_option,
0, sizeof(info->operation_option));
mtd_manager_destroy(info->blk_mgr);
info->blk_mgr = 0;
pthread_mutex_destroy(&info->mutex_lock);
}
return 0;
out:
return -1;
}
static int32_t flash_get_erase_unit(void) {
struct flash_info *info = &flash_info;
assert_die_if(info->init_called <= 0, "Flash has not been initialed yet\\n");
return info->block_size;
}
static int64_t flash_erase(int64_t offset, int64_t length) {
struct flash_info *info = &flash_info;
int64_t ret;
assert_die_if(length == 0, "Parameter length is zero\\n");
assert_die_if(info->init_called <= 0,
"Flash has not been initialed yet\\n");
assert_die_if((length + offset) > info->capacity, "Size overlow\\n");
if (offset % info->block_size) {
LOGW("Flash erase offset 0x%llx is not block aligned", offset);
}
if (length % info->block_size) {
LOGW("Flash erase length 0x%llx is not block aligned", length);
}
pthread_mutex_lock(&info->mutex_lock);
ret = info->blk_mgr->erase(info->blk_mgr, offset, length);
if ((ret < 0) || (ret < (offset + length))) {
pthread_mutex_unlock(&info->mutex_lock);
LOGE("FLash erase failed at offset 0x%llx with length 0x%llx\\n",
offset, length);
return -1;
}
pthread_mutex_unlock(&info->mutex_lock);
return 0;
}
static int64_t flash_read(int64_t offset, void* buf, int64_t length) {
struct flash_info *info = &flash_info;
int64_t ret;
assert_die_if(length == 0, "Parameter length is zero\\n");
assert_die_if(buf == 0, "Parameter buf is null\\n");
assert_die_if(info->init_called <= 0,
"Flash has not been initialed yet\\n");
assert_die_if((length + offset) > info->capacity, "Size overlow\\n");
pthread_mutex_lock(&info->mutex_lock);
ret = info->blk_mgr->read(info->blk_mgr, offset, buf, length);
if ((ret < 0) || (ret < (offset + length))) {
pthread_mutex_unlock(&info->mutex_lock);
LOGE("FLash read failed at offset 0x%llx\\n", offset);
return -1;
}
pthread_mutex_unlock(&info->mutex_lock);
return length;
}
static int64_t flash_write(int64_t offset, void* buf, int64_t length) {
struct flash_info *info = &flash_info;
int64_t ret;
assert_die_if(length == 0, "Parameter length is zero\\n");
assert_die_if(buf == 0, "Parameter buf is null\\n");
assert_die_if(info->init_called <= 0, "Flash has not been initialed yet\\n");
assert_die_if((length + offset) > info->capacity, "Size overlow\\n");
if (offset % info->page_size) {
LOGW("Flash write offset 0x%llx is not page aligned", offset);
}
if (length % info->page_size) {
LOGW("Flash write length 0x%llx is not page aligned", length);
}
pthread_mutex_lock(&info->mutex_lock);
ret = info->blk_mgr->write(info->blk_mgr, offset, buf, length);
if (ret < 0) {
pthread_mutex_unlock(&info->mutex_lock);
LOGE("FLash write failed at offset 0x%llx with length 0x%llx\\n",
offset, length);
return -1;
}
pthread_mutex_unlock(&info->mutex_lock);
return length;
}
struct flash_manager flash_manager = {
.init = flash_init,
.deinit = flash_deinit,
.get_erase_unit = flash_get_erase_unit,
.erase = flash_erase,
.write = flash_write,
.read = flash_read,
};
struct flash_manager* get_flash_manager(void) {
return &flash_manager;
}
| 1
|
#include <pthread.h>
pthread_t tid[1 +1 +1 +1];
pthread_mutex_t mutex1, mutex1_2, mutex2_3, mutex3;
pthread_cond_t atelier1_2, atelier2_3;
int NbInput = 50;
int NbOutput = 0;
int NbInput1 = 20;
int NbOutput1 = 0;
int NbInput2 = 20;
int NbOutput2 = 0;
int NbInput3 = 20;
int NbOutput3 = 0;
void atelier3(int i){
printf("Demarrage atelier 3\\n");
pthread_mutex_lock(&mutex3);
while ( NbInput3 > 0 ){
pthread_mutex_unlock(&mutex3);
pthread_mutex_lock(&mutex3);
if ( NbInput3 == 0 ){
printf("L'atelier %d de niveau 3 a epuise son stock.\\n", (int) i);
}
pthread_mutex_unlock(&mutex3);
pthread_mutex_lock(&mutex3);
if ( NbOutput3 < 10 ){
sleep(1);
NbInput3--;
NbOutput3++;
printf("L'atelier %d de niveau 3 produit. Input: %d Output: %d\\n", (int) i, NbInput3, NbOutput3);
}
pthread_mutex_unlock(&mutex3);
pthread_mutex_lock(&mutex3);
if ( NbOutput3 >= 10 ){
pthread_cond_wait(&atelier2_3, &mutex3);
NbOutput3 -= 10;
pthread_mutex_unlock(&mutex3);
pthread_mutex_lock(&mutex2_3);
NbInput2 += 10;
pthread_mutex_unlock(&mutex2_3);
printf("L'atelier %d de niveau 3 a expedie un container.\\n", (int) i);
}
pthread_mutex_unlock(&mutex3);
}
pthread_mutex_unlock(&mutex3);
printf("L'atelier %d de niveau 3 a epuise son stock.\\n", (int) i);
}
void atelier2(int i){
printf("Demarrage atelier 2\\n");
bool signal_sent = 0;
pthread_mutex_lock(&mutex2_3);
while ( NbInput2 > 0 ){
pthread_mutex_unlock(&mutex2_3);
pthread_mutex_lock(&mutex2_3);
if ( NbInput2 <= 10 ){
if (signal_sent == 0){
pthread_mutex_unlock(&mutex2_3);
printf("L'atelier %d de niveau 2 exige un autre container.\\n", (int) i);
pthread_cond_signal(&atelier2_3);
signal_sent = 1;
}
}
else{
signal_sent = 0;
}
pthread_mutex_unlock(&mutex2_3);
pthread_mutex_lock(&mutex2_3);
if ( NbOutput2 < 10 ){
pthread_mutex_unlock(&mutex2_3);
sleep(1);
pthread_mutex_lock(&mutex2_3);
NbInput2--;
NbOutput2++;
printf("L'atelier %d de niveau 2 produit. Input: %d Output: %d\\n", (int) i, NbInput2, NbOutput2);
}
pthread_mutex_unlock(&mutex2_3);
pthread_mutex_lock(&mutex2_3);
if ( NbOutput2 >= 10 ){
pthread_cond_wait(&atelier1_2, &mutex2_3);
NbOutput2 -= 10;
pthread_mutex_unlock(&mutex2_3);
pthread_mutex_lock(&mutex1_2);
NbInput1 += 10;
pthread_mutex_unlock(&mutex1_2);
printf("L'atelier %d de niveau 2 a expedie un container.\\n", (int) i);
}
pthread_mutex_unlock(&mutex2_3);
}
pthread_mutex_unlock(&mutex2_3);
printf("L'atelier %d de niveau 2 a epuise son stock.\\n", (int) i);
}
void atelier1(int i) {
printf("Demarrage atelier 1\\n");
bool signal_sent = 0;
pthread_mutex_lock(&mutex1_2);
while ( NbInput1 > 0 ){
pthread_mutex_unlock(&mutex1_2);
pthread_mutex_lock(&mutex1_2);
if ( NbInput1 <= 10 ){
if (signal_sent == 0){
pthread_mutex_unlock(&mutex1_2);
printf("L'atelier %d de niveau 1 exige un autre container.\\n", (int) i);
pthread_cond_signal(&atelier1_2);
signal_sent = 1;
}
}
else{
signal_sent = 0;
}
pthread_mutex_unlock(&mutex1_2);
sleep(2);
pthread_mutex_lock(&mutex1_2);
NbInput1--;
NbOutput1++;
pthread_mutex_unlock(&mutex1_2);
printf("L'atelier %d de niveau 1 produit. Input: %d Output: %d\\n", (int) i, NbInput1, NbOutput1);
pthread_mutex_lock(&mutex1_2);
if ( NbOutput1 >= 10 ){
printf("L'atelier %d de niveau 1 expedie un container.\\n", (int) i);
NbOutput1 -= 10;
pthread_mutex_unlock(&mutex1_2);
pthread_mutex_lock(&mutex1);
NbOutput += 10;
pthread_mutex_unlock(&mutex1);
}
pthread_mutex_unlock(&mutex1_2);
}
printf("L'atelier %d de niveau 1 a epuise son stock.\\n", (int) i);
pthread_mutex_unlock(&mutex1_2);
}
int main()
{
pthread_create(tid,0,(void *(*)())atelier1,(void*)1);
pthread_create(tid+1,0,(void *(*)())atelier2,(void*)2);
pthread_create(tid+2,0,(void *(*)())atelier3,(void*)3);
pthread_join(tid[0],0);
pthread_join(tid[1],0);
pthread_mutex_lock(&mutex1);
printf("Quantite de produits obtenue: %d\\n",NbOutput);
pthread_mutex_unlock(&mutex1);
exit(0);
}
| 0
|
#include <pthread.h>
char buff[5];
int num;
}PRODUCT;
PRODUCT products = {"",0};
char ch = 'A';
pthread_mutex_t mutex;
pthread_cond_t cond;
void *producer_func(void *arg)
{
pthread_t producer_thid;
producer_thid = pthread_self();
printf("Producer %lu: Starting\\n", producer_thid);
while('Z' > ch){
pthread_mutex_lock(&mutex);
if(products.num != 5){
products.buff[products.num] = ch;
printf("Producer %lu: Putting[%c] into buffer.\\n", producer_thid, ch);
products.num++;
ch++;
if(5 == products.num){
printf("Producter %lu: Buffer is full!!!!\\n", producer_thid);
pthread_cond_signal(&cond);
}
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
printf("Producer %lu: Exiting\\n", producer_thid);
return 0;
}
void *consumer_func(void *arg)
{
pthread_t consumer_thid;
int i;
consumer_thid = pthread_self();
printf("Consumer %lu: Starting\\n", consumer_thid);
while('Z' > ch){
pthread_mutex_lock(&mutex);
printf("Consumer %lu: Waiting...\\n", consumer_thid);
while(products.num != 5){
pthread_cond_wait(&cond, &mutex);
}
printf("Consumer %lu: Getting letters from buffer.\\n", consumer_thid);
for(i=0; products.buff[i]&&products.num; i++, products.num--){
putchar(products.buff[i]);
}
printf("\\n");
pthread_mutex_unlock(&mutex);
}
printf("Consumer %lu: EXiting....\\n", consumer_thid);
return 0;
}
int main(int argc, char *argv[])
{
pthread_t producer_thid, consumer_thid;
void *retval;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
pthread_create(&producer_thid, 0, (void*)producer_func, 0);
pthread_create(&consumer_thid, 0, (void*)consumer_func, 0);
pthread_join(producer_thid, &retval);
pthread_join(consumer_thid, &retval);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
| 1
|
#include <pthread.h>
int fd;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *write_data(void *data)
{
char buf[128] = {};
int count = 1;
int ret = 0;
pthread_mutex_lock(&mutex);
while (1)
{
snprintf(buf, sizeof(buf), "%s : count = %d\\n", (char *)data, count++);
ret = write(fd, buf, strlen(buf));
if (ret < 0)
{
perror("write data");
}
if (count > 1000)
{
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
}
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main(void)
{
pthread_t pth;
int ret = 0;
fd = open("./test", O_WRONLY | O_CREAT | O_TRUNC);
if (fd < 0)
{
perror("open file");
exit(-1);
}
pthread_create(&pth, 0, write_data, "child");
write_data("parent");
return 0;
}
| 0
|
#include <pthread.h>
int quitflag = 0;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER;
void *thr_fn (void *arg)
{
int err, signo;
for (;;) {
err = sigwait (&mask, &signo);
if (err != 0) {
err_exit (err, "sigwait failed");
}
switch (signo) {
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock (&lock);
quitflag = 1;
pthread_mutex_unlock (&lock);
pthread_cond_signal (&waitloc);
return (0);
default:
printf ("unexcepted signal %d\\n", signo);
exit (1);
}
}
}
int main (void)
{
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset (&mask);
sigaddset (&mask, SIGINT);
sigaddset (&mask, SIGQUIT);
if ((err = pthread_sigmask (SIG_BLOCK, &mask, &oldmask)) != 0) {
err_exit (err, "SIG_BLOCK error");
}
err = pthread_create (&tid, 0, thr_fn, 0);
if (err != 0) {
err_exit (err, "can't create thread");
}
pthread_mutex_lock (&lock);
while (quitflag == 0) {
pthread_cond_wait (&waitloc, &lock);
}
pthread_mutex_unlock (&lock);
quitflag = 0;
if (sigprocmask (SIG_SETMASK, &oldmask, 0) < 0) {
err_sys ("SIG_SETMASK error");
}
exit (0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t buffer;
pthread_cond_t condc, condp;
int limit = 0;
int entry = 0;
struct item {
int value;
int ctimer;
} citem[32];
static unsigned long mt[624];
static int mti=624 +1;
_Bool supportsRDRND() {
const unsigned int flag_RDRAND = (1 << 30);
unsigned int level = 0;
unsigned int eax = 0;
unsigned int ebx;
unsigned int ecx;
unsigned int edx;
!__get_cpuid(level, &eax, &ebx, &ecx, &edx);
return((ecx & flag_RDRAND) == flag_RDRAND);
}
void sgenrand(seed) unsigned long seed; {
int i;
for (i=0;i<624;i++) {
mt[i] = seed & 0xffff0000;
seed = 69069 * seed + 1;
mt[i] |= (seed & 0xffff0000) >> 16;
seed = 69069 * seed + 1;
}
mti = 624;
}
double genrand() {
unsigned long y;
static unsigned long mag01[2]={0x0, 0x9908b0df};
if (mti >= 624) {
int kk;
if (mti == 624 +1)
sgenrand(4357);
for (kk=0;kk<624 -397;kk++) {
y = (mt[kk]&0x80000000)|(mt[kk+1]&0x7fffffff);
mt[kk] = mt[kk+397] ^ (y >> 1) ^ mag01[y & 0x1];
}
for (;kk<624 -1;kk++) {
y = (mt[kk]&0x80000000)|(mt[kk+1]&0x7fffffff);
mt[kk] = mt[kk+(397 -624)] ^ (y >> 1) ^ mag01[y & 0x1];
}
y = (mt[624 -1]&0x80000000)|(mt[0]&0x7fffffff);
mt[624 -1] = mt[397 -1] ^ (y >> 1) ^ mag01[y & 0x1];
mti = 0;
}
y = mt[mti++];
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680;
y ^= (y << 15) & 0xefc60000;
y ^= (y >> 18);
return y;
}
void* producer(void *ptr) {
int ptimer = 0;
while(1) {
ptimer = ((abs((unsigned int)genrand()) % 4) + 3);
wait(ptimer * 1000);
pthread_mutex_lock(&buffer);
while(limit >= 32)
pthread_cond_wait(&condp, &buffer);
citem[limit].value = abs((unsigned int)genrand());
citem[limit].ctimer = ((abs((unsigned int)genrand()) % 7) + 2);
limit++;
entry++;
pthread_cond_signal(&condc);
pthread_mutex_unlock(&buffer);
}
}
void* consumer(void *ptr) {
int consumetime;
while(1) {
pthread_mutex_lock(&buffer);
while(limit == 0 || citem[limit-1].value == 0)
pthread_cond_wait(&condc, &buffer);
printf("Consumer consumed: %d\\n", citem[limit-1].value);
consumetime = citem[limit].ctimer * 1000;
limit--;
entry++;
wait(consumetime);
pthread_cond_signal(&condp);
pthread_mutex_unlock(&buffer);
}
}
int main (int argc, char *argv[]) {
if(argc == 2) {
int num = atoi(argv[1]);
pthread_t prod[num], cons[num];
pthread_mutex_init(&buffer, 0);
pthread_cond_init(&condc, 0);
pthread_cond_init(&condp, 0);
int i = 0;
int seed = 4567;
sgenrand(seed);
genrand();
for(;i < num; i++) {
pthread_create(&prod[i], 0, producer, 0);
pthread_create(&cons[i], 0, consumer, 0);
}
for(;i < num; i++) {
pthread_join(prod[i], 0);
pthread_join(cons[i], 0);
}
pthread_mutex_destroy(&buffer);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
}
else
printf("ERROR: Invalid number of inputs\\n");
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
double wtime()
{
struct timeval t;
gettimeofday(&t, 0);
return (double)t.tv_sec + (double)t.tv_usec * 1E-6;
}
void *counter_thread(void *counter)
{
int i;
for (i = 0; i < 5000000; i++) {
pthread_mutex_lock(&mutex);
(*((int *)counter))++;
pthread_mutex_unlock(&mutex);
}
return 0;
}
int main(int argc, char **argv)
{
double t = wtime();
int counter = 0, i;
int nthreads = argc > 1 ? atoi(argv[1]) : 16;
pthread_t *tids = malloc(sizeof(*tids) * nthreads);
if (tids == 0) {
fprintf(stderr, "No enough memory\\n");
exit(1);
}
for (i = 0; i < nthreads; i++) {
if (pthread_create(&tids[i], 0, counter_thread, (void *)&counter) != 0) {
fprintf(stderr, "Can't create thread\\n");
exit(1);
}
}
for (i = 0; i < nthreads; i++)
pthread_join(tids[i], 0);
t = wtime() - t;
printf("Counter (threads %d, counter %d): %.6f sec.\\n", nthreads, counter, t);
if ((nthreads * 5000000) == counter)
printf("%d == %d\\nПрограмма работает правильно.\\n", (nthreads * 5000000), counter);
free(tids);
return 0;
}
| 1
|
#include <pthread.h>
bool compare(char * comm, char * comm2)
{
if( strlen( comm ) == strlen( comm2 ) && strncmp( comm, comm2, strlen( comm )) == 0 )
return 1;
return 0;
}
void errorMsg(const char* str)
{
fprintf( stderr, str);
}
char disk[MAX_BLOCK][BLOCK_SIZE];
int disk_read( int block, char * buf )
{
pthread_mutex_lock(&mutex);
if( block < 0 || block >= MAX_BLOCK )
{ errorMsg("error while reading the disk \\n" ); return -1;}
memcpy( buf, disk[block], BLOCK_SIZE );
pthread_mutex_unlock(&mutex);
return 0;
}
int disk_write( int block, char * buf)
{
if( block < 0 || block >= MAX_BLOCK )
{ errorMsg("error while writing to the disk\\n"); return -1;}
memcpy( disk[block], buf, BLOCK_SIZE );
return 0;
}
int disk_mount( char * name )
{
FILE *fp = fopen( name, "r" );
if(fp != 0)
{
fread( disk, BLOCK_SIZE, MAX_BLOCK, fp );
fclose( fp );
return 1;
}
return -1;
}
int disk_unmount( char * name )
{
FILE * fp = fopen( name, "w" );
if( fp != 0 )
{
fwrite( disk, BLOCK_SIZE, MAX_BLOCK, fp );
fclose( fp );
return 1;
}
return -1;
}
| 0
|
#include <pthread.h>
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo {
int f_count;
pthread_mutex_t f_lock;
int f_id;
struct foo * f_next;
};
struct foo *foo_alloc(int id)
{
struct foo *fp;
int idx;
if ((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 1;
fp->f_id = id;
if (pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return(0);
}
idx = (((unsigned long)id)%29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
}
return(fp);
}
void foo_hold(struct foo *fp)
{
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
struct foo *foo_find(int id)
{
struct foo *fp;
pthread_mutex_lock(&hashlock);
for (fp = fh[(((unsigned long)id)%29)]; fp != 0; fp = fp->f_next) {
if (fp->f_id == id) {
foo_hold(fp);
break;
}
}
pthread_mutex_unlock(&hashlock);
return(fp);
}
void foo_rele(struct foo *fp)
{
struct foo *tfp;
int idx;
pthread_mutex_lock(&fp->f_lock);
if (fp->f_count == 1) {
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_lock(&hashlock);
pthread_mutex_lock(&fp->f_lock);
if (fp->f_count != 1) {
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
return;
}
idx = (((unsigned long)fp->f_id)%29);
tfp = fh[idx];
if (tfp == fp) {
fh[idx] = fp->f_next;
} else {
while (tfp->f_next != fp)
tfp = tfp->f_next;
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
} else {
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
}
}
| 1
|
#include <pthread.h>
const int M = 20, CNT = 20000;
pthread_mutex_t level[20 + 1];
void *func_a() {
int i, count = CNT;
while (count--) {
printf("a start %d\\n", count);
for (i = 0; i < M; i++) {
printf("a want %d\\n", i);
pthread_mutex_lock(&level[i]);
}
puts("a");
for (i = M - 1; i >= 0; i--) {
pthread_mutex_unlock(&level[i]);
}
printf("a over %d\\n", count);
}
}
void *func_b() {
int i, count = CNT;
while (count--) {
printf("b start %d\\n", count);
for (i = M - 1; i >= 0; i--) {
printf("b want %d\\n", i);
pthread_mutex_lock(&level[i]);
}
puts("b");
for (i = 0; i < M; i++) {
pthread_mutex_unlock(&level[i]);
}
printf("b over %d\\n", count);
}
}
int main() {
int i;
for (i = 0; i < M; i++) {
pthread_mutex_init(&level[i], 0);
}
pthread_t a, b;
pthread_create(&a, 0, func_a, 0);
pthread_create(&b, 0, func_b, 0);
pthread_join (a, 0);
pthread_join (b, 0);
return 0;
}
| 0
|
#include <pthread.h>
int active_sessions_counter;
} llp_info_t;
static llp_info_t info;
static pthread_mutex_t info_mutex;
int llp_info_initialize() {
if (pthread_mutex_init(&info_mutex, 0) > 0) {
liblog_error(LAYER_LINK, "error allocating mutex: %s.",
strerror(errno));
return LLP_ERROR;
}
liblog_debug(LAYER_LINK, "mutex initialized.");
info.active_sessions_counter = 0;
return LLP_OK;
}
void llp_info_finalize() {
pthread_mutex_destroy(&info_mutex);
liblog_debug(LAYER_LINK, "mutex destroyed.");
}
int llp_get_active_sessions_counter() {
int return_value;
pthread_mutex_lock(&info_mutex);
return_value = info.active_sessions_counter;
pthread_mutex_unlock(&info_mutex);
return return_value;
}
void llp_add_active_sessions_counter(int increment) {
pthread_mutex_lock(&info_mutex);
info.active_sessions_counter += increment;
pthread_mutex_unlock(&info_mutex);
}
| 1
|
#include <pthread.h>
struct check_info {
int span;
int delay;
};
char phone_num[100000][64] = {
0,
};
static int check_phone_count=0;
static FILE *fp=0;
pthread_mutex_t mutex;
void check_phone(const char* num, int span, int delay, char* ret_buf, int buf_len)
{
FILE *stream;
char cmd[128];
memset( cmd, 0,128);
memset( ret_buf, '\\0', buf_len);
snprintf(cmd,128,"/usr/sbin/asterisk -rx \\"gsm check phone stat %d %s 1 %d\\"", span, num, delay);
stream = popen(cmd, "r" );
fread( ret_buf, sizeof(char), buf_len, stream);
pclose( stream );
}
char* get_phone_num()
{
static int index = 0;
if(index >= check_phone_count)
return 0;
return phone_num[index++];
}
void* thread_func(void* arg)
{
struct check_info* info;
char buf[128];
char *num;
if(arg == 0) {
return (void*)0;
}
info = (struct check_info*)arg;
memset(buf,0,sizeof(buf));
for(;;) {
pthread_mutex_lock(&mutex);
if(0==(num=get_phone_num())) {
pthread_mutex_unlock(&mutex);
break;
}
if(strlen(buf))
fprintf(fp,"%s\\r\\n",buf);
pthread_mutex_unlock(&mutex);
check_phone(num, info->span, info->delay, buf, 128);
while(strstr(buf,"SPAN"))
{
usleep(500000);
check_phone(num, info->span, info->delay, buf, 128);
}
printf("%s\\n",buf);
}
pthread_exit(0);
return (void*)0;
}
int main( int argc,char **argv )
{
char buf[1024];
pthread_t ptid[100];
int err;
char ch;
char tmp[128];
int start = 0;
int spans_number=0;
char *head_title=0;
int phone_buttom_length=0;
int phone_cont=0;
int time_out=0;
char param_buffer[32];
struct check_info info[100];
time_t start_time,end_time;
struct tm *times;
char strtemp[255];
int i;
while((ch = getopt(argc,argv,"n:t:l:c:o:f:h"))!= -1)
{
switch(ch)
{
case 'n':
spans_number=atoi(optarg);
if(spans_number>100)
{
printf("spans_number MAX %d\\n",100);
return -1;
}
printf("SPAN COUNT:%d\\n",spans_number);
break;
case 't':
head_title=optarg;
printf("PHONE NUMBER HEAD:%s\\n",head_title);
break;
case 'l':
phone_buttom_length=atoi(optarg);
break;
case 'c':
phone_cont=atoi(optarg);
if(phone_cont>100000)
{
printf("phone_cont MAX %d\\n",100000);
return -1;
}
printf("PHONE COUNT:%d\\n",phone_cont);
break;
case 'o':
time_out=atoi(optarg);
printf("TIMEOUT:%d\\n",time_out);
break;
case 'f':
fp=fopen(optarg,"w+");
if(!fp)
printf("open log file:%s error\\n",optarg);
break;
case 'h':
printf("%s -n <spans_number> -t <phone_title> -l <phone_buttom_length> -c <phone_numbers> -o <timeouts> -f <logfile>\\n",argv[0]);
return -1;
case '?':
printf("%s -n <spans_number> -t <phone_title> -l <phone_buttom_length> -c <phone_numbers> -o <timeouts>\\n -f <loggile>",argv[0]);
break;
}
}
if(!spans_number||!head_title||!phone_cont||!phone_buttom_length||!time_out)
{
printf("%s -n <spans_number> -t <phone_title> -l <phone_buttom_length> -c <phone_numbers> -o <timeouts>\\n",argv[0]);
return -1;
}
check_phone_count=phone_cont;
sprintf(param_buffer,"%s%%0%dd",head_title,phone_buttom_length);
for(i=0; i<100000; i++) {
memset(phone_num[i],0,64);
}
for(i=0; i<phone_cont; i++) {
sprintf(tmp,param_buffer,start++);
strcpy(phone_num[i],tmp);
}
pthread_mutex_init(&mutex, 0);
time(&start_time);
times = localtime(&start_time);
printf("start time is: %s \\n", asctime(times));
for(i=0; i<spans_number; i++) {
info[i].span=i+1;
info[i].delay=time_out;
pthread_create(&ptid[i], 0, thread_func, &info[i]);
}
for(i=0; i<spans_number;i++) {
pthread_join(ptid[i],0);
}
time(&end_time);
times = localtime(&end_time);
printf("end time is: %s \\n", asctime(times));
printf("using %d seconds\\n",end_time-start_time);
if(fp)
fclose(fp);
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
struct node {
int n_number;
struct node *n_next;
} *head = 0;
static void cleanup_handler(void *arg)
{
printf("Cleanup handler of second thread./n");
free(arg);
(void)pthread_mutex_unlock(&mtx);
}
static void *thread_func(void *arg)
{
struct node *p = 0;
pthread_cleanup_push(cleanup_handler, p);
while (1) {
pthread_mutex_lock(&mtx);
while (head == 0)
{
pthread_cond_wait(&cond, &mtx);
}
p = head;
head = head->n_next;
printf("Got %d from front of queue/n", p->n_number);
free(p);
pthread_mutex_unlock(&mtx);
}
pthread_cleanup_pop(0);
return 0;
}
int main(void)
{
pthread_t tid;
int i;
struct node *p;
pthread_create(&tid, 0, thread_func, 0);
for (i = 0; i < 10; i++) {
p = malloc(sizeof(struct node));
p->n_number = i;
pthread_mutex_lock(&mtx);
p->n_next = head;
head = p;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mtx);
sleep(1);
}
printf("thread 1 wanna end the line.So cancel thread 2./n");
pthread_cancel(tid);
pthread_join(tid, 0);
printf("All done -- exiting/n");
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
double *
jacobi (double *x, double *X, double *A, double *b, int h, int w,
int rank, int size)
{
int li, i, j, convergence, iter;
double d, ldelta, delta;
for (li = 0; li < h; li++)
x[li] = 1.0;
iter = 0;
do
{
iter++;
ldelta = 0.0;
pthread_mutex_lock (&mutex);
MPI_Allgather (x, h, MPI_DOUBLE,
X, h, MPI_DOUBLE, MPI_COMM_WORLD);
pthread_mutex_unlock (&mutex);
{
for (li = 0; li < h; li++)
{
i = li + rank * h;
x[li] = b[li];
for (j = 0; j < w; j++)
if (j != i)
x[li] -= A[li * w + j] * X[j];
x[li] /= A[li * w + i];
{
d = fabs (X[i] - x[li]);
if (d > ldelta) ldelta = d;
}
}
}
pthread_mutex_lock (&mutex);
MPI_Allreduce (&ldelta, &delta, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);
pthread_mutex_unlock (&mutex);
convergence = (delta < JACOBI_EPS);
}
while ((!convergence) && (iter < JACOBI_MAX_ITER));
return x;
}
int
main (int argc, char **argv)
{
int mpi_rank, mpi_size, mpi_thread;
int n, ln;
double *A, *b, *x, *r, *X;
double lmax, max;
struct timeval before, after;
MPI_Init_thread (&argc, &argv, MPI_THREAD_SERIALIZED, &mpi_thread);
if (mpi_thread != MPI_THREAD_SERIALIZED)
{
fprintf (stderr, "MPI_Init_thread: Thread level provided differs with thread level requierd\\n");
pthread_mutex_lock (&mutex);
MPI_Finalize ();
pthread_mutex_unlock (&mutex);
return 1;
}
pthread_mutex_lock (&mutex);
MPI_Comm_size (MPI_COMM_WORLD, &mpi_size);
MPI_Comm_rank (MPI_COMM_WORLD, &mpi_rank);
pthread_mutex_unlock (&mutex);
n = JACOBI_DEF_SIZE;
if (argc == 2)
n = atoi (argv[1]);
if (mpi_rank == ROOT_NODE)
fprintf (stdout, "n = %d\\n", n);
ln = n / mpi_size;
A = (double *) calloc (ln * n, sizeof(double));
if (A == 0)
{
perror ("calloc");
pthread_mutex_lock (&mutex);
MPI_Finalize ();
pthread_mutex_unlock (&mutex);
return 1;
}
b = (double *) calloc (ln, sizeof(double));
if (A == 0)
{
perror ("calloc");
pthread_mutex_lock (&mutex);
MPI_Finalize ();
pthread_mutex_unlock (&mutex);
return 1;
}
x = (double *) calloc (ln, sizeof(double));
if (x == 0)
{
perror ("calloc");
pthread_mutex_lock (&mutex);
MPI_Finalize ();
pthread_mutex_unlock (&mutex);
return 1;
}
X = (double *) calloc (n, sizeof(double));
if (X == 0)
{
perror ("calloc");
pthread_mutex_lock (&mutex);
MPI_Finalize ();
pthread_mutex_unlock (&mutex);
return 1;
}
r = (double *) calloc (ln, sizeof(double));
if (r == 0)
{
perror ("calloc");
pthread_mutex_lock (&mutex);
MPI_Finalize ();
pthread_mutex_unlock (&mutex);
return 1;
}
generate_matrix (A, ln, n, mpi_rank);
generate_vector (b, ln);
gettimeofday (&before, 0);
x = jacobi (x, X, A, b, ln, n, mpi_rank, mpi_size);
gettimeofday (&after, 0);
pthread_mutex_lock (&mutex);
MPI_Allgather (x, ln, MPI_DOUBLE,
X, ln, MPI_DOUBLE, MPI_COMM_WORLD);
pthread_mutex_unlock (&mutex);
compute_residual (r, A, X, b, ln, n);
lmax = find_max_abs (r, ln);
pthread_mutex_lock (&mutex);
MPI_Reduce (&lmax, &max, 1, MPI_DOUBLE, MPI_MAX, ROOT_NODE, MPI_COMM_WORLD);
pthread_mutex_unlock (&mutex);
if (mpi_rank == ROOT_NODE)
display_info (A, x, b, r, n, max, &before, &after);
free (A);
free (b);
free (x);
free (X);
free (r);
pthread_mutex_lock (&mutex);
MPI_Finalize ();
pthread_mutex_unlock (&mutex);
return 0;
}
| 0
|
#include <pthread.h>
void posts_db_init(struct post_fds *fds, char *meta_path, char *post_path) {
fds->meta_fd = open(meta_path, O_RDWR|O_APPEND|O_CREAT, 0600);
fds->post_fd = open(post_path, O_RDWR|O_APPEND|O_CREAT, 0600);
pthread_mutex_init(&fds->mutex, 0);
}
void posts_db_close(struct post_fds *fds) {
close(fds->meta_fd);
close(fds->post_fd);
}
char *get_post(struct post_fds* fds, struct meta_block *block, unsigned long num) {
get_post_meta(fds, block, num);
pthread_mutex_lock(&fds->mutex);
char *ptr = malloc(block->len+1);
ptr[block->len] = 0;
lseek(fds->post_fd, block->loc, 0);
read(fds->post_fd, ptr, block->len);
pthread_mutex_unlock(&fds->mutex);
return ptr;
}
void get_post_meta(struct post_fds* fds, struct meta_block *block, unsigned long num) {
pthread_mutex_lock(&fds->mutex);
lseek(fds->meta_fd, sizeof(struct meta_block)*num, 0);
read(fds->meta_fd, block, sizeof(struct meta_block));
pthread_mutex_unlock(&fds->mutex);
}
void post(struct post_fds* fds, char *name, char *title, char *data, unsigned long len) {
pthread_mutex_lock(&fds->mutex);
struct meta_block block;
block.loc = lseek(fds->post_fd, 0, 2);
block.len = len;
block.timestamp = time(0);
memcpy(block.title, title, TITLE_LEN);
memcpy(block.name, name, NAME_LEN);
write(fds->meta_fd, &block, sizeof(struct meta_block));
write(fds->post_fd, data, len);
pthread_mutex_unlock(&fds->mutex);
}
unsigned long post_head(struct post_fds* fds) {
unsigned long end = lseek(fds->meta_fd, 0, 2);
return end / sizeof(struct meta_block) - 1;
}
| 1
|
#include <pthread.h>
int *arr;
int tid;
int size;
int nthreads;
double *time;
} params;
int pairmax(int *arr, int startIndex, int endIndex);
void *threadParallelSum( void *ptr );
double maximum(double a, double b);
long upper_power_of_two(long v);
static int globalmax = 0;
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int main()
{
int fileno, nthreads, size;
char *file;
printf("Select the file name: (Press 1 or 2 or 3)\\n 1.1 million entries\\n 2.2 million entries\\n 3.4 million entries\\n");
scanf("%d", &fileno);
switch(fileno){
case 1:
printf("File one\\n");
size = 100000;
file = "random100000.txt";
break;
case 2:
printf("File two\\n");
size = 200000;
file = "random200000.txt";
break;
case 3:
printf("File three\\n");
size = 400000;
file = "random400000.txt";
break;
case 4:
printf("File three\\n");
size = 32;
file = "random32.txt";
break;
}
printf("Enter the number of threads : (1, 2, 4, 8, 16)\\n");
scanf("%d", &nthreads);
int arr[size];
double time[nthreads], globalTime;
FILE *myFile;
myFile = fopen(file, "r");
int i = 0;
int j = 0 ;
fscanf (myFile, "%d", &i);
while (!feof (myFile))
{
arr[j] = i;
j++;
fscanf (myFile, "%d", &i);
}
fclose (myFile);
pthread_t threads[nthreads];
params *thread_params = (params*) malloc(nthreads*sizeof(params));
for( i = 0; i < nthreads; i++)
{
thread_params[i].arr = arr;
thread_params[i].tid = i;
thread_params[i].size = size;
thread_params[i].nthreads = nthreads;
thread_params[i].time = time;
pthread_create(&threads[i], 0, threadParallelSum, (void*) &thread_params[i]);
}
for( i = 0; i < nthreads; i++)
{
pthread_join(threads[i], 0);
}
for(i = 0; i < nthreads; i++){
globalTime = maximum(globalTime,time[i]);
}
printf("globalmax : %d , and GlobalTime : %f seconds\\n", globalmax, globalTime);
exit(0);
return 0;
}
void *threadParallelSum( void *ptr )
{
clock_t startT, endT;
double cpu_time_used;
params *p = (params *) ptr;
int tid = p->tid;
int chunk_size = (p -> size / p -> nthreads);
int start = tid * chunk_size;
int end = start + chunk_size;
startT = clock();
int threadmax = pairmax(p->arr, start, end-1);
pthread_mutex_lock( &mutex1 );
globalmax = maximum(threadmax,globalmax);
pthread_mutex_unlock( &mutex1 );
endT = clock();
cpu_time_used = ((double) (endT - startT)) / CLOCKS_PER_SEC;
p->time[tid] = cpu_time_used;
printf("Time taken by individual thread %d is %f seconds\\n", tid, cpu_time_used);
return 0;
}
int pairmax(int *arr, int startIndex, int endIndex)
{
if(endIndex-startIndex == 1)
{
return maximum(arr[startIndex], arr[endIndex]);
}
else if (endIndex-startIndex == 0)
{
return maximum(arr[endIndex],arr[endIndex]);
}
int m = upper_power_of_two((endIndex-startIndex)+1);
if( m == (endIndex-startIndex)+1)
{
m = ((endIndex-startIndex)+1)/2;
}
int left = pairmax(arr,startIndex,startIndex+m-1);
int right = pairmax(arr,startIndex+m,endIndex);
return maximum(left,right);
}
long upper_power_of_two(long v)
{
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
return (v >> 1)+1;
}
double maximum(double a , double b)
{
if(a>b)
{
return a;
}
else
{
return b;
}
}
| 0
|
#include <pthread.h>
int GnChopstick[5] = {0} ;
pthread_mutex_t mutex[5];
pthread_t GpThread[5];
void *Aristotle ();
void *Plato();
void *Marx();
void *Laozi();
void *Zhuangzi();
int thread_create();
void thread_wait();
int main()
{
int i;
for(i = 0;i < 5;i++)
{
pthread_mutex_init(&mutex[i],0);
}
printf("Now the philosopher begin to dinner!\\n" );
for( i = 0; i< 5 ;i ++)
{
thread_create();
thread_wait();
}
return 0;
}
void *Aristotle()
{
if (GnChopstick[0] == 0 && GnChopstick[4] == 0)
{
pthread_mutex_lock(&mutex[0]);
pthread_mutex_lock(&mutex[4]);
printf("Aristotle is eating!\\n");
sleep(2);
pthread_mutex_unlock(&mutex[0]);
pthread_mutex_unlock(&mutex[4]);
}
else
{
printf("Aristotle is thinking!\\n");
}
pthread_exit(0);
}
void *Plato()
{
if (GnChopstick[0] == 0 && GnChopstick[1] == 0)
{
pthread_mutex_lock(&mutex[0]);
pthread_mutex_lock(&mutex[1]);
printf("Plato is eating!\\n");
sleep(3);
pthread_mutex_unlock(&mutex[0]);
pthread_mutex_unlock(&mutex[1]);
}
else
{
printf("Plato is thinking!\\n");
}
pthread_exit(0);
}
void *Marx()
{
if (GnChopstick[1] == 0 && GnChopstick[2] == 0)
{
pthread_mutex_lock(&mutex[1]);
pthread_mutex_lock(&mutex[2]);
printf("Marx is eating!\\n");
sleep(4);
pthread_mutex_unlock(&mutex[1]);
pthread_mutex_unlock(&mutex[2]);
}
else
{
printf("Marx is thinking!\\n");
}
pthread_exit(0);
}
void *Laozi()
{
if (GnChopstick[2] == 0 && GnChopstick[3] == 0)
{
pthread_mutex_lock(&mutex[2]);
pthread_mutex_lock(&mutex[3]);
printf("Laozi is eating!\\n");
sleep(5);
pthread_mutex_unlock(&mutex[2]);
pthread_mutex_unlock(&mutex[3]);
}
else
{
printf("Laozi is thinking!\\n");
}
pthread_exit(0);
}
void *Zhuangzi()
{
if (GnChopstick[3] == 0 && GnChopstick[4] == 0)
{
pthread_mutex_lock(&mutex[3]);
pthread_mutex_lock(&mutex[4]);
printf("Zhuangzi is eating!\\n");
sleep(6);
pthread_mutex_unlock(&mutex[3]);
pthread_mutex_unlock(&mutex[4]);
}
else
{
printf("Zhuangzi is thinking!\\n");
}
pthread_exit(0);
}
int thread_create()
{
int nNum;
if((nNum =pthread_create(&GpThread[0],0,Aristotle,0)) != 0)
{
fprintf(stderr,"fail to create the Aristotle thread");
return -1;
}
if((nNum =pthread_create(&GpThread[1],0,Plato,0)) != 0)
{
fprintf(stderr,"fail to create the Plato thread");
return -1;
}
if((nNum =pthread_create(&GpThread[2],0,Marx,0)) != 0)
{
fprintf(stderr,"fail to create the Marx thread");
return -1;
}
if((nNum =pthread_create(&GpThread[3],0,Laozi,0)) != 0)
{
fprintf(stderr,"fail to create the Laozi thread");
return -1;
}
if((nNum =pthread_create(&GpThread[4],0,Zhuangzi,0)) != 0)
{
fprintf(stderr,"fail to create the Aristotle thread");
return -1;
}
}
void thread_wait()
{
int i;
for(i =0 ;i < 5; i ++)
{
if(GpThread[i] != 0)
pthread_join(GpThread[i],0);
}
}
| 1
|
#include <pthread.h>
int buffer[32] = {0};
int acked = -1;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void * consumer(void * round) {
int version;
version = *((int *)round);
if (version == 10000) return 0;
while (1) {
usleep(10);
pthread_mutex_lock(&mutex);
int i, ver;
for (i = 0; i < 32; i++) {
ver = buffer[i];
}
if (ver > acked) {
acked = ver;
break;
}
pthread_mutex_unlock(&mutex);
}
pthread_mutex_unlock(&mutex);
(*((int *)round))++;
consumer(round);
return 0;
}
void * producer(void * round) {
int version;
version = *((int *)round);
if (version == 10000) return 0;
while (1) {
usleep(10);
pthread_mutex_lock(&mutex);
if (version == acked) break;
assert(version -1 == acked);
pthread_mutex_unlock(&mutex);
}
int i;
for (i = 0; i < 32; i++)
buffer[i] = version + 1;
pthread_mutex_unlock(&mutex);
(*((int *)round))++;
producer(round);
return 0;
}
int main() {
pthread_t thread1, thread2;
int i;
for (i = 0; i < 32; i++)
buffer[i] = 0;
int r1 = 0, r2 = 0;
pthread_create(&thread1, 0, consumer, &r1);
pthread_create(&thread2, 0, producer, &r2);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
return 0;
}
| 0
|
#include <pthread.h>
struct node{
int data;
struct node *next;
} *head;
pthread_t searcher[3];
pthread_t deleter[3];
pthread_t inserter[3];
pthread_mutex_t insert_mutex;
pthread_mutex_t delete_mutex;
sem_t delete_insert_lock;
sem_t delete_search_lock;
void *search(void *arg);
void *delete(void *arg);
void *insert(void *arg);
void add(int num);
void append(int num);
void interrupt_handler();
void print_list(struct node *linked_list);
int main(){
int i;
signal(SIGINT, interrupt_handler);
pthread_mutex_init(&insert_mutex, 0);
pthread_mutex_init(&delete_mutex, 0);
sem_init(&delete_insert_lock, 0, 1);
sem_init(&delete_search_lock, 0, 1);
for(i = 0; i < 3; i++){
pthread_create(&searcher[i], 0, search, 0);
pthread_create(&inserter[i], 0, insert, 0);
pthread_create(&deleter[i], 0, delete, 0);
}
for(i = 0; i < 3; i++){
pthread_join(inserter[i], 0);
pthread_join(searcher[i], 0);
pthread_join(deleter[i], 0);
}
}
void add(int num){
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->data=num;
if(head== 0){
head=temp;
head->next=0;
}else{
temp->next=head;
head=temp;
}
}
void append(int num){
struct node *temp,*right;
temp= (struct node *)malloc(sizeof(struct node));
temp->data=num;
right=(struct node *)head;
while(right->next != 0){
right=right->next;
}
right->next =temp;
right=temp;
right->next=0;
}
void *search(void *arg){
int num;
int flag = 1, count = 0;
struct node *temp;
while(1){
num = genrand_int32() %69;
sem_wait(&delete_search_lock);
temp=head;
printf("[S] Searcher will search for %d\\n", num);
if(temp==0){
printf("[S] The linked list is empty... Cannot find %d\\n", num);
}else{
while(temp != 0){
if(temp->data != num){
temp=temp->next;
++count;
}else{
print_list(head);
flag = 0;
break;
}
}
if (flag != 0){
printf("[S] Cannot find %d in linked list\\n", num);
print_list(head);
}
}
sem_post(&delete_search_lock);
sleep(3);
}
}
void *delete(void *arg){
struct node *temp, *prev;
int count, del_val, i;
while(1){
sem_wait(&delete_insert_lock);
sem_wait(&delete_search_lock);
pthread_mutex_lock(&delete_mutex);
temp=head;
count = 0;
while(temp != 0){
++count;
temp = temp->next;
}
del_val = genrand_int32() % count;
temp = head;
for(i = 0; i < del_val; i++){
prev = temp;
temp = temp->next;
}
if(temp==head){
head=temp->next;
free(temp);
printf("[D] Head value at index %d deleted.\\n", del_val);
print_list(head);
}else{
prev->next=temp->next;
free(temp);
printf("[D] Value at index %d deleted.\\n", del_val);
print_list(head);
}
pthread_mutex_unlock(&delete_mutex);
sem_post(&delete_insert_lock);
sem_post(&delete_search_lock);
sleep(6);
}
}
void *insert(void *arg){
int num;
struct node *temp;
while(1){
sem_wait(&delete_insert_lock);
pthread_mutex_lock(&insert_mutex);
temp=head;
if(temp==0){
num = genrand_int32() %69;
add(num);
printf("[I] CREATED LINKED LIST with value %d\\n", num);
}else{
num = genrand_int32() %69;
while(temp != 0){
if(temp->data != num){
temp=temp->next;
}else{
num = genrand_int32() %69;
temp=head;
}
}
temp=head;
while(temp->next!=0){
temp=temp->next;
}
append(num);
printf("[I] Added value %d to linked list.\\n", num);
}
print_list(head);
sem_post(&delete_insert_lock);
pthread_mutex_unlock(&insert_mutex);
sleep(5);
}
}
void print_list(struct node *linked_list){
int print_val;
printf("Linked List: ");
if(linked_list == 0){
printf("List currently empty\\n");
}else{
while(linked_list != 0){
print_val = linked_list->data;
printf("%d ", print_val);
linked_list = linked_list->next;
}
printf("\\n");
}
}
void interrupt_handler(){
int i;
for(i = 0; i < 3; i++){
pthread_detach(inserter[i]);
pthread_detach(searcher[i]);
pthread_detach(deleter[i]);
}
exit(0);
}
| 1
|
#include <pthread.h>
double cur_time() {
struct timespec ts[1];
clock_gettime(CLOCK_REALTIME, ts);
return ts->tv_sec + ts->tv_nsec * 1.0E-9;
}
void think(double s) {
double t0 = cur_time();
while (cur_time() - t0 < s) { }
}
double enter_lock_time;
double return_from_lock_time;
double enter_unlock_time;
long x;
} record;
record * a;
long i;
long n;
} record_buf;
record_buf * make_record_buf(long n) {
record * a = (record *)calloc(sizeof(record), n);
record_buf * R = (record_buf *)malloc(sizeof(record_buf));
R->a = a;
R->n = n;
R->i = 0;
return R;
}
void enter_lock(record_buf * R) {
long i = R->i;
assert(i < R->n);
R->a[i].enter_lock_time = cur_time();
}
void return_from_lock(record_buf * R) {
long i = R->i;
assert(i < R->n);
R->a[i].return_from_lock_time = cur_time();
}
void enter_unlock(record_buf * R, long x) {
long i = R->i;
assert(i < R->n);
R->a[i].enter_unlock_time = cur_time();
R->a[i].x = x;
R->i = i + 1;
}
int lock_vis(pthread_mutex_t * l,
record_buf * R) {
enter_lock(R);
int r = pthread_mutex_lock(l);
return_from_lock(R);
return r;
}
int unlock_vis(pthread_mutex_t * l,
record_buf * R, long x) {
enter_unlock(R, x);
return pthread_mutex_unlock(l);
}
pthread_mutex_t file_mutex[1];
void dump_record_buf(record_buf * R, int idx, FILE * wp) {
long n = R->n;
long i;
pthread_mutex_lock(file_mutex);
for (i = 0; i < n; i++) {
fprintf(wp, "%ld %d enter_lock %.9f return_from_lock %.9f enter_unlock %.9f\\n",
R->a[i].x, idx,
R->a[i].enter_lock_time, R->a[i].return_from_lock_time,
R->a[i].enter_unlock_time);
}
pthread_mutex_unlock(file_mutex);
}
pthread_t tid;
int idx;
long n_inc;
pthread_mutex_t * m;
FILE * wp;
} * thread_arg_t;
long g = 0;
void * thread_func(void * _arg) {
thread_arg_t arg = _arg;
long i;
long n_inc = arg->n_inc;
record_buf * R = make_record_buf(n_inc);
for (i = 0; i < n_inc; i++) {
lock_vis(arg->m, R);
long x = g++;
think(1.0e-4);
unlock_vis(arg->m, R, x);
think(1.0e-4);
}
dump_record_buf(R, arg->idx, arg->wp);
printf("g = %ld\\n", g);
return 0;
}
int main(int argc, char ** argv)
{
if (argc <= 3) {
fprintf(stderr,
"usage: %s no_of_threads no_of_increments log_file\\n"
"example:\\n %s 16 10000000 log.txt\\n",
argv[0], argv[0]);
exit(1);
}
int n_threads = atoi(argv[1]);
long n_inc = atol(argv[2]);
char * log_file = argv[3];
struct thread_arg args[n_threads];
double t0 = cur_time();
pthread_mutex_t m[1];
int i;
pthread_mutex_init(m, 0);
pthread_mutex_init(file_mutex, 0);
FILE * wp = fopen(log_file, "wb");
if (!wp) { perror("fopen"); exit(1); }
for (i = 0; i < n_threads; i++) {
args[i].idx = i;
args[i].n_inc = n_inc;
args[i].m = m;
args[i].wp = wp;
pthread_create(&args[i].tid, 0,
thread_func, (void *)&args[i]);
}
for (i = 0; i < n_threads; i++) {
pthread_join(args[i].tid, 0);
}
double t1 = cur_time();
printf("OK: elapsed time: %f\\n", t1 - t0);
fclose(wp);
return 0;
}
| 0
|
#include <pthread.h>
int buf[8];
int count;
int in,out;
int waiting;
pthread_mutex_t bbmutex;
pthread_cond_t bbcond;
void *producer(void *arg);
void *consumer(void *arg);
int get();
void put(int val);
void bbint(){
pthread_mutex_init(&bbmutex,0);
pthread_cond_init(&bbcond,0);
in = out = waiting = count = 0;
}
int main(int argc, char const *argv[])
{
int i,cc;
pthread_t pth[4 + 4];
void *retval;
bbint();
for (i = 0; i < 4; i++)
{
cc = pthread_create(&pth[i],0,producer,0);
if(cc != 0){ perror("main"); exit(-1);}
}
for(i = 0; i < 4; i++){
pthread_create(&pth[i + 4],0,consumer,0);
if (cc != 0){ perror("main"); exit(-1);}
}
for(i = 0 ; i < (4 + 4);i++){
pthread_join(pth[i],&retval);
pthread_detach(pth[i]);
if (cc != 0) {perror("main");exit(-1);}
}
exit(0);
}
void *producer(void *arg){
int ret = 0;
int i;
for(i = 0; i <(4*8)/4;i++){
put(i);
}
pthread_exit(&ret);
return 0;
}
void *consumer(void *arg){
int ret = 0;
int val;
int i;
for(i = 0; i< 8; i++){
val = get(i);
}
pthread_exit(&ret);
return 0;
}
int get(){
int val;
pthread_mutex_lock(&bbmutex);
while(1){
if (count > 0){
val = buf[out];
--count;
out = (out + 1) % 8;
if(waiting){
pthread_cond_signal(&bbcond);
}
break;
}else{
waiting++;
pthread_cond_wait(&bbcond,&bbmutex);
--waiting;
}
}
printf("get %d count:%d\\n",val,count);
pthread_mutex_unlock(&bbmutex);
return val;
}
void put(int val){
pthread_mutex_lock(&bbmutex);
while(1){
if(count < 8){
buf[in] = val;
count++;
in = (in + 1) % 8;
if(waiting){
pthread_cond_signal(&bbcond);
}
break;
}else{
waiting++;
pthread_cond_wait(&bbcond,&bbmutex);
--waiting;
}
}
printf("put %d count:%d\\n",val,count );
pthread_mutex_unlock(&bbmutex);
return;
}
| 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>
pthread_mutex_t a = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t b = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t c = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t d = PTHREAD_MUTEX_INITIALIZER;
void *
thr_fn1(void *arg)
{
while (1) {
pthread_mutex_lock(&a);
printf("a");
pthread_mutex_unlock(&b);
}
return ((void *)0);
}
void *
thr_fn2(void *arg)
{
while (1) {
pthread_mutex_lock(&b);
printf("b");
pthread_mutex_unlock(&c);
}
return ((void *)0);
}
void *
thr_fn3(void *arg)
{
while (1) {
pthread_mutex_lock(&c);
printf("c");
pthread_mutex_unlock(&d);
}
return ((void *)0);
}
void *
thr_fn4(void *arg)
{
while (1) {
pthread_mutex_lock(&d);
printf("d");
pthread_mutex_unlock(&a);
}
return ((void *)0);
}
int
main(void)
{
int ret;
pthread_t tid1, tid2, tid3, tid4;
pthread_mutex_lock(&a);
pthread_mutex_lock(&b);
pthread_mutex_lock(&c);
pthread_mutex_lock(&d);
if ((ret = pthread_create(&tid1, 0, thr_fn1, 0)) != 0)
err_exit(ret, "can't create thread 1");
if ((ret = pthread_create(&tid2, 0, thr_fn2, 0)) != 0)
err_exit(ret, "can't create thread 2");
if ((ret = pthread_create(&tid3, 0, thr_fn3, 0)) != 0)
err_exit(ret, "can't create thread 3");
if ((ret = pthread_create(&tid4, 0, thr_fn4, 0)) != 0)
err_exit(ret, "can't create thread 4");
pthread_mutex_unlock(&a);
alarm(5);
if ((ret = pthread_join(tid1, 0)) != 0)
err_exit(ret, "can't join with tid1");
if ((ret = pthread_join(tid2, 0)) != 0)
err_exit(ret, "can't join with tid2");
if ((ret = pthread_join(tid3, 0)) != 0)
err_exit(ret, "can't join with tid3");
if ((ret = pthread_join(tid4, 0)) != 0)
err_exit(ret, "can't join with tid4");
exit(0);
}
| 1
|
#include <pthread.h>
int
csnet_cond_init(struct csnet_cond* cond) {
if (pthread_mutex_init(&cond->mutex, 0) < 0) {
return -1;
}
if (pthread_cond_init(&cond->cond, 0) < 0) {
pthread_mutex_destroy(&cond->mutex);
return -1;
}
return 0;
}
void
csnet_cond_destroy(struct csnet_cond* cond) {
pthread_mutex_destroy(&cond->mutex);
pthread_cond_destroy(&cond->cond);
}
void
csnet_cond_blocking_wait(struct csnet_cond* cond) {
pthread_mutex_lock(&cond->mutex);
pthread_cond_wait(&cond->cond, &cond->mutex);
pthread_mutex_unlock(&cond->mutex);
}
void
csnet_cond_nonblocking_wait(struct csnet_cond* cond, int seconds, int microseconds) {
struct timeval now;
struct timespec timeout;
gettimeofday(&now, 0);
timeout.tv_sec = now.tv_sec + seconds;
pthread_mutex_lock(&cond->mutex);
pthread_cond_timedwait(&cond->cond, &cond->mutex, &timeout);
pthread_mutex_unlock(&cond->mutex);
}
void
csnet_cond_signal_one(struct csnet_cond* cond) {
pthread_cond_signal(&cond->cond);
}
void
csnet_cond_signal_all(struct csnet_cond* cond) {
pthread_cond_broadcast(&cond->cond);
}
| 0
|
#include <pthread.h>
static int has_init_thread_pool = 0;
static int thread_num = 10;
static void *thread_pool;
static struct task *task_head;
pthread_mutex_t task_mutex;
pthread_mutex_t read_task_mutex;
void *thread_handle(void *arg);
int
init_thread_pool(int max)
{
thread_num = max;
if(has_init_thread_pool != 0)
return 0;
has_init_thread_pool = 1;
pthread_mutex_init(&task_mutex,0);
pthread_mutex_init(&read_task_mutex, 0);
thread_pool = (void *)malloc(max);
for (int thread_index = 0; thread_index < max; thread_index ++) {
char *thread_id_str = (char *)malloc(64);
sprintf(thread_id_str, "%d", thread_index);
pthread_t *t = (pthread_t *)malloc(sizeof(pthread_t));
if (pthread_create( t, 0, thread_handle, thread_id_str))
return -1;
}
return 0;
}
int
add_task(struct task *t)
{
pthread_mutex_lock(&task_mutex);
if(t == 0)
return -1;
t->next = 0;
struct task *temp = task_head;
if(temp == 0) {
task_head = t;
} else {
while (temp->next != 0) {
temp = temp->next;
}
temp->next = t;
}
pthread_mutex_unlock(&task_mutex);
return 1;
}
int
add_urgent_task(struct task *t)
{
pthread_mutex_lock(&task_mutex);
t->next = task_head;
task_head = t;
pthread_mutex_unlock(&task_mutex);
return 1;
}
struct task *
get_task()
{
struct task *result = 0;
pthread_mutex_lock(&read_task_mutex);
while (task_head == 0);
pthread_mutex_lock(&task_mutex);
result = task_head;
task_head = result->next;
pthread_mutex_unlock(&task_mutex);
pthread_mutex_unlock(&read_task_mutex);
return result;
}
int
init_thread_pool(void)
{
return init_thread_pool(128);
}
void *
thread_handle(void *arg)
{
while(1) {
struct task *task = get_task();
printf("thread%s: ", arg);
task->handle(task->data);
free(task);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex_fpga= PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_dpll= PTHREAD_MUTEX_INITIALIZER;
{
unsigned char cs;
unsigned short addr;
unsigned short len;
unsigned char buff[64];
}spi_rdwr;
int fd,errnu_f = 0,errnu_d = 0;
spi_rdwr sopt;
int fpga_dpll_test(void *arg)
{
fd = open("/dev/spidev0.0", O_RDWR);
if (fd == -1) {
printf("dpll file open failed.\\n");
return -1;
}
printf("arg=%d\\n",*((char*)arg));
if(*((char*)arg) == 0)
{
short i = 0,data;
while(1)
{
pthread_mutex_lock(&mutex_fpga);
sopt.cs = 0;
sopt.addr = 0x1040;
sopt.len = 4;
sopt.buff[0] = i;
sopt.buff[1] = i;
sopt.buff[2] = i;
sopt.buff[3] = i;
write(fd, &sopt, sizeof(sopt));
usleep(100);
read(fd, &sopt, sizeof(sopt));
data = sopt.buff[0];
pthread_mutex_unlock(&mutex_fpga);
if(data!=i)
{
errnu_f++;
printf("fpga,error,i=%x,data=%x %x %x %x,err=%d\\n\\n",i,data,sopt.buff[1],sopt.buff[2],sopt.buff[3],errnu_f);
}
i++;
if(i>0xfe)
i = 0;
usleep(1000);
}
}
else
{
unsigned char i = 0,data;
while(1)
{
pthread_mutex_lock(&mutex_dpll);
sopt.cs = 1;
sopt.addr = 3;
sopt.len = 1;
sopt.buff[0] = i;
write(fd, &sopt, sizeof(sopt));
usleep(100);
read(fd, &sopt, sizeof(sopt));
data = sopt.buff[0];
pthread_mutex_lock(&mutex_dpll);
if(data!=i)
{
errnu_f++;
printf("dpll,error,i=%x,data=%x,err=%d\\n\\n",i,data,errnu_f);
}
i++;
if(i>0xfe)
i = 0;
usleep(1000);
}
}
}
int main(int argc, char *argv[])
{
int pid;
char arg1 = 0, arg2 = 1;
pthread_t id_1,id_2,id_3,id_4,id_5;
pthread_create(&id_1, 0, (void *)fpga_dpll_test, &arg1);
pthread_create(&id_2, 0, (void *)fpga_dpll_test, &arg1);
pthread_create(&id_3, 0, (void *)fpga_dpll_test, &arg2);
pthread_create(&id_4, 0, (void *)fpga_dpll_test, &arg2);
pthread_create(&id_5, 0, (void *)fpga_dpll_test, &arg1);
sleep(1);
while(1);
return 0;
}
| 0
|
#include <pthread.h>
void* philosopher (void* t_id_t);
pthread_mutex_t forks[4];
int main (int argc, char *argv[])
{
pthread_t seat[4];
int t_id[4] = {0,1,2,3};
int err = 0;
int i=0;
for (i = 0; i < 4; i++)
{
if (pthread_mutex_init (&forks[i], 0) != 0){
printf("\\n mutex init failed\\n");
return 1;
}
}
while(1)
{
for (i = 0; i < 4; i++)
{
pthread_mutex_lock (&forks[i]);
}
for (i = 0; i < 4; i++)
{
err = pthread_create (&seat[i], 0,
philosopher, (void*)&t_id[i]);
if (err != 0){
printf("Unable to create thread\\n");
return 0;
}
}
for (i = 0; i < 4; i++)
{
pthread_mutex_unlock (&forks[i]);
}
for (i = 0; i < 4; i++)
{
pthread_join(seat[i], 0);
}
}
pthread_exit (0);
}
void* philosopher (void* t_id_t)
{
int* t_id = (int*)t_id_t;
printf ("------%d", *t_id);
usleep(100+*t_id);
if(*t_id == 3){
pthread_mutex_lock (&forks[*t_id]);
pthread_mutex_lock (&forks[0]);
}else{
pthread_mutex_lock (&forks[*t_id]);
pthread_mutex_lock (&forks[*t_id+1]);
}
printf ("......%d", *t_id);
if(*t_id == 3){
pthread_mutex_unlock (&forks[*t_id]);
pthread_mutex_unlock (&forks[0]);
}else{
pthread_mutex_unlock (&forks[*t_id]);
pthread_mutex_unlock (&forks[*t_id+1]);
}
pthread_exit (0);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static int avail = 0;
static void *
threadFunc(void *arg)
{
int cnt = atoi((char *) arg);
int j;
for (j = 0; j < cnt; j++) {
sleep(1);
pthread_mutex_lock(&mtx);
avail++;
pthread_mutex_unlock(&mtx);
}
return 0;
}
int
main(int argc, char *argv[])
{
pthread_t tid;
int s, j;
int totRequired;
int numConsumed;
int done;
time_t t;
t = time(0);
totRequired = 0;
for (j = 1; j < argc; j++) {
totRequired += atoi(argv[j]);
pthread_create(&tid, 0, threadFunc, argv[j]);
}
numConsumed = 0;
done = 0;
for (;;) {
pthread_mutex_lock(&mtx);
while (avail > 0) {
numConsumed ++;
avail--;
printf("T=%ld: numConsumed=%d\\n", (long) (time(0) - t),
numConsumed);
done = numConsumed >= totRequired;
}
pthread_mutex_unlock(&mtx);
if (done)
break;
}
exit(0);
}
| 0
|
#include <pthread.h>
extern char **environ;
pthread_mutex_t env_mutex;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
static int environ_extended = 0;
void update_existing_env(const char *str, int env_indx);
void add_new_env(const char *str);
static void thread_init(void) {
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&env_mutex, &attr);
}
int putenv_r(char *str) {
int err, i, len, env_indx;
sigset_t mask, old_mask;
sigfillset(&mask);
pthread_once(&init_done, thread_init);
if (strpbrk(str, "=") == 0)
return -1;
len = strcspn(str, "=");
pthread_mutex_lock(&env_mutex);
if((err = pthread_sigmask(SIG_SETMASK, &mask, &old_mask)) != 0)
err_exit(err, "SIG_BLOCK error");
env_indx = -1;
for (i = 0; environ[i] != 0; i++) {
if((strncmp(str, environ[i], len) == 0) &&
(environ[i][len] == '=')) {
env_indx = i;
break;
}
}
if(env_indx >= 0)
update_existing_env(str, env_indx);
else
add_new_env(str);
if (sigprocmask(SIG_SETMASK, &old_mask, 0) < 0)
err_sys("SIG_SETMASK error");
pthread_mutex_unlock(&env_mutex);
return 0;
}
void update_existing_env(const char *str, int env_indx) {
int env_len, new_env_len;
env_len = strlen(environ[env_indx]);
new_env_len = strlen(str);
if(env_len < new_env_len)
strcpy(environ[env_indx], str);
else {
char *new_env_ptr = (char *) malloc(new_env_len + 1);
strcpy(new_env_ptr, str);
environ[env_indx] = new_env_ptr;
}
}
void add_new_env(const char *str) {
int env_len = 0;
for(int i = 0; environ[i] != 0; i++)
env_len++;
char *new_env_ptr = malloc(strlen(str) + 1);
strcpy(new_env_ptr, str);
if (environ_extended){
environ = realloc(environ, env_len + 1);
} else {
char ** new_environ = malloc(env_len + 1);
for(int i = 0; environ[i] != 0; i++)
new_environ[i] = environ[i];
environ = new_environ;
environ_extended = 1;
}
environ[env_len] = new_env_ptr;
environ[env_len + 1] = 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_consumer = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_producer = PTHREAD_COND_INITIALIZER;
void *producer(void *arg)
{
long int i;
long int loops = (long int)arg;
for (i=0; i<loops; i++) {
pthread_mutex_lock(&mutex);
while (buffer_is_full())
pthread_cond_wait(&cond_consumer, &mutex);
buffer_put(i);
pthread_cond_signal(&cond_producer);
pthread_mutex_unlock(&mutex);
}
return 0;
}
void *consumer(void *arg)
{
long int i;
long int loops = (long int)arg;
for (i=0; i<loops; i++) {
pthread_mutex_lock(&mutex);
while (buffer_is_empty())
pthread_cond_wait(&cond_producer, &mutex);
int tmp = buffer_get();
pthread_cond_signal(&cond_consumer);
pthread_mutex_unlock(&mutex);
fprintf(stdout, "%d\\n", tmp);
}
return 0;
}
int main(int argc, char *argv[])
{
int i;
pthread_t *thread_handles;
struct timeval start, end;
float elapsed_time;
long int num_producers, num_consumers, items;
if (argc <= 3) {
exit(-1);
}
num_producers = strtol(argv[1], 0, 10);
num_consumers = strtol(argv[2], 0, 10);
items = strtol(argv[3], 0, 10);
thread_handles = malloc((num_producers+num_consumers)*sizeof(pthread_t));
fprintf(stdout, "Number of producers = %ld\\n", num_producers);
fprintf(stdout, "Number of consumers = %ld\\n", num_consumers);
fprintf(stdout, "Number of items = %ld\\n", items);
gettimeofday(&start, 0);
for (i=0; i<num_producers; i++)
if (pthread_create(&thread_handles[i], 0, producer, (void *) (items/num_producers))) {
fprintf(stderr, "Error spawning thread\\n");
exit(-1);
}
for (i=num_producers; i<num_producers+num_consumers; i++)
if (pthread_create(&thread_handles[i], 0, consumer, (void *) (items/num_consumers))) {
fprintf(stderr, "Error spawning thread\\n");
exit(-1);
}
for (i=0; i<num_producers+num_consumers; i++) {
pthread_join(thread_handles[i], 0);
}
gettimeofday(&end, 0);
elapsed_time = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1000000.0;
fprintf(stdout, "Elapsed time: %g s\\n", elapsed_time);
free(thread_handles);
return 0;
}
| 0
|
#include <pthread.h>
int buffer;
int count = 0;
pthread_cond_t cond;
pthread_mutex_t mutex;
void put(int value) {
assert(count == 0);
count = 1;
buffer = value;
}
int get() {
assert(count == 1);
count = 0;
return buffer;
}
void *producer(void *arg) {
int i;
int loops = *(int *) arg;
for (i = 0; i < loops; i++) {
pthread_mutex_lock(&mutex);
while (count == 1)
pthread_cond_wait(&cond, &mutex);
put(i);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
return 0;
}
void *consumer(void *arg) {
int i;
int loops = *(int *) arg;
for (i = 0; i < loops; i++) {
pthread_mutex_lock(&mutex);
while (count == 0)
pthread_cond_wait(&cond, &mutex);
int tmp = get();
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
printf("%d\\n", tmp);
}
return 0;
}
int main(){
pthread_t p;
pthread_t c1;
pthread_t c2;
int loops = 10;
pthread_create(&p, 0, producer, &loops);
pthread_create(&c1, 0, consumer, &loops);
pthread_create(&c2, 0, consumer, &loops);
pthread_join(p, 0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_t chCliente[5];
pthread_t caixas[5];
int filas_vazia = 5;
int cliente_fila = 0;
int conf = 0;
sem_t filas[5];
sem_t clientes;
void NoCaixa(float delay1) {
float inst1=0;
float inst2=0;
if(delay1<0.001){
return;
}
inst1 = (float)clock()/(float)CLOCKS_PER_SEC;
while(inst2-inst1<delay1){
inst2 = (float)clock()/(float)CLOCKS_PER_SEC;
}
return;
}
void *ChegadaCliente(void *thread_id){
int j, i;
int caixa, value = 0, qnt, menorFila;
int aux = 0;
while(conf == 0){
menorFila = 50;
caixa = 5 + 1;
pthread_mutex_lock(&mutex);
for(i=0; i<5; i++){
sem_getvalue(&filas[i], &value);
if(value == 0){
menorFila = value;
caixa=i;
break;
}
else if(value < menorFila){
menorFila = value;
caixa = i;
}
}
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&mutex);
cliente_fila++;
sem_wait(&clientes);
sem_post(&filas[caixa]);
sem_getvalue(&clientes, &aux);
if(aux == 0) {
conf = 1;
}
printf("INSERIRU CLIENTE NO CAIXA: %d. FALTAM %d CLIENTES PARA CHEGAR.\\n\\n", caixa, aux);
pthread_mutex_unlock(&mutex);
NoCaixa(2);
}
}
void *AtendeCliente(void *thread_id){
int maiorFila, transfere, caixa;
int i, value, qnt;
int aux = 0;
caixa = (int)thread_id;
sem_getvalue(&clientes, &aux);
while(cliente_fila > 0 || aux > 0){
NoCaixa(3);
maiorFila = 0;
sem_getvalue(&filas[caixa], &value);
if(value == 0){
pthread_mutex_lock(&mutex2);
for(i = 0; i<5;i++){
sem_getvalue(&filas[i], &qnt);
if(qnt > maiorFila){
maiorFila = qnt;
transfere = i;
}
}
if(maiorFila != 0){
cliente_fila--;
sem_wait(&filas[transfere]);
printf("O Caixa %d atendeu o cliente da fila %d. Falta %d clientes\\n\\n", caixa, transfere, aux);
}
else{
printf("Todos os caixas estao vazios!!\\n");
}
pthread_mutex_unlock(&mutex2);
}
else{
pthread_mutex_lock(&mutex2);
if(value == 1){
filas_vazia++;
}
cliente_fila--;
sem_wait(&filas[caixa]);
printf("O Caixa %d atendeu e sobrou %d clientes em sua fila. Falta %d clientes.\\n\\n",caixa, value-1, aux);
pthread_mutex_unlock(&mutex2);
}
sem_getvalue(&clientes, &aux);
}
}
int main(int argc, char *argv[]){
int i,t;
srand( (unsigned)time(0) );
for(t=0; t<5; t++){
sem_init(&filas[t], 0, 0);
}
sem_init(&clientes, 0, 50);
for(i=0; i<5; i++){
if(pthread_create(&chCliente[i], 0, ChegadaCliente, (void*)i)){
printf("Erro na criação da Thread da Fila: %d\\n", t);
}
}
for(t=0; t<5; t++){
if(pthread_create(&caixas[t], 0, AtendeCliente, (void*)t)){
printf("Erro na criacao da Thread da Fila: %d\\n", t);
}
}
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
int fib;
pthread_mutex_t counter_lock = PTHREAD_MUTEX_INITIALIZER;
void* fibonacci(void *n)
{
int a=0,b=1,c,i;
pthread_mutex_lock(&counter_lock);
if(atoi(n)==1){
printf("Fibonacci sequence: ");
printf("%d\\n",a);
exit(0);
}
else if(atoi(n)==2){
printf("Fibonacci sequence: ");
printf("%d, %d",a,b);
exit(0);
}else{
printf("Fibonacci sequence: ");
printf("%d, %d, ",a,b);
for(i=0;i<atoi(n)-2;i++)
{
c=a+b;
printf("%d, ",c);
a=b;
b=c;
}
printf("\\n");
pthread_exit(0);
}
pthread_mutex_unlock(&counter_lock);
return 0;
}
int main(int argc,char* argv[])
{
pthread_t thread;
if(argc!=2)
{
fprintf(stderr,"Syntax: ./a.out <integer value>");
return -1;
}
if(atoi(argv[1])<0)
{
fprintf(stderr,"Argument %d must be positive value\\n",atoi(argv[1]));
return -1;
}
pthread_create(&thread,0,fibonacci,(void*)argv[1]);
pthread_join(thread,0);
return 0;
}
| 1
|
#include <pthread.h>
double pe_final;
double *a;
double *b;
pthread_mutex_t sb;
void *calc(void *threadarg)
{
int i,j,thid;
double pe;
thid =(intptr_t) threadarg;
for(i=thid;i<100000000;i+=8){
pe += a[i]*b[i];
}
pthread_mutex_lock(&sb);
pe_final+=pe;
pthread_mutex_unlock(&sb);
}
int main(int argc, char *argv[]){
int j,t,cj=0,rc;
a =(double*)malloc(100000000*sizeof(double));
b=(double*)malloc(100000000*sizeof(double));
unsigned int seed =time(0);
for(j=0;j<100000000;j++){
a[j]=rand_r(&seed);
b[j]=rand_r(&seed);
}
pthread_t th[8];
struct timeval inicio, final2;
gettimeofday(&inicio, 0);
for(j=0;j<8;j++){
rc = pthread_create(&(th[j]),0, &calc ,(void* )(intptr_t) j);
if(rc){
printf("ERROR,%d",rc);
exit(-1);
}
}
for(j=0; j<8; j++) {
rc = pthread_join(th[j],0);
if(rc){
printf("ERROR,%d",rc);
exit(-1);
}
}
gettimeofday(&final2, 0);
printf("%lf\\n",pe_final);
printf("%lf:milisegundos",(double) (1000.0 * (final2.tv_sec - inicio.tv_sec) + (final2.tv_usec - inicio.tv_usec) / 1000.0));
return 0;
}
| 0
|
#include <pthread.h>
void *functionA();
void *functionB();
void *functionC();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t con_var1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t con_var2 = PTHREAD_COND_INITIALIZER;
int counter = 1;
int main(){
pthread_t thread1, thread2, thread3;
pthread_create(&thread1, 0, &functionA, 0);
pthread_create(&thread2, 0, &functionB, 0);
pthread_create(&thread3, 0, &functionC, 0);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
pthread_join(thread3, 0);
pthread_cond_destroy(&con_var1);
pthread_mutex_destroy(&mutex1);
printf("\\nNow finished\\n");
exit(0);
}
void *functionA(){
while(counter <= 15){
pthread_mutex_lock(&mutex1);
if(!(counter%3) && counter != 3){
printf("I am Thread 1 the current value is: %d\\n", counter);
counter++;
}else if(counter < 6){
pthread_cond_signal(&con_var2);
}else{
pthread_cond_wait(&con_var1, &mutex1);
printf("I am Thread 1 the current value is: %d\\n", counter);
counter++;
}
pthread_mutex_unlock(&mutex1);
sleep(1);
}
pthread_exit(0);
}
void *functionB(){
while(counter<17){
pthread_mutex_lock(&mutex1);
if(!(counter%3) && counter != 3){
pthread_cond_signal(&con_var1);
}else if(counter < 6){
pthread_cond_signal(&con_var2);
}else{
printf("I am Thread 2 the current value is: %d\\n", counter);
counter++;
}
pthread_mutex_unlock(&mutex1);
sleep(1);
}
pthread_exit(0);
}
void *functionC(){
while(counter<17){
pthread_mutex_lock(&mutex1);
if(!(counter%3) && counter != 3){
pthread_cond_signal(&con_var1);
}else if(counter < 6){
pthread_cond_wait(&con_var2, &mutex1);
printf("I am Thread 3 the current value is: %d\\n", counter);
counter++;
}else{
printf("I am Thread 3 the current value is: %d\\n", counter);
counter++;
}
pthread_mutex_unlock(&mutex1);
sleep(1);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
static unsigned int *mod[TILES];
static void
compress_row (size_t row)
{
short first_zero = -1, first_non_zero = -1;
if (row > 3)
return;
for (int i = 0; i < 4; i++) {
if (*mod[row*4 +i] == 0 && first_zero < 0)
first_zero = i;
if (*mod[row*4 +i] == 0 || first_zero < 0)
continue;
first_non_zero = i;
break;
}
if (first_non_zero < 0 || first_zero < 0)
return;
for (int i = 0; i+first_non_zero < 4; i++) {
int tmp;
size_t a, b;
a = row*4 +first_non_zero +i;
b = row*4 +first_zero +i;
tmp = *mod[a];
*mod[a] = *mod[b];
*mod[b] = tmp;
}
compress_row (row);
}
static int
new_tile (struct tile_game *pgame)
{
unsigned char empty[16];
size_t i, j, loc;
pthread_mutex_lock (&pgame->lock);
for (i = 0, j = 0; i < TILES; i++) {
if (pgame->tiles[i])
continue;
empty[j++] = i;
}
if (j == 0)
return -1;
loc = empty[rand_r(&pgame->seedp) % j];
pgame->tiles[loc] = ((rand_r(&pgame->seedp) & 1) +1) * 2;
pgame->moves++;
pthread_mutex_unlock (&pgame->lock);
return pgame->tiles[loc];
}
int
init_tiles (struct tile_game *pgame)
{
pthread_mutex_init (&pgame->lock, 0);
pthread_mutex_lock (&pgame->lock);
pgame->seedp = time(0);
pgame->max_tile = 0;
pgame->moves = 0;
pgame->score = 0;
pgame->tiles = calloc (TILES, sizeof(*pgame->tiles));
if (!pgame->tiles) {
destroy_tiles (pgame);
err (2, "Unable to allocate %lu bytes of memory: %s %d\\n",
TILES * sizeof(*pgame->tiles),
"tile.c", 124);
}
pthread_mutex_unlock (&pgame->lock);
new_tile (pgame);
new_tile (pgame);
return 1;
}
void
destroy_tiles (struct tile_game *pgame)
{
pthread_mutex_destroy (&pgame->lock);
free (pgame->tiles);
}
int
move_tiles (struct tile_game *pgame, enum tile_dir dir)
{
if (!pgame || !pgame->tiles) {
errx (2, "Must initialize the game first");
}
pthread_mutex_lock (&pgame->lock);
switch (dir) {
case UP:
for (int i = 0; i < 4; i++) {
mod[i*4 +0] = &pgame->tiles[0*4 +i];
mod[i*4 +1] = &pgame->tiles[1*4 +i];
mod[i*4 +2] = &pgame->tiles[2*4 +i];
mod[i*4 +3] = &pgame->tiles[3*4 +i];
}
break;
case DOWN:
for (int i = 0; i < 4; i++) {
mod[i*4 +0] = &pgame->tiles[3*4 +i];
mod[i*4 +1] = &pgame->tiles[2*4 +i];
mod[i*4 +2] = &pgame->tiles[1*4 +i];
mod[i*4 +3] = &pgame->tiles[0*4 +i];
}
break;
case LEFT:
for (int i = 0; i < TILES; i++) {
mod[i] = &pgame->tiles[i];
}
break;
case RIGHT:
for (int i = 0; i < 4; i++) {
mod[i*4 +0] = &pgame->tiles[i*4 +3];
mod[i*4 +1] = &pgame->tiles[i*4 +2];
mod[i*4 +2] = &pgame->tiles[i*4 +1];
mod[i*4 +3] = &pgame->tiles[i*4 +0];
}
break;
}
for (int i = 0; i < TILES; i++) {
compress_row (i/4);
if ((i % 4 == 3) || (*mod[i] != *mod[i+1]))
continue;
*mod[i] *= 2;
*mod[i+1] = 0;
pgame->score += *mod[i];
if (*mod[i] > pgame->max_tile)
pgame->max_tile = *mod[i];
}
pthread_mutex_unlock (&pgame->lock);
return new_tile (pgame);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
void* thread1(void* arg);
void* thread2(void* arg);
void* thread3f(void* arg);
void* thread4f(void* arg);
int main(){
pthread_t thread;
pthread_t thread3;
pthread_t thread4;
pthread_create(&thread, 0, thread2, 0);
pthread_create(&thread3, 0, thread3f, 0);
pthread_create(&thread4, 0, thread4f, 0);
thread1(0);
pthread_join(thread, 0);
pthread_join(thread3, 0);
pthread_join(thread4, 0);
return 0;
}
void* thread1(void* arg){
puts ("thread1-1");
pthread_mutex_lock(&mutex1);
puts ("thread1-2");
sched_yield();
pthread_mutex_lock(&mutex2);
puts ("thread1-3");
pthread_mutex_unlock(&mutex2);
puts ("thread1-4");
pthread_mutex_unlock(&mutex1);
}
void* thread2(void* arg){
puts ("thread2-1");
pthread_mutex_lock(&mutex2);
puts ("thread2-2");
sched_yield();
pthread_mutex_unlock(&mutex2);
puts ("thread2-3");
pthread_mutex_lock(&mutex1);
puts ("thread2-4");
pthread_mutex_unlock(&mutex1);
}
void* thread3f(void* arg)
{
puts ("thread3-1");
pthread_mutex_lock(&mutex2);
puts ("thread3-2");
sched_yield();
pthread_mutex_unlock(&mutex2);
puts ("thread3-3");
pthread_mutex_lock(&mutex1);
puts ("thread3-4");
pthread_mutex_unlock(&mutex1);
}
void* thread4f(void* arg){
puts ("thread4-1");
pthread_mutex_lock(&mutex1);
puts ("thread4-2");
sched_yield();
pthread_mutex_lock(&mutex2);
puts ("thread4-3");
pthread_mutex_unlock(&mutex2);
puts ("thread4-4");
pthread_mutex_unlock(&mutex1);
}
| 1
|
#include <pthread.h>
const int THREAD_NUMBER = 3;
pthread_mutex_t thread_mutex[THREAD_NUMBER];
pthread_cond_t thread_cond[THREAD_NUMBER];
bool thread_wait_flag[THREAD_NUMBER];
pthread_mutex_t mutex;
int thread_turn;
void *thread_func(void *arg);
int main(int argc, char **argv)
{
pthread_t tids[THREAD_NUMBER];
for (int i = 0; i < THREAD_NUMBER; ++i)
{
pthread_mutex_init(&thread_mutex[i], 0);
pthread_cond_init(&thread_cond[i], 0);
}
pthread_mutex_init(&mutex, 0);
thread_turn = 0;
for (int i = 0; i < THREAD_NUMBER; ++i)
thread_wait_flag[i] = 0;
for (int i = 0; i < THREAD_NUMBER; ++i)
{
pthread_create(&tids[i], 0, thread_func, (void *)i);
}
for (int i = 0; i < THREAD_NUMBER; ++i)
{
pthread_join(tids[i], 0);
}
printf("\\n");
return 0;
}
void *thread_func(void *arg)
{
int id = (int)arg;
char ch = 'A' + id;
int count = 0;
while (1)
{
if (id == thread_turn)
{
printf("%c", ch);
++count;
if (id == THREAD_NUMBER-1 && count == 10)
break;
pthread_mutex_lock(&mutex);
++thread_turn;
thread_turn %= THREAD_NUMBER;
pthread_mutex_unlock(&mutex);
while (1)
{
pthread_mutex_lock(&thread_mutex[thread_turn]);
if (1 == thread_wait_flag[thread_turn])
{
pthread_cond_signal(&thread_cond[thread_turn]);
pthread_mutex_unlock(&thread_mutex[thread_turn]);
break;
}
pthread_mutex_unlock(&thread_mutex[thread_turn]);
}
if (count == 10)
break;
}
else
{
pthread_mutex_lock(&thread_mutex[id]);
thread_wait_flag[id] = 1;
pthread_cond_wait(&thread_cond[id], &thread_mutex[id]);
thread_wait_flag[id] = 0;
pthread_mutex_unlock(&thread_mutex[id]);
}
}
return (void *)0;
}
| 0
|
#include <pthread.h>
int curRow,curCol;
int ar , ac , br , bc;
struct arg_struct {
int row,col;
};
int A[1000][1000],B[1000][1000],C[1000][1000];
void nextTask();
void *multiply(void *arguments)
{
struct arg_struct *args = (struct arg_struct *)arguments;
int row=args->row , col=args->col ;
int k ;
C[row][col] = 0;
for (k = 0; k < ac; k++)
{
C[row][col] += A[row][k] * B[k][col];
}
nextTask();
pthread_exit(0);
}
void nextTask()
{
if(curRow==(ar-1)&&curCol==(bc-1))
{
pthread_exit(0);
}
else if(curRow==(ar-1))
{
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&mutex);
curRow=0;
curCol++;
pthread_mutex_unlock(&mutex);
}
else
{
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&mutex);
curRow++;
pthread_mutex_unlock(&mutex);
}
struct arg_struct argms;
argms.row=curRow;
argms.col=curCol;
multiply((void *)&argms);
}
int main()
{
int i,j;
scanf("%d %d",&ar,&ac);
scanf("%d %d",&br,&bc);
if(ac!=br)
{
printf("Incompatible Matrices\\n");
return 0;
}
for (i = 0; i < ar; i++)
{
for (j = 0; j < ac; j++)
{
scanf("%d", &A[i][j]);
}
}
for (i = 0; i < ac; i++)
{
for (j = 0; j < bc; j++)
{
scanf("%d", &B[i][j]);
}
}
pthread_t hilo[ar];
struct arg_struct args[ar];
curRow=9;
curCol=0;
for (i = 0; i < 10; i++)
{
args[i].row = i;
args[i].col = 0;
pthread_create(&hilo[i] , 0,multiply, (void *)&args[i]);
}
for (i = 0; i < ar; i++)
pthread_join(hilo[i],0);
for (i = 0; i < ar; i++)
{
for (j = 0; j < bc; j++)
printf("\\t%d\\t ", C[i][j]);
printf("\\n");
}
return 0;
}
| 1
|
#include <pthread.h>
double a;
double b;
int n;
double approx;
int thread_amount;
pthread_mutex_t approx_lock;
double static NEG_1_TO_POS_1 = 0.66666666666667;
double static ZERO_TO_POS_10 = 333.333;
double f(double a) {
return a * a;
}
void trap() {
double h = (b-a) / n;
approx = ( f(a) - f(b) ) / 2.0;
for(int i = 1; i < n-1; i++) {
double x_i = a + i*h;
approx += f(x_i);
}
approx = h*approx;
}
void * thread_trap(void * t_num_void_pointer){
int my_rank = *((int *) t_num_void_pointer);
double h = (b-a) / n;
int local_n = n/thread_amount;
double local_a = a + my_rank + local_n * h;
double local_b = local_a + local_n * h;
pthread_mutex_lock(&approx_lock);
approx += h * ((f(local_a) + f(local_b)) / 2.0);
pthread_mutex_unlock(&approx_lock);
int i;
for(i=1; i<local_n; i++){
double x_i = local_a + 1*h;
pthread_mutex_lock(&approx_lock);
approx += h * f(x_i);
pthread_mutex_unlock(&approx_lock);
}
return 0;
}
void run_threads() {
pthread_t * threads = malloc(sizeof(pthread_t) * thread_amount);
int i;
for(i=0; i<thread_amount; i++){
int * thread_number = malloc(sizeof(int));
*thread_number = i;
pthread_create(&threads[i], 0, thread_trap, thread_number);
}
for(int i=0; i<thread_amount; i++){
pthread_join(threads[i],0);
}
}
int main() {
a = -1.0;
b = 1.0;
n = 1000000000;
int current_number_of_threads[3] = {2, 50, 100};
pthread_mutex_init(&approx_lock,0);
int i = 0;
for (i = 0; i<3; i++) {
approx = 0;
thread_amount = current_number_of_threadsi[i];
printf("\\nRan with %d threads\\n", thread_amount);
timerStart();
run_threads();
printf("Took %ld ms\\n", timerStop());
printf("a:%f\\t b:%f\\t n:%d\\t actual:%f\\t approximation:%f\\n", a, b, n, NEG_1_TO_POS_1, approx);
}
a = 0.0;
b = 10.0;
n = 1000000000;
int i = 0;
for (i = 0; i<3; i++) {
approx = 0;
thread_amount = current_number_of_threadsi[i];
printf("\\nRan with %d threads\\n", thread_amount);
timerStart();
run_threads();
printf("Took %ld ms\\n", timerStop());
printf("a:%f\\t b:%f\\t n:%d\\t actual:%f\\t approximation:%f\\n", a, b, n, NEG_1_TO_POS_1, approx);
}
pthread_mutex_destroy(&approx_lock);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t forks[5];
pthread_mutex_t getting_forks_mx;
pthread_cond_t getting_forks_cond;
pthread_t phils[5];
void *philosopher (void *id);
int food_on_table ();
void get_forks (int, int, int);
void down_forks (int, int);
pthread_mutex_t foodlock;
int sleep_seconds = 0;
int
main (int argn,
char **argv)
{
int i;
if (argn == 2)
sleep_seconds = atoi (argv[1]);
pthread_mutex_init (&foodlock, 0);
for (i = 0; i < 5; i++)
pthread_mutex_init (&forks[i], 0);
pthread_mutex_init(&getting_forks_mx, 0);
pthread_cond_init(&getting_forks_cond, 0);
for (i = 0; i < 5; i++)
pthread_create (&phils[i], 0, philosopher, (void *)i);
for (i = 0; i < 5; i++)
pthread_join (phils[i], 0);
return 0;
}
void *
philosopher (void *num)
{
int id;
int left_fork, right_fork, f;
id = (int)num;
printf ("Philosopher %d sitting down to dinner.\\n", id);
right_fork = id;
left_fork = id + 1;
if (left_fork == 5)
left_fork = 0;
while (f = food_on_table ()) {
printf ("Philosopher %d: get dish %d.\\n", id, f);
get_forks (id, right_fork, left_fork);
printf ("Philosopher %d: eating.\\n", id);
usleep (30000 * (50 - f + 1));
down_forks (left_fork, right_fork);
}
printf ("Philosopher %d is done eating.\\n", id);
return (0);
}
int
food_on_table ()
{
static int food = 50;
int myfood;
pthread_mutex_lock (&foodlock);
if (food > 0) {
food--;
}
myfood = food;
pthread_mutex_unlock (&foodlock);
return myfood;
}
void
get_forks (int phil,
int fork1,
int fork2)
{
int res;
pthread_mutex_lock(&getting_forks_mx);
do {
if (res=pthread_mutex_trylock(&forks[fork1])) {
res=pthread_mutex_trylock(&forks[fork2]);
if (res) pthread_mutex_unlock(&forks[fork1]);
}
if (res) pthread_cond_wait(&getting_forks_cond, &getting_forks_mx);
} while(res);
pthread_mutex_unlock(&getting_forks_mx);
}
void
down_forks (int f1,
int f2)
{
pthread_mutex_lock(&getting_forks_mx);
pthread_mutex_unlock (&forks[f1]);
pthread_mutex_unlock (&forks[f2]);
pthread_cond_broadcast(&getting_forks_cond);
pthread_mutex_unlock(&getting_forks_mx);
}
| 1
|
#include <pthread.h>
int sum = 0;
int arr[8][100];
pthread_mutex_t sum_mutex;
void* do_work(void* num)
{
int i, j, start, end;
int* int_num;
int local_sum = 0;
int_num = (int *) num;
start = *int_num * 8 / 4;
end = start + 8 / 4;
printf ("Thread %d summing arr[%d][%d] through arr[%d][%d]\\n", *int_num, start, 100, end-1, 100);
for (i = start; i < end; i++) {
for (j = 0; j < 100; j++) {
local_sum += arr[i][j];
}
}
pthread_mutex_lock (&sum_mutex);
sum = sum + local_sum;
pthread_mutex_unlock (&sum_mutex);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int i, j;
int start, thread_nums[4];
pthread_t threads[4];
pthread_attr_t attr;
for (i = 0; i < 8; i++) {
for (j = 0; j < 100; j++) {
arr[i][j] = i * 100 + j;
}
}
pthread_mutex_init(&sum_mutex, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (i = 0; i < 4; i++) {
thread_nums[i] = i;
pthread_create(&threads[i], &attr, do_work, (void *) &thread_nums[i]);
}
for (i = 0; i < 4; i++) {
pthread_join(threads[i], 0);
}
printf ("Threaded array sum = %d\\n", sum);
sum = 0;
for (i = 0; i < 8; i++) {
for (j = 0; j < 100; j++) {
sum += arr[i][j];
}
}
printf("Loop array sum = %d\\n", sum);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&sum_mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
struct clientinfo {
int s;
struct sockaddr_in sin;
};
struct line {
char *s;
int status;
struct line *next;
} *head, **ptail;
int n_sent = 0, n_received=0, n_flushed=0;
pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t clients_mutex = PTHREAD_MUTEX_INITIALIZER;
int n_clients = 0;
int s;
char * read_line(int fd);
void done (void);
struct line * queue_get() {
struct line *cur;
char *s;
pthread_mutex_lock(&queue_mutex);
for (cur = head; cur != 0; cur = cur->next) {
if (cur->status == 1) {
cur->status = 0;
pthread_mutex_unlock(&queue_mutex);
return cur;
}
}
s = read_line(0);
if (s) {
cur = malloc(sizeof (struct line));
cur->s = s;
cur->status = 0;
cur->next = 0;
*ptail = cur;
ptail = &cur->next;
n_sent++;
pthread_mutex_unlock(&queue_mutex);
return cur;
} else {
if (head == 0) {
fprintf(stderr, "Reached end of file. Exiting.\\n");
done();
} else
ptail = 0;
pthread_mutex_unlock(&queue_mutex);
return 0;
}
}
void queue_abort(struct line *node) {
pthread_mutex_lock(&queue_mutex);
node->status = 1;
pthread_mutex_unlock(&queue_mutex);
}
void queue_print() {
struct line *cur;
fprintf(stderr, "Queue\\n");
for (cur = head; cur != 0; cur = cur->next) {
switch(cur->status) {
case 0:
fprintf(stderr, "running "); break;
case 1:
fprintf(stderr, "aborted "); break;
case 2:
fprintf(stderr, "finished "); break;
}
fprintf(stderr, cur->s);
}
}
void queue_finish(struct line *node, char *s) {
struct line *next;
pthread_mutex_lock(&queue_mutex);
free(node->s);
node->s = s;
node->status = 2;
n_received++;
while (head && head->status == 2) {
fputs(head->s, stdout);
free(head->s);
next = head->next;
free(head);
head = next;
n_flushed++;
if (head == 0) {
if (ptail == 0) {
fprintf(stderr, "All sentences finished. Exiting.\\n");
done();
} else
ptail = &head;
}
}
fflush(stdout);
fprintf(stderr, "%d sentences sent, %d sentences finished, %d sentences flushed\\n", n_sent, n_received, n_flushed);
pthread_mutex_unlock(&queue_mutex);
}
char * read_line(int fd) {
int size = 80;
char *s = malloc(size+2);
int result, errors=0;
int i = 0;
result = read(fd, s+i, 1);
while (1) {
if (result < 0) {
perror("read()");
errors++;
if (errors > 5) {
free(s);
return 0;
} else {
sleep(1);
}
} else if (result == 0 || s[i] == '\\n') {
break;
} else {
i++;
if (i == size) {
size = size*2;
s = realloc(s, size+2);
}
}
result = read(fd, s+i, 1);
}
if (result == 0 && i == 0) {
free(s);
return 0;
}
s[i] = '\\n';
s[i+1] = '\\0';
return s;
}
void * new_client(void *arg) {
struct clientinfo *client = (struct clientinfo *)arg;
struct line *cur;
int len;
char *s;
int flags;
pthread_mutex_lock(&clients_mutex);
n_clients++;
pthread_mutex_unlock(&clients_mutex);
fprintf(stderr, "Client connected (%d connected)\\n", n_clients);
for (;;) {
cur = queue_get();
if (cur) {
fprintf(stderr, "Sending to client: %s", cur->s);
write(client->s, cur->s, strlen(cur->s));
} else {
close(client->s);
pthread_mutex_lock(&clients_mutex);
n_clients--;
pthread_mutex_unlock(&clients_mutex);
fprintf(stderr, "Client finished (%d connected)\\n", n_clients);
pthread_exit(0);
}
s = read_line(client->s);
if (s) {
fprintf(stderr, "Client returned: %s", s);
queue_finish(cur, s);
} else {
pthread_mutex_lock(&clients_mutex);
n_clients--;
pthread_mutex_unlock(&clients_mutex);
fprintf(stderr, "Client died (%d connected)\\n", n_clients);
queue_abort(cur);
close(client->s);
free(client);
pthread_exit(0);
}
}
}
void done (void) {
close(s);
exit(0);
}
int main (int argc, char *argv[]) {
struct sockaddr_in sin, from;
int g, len;
struct clientinfo *client;
int port;
int opt;
int errors = 0;
pthread_t tid;
if (argc >= 2)
port = atoi(argv[1]);
else
port = DEFAULT_PORT;
head = 0;
ptail = &head;
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
opt = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_port = htons(port);
while (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
perror("bind()");
sleep(1);
errors++;
if (errors > 100)
exit(1);
}
len = sizeof(sin);
getsockname(s, (struct sockaddr *) &sin, &len);
fprintf(stderr, "Listening on port %hd\\n", ntohs(sin.sin_port));
while (listen(s, 32) < 0) {
perror("listen()");
sleep(1);
errors++;
if (errors > 100)
exit(1);
}
for (;;) {
len = sizeof(from);
g = accept(s, (struct sockaddr *)&from, &len);
if (g < 0) {
perror("accept()");
sleep(1);
continue;
}
client = malloc(sizeof(struct clientinfo));
client->s = g;
bcopy(&from, &client->sin, len);
pthread_create(&tid, 0, new_client, client);
}
}
| 1
|
#include <pthread.h>
int thread_count;
double data[] = {1.3, 2.9, 0.4, 0.3, 1.3, 4.4, 1.7, 0.4, 3.2, 0.3,
4.9, 2.4, 3.1, 4.4, 3.9, 0.4, 4.2, 4.5, 4.9, 0.9};
int bin_count = 5;
int data_count, sum, local_d_count;
int *bin_counts, *local_bin_count;
double min_meas, max_meas, bin_width;
double *bin_maxes, *local_values;
pthread_mutex_t mutex;
int i;
void Usage(char* prog_name);
void *printData(void* rank);
int main (int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
if (argc != 2) Usage(argv[0]);
thread_count = atoi(argv[1]);
thread_handles = malloc(thread_count*sizeof(pthread_t));
data_count = sizeof(data)/sizeof(data[0]);
min_meas = data[0];
max_meas = data[0];
for(i=1;i<data_count;i++)
{
if(min_meas > data[i])
{
min_meas = data[i];
}
if(max_meas < data[i])
{
max_meas = data[i];
}
}
sum = min_meas+max_meas;
local_d_count = data_count/thread_count;
bin_width = (max_meas - min_meas)/bin_count;
bin_counts = malloc(bin_count*sizeof(int));
bin_maxes = malloc(bin_count*sizeof(double));
local_bin_count = malloc(bin_count*sizeof(int));
for (i=0;i<bin_count;i++)
{
bin_maxes[i] = min_meas+(bin_width*(i+1));
bin_counts[i] = 0;
local_bin_count[i] = 0;
}
local_values = malloc(local_d_count*sizeof(double));
printf("min_meas: %lf\\n", min_meas);
printf("max_meas: %lf\\n", max_meas);
printf("bin_width: %lf\\n", bin_width);
printf("local_d_count: %d\\n", local_d_count);
for (thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread], 0,
printData, (void*) thread);
for (thread = 0; thread < thread_count; thread++)
pthread_join(thread_handles[thread], 0);
printf("------------------------\\n");
for (i = 0; i < bin_count; i++) {
printf("bin_maxes: %lf\\n", bin_maxes[i]);
printf("bin count: %d\\n", bin_counts[i]);
printf("------------------------\\n");
}
free(local_values);
free(bin_counts);
free(bin_maxes);
return 0;
}
void Usage (char* prog_name) {
fprintf(stderr, "usage: %s <thread_count>\\n", prog_name);
exit(0);
}
void *printData(void* rank) {
long my_rank = (long) rank;
int local_data_count = data_count / (int) thread_count;
int first_thread = my_rank * local_data_count;
int last_thread = (my_rank + 1) * local_data_count - 1;
double* local_data = malloc(local_data_count*sizeof(double));
printf("TESTING");
int j = 0;
for (i = first_thread; i <= last_thread; i++, j++) {
local_data[j] = data[i];
}
for (j = 0; j < local_data_count; j++) {
printf("%lf from rank: %ld\\n", local_data[j], my_rank);
}
for (i = 0; i < local_data_count; i++) {
for (j = 0; j < bin_count; j++) {
if (local_data[i] <= bin_maxes[j])
{
pthread_mutex_lock(&mutex);
bin_counts[j]++;
pthread_mutex_unlock(&mutex);
break;
}
}
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t resource1;
pthread_mutex_t resource2;
void *threadOne(void *args)
{
pthread_mutex_lock(&resource1);
pthread_mutex_lock(&resource2);
printf("Thread 1 has both resources, and is running!\\n");
pthread_mutex_unlock(&resource2);
pthread_mutex_unlock(&resource1);
printf("Thread 1 is done!\\n");
pthread_exit(0);
return 0;
}
void *threadTwo(void *args)
{
pthread_mutex_lock(&resource2);
pthread_mutex_lock(&resource1);
printf("Thread 2 has both resources, and is running!\\n");
pthread_mutex_unlock(&resource1);
pthread_mutex_unlock(&resource2);
printf("Thread 2 is done!\\n");
pthread_exit(0);
return 0;
}
int main()
{
int n = 0;
pthread_t tidOne;
pthread_t tidTwo;
while (n < 1000)
{
pthread_create(&tidOne, 0, &threadOne, 0);
pthread_create(&tidTwo, 0, &threadTwo, 0);
n++;
}
pthread_join(tidOne, 0);
pthread_join(tidTwo, 0);
}
| 1
|
#include <pthread.h>
{
int stock;
pthread_t thread_store;
pthread_t thread_clients[5];
pthread_mutex_t mutex_stock;
pthread_cond_t cond_stock;
pthread_cond_t cond_clients;
}
store_t;
static store_t store =
{
.stock = 20,
.mutex_stock = PTHREAD_MUTEX_INITIALIZER,
.cond_stock = PTHREAD_COND_INITIALIZER,
.cond_clients = PTHREAD_COND_INITIALIZER,
};
static int get_random(int max)
{
double val;
val = (double) max * rand();
val = val / (32767 + 1.0);
return ((int) val);
}
static void *fn_store (void *p_data)
{
while (1)
{
pthread_mutex_lock(&store.mutex_stock);
pthread_cond_wait(&store.cond_stock, &store.mutex_stock);
store.stock = 20;
printf("Remplissage du stock de %d articles !\\n", store.stock);
pthread_cond_signal(&store.cond_clients);
pthread_mutex_unlock(&store.mutex_stock);
}
return 0;
}
static void *fn_clients(void *p_data)
{
int nb = (int)p_data;
while (1)
{
int val = get_random(6);
sleep((get_random(3)));
pthread_mutex_lock(&store.mutex_stock);
if (val > store.stock)
{
pthread_cond_signal(&store.cond_stock);
pthread_cond_wait(&store.cond_clients, &store.mutex_stock);
}
store.stock = store.stock - val;
printf("Client %d prend %d du stock, reste, %d en stock!\\n",
nb, val, store.stock);
pthread_mutex_unlock(&store.mutex_stock);
}
return 0;
}
int main (void)
{
int i = 0;
int ret = 0;
printf("Creation du thread magasin!\\n");
ret = pthread_create(&store.thread_store, 0, fn_store, 0);
if (!ret)
{
printf("Creation des threads clients !\\n");
for (i = 0; i < 5; i++)
{
ret = pthread_create(&store.thread_clients[i], 0, fn_clients, (void *)i);
if (ret)
fprintf(stderr, "%s", strerror(ret));
}
}
else
fprintf(stderr, "%s", strerror(ret));
i = 0;
for (i = 0; i < 5; i++)
pthread_join(store.thread_clients[i], 0);
pthread_join(store.thread_store, 0);
return (0);
}
| 0
|
#include <pthread.h>
int stoj = 0;
int pocet_chlebov;
int pocet_pekarov = 0;
pthread_mutex_t mutex_pocet_chlebov = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_pocitadlo_pekarov = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_turniket = PTHREAD_MUTEX_INITIALIZER;
sem_t sem_pece;
sem_t sem_pekari;
void priprava(int id) {
printf("Pekar %d pripravuje chleba\\n", id);
sleep(4);
}
void pecenie(int id) {
printf("Pekar %d pecie chleba\\n", id);
sem_wait(&sem_pece);
sleep(2);
sem_post(&sem_pece);
pthread_mutex_lock(&mutex_pocet_chlebov);
pocet_chlebov++;
pthread_mutex_unlock(&mutex_pocet_chlebov);
}
void prestavka(int id) {
printf("Pekar %d prestávkuje\\n", id);
sleep(4);
}
void *pekar( void *ptr ) {
int id = (long) ptr;
int pocet_chlebov = 0;
int i;
while(!stoj) {
priprava(id);
if(stoj) break;
pecenie(id);
if(stoj) break;
pocet_chlebov++;
if(pocet_chlebov % 2 == 0) {
pthread_mutex_lock(&mutex_pocitadlo_pekarov);
printf("%d ide na prestavku\\n", id);
if(stoj) break;
if(pocet_pekarov == (10 - 1)) {
pocet_pekarov = 0;
printf("%d je posledny\\n", id);
for(i=0;i<(10 -1);i++) {
sem_post(&sem_pekari);
pthread_mutex_lock(&mutex_turniket);
}
pthread_mutex_unlock(&mutex_pocitadlo_pekarov);
} else {
printf("%d ide cakat na posledného\\n", id);
pocet_pekarov++;
pthread_mutex_unlock(&mutex_pocitadlo_pekarov);
sem_wait(&sem_pekari);
pthread_mutex_unlock(&mutex_turniket);
}
if(stoj)break;
prestavka(id);
}
}
return 0;
}
int main(void) {
long i;
pthread_t pekari[10];
sem_init(&sem_pece, 0, 4);
sem_init(&sem_pekari, 0, 0);
for (i=0;i<10;i++) pthread_create( &pekari[i], 0, &pekar, (void*)i);
sleep(30);
stoj = 1;
for (i=0;i<10;i++) pthread_join( pekari[i], 0);
printf("Upieklo sa %d chlebov\\n", pocet_chlebov);
exit(0);
}
| 1
|
#include <pthread.h>
struct Data *table[ 29 ];
pthread_mutex_t tablelock = PTHREAD_MUTEX_INITIALIZER;
struct Data {
int count;
pthread_mutex_t lock;
struct Data *next;
int id;
int number;
};
struct Data *data_alloc( void ) {
struct Data *data;
int index;
if ( (data = malloc( sizeof( struct Data ) )) != 0 ) {
data->count = 1;
if ( pthread_mutex_init( &data->lock, 0 ) != 0 ) {
free( data );
return 0;
}
index = ( ((unsigned long) data) % 29 );
pthread_mutex_lock( &tablelock );
data->next = table[ index ];
table[ index ] = data->next;
pthread_mutex_lock( &data->lock );
pthread_mutex_unlock( &tablelock );
data->number = -9999;
pthread_mutex_unlock( data->lock );
}
return data;
}
void data_hold( struct Data *data ) {
pthread_mutex_lock( &data->lock );
data->count++;
pthread_mtex_unlock( &data->lock );
}
struct Data *data_find( int id ) {
struct Data *data;
int index = ( ((unsigned long) data) % 29 );
pthread_mutex_lock( &tablelock );
for ( data = table[index]; data != 0; data = data->next ) {
if ( data->id == id ) {
data_hold( data );
break;
}
}
pthread_mutex_unlock( &tablelock );
return data;
}
void data_release( struct Data *data ) {
struct Data *tmp;
int index;
pthread_mutex_lock( &data->lock );
if ( data->count == 1 ) {
pthread_mutex_unlock( &data->lock );
pthread_mutex_lock( &tablelock );
pthread_mutex_lock( &data->lock );
if ( data->count != 1 ) {
data->count--;
pthread_mutex_unlock( &data->lock );
pthread_mutex_unlock( &tablelock );
return;
}
index = ( ((unsigned long) data) % 29 );
tmp = table[ index ];
if ( tmp == data ) {
table[ index ] = data->next;
} else {
while ( tmp->next != data ) {
tmp = data->next;
}
tmp->next = data->next;
}
pthread_mutex_unlock( &tablelock );
pthread_mutex_unlock( &data->lock );
pthread_mutex_destroy( &data->lock );
free( data );
} else {
data->count--;
pthread_mutex_unlock( &data->lock );
}
}
void *thread_run( void *arg ) {
return (void *) 0;
}
void *thread2_run( void *arg ) {
return (void *) 0;
}
int main( int argc, char **argv ) {
pthread_t tid, tid2;
int err;
if ( (err = pthread_create( &tid, 0, thread_run, 0 )) != 0 ) {
err_quit( "error on creating first thread: %s\\n", strerror( err ) );
}
if ( (err = pthread_create( &tid2, 0, thread2_run, 0 )) != 0 ) {
err_quit( "error on creating second thread: %s\\n", strerror( err ) );
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
int* vet;
} Vector;
Vector V;
int t;
void merge(int *vet, int left, int middle, int right);
void* threadedMergeSort(int* args);
int main(int argc, char** argv) {
int i, n;
int args[2];
if (argc != 3) {
fprintf (stderr, "Wrong number of arguments. Syntax: %s dimension threshold\\n", argv[0]);
return -1;
}
n = atoi(argv[1]);
t = atoi(argv[2]);
V.vet = (int*)malloc(n*sizeof(int));
pthread_mutex_init(&V.mutex, 0);
srand(n);
fprintf(stdout, "Array before sorting: ");
pthread_mutex_lock(&V.mutex);
for(i = 0; i < n; i++) {
V.vet[i] = rand() % 100;
fprintf(stdout, "%d ", V.vet[i]);
}
pthread_mutex_unlock(&V.mutex);
fprintf(stdout, "\\n");
args[0] = 0;
args[1] = n-1;
threadedMergeSort(args);
fprintf(stdout, "Array after sorting: ");
pthread_mutex_lock(&V.mutex);
for(i = 0; i < n; i++) {
fprintf(stdout, "%d ", V.vet[i]);
}
pthread_mutex_unlock(&V.mutex);
fprintf(stdout, "\\n");
return 0;
}
void* threadedMergeSort(int* args) {
int* arg = args;
int left, middle, right;
int argsA[2], argsB[2];
pthread_t threadA, threadB;
void* retValue;
left = arg[0];
right = arg[1];
if (left < right) {
middle = left + (right - left)/2;
if ((right - left) >= t) {
argsA[0] = left;
argsA[1] = middle;
pthread_create(&threadA, 0, (void*)threadedMergeSort, (void*)argsA);
argsB[0] = middle + 1;
argsB[1] = right;
pthread_create(&threadB, 0, (void*)threadedMergeSort, (void*)argsB);
pthread_join(threadA, &retValue);
pthread_join(threadB, &retValue);
} else {
argsA[0] = left;
argsA[1] = middle;
argsB[0] = middle + 1;
argsB[1] = right;
threadedMergeSort(argsA);
threadedMergeSort(argsB);
}
pthread_mutex_lock(&V.mutex);
merge(V.vet, left, middle, right);
pthread_mutex_unlock(&V.mutex);
}
return (void*)0;
}
void merge(int *vet, int left, int middle, int right) {
int i, j, k;
int n1 = middle - left + 1;
int n2 = right - middle;
int L[n1], R[n2];
for (i = 0; i <= n1; i++) {
L[i] = vet[left + i];
}
for (j = 0; j <= n2; j++) {
R[j] = vet[middle + 1 + j];
}
i = 0;
j = 0;
k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
vet[k++] = L[i++];
} else {
vet[k++] = R[j++];
}
}
while (i < n1) {
vet[k++] = L[i++];
}
while (j < n2) {
vet[k++] = R[j++];
}
return;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex [4];
pthread_cond_t cond [4];
int flag[4];
void *thread_cond(void *args) {
int id = (*(int *)args);
free(args);
if (id != 0)
{
pthread_mutex_lock(&mutex[id]);
if (!flag[id])
{
pthread_cond_wait(&cond[id], &mutex[id]);
}
pthread_mutex_unlock(&mutex[id]);
}
printf ("Thread :%d\\n",id);
if (id!=4 -1)
{
pthread_mutex_lock(&mutex[(id+1)]);
flag[(id+1)]=1;
pthread_cond_signal(&cond[(id+1)]);
pthread_mutex_unlock(&mutex[(id+1)]);
}
return 0;
}
int main(void)
{
int i;
pthread_t threads[4];
int *targ;
for(i=0; i<4; i++)
{
pthread_mutex_init(&mutex[i], 0);
pthread_cond_init(&cond[i],0);
flag[i]=0;
targ = malloc(sizeof(int));
*targ = i;
pthread_create(&threads[i], 0, thread_cond, targ);
}
for(i=0; i<4; i++)
{
pthread_join(threads[i], 0);
}
return 0;
}
| 0
|
#include <pthread.h>
void * Lector(void * p);
void * Escritor(void * p);
int dato=5;
pthread_mutex_t mutex;
pthread_cond_t leer,escribir;
int leyendo=0,escribiendo=0;
int main()
{
pthread_t l1,l2,e1,e2;
int i;
pthread_mutex_init(&mutex,0);
pthread_cond_init(&leer,0);
pthread_cond_init(&escribir,0);
srand(time(0));
pthread_create(&e1,0,Escritor,(void *)1);
pthread_create(&e2,0,Escritor,(void *)2);
pthread_create(&l1,0,Lector,(void *)1);
pthread_create(&l2,0,Lector,(void *)2);
pthread_join(l1,0);
pthread_join(l2,0);
pthread_join(e1,0);
pthread_join(e2,0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&leer);
pthread_cond_destroy(&escribir);
}
void * Lector(void *p)
{
int i;
i=(int)p;
while(1)
{
pthread_mutex_lock(&mutex);
if(escribiendo)
pthread_cond_wait(&leer,&mutex);
leyendo++;
pthread_mutex_unlock(&mutex);
printf("Soy el lector %d y leo el dato %d\\n", i, dato);
sleep(1);
pthread_mutex_lock(&mutex);
leyendo--;
if(!leyendo)
pthread_cond_signal(&escribir);
pthread_mutex_unlock(&mutex);
sleep(rand()%5);
}
}
void * Escritor(void * p)
{
int i;
i=(int)p;
while(1)
{
pthread_mutex_lock(&mutex);
while(leyendo||escribiendo)
pthread_cond_wait(&escribir,&mutex);
escribiendo++;
pthread_mutex_unlock(&mutex);
sleep(1);
dato+=2;
printf("Soy el escritor %d y he modificado el valor a %d\\n", i,dato);
pthread_mutex_lock(&mutex);
escribiendo--;
pthread_cond_broadcast(&escribir);
pthread_cond_broadcast(&leer);
pthread_mutex_unlock(&mutex);
sleep(rand()%5);
}
}
| 1
|
#include <pthread.h>
extern char **environ;
pthread_mutex_t env_mutex;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
static void thread_init(void)
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&env_mutex,&attr);
pthread_mutexattr_destroy(&attr);
}
int getenv_r(const char *name, char *buf, int buflen)
{
int i, len, olen;
pthread_once(&init_done, thread_init);
len = strlen(name);
pthread_mutex_lock(&env_mutex);
for (i=0; environ[i] != 0; i++)
{
if ((strncmp(name ,environ[i], len) == 0) && (environ[i][len]=='='))
{
olen = strlen(&environ[i][len+1]);
if (olen >=buflen)
{
pthread_mutex_unlock(&env_mutex);
return (ENOSPC);
}
strcpy(buf, &environ[i][len+1]);
pthread_mutex_unlock(&env_mutex);
return (0);
}
}
pthread_mutex_unlock(&env_mutex);
return (ENOENT);
}
| 0
|
#include <pthread.h>
pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t stats_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_rider = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_driver = PTHREAD_COND_INITIALIZER;
const int MAX_SLEEP = 40 / 2;
int riderQ[( (5/2) + 1 )];
int rider_processed[5];
int qSize = 0;
int first = 0;
int last = 0;
int totalRidersServed = 0;
void *Cliente();
void *Manejador();
int main()
{
printf( "==========================================");
printf("\\n PMServices ");
printf("\\n ___________ By ");
printf("\\n // ||| \\\\\\\\ Prasamsha Pradhan ");
printf("\\n __//____|||____\\\\\\\\____ Christian Moreano ");
printf("\\n| _| | _ || ");
printf("\\n|/ \\\\______|______/ \\\\_|| ");
printf("\\n_\\\\_/_____________\\\\_/_____\\n");
printf( "==========================================\\n");
printf("Riders(N)= %d ,Drivers(M)= %d ,Time(S)= %d\\n\\n", 5 , 1 ,40);
srand( time( 0 ) );
pthread_t riders[5];
pthread_t drivers[1];
int i = 0;
for( i = 0; i < 40; ++i )
{
riderQ[i] = 0;
}
int rider_id[5];
int driver_id[1];
for( i = 0; i < 5; ++i )
{
rider_processed[i] = 0;
rider_id[i] = i + 1;
pthread_create( &riders[i], 0, Cliente, rider_id + i );
}
for( i = 0; i < 1; ++i )
{
driver_id[i] = i + 5 + 1;
pthread_create( &drivers[i], 0, Manejador, driver_id + i );
}
sleep( 40 );
pthread_mutex_lock( &queue_mutex );
sleep( 1 );
printf( "========================================================");
printf( "\\nTotal number of Riders served: %i\\n", totalRidersServed );
printf( "Total number of Riders remains in the wait queue: %i\\n", qSize );
printf( "Average number of Riders each Driver served: %f\\n",
(float)totalRidersServed / 1 );
printf( "========================================================\\n");
return 0;
}
void *Cliente( void* dummy )
{
int* id_ptr = (int *) dummy;
int id = *id_ptr;
srand( time( 0 ) * id );
sleep( rand() % MAX_SLEEP );
for( ; ; )
{
if( rider_processed[id - 1] == 1 )
sleep( 1 );
else if( rider_processed[id - 1] == 2 )
{
rider_processed[id - 1] = 0;
printf( "Rider %i: completed riding. Queue size: %i.\\n",
id, qSize );
srand( time( 0 ) * id );
sleep( ( rand() % MAX_SLEEP ) + 1 );
}
if( rider_processed[id - 1] != 0 )
continue;
pthread_mutex_lock( &queue_mutex );
while( qSize == ( (5/2) + 1 ) )
pthread_cond_wait( &cond_rider, &queue_mutex );
riderQ[first] = id;
rider_processed[id - 1] = 1;
first = ( first + 1 ) % ( (5/2) + 1 );
++qSize;
printf( "Rider %i: arrived. Queue size: %i.\\n", id, qSize );
pthread_cond_signal( &cond_driver );
pthread_mutex_unlock( &queue_mutex );
}
pthread_exit( 0 );
}
void *Manejador( void* dummy )
{
int* id_ptr = (int *) dummy;
int id = *id_ptr;
srand( time( 0 ) * id );
sleep( rand() % MAX_SLEEP );
for( ; ; )
{
pthread_mutex_lock( &queue_mutex );
printf( "Driver %i: arrived. Queue size: %i.\\n", id, qSize );
while( qSize == 0 )
pthread_cond_wait( &cond_driver, &queue_mutex );
rider_processed[ riderQ[last] - 1 ] = 2;
riderQ[last] = 0;
last = ( last + 1 ) % ( (5/2) + 1 );
--qSize;
++totalRidersServed;
printf( "Driver %i: riding. Queue size: %i.\\n", id, qSize );
pthread_cond_signal( &cond_rider );
pthread_mutex_unlock( &queue_mutex );
srand( time( 0 ) * id );
sleep( ( rand() % MAX_SLEEP ) + 1 );
}
pthread_exit( 0 );
}
| 1
|
#include <pthread.h>
void *static_guard_page;
void static_fixup_init(void)
{
static_guard_page = alloc_guard_page(1);
if (!static_guard_page)
abort();
}
static int
add_static_fixup_site(enum static_fixup_type type, struct insn *insn,
struct vm_field *vmf, struct compilation_unit *cu)
{
struct vm_class *vmc;
struct static_fixup_site *site;
vmc = vmf->class;
site = malloc(sizeof *site);
if (!site)
return -ENOMEM;
site->type = type;
site->insn = insn;
site->vmf = vmf;
site->cu = cu;
pthread_mutex_lock(&vmc->mutex);
list_add_tail(&site->vmc_node, &vmc->static_fixup_site_list);
pthread_mutex_unlock(&vmc->mutex);
list_add_tail(&site->cu_node, &cu->static_fixup_site_list);
return 0;
}
int add_getstatic_fixup_site(struct insn *insn,
struct vm_field *vmf, struct compilation_unit *cu)
{
return add_static_fixup_site(STATIC_FIXUP_GETSTATIC, insn, vmf, cu);
}
int add_putstatic_fixup_site(struct insn *insn,
struct vm_field *vmf, struct compilation_unit *cu)
{
return add_static_fixup_site(STATIC_FIXUP_PUTSTATIC, insn, vmf, cu);
}
unsigned long static_field_signal_bh(unsigned long ret)
{
if (fixup_static_at(ret))
return throw_from_signal_bh(ret);
return ret;
}
| 0
|
#include <pthread.h>
char buf[128];
int wpos;
int rpos;
pthread_cond_t cv;
pthread_mutex_t mtx;
void * printer(void * data){
pthread_cond_wait(&cv,&mtx);
while (1){
write(1,buf+wpos+1,buf[wpos]);
wpos += 16;
wpos %= 128;
pthread_cond_wait(&cv,&mtx);
}
}
void * reader(void * data){
struct addrinfo hints;
memset(&hints,0,sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
hints.ai_protocol = 0;
int res;
struct addrinfo * addrinfo;
res = getaddrinfo(0,"8888",&hints,&addrinfo);
if (res){
printf("Error when resolving: %s\\n",gai_strerror(res));
return 0;
}
int listenfd = -1;
while (addrinfo != 0){
listenfd = socket(addrinfo->ai_family,
addrinfo->ai_socktype,
addrinfo->ai_protocol);
if (listenfd == -1)
continue;
if (bind(listenfd,addrinfo->ai_addr,addrinfo->ai_addrlen) == 0)
break;
close(listenfd);
listenfd = -1;
addrinfo = addrinfo->ai_next;
}
if (listenfd == -1){
printf("Bind failed\\n");
return 0;
}
freeaddrinfo(addrinfo);
int readfd;
if (listen(listenfd,1)==-1){
printf("Listen failed\\n");
return 0;
}
readfd = accept(listenfd,0,0);
if (readfd == -1)
return 0;
int len;
char tmp[16];
while ((len = read(readfd,tmp,15))){
char chlen;
chlen = len;
pthread_mutex_lock(&mtx);
buf[rpos]=chlen;
memcpy(buf+rpos+1,tmp,len);
rpos+=16;
rpos%=128;
pthread_cond_signal(&cv);
pthread_mutex_unlock(&mtx);
}
close(readfd);
close(listenfd);
return 0;
}
int main (int argc, char ** argv){
pthread_mutex_init(&mtx,0);
pthread_cond_init(&cv,0);
wpos = 0;
rpos = 0;
pthread_t read_thr;
pthread_t print_thr;
pthread_create(&read_thr,0,reader,0);
pthread_create(&print_thr,0,printer,0);
pthread_join(read_thr,0);
pthread_cancel(print_thr);
return 0;
}
| 1
|
#include <pthread.h>
pthread_t ledThread;
pthread_mutex_t ledStatusChange;
void *ledHandler(void*);
int main()
{
short status=PASS;
ioperm(0x80,2,1);
int ledStatus=0x00;
unsigned int i=0;
ledStatus = 0x0F;
pthread_mutex_init (&ledStatusChange, 0);
if (pthread_create (&ledThread, 0, ledHandler,&ledStatus))
{
status = FAIL;
goto finishTest;
}
if (askYesNoQuestion("Are all Post LEDs green?") == NO)
{
status=FAIL;
goto finishTest;
}
pthread_mutex_lock(&ledStatusChange);
ledStatus = 0xF0;
pthread_mutex_unlock(&ledStatusChange);
if (askYesNoQuestion("Are all Post LEDs red?") == NO)
{
status=FAIL;
goto finishTest;
}
pthread_mutex_lock(&ledStatusChange);
ledStatus = 0xFF;
pthread_mutex_unlock(&ledStatusChange);
if (askYesNoQuestion("Are all Post LEDs yellow?") == NO)
{
status=FAIL;
}
ledStatus = 0x00;
finishTest:
testPrint("Post Code LED Test");
if (status==FAIL)
failedMessage();
else
passedMessage();
}
void *ledHandler(void *var)
{
while(*(int*)var != 0x00)
{
pthread_mutex_lock(&ledStatusChange);
outw(*(int*)var,0x80);
pthread_mutex_unlock(&ledStatusChange);
}
}
| 0
|
#include <pthread.h>
void *worker(){
int workNum;
int readnum, i;
int newsock;
int connectionsNum = 0;
int state, end, choice;
double t2;
struct timeval tim;
FILE *fd;
vote *v;
pthread_mutex_lock (& worker_id);
workNum = workerNumber;
workerNumber += 1;
pthread_mutex_unlock (& worker_id);
v = malloc(sizeof(vote));
printf ("I am the newly created thread %ld with id %d\\n", pthread_self (), workNum);
while(1) {
while ( pool.count > 0) {
connectionsNum += 1;
newsock = obtain (& pool );
pthread_cond_signal (& cond_nonfull );
usleep (500000) ;
pthread_mutex_lock (& stat_file );
fd = fopen(info.poll_log_dat, "r+");
if (fd == 0) {
errors(newsock, "Error while openning file to insert statistics!");
exit(1);
}
fseek(fd, 0, 2);
gettimeofday(&tim, 0);
t2=tim.tv_sec+(tim.tv_usec/1000000.0);
fprintf(fd, "Stat-req-arrival: %.6lf\\nStat-req-dispatch: %.6lf\\nStat-thread-id: %d\\nStat-thread-count: %d\\n\\n\\n", master_time, t2 - master_time, workNum, connectionsNum);
fclose(fd);
pthread_mutex_unlock (& stat_file );
state = STATE_INITIAL;
end = FALSE;
for (;;) {
switch(state) {
case STATE_INITIAL:
choice = init_state(newsock);
switch(choice) {
case VOTE_BEGIN:
readnum = CRED_REQUESTS;
if( write(newsock, &readnum, sizeof(int) ) < 0)
{
errors(newsock, "server_write");
exit(1);
}
state = STATE_VOTE_CREDENTIALS;
break;
case POLL_RESULTS:
readnum = CRED_REQUESTS;
if( write(newsock, &readnum, sizeof(int) ) < 0)
{
errors(newsock, "server_write");
exit(1);
}
state = STATE_RESULTS_CREDENTIALS;
break;
case QUIT:
state = QUIT;
break;
default:
state = QUIT;
break;
}
break;
case STATE_VOTE_CREDENTIALS:
state = vote_cred(newsock, v);
break;
case STATE_RESULTS_CREDENTIALS:
results_server(newsock);
state = STATE_INITIAL;
break;
case STATE_VOTE_SELECTION:
vote_selection(newsock, v);
state = STATE_INITIAL;
break;
case QUIT:
readnum = QUIT;
end = TRUE;
break;
}
if (end == TRUE) {
if( write(newsock, &readnum, sizeof(int) ) < 0)
{
errors(newsock, "server_write");
exit(1);
}
break;
}
}
close(newsock);
}
if (exitc == 1)
break;
}
free(v);
pthread_exit (0) ;
}
| 1
|
#include <pthread.h>
pthread_mutex_t count_mutex;
pthread_mutex_t stop_mutex;
pthread_cond_t count_empty_cond;
pthread_cond_t count_full_cond;
int count=0;
int iteration=0;
enum THREAD_ENUM{
FILL_THREAD=0,
EMPTY_THREAD=1,
ALL_THREADS
};
char THREAD_NAMES[ALL_THREADS][64]={
"FILL",
"EMPTY"
};
void *fillCount(void *id)
{
long thread_id = (long)id;
while(1){
printf("%s::%d thread %ld, count: %d\\n", __FUNCTION__, 41, thread_id, count);
pthread_mutex_lock(&count_mutex);
while(0 != count){
printf("%s::%d thread %ld count: %d, wait buffer empty\\n", __FUNCTION__, 45, thread_id, count);
pthread_cond_wait(&count_empty_cond, &count_mutex);
printf("%s::%d thread %ld count: %d, receive empty signal\\n", __FUNCTION__, 47, thread_id, count);
}
while(20 > count){
count++;
printf("%s::%d thread %ld fill count: %d\\n", __FUNCTION__, 52, thread_id, count);
}
printf("%s::%d thread %ld count: %d, count filled\\n", __FUNCTION__, 55, thread_id, count);
pthread_cond_signal(&count_full_cond);
printf("%s::%d thread %ld count: %d, signaled full\\n", __FUNCTION__, 57, thread_id, count);
pthread_mutex_unlock(&count_mutex);
pthread_mutex_lock(&stop_mutex);
iteration++;
if(iteration > 45){
pthread_mutex_unlock(&stop_mutex);
pthread_exit(0);
}
pthread_mutex_unlock(&stop_mutex);
}
printf("%s::%d thread %ld count: %d, going to exit thread\\n", __FUNCTION__, 69, thread_id, count);
pthread_exit(0);
}
void *emptyCount(void *id)
{
long thread_id = (long)id;
while(1){
printf("%s::%d thread %ld, count: %d\\n", __FUNCTION__, 79, thread_id, count);
pthread_mutex_lock(&count_mutex);
while(20 != count){
printf("%s::%d thread %ld count: %d, wait buffer filled\\n", __FUNCTION__, 83, thread_id, count);
pthread_cond_wait(&count_full_cond, &count_mutex);
printf("%s::%d thread %ld count: %d, receive full signal\\n", __FUNCTION__, 85, thread_id, count);
}
while( 0 != count){
count--;
printf("%s::%d thread %ld empty count: %d\\n", __FUNCTION__, 90, thread_id, count);
}
printf("%s::%d thread %ld count: %d, count emptyed\\n", __FUNCTION__, 93, thread_id, count);
pthread_cond_signal(&count_empty_cond);
printf("%s::%d thread %ld count: %d, signaled empty\\n", __FUNCTION__, 95, thread_id, count);
pthread_mutex_unlock(&count_mutex);
pthread_mutex_lock(&stop_mutex);
iteration++;
if(iteration > 45){
pthread_mutex_unlock(&stop_mutex);
pthread_exit(0);
}
pthread_mutex_unlock(&stop_mutex);
}
printf("%s::%d thread %ld count: %d, going to exit thread\\n", __FUNCTION__, 107, thread_id, count);
pthread_exit(0);
}
int main(int argc, char *argv[]){
long t1=1, t2=2;
pthread_t fillThread, emptyThread;
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init(&count_empty_cond, 0);
pthread_cond_init(&count_full_cond, 0);
pthread_attr_init(&attr);
pthread_create(&fillThread, &attr, fillCount, (void *)t1);
pthread_create(&emptyThread, &attr, emptyCount, (void *)t2);
pthread_join(fillThread, 0);
pthread_join(emptyThread, 0);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_empty_cond);
pthread_cond_destroy(&count_full_cond);
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
void *sum(void *p);
unsigned long int psum[8][8];
unsigned long int sumtotal = 0;
unsigned long int n;
int numthreads;
pthread_mutex_t mutex;
int main(int argc, char **argv) {
pthread_t tid[8];
int i, myid[8];
struct timeval start, end;
gettimeofday(&start, 0);
scanf("%lu %d", &n, &numthreads);
for (i = 0; i < numthreads; i++) {
myid[i] = i;
psum[i][0] = 0;
pthread_create(&tid[i], 0, sum, &myid[i]);
}
for (i = 0; i < numthreads; i++) {
pthread_join(tid[i], 0);
}
pthread_mutex_destroy(&mutex);
gettimeofday(&end, 0);
long spent = (end.tv_sec * 1000000 + end.tv_usec)
- (start.tv_sec * 1000000 + start.tv_usec);
printf("%lu\\n%ld\\n", sumtotal, spent);
return 0;
}
void *sum(void *p) {
int myid = *((int *) p);
unsigned long int start = (myid * (unsigned long int) n) / numthreads;
unsigned long int end = ((myid + 1) * (unsigned long int) n) / numthreads;
unsigned long int i;
psum[myid][0] = 0;
for (i = start; i < end; i++) {
psum[myid][0] += 2;
}
pthread_mutex_lock(&mutex);
sumtotal += psum[myid][0];
pthread_mutex_unlock(&mutex);
return 0 ;
}
| 1
|
#include <pthread.h>
int size;
int used;
struct __node_t *next;
} node_t;
struct __list_t {
struct __node_t *head;
pthread_mutex_t lock;
} list_t;
struct __list_t *L;
void *heap_start;
int heap_end;
int mymalloc_init() {
L = sbrk(4096);
if (L == (void *) -1) {
return 1;
}
L->head = (node_t *)(L + 1);
L->head->size = 4096 - sizeof(node_t) - sizeof(list_t);
L->head->next = 0;
L->head->used = 0;
heap_start = L->head;
heap_end = 4096 - sizeof(node_t);
return 0;
}
node_t * get_last_node() {
node_t * cur = L->head;
while (cur->next) {
cur = cur -> next;
}
return cur;
}
void *mymalloc(unsigned int size) {
if (size == 0){
size = 8;
}
else{
if(size%8 != 0){
size = size + 8 - (size%8);
}
}
pthread_mutex_lock(&L->lock);
if (L->head->size >= size + sizeof(node_t)) {
int keepsize = L->head->size;
node_t * ret_val = L->head;
ret_val->used = 1;
ret_val->size = size;
L->head = (node_t *)((char *)L->head + size + sizeof(node_t));
L->head->size = keepsize - size - sizeof(node_t);
pthread_mutex_unlock(&L->lock);
return ret_val + 1;
}
else {
node_t * prev = L->head;
while (prev->next && prev->next->size < size + sizeof(node_t)) {
prev = prev->next;
}
if (prev->next) {
int keepsize = prev->next->size;
node_t * ret_val = prev->next;
ret_val->used = 1;
ret_val->size = size;
node_t * save = prev->next->next;
prev->next = (node_t *)((char *)ret_val + size + sizeof(node_t));
prev->next->size = keepsize - size - sizeof(node_t);
prev->next->next = save;
pthread_mutex_unlock(&L->lock);
return ret_val + 1;
}
}
sbrk(4096);
node_t * last = get_last_node();
last->size = last->size + 4096;
heap_end = heap_end + 4096;
pthread_mutex_unlock(&L->lock);
return mymalloc(size);
}
void coalesce(node_t * cur) {
if (cur->next){
if ((node_t *)((char *)cur + cur->size + sizeof(node_t)) == cur->next) {
cur->size += cur->next->size + sizeof(node_t);
cur->next = cur->next->next;
}
}
}
unsigned int myfree(void *ptr) {
pthread_mutex_lock(&L->lock);
if (ptr < heap_start || ptr > (void *)((char *)heap_start + heap_end)) {
pthread_mutex_unlock(&L->lock);
return 1;
}
ptr = ptr - sizeof(node_t);
node_t * temp = (node_t *)ptr;
if (temp->used != 1) {
pthread_mutex_unlock(&L->lock);
return 1;
}
temp->used = 0;
if (temp < L->head) {
temp->next = L->head;
L->head = temp;
}
else{
node_t * prev = L->head;
while (prev->next && prev->next < temp){
prev = prev->next;
}
temp->next = prev->next;
prev->next = temp;
}
pthread_mutex_unlock(&L->lock);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t memory_mutex = PTHREAD_MUTEX_INITIALIZER;
extern int mmcamera_stacktrace(intptr_t* addrs, size_t max_entries);
struct hdr_t {
struct hdr_t *prev;
struct hdr_t *next;
intptr_t bt[15];
int bt_depth;
};
static unsigned num;
static hdr_t *last;
static inline void add(hdr_t *hdr)
{
hdr->prev = 0;
hdr->next = last;
if (last) last->prev = hdr;
last = hdr;
num++;
}
void *__override_malloc(size_t size)
{
pthread_mutex_lock(&memory_mutex);
hdr_t *hdr = malloc(sizeof(hdr_t)+size);
if (hdr) {
hdr->bt_depth = mmcamera_stacktrace(
hdr->bt, 15);
add(hdr);
pthread_mutex_unlock(&memory_mutex);
return hdr+1;
}
pthread_mutex_unlock(&memory_mutex);
return 0;
}
void __override_free(hdr_t *hdr)
{
pthread_mutex_lock(&memory_mutex);
if (hdr) {
hdr--;
if (hdr->prev)
hdr->prev->next = hdr->next;
else
last = hdr->next;
if (hdr->next)
hdr->next->prev = hdr->prev;
free(hdr);
num--;
}
pthread_mutex_unlock(&memory_mutex);
}
void *__override_calloc(size_t nmemb, size_t size)
{
pthread_mutex_lock(&memory_mutex);
hdr_t *hdr = calloc(1, sizeof(hdr_t)+nmemb*size);
if (hdr) {
hdr->bt_depth = mmcamera_stacktrace(
hdr->bt, 15);
add(hdr);
pthread_mutex_unlock(&memory_mutex);
return hdr + 1;
}
pthread_mutex_unlock(&memory_mutex);
return 0;
}
void *__override_realloc(void *ptr, size_t size)
{
pthread_mutex_lock(&memory_mutex);
hdr_t *hdr = realloc(ptr, sizeof(hdr_t)+size);
if (hdr) {
hdr->bt_depth = mmcamera_stacktrace(
hdr->bt, 15);
add(hdr);
pthread_mutex_unlock(&memory_mutex);
return hdr + 1;
}
pthread_mutex_unlock(&memory_mutex);
return 0;
}
static void free_leaked_memory(void) ;
static void free_leaked_memory(void)
{
pthread_mutex_lock(&memory_mutex);
hdr_t *del; int cnt;
while(last) {
del = last;
last = last->next;
fprintf(stderr, "+++ DELETING LEAKED MEMORY AT %p (%d REMAINING)\\n", del + 1, num)
;
for (cnt = 0; cnt < del->bt_depth; cnt++)
fprintf(stderr, " %2d %p", del->bt_depth - cnt, (void *)del->bt[cnt]);
free(del);
num--;
}
pthread_mutex_unlock(&memory_mutex);
}
| 1
|
#include <pthread.h>
struct shape *s;
pthread_mutex_t blok;
void exit_tetris( void ){
erase();
move( startY, startX );
printw( "Game over!\\n" );
move( startY + 5, startX );
printw( "You scored %d!\\n", score );
refresh();
sleep_t( 3. );
endwin();
free( s );
pthread_mutex_destroy( &blok );
exit( 0 );
}
void *user( void *arg ){
while( 1 ){
switch( getch() ){
case 'a':
pthread_mutex_lock ( &blok );
if( can_move_left(s) )s->x--;
draw_area();
draw_shape( s );
refresh();
pthread_mutex_unlock ( &blok );
break;
case 'd':
pthread_mutex_lock ( &blok );
if( can_move_right(s) )s->x++;
draw_area();
draw_shape( s );
refresh();
pthread_mutex_unlock ( &blok );
break;
case 'w':
pthread_mutex_lock ( &blok );
s->rot = ( s->rot + 1 + 4) % 4;
if( can_rotate(s) ){
draw_area();
draw_shape( s );
refresh();
} else
s->rot = ( s->rot - 1 + 4 ) % 4;
pthread_mutex_unlock ( &blok );
break;
case 's':
pthread_mutex_lock ( &blok );
s->rot = ( s->rot - 1 + 4 ) % 4;
if( can_rotate(s) ){
draw_area();
draw_shape( s );
refresh();
} else
s->rot = ( s->rot + 1 + 4 ) % 4;
pthread_mutex_unlock ( &blok );
break;
case 'j':
pthread_mutex_lock ( &blok );
while( can_move_down(s) )s->y++;
s->y--;
score += check_area();
draw_area();
draw_shape( s );
refresh();
pthread_mutex_unlock ( &blok );
break;
default:
break;
}
}
exit_tetris();
return 0;
}
void *game( void *arg ){
int temp;
pthread_mutex_lock ( &blok );
get_next_shape( s );
pthread_mutex_unlock ( &blok );
while( 1 ){
pthread_mutex_lock ( &blok );
if( game_over(s) ){ break; }
if( (temp = can_move_down( s )) == 0 ){
add_to_area( s );
get_next_shape( s );
score += check_area();
}
draw_area();
draw_shape( s );
s->y++;
pthread_mutex_unlock ( &blok );
refresh();
if( temp == 1 )sleep_t( 0.5 );
}
exit_tetris();
return 0;
}
int main( int argc, char **argv ){
pthread_t *user_d, *game_d;
user_d = (pthread_t *)malloc( sizeof( *user_d ) );
game_d = (pthread_t *)malloc( sizeof( *game_d ) );
s = ( struct shape* )malloc( sizeof(*s) );
srand( (unsigned)time(0) );
initscr();
getmaxyx( stdscr, maxY, maxX );
curs_set( 0 );
if( maxY < 24 || maxX < 80 ){
printw( "Your terminal window is too small\\n" ); refresh();
sleep_t( 2. );
exit_tetris();
} else{
noecho();
raw();
pthread_mutex_init(&blok, 0);
pthread_create( user_d, 0, user, 0 );
pthread_create( game_d, 0, game, 0 );
pthread_join( *user_d, 0 );
pthread_join( *game_d, 0 );
pthread_mutex_destroy( &blok );
}
exit_tetris();
return 0;
}
| 0
|
#include <pthread.h>
unsigned int nthreads = 30;
int load_grid(int grid[][9], char *filename);
int grid[9][9];
int reorgGrid[9][9];
int nextCell = 0;
int nextReorgCell = 0;
int erros = 0;
pthread_t tidpai;
pthread_mutex_t mutexCell, mutexReorg, mutexErr;
pthread_barrier_t trump;
void checkCol(int cell) {
int col = cell % 9;
int row = cell / 9;
for (int i = row + 1; i < 9; i++) {
if (grid[row][col] == grid[i][col]) {
printf("Erro na coluna %d!\\n", col + 1);
pthread_mutex_lock(&mutexErr);
erros++;
pthread_mutex_unlock(&mutexErr);
return;
}
}
}
void checkRow(int cell) {
int col = cell % 9;
int row = cell / 9;
for (int i = col + 1; i < 9; i++) {
if (grid[row][col] == grid[row][i]) {
printf("Erro na linha %d!\\n", row + 1);
pthread_mutex_lock(&mutexErr);
erros++;
pthread_mutex_unlock(&mutexErr);
return;
}
}
}
void checkReg(int cell) {
int row = (cell / 27) * 3 + (cell / 3) % 3;
int col = (cell % 3) + ((cell % 27) / 9) * 3;
for (int i = col + 1; i < 9; i++) {
if (reorgGrid[row][col] == reorgGrid[row][i]) {
printf("Erro na região %d!\\n", row + 1);
pthread_mutex_lock(&mutexErr);
erros++;
pthread_mutex_unlock(&mutexErr);
return;
}
}
}
void reorganizeRegions(int cell) {
int rowNew = (cell / 27) * 3 + (cell / 3) % 3;
int colNew = (cell % 3) + ((cell % 27) / 9) * 3;
int rowOld = cell / 9;
int colOld = cell % 9;
reorgGrid[rowNew][colNew] = grid[rowOld][colOld];
}
void *check(void* arg) {
int cell;
while (1) {
pthread_mutex_lock(&mutexReorg);
if (nextReorgCell > 81) {
pthread_mutex_unlock(&mutexReorg);
break;
}
int reorgCell = nextReorgCell;
nextReorgCell++;
pthread_mutex_unlock(&mutexReorg);
reorganizeRegions(reorgCell);
}
pthread_barrier_wait(&trump);
pthread_mutex_lock(&mutexCell);
while (nextCell < 242) {
switch (nextCell % 3) {
case 0:
cell = nextCell / 3;
nextCell++;
pthread_mutex_unlock(&mutexCell);
checkCol(cell);
break;
case 1:
cell = nextCell / 3;
nextCell++;
pthread_mutex_unlock(&mutexCell);
checkRow(cell);
break;
case 2:
cell = nextCell / 3;
nextCell++;
pthread_mutex_unlock(&mutexCell);
checkReg(cell);
break;
}
pthread_mutex_lock(&mutexCell);
}
pthread_mutex_unlock(&mutexCell);
return 0;
}
int main(int argc, char **argv) {
if(argc != 3) {
printf("Usage: ./t1_v1 file.txt number_threads\\n");
exit(0);
}
char *gridFile = argv[1];
nthreads = atoi(argv[2]);
tidpai = pthread_self();
if(nthreads > 80) nthreads = 80;
load_grid(grid, gridFile);
pthread_mutex_init(&mutexCell, 0);
pthread_mutex_init(&mutexReorg, 0);
pthread_mutex_init(&mutexErr, 0);
pthread_barrier_init(&trump, 0, nthreads);
pthread_t thread[nthreads];
for (int i = 0; i < nthreads; i++) {
pthread_create(&thread[i], 0, check, 0);
}
for (int i = 0; i < nthreads; i++) {
pthread_t t = thread[i];
pthread_join(t, 0);
}
printf("%d erros.\\n", erros);
pthread_barrier_destroy(&trump);
pthread_mutex_destroy(&mutexCell);
pthread_mutex_destroy(&mutexReorg);
pthread_mutex_destroy(&mutexErr);
pthread_exit(0);
}
int load_grid(int grid[][9], char *filename) {
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;
}
| 1
|
#include <pthread.h>
static int thread_exit;
static pthread_t thread_id;
static int thread_inuse;
static pthread_cond_t thread_cond;
static pthread_mutex_t thread_mutex;
static void (*thread_func)(void*, int, int);
static void* thread_arg;
static void* thread_proc(void* arg)
{
pthread_mutex_lock(&thread_mutex);
while (1) {
void (*func)(void*, int, int);
while (!thread_func && !thread_exit)
pthread_cond_wait(&thread_cond, &thread_mutex);
if (thread_exit) {
pthread_mutex_unlock(&thread_mutex);
break;
}
func = thread_func;
pthread_mutex_unlock(&thread_mutex);
func(thread_arg, 1, 2);
pthread_mutex_lock(&thread_mutex);
thread_func = 0;
pthread_cond_signal(&thread_cond);
}
pthread_exit(0);
return 0;
}
int thread_init(void)
{
thread_exit = 0;
if (pthread_mutex_init(&thread_mutex, 0) != 0)
return -1;
if (pthread_cond_init(&thread_cond, 0) != 0)
return -1;
if (pthread_create(&thread_id, 0, thread_proc, 0) != 0)
return -1;
return 0;
}
void thread_done(void)
{
pthread_mutex_lock(&thread_mutex);
thread_exit = 1;
pthread_cond_signal(&thread_cond);
pthread_mutex_unlock(&thread_mutex);
pthread_join(thread_id, 0);
pthread_mutex_destroy(&thread_mutex);
pthread_cond_destroy(&thread_cond);
}
void osd_parallelize(void (*func)(void* arg, int num, int max), void* arg, int max)
{
if (!thread_is_active()) {
func(arg, 0, 1);
return;
}
if (max <= 1) {
func(arg, 0, 1);
return;
}
if (thread_inuse) {
func(arg, 0, 1);
return;
}
thread_inuse = 1;
pthread_mutex_lock(&thread_mutex);
thread_func = func;
thread_arg = arg;
pthread_cond_signal(&thread_cond);
pthread_mutex_unlock(&thread_mutex);
func(arg, 0, 2);
pthread_mutex_lock(&thread_mutex);
while (thread_func)
pthread_cond_wait(&thread_cond, &thread_mutex);
pthread_mutex_unlock(&thread_mutex);
thread_inuse = 0;
}
| 0
|
#include <pthread.h>
void *ihome_read ( void *prm)
{
struct hostent *server;
struct sockaddr_in serv_addr;
int bytes, sent, received, total, l_indx;
char response[1000], *e1, *e2, *e3;
while (1)
{
for (l_indx = 0; l_indx < nb_Of_Input_Elements; l_indx++)
{
pthread_mutex_lock( &inputs_Array_Of_Elements[l_indx].mutex ) ;
inputs_Array_Of_Elements[l_indx].value = (bcm2835_gpio_lev(pins_in[l_indx]) == HIGH) ? TRUE : FALSE ;
pthread_mutex_unlock( &inputs_Array_Of_Elements[l_indx].mutex ) ;
}
socket_read = socket(AF_INET, SOCK_STREAM, 0);
server = gethostbyname(host);
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
memcpy(&serv_addr.sin_addr.s_addr, server->h_addr_list[0], server->h_length);
memcpy(&serv_addr.sin_addr.s_addr, server->h_addr_list[0], server->h_length);
if (connect(socket_read, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
close(socket_read);
log_print("read socket failed to connect.\\n");
continue ;
}
send(socket_read, http_get_request, total, 0);
memset(response, 0, sizeof(response));
total = sizeof(response) - 1;
received = 0;
recv(socket_read, response, total, 0);
close(socket_read);
if (received >= total)
{
log_print("received data > total in read task \\n");
continue ;
}
e1 = strstr(response, "\\r\\n\\r\\n");
if (e1 != 0)
{
if (e1[4] == '0')
{
}
else
{
e2 = strstr (e1, "w_cmd:");
if (e2 != 0)
{
for (l_indx = 0, e3 = e2 + 6 ; l_indx < nb_Of_Command_Elements && ( *e3 != ',') ; e3++)
{
if ( *e3 != ':' )
{
if (*e3 != 'x')
commands_Array_Of_Elements[l_indx++].value = (atoi(e3) == 1 ) ? TRUE : FALSE ;
else
l_indx++;
}
}
}
}
}
nanosleep((struct timespec[]) {{0, 50000000}}, 0);
}
}
| 1
|
#include <pthread.h>
static unsigned int avail = 0;
static int work_pipe[2];
static pthread_mutex_t mtx_work;
static unsigned int producers = 10000;
unsigned int random_uint(unsigned int max)
{
float tmp = (float)rand()/(float)32767 * (float)max;
return (unsigned int)ceilf(tmp);
}
void* producer (void* param)
{
int ret;
unsigned int* thread_num = (unsigned int*)param;
unsigned int result;
unsigned int pipe_ready = 1;
result = *thread_num;
do {
sleep(random_uint(2));
pthread_mutex_lock(&mtx_work);
ret = write(work_pipe[1], &result, sizeof(unsigned int));
if (ret <= 0) {
pipe_ready = 0;
pthread_mutex_unlock(&mtx_work);
fprintf (stderr, "producer -- pipe was full!\\n");
continue;
}
avail++;
producers--;
pthread_mutex_unlock(&mtx_work);
} while (!pipe_ready);
}
void main (int argc, char** argv)
{
unsigned int i, ret;
unsigned int work_unit;
unsigned int finished = 0;
pthread_t thread_id[10000];
unsigned int thread_num[10000];
unsigned int processed = 0;
int sum = 0;
pipe(work_pipe);
fcntl(work_pipe[0], F_SETFL, O_NONBLOCK);
fcntl(work_pipe[1], F_SETFL, O_NONBLOCK);
for (i=0; i<10000; i++) {
thread_num[i] = i;
pthread_create(&thread_id[i], 0, producer, &thread_num[i]);
pthread_detach(thread_id[i]);
}
while (!finished) {
processed = 0;
pthread_mutex_lock(&mtx_work);
while (avail > 0) {
ret = read(work_pipe[0], &work_unit, sizeof(unsigned int));
if (ret > 0) {
sum += work_unit;
avail--;
processed++;
} else {
fprintf (stderr, "consumer -- tried to read from empty pipe!\\n");
}
if (producers == 0) {
finished = 1;
}
}
pthread_mutex_unlock(&mtx_work);
if (processed)
printf ("consumer -- processed %u work units\\n", processed);
}
printf (" Work unit sum: %u\\n", sum);
sum = 0;
for (i=0; i<10000; i++) {
sum += i;
}
printf ("Expected result: %u\\n", sum);
}
| 0
|
#include <pthread.h>
volatile unsigned char program_runs;
static pthread_mutex_t mikes_lock;
volatile unsigned short threads_running;
volatile unsigned char user_control;
volatile unsigned char user_dir;
volatile unsigned char start_automatically;
void threads_running_add(short x)
{
pthread_mutex_lock(&mikes_lock);
threads_running += x;
pthread_mutex_unlock(&mikes_lock);
}
void signal_term_handler(int signum)
{
program_runs = 0;
}
void say_greeting()
{
say("Hello");
sleep(1);
say("my name is");
sleep(1);
say("me cash.");
sleep(1);
say("How do you do?");
}
int main(int argc, char **argv)
{
program_runs = 1;
threads_running = 1;
pthread_mutex_init(&mikes_lock, 0);
signal(SIGTERM, signal_term_handler);
load_config();
if ((!mikes_config.autostart) && (argc > 1))
if (strcmp(argv[1], "autostart") == 0) return 0;
init_mikes_logs();
say_greeting();
init_public_relations();
init_pose(1, MAP_H);
init_base_module();
init_astar();
init_lidar();
init_mcl();
init_planner();
init_steering();
init_ncurses_control();
init_gui();
while (program_runs)
{
sleep(1);
}
int old_tr = threads_running + 1;
while (threads_running > 1)
{
usleep(10000);
if (threads_running < old_tr)
{
char tr[50];
sprintf(tr, "%d threads running", threads_running);
mikes_log(ML_INFO, tr);
old_tr = threads_running;
}
}
mikes_log(ML_INFO, "Kocur mikes quits.");
usleep(100000);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t db_source_mutex = PTHREAD_MUTEX_INITIALIZER;
char sname[32];
char dbname[32];
char uname[32];
char auth[32];
char dbport[32];
int _db_connect(struct db_context_t *dbc)
{
const char *conninfo;
char tmp[256];
pthread_mutex_lock(&db_source_mutex);
sprintf(tmp, "host=%s dbname=%s user=%s password=%s port=%s", sname, dbname, uname, auth, dbport);
conninfo = tmp;
dbc->conn = PQconnectdb(conninfo);
if ( PQstatus(dbc->conn)==CONNECTION_BAD )
{
LOG_ERROR_MESSAGE("Connection to database '%s' failed.",
dbname);
LOG_ERROR_MESSAGE("%s", PQerrorMessage(dbc->conn));
PQfinish(dbc->conn);
return ERROR;
}
printf("database connection thread_id[%d], backend_pid[%d]\\n", (int)pthread_self(), PQbackendPID(dbc->conn));
pthread_mutex_unlock(&db_source_mutex);
return OK;
}
int
_db_disconnect(struct db_context_t *dbc)
{
pthread_mutex_lock(&db_source_mutex);
PQfinish(dbc->conn);
pthread_mutex_unlock(&db_source_mutex);
return OK;
}
int _db_init(char *_sname, char *_dbname, char *_uname, char *_auth, char *_dbport)
{
if (_sname!= 0)
strcpy(sname, _sname);
if (_dbname != 0)
strcpy(dbname, _dbname);
if (_uname != 0)
strcpy(uname, _uname);
if (_auth != 0)
strcpy(auth, _auth);
if (_dbport != 0)
strcpy(dbport, _dbport);
return OK;
}
int commit_transaction(struct db_context_t *dbc)
{
PGresult *res;
res = PQexec(dbc->conn, "COMMIT");
if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
{
LOG_ERROR_MESSAGE("%s\\nPQbackendPID[%d]\\nPQstatus[%d]\\nPQtransactionStatus[%d]\\nPQsocket[%d]\\nPQprotocolVersion[%d]\\n", PQerrorMessage(dbc->conn), PQbackendPID(dbc->conn), (int)PQstatus(dbc->conn), (int)PQtransactionStatus(dbc->conn), PQsocket(dbc->conn), PQprotocolVersion(dbc->conn));
PQclear(res);
return ERROR;
}
PQclear(res);
return OK;
}
int rollback_transaction(struct db_context_t *dbc)
{
PGresult *res;
res = PQexec(dbc->conn, "ROLLBACK");
if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
{
LOG_ERROR_MESSAGE("%s\\nPQbackendPID[%d]\\nPQstatus[%d]\\nPQtransactionStatus[%d]\\nPQsocket[%d]\\nPQprotocolVersion[%d]\\n", PQerrorMessage(dbc->conn), PQbackendPID(dbc->conn), (int)PQstatus(dbc->conn), (int)PQtransactionStatus(dbc->conn), PQsocket(dbc->conn), PQprotocolVersion(dbc->conn));
PQclear(res);
return ERROR;
}
PQclear(res);
return OK;
}
int begin_transaction(struct db_context_t *dbc)
{
PGresult *res;
res = PQexec(dbc->conn, "BEGIN");
if (!res || PQresultStatus(res) != PGRES_COMMAND_OK)
{
LOG_ERROR_MESSAGE("%s\\nPQbackendPID[%d]\\nPQstatus[%d]\\nPQtransactionStatus[%d]\\nPQsocket[%d]\\nPQprotocolVersion[%d]\\n", PQerrorMessage(dbc->conn), PQbackendPID(dbc->conn), (int)PQstatus(dbc->conn), (int)PQtransactionStatus(dbc->conn), PQsocket(dbc->conn), PQprotocolVersion(dbc->conn));
PQclear(res);
return ERROR;
}
PQclear(res);
return OK;
}
| 0
|
#include <pthread.h>
int NumProcs;
pthread_mutex_t SyncLock;
pthread_cond_t SyncCV;
int SyncCount;
pthread_mutex_t ThreadLock;
int Count;
void Barrier()
{
int ret;
pthread_mutex_lock(&SyncLock);
SyncCount++;
if(SyncCount == NumProcs) {
ret = pthread_cond_broadcast(&SyncCV);
SyncCount = 0;
assert(ret == 0);
} else {
ret = pthread_cond_wait(&SyncCV, &SyncLock);
assert(ret == 0);
}
pthread_mutex_unlock(&SyncLock);
}
void* ThreadLoop(void* tmp)
{
int threadId = (int) tmp;
int ret;
int i;
if(threadId==0)
m5_reset_stats(0,0);
Barrier();
for (i = 0; i < (10000 / NumProcs); i++) {
m5_work_begin(0,threadId);
pthread_mutex_lock(&ThreadLock);
Count++;
pthread_mutex_unlock(&ThreadLock);
m5_work_end(0,threadId);
}
}
int main(int argc, char** argv)
{
pthread_t* threads;
pthread_attr_t attr;
int ret;
int dx;
if(argc != 1) {
fprintf(stderr, "USAGE: %s <numProcesors>\\n", argv[0]);
exit(-1);
}
assert(argc == 1);
NumProcs = 1;
assert(NumProcs > 0 && NumProcs <= 16);
threads = (pthread_t *) malloc(sizeof(pthread_t) * NumProcs);
assert(threads != 0);
pthread_attr_init(&attr);
ret = pthread_mutex_init(&SyncLock, 0);
assert(ret == 0);
ret = pthread_mutex_init(&ThreadLock, 0);
assert(ret == 0);
ret = pthread_cond_init(&SyncCV, 0);
assert(ret == 0);
SyncCount = 0;
Count = 0;
for(dx=0; dx < NumProcs; dx++) {
ret = pthread_create(&threads[dx], &attr, ThreadLoop, (void*) dx);
assert(ret == 0);
}
for(dx=0; dx < NumProcs; dx++) {
ret = pthread_join(threads[dx], 0);
assert(ret == 0);
}
printf("Count: %d\\n",Count);
pthread_mutex_destroy(&ThreadLock);
pthread_mutex_destroy(&SyncLock);
pthread_cond_destroy(&SyncCV);
return 0;
}
| 1
|
#include <pthread.h>
int main(){
pthread_mutexattr_t attributes;
pthread_mutexattr_init(&attributes);
pthread_mutexattr_setpshared(&attributes,PTHREAD_PROCESS_SHARED);
int handle = shm_open("/shm",O_CREAT|O_RDWR,0777);
ftruncate(handle,1024*sizeof(int));
char *mem=(char *)mmap(0,1024*sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED,handle,0);
pthread_mutex_t *mutex;
mutex=(pthread_mutex_t *)mem;
pthread_mutex_init(mutex,&attributes);
pthread_mutexattr_destroy(&attributes);
int ret =0;
int *pcount=(int *)(mem+sizeof(pthread_mutex_t));
*pcount=0;
pid_t pid = fork();
if(pid==0){
pthread_mutex_lock(mutex);
(*pcount)++;
pthread_mutex_unlock(mutex);
ret=57;
}else{
int status;
waitpid(pid,&status,0);
printf("Child returned %i\\n",WEXITSTATUS(status));
pthread_mutex_lock(mutex);
(*pcount)++;
pthread_mutex_unlock(mutex);
printf("Count=%i\\n",*pcount);
pthread_mutex_destroy(mutex);
}
munmap(mem,1024*sizeof(int));
shm_unlink("/shm");
return ret;
}
| 0
|
#include <pthread.h>
void
tcp_read ( struct chat_client *chat_client_p ){
char buffer[MAX_BUFFER_LEN];
char message[MAX_MESSAGE_LEN];
int retval;
int retval_command;
int nsfd;
char *hello = "Bitte gib deinen Nickname ein: ";
int len;
int message_terminated;
nsfd = chat_client_p->socket;
send(nsfd, hello, strlen(hello), 0);
for(;;){
memset(&buffer[0], 0, sizeof(buffer));
memset(&message[0], 0, sizeof(message));
retval = read(nsfd, buffer, sizeof(buffer));
if(retval == 0){
close_connection(chat_client_p);
return;
}
if (retval != -1){
if(strlen(chat_client_p->nickname)==0){
set_nickname(chat_client_p, buffer);
strncpy(message, chat_client_p->nickname, MAX_BUFFER_LEN);
strncat(message, " joined chat\\n", MAX_BUFFER_LEN);
write_message( chat_client_p, message);
}
else{
retval_command = handle_command(chat_client_p, buffer);
if(retval_command == 0){
continue;
}
else if(retval_command == -1){
return;
}
if(message_terminated){
strncpy(message, chat_client_p->nickname, MAX_NICK_LEN);
strncat(message, ": ", 2);
strncat(message, buffer, MAX_BUFFER_LEN);
}
else{
strncpy(message, buffer, MAX_BUFFER_LEN);
}
write_message(chat_client_p, message);
}
len = strlen(message);
if(message[len-1] == '\\n'){
message_terminated = 1;
}
else{
message_terminated = 0;
}
}
}
}
void
write_message ( struct chat_client *chat_client_p, char message[MAX_MESSAGE_LEN] )
{
list_node_t *cur;
for(cur=chat_client_p->ll->first_p; cur != 0; cur=cur->next_p){
pthread_mutex_lock(&(cur->mutex));
int *socket = cur->data_p;
if(*socket != chat_client_p->socket){
send(*socket, message, strlen(message), 0);
}
pthread_mutex_unlock(&(cur->mutex));
}
}
| 1
|
#include <pthread.h>
int shmid;
char *addr;
pthread_mutex_t *p_mutex;
pthread_mutexattr_t mutex_attr;
void sigint_handler(int signal)
{
int ret;
ret = shmctl(shmid, IPC_RMID, 0);
if (ret < 0)
{
perror("shmctl");
}
pthread_mutexattr_destroy(&mutex_attr);
}
void print0(size_t count)
{
int i;
for (i = 0; i < count; i++)
{
fprintf(stderr, "0");
}
fprintf(stderr, "\\n");
}
void print1(size_t count)
{
int i;
for (i = 0; i < count; i++)
{
fprintf(stderr, "1");
}
fprintf(stderr, "\\n");
}
void parent()
{
int i = 100;
signal(SIGINT, sigint_handler);
shmid = shmget(2, 0, 0666);
if (shmid < 0)
{
shmid = shmget(2, 4096, IPC_CREAT | IPC_EXCL | 0666);
if (shmid < 0)
{
perror("parent shmget");
return;
}
}
addr = shmat(shmid, 0, 0);
if (addr == (void *)-1)
{
perror("shmat");
return;
}
p_mutex = (pthread_mutex_t *)addr;
pthread_mutex_init(p_mutex, &mutex_attr);
while(i--)
{
pthread_mutex_lock(p_mutex);
print0(100);
pthread_mutex_unlock(p_mutex);
}
}
void child()
{
int i = 100;
int shmid;
char *addr;
shmid = shmget(2, 0, 0666);
if (shmid < 0)
{
perror("child shmget");
return;
}
addr = shmat(shmid, 0, 0);
p_mutex = (pthread_mutex_t *)addr;
while(i--)
{
pthread_mutex_lock(p_mutex);
print1(100);
pthread_mutex_unlock(p_mutex);
}
}
int main(void)
{
pid_t pid;
int status;
pthread_mutexattr_init(&mutex_attr);
pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED);
debug_info("sizeof mutex is: %ld\\n", sizeof(pthread_mutex_t));
if ((pid = fork()) < 0)
{
debug_error("fork error");
exit(-1);
}
else if (pid > 0)
{
int ret;
parent();
wait(&status);
ret = shmctl(shmid, IPC_RMID, 0);
if (ret < 0)
{
perror("shmctl");
}
pthread_mutexattr_destroy(&mutex_attr);
}
else
{
usleep(200);
child();
}
exit(0);
}
| 0
|
#include <pthread.h>
{
int value;
struct cell *next;
}
*cell;
{
int length;
cell first;
cell last;
}
*list;
list add (int v, list l)
{
cell c = (cell) malloc (sizeof (struct cell));
c->value = v;
c->next = 0;
if (l == 0){
l = (list) malloc (sizeof (struct list));
l->length = 0;
l->first = c;
}else{
l->last->next = c;
}
l->length++;
l->last = c;
return l;
}
void put (int v,list *l)
{
(*l) = add (v,*l);
}
int get (list *l)
{
int res;
list file = *l;
if (l == 0) {
fprintf (stderr, "get error!\\n");
return 0;
}
res = file->first->value;
file->length--;
if (file->last == file->first){
file = 0;
}else{
file->first = file->first->next;
}
return res;
}
int size (list l)
{
if (l==0) return 0;
return l->length;
}
list in = 0, out = 0;
pthread_mutex_t producer_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t consumer_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t new_input = PTHREAD_COND_INITIALIZER;
pthread_cond_t new_output = PTHREAD_COND_INITIALIZER;
void process_value (int v)
{
int i,j;
for (i=0;i<PROCESSING;i++) j++;
pthread_mutex_lock(&consumer_mutex);
put(-v,&out);
pthread_cond_signal (&new_output);
pthread_mutex_unlock(&consumer_mutex);
}
void* process (void *args)
{
pthread_mutex_lock(&producer_mutex);
while (1) {
if (size(in) > 0){
int v = get(&in);
pthread_mutex_unlock(&producer_mutex);
process_value(v);
pthread_mutex_lock(&producer_mutex);
}else{
pthread_cond_wait (&new_input,&producer_mutex);
}
}
return 0;
}
void* produce (void *args)
{
int v = 0;
while (v < PRODUCED) {
pthread_mutex_lock(&producer_mutex);
if (size(in) < FILE_SIZE){
put (v,&in);
PRINT("%d produced\\n",v);
pthread_cond_signal (&new_input);
v++;
pthread_mutex_unlock (&producer_mutex);
}else{
pthread_mutex_unlock(&producer_mutex);
sched_yield();
}
}
return 0;
}
void* consume (void *args)
{
int v = 0;
while (v < PRODUCED) {
pthread_mutex_lock(&consumer_mutex);
if (size(out) > 0){
int res = get (&out);
PRINT("consume %d\\n",res);
v++;
}else{
pthread_cond_wait (&new_output,&consumer_mutex);
}
pthread_mutex_unlock(&consumer_mutex);
}
exit (0);
return 0;
}
int main(void)
{
int i;
pthread_t producer,consumer;
pthread_t thread_array[MAX_THREADS];
for (i=0; i<MAX_THREADS; i++){
pthread_create (&thread_array[i],0,process,0);
}
pthread_create (&producer,0,produce,0);
pthread_create (&consumer,0,consume,0);
pthread_exit (0);
return 0;
}
| 1
|
#include <pthread.h>
struct foo {
int count;
pthread_mutex_t mutex;
char s[3];
};
struct foo * fp;
struct foo * init_foo() {
struct foo * fp;
if ((fp = (struct foo *) malloc(sizeof(struct foo))) != 0) {
fp->count = 1;
fp->s[0] = 'a';
fp->s[1] = 'b';
fp->s[2] = 'c';
if (pthread_mutex_init(&fp->mutex, 0) != 0) {
pthread_mutex_destroy(&fp->mutex);
free(fp);
return 0;
}
}
return fp;
}
void attach_foo(struct foo * fp) {
pthread_mutex_lock(&fp->mutex);
fp->count++;
printf("%d thread has attached '%c' in thread:%u\\n", fp->count,
fp->s[fp->count - 2], (unsigned int) pthread_self());
sleep(1);
pthread_mutex_unlock(&fp->mutex);
}
void * func1(void * arg) {
attach_foo(fp);
return ((void *) 0);
}
void * func2(void * arg) {
attach_foo(fp);
return ((void *) 0);
}
void * func3(void *arg) {
attach_foo(fp);
return ((void *) 0);
}
void printids(const char *s) {
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid %u tid %u (0x%x)\\n", s, (unsigned int) pid,
(unsigned int) tid, (unsigned int) tid);
}
int main(int argc, char *argv[]) {
int ret;
pid_t pid;
pthread_t tid1, tid2, tid3;
redirect("capture name.capture");
fprintf(stderr, "This error message should not be redirected\\n");
fflush(stderr);
if ((pid = fork()) < 0) {
fprintf(stderr, "fork error");
} else if (pid == 0) {
printids("This is from child process:");
} else {
printids("This is from parent process:");
printids("This is from main thread:");
fp = init_foo();
printf("%d thread begin to attach foo\\n", fp->count);
ret = pthread_create(&tid1, 0, func1, 0);
if (ret != 0) {
fprintf(stderr, "%s\\n", strerror(errno));
}
ret = pthread_create(&tid2, 0, func2, 0);
if (ret != 0) {
fprintf(stderr, "%s\\n", strerror(errno));
}
ret = pthread_create(&tid3, 0, func3, 0);
if (ret != 0) {
fprintf(stderr, "%s\\n", strerror(errno));
}
sleep(4);
printf("%d thread has attached all foo\\n", fp->count);
}
pthread_join(tid1, 0);
pthread_join(tid2, 0);
pthread_join(tid3, 0);
exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t lockFlow;
pthread_mutex_t lockHillA;
pthread_mutex_t lockHillB;
pthread_mutex_t lockTurn;
void * flowAtoB (void * arg);
void * flowBtoA (void * arg);
int monAtoB = 0,
monBtoA = 0;
int main (int argc, char * argv[])
{
pthread_t monkeysAB[10 + 10];
int * id = 0,
i = 0;
pthread_mutex_init (&lockFlow, 0);
pthread_mutex_init (&lockHillA, 0);
pthread_mutex_init (&lockHillB, 0);
pthread_mutex_init (&lockTurn, 0);
for (i = 0; i < (10 + 10); i++)
{
id = (int *) malloc (sizeof(int));
*id = i;
if (i % 2 == 0)
{
if (pthread_create (&monkeysAB[i], 0, flowAtoB, (void *) id))
{
printf ("Falha na criacao da thread %d\\n", i);
return - 1;
}
}
else
{
if (pthread_create (&monkeysAB[i], 0, flowBtoA, (void *) id))
{
printf ("Falha na criacao da thread %d\\n", i);
return - 1;
}
}
id++;
}
for (i = 0; i < (10 + 10); i++)
{
if (pthread_join (monkeysAB[i], 0))
{
printf ("Falha na uniao das threads\\n");
return -1;
}
}
return 0;
}
void * flowAtoB (void * arg)
{
int i = *((int *) arg);
while (1)
{
pthread_mutex_lock (&lockTurn);
pthread_mutex_lock (&lockHillA);
monAtoB++;
if (monAtoB == 1)
pthread_mutex_lock (&lockFlow);
pthread_mutex_unlock (&lockHillA);
pthread_mutex_unlock (&lockTurn);
printf ("\\nMacaco %d do morro A estah atravessando para o morro B\\n", i);
sleep (2);
pthread_mutex_lock (&lockHillA);
monAtoB--;
printf ("\\nMacaco %d do morro A terminou de atravessar para o morro B\\nMacacos na corda: %d\\n", i, monAtoB);
if (monAtoB == 0)
pthread_mutex_unlock (&lockFlow);
pthread_mutex_unlock (&lockHillA);
}
pthread_exit (0);
}
void * flowBtoA (void * arg)
{
int i = *((int *) arg);
while (1)
{
pthread_mutex_lock (&lockTurn);
pthread_mutex_lock (&lockHillB);
monBtoA++;
if (monBtoA == 1)
pthread_mutex_lock (&lockFlow);
pthread_mutex_unlock (&lockHillB);
pthread_mutex_unlock (&lockTurn);
printf ("\\nMacaco %d do morro B estah atravessando para o morro A\\n", i);
sleep (2);
pthread_mutex_lock (&lockHillB);
monBtoA--;
printf ("\\nMacaco %d do morro B terminou de atravessar para o morro A\\nMacacos na corda: %d\\n", i, monBtoA);
if (monBtoA == 0)
pthread_mutex_unlock (&lockFlow);
pthread_mutex_unlock (&lockHillB);
}
pthread_exit (0);
}
| 1
|
#include <pthread.h>
static char OUTPUT_FILENAME[100] = "sequence.log";
static char IF_FILENAME[100] = "occurrence.log";
static long LOOPS = 190000;
static unsigned int THREAD_NUMS = 4;
static unsigned int MCODE_NUMS = 4;
static int sequence[100];
int sequenceOrder;
unsigned int order = 0;
pthread_mutex_t mutex;
void placeholder();
void maliciousePrototype(int o);
void recordMessage();
int ThreadRoutine() {
for (unsigned int m = 0; m < MCODE_NUMS; m++) {
maliciousePrototype(m + 1);
}
return 0;
}
int ThreadCreation() {
pthread_t threads[10];
const unsigned int num_threads = THREAD_NUMS;
unsigned int running_threads = 0;
for (running_threads = 0; running_threads < num_threads; running_threads++) {
pthread_create(&threads[running_threads], 0, (void *)ThreadRoutine,
0);
}
for (running_threads = 0; running_threads < num_threads; running_threads++) {
pthread_join(threads[running_threads], 0);
}
return 1;
}
int main(int argc, char *argv[]) {
int i;
LOOPS = atol(argv[1]);
pthread_mutex_init(&mutex, 0);
for (i = 0; i < 100; i++) {
sequence[i] = 0;
}
sequenceOrder = 0;
ThreadCreation();
recordMessage();
return 0;
}
inline void placeholder() {
for (int i = 0; i < LOOPS; i++)
;
}
void recordMessage() {
int i;
FILE *fp;
if ((fp = fopen(IF_FILENAME, "a+")) == 0) {
printf("can't open the file! \\n");
} else {
if (order == 4) {
fprintf(fp, "1\\n");
} else {
fprintf(fp, "0\\n");
}
}
fclose(fp);
if ((fp = fopen(OUTPUT_FILENAME, "a+")) == 0) {
printf("can't open the file! \\n");
} else {
for (i = 0; sequence[i] != 0; i++) {
fprintf(fp, "%d, ", sequence[i]);
}
fprintf(fp, "\\n");
}
fclose(fp);
}
void maliciousePrototype(int o) {
placeholder();
pthread_mutex_lock(&mutex);
sequence[sequenceOrder++] = o;
if ((o - order) == 1) {
order = o;
}
pthread_mutex_unlock(&mutex);
}
| 0
|
#include <pthread.h>
struct foo {
int f_count;
pthread_mutex_t f_lock;
};
struct foo * foo_alloc() {
struct foo * fp;
if((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 1;
if(pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return 0;
}
}
return fp;
}
void foo_hold(struct foo * fp){
pthread_mutex_lock(&fp->f_lock);
++fp->f_count;
pthread_mutex_unlock(&fp->f_lock);
}
void foo_rele(struct foo * fp){
pthread_mutex_lock(&fp->f_lock);
if(--fp->f_count == 0) {
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
} else {
printf("%d\\n", fp->f_count);
pthread_mutex_unlock(&fp->f_lock);
}
}
void * thr_fn1(void * arg) {
foo_hold((struct foo *)arg);
return ((void *)1);
}
void * thr_fn2(void * arg) {
sleep(1);
foo_rele((struct foo *)arg);
return ((void *)2);
}
int main(int argc, char * argv[]) {
int err;
pthread_t tid1, tid2, tid3;
void * tret;
struct foo * fp;
fp = foo_alloc();
if((err = pthread_create(&tid1, 0, thr_fn1, (struct foo *)fp)) != 0)
err_quit("can't create thread 1: %s\\n", strerror(err));
if((err = pthread_create(&tid2, 0, thr_fn2, (struct foo *)fp)) != 0)
err_quit("can't create thread 2: %s\\n", strerror(err));
if((err = pthread_create(&tid3, 0, thr_fn1, (struct foo *)fp)) != 0)
err_quit("can't create thread 3: %s\\n", strerror(err));
if((err = pthread_join(tid1, &tret)) != 0)
err_quit("can't join thread 1: %s\\n", strerror(err));
if((err = pthread_join(tid2, &tret)) != 0)
err_quit("can't join thread 2: %s\\n", strerror(err));
if((err = pthread_join(tid3, &tret)) != 0)
err_quit("can't join thread 3: %s\\n", strerror(err));
return 0;
}
| 1
|
#include <pthread.h>
int tam_vet;
int MAX_THREADS;
unsigned long int prod;
int count = 0;
pthread_mutex_t mutex;
unsigned long int *a, *b;
void calculo_produto() {
pthread_mutex_lock(&mutex);
++count;
if (count == tam_vet) return;
prod += a[count] * b[count];
pthread_mutex_unlock(&mutex);
}
int main (int argc, char *argv[])
{
MAX_THREADS = atoi(argv[2]);
int i;
prod = 0.0;
pthread_mutex_init(&mutex, 0);
pthread_t thread;
if(argc<2){
printf("uso %s <tamanho vetores>\\n", argv[0]);
exit(1);
}
tam_vet = atoi(argv[1]);
printf("Inicializando vetores A e B...\\n");
for (i=0; i<tam_vet; i++)
a[i] = i;
for (i=0; i<tam_vet; i++)
b[i] = i;
for (i = 0; i < MAX_THREADS; ++i) {
pthread_create(&thread, 0, calculo_produto, 0);
}
a = (unsigned long int *) malloc(sizeof(unsigned long int) * tam_vet);
b = (unsigned long int *) malloc(sizeof(unsigned long int) * tam_vet);
printf("Calculando...\\n");
for (i = 0; i < MAX_THREADS; ++i) {
pthread_join(thread, 0);
}
printf("Terminou!\\n");
printf("******************************************************\\n");
printf("Produto escalar: %lu\\n", prod);
printf("******************************************************\\n");
pthread_mutex_destroy(&mutex);
free(a);
free(b);
}
| 0
|
#include <pthread.h>
void error(const char*);
void *thread_run(void *arg) {
char buffer[65536];
char bigbuf[65536];
char *pch;
int i, j, n, newsockfd;
int abort;
int small_sum;
int addvals[10000];
int tot_vals;
newsockfd = *(unsigned int *)arg;
bzero(buffer,65536);
n = read(newsockfd,buffer,65536);
if (n<0) {
error("ERROR reading from socket");
close(newsockfd);
}
pthread_mutex_lock (&runsum);
if ((strcmp(buffer,"ABORT")==0)) {
abort=1;
printf("Got a request for Abort, add nothing, print abort message...\\n");
} else {
sum_struct.client_calls++;
abort=0;
printf("Got a request for a sum.\\n");
}
printf("String: %s\\n",buffer);
small_sum=0;
if (abort) {
sprintf(bigbuf,"Recieved your request for abort. Nothing done.\\n");
n = write(newsockfd,bigbuf,sizeof(bigbuf));
} else {
i=0;
pch = strtok(buffer, " ");
while (pch != 0) {
addvals[i]=atoi(pch);
i++;
pch = strtok (0, " ");
}
tot_vals=i;
i=0;
for (i=0; i<tot_vals; i++)
small_sum+=addvals[i];
sum_struct.sum+=small_sum;
sprintf(bigbuf,"Your sum: %d\\nThe current Grand Total is %d and I have served %d clients so far.",small_sum,sum_struct.sum,sum_struct.client_calls);
n = write(newsockfd,bigbuf,sizeof(bigbuf));
}
printf("Sum: %d\\n",sum_struct.sum);
printf("Client calls: %d\\n",sum_struct.client_calls);
if (n < 0) {
error("ERROR writing to socket");
close(newsockfd);
}
close(newsockfd);
pthread_mutex_unlock (&runsum);
pthread_exit((void*) 0);
return 0;
}
| 1
|
#include <pthread.h>
{
int id;
int cineId;
int status;
int ocupados;
} Sala;
{
int id;
int cineId;
} Taquilla;
{
int id;
} Usuario;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int atendidos = 0;
int iCola = 0;
Usuario * cola;
Sala * salas;
Taquilla * taquillas;
Usuario * usuarios;
void * salaCtrl(void *);
void * taquillaCtrl(void *);
void * usuarioCtrl(void *);
int main(int argc, const char * argv[])
{
pthread_t * tSala = (pthread_t*)malloc(sizeof(pthread_t) * 5 * 5);
pthread_t * tTaquilla = (pthread_t*)malloc(sizeof(pthread_t) * 5 * 3);
pthread_t * tUsuario = (pthread_t*)malloc(sizeof(pthread_t) * 50);
cola = (Usuario*)malloc(sizeof(Usuario) * 50);
salas = (Sala*)malloc(sizeof(Sala) * 5 * 5);
taquillas = (Taquilla*)malloc(sizeof(Taquilla) * 5 * 3);
usuarios = (Usuario*)malloc(sizeof(Usuario) * 50);
srand((int)time(0));
for (int i = 0; i < 5 * 5; ++i)
{
salas[i].id = (int)floor(i / 5) + 1;
salas[i].cineId = (i % 5) + 1;
salas[i].status = 0;
salas[i].ocupados = 0;
pthread_create((tSala + i), 0, salaCtrl, (void*)(salas + i));
}
for (int i = 0; i < 5 * 3; ++i)
{
taquillas[i].id = (int)floor(i / 3) + 1;
taquillas[i].cineId = (i % 5) + 1;
pthread_create((tTaquilla + i), 0, taquillaCtrl, (void*)(taquillas + i));
}
for (int i = 0; i < 50; ++i)
{
usuarios[i].id = i + 1;
pthread_create((tUsuario + i), 0, usuarioCtrl, (void*)(usuarios + i));
}
for (int i = 0; i < 5 * 5; ++i)
pthread_join(*(tSala + i), 0);
for (int i = 0; i < 5 * 3; ++i)
pthread_join(*(tTaquilla + i), 0);
for (int i = 0; i < 50; ++i)
pthread_join(*(tUsuario + i), 0);
free(cola);
free(salas);
free(taquillas);
free(usuarios);
return 0;
}
void * salaCtrl(void * arg)
{
Sala* data = (struct Sala*)arg;
int id = data->id;
int cineId = data->cineId;
while (atendidos < 50 || data->status == 1)
{
if (data->status == 1)
sleep(rand() % 10);
pthread_mutex_lock(&mutex);
if (data->ocupados > 0 && data->status == 0)
{
printf(" * Inicia pelicula en sala %d :: cine %d :: (%d/%d) \\n",
id, cineId, data->ocupados, 5);
data->status = 1;
}
else
{
if (data->status == 1)
{
printf(" / Termina pelicula en sala %d :: cine %d :: (%d/%d) \\n",
id, cineId, data->ocupados, 5);
data->status = 0;
data->ocupados = 0;
}
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void * taquillaCtrl(void * arg)
{
Taquilla* data = (struct Taquilla*)arg;
int id = data->id;
int cineId = data->cineId;
sleep(rand() % 4);
while (atendidos < 50)
{
int posSala = -1;
pthread_mutex_lock(&mutex);
for (int i = 0; i < 5 * 5; i++)
{
if (salas[i].cineId == cineId
&& salas[i].ocupados < 5
&& salas[i].status == 0)
posSala = i;
}
if (iCola > 0 && posSala != -1)
{
Usuario usuario = cola[iCola];
iCola--;
atendidos++;
salas[posSala].ocupados++;
printf(" - Atendiendo al usuario %d :: taquilla %d :: cine %d :: sala %d \\n",
usuario.id, id, cineId, salas[posSala].id);
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void * usuarioCtrl(void * arg)
{
Usuario* data = (struct Usuario*)arg;
int id = data->id;
usleep(rand() % (id + 1));
pthread_mutex_lock(&mutex);
printf(" + Llegó el usuario %d \\n", id);
iCola++;
cola[iCola] = *data;
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.