text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
int buffer[10];
int fill_ptr = 0;
int use_ptr = 0;
int count = 0;
pthread_cond_t empty, fill;
pthread_mutex_t mutex;
void put(int value) {
buffer[fill_ptr] = value;
fill_ptr = (fill_ptr + 1) % 10;
count++;
}
int get() {
int tmp = buffer[use_ptr];
use_ptr = (use_ptr + 1) % 10;
count--;
return tmp;
}
void *producer(void *arg) {
int i;
int loops = *(int *) arg;
for (i = 0; i < loops; i++) {
pthread_mutex_lock(&mutex);
while (count == 10)
pthread_cond_wait(&empty, &mutex);
put(i);
pthread_cond_signal(&fill);
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(&fill, &mutex);
int tmp = get();
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
printf("%d\\n", tmp);
}
return 0;
}
int main(){
pthread_t p1;
pthread_t p2;
pthread_t p3;
pthread_t c1;
pthread_t c2;
int loops = 10;
pthread_create(&p1, 0, producer, &loops);
pthread_create(&p2, 0, producer, &loops);
pthread_create(&p3, 0, producer, &loops);
pthread_create(&c1, 0, consumer, &loops);
pthread_create(&c2, 0, consumer, &loops);
pthread_join(p1, 0);
pthread_join(p2, 0);
pthread_join(p3, 0);
pthread_join(c1, 0);
pthread_join(c2, 0);
return 0;
}
| 1
|
#include <pthread.h>
void * threadPartialSum(void * args);
double globalSum;
int numberOfThreads;
long length;
float * myArray;
pthread_mutex_t updateSumLock;
int main(int argc, char* argv[]) {
long i;
pthread_t * threadHandles;
int errorCode;
double seqSum;
long startTime, endTime, seqTime, parallelTime;
if (argc != 3) {
return(0);
};
sscanf(argv[1],"%d",&length);
sscanf(argv[2],"%d",&numberOfThreads);
threadHandles = (pthread_t *) malloc(numberOfThreads*sizeof(pthread_t));
myArray=(float *) malloc(length*sizeof(float));
srand(5);
for (i=0; i < length; i++) {
myArray[i] = rand() / (float) 32767;
}
time(&startTime);
seqSum = 0.0;
for (i=0; i < length; i++) {
seqSum += myArray[i];
}
time(&endTime);
seqTime = endTime - startTime;
time(&startTime);
pthread_mutex_init(&updateSumLock, 0);
globalSum = 0.0;
for (i=0; i < numberOfThreads; i++) {
if (errorCode = pthread_create(&threadHandles[i], 0, threadPartialSum, (void *) i) != 0) {
printf("pthread %d failed to be created with error code %d\\n", i, errorCode);
}
}
for (i=0; i < numberOfThreads; i++) {
if (errorCode = pthread_join(threadHandles[i], (void **) 0) != 0) {
printf("pthread %d failed to be joined with error code %d\\n", i, errorCode);
}
}
time(&endTime);
parallelTime = endTime - startTime;
printf( "Time to sum %ld floats using %d threads %ld seconds (seq. %ld seconds)\\n", length, numberOfThreads,
parallelTime, seqTime);
printf("Thread's Sum is %lf and seq. sum %lf\\n\\n",globalSum, seqSum);
free(myArray);
return 0;
}
void * threadPartialSum(void * rank) {
long myRank = (long) rank;
long i, stride;
long firstIndex;
double localSum;
stride = length / numberOfThreads;
firstIndex = myRank;
localSum = 0.0;
for (i=firstIndex; i < length; i = i + stride) {
localSum += myArray[i];
}
pthread_mutex_lock(&updateSumLock);
globalSum += localSum;
pthread_mutex_unlock(&updateSumLock);
return 0;
}
| 0
|
#include <pthread.h>
static int value = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int getValue()
{
pthread_mutex_lock(&mutex);
value++;
pthread_mutex_unlock(&mutex);
return value;
}
void *work_thread1(void *p)
{
struct timeval tv1, tv2;
gettimeofday(&tv1, 0);
printf("thread1start %ld,%ld\\n", tv1.tv_sec, tv1.tv_usec);
int i = 0;
for(i = 0; i < 10000000; i++)
{
pthread_mutex_lock(&mutex);
value++;
pthread_mutex_unlock(&mutex);
}
gettimeofday(&tv2, 0);
printf("thread1end %ld,%ld value = %d\\n", tv2.tv_sec, tv2.tv_usec, value);
return 0;
}
void *work_thread2(void *p)
{
struct timeval tv1, tv2;
gettimeofday(&tv1, 0);
printf("thread2start %ld,%ld\\n", tv1.tv_sec, tv1.tv_usec);
int i = 0;
for(i = 0; i < 10000000; i++)
{
pthread_mutex_lock(&mutex);
value++;
pthread_mutex_unlock(&mutex);
}
gettimeofday(&tv2, 0);
printf("thread2end %ld,%ld value = %d\\n", tv2.tv_sec, tv2.tv_usec, value);
return 0;
}
int main(int argc, char *argv[])
{
pthread_t pid1, pid2;
struct timeval tv1, tv2;
gettimeofday(&tv1, 0);
printf("main %ld,%ld\\n", tv1.tv_sec, tv1.tv_usec);
pthread_create(&pid1, 0, work_thread1, 0);
pthread_create(&pid2, 0, work_thread2, 0);
pthread_join(pid1, 0);
pthread_join(pid2, 0);
gettimeofday(&tv2, 0);
printf("main %ld,%ld\\n", tv2.tv_sec, tv2.tv_usec);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER;
void output_init()
{
return;
}
void output( char * string, ... )
{
va_list ap;
char *ts="[??:??:??]";
struct tm * now;
time_t nw;
pthread_mutex_lock(&m_trace);
nw = time(0);
now = localtime(&nw);
if (now == 0)
printf(ts);
else
printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec);
__builtin_va_start((ap));
vprintf(string, ap);
;
pthread_mutex_unlock(&m_trace);
}
void output_fini()
{
return;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
extern int pid_map[350 -300];
int last;
int allocate_map(void)
{
int i;
for(i = 300; i<350; i++)
{
pid_map[i-300] = 0;
}
if(pid_map[0] != 0)
{
return -1;
}
return 1;
}
int allocate_pid(void)
{
int i;
for(i = 300;i<350; i++)
{
if(pid_map[i - 300] == 0)
{
pid_map[i - 300] = 1;
return i;
}
}
return -1;
}
void release_pid(int pid)
{
pid_map[pid - 300] = 0;
}
int in_use[350 + 1];
pthread_mutex_t test_mutex;
int pid = -1;
void *allocator(void *param)
{
int x = (*(unsigned int*)param);
int timeToSleep = 1;
pthread_mutex_lock(&test_mutex);
printf("Waiting %d seconds\\n", timeToSleep);
sleep(timeToSleep);
pthread_mutex_unlock(&test_mutex);
pthread_exit(0);
}
int main(void)
{
int i;
pthread_t tids[100];
int storage [100];
int toSleep = 1;
if (allocate_map() == -1)
return -1;
pthread_mutex_init(&test_mutex, 0);
int x = 0;
for(i = 0; i < 100;i++)
{
x = 0;
while(x != 1)
{
pid = allocate_pid();
if(pid > 0)
{
x = 1;
}
}
storage[i] = pid;
printf("Now using pid: %d\\n", pid);
pthread_create(&tids[i], 0, &allocator,&toSleep);
}
for(i = 0; i < 100; i++)
{
pthread_join(tids[i], 0);
pid = storage[i];
release_pid(pid);
printf("Releasing pid: %d\\n", pid);
}
pthread_mutex_destroy(&test_mutex);
printf("***DONE***\\n");
return 0;
}
| 1
|
#include <pthread.h>
struct lectred {
pthread_mutex_t mutex;
int nb_l;
int nb_w;
struct list * first;
struct list * last;
};
struct list {
pthread_cond_t * ma_cond;
int est_lect;
struct list * suivant;
};
struct lectred* lectred_init() {
struct lectred * lectred = malloc(sizeof(struct lectred));
pthread_mutex_init(&lectred->mutex, 0);
lectred->nb_w = 0;
lectred->nb_l = 0;
lectred->first = 0;
lectred->last = 0;
return lectred;
}
pthread_cond_t * add_thread_list(struct lectred* lectred, int bl) {
struct list * l = malloc(sizeof(struct list));
l->ma_cond = malloc(sizeof(pthread_cond_t));
pthread_cond_init(l->ma_cond, 0);
l->est_lect = bl;
l->suivant = 0;
if(lectred->first == 0) {
lectred->first = l;
lectred->last = l;
} else {
lectred->last->suivant = l;
lectred->last = l;
}
return l->ma_cond;
}
void remove_thread_list(struct lectred* lectred) {
pthread_cond_destroy(lectred->first->ma_cond);
free(lectred->first->ma_cond);
if(lectred->first == lectred->last) {
free(lectred->first);
lectred->first = 0;
lectred->last = 0;
} else {
struct list * tmp = lectred->first;
lectred->first = lectred->first->suivant;
free(tmp);
}
}
int est_pas_premier(struct lectred* lectred, pthread_cond_t * ma_cond) {
return ma_cond != lectred->first->ma_cond;
}
void begin_read(struct lectred* lectred) {
pthread_mutex_lock(&lectred->mutex);
pthread_cond_t * ma_cond = add_thread_list(lectred, 1);
while(est_pas_premier(lectred, ma_cond) || lectred->nb_w > 0) {
pthread_cond_wait( ma_cond, &lectred->mutex);
}
lectred->nb_l ++;
remove_thread_list(lectred);
if(lectred->first != 0 && lectred->first->est_lect) {
pthread_cond_signal(lectred->first->ma_cond);
}
pthread_mutex_unlock(&lectred->mutex);
}
void end_read(struct lectred* lectred) {
pthread_mutex_lock(&lectred->mutex);
lectred->nb_l --;
if(lectred->nb_l == 0 && lectred->first != 0 && !lectred->first->est_lect) {
pthread_cond_signal( lectred->first->ma_cond);
}
pthread_mutex_unlock(&lectred->mutex);
}
void begin_write(struct lectred* lectred) {
pthread_mutex_lock(&lectred->mutex);
pthread_cond_t * ma_cond = add_thread_list(lectred, 0);
while(est_pas_premier(lectred, ma_cond) || lectred->nb_l > 0 || lectred->nb_w > 0) {
pthread_cond_wait( ma_cond, &lectred->mutex);
}
lectred->nb_w ++;
remove_thread_list(lectred);
pthread_mutex_unlock(&lectred->mutex);
}
void end_write(struct lectred* lectred) {
pthread_mutex_lock(&lectred->mutex);
lectred->nb_w --;
if(lectred->first != 0) {
pthread_cond_signal(lectred->first->ma_cond);
}
pthread_mutex_unlock(&lectred->mutex);
}
void lectred_destroy(struct lectred* lectred) {
pthread_mutex_destroy(&lectred->mutex);
free(lectred);
}
| 0
|
#include <pthread.h>
extern struct __pthread *__pthread_free_threads;
extern pthread_mutex_t __pthread_free_threads_lock;
void
__pthread_dealloc (struct __pthread *pthread)
{
assert (pthread->state != PTHREAD_TERMINATED);
if (! __atomic_dec_and_test (&pthread->nr_refs))
return;
__pthread_setid (pthread->thread, 0);
__pthread_mutex_lock (&pthread->state_lock);
if (pthread->state != PTHREAD_EXITED)
pthread_cond_broadcast (&pthread->state_cond);
__pthread_mutex_unlock (&pthread->state_lock);
pthread_mutex_lock (&__pthread_free_threads_lock);
__pthread_enqueue (&__pthread_free_threads, pthread);
pthread_mutex_unlock (&__pthread_free_threads_lock);
pthread->state = PTHREAD_TERMINATED;
}
| 1
|
#include <pthread.h>
long start, end;
void *async_event_server(void *arg);
void *handler1(void *arg);
void usage(void)
{
rt_help();
printf("async_handler_jk specific options:\\n");
}
int parse_args(int c, char *v)
{
int handled = 1;
switch (c) {
case 'h':
usage();
exit(0);
default:
handled = 0;
break;
}
return handled;
}
void *async_event_server(void *arg)
{
int err=0;
struct thread *thread = ((struct thread *)arg);
thread->func = 0;
thread->flags |= 8;
for (; ;) {
if ((err = pthread_mutex_lock(&thread->mutex)))
return (void*)(intptr_t)err;
while (thread->flags & 8)
pthread_cond_wait(&thread->cond, &thread->mutex);
pthread_mutex_unlock(&thread->mutex);
thread->func = handler1;
if (thread->func != 0)
thread->func(arg);
set_thread_priority(thread->pthread, thread->priority);
thread->flags |= 8;
}
}
void *user_thread(void *arg)
{
struct thread *thread = ((struct thread *)arg);
struct thread *server = (struct thread*)thread->arg;
start = rt_gettime();
set_thread_priority(server->pthread, thread->priority);
server->flags &= ~8;
pthread_cond_broadcast(&server->cond);
return 0;
}
void *handler1(void *arg)
{
end = rt_gettime();
return 0;
}
int main(int argc, char* argv[])
{
int aes_id;
int user_id;
long delta;
struct thread *server;
setup();
pass_criteria = 100;
rt_init("h", parse_args, argc, argv);
aes_id = create_fifo_thread(async_event_server, (void*)0, 83);
server = get_thread(aes_id);
user_id = create_fifo_thread(user_thread, (void*)server, 43);
usleep(1000);
pthread_detach(server->pthread);
join_thread(user_id);
join_threads();
delta = (end - start)/NS_PER_US;
printf("delta = %ld us\\n", delta);
printf("\\nCriteria: latencies < %d\\n", (int)pass_criteria);
printf("Result: %s\\n", delta > pass_criteria ? "FAIL" : "PASS");
return 0;
}
| 0
|
#include <pthread.h>
struct s_word_object{
char *word;
word_object *next;
};
static word_object *list_head;
static pthread_mutex_t list_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t list_data_ready = PTHREAD_COND_INITIALIZER;
static pthread_cond_t list_data_flush = PTHREAD_COND_INITIALIZER;
static void add_to_list(char *word) {
word_object *last_object, *tmp_object;
char *tmp_string=strdup(word);
tmp_object=malloc(sizeof(word_object));
pthread_mutex_lock(&list_lock);
if(list_head==0){
last_object=tmp_object;
list_head = last_object;
pthread_mutex_unlock(&list_lock);
} else{
last_object= list_head;
while(last_object->next){
last_object=last_object->next;
}
last_object->next=tmp_object;
last_object=last_object->next;
}
last_object ->word=tmp_string;
last_object ->next=0;
pthread_mutex_unlock(&list_lock);
pthread_cond_signal(&list_data_ready);
}
static word_object *list_get_first(void){
word_object *first_object;
first_object=list_head;
list_head=list_head->next;
return first_object;
}
void *print_func(void *arg){
word_object *current_object;
fprintf(stderr, "Print thread starting\\n");
while(1){
pthread_mutex_lock(&list_lock);
while(list_head==0){
pthread_cond_wait(&list_data_ready,&list_lock);
}
current_object=list_get_first();
pthread_mutex_unlock(&list_lock);
printf("Print Thread: %s\\n",current_object ->word);
free(current_object->word);
free(current_object);
pthread_cond_signal(&list_data_flush);
}
return arg;
}
static void list_flush(void){
pthread_mutex_lock(&list_lock);
while(list_head != 0){
pthread_cond_signal(&list_data_ready);
pthread_cond_wait(&list_data_flush, &list_lock);
}
pthread_mutex_unlock(&list_lock);
}
int main(int argc, char **argv){
char input_word[256];
int c;
int option_index;
int count=-1;
pthread_t print_thread;
static struct option long_options[]={
{"count", required_argument, 0, 'c'},
{0, 0, 0, 0 }
};
while(1) {
c= getopt_long(argc, argv, "c:", long_options, &option_index);
if(c==-1){
break;
}
switch(c) {
case 'c':
count=atoi(optarg); break;
}
}
pthread_create(&print_thread,0, print_func,0);
fprintf(stderr, "Accepting %i input strings\\n", count);
while(scanf("%256s", input_word) !=EOF) {
add_to_list(input_word);
if(!--count) break;
}
list_flush();
return 0;
}
| 1
|
#include <pthread.h>
static int myFd ;
static int __spiChannel=0;
static pthread_mutex_t mutexMCP;
int channelConfig=8;
void mcp3008Setup(int spiChannel)
{
printf("INIT MCP3008\\n");
if ((myFd = wiringPiSPISetup (spiChannel, 1000000)) < 0)
{
fprintf (stderr, "Can't open the SPI bus: %s\\n", strerror (errno)) ;
exit (1) ;
}
__spiChannel = spiChannel;
pthread_mutex_init(&mutexMCP, 0);
}
void mcp3008Close() {
close(myFd);
}
int myAnalogRead(int analogChannel)
{
if(analogChannel<0 || analogChannel>7)
return -1;
unsigned char buffer[3] = {1};
buffer[1] = (8 +analogChannel) << 4;
pthread_mutex_lock(&mutexMCP);
wiringPiSPIDataRW(__spiChannel, buffer, 3);
pthread_mutex_unlock(&mutexMCP);
return ( (buffer[1] & 3 ) << 8 ) + buffer[2];
}
| 0
|
#include <pthread.h>
FILE *file;
int size,chars_per_thread, current_location, current_word, current_char;
char **words;
int *count;
pthread_mutex_t mutex;
} word_counter;
void *count_words(void* a)
{
word_counter* counter = a;
pthread_mutex_lock(&counter->mutex);
int found_word = 0, c, chars = 0, stop = 1,found_apostrophe = 0, current_char = 0, current_word = 0, i, lines = 0;
char **str = (char**) calloc(1000000, sizeof(char*));
for ( i = 0; i < 1000000; i++ )
{
str[i] = (char*) calloc(50, sizeof(char));
}
while ((c =fgetc(file)) != EOF){
chars++;
if (!isalpha(c))
{
if (found_word) {
if (!found_apostrophe && c=='\\'') {
found_apostrophe = 1;
}
else {
if(same(str[current_word], counter) ==1){
counter->words[counter->current_word] = str[current_word];
counter->count[counter->current_word]++;
counter->current_word ++;
}
current_word ++;
current_char = 0;
found_apostrophe = 0;
found_word = 0;
if(chars > counter->chars_per_thread)
stop = 0;
}
}
}
else {
if (found_apostrophe) {
str[current_word][current_char] = '\\'';
current_char++;
found_apostrophe == 0;
}
found_word = 1;
c = tolower(c);
str[current_word][current_char] = c;
current_char++;
}
}
free(str);
pthread_mutex_unlock(&counter->mutex);
return 0;
pthread_exit(0);
}
int same(char *str, word_counter* counter){
int i;
for(i = 0; i < counter->current_word; i++){
if(strcmp(counter->words[i], str) ==0){
counter->count[i]++;
return 0;
}
}
return 1;
}
int main(int argc, char **argv)
{
int size, j;
if(argc < 1){
printf("improper argument! Refer to the ReadMe.");
return 1;
}
int i, num_threads;
long characters = 0;
num_threads = atoi(argv[1]);
word_counter counter;
file = fopen("test.txt", "r");
int c;
while ((c =fgetc(file)) != EOF ){
characters ++;
}
counter.chars_per_thread = characters/num_threads;
printf("chars: %lu, chars per thread: %d\\n", characters, counter.chars_per_thread);
fclose(file);
counter.current_char = 0;
counter.current_word = 0;
counter.count = (int*)calloc(1000000, sizeof(int));
counter.words = (char**) calloc(1000000, sizeof(char*));
for ( i = 0; i < 1000000; i++ )
{
counter.words[i] = (char*) calloc(50, sizeof(char));
}
file = fopen("test.txt", "r");
pthread_t threads[num_threads];
if (pthread_mutex_init(&counter.mutex, 0) != 0)
{
printf("\\n mutex init failed\\n");
return 1;
}
for(i = 0; i < num_threads; ++i){
if(pthread_create(&threads[i], 0, count_words, &counter)){
fprintf(stderr, "Error creating thread\\n");
return 1;
}
}
for(i = 0; i < num_threads; ++i){
if(pthread_join(threads[i], 0)) {
fprintf(stderr, "Error joining thread\\n");
return 2;
}
}
char* temp;
int count_temp;
for (i = 0; i < counter.current_word ; i++) {
for (j = 0; j < counter.current_word - 1; j++) {
if (strcmp(counter.words[j], counter.words[j + 1]) > 0) {
strcpy(temp, counter.words[j]);
count_temp = counter.count[j];
strcpy(counter.words[j], counter.words[j + 1]);
counter.count[j] = counter.count[j+1];
strcpy(counter.words[j + 1], temp);
counter.count[j+1] = count_temp;
}
}
}
fclose(file);
for(i = 0; i < counter.current_word; ++i){
printf("%s %i\\n", counter.words[i], counter.count[i]);
}
return 0;
}
| 1
|
#include <pthread.h>
const int MAX_KEY = 100000000;
struct list_node_s {
int data;
struct list_node_s* next;
};
struct list_node_s* head = 0;
int num_hilos;
int total_ops;
double insert_percent;
double search_percent;
double delete_percent;
pthread_mutex_t mutex;
pthread_mutex_t count_mutex;
int total_miembro=0, total_insercion=0, total_borrado=0;
void Usage(char* prog_name);
void Get_input(int* inserts_in_main_p);
void* Thread_work(void* rank);
int Insert(int value);
void Print(void);
int Member(int value);
int Delete(int value);
void Free_list(void);
int Is_empty(void);
int main(int argc, char* argv[]) {
long i;
int key, success, attempts;
pthread_t* thread_handles;
int inserts_in_main;
unsigned seed = 1;
double inicio, fin;
if (argc != 2) Usage(argv[0]);
num_hilos = strtol(argv[1],0,10);
Get_input(&inserts_in_main);
i = attempts = 0;
while ( i < inserts_in_main && attempts < 2*inserts_in_main ) {
key = my_rand(&seed) % MAX_KEY;
success = Insert(key);
attempts++;
if (success) i++;
}
printf("%ld claves insertadas\\n", i);
thread_handles = malloc(num_hilos*sizeof(pthread_t));
pthread_mutex_init(&mutex, 0);
pthread_mutex_init(&count_mutex, 0);
GET_TIME(inicio);
for (i = 0; i < num_hilos; i++)
pthread_create(&thread_handles[i], 0, Thread_work, (void*) i);
for (i = 0; i < num_hilos; i++)
pthread_join(thread_handles[i], 0);
GET_TIME(fin);
printf("Tiempo de ejecución = %e segundos\\n", fin - inicio);
printf("Total operaciones = %d\\n", total_ops);
printf("Operaciones miembro = %d\\n", total_miembro);
printf("Operaciones insercion= %d\\n", total_insercion);
printf("Operaciones borrado= %d\\n", total_borrado);
Free_list();
pthread_mutex_destroy(&mutex);
pthread_mutex_destroy(&count_mutex);
free(thread_handles);
return 0;
}
void Usage(char* prog_name) {
fprintf(stderr, "usage: %s <num_hilos>\\n", prog_name);
exit(0);
}
void Get_input(int* inserts_in_main_p) {
printf("Número de claves a insertar:\\n");
scanf("%d", inserts_in_main_p);
printf("Número total de operaciones:\\n");
scanf("%d", &total_ops);
printf("Porcentaje de operaciones de búsqueda:\\n");
scanf("%lf", &search_percent);
printf("Porcentaje de operaciones de inserción:\\n");
scanf("%lf", &insert_percent);
delete_percent = 1.0 - (search_percent + insert_percent);
}
int Insert(int value) {
struct list_node_s* curr = head;
struct list_node_s* pred = 0;
struct list_node_s* temp;
int rv = 1;
while (curr != 0 && curr->data < value) {
pred = curr;
curr = curr->next;
}
if (curr == 0 || curr->data > value) {
temp = malloc(sizeof(struct list_node_s));
temp->data = value;
temp->next = curr;
if (pred == 0)
head = temp;
else
pred->next = temp;
} else {
rv = 0;
}
return rv;
}
void Print(void) {
struct list_node_s* temp;
printf("lista = ");
temp = head;
while (temp != (struct list_node_s*) 0) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\\n");
}
int Member(int value) {
struct list_node_s* temp;
temp = head;
while (temp != 0 && temp->data < value)
temp = temp->next;
if (temp == 0 || temp->data > value) {
return 0;
} else {
return 1;
}
}
int Delete(int value) {
struct list_node_s* curr = head;
struct list_node_s* pred = 0;
int rv = 1;
while (curr != 0 && curr->data < value) {
pred = curr;
curr = curr->next;
}
if (curr != 0 && curr->data == value) {
if (pred == 0) {
head = curr->next;
free(curr);
} else {
pred->next = curr->next;
free(curr);
}
} else {
rv = 0;
}
return rv;
}
void Free_list(void) {
struct list_node_s* current;
struct list_node_s* following;
if (Is_empty()) return;
current = head;
following = current->next;
while (following != 0) {
free(current);
current = following;
following = current->next;
}
free(current);
}
int Is_empty(void) {
if (head == 0)
return 1;
else
return 0;
}
void* Thread_work(void* rank) {
long my_rank = (long) rank;
int i, val;
double which_op;
unsigned seed = my_rank + 1;
int my_member=0, my_insert=0, my_delete=0;
int ops_per_thread = total_ops/num_hilos;
for (i = 0; i < ops_per_thread; i++) {
which_op = my_drand(&seed);
val = my_rand(&seed) % MAX_KEY;
if (which_op < search_percent) {
pthread_mutex_lock(&mutex);
Member(val);
pthread_mutex_unlock(&mutex);
my_member++;
} else if (which_op < search_percent + insert_percent) {
pthread_mutex_lock(&mutex);
Insert(val);
pthread_mutex_unlock(&mutex);
my_insert++;
} else {
pthread_mutex_lock(&mutex);
Delete(val);
pthread_mutex_unlock(&mutex);
my_delete++;
}
}
pthread_mutex_lock(&count_mutex);
total_miembro += my_member;
total_insercion += my_insert;
total_borrado += my_delete;
pthread_mutex_unlock(&count_mutex);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex_lock;
static int count = 0;
void *test_func(void *arg)
{
int i = 0;
for(i = 0; i < 2000000; i++)
{
pthread_mutex_lock(&mutex_lock);
count++;
pthread_mutex_unlock(&mutex_lock);
}
return 0;
}
int main(int argc, const char *argv[])
{
struct timeval tv1, tv2;
gettimeofday(&tv1, 0);
printf("main %ld,%ld\\n", tv1.tv_sec, tv1.tv_usec);
pthread_mutex_init(&mutex_lock, 0);
pthread_t thread_ids[10];
int i = 0;
for(i = 0; i < sizeof(thread_ids)/sizeof(pthread_t); i++)
{
pthread_create(&thread_ids[i], 0, test_func, 0);
}
for(i = 0; i < sizeof(thread_ids)/sizeof(pthread_t); i++)
{
pthread_join(thread_ids[i], 0);
}
gettimeofday(&tv2, 0);
printf("main %ld,%ld, count = %d\\n", tv2.tv_sec, tv2.tv_usec, count);
return 0;
}
| 1
|
#include <pthread.h>
enum { MAX_THREADS = 3 };
enum { MAX_CYCLES = 5 };
enum { T_UNSTARTED, T_RUNNING, T_FINISHED, T_JOINED };
static int n_threads = MAX_THREADS;
static int n_cycles = MAX_CYCLES;
static pthread_mutex_t mtx_waiting = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cnd_waiting = PTHREAD_COND_INITIALIZER;
static int num_waiting = 0;
static int cycle = -1;
static pthread_mutex_t mtx_state = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cnd_state = PTHREAD_COND_INITIALIZER;
static int *arr_state = 0;
static int num_unjoined = 0;
static float gl_rand = 0;
static long gl_long = 0;
static float next_iteration_random_number(int tid, int iteration)
{
pthread_mutex_lock(&mtx_waiting);
assert(cycle == iteration || cycle == iteration - 1);
num_waiting++;
err_remark("-->> TID %d, I = %d (C = %d, W = %d)\\n",
tid, iteration, cycle, num_waiting);
while (cycle != iteration && num_waiting != n_threads)
{
assert(num_waiting > 0 && num_waiting <= n_threads);
err_remark("-CW- TID %d, I = %d (C = %d, W = %d)\\n",
tid, iteration, cycle, num_waiting);
pthread_cond_wait(&cnd_waiting, &mtx_waiting);
}
assert(cycle == iteration || num_waiting == n_threads);
err_remark("---- TID %d, I = %d (C = %d, W = %d)\\n",
tid, iteration, cycle, num_waiting);
if (cycle != iteration)
{
gl_long = lrand48();
gl_rand = (float)gl_long;
num_waiting = 0;
cycle = iteration;
err_remark("---- TID %d generates cycle %d: L = %ld, F = %g\\n",
tid, cycle, gl_long, gl_rand);
pthread_cond_broadcast(&cnd_waiting);
}
err_remark("<<-- TID %d, I = %d (C = %d, W = %d) L = %ld, F = %g\\n",
tid, iteration, cycle, num_waiting, gl_long, gl_rand);
pthread_mutex_unlock(&mtx_waiting);
return gl_rand;
}
static void *thread_function(void *vp)
{
int tid = (int)(uintptr_t)vp;
for (int i = 0; i < n_cycles; i++)
{
float f = next_iteration_random_number(tid, i);
struct timespec rq;
rq.tv_sec = 0;
rq.tv_nsec = (((gl_long & 0xFF) + (0xF * tid))) % 200 * 50000000;
assert(rq.tv_nsec >= 0 && rq.tv_nsec < 10000000000);
err_remark("TID %d at work: I = %d, F = %g, t = 0.%06d\\n",
tid, i, f, (int)(rq.tv_nsec / 1000));
fflush(stdout);
nanosleep(&rq, 0);
}
pthread_mutex_lock(&mtx_state);
arr_state[tid] = T_FINISHED;
pthread_cond_signal(&cnd_state);
err_remark("TID %d finished\\n", tid);
pthread_mutex_unlock(&mtx_state);
return 0;
}
static const char usestr[] = "[-n threads][-c cycles]";
static const char optstr[] = "c:hn:";
static const char hlpstr[] =
" -c cycles Number of iterations (default 5)\\n"
" -h Print this help and exit\\n"
" -n threads Number of threads (default 3)\\n"
;
int main(int argc, char **argv)
{
err_setarg0(argv[0]);
int opt;
while ((opt = getopt(argc, argv, optstr)) != -1)
{
switch (opt)
{
case 'c':
n_cycles = atoi(optarg);
if (n_cycles < 1)
err_error("number of cycles '%s' should be at least 1\\n", optarg);
break;
case 'n':
n_threads = atoi(optarg);
if (n_threads < 1)
err_error("number of threads '%s' should be at least 1\\n", optarg);
break;
case 'h':
err_help(usestr, hlpstr);
default:
err_usage(usestr);
}
}
if (optind != argc)
err_usage(usestr);
printf("Threads = %d, Cycles = %d\\n", n_threads, n_cycles);
arr_state = calloc(n_threads, sizeof(int));
if (arr_state == 0)
err_syserr("Out of memory");
err_setlogopts(ERR_NOARG0|ERR_MICRO);
err_stderr(stdout);
err_settimeformat("%H:%M:%S");
pthread_t thread[n_threads];
for (int i = 0; i < n_threads; i++)
{
int rc = pthread_create(&thread[i], 0, thread_function, (void *)(uintptr_t)i);
if (rc != 0)
{
errno = rc;
err_stderr(stderr);
err_syserr("failed to create TID %d", i);
}
pthread_mutex_lock(&mtx_state);
arr_state[i] = T_RUNNING;
num_unjoined++;
pthread_mutex_unlock(&mtx_state);
}
pthread_mutex_lock(&mtx_state);
err_remark("Main thread waiting for children to signal\\n");
while (num_unjoined > 0)
{
pthread_cond_wait(&cnd_state, &mtx_state);
for (int i = 0; i < n_threads; i++)
{
if (arr_state[i] == T_FINISHED)
{
void *vp;
int rc = pthread_join(thread[i], &vp);
if (rc != 0)
{
errno = rc;
err_stderr(stderr);
err_syserr("Failed to join TID %d", i);
}
num_unjoined--;
arr_state[i] = T_JOINED;
err_remark("TID %d returned %p\\n", i, vp);
}
}
}
pthread_mutex_unlock(&mtx_state);
return 0;
}
| 0
|
#include <pthread.h>
int num_iteraciones;
int max_bucket;
int count_bucket;
pthread_mutex_t lock;
pthread_cond_t bearAsleep, bearAwake;
void startProduce(){
pthread_mutex_lock(&lock);
while(count_bucket==count_bucket){
pthread_cond_wait(&bearAsleep,&lock);
}
++count_bucket;
pthread_mutex_unlock(&lock);
}
void doneProduce(){
pthread_mutex_lock(&lock);
if(count_bucket==max_bucket){
pthread_cond_signal(&bearAwake);
}
pthread_mutex_unlock(&lock);
}
void startEat(){
pthread_mutex_lock(&lock);
while (count_bucket==0) {
pthread_cond_wait(&bearAwake,&lock);
}
count_bucket=0;
pthread_mutex_unlock(&lock);
}
void endEat(){
pthread_mutex_lock(&lock);
if (count_bucket==0) {
pthread_cond_broadcast(&bearAsleep);
}
pthread_mutex_unlock(&lock);
}
void *Oso(void *id) {
long tid = (long)id;
int i;
for (i=0; i<num_iteraciones; i++){
printf("Estancion %d\\n",i+1);
printf("Oso quiere comer\\n");
startEat();
sleep(rand()%5);
printf("Oso termino de comer\\n");
endEat();
sleep(rand()%5);
}
pthread_exit(0);
}
void *Abeja(void *id) {
long tid = (long)id;
while(1) {
printf("Abeja %ld quiere producir\\n",tid+1);
startProduce();
printf("Abeja %ld produciendo %d de %d\\n", tid+1,count_bucket,max_bucket);
sleep(rand()%5);
printf("Abeja %ld termino de producir\\n",tid+1);
doneProduce();
sleep(rand()%5);
}
pthread_exit(0);
}
int main(int argc, char *argv[]) {
long i=1;
if (argc != 4) {
printf("Uso correcto: %s num-abejas capacidad-del-balde num_iteraciones\\n", argv[0]);
exit(1);
}
int num_bee =atoi(argv[1]);
max_bucket = atoi(argv[2]);
num_iteraciones = atoi(argv[3]);
count_bucket=0;
pthread_t bear;
pthread_t bee[num_bee];
if (num_bee <= 0) {
printf("num-abejas debe ser mayor que 0");
exit(1);
}
if (max_bucket < 0) {
printf("capacidad-del-balde debe ser mayor que 0");
exit(1);
}
if (num_iteraciones < 0) {
printf("num_iteraciones debe ser mayor que 0");
exit(1);
}
srand(time(0));
printf("main(): creando thread Oso\\n");
if (pthread_create(&bear, 0, Oso, (void *)i)) {
printf("Error creando thread oso[%ld]\\n", i);
exit(1);
}
printf("main(): creando threads abejas\\n");
for (i=0; i<num_bee; i++) {
if (pthread_create(&bee[i], 0, Abeja, (void *)i)) {
printf("Error creando thread abeja[%ld]\\n", i);
exit(1);
}
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
void *find_words(void*);
int map_reduce(int number_threads, char *string, struct list *list);
int main(void) {
char *string;
int cur_time, i, j;
struct list *list;
struct stat *buf;
buf = (struct stat *) malloc(sizeof(struct stat));
stat("./Don_Quixote.txt", buf);
int fd = open("./Don_Quixote.txt", O_RDONLY);
string = (char *)malloc(sizeof(char) * buf->st_size);
read(fd, string, buf->st_size);
list = (struct list *)malloc(sizeof(struct list));
for(j = 2; j < 4; ++j) {
list_init(list);
cur_time = clock();
map_reduce(j, string, list);
cur_time = clock() - cur_time;
printf("%d\\n\\n", cur_time);
for(i = 0; i < list->current_length; ++i)
free(list->head[i]);
list_destroy(list);
}
free(string);
free(list);
exit(0);
}
int is_separator(char *simbol, char *separators) {
while(*separators != 0) {
if(*simbol == *separators)
return 1;
++separators;
}
return 0;
}
void *find_words(void *arg) {
struct list *list;
char *begin, *end;
char *new_begin, *new_str;
int i, is_unique;
void **pointer;
pointer = (void **)arg;
list = (struct list *)(pointer[0]);
begin = (char *)(pointer[1]);
end = (char *)(pointer[2]);
while(begin != end) {
while(begin <= end && is_separator(begin, " ,.?!"))
++begin;
if(begin > end)
return 0;
new_begin = begin;
while(new_begin <= end && !is_separator(new_begin, " ,.?!"))
++new_begin;
--new_begin;
pthread_mutex_lock(list->mutex);
is_unique = 0;
for(i = 0; i < list->current_length; ++i) {
if(strncmp(list->head[i], begin, new_begin - begin + 1) == 0) {
is_unique = 1;
break;
}
}
if(is_unique == 0) {
new_str = (char *)malloc(sizeof(char) * (new_begin - begin + 2));
memcpy(new_str, begin, new_begin - begin + 1);
new_str[new_begin - begin + 1] = '\\0';
list_add(list, new_str);
}
pthread_mutex_unlock(list->mutex);
usleep(1000);
begin = new_begin + 1;
}
pthread_exit(0);
}
int map_reduce(int number_threads, char *string, struct list *list) {
int length, delta_length, i, begin_offset, end_offset, cur_pthread;
void ***arg;
pthread_t *pthreads;
pthreads = (pthread_t *)malloc(sizeof(pthread_t)*number_threads);
arg = (void ***)malloc(sizeof(void *) * number_threads);
length = strlen(string);
delta_length = length / number_threads;
begin_offset = 0;
cur_pthread = 0;
for(i = 0; i < number_threads; ++i) {
if(i == number_threads - 1)
end_offset = length;
else {
end_offset = delta_length * (i + 1);
while(end_offset >= begin_offset && !is_separator(string + end_offset, " ,.?!"))
--end_offset;
}
if(end_offset >= begin_offset) {
arg[cur_pthread] = (void **)malloc(sizeof(void *) * 3);
arg[cur_pthread][0] = list;
arg[cur_pthread][1] = string + begin_offset;
arg[cur_pthread][2] = string + end_offset - 1;
pthread_create((pthreads + cur_pthread), 0, find_words, (void*)(arg[cur_pthread]));
++cur_pthread;
}
begin_offset = end_offset;
}
for(i = 0; i < cur_pthread; ++i) {
pthread_join(pthreads[i], 0);
free(arg[i]);
}
free(pthreads);
free(arg);
return 0;
}
static pthread_cond_t c = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
static void *th_waiters(void *arg)
{
pthread_mutex_lock(&m);
while (! isend) {
pthread_cond_wait(&c, &m);
count++;
}
pthread_mutex_unlock(&m);
return arg;
}
static void *th_signal(void *arg)
{
while (! isend)
pthread_cond_signal(&c);
return arg;
}
static void test_exec(void)
{
int i;
pthread_t *t;
count = 0;
t = malloc(sizeof(*t) * nproc);
for (i = 0; i < nproc-1; i++)
pthread_create(&t[i], 0, th_waiters, 0);
pthread_create(&t[i], 0, th_signal, 0);
for (i = 0; i < nproc; i++)
pthread_join(t[i], 0);
free(t);
}
static void test_print_results(int sig)
{
isend = 1;
print_results();
pthread_cond_broadcast(&c);
}
| 0
|
#include <pthread.h>
const int mul_a[8] = {2769, 4587, 8761, 9031, 6743, 7717, 9913, 8737};
const int add_b[8] = {767, 1657, 4057, 8111, 11149, 11027, 9901, 6379};
void *bloomThread(void *args)
{
struct sharedData* sd = (struct sharedData *)args;
int tid = sd->threadid;
struct Bloom* bloom = sd->b;
int x, opt;
int i;
char filename[sizeof "file100.txt"];
sprintf(filename, "file%03d.txt", tid);
FILE *fp = fopen(filename,"r");
struct hashData* hdata = (struct hashData*)malloc(sizeof(struct hashData));
hdata->bloom = sd->b;
int arr[NUM_OF_HASH];
hdata->arr = arr;
while (fscanf(fp, "%d %d\\n",&opt, &x) == 2)
{ pthread_t threads[NUM_OF_HASH];
for( i = 0 ; i < NUM_OF_HASH ; i++ )
{
hdata->tid = i;
hdata->x = x;
int rc = pthread_create(&threads[i], 0, hashCalculate, (void *)hdata);
if (rc){
printf("ERROR; return code from pthread_create() is %d\\n in main", rc);
exit(-1);
}
}
for( i = 0 ; i < NUM_OF_HASH ; i++ ) {
pthread_join(threads[i],0);
}
modifyHash(arr);
sortHashes(arr);
if(opt){
insertHash(arr, bloom);
}
else
{
if(findHash(arr, bloom)){
printf("%d may be present\\n",x);
FILE *fp = fopen("results2.txt","a");
fprintf(fp, "may be present :%d\\n",x);
fclose(fp);
}
else
continue;
}
}
free(hdata);
fclose(fp);
free(sd);
pthread_exit(0);
}
void sortHashes(int a[]){
int i,j, temp;
for(i=0;i< NUM_OF_HASH/2;i++){
for(j=0;j<NUM_OF_HASH/2;j++){
if(a[i]<a[j])
{ temp = a[i];
a[i] =a[j];
a[j] = temp;
temp = a[i+NUM_OF_HASH/2];
a[i+NUM_OF_HASH/2] =a[j+NUM_OF_HASH/2];
a[j+NUM_OF_HASH/2] = temp;
}
}
}
}
void* hashCalculate(void* hdata){
int m;
struct hashData* hd = (struct hashData*)hdata;
int id = hd->tid;
if(id<(NUM_OF_HASH/2))
m = BLOOM_SIZE;
else
m = W;
hd->arr[id] = (mul_a[id]*hd->x + add_b[id])%m;
if(hd->arr[id] < 0)
hd->arr[id]*=-1;
pthread_exit(0);
}
void getLocks(int a[], struct Bloom* b){
int i,j,d;
for(i =1; i<NUM_OF_HASH;i++){
d = a[i]/32;
pthread_mutex_lock(&(b->mutexArr[d]));
}
}
void releaseLocks(int a[], struct Bloom* b){
int i,j;
for(i =0; i<NUM_OF_HASH;i++){
int d = a[i]/32;
pthread_mutex_unlock(&(b->mutexArr[d]));
}
}
void insertHash(int a[], struct Bloom* b){
int i,m,d;
getLocks(a,b);
for(i =0; i<NUM_OF_HASH;i++){
d = a[i]/32;
m = a[i]%32;
if((b->bit[d]&(1<<m)) > 0)
continue;
else
b->bit[d] = (b->bit[d] | (1<<m));
}
releaseLocks(a,b);
}
int findHash(int a[], struct Bloom* b){
int i,j =1, d,m;
for(i =0; i<NUM_OF_HASH;i++){
d = a[i]/32;
m = a[i]%32;
if((b->bit[d]&(1<<m)) > 0)
continue;
else
j= 0;
}
return j;
}
void modifyHash(int a[]){
int i,j =0;
for(i =0; i<NUM_OF_HASH/2;i++){
j+=NUM_OF_HASH/2 + i;
a[j]+=a[i];
int u = (int)(a[i]/W +0.999999999);
if(a[j]>u)
a[j] - W;
}
}
| 1
|
#include <pthread.h>
int kuz;
pthread_mutex_t zain = PTHREAD_MUTEX_INITIALIZER;
void* suma(void*arg)
{
for(int i=0;i<10000;++i)
{
pthread_mutex_lock(&zain);
kuz= kuz +1;
pthread_mutex_unlock(&zain);
}
pthread_exit(0);
}
void* resta(void*arg)
{
for(int i=0;i<10000;++i)
{
pthread_mutex_lock(&zain);
kuz= kuz-1;
pthread_mutex_unlock(&zain);
}
pthread_exit(0);
}
int main()
{
kuz =0;
pthread_t* tids= (pthread_t*)malloc(2*sizeof(pthread_t));
pthread_create((tids),0,suma,0);
pthread_create((tids+1),0,resta,1);
pthread_join(*(tids),0);
pthread_join(*(tids+1),0);
printf("valor final de kuz ocn mutex : %d\\n",kuz);
return 0;
}
| 0
|
#include <pthread.h>
static short LOCK_INIT = 0;
static pthread_mutex_t lock;
static void init_serial_lock()
{
if (pthread_mutex_init(&lock, 0) != 0)
{
LOGGER(LOG_CRIT,"\\n mutex init failed\\n");
}
else
LOCK_INIT = 1;
}
void destroy_serial_lock()
{
if (pthread_mutex_destroy(&lock) != 0)
LOGGER(LOG_INFO,"can't destroy rwlock");
else
LOCK_INIT = 0;
}
void read_serial_lock()
{
if (!LOCK_INIT)
init_serial_lock();
pthread_mutex_lock(&lock);
}
void write_serial_lock()
{
if (!LOCK_INIT)
init_serial_lock();
if (pthread_mutex_lock(&lock) != 0)
LOGGER(LOG_INFO,"can't get rdlock");
}
void serial_unlock()
{
pthread_mutex_unlock(&lock);
}
void gecko_clean_up()
{
close(tty_fd);
stop_reader_thread();
destroy_serial_lock();
destroy_lock();
delete_all_node();
close_log();
}
void signal_callback_handler(int signum)
{
LOGGER(LOG_DEBUG,"\\nCaught signal %d\\n", signum);
gecko_clean_up();
exit(signum);
}
void read_display_current_configuration(int fd)
{
struct termios tio;
memset(&tio, 0, sizeof(tio));
tcgetattr(fd, &tio);
LOGGER(LOG_DEBUG,"\\nsize tio.c_cflag :%d", sizeof(tio.c_cflag));
LOGGER(LOG_DEBUG,"\\nsize tio.c_cflag :%d", sizeof(tio.c_cflag));
LOGGER(LOG_DEBUG,"c_cflag :%d", tio.c_cflag);
LOGGER(LOG_DEBUG,"c_iflag :%d", tio.c_iflag);
LOGGER(LOG_DEBUG,"c_ispeed :%d", tio.c_ispeed);
LOGGER(LOG_DEBUG,"c_oflag :%d", tio.c_oflag);
LOGGER(LOG_DEBUG,"c_ospeed :%d", tio.c_ospeed);
}
int gecko_start_serial_service(char * port)
{
init_serial_lock();
struct sigaction saio;
saio.sa_handler = signal_callback_handler;
sigemptyset(&saio.sa_mask);
saio.sa_flags = 0;
saio.sa_restorer = 0;
sigaction(SIGINT, &saio, 0);
LOGGER(LOG_DEBUG,"Using port %s", port);
int fd = open_serial_port(port);
if (fd == -1)
{
LOGGER(LOG_ERR,"error in open device %s",port);
return 1;
}
if (configure_serial_port(fd) != -1)
{
if(LOG_LEVEL==LOG_DEBUG)
read_display_current_configuration(fd);
serial_write(fd, START_SCAN);
LOGGER(LOG_DEBUG,"send start scan command to serial device\\n");
start_serial_reader_thread(fd);
}
else
{
LOGGER(LOG_CRIT,"Error in opening serial port\\n");
perror("error in configuring port");
}
return 0;
}
void show_mem_rep(char *start, int n)
{
int i;
for (i = 0; i < n; i++)
LOGGER(LOG_DEBUG," %.2x", start[i]);
LOGGER(LOG_DEBUG,"\\n");
}
int test_main()
{
return 0;
}
| 1
|
#include <pthread.h>
int buffer[2];
int size;
int error;
pthread_mutex_t lock;
pthread_t threads[1 + 1];
void * produce (void *arg) {
int i;
for(i = 0; i < 5; i++) {
pthread_mutex_lock(&lock);
size++;
pthread_mutex_unlock(&lock);
}
return 0;
}
void * consume (void *arg) {
int i;
for(i = 0; i < 5; i++) {
pthread_mutex_lock(&lock);
if (size > 0) {
size--;
}
pthread_mutex_unlock(&lock);
}
return 0;
}
void setup() {
int i, err;
size = 0;
if (pthread_mutex_init(&lock, 0) != 0)
printf("\\n mutex init failed\\n");
for (i = 0; i < 1; i++) {
err = pthread_create(&threads[i], 0, produce, 0);
if (err != 0)
printf("\\ncan't create thread :[%s]", strerror(err));
}
for (i = 0; i < 1; i++) {
err = pthread_create(&threads[i+1], 0, consume, 0);
if (err != 0)
printf("\\ncan't create thread :[%s]", strerror(err));
}
}
int run() {
int i;
for (i = 0; i < 1 +1; i++)
pthread_join(threads[i], 0);
return (size >= 0 && size <= 2);
}
int main() {
setup();
return !run();
}
| 0
|
#include <pthread.h>
sem_t full;
sem_t empty;
pthread_mutex_t m;
int buf[10]={0};
int n=0;
int print()
{
int i;
for(i=0;i<10;i++)
printf("%d ",buf[i]);
printf("\\n");
return 0;
}
void *producter(void* p)
{
int i;
for(i=0;i<20;i++)
{
sem_wait(&empty);
pthread_mutex_lock(&m);
buf[n++]=1;
printf("%d生产了第%d个产品\\n",pthread_self(),n-1);
print();
pthread_mutex_unlock(&m);
sem_post(&full);
sleep(1);
}
pthread_exit((void*)0);
}
void *consumer(void* p)
{
int i;
for(i=0;i<20;i++)
{
sem_wait(&full);
pthread_mutex_lock(&m);
buf[--n]=0;
printf("%d消费了第%d个产品\\n",pthread_self(),n);
print();
pthread_mutex_unlock(&m);
sem_post(&empty);
sleep(2);
}
pthread_exit((void*)0);
}
int main()
{
memset(buf,0,sizeof(buf));
pthread_t pid1,pid2,cid1,cid2;
sem_init(&empty,0,10);
sem_init(&full,0,0);
pthread_mutex_init(&m,0);
pthread_create(&pid1,0,producter,0);
pthread_create(&cid1,0,consumer,0);
pthread_create(&pid2,0,producter,0);
pthread_create(&cid2,0,consumer,0);
pthread_join(pid1,0);
pthread_join(pid2,0);
pthread_join(cid1,0);
pthread_join(cid2,0);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t globalmutex=PTHREAD_MUTEX_INITIALIZER;
static _getenvType __getenv=0;
static void __loadsymbol(void)
{
const char *err=0;
pthread_mutex_lock(&globalmutex);
if(__getenv) {pthread_mutex_unlock(&globalmutex); return;}
dlerror();
__getenv=(_getenvType)dlsym(RTLD_NEXT, "getenv");
err=dlerror();
if(err) fprintf(stderr, "[gefaker] %s\\n", err);
else if(!__getenv) fprintf(stderr, "[gefaker] Could not load symbol.\\n");
pthread_mutex_unlock(&globalmutex);
}
char *getenv(const char *name)
{
char *env=0; int verbose=0;
__loadsymbol();
if(!__getenv) return 0;
if((env=__getenv("VGL_VERBOSE"))!=0 && strlen(env)>0
&& !strncmp(env, "1", 1)) verbose=1;
if(name && (!strcmp(name, "LD_PRELOAD")
))
{
if(verbose)
fprintf(stderr, "[VGL] NOTICE: Fooling application into thinking that LD_PRELOAD is unset\\n");
return 0;
}
else return __getenv(name);
}
| 0
|
#include <pthread.h>
int memory[(2*960+1)];
int next_alloc_idx = 1;
pthread_mutex_t m;
int top;
int index_malloc(){
int curr_alloc_idx = -1;
pthread_mutex_lock(&m);
if(next_alloc_idx+2-1 > (2*960+1)){
pthread_mutex_unlock(&m);
curr_alloc_idx = 0;
}else{
curr_alloc_idx = next_alloc_idx;
next_alloc_idx += 2;
pthread_mutex_unlock(&m);
}
return curr_alloc_idx;
}
void EBStack_init(){
top = 0;
}
int isEmpty() {
if(top == 0)
return 1;
else
return 0;
}
int push(int d) {
int oldTop = -1, newTop = -1;
newTop = index_malloc();
if(newTop == 0){
return 0;
}else{
memory[newTop+0] = d;
while (1) {
oldTop = top;
memory[newTop+1] = oldTop;
if(__sync_bool_compare_and_swap(&top,oldTop,newTop)){
return 1;
}
}
}
}
void __VERIFIER_atomic_assert(int r)
{
__atomic_begin();
assert(!r || !isEmpty());
__atomic_end();
}
void push_loop(){
int r = -1;
int arg = __nondet_int();
while(1){
r = push(arg);
__VERIFIER_atomic_assert(r);
}
}
pthread_mutex_t m2;
int state = 0;
void* thr1(void* arg)
{
pthread_mutex_lock(&m2);
switch(state)
{
case 0:
EBStack_init();
state = 1;
case 1:
pthread_mutex_unlock(&m2);
push_loop();
break;
}
return 0;
}
int main()
{
pthread_t t1,t2;
pthread_create(&t1, 0, thr1, 0);
pthread_create(&t2, 0, thr1, 0);
return 0;
}
| 1
|
#include <pthread.h>
int pega_talheres(int id, int num_esquerdo, int num_direito);
void devolve_talheres(int num_esquerdo, int num_direito);
void pega_token();
void devolve_token();
void *filosofo(void *num);
int NUM_FILOSOFOS;
unsigned TMP_COMENDO;
unsigned TMP_PENSANDO;
int NUM_TOKENS;
int COMIDA_NA_MESA;
pthread_mutex_t LOCK_NUM_TOKENS;
pthread_mutex_t *TALHERES;
void pega_token() {
int ret = 0;
while (!ret) {
pthread_mutex_lock(&LOCK_NUM_TOKENS);
if (NUM_TOKENS > 0) {
NUM_TOKENS--;
ret = 1;
}
else {
ret = 0;
}
pthread_mutex_unlock(&LOCK_NUM_TOKENS);
usleep(100);
}
}
void devolve_token(){
pthread_mutex_lock(&LOCK_NUM_TOKENS);
NUM_TOKENS++;
pthread_mutex_unlock(&LOCK_NUM_TOKENS);
}
int pega_talheres(int id, int num_esquerdo, int num_direito) {
pthread_mutex_lock(&TALHERES[num_esquerdo]);
printf("\\nTalher %d pego pelo filósofo %d.", num_esquerdo, id);
pthread_mutex_lock(&TALHERES[num_direito]);
printf("\\nTalher %d pego pelo filósofo %d.", num_direito, id);
return 1;;
}
void devolve_talheres(int num_esquerdo, int num_direito) {
pthread_mutex_unlock(&TALHERES[num_esquerdo]);
pthread_mutex_unlock(&TALHERES[num_direito]);
}
void *filosofo(void *num) {
int id = (int)num;
int alimentado = 0;
int talher_esquerdo, talher_direito;
talher_esquerdo = id;
talher_direito = id+1;
if (talher_direito == NUM_FILOSOFOS) {
talher_direito = 0;
}
while(COMIDA_NA_MESA) {
printf("\\nFilósofo %d está pronto pra comer.", id);
pega_token();
printf("\\nFilósofo %d sentou-se à mesa. (token %d)", id, NUM_TOKENS);
pega_talheres(id, talher_esquerdo, talher_direito);
printf("\\nFilósofo %d começou a comer... (talheres %d, %d)", id, talher_esquerdo, talher_direito);
usleep(TMP_COMENDO * 1000);
alimentado += TMP_COMENDO / 100;
printf("\\nFilósofo %d terminou de comer. Total ingerido: %dg", id, alimentado);
devolve_talheres(talher_esquerdo, talher_direito);
devolve_token();
printf("\\nFilósofo %d levantou-se para pensar...", id);
usleep(TMP_PENSANDO * 1000);
}
printf("\\nFilósofo %d acabou de comer.", id);
return (void *) 0;
}
int main(void) {
int i;
printf("\\n*** Problema do Jantar dos Filosofos ***\\n"
"*** Trabalho 2 de SO1 ***\\n"
"Solucao de N-1 Tokens\\n");
printf("\\nNumero filosofos: ");
scanf("%d", &NUM_FILOSOFOS);
printf("Tempo comendo (ms): ");
scanf("%d", &TMP_COMENDO);
printf("Tempo pensando (ms): ");
scanf("%d", &TMP_PENSANDO);
COMIDA_NA_MESA = 1;
NUM_TOKENS = NUM_FILOSOFOS-1;
pthread_t filosofos[NUM_FILOSOFOS];
TALHERES = malloc(sizeof(pthread_mutex_t) * NUM_FILOSOFOS);
pthread_mutex_init(&LOCK_NUM_TOKENS, 0);
for (i=0; i < NUM_FILOSOFOS; i++) {
pthread_mutex_init(&TALHERES[i], 0);
}
for (i=0; i < NUM_FILOSOFOS; i++) {
pthread_create(&filosofos[i], 0, filosofo, (void *) i);
}
for (i=0; i < NUM_FILOSOFOS; i++) {
pthread_join(filosofos[i], 0);
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t request_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
pthread_cond_t got_job_request = PTHREAD_COND_INITIALIZER;
int num_requests = 0;
int done_creating_jobRequests = 0;
struct arg_structure
{
int arg1;
int arg2;
};
struct Job
{
int job_id;
struct Job* next_job;
struct arg_structure* args;
void (*function)(void* arg);
};
struct Job* jobs_list = 0;
struct Job* last_job = 0;
void add_job_request(int p_num_job,
void (*p_function)(void*),
void* p_arg,
pthread_cond_t* p_condition_var,
pthread_mutex_t* p_mutex)
{
struct Job* a_new_job;
struct arg_structure *args = p_arg;
a_new_job = (struct Job*) malloc(sizeof(struct Job));
if (a_new_job == 0)
{
fprintf(stderr, "add_job_request() : No hay más memoria\\n");
exit(1);
}
a_new_job -> job_id = p_num_job;
a_new_job -> next_job = 0;
a_new_job -> function = p_function;
a_new_job -> args = args;
int rc;
rc = pthread_mutex_lock(p_mutex);
if (num_requests == 0)
{
jobs_list = a_new_job;
last_job = a_new_job;
}
else
{
last_job -> next_job = a_new_job;
last_job = a_new_job;
}
num_requests ++;
rc = pthread_mutex_unlock(p_mutex);
rc = pthread_cond_signal(p_condition_var);
}
struct Job* get_job_request(pthread_mutex_t* p_mutex)
{
struct Job* the_job;
int rc;
rc = pthread_mutex_lock(p_mutex);
if (num_requests > 0)
{
the_job = jobs_list;
jobs_list = the_job -> next_job;
if (jobs_list == 0)
{
last_job = 0;
}
num_requests -- ;
}
else
{
the_job = 0;
}
rc = pthread_mutex_unlock(p_mutex);
return the_job;
}
void doJob(struct Job* p_Job_to_do, int p_thread_ID)
{
if (p_Job_to_do)
{
void (*function_buffer)(void*);
void* args_buff;
args_buff = p_Job_to_do -> args;
function_buffer = p_Job_to_do -> function;
function_buffer (args_buff);
printf("Thread '%d' handled request '%d'\\n",p_thread_ID, p_Job_to_do -> job_id);
fflush(stdout);
}
}
void* handle_Job_Requests(void* data)
{
struct Job* a_new_job;
int thread_id = *((int*)data);
int th;
th = pthread_mutex_lock(&request_mutex);
while (1)
{
if (num_requests > 0)
{
a_new_job = get_job_request(&request_mutex);
if (a_new_job)
{
doJob(a_new_job, thread_id);
free(a_new_job);
}
}
else
{
if (done_creating_jobRequests)
{
pthread_mutex_unlock(&request_mutex);
printf("thread '%d' exiting\\n", thread_id);
fflush(stdout);
pthread_exit(0);
}
th = pthread_cond_wait(&got_job_request, &request_mutex);
}
}
}
void* task1(void* p_args)
{
struct arg_structure *args = (struct arg_structure *) p_args;
printf("Hola soy la tarea con parametros: PRIMERO : '%d' SEGUNDO : '%d' ", args -> arg1, args -> arg2);
}
int main(int argc, char* argv[])
{
int i;
int thr_id[3];
pthread_t threadPool[3];
struct timespec delay;
struct arg_structure args;
args.arg1 = 5;
for (i = 0; i < 3; i ++)
{
thr_id[i] = i;
pthread_create(&threadPool[i], 0, handle_Job_Requests, (void*)&thr_id[i]);
}
for (i = 0; i < 10; i ++)
{
add_job_request(i, (void*) task1, (void *)&args, &got_job_request, &request_mutex);
if (rand() > 3*(32767 / 4))
{
delay.tv_sec = 0;
delay.tv_nsec = 1;
nanosleep(&delay, 0);
}
}
{
int rc;
rc = pthread_mutex_lock(&request_mutex);
done_creating_jobRequests = 1;
rc = pthread_cond_broadcast(&got_job_request);
rc = pthread_mutex_unlock(&request_mutex);
}
for (i = 0; i < 3; i ++)
{
void* thr_retval;
pthread_join(threadPool[i], &thr_retval);
}
printf("Glory, we are done.\\n");
return 0;
}
| 1
|
#include <pthread.h>
int N_MAX = 10e7;
int N_THREADS = 4;
int count = 0;
pthread_mutex_t mutex;
void *Average(void *param) {
double mean = 0;
double *ret = malloc(sizeof(double *));
assert(ret);
double *roots = *((double**) param);
long step = N_MAX / N_THREADS;
pthread_mutex_lock(&mutex);
long start = count++ * step;
pthread_mutex_unlock(&mutex);
for(long i = start; i < start + step; i++) {
roots[i] = sqrt(i+1);
mean += roots[i];
}
mean /= step;
*ret = mean;
return ret;
}
void main(int argc, char *argv[]) {
switch (argc) {
case 1:
break;
case 2:
N_THREADS = atoi(argv[1]);
assert(N_THREADS > 0);
break;
case 3:
N_THREADS = atoi(argv[1]);
N_MAX = atoi(argv[2]);
assert(N_THREADS > 0);
assert(N_MAX > 0);
break;
default:
printf("Usage: ./exercicio1 [threads] [numbers]\\n\\n");
printf("threads: number of threads to be used (optional, defaults to 10e8)\\n");
printf("numbers: amount of numbers to calculate (optional, defaults to 4)\\n");
exit(1);
break;
}
double *roots = (double*) malloc(N_MAX * sizeof(double));
double *means = (double*) malloc(N_THREADS * sizeof(double));
double mean = 0;
pthread_t threads[N_THREADS];
void *retval;
pthread_mutex_init(&mutex, 0);
for(int i = 0; i < N_THREADS; i++)
pthread_create(&threads[i], 0, Average, (void *)&roots);
for(int i = 0; i < N_THREADS; i++) {
pthread_join(threads[i], &retval);
means[i] = *(double*)retval;
}
for(int i = 0; i < N_THREADS; i++)
mean += means[i];
mean /= N_THREADS;
printf("Total mean: %f\\n", mean);
free(means);
free(roots);
free(retval);
pthread_mutex_destroy(&mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t m;
void *odd(void *max)
{
int i;
FILE *fd;
struct timeval tp;
fd = fopen("odd_num", "w");
for (i = 1; i < *(int*)max; i+= 2)
fprintf(fd, "%d\\n", i);
pthread_mutex_lock(&m);
for (i = 0; i < 10000; i++)
printf("odd\\n");
pthread_mutex_unlock(&m);
}
void *even(void *max)
{
int i;
FILE *fd;
struct timeval tp;
fd = fopen("even_num", "w");
for (i = 2; i < *(int*)max; i+= 2)
fprintf(fd, "%d\\n", i);
pthread_mutex_lock(&m);
for (i = 0; i < 10000; i++)
printf("even\\n");
pthread_mutex_unlock(&m);
}
main()
{
int max = 50, max1 = 100, max2 = 200, i;
FILE *fd;
pthread_attr_t attr;
pthread_t *th1, *th2;
void *st1, *st2;
size_t sz;
int policy;
struct timeval tp;
pthread_mutex_init(&m, 0);
pthread_attr_init(&attr);
st1 = (void *) malloc(40960);
pthread_attr_setstacksize(&attr, 40960);
pthread_attr_setstack(&attr, st1, 40960);
pthread_attr_getstacksize(&attr, &sz);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS);
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
th1 = (pthread_t *) malloc(sizeof(pthread_t));
if (pthread_create(th1, &attr, odd, &max1)) {
perror("error creating the first thread");
exit(1);
}
printf("created the first thread\\n");
st2 = (void *)malloc(40960);
pthread_attr_setstacksize(&attr, 40960);
pthread_attr_setstack(&attr, st2, 40960);
th2 = (pthread_t *) malloc(sizeof(pthread_t));
if (pthread_create(th2, &attr, even, &max2)) {
perror("error creating the second thread");
exit(1);
}
printf("created the second thread\\n");
fd = fopen("whole_num", "w");
pthread_mutex_lock(&m);
for (i = 0; i < 10000; i++)
printf("main\\n");
pthread_mutex_unlock(&m);
for (i = 1; i < max; i++)
fprintf(fd, "%d\\n", i);
pthread_join(*th1, 0);
pthread_join(*th2, 0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex =PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condizione =PTHREAD_MUTEX_INITIALIZER;
int n=0;
int *a;
float media;
int i=0;
int flag =0;
void *funzione(void*para){
while (i<n){
pthread_mutex_lock(&mutex);
media += a[i];
i++;
pthread_mutex_unlock(&mutex);
}
flag =1;
if(flag==1){
pthread_mutex_lock(&mutex);
pthread_cond_signal(&condizione);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void *funzione2(void*param){
pthread_mutex_lock(&mutex);
while(flag==0){
pthread_cond_wait(&condizione,&mutex);
}
pthread_mutex_unlock(&mutex);
media =media/n;
printf("La media è:%f\\n",media);
pthread_exit(0);
}
int main(int argc, char *argv[]){
if (argc <2){
perror("errore");
exit(1);
}
n=atoi(argv[1]);
if ( !(n%3 ==0) ){
perror("non è multiplo");
exit(1);
}
a = malloc(n*sizeof(int));
for (int i=0;i<n;i++){
a[i]=1+rand()%20;
}
for (int i=0;i<n;i++){
printf("%d\\n",a[i]);
}
pthread_t thread[3];
for(int i=0;i<3;i++){
pthread_create(&thread[i],0,funzione,0);
}
pthread_create(&thread[3],0,funzione2,0);
for(int i=0;i<=3;i++){
pthread_join(thread[i],0);
}
return 0;
}
| 0
|
#include <pthread.h>
struct wonk{
int a;
} *shrdPtr;
pthread_mutex_t lock;
struct wonk *getNewVal(struct wonk**old){
*old = 0;
struct wonk *newval = (struct wonk*)malloc(sizeof(struct wonk));
newval->a = 1;
return newval;
}
void *updaterThread(void *arg){
int i;
for(i = 0; i < 10; i++){
pthread_mutex_lock(&lock);
struct wonk *newval = getNewVal(&shrdPtr);
pthread_mutex_unlock(&lock);
usleep(20);
pthread_mutex_lock(&lock);
shrdPtr = newval;
pthread_mutex_unlock(&lock);
}
}
void swizzle(int *result){
pthread_mutex_lock(&lock);
if(shrdPtr != 0)
{
pthread_mutex_unlock(&lock);
pthread_mutex_lock(&lock);
assert(shrdPtr != 0);
*result += shrdPtr->a;
pthread_mutex_unlock(&lock);
}else{
pthread_mutex_unlock(&lock);
}
}
void *accessorThread(void *arg){
int *result = (int*)malloc(sizeof(int));
*result = 0;
while(*result < 1000){
swizzle(result);
usleep(10 + (rand() % 100) );
}
pthread_exit(result);
}
int main(int argc, char *argv[]){
int res = 0;
shrdPtr= (struct wonk*)malloc(sizeof(struct wonk));
shrdPtr->a = 1;
pthread_mutex_init(&lock,0);
pthread_t acc[4],upd;
pthread_create(&acc[0],0,accessorThread,(void*)shrdPtr);
pthread_create(&acc[1],0,accessorThread,(void*)shrdPtr);
pthread_create(&acc[2],0,accessorThread,(void*)shrdPtr);
pthread_create(&acc[3],0,accessorThread,(void*)shrdPtr);
pthread_create(&upd,0,updaterThread,(void*)shrdPtr);
pthread_join(upd,0);
pthread_join(acc[0],(void**)&res);
pthread_join(acc[1],(void**)&res);
pthread_join(acc[2],(void**)&res);
pthread_join(acc[3],(void**)&res);
fprintf(stderr,"Final value of res was %d\\n",res);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
int cont = 1;
void* helper(void* v_bar) {
pthread_barrier_t* bar = (pthread_barrier_t*)v_bar;
register int* i = malloc(sizeof(*i));
*i = 3;
pthread_barrier_wait(bar);
pthread_mutex_lock(&mu);
while (cont) {
if (*i)
pthread_mutex_unlock(&mu);
sched_yield();
pthread_mutex_lock(&mu);
}
pthread_mutex_unlock(&mu);
free((void *)i);
fprintf(stderr, "Quitting the helper.\\n");
return 0;
}
int main() {
pthread_barrier_t bar;
pthread_barrier_init(&bar, 0, 2);
pthread_t thr;
pthread_create(&thr, 0, &helper, &bar);
pthread_barrier_wait(&bar);
pthread_barrier_destroy(&bar);
fprintf(stderr, "Abandoning the helper.\\n");
pthread_detach(thr);
return 0;
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error() ;
unsigned int __VERIFIER_nondet_uint();
static int top=0;
static unsigned int arr[(400)];
pthread_mutex_t m;
_Bool flag=(0);
void error(void)
{
ERROR: __VERIFIER_error(); return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
return (top==0) ? (1) : (0);
}
int push(unsigned int *stack, int x)
{
if (top==(400))
{
printf("stack overflow\\n");
return (-1);
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (top==0)
{
printf("stack underflow\\n");
return (-2);
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for(i=0; i<(400); i++)
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint()%(400);
if ((push(arr,tmp)==(-1)))
error();
pthread_mutex_unlock(&m);
}
return 0;
}
void *t2(void *arg)
{
int i;
for(i=0; i<(400); i++)
{
pthread_mutex_lock(&m);
if (top>0)
{
if ((pop(arr)==(-2)))
error();
}
pthread_mutex_unlock(&m);
}
return 0;
}
int main(void)
{
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 1
|
#include <pthread.h>
struct heap_block {
void *ptr;
size_t size;
};
struct heap_global {
int initialized;
unsigned int block_count;
unsigned int block_count_size;
pthread_mutex_t mutex;
struct heap_block *blocks;
unsigned int blocks_array_size;
};
static struct heap_global heap_global = {
.initialized = 0,
.block_count = 0,
.block_count_size = 0,
.blocks = 0,
.blocks_array_size = 0,
};
static void initialize_blocks(void)
{
heap_global.blocks = malloc(256 * sizeof(struct heap_block));
heap_global.blocks_array_size = 256;
}
static void grow_blocks(void)
{
unsigned int blocks_array_old_size = heap_global.blocks_array_size;
heap_global.blocks_array_size *= 2;
struct heap_block *new_blocks = calloc(heap_global.blocks_array_size, sizeof(struct heap_block));
memcpy(new_blocks, heap_global.blocks, blocks_array_old_size * sizeof(struct heap_block));
free(heap_global.blocks);
heap_global.blocks = new_blocks;
}
static void shrink_blocks(void)
{
heap_global.blocks_array_size /= 2;
struct heap_block *new_blocks = malloc(heap_global.blocks_array_size * sizeof(struct heap_block));
memcpy(new_blocks, heap_global.blocks, heap_global.blocks_array_size * sizeof(struct heap_block));
free(heap_global.blocks);
heap_global.blocks = new_blocks;
}
static void scale_blocks_if_needed(void)
{
if(heap_global.block_count == heap_global.blocks_array_size)
grow_blocks();
else if(heap_global.block_count == heap_global.blocks_array_size / 2) {
if(heap_global.blocks_array_size != 256)
shrink_blocks();
}
}
static void insert_block(void *ptr, size_t size)
{
unsigned int i;
for(i = 0; i < heap_global.blocks_array_size; i++) {
if(heap_global.blocks[i].ptr == 0) {
heap_global.blocks[i].ptr = ptr;
heap_global.blocks[i].size = size;
heap_global.block_count++;
heap_global.block_count_size += size;
return;
}
}
}
static void erase_block(void *ptr)
{
unsigned int i;
for(i = 0; i < heap_global.blocks_array_size; i++) {
if(heap_global.blocks[i].ptr == ptr) {
heap_global.blocks[i].ptr = 0;
heap_global.block_count--;
heap_global.block_count_size -= heap_global.blocks[i].size;
return;
}
}
}
static void initialize_heap(void)
{
initialize_blocks();
pthread_mutex_init(&heap_global.mutex, 0);
heap_global.initialized = 1;
}
static void lock_heap(void)
{
pthread_mutex_lock(&heap_global.mutex);
}
static void unlock_heap(void)
{
pthread_mutex_unlock(&heap_global.mutex);
}
void *heap_malloc(size_t size)
{
if(heap_global.initialized == 0) {
initialize_heap();
}
scale_blocks_if_needed();
void *ptr = malloc(size);
lock_heap();
insert_block(ptr, size);
unlock_heap();
return ptr;
}
void heap_free(void *ptr)
{
scale_blocks_if_needed();
lock_heap();
erase_block(ptr);
unlock_heap();
free(ptr);
}
unsigned int heap_block_count(void)
{
return heap_global.block_count;
}
unsigned int heap_block_count_bytes(void)
{
return heap_global.block_count_size;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cv = PTHREAD_COND_INITIALIZER;
static int waiting;
static void cleanup(void *p)
{
waiting = 0;
pthread_cond_signal(&cv);
pthread_mutex_unlock(&mx);
}
static void *waiter(void *p)
{
pthread_mutex_lock(&mx);
waiting = 1;
pthread_cond_signal(&cv);
pthread_cleanup_push(cleanup, 0);
while (waiting) pthread_cond_wait(&cv, &mx);
pthread_cleanup_pop(1);
return 0;
}
int main(void)
{
pthread_t td;
struct timespec ts;
void *rv;
pthread_mutex_lock(&mx);
pthread_create(&td, 0, waiter, 0);
while (!waiting) pthread_cond_wait(&cv, &mx);
pthread_cancel(td);
clock_gettime(CLOCK_REALTIME, &ts);
if ((ts.tv_nsec+=30000000) >= 1000000000) {
ts.tv_sec++;
ts.tv_nsec -= 1000000000;
}
while (waiting && !pthread_cond_timedwait(&cv, &mx, &ts));
waiting = 0;
pthread_cond_signal(&cv);
pthread_mutex_unlock(&mx);
pthread_join(td, &rv);
if (rv != PTHREAD_CANCELED)
t_error("pthread_cond_wait did not act on cancellation\\n");
return t_status;
}
| 1
|
#include <pthread.h>
int ticket_no = 1001;
sem_t ticket_counter;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* ticket_buy(){
pthread_mutex_lock(&mutex);
if(sem_trywait(&ticket_counter) == 0){
printf("This customer has bought ticket %d\\n", ticket_no++);
}
else{
printf("This customer could not get a ticket\\n");
}
int value;
sem_getvalue(&ticket_counter, &value);
printf("..Number of berths left: %d\\n", value);
pthread_mutex_unlock(&mutex);
return 0;
}
void* ticket_cancel(){
pthread_mutex_lock(&mutex);
sem_post(&ticket_counter);
printf("One ticket has just been cancelled\\n");
int value;
sem_getvalue(&ticket_counter, &value);
printf("..Number of berths left: %d\\n", value);
pthread_mutex_unlock(&mutex);
return 0;
}
int main(){
sem_init(&ticket_counter, 0, 10);
pthread_t t[20];
pthread_t cancel[3];
int i;
for(i = 0; i < 10; i++){
pthread_create(&t[i], 0, ticket_buy, 0);
}
for(i = 0; i < 3; i++){
pthread_create(&cancel[i], 0, ticket_cancel, 0);
}
for(i = 10; i < 20; i++){
pthread_create(&t[i], 0, ticket_buy, 0);
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock;
int32_t x = 0, y = 0;
void* fast_thread1()
{
pthread_mutex_lock(&lock);
for (uint32_t j = 0; j < 1000000; j++) {
x++;
}
pthread_mutex_unlock(&lock);
return 0;
}
void* fast_thread2()
{
pthread_mutex_lock(&lock);
for (uint32_t j = 0; j < 1000000 - 1; j++) {
x--;
}
pthread_mutex_unlock(&lock);
return 0;
}
void* slow_thread1()
{
for (uint32_t j = 0; j < 1000000; j++) {
pthread_mutex_lock(&lock);
y++;
pthread_mutex_unlock(&lock);
}
return 0;
}
void* slow_thread2()
{
for (uint32_t j = 0; j < 1000000 - 1; j++) {
pthread_mutex_lock(&lock);
y--;
pthread_mutex_unlock(&lock);
}
return 0;
}
int main()
{
clock_t start, diff;
int msec;
pthread_t ft1, ft2, st1, st2;
pthread_mutex_init(&lock, 0);
start = clock();
pthread_create(&ft1, 0, fast_thread1, 0);
pthread_create(&ft2, 0, fast_thread2, 0);
pthread_join(ft1, 0);
pthread_join(ft2, 0);
diff = clock() - start;
msec = diff * 1000 / CLOCKS_PER_SEC;
printf("fast x = %d, took %d milliseconds!\\n", x, msec);
start = clock();
pthread_create(&st1, 0, slow_thread1, 0);
pthread_create(&st2, 0, slow_thread2, 0);
pthread_join(st1, 0);
pthread_join(st2, 0);
diff = clock() - start;
msec = diff * 1000 / CLOCKS_PER_SEC;
printf("slow y = %d, took %d milliseconds!\\n", y, msec);
pthread_mutex_destroy(&lock);
return 0;
}
| 1
|
#include <pthread.h>
void *controlLED(void *p);
void *inputRead(void *p);
pthread_mutex_t lock;
int led_state[4];
uint8_t led_pins[4]={RPI_GPIO_P1_11, RPI_GPIO_P1_12, RPI_V2_GPIO_P1_13, RPI_GPIO_P1_15},
sw_pins[4]={RPI_GPIO_P1_16, RPI_GPIO_P1_18, RPI_GPIO_P1_22, RPI_V2_GPIO_P1_29};
int main(int argc, char **argv){
pthread_t threads_led[4], threads_sw[4];
int i, ret, num[4]={1,2,3,4};
if( pthread_mutex_init(&lock, 0) != 0 ){
fprintf(stderr, "Erro ao inicializar mutex.\\n");
exit(1);
}
if( !bcm2835_init() ){
fprintf(stderr, "Erro ao inicializar biblioteca bcm2835.\\n");
exit(1);
}
for(i=0; i<4; i++)
bcm2835_gpio_fsel(led_pins[i], BCM2835_GPIO_FSEL_OUTP);
for(i=0; i<4; i++){
bcm2835_gpio_fsel(sw_pins[i], BCM2835_GPIO_FSEL_INPT);
bcm2835_gpio_fsel(sw_pins[i], BCM2835_GPIO_PUD_OFF);
}
for(i=0; i<4; i++){
ret = pthread_create(&threads_led[i], 0, controlLED, &num[i]);
if(ret != 0){
fprintf(stderr, "Erro thread LED %d. Código %d: %s\\n", (i+1), ret, strerror(ret));
exit(1);
}
ret = pthread_create(&threads_sw[i], 0, inputRead, &num[i]);
if(ret != 0){
fprintf(stderr, "Erro thread SW %d. Código %d: %s\\n", (i+1), ret, strerror(ret));
exit(1);
}
}
for(i=0; i<4; i++){
pthread_join(threads_led[i], 0);
pthread_join(threads_sw[i], 0);
}
bcm2835_close();
pthread_mutex_destroy(&lock);
return 0;
}
void *controlLED(void *p){
int *num = (int *)p;
while(1){
pthread_mutex_lock(&lock);
if( led_state[*num-1] )
bcm2835_gpio_write(led_pins[*num-1], HIGH);
else
bcm2835_gpio_write(led_pins[*num-1], LOW);
pthread_mutex_unlock(&lock);
bcm2835_delay(50);
}
pthread_exit(0);
}
void *inputRead(void *p){
int *num = (int *)p;
while(1){
pthread_mutex_lock(&lock);
led_state[*num-1] = bcm2835_gpio_lev(sw_pins[*num-1]);
pthread_mutex_unlock(&lock);
bcm2835_delay(50);
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
static void *pthread_func_1(void *);
static void *pthread_func_2(void *);
int main(int argc,char **argv)
{
pthread_t pt_1=0;
pthread_t pt_2=0;
pthread_attr_t attr={0};
int ret=0;
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond,0);
pthread_attr_init(&attr);
pthread_attr_setscope(&attr,PTHREAD_SCOPE_SYSTEM);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
ret=pthread_create(&pt_1,&attr,pthread_func_1,0);
if(ret!=0)
{
perror("pthread_1_create");
}
ret=pthread_create(&pt_2,0,pthread_func_2,0);
if(ret!=0)
{
perror("pthread_2_create");
}
pthread_join(pt_2,0);
sleep(5);
return 0;
}
static void *pthread_func_1(void *arg)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond,&mutex);
int i=0;
for(;i<3;i++)
{
printf("This is pthread_1.\\n");
if(i==2)
{
pthread_exit(0);
}
}
pthread_mutex_unlock(&mutex);
return ;
}
static void *pthread_func_2(void *arg)
{
pthread_mutex_lock(&mutex);
int i=0;
for(;i<6;i++)
{
printf("This is pthread_2.\\n");
}
pthread_mutex_unlock(&mutex);
printf("guiqinghai\\n");
pthread_cond_signal(&cond);
return ;
}
| 1
|
#include <pthread.h>
void * handle_clnt(void * arg);
void send_msg(char * msg, int len);
void error_handling(char * msg);
int clnt_cnt=0;
int clnt_socks[256];
pthread_mutex_t mutx;
int main(int argc, char *argv[])
{
int serv_sock, clnt_sock;
struct sockaddr_in serv_adr, clnt_adr;
int clnt_adr_sz;
pthread_t t_id;
if(argc!=2) {
printf("Usage : %s <port>\\n", argv[0]);
exit(1);
}
pthread_mutex_init(&mutx, 0);
serv_sock=socket(PF_INET, SOCK_STREAM, 0);
memset(&serv_adr, 0, sizeof(serv_adr));
serv_adr.sin_family=AF_INET;
serv_adr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_adr.sin_port=htons(atoi(argv[1]));
if(bind(serv_sock, (struct sockaddr*) &serv_adr, sizeof(serv_adr))==-1)
error_handling("bind() error");
if(listen(serv_sock, 5)==-1)
error_handling("listen() error");
while(1)
{
clnt_adr_sz=sizeof(clnt_adr);
clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_adr,&clnt_adr_sz);
pthread_mutex_lock(&mutx);
clnt_socks[clnt_cnt++]=clnt_sock;
pthread_mutex_unlock(&mutx);
pthread_create(&t_id, 0, handle_clnt, (void*)&clnt_sock);
pthread_detach(t_id);
printf("Connected client IP: %s \\n", inet_ntoa(clnt_adr.sin_addr));
}
close(serv_sock);
return 0;
}
void * handle_clnt(void * arg)
{
int clnt_sock=*((int*)arg);
int str_len=0, i;
char msg[100];
while((str_len=read(clnt_sock, msg, sizeof(msg)))!=0)
send_msg(msg, str_len);
pthread_mutex_lock(&mutx);
for(i=0; i<clnt_cnt; i++)
{
if(clnt_sock==clnt_socks[i])
{
while(i++<clnt_cnt-1)
clnt_socks[i]=clnt_socks[i+1];
break;
}
}
clnt_cnt--;
pthread_mutex_unlock(&mutx);
close(clnt_sock);
return 0;
}
void send_msg(char * msg, int len)
{
int i;
pthread_mutex_lock(&mutx);
for(i=0; i<clnt_cnt; i++)
write(clnt_socks[i], msg, len);
pthread_mutex_unlock(&mutx);
}
void error_handling(char * msg)
{
fputs(msg, stderr);
fputc('\\n', stderr);
exit(1);
}
| 0
|
#include <pthread.h>
int nextCustomerNo=1;
int f=0,l=0;
int waitingCustomerCount=0;
int custNos[4];
pthread_mutex_t lck;
pthread_cond_t custCond[4];
pthread_cond_t brbrCond;
void wakeUpbarber()
{ pthread_cond_signal(&brbrCond);
}
void customerWait(int chair)
{ pthread_cond_wait(&custCond[chair],&lck);
}
int checkVacancyAndWait(void)
{
int chair;
int custNo;
pthread_mutex_lock(&lck);
if(waitingCustomerCount==4)
{
pthread_mutex_unlock(&lck);
return 0;
}
else
{ chair=l;
custNo=custNos[chair]=nextCustomerNo++;
l=(l+1)%4;
waitingCustomerCount++;
if(waitingCustomerCount==1)
wakeUpbarber();
customerWait(chair);
pthread_mutex_unlock(&lck);
return custNo;
}
}
int checkCustomerAndSleep(void)
{ pthread_mutex_lock(&lck);
if(waitingCustomerCount==0)
pthread_cond_wait(&brbrCond,&lck);
}
void serviceCustomer()
{ int custNo,chair;
chair=f;
f=(f+1)%4;
custNo =custNos[chair];
waitingCustomerCount--;
pthread_cond_signal(&custCond[chair]);
pthread_mutex_unlock(&lck);
printf("barber Servicing %d Customer \\n",custNo);
sleep(3);
}
void*barber()
{ while(1)
{
checkCustomerAndSleep();
serviceCustomer();
}
}
void* customer()
{
int custno;
while(1)
{
custno=checkVacancyAndWait();
if(custno!=0)
{
printf("Customer %d getting serviced...\\n",custno);
sleep(3);
}
else
{ printf("No chair is vacant and customer leaving,...\\n");
sleep(3);
}
}
}
int main()
{ int i;
pthread_t brbr,cust[4 +1];
pthread_create(&brbr,0,barber,0);
for(i=0;i<4 +1;i++)
pthread_create(&cust[i],0,customer,0);
pthread_join(brbr,0);
}
| 1
|
#include <pthread.h>
pthread_t thread1, thread2;
pthread_mutex_t spi_read_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t spi_read_cond = PTHREAD_COND_INITIALIZER;
int exit_spi_read = 0;
int spi_read_loop = 0;
int spi_read_start_loop (int start){
int retval = 0;
if (start){
spi_read_loop = 1;
retval = pthread_cond_broadcast (&spi_read_cond);
}
else {
spi_read_loop = 0;
retval = 0;
}
return retval;
}
int exit_spi_read (void){
exit_spi_read = 1;
}
void spi_read_thread (void *threadID){
while(!exit_spi_read){
pthread_mutex_lock( &spi_read_mutex );
while (!spi_read_loop){
pthread_cond_wait (&spi_read_cond, &spi_read_mutex);
}
pthread_mutex_unlock( &count_mutex );
}
}
int init_spi_read (unsigned int buffer_size){
int iret1, iret2;
int threadID=0;
iret1 = pthread_create( &thread1, 0, spi_read_thread, (void*) &threadID);
if(iret1)
{
fprintf(stderr,"Error - pthread_create() return code: %d\\n",iret1);
exit(1);
}
iret2 = pthread_create( &thread2, 0, print_message_function, (void*) &(threadID=1));
if(iret2)
{
fprintf(stderr,"Error - pthread_create() return code: %d\\n",iret2);
exit(1);
}
}
| 0
|
#include <pthread.h>
int buffer[10];
int position_c = 0;
int position_p = 0;
pthread_mutex_t buf = PTHREAD_MUTEX_INITIALIZER;
sem_t empty;
sem_t full;
int produce_item(int id) {
time_t t;
srand((unsigned) time(&t));
return (rand() % 197) + id;
}
void insert_item(int item, int position) {
buffer[position] = item;
}
int remove_item(int position) {
return buffer[position];
}
void* producer(void* arg) {
int item;
int id = *((int*) arg);
printf("PRODUTOR %d CRIADO.\\n", id);
while(1) {
item = produce_item(id); sleep(1);
sem_wait(&empty);
pthread_mutex_lock(&buf);
insert_item(item, position_p); position_p = (position_p + 1) % 10;
printf("Inserido dado por %d. ITEM = %d.\\n",id, item); fflush(stdout);
pthread_mutex_unlock(&buf);
sem_post(&full);
}
}
void* consumer(void* arg) {
int item;
int id = *((int*) arg);
printf("CONSUMIDOR %d CRIADO.\\n", id);
while(1) {
sem_wait(&full);
pthread_mutex_lock(&buf);
item = remove_item(position_c); position_c = (position_c + 1) % 10;
pthread_mutex_unlock(&buf);
sem_post(&empty);
printf("Consumindo dado por %d. ITEM = %d.\\n", id, item); fflush(stdout);
sleep(4);
}
}
int main() {
pthread_t a[6];
time_t t;
int i, j, k;
int * id;
sem_init(&empty, 0, 10);
sem_init(&full, 0, 0);
srand((unsigned) time(&t));
j = 0; k = 0;
for (i = 0; i < 6 ; i++) {
id = (int *) malloc(sizeof(int));
if(rand() % 2) {
*id = k; k++;
pthread_create(&a[i], 0, consumer, (void *) (id));
}
else {
*id = j; j++;
pthread_create(&a[i], 0, producer, (void *) (id));
}
}
pthread_join(a[0],0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t forks[(5 -1)];
void eat(int philosopher)
{
printf("Philosopher %i has started eating! \\n", philosopher);
usleep(100);
printf("Philosopher %i has finished eating! \\n", philosopher);
}
void think(int philosopher)
{
printf("Philosopher %i is thinking super-duper hard! \\n", philosopher);
}
void get_left_fork(int philosopher)
{
int left_fork_index = philosopher;
printf("Philosopher %i is trying to get fork %i (left)!\\n", philosopher, left_fork_index);
pthread_mutex_lock(&forks[left_fork_index]);
printf("Philosopher %i got fork %i (left)!\\n", philosopher, left_fork_index);
}
void get_right_fork(int philosopher)
{
int right_fork_index = (philosopher-1) % 5;
if (right_fork_index == -1) right_fork_index = 5 -1;
printf("Philosopher %i is trying to get fork %i (right)!\\n", philosopher, right_fork_index);
pthread_mutex_lock(&forks[right_fork_index]);
printf("Philosopher %i got fork %i (right)!\\n", philosopher, right_fork_index);
}
void drop_left_fork(int philosopher)
{
int left_fork_index = philosopher;
printf("Philosopher %i is dropping fork %i (left)!\\n", philosopher, left_fork_index);
pthread_mutex_unlock(&forks[left_fork_index]);
}
void drop_right_fork(int philosopher)
{
int right_fork_index = (philosopher-1) % 5;
if (right_fork_index == -1) right_fork_index = 5 -1;
printf("Philosopher %i is dropping fork %i (right)!\\n", philosopher, right_fork_index);
pthread_mutex_unlock(&forks[right_fork_index]);
}
static void *philosophers(int philosopher)
{
int me = philosopher;
while(1)
{
think(me);
get_left_fork(me);
think(me);
get_right_fork(me);
eat(me);
drop_left_fork(me);
drop_right_fork(me);
}
pthread_exit(0);
}
int main(int argc, char **argv)
{
int count;
for (count = 0; count < 5; count++)
{
pthread_mutex_init(&forks[count],0);
}
pthread_t great_thinkers[5 -1];
for (count = 0; count < 5; count++)
{
pthread_create(&great_thinkers[count],0,philosophers,count);
}
for (count = 0; count < 5; count++)
{
pthread_join(great_thinkers[count],0);
}
return 0;
}
| 0
|
#include <pthread.h>
char *directory;
int totalSize=0;
pthread_mutex_t totalSizeMutex;
void *copyFile(void *filename)
{
struct stat buf;
int fd = open(filename,O_RDONLY);
fstat(fd, &buf);
int size = (int) buf.st_size;
close(fd);
pthread_mutex_lock(&totalSizeMutex);
totalSize += size;
pthread_mutex_unlock(&totalSizeMutex);
char** newArg = (char**) malloc(4*sizeof(char*));
newArg[0] = "mv";
newArg[1] = filename;
newArg[2] = directory;
newArg[3] = 0;
pid_t pid=fork();
if (pid==-1) {
printf("fork failed\\n");
}else if(pid==0){
execvp(newArg[0],newArg);
printf("error:moving %s not successful\\n",newArg[1]);
}else{
wait(0);
}
pthread_exit(0);
}
int main(int argc, char *argv[])
{
pthread_t threads[argc-2];
directory=argv[argc-1];
int rc;
long t;
for(t=0; t<argc-2; t++){
rc = pthread_create(&threads[t], 0, copyFile, (void *)argv[t+1]);
if (rc){
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
for (t = 0; t < argc-2; t++) {
pthread_join(threads[t], 0);
}
printf("%d bytes copied\\n",totalSize);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int value;
struct elem *next;
}elem;
unsigned int sizeBuffer, statusBuffer;
elem *head,*last;
}blockingQueue;
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer = 11;
blockingQueue Q;
elem* newElem(){
return malloc(1*sizeof(elem));
}
void newBlockingQueue(int sz){
int i;
if(sz>11){
sz = 11;
}
Q.sizeBuffer = 11;
Q.statusBuffer = sz;
Q.head = newElem();
elem* aux = Q.head;
for(i=0; i<sz; i++){
aux->value = i+1;
if(i!=sz-1){
aux->next = newElem();
aux=aux->next;
}
}
aux->next = 0;
Q.last = aux;
}
void putBlockingQueue(int newValue, int number){
if(Q.statusBuffer==0){
Q.last = newElem();
Q.head = Q.last;
}else{
Q.last->next = newElem();
Q.last = Q.last->next;
}
Q.last->value = newValue;
Q.last->next = 0;
printf("Elemento Adicionado [Produtor %d]: %d\\n", number, Q.last->value);
Q.statusBuffer++;
}
int takeBlockingQueue(int number){
printf("Elemento Retirado [Consumidor %d]: %d\\n", number, Q.head->value);
Q.head = Q.head->next;
Q.statusBuffer--;
if(Q.statusBuffer==0){
Q.last == 0;
}
}
void *producer(void* t) {
int i = 11;
int number = (int) t;
while(1){
i++;
pthread_mutex_lock(&the_mutex);
while (Q.statusBuffer != 0)
pthread_cond_wait(&condp, &the_mutex);
putBlockingQueue(i, number);
pthread_cond_signal(&condc);
pthread_mutex_unlock(&the_mutex);
}
}
void *consumer(void* i) {
int number = (int) i;
while(1){
pthread_mutex_lock(&the_mutex);
while (Q.statusBuffer == 0)
pthread_cond_wait(&condc, &the_mutex);
takeBlockingQueue(number);
pthread_cond_signal(&condp);
pthread_mutex_unlock(&the_mutex);
}
}
int main() {
newBlockingQueue(10);
pthread_t pro[5], con[5];
long i;
pthread_mutex_init(&the_mutex, 0);
pthread_cond_init(&condc, 0);
pthread_cond_init(&condp, 0);
for(i=0; i<5; i++){
printf("Criando Produtores...\\n");
pthread_create(&pro[i], 0, producer, (void*) i);
}
for(i=0; i<5; i++){
printf("Criando Consumidores...\\n");
pthread_create(&con[i], 0, consumer, (void*) i);
}
for(i=0; i<5; i++){
printf("Esperando Produtores...\\n");
pthread_join(pro[i], 0);
}
for(i=0; i<5; i++){
printf("Esperando Consumidores...\\n");
pthread_join(con[i], 0);
}
pthread_mutex_destroy(&the_mutex);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
}
| 0
|
#include <pthread.h>
pthread_mutex_t tenedor[5];
sem_t s;
void pensar(int i)
{
printf("Filosofo %d pensando...\\n",i);
usleep(random() % 1000000);
}
void comer(int i)
{
printf("Filosofo %d comiendo...\\n",i);
usleep(random() % 1000000);
}
void tomar_tenedores(int i)
{
pthread_mutex_lock(&tenedor[i]);
usleep(1000000);
pthread_mutex_lock(&tenedor[(i+1)%5]);
}
void dejar_tenedores(int i)
{
pthread_mutex_unlock(&tenedor[i]);
pthread_mutex_unlock(&tenedor[(i+1)%5]);
}
void *filosofo(void * p)
{
int i = (int)p;
for (;;)
{
if(sem_wait(&s) == 0) {
tomar_tenedores(i);
comer(i);
dejar_tenedores(i);
sem_post(&s);
pensar(i);
}
}
}
int main ()
{
int i;
pthread_t filosofos[5];
sem_init(&s, 1, 5 -1);
for (i=0;i<5;i++)
pthread_mutex_init(&tenedor[i], 0);
for (i=0;i<5;i++)
pthread_create(&filosofos[i], 0, filosofo, (void *)i);
for (i=0;i<5;i++)
pthread_join(filosofos[i], 0);
return 0;
}
| 1
|
#include <pthread.h>
int counter= 0;
pthread_mutex_t mutex= PTHREAD_MUTEX_INITIALIZER;
void dawdle(int cnt) {
int i;
double dummy= 3.141;
for(i=0;i<cnt*10;i++) {
dummy= dummy*dummy/dummy;
}
sleep(1);
}
void *thread(void *args) {
int i,val;
int arg = *((int*)args);
for (i= 0; i<10; i++) {
pthread_mutex_lock(&mutex);
val= counter;
dawdle(arg);
printf("Thread %lu: %d\\n",pthread_self(),val+1);
counter= val+1;
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main(int argc,char **argv) {
int arg1=1, arg2=0;
pthread_t tidA,tidB;
if (pthread_create(&tidA,0,thread,(void *)&arg1) != 0) {
fprintf (stderr, "Konnte Thread 1 nicht erzeugen\\n");
exit (1);
}
if (pthread_create(&tidB,0,thread,(void *)&arg2) != 0) {
fprintf (stderr, "Konnte Thread 2 nicht erzeugen\\n");
exit (1);
}
pthread_join(tidA, 0);
pthread_join(tidB, 0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
int unpipe_create(int size_log2) {
int id;
long pagesize;
struct unpipe_ctx *p;
pthread_mutexattr_t m_attr;
pthread_condattr_t c_attr_r;
pthread_condattr_t c_attr_w;
pagesize = sysconf(_SC_PAGESIZE);
assert(sizeof(struct unpipe_ctx *) < pagesize);
id = shmget(IPC_PRIVATE, pagesize + (1<<size_log2), 0644 | IPC_CREAT);
if (id == -1) return id;
p = shmat(id, 0, 0);
memset(p, '\\0', sizeof(struct unpipe_ctx));
p->id = id;
p->size = 1<<size_log2;
p->base_offset = pagesize;
pthread_mutexattr_init(&m_attr);
pthread_condattr_init(&c_attr_r);
pthread_condattr_init(&c_attr_w);
pthread_mutexattr_setpshared(&m_attr, PTHREAD_PROCESS_SHARED);
pthread_condattr_setpshared(&c_attr_r, PTHREAD_PROCESS_SHARED);
pthread_condattr_setpshared(&c_attr_w, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&p->lock, &m_attr);
pthread_cond_init(&p->r_cv, &c_attr_r);
pthread_cond_init(&p->w_cv, &c_attr_w);
shmdt(p);
return id;
}
struct unpipe_ctx *unpipe_connect(int id, int mode) {
struct unpipe_ctx *p;
p = shmat(id, 0, 0);
pthread_mutex_lock(&p->lock);
if (mode == 0) {
p->r_ref_count++;
} else if (mode == 1) {
p->w_ref_count++;
}
pthread_mutex_unlock(&p->lock);
return p;
}
int unpipe_disconnect(struct unpipe_ctx *p, int mode) {
pthread_mutex_lock(&p->lock);
if (mode == 0) {
p->r_ref_count--;
if (p->r_ref_count == 0) {
p->r_closed = 1;
pthread_cond_signal(&p->w_cv);
}
} else if (mode == 1) {
p->w_ref_count--;
if (p->w_ref_count == 0) {
p->w_closed = 1;
pthread_cond_signal(&p->r_cv);
}
}
pthread_mutex_unlock(&p->lock);
return shmdt(p);
}
int unpipe_destroy(struct unpipe_ctx *p) {
pthread_mutex_lock(&p->lock);
shmctl(p->id, IPC_RMID, 0);
pthread_mutex_unlock(&p->lock);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t locki[32];
int inode[32];
pthread_mutex_t lockb[26];
int busy[26];
void *thread_routine (void *arg)
{
int b;
long tid = (long) arg;
int i = tid % 32;
printf ("t%ld: starting, inode %d\\n", tid, i);
pthread_mutex_lock (&locki[i]);
if (inode[i] == 0)
{
b = (i*2) % 26;
while (1) {
printf ("t%ld: checking block %d\\n", tid, b);
pthread_mutex_lock (&lockb[b]);
if (!busy[b]) {
busy[b] = 1;
inode[i] = b+1;
pthread_mutex_unlock (&lockb[b]);
break;
}
pthread_mutex_unlock (&lockb[b]);
b = (b+1) % 26;
}
}
pthread_mutex_unlock (&locki[i]);
return 0;
}
int main ()
{
pthread_t tids[13];
int i, ret;
for (i = 0; i < 32; ++i)
{
ret = pthread_mutex_init(&locki[i], 0);
assert (ret == 0);
}
for (i = 0; i < 26; ++i)
{
ret = pthread_mutex_init(&lockb[i], 0);
assert (ret == 0);
}
for (i = 0; i < 13; ++i)
{
ret =pthread_create(&tids[i], 0, thread_routine, (void*) (long) i);
assert (ret == 0);
}
for (i = 0; i < 13; ++i)
{
ret = pthread_join (tids[i], 0);
assert (ret == 0);
}
return 0;
}
| 0
|
#include <pthread.h>
void gw_dm_zombie ( void *_job_id )
{
gw_job_t * job;
gw_array_t * array;
int job_id;
int task_id;
int array_id;
int rt;
char conf_filename[2048];
if ( _job_id != 0 )
{
job_id = *( (int *) _job_id );
job = gw_job_pool_get(job_id, GW_TRUE);
if ( job == 0 )
{
gw_log_print("DM",'E',"Job %i does not exist (JOB_STATE_ZOMBIE).\\n",job_id);
free(_job_id);
return;
}
}
else
return;
switch (job->job_state)
{
case GW_JOB_STATE_EPILOG:
gw_job_set_state(job, GW_JOB_STATE_ZOMBIE, GW_FALSE);
gw_log_print("DM",'I',"Job %i done, with exit code %i.\\n",job->id, job->exit_code);
gw_job_print(job,"DM",'I',"Job done, history:\\n");
gw_job_print_history(job);
job->history->reason = GW_REASON_NONE;
job->exit_time = time(0);
if ( job->client_waiting > 0 )
gw_am_trigger(gw_dm.rm_am,"GW_RM_WAIT_SUCCESS", _job_id);
else
free(_job_id);
gw_user_pool_dec_running_jobs(job->user_id);
pthread_mutex_lock(&(job->history->host->mutex));
job->history->host->running_jobs--;
pthread_mutex_unlock(&(job->history->host->mutex));
pthread_mutex_unlock(&(job->mutex));
gw_job_pool_dep_check(job_id);
break;
case GW_JOB_STATE_KILL_EPILOG:
gw_job_set_state(job, GW_JOB_STATE_ZOMBIE, GW_FALSE);
gw_job_print(job,"DM",'I',"Job killed, history:\\n");
gw_job_print_history(job);
job->exit_time = time(0);
array_id = job->array_id;
task_id = job->task_id;
gw_user_pool_dec_running_jobs(job->user_id);
pthread_mutex_lock(&(job->history->host->mutex));
job->history->host->running_jobs--;
pthread_mutex_unlock(&(job->history->host->mutex));
sprintf(conf_filename, "%s/job.conf", job->directory);
unlink(conf_filename);
pthread_mutex_unlock(&(job->mutex));
gw_job_pool_free(job_id);
gw_log_print("DM",'I',"Job %i killed and freed.\\n", job_id);
if (array_id != -1)
{
array = gw_array_pool_get_array(array_id,GW_TRUE);
if ( array != 0 )
{
rt = gw_array_del_task(array,task_id);
pthread_mutex_unlock(&(array->mutex));
if (rt == 0)
{
gw_array_pool_array_free(array_id);
gw_log_print("DM",'I',"Array %i freed\\n",array_id);
}
}
else
gw_log_print("DM",'E',"Could not delete task %i from array %i.\\n",
task_id, array_id);
}
gw_am_trigger(gw_dm.rm_am,"GW_RM_KILL_SUCCESS", _job_id);
break;
default:
gw_log_print("DM",'E',"Zombie callback in wrong job (%i) state.\\n", job_id);
free(_job_id);
pthread_mutex_unlock(&(job->mutex));
break;
}
}
| 1
|
#include <pthread.h>
struct module_tick *module_tick_create(struct module_tick_master *master, struct module_base *base, float interval, unsigned long flags)
{
struct module_tick *new = malloc(sizeof(*new));
assert(new);
fprintf(stderr, "createing tick: %p, master %p, interval %f\\n", new, master, interval);
memset(new , 0 , sizeof(*new));
new->master = master;
new->flags = flags;
module_tick_set_interval(new, interval);
pthread_mutex_lock(&master->mutex);
master->ticks = module_tick_add(master->ticks, new);
new->div_seq = master->seq - new->div;
if(TICK_FLAG_SECALGN&flags){
new->div_seq += (TICK_FLAG_SECALGN&flags)-1;
}
master->outcnt++;
new->inwait = 0;
new->base = base;
pthread_mutex_unlock(&master->mutex);
return new;
}
struct module_tick *module_tick_add(struct module_tick *list, struct module_tick *new)
{
struct module_tick *ptr = list;
if(!ptr){
return new;
}
while(ptr->next)
ptr = ptr->next;
ptr->next = new;
return list;
}
struct module_tick *module_tick_rem(struct module_tick *list, struct module_tick *rem)
{
struct module_tick *ptr = list;
if(!rem){
return list;
}
if(ptr == rem){
struct module_tick *next = ptr->next;
ptr->next = 0;
return next;
}
while(ptr->next){
if(ptr->next == rem){
struct module_tick *found = ptr->next;
ptr->next = found->next;
found->next = 0;
break;
}
ptr = ptr->next;
}
return list;
}
void module_tick_delete(struct module_tick *tick)
{
struct module_tick_master *master = tick->master;
pthread_mutex_lock(&master->mutex);
master->outcnt--;
master->ticks = module_tick_rem(master->ticks, tick);
pthread_mutex_unlock(&master->mutex);
free(tick);
}
void module_tick_set_interval(struct module_tick *tick, float interval)
{
struct module_tick_master *master = tick->master;
tick->interval = interval;
if(interval != 0)
tick->div = (interval*1000)/(master->ms_interval);
else
tick->div = 1;
fprintf(stderr, "Set tick interval set to %f (div %d)\\n", interval, tick->div);
}
int module_tick_wait(struct module_tick *tick, struct timeval *time)
{
struct module_tick_master *master = tick->master;
int retval = 0;
if(!master)
return -1;
if(!master->run)
return -1;
if(!tick)
return -1;
pthread_mutex_lock(&master->mutex);
master->outcnt--;
tick->inwait = 1;
do{
retval = pthread_cond_wait(&master->cond, &master->mutex);
}while((retval == 0) && ((master->seq - tick->div_seq) < tick->div));
tick->inwait = 0;
master->outcnt++;
memcpy(time, &master->time, sizeof(struct timeval));
tick->seq = master->seq;
pthread_mutex_unlock(&master->mutex);
tick->div_seq += tick->div;
if(tick->seq > tick->div_seq){
tick->rollerr++;
if(tick->flags&TICK_FLAG_SKIP){
if((tick->div == 1)||!(tick->flags&TICK_FLAG_SECALGN)){
retval = (tick->seq-tick->div_seq)/tick->div;
tick->div_seq = tick->seq;
} else {
retval = 0;
while(tick->seq > tick->div_seq){
tick->div_seq += tick->div;
retval++;
}
}
}
}
return retval;
}
void module_tick_master_set_interval(struct module_tick_master *master, int ms_interval)
{
struct module_tick *ptr = master->ticks;
fprintf(stderr, "Set tick master interval to %d ms\\n", ms_interval);
master->ms_interval = ms_interval;
while(ptr){
module_tick_set_interval(ptr, ptr->interval);
ptr = ptr->next;
}
}
| 0
|
#include <pthread.h>
sem_t barber,customer;
pthread_mutex_t mutex;
int waiting=0;
int count=0;
void* barber1(void* param){
while(1){
sem_wait(&customer);
pthread_mutex_lock(&mutex);
sleep(2);
waiting=waiting-1;
sem_post(&barber);
pthread_mutex_unlock(&mutex);
printf("Cut Hair");
count++;
if(count==5)break;
}
}
void* customer1(void* param){
pthread_mutex_lock(&mutex);
if(waiting<5){
waiting=waiting+1;
sem_post(&customer);
pthread_mutex_unlock(&mutex);
sem_wait(&barber);
printf("Get Hair Cut");
}else{
pthread_mutex_unlock(&mutex);
}
sleep(2);
}
int main(){
sem_init(&barber,0,0);
sem_init(&customer,0,0);
pthread_mutex_init(&mutex,0);
pthread_t barb,customers[5];
pthread_create(&barb,0,barber1,0);
int i;
for(i=0;i<5;i++){
pthread_create(&customers[i],0,customer1,0);
}
pthread_join(barb,0);
for(i=0;i<5;i++){
pthread_join(customers[i],0);
}
}
| 1
|
#include <pthread.h>
int num_threads;
pthread_mutex_t *mutexes;
pthread_mutex_t *share_p;
none,
one,
two
} utensil;
int phil_num;
int course;
utensil forks;
}phil_data;
phil_data *philosophers;
void shared_print(int id){
pthread_mutex_lock(&share_p[id]);
printf("No.%d Philosopher ate dinner\\n", id);
pthread_mutex_unlock(&share_p[id]);
}
void *eat_meal(void *phil_ptr){
phil_data *phils = phil_ptr;
int phil_ID = phils->phil_num;
while(1){
if(philosophers[phil_ID].course != 3){
if(phil_ID == 0){
if(philosophers[num_threads-1].forks != two){
pthread_mutex_lock(&mutexes[phil_ID]);
philosophers[phil_ID].forks = one;
}
}
else{
if(philosophers[phil_ID-1].forks != two){
pthread_mutex_lock(&mutexes[phil_ID]);
philosophers[phil_ID].forks = one;
}
}
if (philosophers[(phil_ID+1)%num_threads].forks == none) {
pthread_mutex_lock(&mutexes[(phil_ID+1)%num_threads]);
philosophers[phil_ID].forks = two;
}
else{
pthread_mutex_unlock(&mutexes[phil_ID]);
philosophers[phil_ID].forks = none;
}
if (philosophers[phil_ID].forks == two){
sleep(1);
shared_print(phil_ID);
philosophers[phil_ID].course += 1;
pthread_mutex_unlock(&mutexes[phil_ID]);
pthread_mutex_unlock(&mutexes[(phil_ID+1)%num_threads]);
philosophers[phil_ID].forks = none;
}
if (philosophers[phil_ID].course == 3){
break;
}
}
}
return 0;
}
int main( int argc, char **argv ){
int num_philosophers, error;
if (argc < 2) {
fprintf(stderr, "Format: %s <Number of philosophers>\\n", argv[0]);
return 0;
}
num_philosophers = num_threads = atoi(argv[1]);
pthread_t threads[num_threads];
philosophers = malloc(sizeof(phil_data)*num_philosophers);
mutexes = malloc(sizeof(pthread_mutex_t)*num_philosophers);
share_p = malloc(sizeof(pthread_mutex_t)*num_philosophers);
for( int i = 0; i < num_philosophers; i++ ){
philosophers[i].phil_num = i;
philosophers[i].course = 0;
philosophers[i].forks = none;
}
error = 0;
int mutexes_init = 0;
int share_p_init = 0;
for(int i = 1; i < num_threads; i++){
error = pthread_mutex_init(&mutexes[i], 0);
if(error == -1){
printf("\\n Mutex initialization failed \\n");
exit(1);
}
mutexes_init = 1;
}
for(int i = 1; i < num_threads; i++){
error = pthread_mutex_init(&share_p[i], 0);
if(error == -1){
printf("\\n Mutex2 initialization failed \\n");
exit(1);
}
share_p_init = 1;
}
for (int i = 0; i < num_threads; i++) {
error = pthread_create(&threads[i], 0, (void *)eat_meal, (void *)(&philosophers[i]));
if(error != 0){
printf("\\n Thread creation failed \\n");
exit(1);
}
}
for (int i = 0; i < num_threads; i++) {
error = pthread_join(threads[i], 0);
if(error!=0){
printf("\\n Threads didnt join \\n");
exit(1);
}
}
if (mutexes_init == 1) {
error = pthread_mutex_destroy(mutexes);
}
if (share_p_init == 1) {
error = pthread_mutex_destroy(share_p);
}
free(philosophers);
free(mutexes);
free(share_p);
return 0;
}
| 0
|
#include <pthread.h>
int shared_data = 1;
int read_count = 0, write_count = 0;
pthread_mutex_t mutex_write_count,mutex_read_count,mutex_write,mutex_read;
sem_t read_ready;
void initialize()
{
pthread_mutex_init(&mutex_write,0);
pthread_mutex_init(&mutex_write_count,0);
pthread_mutex_init(&mutex_read_count,0);
sem_init(&read_ready,0,1);
}
void* reader(void *data)
{
pthread_mutex_lock(&mutex_read_count);
read_count++;
if (read_count == 1)
{
sem_wait(&read_ready);
}
pthread_mutex_unlock(&mutex_read_count);
printf("reading - shared data is : %d\\n",shared_data);
pthread_mutex_lock(&mutex_read_count);
read_count--;
if (read_count == 0)
{
sem_post(&read_ready);
}
pthread_mutex_unlock(&mutex_read_count);
}
void* writer(void *data)
{
pthread_mutex_lock(&mutex_write_count);
write_count++;
if (write_count == 1)
{
sem_wait(&read_ready);
}
pthread_mutex_unlock(&mutex_write_count);
pthread_mutex_lock(&mutex_write);
shared_data = (int)data;
printf("updated shared data : %d\\n",shared_data);
pthread_mutex_unlock(&mutex_write);
pthread_mutex_lock(&mutex_write_count);
write_count--;
if (write_count == 0)
{
sem_post(&read_ready);
}
pthread_mutex_unlock(&mutex_write_count);
}
int main(int argc,char *argv[])
{
if (argc != 3)
{
fprintf(stderr,"Error : incorrect format. use <executable> number_of_readers number_of_writers");
return -1;
}
int reader_num = atoi(argv[1]);
int writer_num = atoi(argv[2]);
reader_num = (reader_num < (20>>1)) ? reader_num : 20>>1 ;
writer_num = (writer_num < (20>>1)) ? writer_num : 20>> 1;
int i = 0;
pthread_t readers[reader_num];
pthread_t writers[writer_num];
initialize();
for(i=0;i<reader_num;i++)
{
pthread_create(&readers[i],0,reader,0);
}
for(i=0;i<writer_num;i++)
{
pthread_create(&writers[i],0,writer,(void*)i);
}
for(i=0;i<reader_num;i++)
{
pthread_join(readers[i],0);
}
for(i=0;i<writer_num;i++)
{
pthread_join(writers[i],0);
}
return 0;
}
| 1
|
#include <pthread.h>
void print(char *v){
puts(v);
}
char *t;
char *p;
int start_t;
int stop_t;
int start_p;
int stop_p;
int thread_id;
int padding;
short *found_pos;
pthread_mutex_t *mutex;
}params;
int how_many_positions(char *p, char searched, int pattern_size){
int nr_pos=0;
char *curr = p;
int i = 0;
while(*curr != searched && i < pattern_size){
nr_pos++;
curr--;
i++;
}
if (nr_pos == pattern_size)
return 1;
return nr_pos;
}
void* process_text(void *par){
params *pmtrs = (params*)par;
int thread_id = pmtrs->thread_id;
char *t = pmtrs->t;
char *p = pmtrs->p;
int start_t = pmtrs->start_t;
int stop_t = pmtrs-> stop_t;
int start_p = pmtrs-> start_p;
int stop_p = pmtrs-> stop_p;
short *found_pos = pmtrs-> found_pos;
pthread_mutex_t *mutex = pmtrs->mutex;
int found = 0;
long processed=0;
long total_processed=0;
start_p += stop_p-1;
start_t += stop_p-1;
while(start_t <= stop_t){
if (start_p == 0){
found = 1;
pthread_mutex_lock(mutex);
if (found_pos[start_t] != 1){
printf("%d Found one pattern\\n", thread_id);
found_pos[start_t] = 1;
}
pthread_mutex_unlock(mutex);
start_t += processed;
start_p += processed;
start_t += stop_p;
processed = 0;
}
if (t[start_t] == p[start_p]){
start_t --;
start_p --;
processed++;
}
else {
if (stop_t-start_t < stop_p)
break;
int num = how_many_positions(p + (stop_p - processed -1), t[start_t], stop_p);
start_t+= processed;
start_t+= num;
total_processed += processed;
total_processed += num;
processed = 0;
start_p = stop_p-1;
}
}
}
int main(int argc, char **argv){
if (argc < 2){
printf("grep <pattern> <text>\\n");
return 1;
}
int id = 0;
pthread_t threads[32];
pthread_t threads2[32];
params prms[32];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
char *p, *t;
p = argv[2];
t = argv[1];
int start_p = 0;
int start_t = 0;
int stop_p = strlen(argv[2]);
int stop_t = strlen(argv[1]);
int NR_THREADS = 32;
int chunk = stop_t/NR_THREADS;
int remainder = stop_t %NR_THREADS;
short *found = (short*)calloc(stop_t, sizeof(short));
clock_t start = clock();
for (id = 0; id < NR_THREADS; ++id)
{
start_p = 0;
start_t = id * chunk;
stop_t = (id + 1) * chunk -1;
if (id == NR_THREADS-1)
stop_t += remainder;
prms[id].t = t;
prms[id].p = p;
prms[id].start_t = start_t;
prms[id].stop_t = stop_t;
prms[id].start_p = start_p;
prms[id].stop_p = stop_p;
prms[id].found_pos = found;
prms[id].thread_id = id;
prms[id].mutex = &mutex;
int rc = pthread_create(&threads[id], 0, process_text, (void *)&prms[id]);
}
for(id = 0; id < NR_THREADS; ++id){
int rc = pthread_join(threads[id], 0);
}
pthread_mutex_destroy(&mutex);
pthread_mutex_init(&mutex, 0);
for (id = 0; id < NR_THREADS; ++id)
{
int last_thread_id = NR_THREADS-1;
if (id != NR_THREADS-1){
start_p = 0;
start_t = (id + 1) * chunk;
stop_t = (id + 1) * chunk;
start_t -= stop_p;
stop_t += stop_p-1;
prms[id].t = t;
prms[id].p = p;
prms[id].start_t = start_t;
prms[id].stop_t = stop_t;
prms[id].start_p = start_p;
prms[id].stop_p = stop_p;
prms[id].found_pos = found;
prms[id].thread_id = id;
prms[id].mutex = &mutex;
int rc = pthread_create(&threads[id], 0, process_text, (void *)&prms[id]);
}
}
for(id = 0; id < NR_THREADS; ++id){
if (id == NR_THREADS-1)
continue;
int rc = pthread_join(threads[id], 0);
}
pthread_mutex_destroy(&mutex);
clock_t stop = clock();
printf("Executed in %f\\n",((float)stop-start)/CLOCKS_PER_SEC);
return 0;
}
| 0
|
#include <pthread.h>
int avail = 2;
int happy_ind = 1;
int total_happy = 0;
pthread_mutex_t mutex_avail;
enum { h_unknown = 0, h_yes, h_no };
unsigned char buf[256] = {0, h_yes, 0};
struct th_data {
pthread_t pid;
int thread_num;
int maxnum;
int i;
int *bit_pointer;
};
struct happy_data {
pthread_t pid;
int num;
int *bit_pointer;
};
int happy(int n)
{
int sum = 0, x, nn;
if (n < 256) {
if (buf[n]) return 2 - buf[n];
buf[n] = h_no;
}
for (nn = n; nn; nn /= 10) x = nn % 10, sum += x * x;
x = happy(sum);
if (n < 256) buf[n] = 2 - x;
return x;
}
static void parent_sig(int sig) {
_exit(1);
}
static void *happy_thread (void *arg)
{
struct happy_data *thread = (struct happy_data*) arg;
int local = 1;
int s;
while (local < thread->num) {
s = pthread_mutex_lock(&mutex_avail);
if (s != 0) {
errEXIT("mutex lock");
}
local = happy_ind;
happy_ind++;
s = pthread_mutex_unlock(&mutex_avail);
if (s != 0) {
errEXIT("mutex lock");
}
if (!testbit(thread->bit_pointer, local)) {
if (happy(local)) {
s = pthread_mutex_lock(&mutex_avail);
if (s != 0) {
errEXIT("mutex lock");
}
total_happy++;
s = pthread_mutex_unlock(&mutex_avail);
if (s != 0) {
errEXIT("mutex lock");
}
}
}
}
pthread_exit((void *) 0);
}
static void *thread_func (void *arg)
{
int local;
int s;
int j;
int prime = 2;
struct th_data *thread = (struct th_data*) arg;
int n = thread->maxnum;
while (prime < (int)sqrt(thread->maxnum)) {
pthread_mutex_lock(&mutex_avail);
if (s != 0) {
errEXIT("mutex lock");
}
prime = avail;
avail++;
pthread_mutex_unlock(&mutex_avail);
if (s != 0) {
errEXIT("mutex lock");
}
pthread_mutex_lock(&mutex_avail);
if (s != 0) {
errEXIT("mutex lock");
}
local = testbit(thread->bit_pointer, prime);
pthread_mutex_unlock(&mutex_avail);
if (s != 0) {
errEXIT("mutex lock");
}
if (!local) {
for (j = 2; prime * j < n; j++) {
pthread_mutex_lock(&mutex_avail);
if (s != 0) {
errEXIT("mutex lock");
}
setbit(thread->bit_pointer, (prime * j));
pthread_mutex_unlock(&mutex_avail);
if (s != 0) {
errEXIT("mutex lock");
}
}
}
}
pthread_exit((void *) 0);
}
int main (int argc, char *argv[])
{
int procs;
int *bitmap;
int opt;
int n;
int i;
int index = 2;
int s;
struct th_data *threads;
struct happy_data *hp_threads;
pthread_attr_t attr;
struct sigaction p_sa;
sigemptyset(&p_sa.sa_mask);
if (sigaction(SIGINT, &p_sa, 0) == -1)
errEXIT("sigaction");
if (sigaction(SIGQUIT, &p_sa, 0) == -1)
errEXIT("sigaction");
if (sigaction(SIGHUP, &p_sa, 0) == -1 )
errEXIT("sigaction");
pthread_mutex_init(&mutex_avail, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
n = get_args(argc, argv, &procs);
threads = (struct th_data*) malloc(procs * sizeof(struct th_data));
hp_threads = (struct happy_data*) malloc(procs * sizeof(struct happy_data));
bitmap = malloc(((n/32) + 1) *sizeof(int));
bzero(bitmap, (((n/32) + 1) * sizeof(int)));
for (i = 0; i < procs; i++) {
threads[i].thread_num = i + 1;
threads[i].maxnum = n;
threads[i].bit_pointer = bitmap;
s = pthread_create(&threads[i].pid, &attr, thread_func, (void *)&threads[i]);
if (s != 0) {
error(1, s, "%s\\n", "Pthread creation");
}
}
for (i = 0; i < procs; i++) {
s = pthread_join(threads[i].pid, 0);
if (s != 0) {
error(1, s, "%s\\n", "Pthread join");
}
}
for (i = 0; i < procs; i++) {
hp_threads[i].num = n;
hp_threads[i].bit_pointer = bitmap;
s = pthread_create(&hp_threads[i].pid, &attr, happy_thread, (void *)&hp_threads[i]);
if (s != 0) {
error(1, s, "%s\\n", "Pthread creation");
}
}
for (i = 0; i < procs; i++) {
s = pthread_join(hp_threads[i].pid, 0);
if (s != 0) {
error(1, s, "%s\\n", "Pthread join");
}
}
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&mutex_avail);
printf("Total happy %d\\n", total_happy);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_once_t g_init = PTHREAD_ONCE_INIT;
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
void init_g_lock(void)
{
pthread_mutex_init(&g_lock, 0);
}
void *input_onoff(void *arg) {
char buf[80];
int len;
char *onoff=(char*) arg;
char *path = "/sys/class/input/input2/enabled";
pthread_mutex_lock(&g_lock);
int fd = open(path, O_WRONLY);
if (fd < 0) {
strerror_r(errno, buf, sizeof(buf));
ALOGE("Error opening %s: %s\\n", path, buf);
} else
len = write(fd, onoff, 1);
if (len < 0) {
strerror_r(errno, buf, sizeof(buf));
ALOGE("Error writing to %s: %s\\n", path, buf);
}
close(fd);
path = "/sys/class/input/input3/enabled";
fd = open(path, O_WRONLY);
if (fd < 0) {
strerror_r(errno, buf, sizeof(buf));
ALOGE("Error opening %s: %s\\n", path, buf);
} else
len = write(fd, onoff, 1);
if (len < 0) {
strerror_r(errno, buf, sizeof(buf));
ALOGE("Error writing to %s: %s\\n", path, buf);
}
close(fd);
path = "/sys/class/input/input14/enabled";
fd = open(path, O_WRONLY);
if (fd < 0) {
strerror_r(errno, buf, sizeof(buf));
ALOGE("Error opening %s: %s\\n", path, buf);
} else
len = write(fd, onoff, 1);
if (len < 0) {
strerror_r(errno, buf, sizeof(buf));
ALOGE("Error writing to %s: %s\\n", path, buf);
}
close(fd);
pthread_mutex_unlock(&g_lock);
return 0;
}
void cm_power_set_interactive_ext(int on) {
ALOGD("%s: %s input devices", __func__, on ? "enabling" : "disabling");
pthread_t pth;
pthread_attr_t threadAttr;
pthread_attr_init(&threadAttr);
pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
pthread_once(&g_init, init_g_lock);
pthread_create(&pth,&threadAttr,input_onoff, (void*) on ? "1" : "0");
pthread_attr_destroy(&threadAttr);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
int cnt;
void espera_activa( int tiempo) {
time_t t;
t = time(0) + tiempo;
while(time(0) < t);
}
void *tareaA( void * args) {
printf("tareaA::voy a dormir\\n");
sleep(3);
printf("tareaA::me despierto y pillo mutex\\n");
pthread_mutex_lock(&mutex);
printf("tareaA::incremento valor\\n");
++cnt;
printf("tareaA::desbloqueo mutex\\n");
pthread_mutex_unlock(&mutex);
printf("tareaA::FINISH\\n");
}
void *tareaM( void * args) {
printf("\\ttareaM::me voy a dormir\\n");
sleep(5);
printf("\\ttareaM::me despierto y hago espera activa\\n");
espera_activa(15);
printf("\\ttareaM::FINSIH\\n");
}
void *tareaB( void * args) {
printf("\\t\\ttareaB::me voy a dormir\\n");
sleep(1);
printf("\\t\\ttareaB::me despierto y pillo mutex\\n");
pthread_mutex_lock(&mutex);
printf("\\t\\ttareaB::espera activa\\n");
espera_activa(7);
printf("\\t\\ttareaB::incremento cnt\\n");
++cnt;
printf("\\t\\ttareaB::suelto mutex\\n");
pthread_mutex_unlock(&mutex);
printf("\\t\\ttareaB::FINISH\\n");
}
int main() {
pthread_t hebraA, hebraM, hebraB;
pthread_attr_t attr;
pthread_mutexattr_t attrM;
struct sched_param prio;
cnt = 0;
pthread_mutexattr_init(&attrM);
if( pthread_mutexattr_setprotocol(&attrM, PTHREAD_PRIO_INHERIT) != 0) {
printf("ERROR en __set_protocol\\n");
exit(-1);
}
if( pthread_mutexattr_setprioceiling(&attrM, 3) != 0){
printf("ERROR en __setprioceiling\\n");
}
pthread_mutex_init(&mutex, &attrM);
if( pthread_attr_init( &attr) != 0) {
printf("ERROR en __attr_init\\n");
exit(-1);
}
if( pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED) != 0){
printf("ERROR __setinheritsched\\n");
exit(-1);
}
if( pthread_attr_setschedpolicy( &attr, SCHED_FIFO) != 0) {
printf("ERROR __setschedpolicy\\n");
exit(-1);
}
int error;
prio.sched_priority = 1;
if( pthread_attr_setschedparam(&attr, &prio) != 0) {
printf("ERROR __attr_setschedparam %d\\n", error);
exit(-1);
}
if( (error=pthread_create(&hebraB, &attr, tareaB, 0)) != 0) {
printf("ERROR __pthread_create \\ttipo: %d\\n", error);
exit(-1);
}
prio.sched_priority = 2;
if( pthread_attr_setschedparam(&attr, &prio) != 0) {
printf("ERROR __attr_setschedparam\\n");
exit(-1);
}
if( pthread_create(&hebraM, &attr, tareaM, 0) != 0) {
printf("ERROR __pthread_create\\n");
exit(-1);
}
prio.sched_priority = 3;
if( pthread_attr_setschedparam(&attr, &prio) != 0) {
printf("ERROR __attr_setschedparam\\n");
exit(-1);
}
if( pthread_create(&hebraA, &attr, tareaA, 0) != 0) {
printf("ERROR __pthread_create\\n");
exit(-1);
}
pthread_join(hebraA, 0);
pthread_join(hebraM, 0);
pthread_join(hebraB, 0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_t t[100];
pthread_mutex_t m[100];
void* Do_Stuff(void *ptr){
int id = *(int*)ptr;
free(ptr);
printf("The thread %d started\\n", id);
pthread_mutex_lock(m + id);
while(1){
printf("Give no:");
int nr;
scanf("%d", &nr);
if(no >= 0 && nr < n);
if(pthread_mutex_trylock(&m[nr]) == 0){
printf("Waiting thread no %d\\n", no);
pthread_mutex_unlock(&m[nr]);
pthread_mutex_unloc(&m[id]);
break;
}
else{
pthread_mutex_unlock(&m[nr]);
}
}
printf("Thread with id %d is done\\n", id);
return 0;
}
int main(){
printf("Give the number o threads:\\n");
scanf("%d", &n);
for(i = 0 ; i < n ; i++){
pthread_mutex_init(&m[i], 0);
pthread_mutex_lock(&m[i]);
}
for(i = 0 ; i < n ; i++){
int *ci = malloc(sizeof(int));
*ci = i;
if(pthread_create(&t[i], 0, Do_Stuff, ci)){
perror("can't create thread\\n");
exit(1);
}
}
for(i = 0 ; i < n ; i++){
pthread_join(t[i], 0);
}
for(i = 0 ; i < n ; i++){
pthread_mutex_destroy(&m[i]);
}
return 0;
}
| 0
|
#include <pthread.h>
sem_t male, female;
pthread_cond_t vacio;
pthread_mutex_t candado;
int variable;
int valueHombre, valueMujer;
void* hombre(void* args);
void* mujer(void* args);
int main(int argc, char* argv[]){
if(argc!=2){
printf("ERROR de argumentos. <%s> <numero de hebras>\\n",argv[0]);
exit(-1);
}
sem_init(&male, 0, 3);
sem_init(&female, 0, 3);
pthread_mutex_init(&candado, 0);
pthread_cond_init(&vacio, 0);
int numHebras = atoi(argv[1]), i;
pthread_t* hombres, *mujeres;
hombres = (pthread_t *) malloc (sizeof(pthread_t)*numHebras);
mujeres = (pthread_t *) malloc (sizeof(pthread_t)*numHebras);
for(i=0 ; i<numHebras; i++){
pthread_create(&hombres[i], 0, (void*)hombre, 0);
pthread_create(&mujeres[i], 0, (void*)mujer, 0);
}
for(i=0 ; i<numHebras; i++){
pthread_join(hombres[i], 0);
pthread_join(mujeres[i], 0);
}
pthread_exit(0);
}
void* hombre(void* args){
pthread_mutex_lock(&candado);
while(variable==-1){
printf("Hay mujeres en WC\\n");
pthread_cond_wait(&vacio, &candado);
}
variable=1;
pthread_mutex_unlock(&candado);
sem_wait(&male);
printf("-> entra hombre\\n");
sleep(2);
sem_post(&male);
printf("<- sale hombre\\n");
pthread_mutex_lock(&candado);
sem_getvalue(&male, &valueHombre);
if(valueHombre==3){
variable=0;
pthread_cond_signal(&vacio);
printf("Han salido los hombres y el WC esta vacio\\n");
}
pthread_mutex_unlock(&candado);
pthread_exit(0);
}
void* mujer(void* args){
pthread_mutex_lock(&candado);
while(variable==1){
printf("Hay hombres en WC\\n");
pthread_cond_wait(&vacio, &candado);
}
variable=-1;
pthread_mutex_unlock(&candado);
sem_wait(&female);
printf("-> entra mujer\\n");
sleep(2);
printf("<- sale mujer\\n");
sem_post(&female);
pthread_mutex_lock(&candado);
sem_getvalue(&female, &valueMujer);
if(valueMujer==3){
variable=0;
pthread_cond_signal(&vacio);
printf("Han salido las mujeres y el WC esta vacio\\n");
}
pthread_mutex_unlock(&candado);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
char buffer[9][18] = { 0 };
int start = 0;
int end = 0;
int size = 0;
FILE *in;
FILE *out;
pthread_t producer;
pthread_t consumer;
pthread_mutex_t buf_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t empty_slot = PTHREAD_COND_INITIALIZER;
pthread_cond_t item_avail = PTHREAD_COND_INITIALIZER;
void *pro()
{
char c = 1;
while (c != EOF)
{
pthread_mutex_lock(&buf_lock);
while(size >= 9)
{
pthread_cond_wait(&empty_slot, &buf_lock);
}
int i;
for (i = 0; i < 18 && c != EOF; i++)
{
c = (char)fgetc(in);
buffer[end][i] = c;
}
end = (end + 1) % 9;
size++;
pthread_cond_signal(&item_avail);
pthread_mutex_unlock(&buf_lock);
}
}
void *con()
{
char c = 1;
while (c != EOF) {
pthread_mutex_lock(&buf_lock);
while(size == 0)
{
pthread_cond_wait(&item_avail, &buf_lock);
}
int i;
for (i = 0; i < 18; i++)
{
c = (char)buffer[start][i];
if (c == EOF)
{
break;
}
putc(c, out);
}
start = (start + 1) % 9;
size--;
pthread_cond_signal(&empty_slot);
pthread_mutex_unlock(&buf_lock);
}
}
int main(int argc, char *argv[])
{
if (argc != 3)
{
printf("File was used properly\\n");
return 0;
}
in = fopen(argv[1], "r");
if (in == 0)
{
printf("Problem with input file is detected\\n");
return 0;
}
out = fopen(argv[2], "w");
pthread_cond_signal(&item_avail);
pthread_create(&producer, 0, pro, (void *)0);
pthread_create(&consumer, 0, con, (void *)0);
pthread_join(producer, 0);
fclose(in);
pthread_join(consumer, 0);
fclose(out);
pthread_cond_destroy(&item_avail);
pthread_cond_destroy(&empty_slot);
pthread_mutex_destroy(&buf_lock);
printf("All actions have been completed\\n");
return 0;
}
| 0
|
#include <pthread.h>
int chopstick[5] = {0,0,0,0,0};
int state[5];
pthread_cond_t chopstic_cond[5] = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex_lock = PTHREAD_MUTEX_INITIALIZER;
void pick_chopstick(int id)
{
pthread_mutex_lock(&mutex_lock);
sleep(1);
if(state[id] == 1 && chopstick[id]==0 && chopstick[(id+1)%5]==0){
pthread_cond_wait(&chopstic_cond[id],&mutex_lock);
chopstick[id] = 1;
printf("philosopher %d is pick up the left chopstick %d .\\n",id,id);
pthread_cond_wait(&chopstic_cond[(id+1)%5],&mutex_lock);
chopstick[(id+1)%5] = 1;
printf("philosopher %d is pick up the right chopstick %d .\\n",id,(id+1)%5);
}
else{
}
pthread_mutex_unlock(&mutex_lock);
}
void take_down_chopstick(int id)
{
pthread_mutex_lock(&mutex_lock);
chopstick[id] = 0;
printf("philosopher %d is take down the left chopstick %d .\\n",id,id);
pthread_cond_signal(&chopstic_cond[id]);
pthread_mutex_unlock(&mutex_lock);
pthread_mutex_lock(&mutex_lock);
chopstick[(id+1)%5] = 0;
printf("philosopher %d is take down the right chopstick %d .\\n",id,(id+1)%5);
pthread_cond_signal(&chopstic_cond[(id+1)%5]);
state[id]= 0;
pthread_mutex_unlock(&mutex_lock);
}
void *philosopher(void* data)
{
int id = (int)data;
while(1){
int sleep_time = (int)((random() % 3) + 1);
printf("Philosopher %d is thinking\\n",id);
sleep(sleep_time);
state[id] = 1;
printf("philosopher %d is hungry.\\n",id);
pick_chopstick(id);
if(chopstick[id] == 1 && chopstick[(id+1)%5] ==1)
{
state[id] = 2;
printf("philosopher %d is eating.\\n",id);
sleep(1);
take_down_chopstick(id);
}
}
}
int main(){
int i=0;
pthread_t pthred_philosopher[5];
for(i=0;i<5;i++){
pthread_create(&pthred_philosopher[i],0,philosopher,i);
state[i]=0;
}
for(i=0;i<5;i++){
pthread_join(pthred_philosopher[i],0);
}
return 0;
}
| 1
|
#include <pthread.h>
char* buf[5];
int pos;
pthread_mutex_t mutex;
void* task(void* p)
{
pthread_mutex_lock(&mutex);
buf[pos] = p;
sleep(1);
pos++;
pthread_mutex_unlock(&mutex);
}
int main(void)
{
pthread_mutex_init(&mutex,0);
pthread_t tid,tid2;
pthread_create(&tid,0,task,"zhangfei");
pthread_create(&tid2,0,task,"guanyu");
pthread_join(tid,0);
pthread_join(tid2,0);
pthread_mutex_destroy(&mutex);
int i = 0;
printf("字符指针数组中的内容是:");
for(i = 0; i < pos; i++)
{
printf("%s ",buf[i]);
}
printf("\\n");
return 0;
}
| 0
|
#include <pthread.h>
int counter = 0;
pthread_mutex_t lock;
void thread1(void *arg);
void thread2(void *arg);
int main(int argc, char * argv[])
{
pthread_t id1, id2;
if(pthread_mutex_init(&lock, 0) != 0){
printf("mutex init failed.\\n");
exit(1);
}
pthread_create(&id1, 0, (void *) thread1, 0);
pthread_create(&id2, 0, (void *) thread2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
printf("The final value of counter is %d\\n", counter);
exit(0);
}
void thread1(void *arg){
int i, val;
for(i = 1; i <= 5; i++){
printf("[thread1, loop%d]Entering loop\\n", i);
pthread_mutex_lock(&lock);
val = ++counter;
printf("[thread1, loop%d]\\tcounter value++, and saved as val:%d\\n",i, val);
printf("[thread1, loop%d] \\t\\tfirst ref: counter = %d\\n", i, counter);
printf("[thread1, loop%d]\\tEntering 300us wait.\\n", i);
usleep(300);
printf("[thread1, loop%d] \\t\\tsecond ref: counter = %d\\n", i, counter);
counter = val;
printf("[thread1, loop%d]\\tcounter value restored to val:%d\\n",i, val);
pthread_mutex_unlock(&lock);
}
}
void thread2(void *arg){
int i, val;
for(i = 1; i <= 5; i++){
printf("[thread2, loop%d]\\t\\t\\t\\t\\t\\tEntering loop\\n", i);
pthread_mutex_lock(&lock);
val = ++counter;
printf("[thread2, loop%d]\\t\\t\\t\\t\\t\\t\\tcounter value++, and saved as val:%d\\n",i, val);
printf("[thread2, loop%d]\\t\\t\\t\\t\\t\\t\\tEntering 100us wait.\\n", i);
usleep(100);
printf("[thread2, loop%d]\\t\\t\\t\\t\\t\\t\\tcounter = %d\\n", i, counter);
counter = val;
printf("[thread2, loop%d]\\t\\t\\t\\t\\t\\t\\tcounter value restored to val:%d\\n",i, val);
pthread_mutex_unlock(&lock);
}
}
| 1
|
#include <pthread.h>
int ticketcount;
pthread_mutex_t lock;
pthread_cond_t cond1,cond2;
}NODE,*pNODE;
void* sale(void* arg)
{
pNODE p = (pNODE)arg;
while(1){
pthread_mutex_lock(&p->lock);
while(p->ticketcount <= 0)
{
pthread_cond_signal(&p->cond2);
pthread_cond_wait(&p->cond1,&p->lock);
}
printf("%d sell %d\\n",getpid(),p->ticketcount);
p->ticketcount--;
pthread_mutex_unlock(&p->lock);
}
}
void* putter(void* arg)
{
pNODE p = (pNODE)arg;
while(1){
pthread_mutex_lock(&p->lock);
while(p->ticketcount > 0){
pthread_cond_wait(&p->cond2,&p->lock);
pthread_cond_signal(&p->cond1);
}
p->ticketcount += 10;
printf("tickets on\\n");
sleep(1);
pthread_mutex_unlock(&p->lock);
}
}
int main(int argc,char* argv[])
{
if(argc!=3)
{
printf("wrong argv!\\n");
exit(1);
}
int m = atoi(argv[1]);
int n = atoi(argv[2]);
pthread_t arr[m+n];
memset(arr,0,sizeof(arr));
NODE anode;
memset(&anode,0,sizeof(anode));
if(pthread_mutex_init(&anode.lock, 0)!=0)
{
printf("mutex_init fail!\\n");
exit(1);
}
anode.ticketcount = 0;
if(pthread_cond_init(&anode.cond1,0))
{
printf("cond_init fail!\\n");
exit(1);
}
if(pthread_cond_init(&anode.cond2,0))
{
printf("cond_init fail!\\n");
exit(1);
}
int index = 0;
while(m){
if(pthread_create(&arr[index],0,sale,(void*)&anode)!=0)
{
printf("pthread_create sale fail!\\n");
exit(1);
}
m--;
index++;
}
while(n){
if(pthread_create(&arr[index],0,putter,(void*)&anode)!=0){
printf("pthread_create putter fail\\n");
exit(1);
}
n--;
index++;
}
index--;
while(index)
{
pthread_join(arr[index],0);
index--;
}
pthread_cond_destroy(&anode.cond1);
pthread_cond_destroy(&anode.cond2);
return 0;
}
| 0
|
#include <pthread.h>
void *handler ( void *ptr );
static pthread_mutex_t mutex ;
int counter;
int main()
{
int cnt;
int i[4];
pthread_t threads[4];
for (cnt = 0; cnt < 4; cnt++){
i[cnt] = cnt;
}
if (pthread_mutex_init(&mutex, 0)){
printf("ERROR on INIT of MUTEX\\n");
exit(-1);
}
for (cnt = 0; cnt < 4; cnt++){
if( pthread_create (&threads[cnt], 0, handler, (void *) &i[cnt])){
printf("ERROR on create1\\n");
exit(-1);
}
}
for (cnt = 0; cnt < 4; cnt++){
if (pthread_join(threads[cnt], 0)){
printf("error on join\\n");
exit(-1);
}
}
if (pthread_mutex_destroy(&mutex)){
printf("error destroying\\n");
exit(-1);
}
exit(0);
}
void *handler ( void *ptr )
{
int x;
x = *((int *) ptr);
printf("Thread %d: *** Waiting to enter critical region...\\n", x);
pthread_mutex_lock(&mutex);
printf("Thread %d: Now in critical region...\\n", x);
printf("Thread %d: Counter Value: %d\\n", x, counter);
printf("Thread %d: Incrementing Counter...\\n", x);
counter++;
printf("Thread %d: New Counter Value: %d\\n", x, counter);
printf("Thread %d: Exiting critical region...\\n", x);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
sem_t estudante;
sem_t monitor;
pthread_mutex_t mutex;
int cadeira[4];
int count = 0;
int proxAcento = 0;
int proxEnsinar = 0;
void dormirAleatorio();
void *jogando(void* stu_id);
void *monitorEnsinado();
int main(int argc, char **argv){
pthread_t *estudantes;
pthread_t monitorEnsina;
int *idEstudante, numEstudante, i;
printf("Informe a quantidade de estudantes: ");
scanf("%d", &numEstudante);
estudantes = (pthread_t*)malloc(sizeof(pthread_t) *numEstudante);
idEstudante = (int*)malloc(sizeof(int) *numEstudante);
memset(idEstudante, 0, numEstudante);
sem_init(&estudante,0,0);
sem_init(&monitor,0,1);
srand(time(0));
pthread_mutex_init(&mutex,0);
pthread_create(&monitorEnsina, 0, monitorEnsinado, 0);
for(i = 0; i < numEstudante; i++){
idEstudante[i] = i+1;
pthread_create(&estudantes[i], 0, jogando, (void*) &idEstudante[i]);
}
pthread_join(monitorEnsina, 0);
for(i = 0; i < numEstudante; i++){
pthread_join(estudantes[i],0);
}
return 0;
}
void *jogando(void *stu_id){
int id = *(int*)stu_id;
printf("O estudante %d está sendo ajudado.\\n",id);
while(1){
dormirAleatorio();
pthread_mutex_lock(&mutex);
if(count < 4){
cadeira[proxAcento] = id;
count++;
printf("O estudante %d está jogando \\n", id);
printf("Os estudantes: [1] %d [2] %d [3] %d [4] %d estão jogando.\\n", cadeira[0],cadeira[1],cadeira[2], cadeira[3]);
proxAcento = (proxAcento+1) % 4;
pthread_mutex_unlock(&mutex);
sem_post(&estudante);
sem_wait(&monitor);
}
else{
pthread_mutex_unlock(&mutex);
printf("Não existe cadeira disponíveis. O estudante %d está jogando \\n", id);
}
}
}
void *monitorEnsinado(){
while(1){
sem_wait(&estudante);
pthread_mutex_lock(&mutex);
printf("O monitor está sanando dúvidas do estudante: %d\\n",cadeira[proxEnsinar]);
cadeira[proxEnsinar]=0;
count--;
printf("Os estudantes: [1] %d [2] %d [3] %d [4] %d estão jogando \\n", cadeira[0], cadeira[1], cadeira[2], cadeira[3]);
proxEnsinar = (proxEnsinar + 1) % 4;
dormirAleatorio();
printf("Monitor terminou de sanar dúvidas.\\n\\n");
pthread_mutex_unlock(&mutex);
sem_post(&monitor);
}
}
void dormirAleatorio(){
int time = rand() % 2 + 1;
sleep(time);
}
| 0
|
#include <pthread.h>
int thread_flag;
pthread_cond_t thread_flag_cv;
pthread_mutex_t thread_flag_mutex;
void initialize_flag() {
pthread_mutex_init(&thread_flag_mutex, 0);
pthread_cond_init(&thread_flag_cv, 0);
thread_flag = 0;
}
void do_work(){
printf(" [_work_] | doing work now ... \\n");
sleep(1);
}
void* thread_function(void* thread_arg) {
while (1) {
pthread_mutex_lock(&thread_flag_mutex);
while(!thread_flag){
printf(" [thread] | wait... \\n");
pthread_cond_wait(&thread_flag_cv, &thread_flag_mutex);
}
pthread_mutex_unlock(&thread_flag_mutex);
do_work();
}
return 0;
}
void set_thread_flag(int flag_value) {
pthread_mutex_lock(&thread_flag_mutex);
thread_flag = flag_value;
pthread_cond_signal(&thread_flag_cv);
pthread_mutex_unlock(&thread_flag_mutex);
}
void main(int argc, char* argv[]){
pthread_t thread;
initialize_flag();
pthread_create(&thread, 0, &thread_function, 0);
while(1){
printf(" [_main_] | wait... \\n");
thread_flag=!thread_flag;
pthread_cond_broadcast(&thread_flag_cv);
sleep(2);
}
pthread_join(thread, 0);
return;
}
| 1
|
#include <pthread.h>
int array[3] ={0,0,0};
pthread_mutex_t mutex;
pthread_cond_t cond;
int count;
} semaphore_t;
void init_sem(semaphore_t *s, int i)
{
s->count = i;
pthread_mutex_init(&(s->mutex), 0);
pthread_cond_init(&(s->cond), 0);
}
void P(semaphore_t *sem)
{
pthread_mutex_lock (&(sem->mutex));
sem->count--;
if (sem->count < 0)
pthread_cond_wait(&(sem->cond), &(sem->mutex));
pthread_mutex_unlock (&(sem->mutex));
}
void V(semaphore_t * sem)
{
pthread_mutex_lock (&(sem->mutex));
sem->count++;
if (sem->count <= 0) {
pthread_cond_signal(&(sem->cond));
}
pthread_mutex_unlock (&(sem->mutex));
pthread_yield();
}
int n_array[3] = {1, 1, 1};
int n = 0;
semaphore_t mutex;
void function_reader(void)
{
while (1){
if(n_array[0] == 1 && n_array[1] == 1 && n_array[2] == 1){
P(&mutex);
int i = 0;
for(i = 0; i <= 2; i++){
printf("parent consuming child: %d having value: %d \\n", i, array[i]);
}
sleep(1);
V(&mutex);
int j = 0;
for(j = 0; j <= 2; j++){
n_array[j]--;
}
}
}
}
void function_writer(void)
{
int local_n = n;
n++;
while (1){
if(n_array[local_n] == 0){
P(&mutex);
array[local_n]++;
sleep(1);
V(&mutex);
n_array[local_n]++;
}
}
}
int main()
{
int n0 = 0;
int n1 = 1;
int n2 = 2;
init_sem(&mutex, 1);
start_thread(function_reader, 0);
start_thread(function_writer, 0);
start_thread(function_writer, 0);
start_thread(function_writer, 0);
while(1) sleep(1);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t turno = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t bd = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int rc = 0;
void * ler(void * arg){
int i = *((int*) arg);
while(1){
pthread_mutex_lock(&turno);
pthread_mutex_lock(&mutex);
rc = rc + 1;
if(rc == 1){
pthread_mutex_lock(&bd);
}
pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&turno);
printf("leitor %d lendo dados bd %d\\n", i, rc);
sleep(2);
pthread_mutex_lock(&mutex);
rc = rc - 1;
if(rc == 0){
pthread_mutex_unlock(&bd);
}
pthread_mutex_unlock(&mutex);
printf("dados lidos sendo usados\\n");
sleep(2);
}
pthread_exit(0);
}
void * escrever(void * arg){
int i = *((int *) arg);
while(1){
printf("escritor %d precisa escrever no bd\\n", i);
sleep(2);
pthread_mutex_lock(&turno);
pthread_mutex_lock(&bd);
printf("escritor %d escrevendo no bd\\n", i);
sleep(2);
pthread_mutex_unlock(&bd);
pthread_mutex_unlock(&turno);
}
pthread_exit(0);
}
int main() {
pthread_t l[20];
pthread_t e[10];
int i;
int *id;
for (i = 0; i < 20 ; i++) {
id = (int *) malloc(sizeof(int));
*id = i;
pthread_create(&l[i], 0, ler, (void *) (id));
}
for (i = 0; i < 10 ; i++) {
id = (int *) malloc(sizeof(int));
*id = i;
pthread_create(&e[i], 0, escrever, (void *) (id));
}
pthread_join(l[0],0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_cond_t myCond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t myLock = PTHREAD_MUTEX_INITIALIZER;
{
int _data;
struct ListNode* _next;
}Node,*pNode,**ppNode;
pNode AllocNode(int data)
{
pNode NewNode = (pNode)malloc(sizeof(Node));
if(NewNode == 0)
{
perror("malloc");
return 0;
}
NewNode->_next = 0;
NewNode->_data = data;
return NewNode;
}
void DeallocNode(pNode node)
{
if(node != 0)
free(node);
}
int IsEmpty(pNode head)
{
assert(head);
if(head -> _next == 0)
return 1;
else
return 0;
}
void InitList(ppNode l)
{
assert(l);
pNode head = AllocNode(0);
*l = head;
if(head == 0)
{
printf("申请头结点失败\\n");
perror("AllocNode");
}
return ;
}
void PushNode(pNode head,int data)
{
assert(head);
pNode NewNode = AllocNode(data);
if(NewNode == 0)
{
perror("AllocNode");
return;
}
NewNode->_next = head->_next;
head->_next = NewNode;
}
void PopNode(pNode head)
{
assert(head);
if(IsEmpty(head))
return;
Node* del = head->_next;
head->_next = del->_next;
DeallocNode(del);
}
void DestroyList(pNode head)
{
assert(head);
Node* cur = head->_next;
while(cur)
{
PopNode(head);
cur = cur->_next;
}
DeallocNode(head);
}
void ShowList(pNode head)
{
assert(head);
Node* cur = head->_next;
while(cur)
{
printf("%d ",cur->_data);
cur = cur->_next;
}
printf("\\n");
}
void* Product(void* h)
{
assert(h);
pNode head = h;
while(1)
{
sleep(1);
int data = rand()%1000;
pthread_mutex_lock(&myLock);
PushNode(head,data);
printf("Product:%d\\n",data);
pthread_mutex_unlock(&myLock);
pthread_cond_signal(&myCond);
}
return 0;
}
void* Consumer(void* h)
{
assert(h);
pNode head = h;
while(1)
{
pthread_mutex_lock(&myLock);
while(IsEmpty(head))
{
pthread_cond_wait(&myCond,&myLock);
}
printf("Consumer:%d\\n",head->_next->_data);
PopNode(head);
pthread_mutex_unlock(&myLock);
}
return 0;
}
void test()
{
pNode head;
InitList(&head);
if(head == 0)
return;
pthread_t tid1;
pthread_t tid2;
pthread_create(&tid1,0,Product,(void*)head);
pthread_create(&tid2,0,Consumer,(void*)head);
pthread_join(tid1,0);
pthread_join(tid2,0);
return ;
}
int main()
{
test();
return 0;
}
| 0
|
#include <pthread.h>
struct data {
long counter[256];
};
const int SIZE = sizeof(struct data);
static pthread_mutex_t mutex_arr[256];
static pthread_mutex_t output_mutex;
static struct data data;
void handle_error(long return_code, const char *msg, int in_thread) {
if (return_code < 0) {
char extra_txt[16384];
char error_msg[16384];
char *extra_msg = extra_txt;
int myerrno = errno;
const char *error_str = strerror(myerrno);
if (msg != 0) {
sprintf(extra_msg, "%s\\n", msg);
} else {
extra_msg = "";
}
sprintf(error_msg, "%sreturn_code=%ld\\nerrno=%d\\nmessage=%s\\n", extra_msg, return_code, myerrno, error_str);
write(STDOUT_FILENO, error_msg, strlen(error_msg));
if (in_thread) {
pthread_exit(0);
} else {
exit(1);
}
}
}
void *run(void *raw_name) {
int retcode;
time_t thread_start = time(0);
char *name = (char *) raw_name;
int fd = -1;
time_t open_start = time(0);
while (fd == -1) {
fd = open(raw_name, O_RDONLY);
if (fd < 0 && errno == EMFILE) {
sleep(1);
continue;
}
if (fd < 0) {
char msg[256];
sprintf(msg, "error while opening file=%s", name);
handle_error(fd, msg, 1);
}
}
time_t open_duration = time(0) - open_start;
time_t total_mutex_wait = 0;
char buffer[16384];
while (1) {
ssize_t size_read = read(fd, buffer, 16384);
if (size_read == 0) {
break;
}
if (size_read < 0) {
if (errno == 9) {
close(fd);
pthread_exit(0);
}
char msg[256];
sprintf(msg, "error while reading file=%s", name);
handle_error(size_read, msg, 1);
}
int i;
for (i = 0; i < size_read; i++) {
unsigned char c = buffer[i];
time_t t0 = time(0);
retcode = pthread_mutex_lock(&(mutex_arr[c]));
time_t dt = time(0) - t0;
total_mutex_wait += dt;
handle_error(retcode, "error while getting mutex", 1);
long *counter = data.counter;
counter[c]++;
retcode = pthread_mutex_unlock(& (mutex_arr[c]));
handle_error(retcode, "error while releasing mutex", 1);
}
}
close(fd);
time_t thread_duration = time(0) - thread_start;
unsigned int i;
pthread_mutex_lock(&output_mutex);
printf("------------------------------------------------------------\\n");
printf("%s: pid=%ld\\n", name, (long) getpid());
printf("open duration: ~ %ld sec; total wait for data: ~ %ld sec; thread duration: ~ %ld\\n", (long) open_duration, (long) total_mutex_wait, (long) thread_duration);
printf("------------------------------------------------------------\\n");
for (i = 0; i < 256; i++) {
long *counter = data.counter;
retcode = pthread_mutex_lock(&(mutex_arr[i]));
handle_error(retcode, "error while getting mutex", 1);
long val = counter[i];
retcode = pthread_mutex_unlock(& (mutex_arr[i]));
handle_error(retcode, "error while releasing mutex", 1);
if (! (i & 007)) {
printf("\\n");
}
if ((i & 0177) < 32 || i == 127) {
printf("\\\\%03o: %10ld ", i, val);
} else {
printf("%4c: %10ld ", (char) i, val);
}
}
printf("\\n\\n");
printf("------------------------------------------------------------\\n\\n");
fflush(stdout);
pthread_mutex_unlock(&output_mutex);
return 0;
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage\\n\\n");
printf("%s file1 file2 file3 ... filen\\ncount files, show accumulated output after having completed one file\\n\\n", argv[0]);
exit(1);
}
time_t start_time = time(0);
int retcode = 0;
int i;
printf("%d files will be read\\n", argc-1);
fflush(stdout);
for (i = 0; i < 256; i++) {
data.counter[i] = 0L;
}
for (i = 0; i < 256; i++) {
retcode = pthread_mutex_init(&(mutex_arr[i]), 0);
handle_error(retcode, "creating mutex", 0);
}
retcode = pthread_mutex_init(&output_mutex, 0);
handle_error(retcode, "creating mutex", 0);
pthread_t *threads = malloc((argc-1)*sizeof(pthread_t));
for (i = 1; i < argc; i++) {
retcode = pthread_create(&(threads[i-1]), 0, run, argv[i]);
handle_error(retcode, "starting thread", 0);
}
pthread_mutex_lock(&output_mutex);
printf("%d threads started\\n", argc-1);
fflush(stdout);
pthread_mutex_unlock(&output_mutex);
for (i = 0; i < argc-1; i++) {
retcode = pthread_join(threads[i], 0);
handle_error(retcode, "joining thread", 0);
}
for (i = 0; i < 256; i++) {
retcode = pthread_mutex_destroy(&(mutex_arr[i]));
handle_error(retcode, "destroying mutex", 0);
}
retcode = pthread_mutex_destroy(&output_mutex);
handle_error(retcode, "destroying mutex", 0);
time_t total_time = time(0) - start_time;
printf("total %ld sec\\n", (long) total_time);
printf("done\\n");
exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t m;
struct ThreadPool pool;
int *ptr;
size_t num;
int depth;
} args_t;
struct Task **array;
size_t size;
size_t capacity;
} tarray_t;
void add_task_array(tarray_t *t, struct Task *task) {
if (t->size == t->capacity) {
t->capacity *= 2;
t->array = (struct Task **) realloc(t->array, t->capacity * sizeof(struct Task *));
}
t->array[t->size++] = task;
}
void init_task_array(tarray_t *t) {
t->size = 0;
t->capacity = 2;
t->array = (struct Task **) malloc(t->capacity * sizeof(struct Task *));
}
tarray_t my_tasks;
void destroy_task(struct Task *my_task) {
pthread_mutex_destroy(&my_task->m);
pthread_cond_destroy(&my_task->cond);
free(my_task->arg);
free(my_task);
}
void add_task(struct Task *task) {
thpool_submit(&pool, task);
add_task_array(&my_tasks, task);
}
void quicksort(void *args);
void task_init_qsort(struct Task *my_task, int *ptr, size_t num, int depth) {
pthread_mutex_init(&my_task->m, 0);
pthread_cond_init(&my_task->cond, 0);
my_task->done = 0;
my_task->f = quicksort;
args_t *args = (args_t *) malloc(sizeof(args_t));
args->ptr = ptr;
args->num = num;
args->depth = depth;
my_task->arg = args;
}
int int_cmp(const void *a, const void *b) {
if (*((int *) a) > *((int *) b)) {
return 1;
}
if (*((int *) a) == *((int *) b)) {
return 0;
}
return -1;
}
void swap_int(int *a, int *b) {
int c = *a;
*a = *b;
*b = c;
}
void quicksort(void *args) {
int *ptr = ((args_t *) args)->ptr;
size_t num = ((args_t *) args)->num;
int depth = ((args_t *) args)->depth;
if (num <= 1) {
return;
}
if (depth <= 0) {
qsort(ptr, num, sizeof(int), int_cmp);
return;
}
int mid = *(ptr + num / 2);
int i = 0, j = num - 1;
while (i <= j) {
while (*(ptr + i) < mid) ++i;
while (*(ptr + j) > mid) --j;
if (i <= j) swap_int(ptr + i++, ptr + j--);
}
pthread_mutex_lock(&m);
struct Task *task1 = (struct Task *) malloc(sizeof(struct Task));
struct Task *task2 = (struct Task *) malloc(sizeof(struct Task));
task_init_qsort(task1, ptr, j + 1, depth - 1);
task_init_qsort(task2, ptr + i, num - i, depth - 1);
add_task(task1);
add_task(task2);
pthread_mutex_unlock(&m);
}
int main(int argc, char **argv) {
srand(42);
int threads = atoi(argv[1]);
size_t n = atoi(argv[2]);
int max_depth = atoi(argv[3]);
int *array = (int *) malloc(n * sizeof(int));
for (size_t i = 0; i < n; ++i) {
array[i] = rand();
}
pthread_mutex_init(&m, 0);
pthread_mutex_lock(&m);
init_task_array(&my_tasks);
thpool_init(&pool, threads);
struct Task *my_task = (struct Task *) malloc(sizeof(struct Task));
task_init_qsort(my_task, &array[0], n, max_depth);
add_task(my_task);
pthread_mutex_unlock(&m);
for (size_t i = 0; i < my_tasks.size; ++i) {
thpool_wait(my_tasks.array[i]);
destroy_task(my_tasks.array[i]);
}
free(my_tasks.array);
for (int i = 0; i < (int) n - 1; ++i) {
assert(array[i] <= array[i + 1]);
}
free(array);
thpool_finit(&pool);
pthread_mutex_destroy(&m);
return 0;
}
| 0
|
#include <pthread.h>
void printClinicalHistory(int index, int clientfd, int r){
pthread_mutex_lock(&lock);
sem_wait(semaforo);
read(pipefd[0], &witness, sizeof(char));
if(index < 0 || index >= dogAmount){
printf("\\nNumero de registro invalido");
fflush(stdout);
return;
}
char path[60];
sprintf(path, "%s%i%s","history/server/",(index+1), ".txt");
historicalTxt = fopen(path, "r+");
if(historicalTxt == 0){
historicalTxt = fopen(path, "w+");
if(historicalTxt == 0){
perror("Error creando el archivo de historia para el registro");
exit(-1);
}else{
fseek(dataDogs, sizeof(struct dogType)*index, 0);
struct dogType *pet;
pet = malloc(sizeof(struct dogType));
size_t response = fread(pet, sizeof(struct dogType), 1, dataDogs);
fseek(historicalTxt, 0, 0);
fwrite("Bienvenido a la historia clinica", sizeof(char), 32, historicalTxt);
fwrite("\\nNombre: ", sizeof(char),9, historicalTxt);
fwrite(pet->name, realLength(pet->name) , 1, historicalTxt);
fwrite("\\nTipo: ", sizeof(char),7, historicalTxt);
fwrite(pet->type, realLength(pet->type) , 1, historicalTxt);
fwrite("\\nEdad: ",sizeof(char), 7, historicalTxt);
fprintf(historicalTxt, "%i", pet->age);
fwrite("\\nRaza: ", sizeof(char),7, historicalTxt);
fwrite(pet->race, realLength(pet->race) , 1, historicalTxt);
fwrite("\\nAltura: ", sizeof(char), 8, historicalTxt);
fprintf(historicalTxt, "%i", pet->height);
fwrite("\\nPeso: ", sizeof(char), 7, historicalTxt);
fprintf(historicalTxt, "%lf", pet->weight);
fwrite("\\nGenero: ", sizeof(char), 8, historicalTxt);
fwrite(&pet->gender,sizeof(char), 1, historicalTxt);
fwrite("\\n\\nObservaciones:", sizeof(char), 16, historicalTxt);
free(pet);
}
}
fseek(historicalTxt, 0, 2);
int fsize = ftell(historicalTxt);
fseek(historicalTxt, 0, 0);
char stringHistory [fsize + 1];
fread(stringHistory, fsize, 1, historicalTxt);
fclose(historicalTxt);
stringHistory[fsize] = 0;
r = send(clientfd, &fsize, sizeof(int), 0);
r = send(clientfd, &stringHistory, fsize, 0);
int sizeOfString = 0;
r = recv(clientfd, &sizeOfString, sizeof(int), 0);
char stringHistoryUpdated[sizeOfString+1];
r = recv(clientfd, &stringHistoryUpdated, sizeOfString, 0);
char pathNew[60];
sprintf(pathNew, "%s%i%s","history/server/",(index+1), ".txt");
historicalTxt = fopen(pathNew, "w+");
if(historicalTxt == 0){
perror("Error creando el archivo de historia para el registro");
exit(-1);
}else{
fwrite(stringHistoryUpdated, sizeOfString, 1, historicalTxt);
}
fclose(historicalTxt);
write(pipefd[1], &witness, sizeof(char));
sem_post(semaforo);
pthread_mutex_unlock(&lock);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t trigger_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t trigger_bcast = PTHREAD_COND_INITIALIZER;
enum broadcast_t {STATUS, BLACKBOARD, CLEAR};
static int broadcast_type = STATUS;
void trigger_broadcast(int type) {
pthread_mutex_lock(&trigger_mutex);
broadcast_type = type;
pthread_cond_signal(&trigger_bcast);
pthread_mutex_unlock(&trigger_mutex);
}
void trigger_status() {
trigger_broadcast(STATUS);
}
void trigger_blackboard() {
trigger_broadcast(BLACKBOARD);
}
void trigger_clear() {
trigger_broadcast(CLEAR);
}
void broadcast_status() {
struct cl_entry *current;
struct net_status *status;
uint8_t dcount;
uint16_t scount;
uint8_t tcount;
uint8_t permission;
int ret;
current = start_iteration();
dcount = docent_exists();
tcount = tutor_exists();
scount = get_client_count() - dcount - tcount;
while (current != 0) {
if (current == get_write_user()) {
permission = 1;
} else {
permission = 0;
}
status = build_status(current->cdata->role, current->cdata->cid,
permission, dcount, tcount, scount);
ret = send(current->cdata->sfd, status, sizeof(struct net_status), 0);
if (ret < 0) {
perror("send");
}
free(status);
current = iteration_next();
}
log_debug("broadcasting agent: status sent to all connected clients");
end_iteration();
}
void broadcast_blackboard(char *blackboard, int bsem_id, int excl_w) {
struct cl_entry *current;
struct net_board *board;
int ret;
int length;
lock_sem(bsem_id);
length = strlen(blackboard);
board = build_board(blackboard, length);
unlock_sem(bsem_id);
current = start_iteration();
while (current != 0) {
if ((current == get_write_user()) && excl_w) {
current = iteration_next();
continue;
}
ret = send(current->cdata->sfd, board, sizeof(struct net_header) + length, 0);
if (ret < 0) {
perror("send");
}
current = iteration_next();
}
end_iteration();
free(board);
log_debug("broadcasting agent: blackboard sent to all connected clients");
}
void* broadcasting_agent(void *arg) {
int bsem_id;
key_t bsem_key = ftok(FTOK_PATH, BSEM_ID);
bsem_id = get_sem(bsem_key);
int bshm_id;
key_t bshm_key = ftok(FTOK_PATH, BSHM_ID);
bshm_id = get_blackboard(bshm_key);
char *blackboard;
blackboard = blackboard_attach(bshm_id);
log_info("broadcasting agent: waiting for trigger");
pthread_mutex_lock(&trigger_mutex);
while(1) {
pthread_cond_wait(&trigger_bcast, &trigger_mutex);
switch (broadcast_type) {
case STATUS:
log_debug("broadcasting agent: received status trigger");
broadcast_status();
break;
case BLACKBOARD:
log_debug("broadcasting agent: received blackboard trigger");
broadcast_blackboard(blackboard, bsem_id, 1);
break;
case CLEAR:
log_debug("broadcasting agent: received clear trigger");
broadcast_blackboard(blackboard, bsem_id, 0);
break;
}
}
pthread_mutex_unlock(&trigger_mutex);
blackboard_detach(blackboard);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
static pthread_key_t key;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;
extern char **environ;
static void
thread_init(void)
{
pthread_key_create(&key, free);
}
char *
getenv(const char *name)
{
int i, len;
char *envbuf;
pthread_once(&init_done, thread_init);
pthread_mutex_lock(&env_mutex);
envbuf = (char *)pthread_getspecific(key);
if (envbuf == 0) {
envbuf = malloc(4096);
if (envbuf == 0) {
pthread_mutex_unlock(&env_mutex);
return(0);
}
pthread_setspecific(key, envbuf);
}
len = strlen(name);
for (i = 0; environ[i] != 0; i++) {
if ((strncmp(name, environ[i], len) == 0) &&
(environ[i][len] == '=')) {
strncpy(envbuf, &environ[i][len+1], 4096 -1);
pthread_mutex_unlock(&env_mutex);
return(envbuf);
}
}
pthread_mutex_unlock(&env_mutex);
return(0);
}
| 1
|
#include <pthread.h>
int buffer[8];
int head = 0;
int tail = 0;
int num_elem = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t production_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t consume_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t product = PTHREAD_COND_INITIALIZER;
pthread_cond_t consume = PTHREAD_COND_INITIALIZER;
void* produtor(void* threadid) {
int i;
while(i < 20)
{
sleep(1);
if(num_elem < 8){
pthread_mutex_lock(&mutex);
buffer[tail] = rand() % 20;
printf("Produtor %d: Produzi %d.\\n", threadid, buffer[tail]);
tail = (tail+1) % 8;
num_elem++;
i++;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&consume);
}
else{
printf("Produtor %d: Buffer cheio, serei suspenso.\\n", threadid);
pthread_mutex_lock(&production_mutex);
pthread_cond_wait(&product, &production_mutex);
pthread_mutex_unlock(&production_mutex);
printf("Produtor %d: Fui liberado!\\n", threadid);
}
}
pthread_exit(0);
}
void* consumidor(void* threadid) {
int i;
while(i < 20)
{
sleep(2);
if(num_elem > 0){
pthread_mutex_lock(&mutex);
printf("Consumidor %d: Consumi %d.\\n", threadid, buffer[head]);
head = (head+1) % 8;
num_elem--;
i++;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&product);
}
else{
printf("Consumidor %d: Buffer vazio, serei suspenso.\\n", threadid);
pthread_mutex_lock(&consume_mutex);
pthread_cond_wait(&consume, &consume_mutex);
pthread_mutex_unlock(&consume_mutex);
printf("Consumidor %d: Fui liberado!\\n", threadid);
}
}
pthread_exit(0);
}
int main(int argc, char const *argv[])
{
pthread_t threads[4];
pthread_create(&threads[0], 0, produtor, (void *)0);
pthread_create(&threads[1], 0, produtor, (void *)1);
pthread_create(&threads[2], 0, consumidor, (void *)2);
pthread_create(&threads[3], 0, consumidor, (void *)3);
for (int i = 0; i < 4; i++)
{
pthread_join(threads[i], 0);
}
return 0;
}
| 0
|
#include <pthread.h>
void* TA_Routine(void* arg);
void* Student_Routine(void* arg);
int student_id;
unsigned int seed;
} param;
pthread_mutex_t mutex_lock;
sem_t students_sem;
sem_t ta_sem;
int waiting_students;
void* TA_Routine(void* arg) {
unsigned int helping_time;
unsigned int ta_seed = 5;
int student_wait;
while(1) {
sem_post(&ta_sem);
helping_time = (unsigned int)(rand_r(&ta_seed)%3) + 1;
sem_wait(&students_sem);
pthread_mutex_lock(&mutex_lock);
waiting_students--;
student_wait = waiting_students;
pthread_mutex_unlock(&mutex_lock);
sleep(helping_time);
}
}
void* Student_Routine(void* arg) {
unsigned int program_time;
int num_help = 0;
int student_ID;
unsigned int seed;
param *p = (param *)arg;
student_ID = p->student_id;
seed = p->seed;
while(num_help < 2) {
program_time = (unsigned int)(rand_r(&seed)%3) + 1;
printf("\\tStudent %d programming for %d seconds\\n", student_ID, program_time);
sleep(program_time);
pthread_mutex_lock(&mutex_lock);
if(waiting_students < 2) {
waiting_students++;
sem_post(&students_sem);
pthread_mutex_unlock(&mutex_lock);
sem_wait(&ta_sem);
printf("Student %d receiving help\\n", student_ID);
num_help++;
}
else {
printf("\\t\\t\\tStudent %d will try later\\n", student_ID);
pthread_mutex_unlock(&mutex_lock);
}
}
pthread_exit(0);
return 0;
}
int main(void) {
pthread_t *threads;
pthread_attr_t pthread_my_attr;
param * arg;
printf("CS149 Sleeping TA from Michelle Luong\\n");
if(sem_init(&students_sem, 0, 0) != 0) {
printf("Error, initialization failed for student semaphore\\n");
}
if(sem_init(&ta_sem, 0, 0) != 0) {
printf("Error, initialization failed for TA semaphore\\n");
}
pthread_mutex_init(&mutex_lock, 0);
threads = (pthread_t *)malloc(sizeof(pthread_t)*(4 + 1));
arg = (param*)malloc(sizeof(param)*4);
pthread_attr_init(&pthread_my_attr);
for(int i = 0; i < 4; i++) {
arg[i].student_id = i;
arg[i].seed = (unsigned int)i;
pthread_create(&threads[i+1], &pthread_my_attr, Student_Routine, (void *)(arg + i));
}
pthread_create(&threads[0], &pthread_my_attr, TA_Routine, 0);
for(int i = 1; i < 4; i++) {
pthread_join(threads[i], 0);
}
pthread_cancel(threads[0]);
sem_destroy(&students_sem);
sem_destroy(&ta_sem);
pthread_mutex_destroy(&mutex_lock);
free(arg);
free(threads);
return 0;
}
| 1
|
#include <pthread.h>
static void *(*mem_alloc)(const size_t) = &malloc;
static void (*mem_free)(void *) = &free;
void fcgi_context_module_init(void *(*mem_alloc_p)(const size_t),
void (*mem_free_p)(void *))
{
mem_alloc = mem_alloc_p;
mem_free = mem_free_p;
}
void fcgi_context_free(struct fcgi_context *tdata)
{
request_list_free(&tdata->rl);
fcgi_fd_list_free(&tdata->fdl);
chunk_list_free_chunks(&tdata->cl);
}
int fcgi_context_init(struct fcgi_context *tdata,
const struct fcgi_fd_matrix fdm,
unsigned int thread_id,
unsigned int request_capacity,
struct fcgi_config *config)
{
unsigned int request_offset = 1 + request_capacity * thread_id;
check(!request_list_init(&tdata->rl,
config->location_count,
request_offset,
request_capacity),
"Failed to init request list.");
check(!fcgi_fd_list_init(&tdata->fdl,
fdm,
thread_id,
config),
"Failed to init fd list.");
chunk_list_init(&tdata->cl);
return 0;
error:
fcgi_context_free(tdata);
return -1;
}
void fcgi_context_list_free(struct fcgi_context_list *tdlist)
{
int i;
pthread_mutex_destroy(&tdlist->thread_id_counter_mutex);
for (i = 0; i < tdlist->n; i++) {
if (!tdlist->tds[i]) {
continue;
}
fcgi_context_free(tdlist->tds[i]);
mem_free(tdlist->tds[i]);
}
mem_free(tdlist->tds);
tdlist->n = 0;
tdlist->tds = 0;
}
int fcgi_context_list_init(struct fcgi_context_list *tdlist,
struct fcgi_config *config,
int workers,
int worker_capacity)
{
struct fcgi_context *tdata;
struct fcgi_fd_matrix fdm = fcgi_fd_matrix_create(config, workers);
const uint16_t capacity = next_power_of_2(worker_capacity);
int i;
check(capacity > 0, "No request capacity.");
check(capacity < UINT16_MAX, "Request capacity too large.");
tdlist->thread_id_counter = 0;
pthread_mutex_init(&tdlist->thread_id_counter_mutex, 0);
tdlist->tds = mem_alloc(workers * sizeof(*tdlist->tds));
check_mem(tdlist->tds);
tdlist->n = workers;
for (i = 0; i < workers; i++) {
tdata = mem_alloc(sizeof(*tdata));
check_mem(tdata);
tdlist->tds[i] = tdata;
check(!fcgi_context_init(tdata, fdm, i, capacity, config),
"[THREAD_ID %d] Failed to init thread data.", i);
}
fcgi_fd_matrix_free(&fdm);
return 0;
error:
fcgi_fd_matrix_free(&fdm);
fcgi_context_list_free(tdlist);
return -1;
}
int fcgi_context_list_assign_thread_id(struct fcgi_context_list *tdlist)
{
int my_thread_id;
check(tdlist->thread_id_counter < tdlist->n,
"All thread id's have already assigned.");
pthread_mutex_lock(&tdlist->thread_id_counter_mutex);
my_thread_id = tdlist->thread_id_counter;
tdlist->thread_id_counter += 1;
pthread_mutex_unlock(&tdlist->thread_id_counter_mutex);
return my_thread_id;
error:
return -1;
}
struct fcgi_context *fcgi_context_list_get(
struct fcgi_context_list *tdlist,
int thread_id)
{
struct fcgi_context *tdata;
check(thread_id >= 0 && thread_id < tdlist->n,
"Thread id %d is out of range.", thread_id);
tdata = tdlist->tds[thread_id];
check(tdata, "Thread data is NULL for thread id %d.", thread_id);
return tdata;
error:
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER;
void *functionCount1();
void *functionCount2();
int count = 0;
main()
{
pthread_t thread1, thread2;
pthread_create( &thread1, 0, &functionCount1, 0);
pthread_create( &thread2, 0, &functionCount2, 0);
pthread_join( thread1, 0);
pthread_join( thread2, 0);
exit(0);
}
void *functionCount1()
{
for(;;)
{
pthread_mutex_lock( &condition_mutex );
while( count >= 3 && count <= 6 )
{
if(count >= 10) return(0);
pthread_cond_wait( &condition_cond, &condition_mutex );
}
pthread_cond_signal( &condition_cond );
pthread_mutex_unlock( &condition_mutex );
pthread_mutex_lock( &count_mutex );
count++;
printf("Counter value functionCount1: %d\\n",count);
pthread_mutex_unlock( &count_mutex );
if(count >= 10) return(0);
}
}
void *functionCount2()
{
for(;;)
{
pthread_mutex_lock( &condition_mutex );
if( count < 3 || count > 6 )
{
pthread_cond_signal( &condition_cond );
}
while( count < 3 || count > 6 )
{
if(count >= 10) return(0);
pthread_cond_wait( &condition_cond, &condition_mutex );
}
pthread_mutex_unlock( &condition_mutex );
pthread_mutex_lock( &count_mutex );
count++;
printf("Counter value functionCount2: %d\\n",count);
pthread_mutex_unlock( &count_mutex );
if(count >= 10) return(0);
}
}
| 1
|
#include <pthread.h>
struct sigwaiter *sigwaiters;
siginfo_t
sigwaiter_block (struct signal_state *ss, const sigset_t *restrict set)
{
assert (pthread_mutex_trylock (&sig_lock) == EBUSY);
assert (pthread_mutex_trylock (&ss->lock) == EBUSY);
assert (! ss->sigwaiter);
struct sigwaiter waiter;
waiter.next = sigwaiters;
if (waiter.next)
{
assert (! waiter.next->prev);
waiter.next->prev = &waiter;
}
waiter.prev = 0;
sigwaiters = &waiter;
waiter.ss = ss;
waiter.info.si_signo = 0;
waiter.signals = *set;
ss->sigwaiter = &waiter;
pthread_mutex_unlock (&ss->lock);
pthread_mutex_unlock (&sig_lock);
futex_wait (&waiter.info.si_signo, 0);
pthread_mutex_lock (&ss->lock);
ss->sigwaiter = 0;
pthread_mutex_unlock (&ss->lock);
assert (waiter.info.si_signo);
return waiter.info;
}
void
sigwaiter_unblock (struct sigwaiter *waiter)
{
assert (pthread_mutex_trylock (&sig_lock) == EBUSY);
assert (pthread_mutex_trylock (&waiter->ss->lock) == EBUSY);
struct sigwaiter *prev = waiter->prev;
struct sigwaiter *next = waiter->next;
if (next)
next->prev = prev;
if (prev)
prev->next = next;
else
sigwaiters = next;
sigdelset (&process_pending, waiter->info.si_signo);
sigdelset (&waiter->ss->pending, waiter->info.si_signo);
pthread_mutex_unlock (&waiter->ss->lock);
pthread_mutex_unlock (&sig_lock);
futex_wake (&waiter->info.si_signo, 1);
}
| 0
|
#include <pthread.h>
struct bbsem {
pthread_mutex_t mutex;
pthread_cond_t is_nonzero;
int value;
};
struct bbsem *
bbseminit(int val)
{
struct bbsem *tmp;
tmp = malloc(sizeof(*tmp));
if (tmp == 0)
return(0);
pthread_cond_init(&tmp->is_nonzero, 0);
pthread_mutex_init(&tmp->mutex, 0);
tmp->value = val;
return(tmp);
}
void
bbsemdestroy(struct bbsem *bp)
{
if (pthread_mutex_destroy(&bp->mutex) != 0)
err(1, "pthread_mutex_destroy failed:");
if (pthread_cond_destroy(&bp->is_nonzero) != 0)
err(1, "pthread_cond_destroy failed:");
free(bp);
}
void
bbsemwait(struct bbsem *bp)
{
pthread_mutex_lock(&bp->mutex);
while (bp->value == 0)
pthread_cond_wait(&bp->is_nonzero, &bp->mutex);
bp->value--;
pthread_mutex_unlock(&bp->mutex);
}
void
bbsemfree(struct bbsem *bp)
{
pthread_mutex_lock(&bp->mutex);
bp->value++;
pthread_cond_signal(&bp->is_nonzero);
pthread_mutex_unlock(&bp->mutex);
}
| 1
|
#include <pthread.h>
struct queue_root {
struct queue_head *in_queue;
struct queue_head *out_queue;
pthread_mutex_t lock;
};
struct queue_root *ALLOC_QUEUE_ROOT()
{
struct queue_root *root =
malloc(sizeof(struct queue_root));
pthread_mutex_init(&root->lock, 0);
root->in_queue = 0;
root->out_queue = 0;
return root;
}
void INIT_QUEUE_HEAD(struct queue_head *head)
{
head->next = ((void*)0xCAFEBAB5);
}
void queue_put(struct queue_head *new,
struct queue_root *root)
{
while (1) {
struct queue_head *in_queue = root->in_queue;
new->next = in_queue;
if (__sync_bool_compare_and_swap(&root->in_queue, in_queue, new)) {
break;
}
}
}
struct queue_head *queue_get(struct queue_root *root)
{
pthread_mutex_lock(&root->lock);
if (!root->out_queue) {
while (1) {
struct queue_head *head = root->in_queue;
if (!head) {
break;
}
if (__sync_bool_compare_and_swap(&root->in_queue, head, 0)) {
while (head) {
struct queue_head *next = head->next;
head->next = root->out_queue;
root->out_queue = head;
head = next;
}
break;
}
}
}
struct queue_head *head = root->out_queue;
if (head) {
root->out_queue = head->next;
}
pthread_mutex_unlock(&root->lock);
return head;
}
| 0
|
#include <pthread.h>
int chopstick[5] = {0,0,0,0,0};
int state[5];
pthread_cond_t chopstic_cond[5] = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex_lock = PTHREAD_MUTEX_INITIALIZER;
void pick_chopstick(int id)
{
pthread_mutex_lock(&mutex_lock);
if(state[id] == 1 && chopstick[id]==0){
chopstick[id] = 1;
pthread_cond_wait(&chopstic_cond[id],&mutex_lock);
printf("philosopher %d is pick up the left chopstick %d .\\n",id,id);
}
pthread_mutex_unlock(&mutex_lock);
sleep(1);
pthread_mutex_lock(&mutex_lock);
if(chopstick[(id+1)%5]==0){
chopstick[(id+1)%5] = 1;
pthread_cond_wait(&chopstic_cond[(id+1)%5],&mutex_lock);
printf("philosopher %d is pick up the right chopstick %d .\\n",id,(id+1)%5);
}
pthread_mutex_unlock(&mutex_lock);
}
void take_down_chopstick(int id)
{
pthread_mutex_lock(&mutex_lock);
chopstick[id] = 0;
pthread_cond_signal(&chopstic_cond[id]);
printf("philosopher %d is take down the left chopstick %d .\\n",id,id);
pthread_mutex_unlock(&mutex_lock);
pthread_mutex_lock(&mutex_lock);
chopstick[(id+1)%5] = 0;
pthread_cond_signal(&chopstic_cond[(id+1)%5]);
printf("philosopher %d is take down the right chopstick %d .\\n",id,(id+1)%5);
pthread_mutex_unlock(&mutex_lock);
}
void *philosopher(void* data)
{
int id = (int)data;
while(1){
printf("Philosopher %d is thinking\\n",id);
sleep(1);
state[id] = 1;
printf("philosopher %d is hungry.\\n",id);
pick_chopstick(id);
if(chopstick[id] == 1 && chopstick[(id+1)%5] ==1 && state[id] == 1)
{
printf("philosopher %d is eating.\\n",id);
sleep(1);
take_down_chopstick(id);
}
}
}
int main(){
int i=0;
pthread_t pthred_philosopher[5];
for(i=0;i<5;i++){
pthread_create(&pthred_philosopher[i],0,philosopher,i);
state[i]=0;
}
for(i=0;i<5;i++){
pthread_join(pthred_philosopher[i],0);
}
return 0;
}
| 1
|
#include <pthread.h>
void *Thread_IN(void *arg);
void *Thread_OUT(void *arg);
char thread1[]="Thread A";
char thread2[]="Thread B";
pthread_mutex_t mutx;
int counter = 0;
int queue = 0;
int main(int argc, char **argv)
{
pthread_t t1, t2;
void *thread_result;
int state;
state = pthread_mutex_init(&mutx, 0);
if(state)
{
puts("Error mutex initialization");
}
pthread_create(&t1, 0, Thread_IN, &thread1);
pthread_create(&t2, 0, Thread_OUT, &thread2);
pthread_join(t1, &thread_result);
pthread_join(t2, &thread_result);
printf("Terminated %s, %s !!!\\n", &thread1, &thread2);
printf("Total Counts for threads: %d\\n", counter);
pthread_mutex_destroy(&mutx);
return 0;
}
void *Thread_IN(void *arg)
{
int i;
printf("Creating Thread: %s\\n", (char*)arg);
for(i=0; i<2; i++)
{
pthread_mutex_lock(&mutx);
sleep(1);
queue++;
counter++;
printf("%s: INSERT item to BUFFER %d\\n", (char*)arg, queue);
pthread_mutex_unlock(&mutx);
}
}
void *Thread_OUT(void *arg)
{
int i;
printf("Creating Thread: %s\\n", (char*)arg);
for(i=0; i<2; i++)
{
pthread_mutex_lock(&mutx);
sleep(1);
printf("%s: REMOVE item from BUFFER %d\\n", (char*)arg, queue);
queue--;
counter++;
pthread_mutex_unlock(&mutx);
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
void *thread1( void *arg ) {
pthread_cleanup_push( pthread_mutex_unlock, &mutex );
while ( 1 ) {
printf( "thread1 is running\\n" );
pthread_mutex_lock( &mutex );
pthread_cond_wait( &cond, &mutex );
printf( "thread1 applied the condition\\n" );
pthread_mutex_unlock( &mutex );
sleep( 4 );
}
pthread_cleanup_pop( 0 );
}
void *thread2( void *arg ) {
while ( 1 ) {
printf( "thread2 is running\\n" );
pthread_mutex_lock( &mutex );
pthread_cond_wait( &cond, &mutex );
printf( "thread2 applied the condition\\n" );
pthread_mutex_unlock( &mutex );
sleep( 1 );
}
}
int main() {
pthread_t thid1, thid2;
printf( "condition variable study!\\n" );
pthread_mutex_init( &mutex, 0 );
pthread_cond_init( &cond, 0 );
pthread_create( &thid1, 0, (void *) thread1, 0 );
pthread_create( &thid2, 0, (void *) thread2, 0 );
do {
pthread_cond_signal( &cond );
} while ( 1 );
sleep( 20 );
pthread_exit( 0 );
return 0;
}
| 1
|
#include <pthread.h>
pthread_t tid[8];
pthread_mutex_t mutex;
struct padded_int
{
int value;
char padding[60];
} private_count[8];
int *array;
int length = 1000000000;
int count = 0;
int double_count = 0;
int t = 8;
int max_threads = 0;
void *count3s_thread(void *arg) {
int i;
struct timeval tv1,tv2;
int length_per_thread = length/max_threads;
int id = *((int*)(&arg));
int start = id * length_per_thread;
printf("\\tThread [%d] starts [%d] length [%d]\\n",id, start, length_per_thread);
gettimeofday(&tv1,0);
for (i = start; i < start + length_per_thread; i++) {
if (array[i] == 3) {
private_count[id].value++;
}
}
pthread_mutex_lock(&mutex);
count = count + private_count[id].value;
pthread_mutex_unlock(&mutex);
gettimeofday(&tv2,0);
printf("\\tThread [%d] ended - delay %lf\\n",id,
(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));
}
void initialize_vector() {
int i = 0;
array = (int*) malloc(sizeof(int) * 1000000000);
if (array == 0) {
printf("Allocation memory failed!\\n");
exit(-1);
}
for (; i < 1000000000; i++) {
array[i] = rand() % 20;
if (array[i] == 3)
double_count++;
}
}
int main(int argc, char *argv[]) {
int i = 0;
int err;
struct timeval tv1, tv2, tv3, tv4;
if (argc == 2) {
max_threads = atoi(argv[1]);
if (max_threads > 8)
max_threads = 8;
} else {
max_threads = 8;
}
printf("[3s-05] Using %d threads\\n",max_threads);
srand(time(0));
printf("*** 3s-05 ***\\n");
printf("Initializing vector... ");
fflush(stdout);
gettimeofday(&tv1, 0);
initialize_vector();
gettimeofday(&tv2, 0);
printf("Vector initialized! - elapsed %lf sec.\\n",(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
(double) (tv2.tv_sec - tv1.tv_sec));
fflush(stdout);
gettimeofday(&tv3, 0);
pthread_mutex_init(&mutex,0);
while (i < max_threads) {
private_count[i].value = 0;
err = pthread_create(&tid[i], 0, &count3s_thread, (void*)i);
if (err != 0)
printf("[3s-05] Can't create a thread: [%d]\\n", i);
else
printf("[3s-05] Thread created!\\n");
i++;
}
i = 0;
for (; i < max_threads; i++) {
void *status;
int rc;
rc = pthread_join(tid[i], &status);
if (rc) {
printf("ERROR; retrun code from pthread_join() is %d\\n", rc);
exit(-1);
} else {
printf("Thread [%d] exited with status [%ld]\\n", i, (long)status);
}
}
printf("[3s-05] Count by threads %d\\n", count);
printf("[3s-05] Double check %d\\n", double_count);
pthread_mutex_destroy(&mutex);
gettimeofday(&tv4,0);
printf("[[3s-05] Elapsed time %lf sec.\\n", (double) (tv4.tv_usec - tv3.tv_usec) / 1000000 +
(double) (tv4.tv_sec - tv3.tv_sec));
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
int Graph[105][105] ;
int dist[105][105] ;
void init_graph_matrix(int * , int *) ;
void print_dst(int) ;
pthread_mutex_t read_mutex ;
pthread_mutex_t write_mutex ;
int read_count ;
struct parameters{
int i ;
int k ;
int n ;
} ;
void * floyd_warshall(void * t){
struct parameters * param = (struct parameters *)t ;
int i , n , j , k , result ;
i = param->i ;
k = param->k ;
n = param->n ;
for(j = 0 ; j < n ; j++){
pthread_mutex_lock(&read_mutex) ;
read_count++ ;
if(read_count == 1)
pthread_mutex_lock(&write_mutex) ;
pthread_mutex_unlock(&read_mutex) ;
result = dist[i][k] + dist[k][j] < dist[i][j] ;
pthread_mutex_lock(&read_mutex) ;
read_count-- ;
if(read_count == 0)
pthread_mutex_unlock(&write_mutex) ;
pthread_mutex_unlock(&read_mutex) ;
if(result == 1){
pthread_mutex_lock(&write_mutex) ;
dist[i][j] = dist[i][k] + dist[k][j] ;
pthread_mutex_unlock(&write_mutex) ;
}
}
pthread_exit(0) ;
}
int main(){
int n , m , k , i , j ;
init_graph_matrix(&n , &m) ;
pthread_t threads[100] ;
struct parameters t[100] ;
pthread_attr_t attr ;
pthread_mutex_init(&read_mutex , 0) ;
pthread_mutex_init(&write_mutex , 0) ;
read_count = 0 ;
pthread_attr_init(&attr) ;
pthread_attr_setdetachstate(&attr , PTHREAD_CREATE_JOINABLE) ;
for( k = 0 ; k < n ; k++){
for( i = 0 ; i < n ; i++){
struct parameters * param = &(t[i]) ;
param->i = i ;
param->k = k ;
param->n = n ;
pthread_create(&threads[i] , &attr , floyd_warshall , (void *)param) ;
}
for(i = 0 ; i < n ; i++){
pthread_join(threads[i] , 0) ;
}
}
print_dst(n) ;
pthread_attr_destroy(&attr) ;
pthread_mutex_destroy(&read_mutex) ;
pthread_mutex_destroy(&write_mutex) ;
pthread_exit(0) ;
}
void print_dst(int n){
printf("\\nOutput:\\n\\n") ;
int i , j ;
for(i = 0 ; i < n ; i++){
for(j = 0 ; j < n ; j++)
if(dist[i][j] == 10000007)
printf("INF\\t") ;
else
printf("%d\\t" , dist[i][j]) ;
printf("\\n") ;
}
}
void init_graph_matrix(int *n , int *m){
int i , j , N , M , u , v , w ;
printf("Enter the value of n : ") ;
scanf("%d", n) ;
printf("Enter the value of m : ") ;
scanf("%d", m) ;
N = *n ;
M = *m ;
assert( M <= N*(N+1)/2 ) ;
for(i = 0 ; i < N ; i++)
for(j = 0 ; j < N ; j++){
Graph[i][j] = 0 ;
if(i == j)
dist[i][j] = 0 ;
else
dist[i][j] = 10000007 ;
}
printf("Enter %d sets of (u v w) values\\n" , M) ;
for(i = 0 ; i < M ; i++){
scanf("%d %d %d" , &u , &v , &w) ;
Graph[u-1][v-1] = 1 ;
Graph[v-1][u-1] = 1 ;
dist[u-1][v-1] = w ;
dist[v-1][u-1] = w ;
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t a;
pthread_mutex_t c;
pthread_mutex_t g;
pthread_mutex_t f;
int k;
int j;
void* fn1(void * args){
pthread_mutex_lock(&a);;
if( k == 25 ){
pthread_mutex_unlock(&f);;
} else {
pthread_mutex_lock(&c);;
}
pthread_mutex_lock(&g);;
if(j)
printf("hola\\n");
else
printf("adios\\n");
}
void* fn2(void * args){
pthread_mutex_unlock(&a);;
if( k == 12 ){
j = 1;
pthread_mutex_unlock(&c);;
} else {
j = 0;
pthread_mutex_lock(&f);;
j = 1;
pthread_mutex_unlock(&g);;
}
}
int main() {
pthread_t thread1;
pthread_t thread2;
pthread_create(&thread1, 0, &fn1, 0);
pthread_create(&thread2, 0, &fn2, 0);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
double target;
void* opponent(void *arg)
{ int i;
for (i = 0; i < 10000; ++i)
{
pthread_mutex_lock(&mutex);
target -= target * 2 + tan(target);
pthread_mutex_unlock(&mutex);
}
return 0;
}
int main(int argc, char **argv)
{
pthread_t other;
target = 5.0;
if(pthread_mutex_init(&mutex, 0))
{
printf("Unable to initialize a mutex\\n");
return -1;
}
if(pthread_create(&other, 0, &opponent, 0))
{
printf("Unable to spawn thread\\n");
return -1;
}
int i;
for (i = 0; i < 10000; ++i)
{
pthread_mutex_lock(&mutex);
target += target * 2 + tan(target);
pthread_mutex_unlock(&mutex);
}
if(pthread_join(other, 0))
{
printf("Could not join thread\\n");
return -1;
}
pthread_mutex_destroy(&mutex);
printf("Result: %f\\n", target);
return 0;
}
| 1
|
#include <pthread.h>
void* f1(void*);
void* f2(void*);
void* f3(void*);
void* f4(void*);
struct thread_data{
size_t last_thread_on_that_zone[10];
int picture[10];
pthread_mutex_t* mutex_data;
pthread_cond_t* vcond_data;
};
void init_thread_data(struct thread_data* p){
for(size_t i=0;i<4;++i){
p->last_thread_on_that_zone[i]=0;
}
p->mutex_data=malloc(sizeof(pthread_mutex_t)*10);
p->vcond_data=malloc(sizeof(pthread_cond_t)*10);
for(size_t i=0;i<10;++i){
pthread_mutex_init(&(p->mutex_data[i]),0);
pthread_cond_init(&(p->vcond_data[i]),0);
}
}
void destroy_thread_data(struct thread_data* p){
free(p->mutex_data);
free(p->vcond_data);
}
void* f1(void* p){
struct thread_data* param=(struct thread_data*)p;
size_t my_function_number=1;
for(size_t i=0;i<10;++i){
pthread_mutex_lock(&(param->mutex_data[i]));
while(param->last_thread_on_that_zone[i]!=my_function_number){
pthread_cond_wait(&(param->vcond_data[i]),&(param->mutex_data[i]));
}
sleep(.5);
param->last_thread_on_that_zone[i]++;
pthread_cond_broadcast(&(param->vcond_data[i]));
pthread_mutex_unlock(&(param->mutex_data[i]));
}
pthread_exit(0);
}
int main(){
struct thread_data* param;
param=malloc(sizeof(struct thread_data));
init_thread_data(param);
pthread_t idt[4];
pthread_create(&idt[0],0,f1,(void*)param);
pthread_create(&idt[1],0,f2,(void*)param);
pthread_create(&idt[2],0,f3,(void*)param);
pthread_create(&idt[3],0,f4,(void*)param);
for(size_t i=0;i<10;++i){
pthread_mutex_lock(&(param->mutex_data[i]));
sleep(.5);
param->last_thread_on_that_zone[i]++;
pthread_cond_broadcast(&(param->vcond_data[i]));
pthread_mutex_unlock(&(param->mutex_data[i]));
}
printf("main is done and waiting for his slow coworkers is finally done!\\n");
for(size_t i=0;i<4;++i){
pthread_join(idt[i],0);
}
destroy_thread_data(param);
free(param);
return 0;
}
void* f2(void* p){
struct thread_data* param=(struct thread_data*)p;
size_t my_function_number=2;
for(size_t i=0;i<10;++i){
pthread_mutex_lock(&(param->mutex_data[i]));
while(param->last_thread_on_that_zone[i]!=my_function_number){
pthread_cond_wait(&(param->vcond_data[i]),&(param->mutex_data[i]));
}
sleep(.5);
param->last_thread_on_that_zone[i]++;
pthread_cond_broadcast(&(param->vcond_data[i]));
pthread_mutex_unlock(&(param->mutex_data[i]));
}
pthread_exit(0);
}
void* f3(void* p){
struct thread_data* param=(struct thread_data*)p;
size_t my_function_number=3;
for(size_t i=0;i<10;++i){
pthread_mutex_lock(&(param->mutex_data[i]));
while(param->last_thread_on_that_zone[i]!=my_function_number){
pthread_cond_wait(&(param->vcond_data[i]),&(param->mutex_data[i]));
}
sleep(.5);
param->last_thread_on_that_zone[i]++;
pthread_cond_broadcast(&(param->vcond_data[i]));
pthread_mutex_unlock(&(param->mutex_data[i]));
}
pthread_exit(0);
}
void* f4(void* p){
struct thread_data* param=(struct thread_data*)p;
size_t my_function_number=4;
for(size_t i=0;i<10;++i){
pthread_mutex_lock(&(param->mutex_data[i]));
while(param->last_thread_on_that_zone[i]!=my_function_number){
pthread_cond_wait(&(param->vcond_data[i]),&(param->mutex_data[i]));
}
sleep(.5);
param->last_thread_on_that_zone[i]++;
pthread_cond_broadcast(&(param->vcond_data[i]));
pthread_mutex_unlock(&(param->mutex_data[i]));
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
volatile int g=0;
void* setter(void* args)
{
pthread_mutex_lock(&mutex);
g = *(int*)args;
pthread_mutex_unlock(&mutex);
return 0;
}
void* t1(void* args)
{
pthread_t otherHandles[(2)];
int threadArgs[(2)];
size_t i;
for(i=0; i < (2); ++i)
{
threadArgs[i] = i+1;
pthread_create(&otherHandles[i], 0, setter, &threadArgs[i]);
}
for(i=0; i < (2); ++i)
{
pthread_join(otherHandles[i], 0);
}
return 0;
}
int main(int argc, char** argv)
{
pthread_t handle;
pthread_t otherHandles[(1)];
int threadArgs[(1)];
size_t i;
pthread_mutex_init(&mutex, 0);
pthread_create(&handle, 0, t1, 0);
for(i=0; i < (1); i++)
{
threadArgs[i] = (2)+i+1;
pthread_create(&otherHandles[i], 0, setter, (void*)&threadArgs[i] );
}
for(i=0; i < (1); ++i)
{
pthread_join(otherHandles[i], 0);
}
pthread_join(handle, 0);
assert(g != 0 && "g is 0 after joining!");
printf("On this schedule, g ends up being %d\\n", g);
return 0;
}
| 1
|
#include <pthread.h>
void *slave(void *myid);
int data[1000];
int sum = 0;
pthread_mutex_t mutex;
int wsize;
void *slave(void *myid)
{
int i, low,high,myresult=0;
low = (int) myid * wsize;
high = low + wsize;
for(i =low;i<high;i++)
myresult += data[i];
pthread_mutex_lock(&mutex);
sum += myresult;
pthread_mutex_unlock(&mutex);
return;
}
main()
{
int i;
pthread_t tid[2];
pthread_mutex_init(&mutex,0);
wsize = 1000/2;
for (i=0;i<1000;i++)
data[i]= i+1;
for (i =0;i<2;i++)
if(pthread_create(&tid[i],0,slave,(void*)i) != 0)
perror("Pthread_create fails");
for(i=0;i<2;i++)
if(pthread_join(tid[i],0) != 0)
perror("Pthread_join fails");
printf("The sum from 1 to %i is %d\\n",1000,sum);
}
| 0
|
#include <pthread.h>
static pthread_key_t key;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;
extern char **environ;
static void
thread_init(void)
{
pthread_key_create(&key, free);
}
char *
getenv(const char *name)
{
int i, len;
char *envbuf;
pthread_once(&init_done, thread_init);
pthread_mutex_lock(&env_mutex);
envbuf = (char *)pthread_getspecific(key);
if (envbuf == 0) {
envbuf = (char*)malloc(4096);
if (envbuf == 0) {
pthread_mutex_unlock(&env_mutex);
return(0);
}
pthread_setspecific(key, envbuf);
}
len = strlen(name);
for (i = 0; environ[i] != 0; i++) {
if ((strncmp(name, environ[i], len) == 0) &&
(environ[i][len] == '=')) {
strncpy(envbuf, &environ[i][len+1], 4096 -1);
pthread_mutex_unlock(&env_mutex);
return(envbuf);
}
}
pthread_mutex_unlock(&env_mutex);
return(0);
}
| 1
|
#include <pthread.h>
struct prodcons {
int buffer[8];
pthread_mutex_t lock;
int readpos,writepos;
pthread_cond_t notempty;
pthread_cond_t notfull;
};
void init(struct prodcons *b)
{
pthread_mutex_init(&b->lock,0);
pthread_cond_init(&b->notempty,0);
pthread_cond_init(&b->notfull,0);
b->readpos = 0 ;
b->writepos = 0 ;
}
void put(struct prodcons *b,int data)
{
pthread_mutex_lock(&b->lock);
if((b->writepos + 1)%8 == b->readpos)
{
pthread_cond_wait(&b->notfull,&b->lock);
}
b->buffer[b->writepos] = data;
b->writepos++;
if(b->writepos >= 8)
b->writepos = 0;
pthread_cond_signal(&b->notempty);
pthread_mutex_unlock(&b->lock);
}
int get(struct prodcons *b)
{
int data;
pthread_mutex_lock(&b->lock);
if(b->writepos == b->readpos)
{
pthread_cond_wait(&b->notempty,&b->lock);
}
data = b->buffer[b->readpos];
b->readpos++;
if(b->readpos >= 8)
b->readpos = 0;
pthread_cond_signal(&b->notfull);
pthread_mutex_unlock(&b->lock);
return data;
}
struct prodcons buffer;
void *producer(void *data)
{
int n;
for(n = 0 ; n < 50 ; n++)
{
printf("%d\\t",n);
put(&buffer,n);
}
put(&buffer,(-1));
return 0;
}
void *consumer(void *data)
{
int d;
while(1)
{
d = get(&buffer);
if(d == (-1))
break;
printf("%d\\t",d);
}
return 0;
}
int main(void)
{
pthread_t th_a,th_b;
void *retval;
init(&buffer);
pthread_create(&th_a,0,producer,0);
pthread_create(&th_b,0,consumer,0);
pthread_join(th_a,&retval);
pthread_join(th_b,&retval);
printf("\\n");
return 0;
}
| 0
|
#include <pthread.h>
pthread_t *Students;
pthread_t TA;
int ChairsCount = 0;
int CurrentIndex = 0;
sem_t TA_Sleep;
sem_t Student_Sem;
sem_t ChairsSem[3];
pthread_mutex_t ChairAccess;
void *TA_Activity();
void *Student_Activity(void *threadID);
int main(int argc, char* argv[])
{
int number_of_students;
int id;
srand(time(0));
sem_init(&TA_Sleep, 0, 0);
sem_init(&Student_Sem, 0, 0);
for(id = 0; id < 3; ++id)
sem_init(&ChairsSem[id], 0, 0);
pthread_mutex_init(&ChairAccess, 0);
printf("\\n\\n\\n********************************************************************************");
printf("\\n********************************************************************************");
printf("\\n\\n\\t\\tTHE CLASSIC TEACHING ASSISTANT PROBLEM\\t\\t");
printf("\\n\\n********************************************************************************\\n");
printf("********************************************************************************\\n\\n");
printf("ENTER THE NUMBER OF STUDENTS :");
scanf("%d", &number_of_students);
Students = (pthread_t*) malloc(sizeof(pthread_t)*number_of_students);
pthread_create(&TA, 0, TA_Activity, 0);
for(id = 0; id < number_of_students; id++)
pthread_create(&Students[id], 0, Student_Activity,(void*) (long)id);
pthread_join(TA, 0);
for(id = 0; id < number_of_students; id++)
pthread_join(Students[id], 0);
free(Students);
return 0;
}
void *TA_Activity()
{
while(1)
{
sem_wait(&TA_Sleep);
printf("\\n\\n\\n~~~~~~~~~~~~~~~~~~~~~TA has been awakened by a student.~~~~~~~~~~~~~~~~~~~~~\\n\\n");
while(1)
{
pthread_mutex_lock(&ChairAccess);
if(ChairsCount == 0)
{
pthread_mutex_unlock(&ChairAccess);
break;
}
sem_post(&ChairsSem[CurrentIndex]);
ChairsCount--;
printf("Student left his/her chair. Remaining Chairs %d\\n", 3 - ChairsCount);
CurrentIndex = (CurrentIndex + 1) % 3;
pthread_mutex_unlock(&ChairAccess);
printf("\\t TA is currently helping the student.\\n");
sleep(5);
sem_post(&Student_Sem);
usleep(1000);
}
}
}
void *Student_Activity(void *threadID)
{
int ProgrammingTime;
while(1)
{
printf("Student %ld is doing programming assignment.\\n", (long)threadID);
ProgrammingTime = rand() % 10 + 1;
sleep(ProgrammingTime);
printf("Student %ld needs help from the TA\\n", (long)threadID);
pthread_mutex_lock(&ChairAccess);
int count = ChairsCount;
pthread_mutex_unlock(&ChairAccess);
if(count < 3)
{
if(count == 0)
sem_post(&TA_Sleep);
else
printf("Student %ld sat on a chair waiting for the TA to finish. \\n", (long)threadID);
pthread_mutex_lock(&ChairAccess);
int index = (CurrentIndex + ChairsCount) % 3;
ChairsCount++;
printf("Student sat on chair.Chairs Remaining: %d\\n", 3 - ChairsCount);
pthread_mutex_unlock(&ChairAccess);
sem_wait(&ChairsSem[index]);
printf("\\t Student %ld is getting help from the TA. \\n", (long)threadID);
sem_wait(&Student_Sem);
printf("Student %ld left TA room.\\n",(long)threadID);
}
else
printf("Student %ld will return at another time. \\n", (long)threadID);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t printf_mutex = PTHREAD_MUTEX_INITIALIZER;
void *print_function(void *arg)
{
char *p = arg;
int i;
for (i = 0; i < 10; i++)
{
pthread_mutex_lock(&printf_mutex);
display(p);
pthread_mutex_unlock(&printf_mutex);
sleep(1);
}
}
int main(int argc, char *argv[])
{
pthread_t threads[2];
int rc;
int i, j;
char *msg1 = "Kalimera kosme\\n";
char *msg2 = "Hello world\\n";
rc = pthread_create(&threads[0], 0, print_function, (void *)msg1);
rc = pthread_create(&threads[1], 0, print_function, (void *)msg2);
if (rc)
{
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
pthread_join( threads[0], 0);
pthread_join( threads[1], 0);
pthread_mutex_destroy(&printf_mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t m;
pthread_cond_t cond;
char str[100];
bool str_available;
void* producer(void* arg ) {
while (1) {
char buf[sizeof str];
fgets(buf, sizeof buf, stdin);
pthread_mutex_lock(&m);
strncpy(str, buf, sizeof str);
str_available = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&m);
}
}
void* consumer(void* arg ) {
while (1) {
pthread_mutex_lock(&m);
while (!str_available) {
pthread_cond_wait(&cond, &m);
}
char str_snapshot[100];
strncpy(str_snapshot, str, sizeof str_snapshot);
str_available = 0;
pthread_mutex_unlock(&m);
printf("Got string: %s", str_snapshot);
for (int i = 0; i < 4; i++) {
usleep(500000);
}
printf("Repeating: %s", str_snapshot);
}
}
int main(void) {
pthread_mutex_init(&m, 0);
pthread_cond_init(&cond, 0);
pthread_t id1, id2;
assert(pthread_create(&id1, 0, producer, 0) == 0);
assert(pthread_create(&id2, 0, consumer, 0) == 0);
assert(pthread_join(id1, 0) == 0);
assert(pthread_join(id2, 0) == 0);
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&m);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t full,empty,acc;
int x=1;
int eflag=0,fflag=0;
int f=0,r=0,id=1;
int cnt=0;
int *q;
void* pro()
{ printf("producer started \\n");
while(1)
{ pthread_mutex_lock(&acc);
if(cnt==5)
{ printf("Producer waiting...\\n");
fflag=1;
pthread_mutex_lock(&full);
pthread_mutex_unlock(&acc);
sleep(rand()%2);
pthread_mutex_lock(&acc);
}
cnt++;
q[f]=id++;
if(cnt==1&&eflag==1)
{ eflag=0;
pthread_mutex_unlock(&empty);
}
printf("produced item %d\\n",q[f]);
f=(f+1)%5;;
pthread_mutex_unlock(&acc);
sleep(rand()%3);
}
}
void* con()
{
printf("Consumer started \\n");
while(1){
if(cnt==0)
{ printf("consumer waiting...\\n");
eflag=1;
pthread_mutex_unlock(&acc);
pthread_mutex_lock(&empty);
sleep(rand()%2);
pthread_mutex_lock(&acc);
}
cnt--;
printf("Consumed item %d\\n",q[r]);
r=(r+1)%5;;
if(cnt==4 && fflag==1)
{ fflag=0;
pthread_mutex_unlock(&full);
}
pthread_mutex_unlock(&acc);
sleep(rand()%2);
}
}
int main()
{ q=(int*)calloc(5,sizeof(int));
pthread_t prod,cons;
pthread_create(&prod,0,pro,0);
pthread_create(&cons,0,con,0);
pthread_join(prod,0);
}
| 0
|
#include <pthread.h>
struct data {
int IMAGE[100];
int DernierThreadSurLaZone[100];
pthread_mutex_t *verrou;
pthread_cond_t *condition;
}data;
void* Fonction1(void*);
void* Fonction2(void*);
void* Focntion3(void*);
void* Fonction4(void*);
void * Fonction1(void *par){
int ma_fonction_numero = 1;
struct data *mon_D1 = (struct data*)par;
for(int i=0; i<100;i++){
pthread_mutex_lock(&(mon_D1->verrou[i]));
mon_D1->IMAGE[i]=mon_D1->IMAGE[i]+5;
mon_D1->DernierThreadSurLaZone[i]=2;
printf("Le thread numero %i travail sur la partie %i\\n",1,i);
pthread_cond_broadcast(&(mon_D1->condition[i]));
pthread_mutex_unlock(&(mon_D1->verrou[i]));
}
printf("Je suis %i-er le premier thread j'ai fini mon travail.\\n",ma_fonction_numero);
pthread_exit(0);
}
void * Fonction2( void * par){
int ma_fonction_numero = 2;
struct data *mon_D1 = (struct data*)par;
for(int i=0;i<100;i++){
pthread_mutex_lock(&(mon_D1->verrou[i]));
while(mon_D1->DernierThreadSurLaZone[i]!=ma_fonction_numero){
pthread_cond_wait(&(mon_D1->condition[i]),&(mon_D1->verrou[i]));
}
mon_D1->IMAGE[i]=mon_D1->IMAGE[i]+5;
printf("Le thread numero %i travail sur la partie %i\\n",2,i);
mon_D1->DernierThreadSurLaZone[i]++;
pthread_cond_broadcast(&(mon_D1->condition[i]));
pthread_mutex_unlock(&(mon_D1->verrou[i]));
}
printf("Je suis le second thread j'ai fini mon travail.\\n");
pthread_exit(0);
}
void * Fonction3(void* par){
int ma_fonction_numero = 3;
struct data *mon_D1 = (struct data*)par;
for(int i=0;i<100;i++){
pthread_mutex_lock(&(mon_D1->verrou[i]));
while(mon_D1->DernierThreadSurLaZone[i]!=ma_fonction_numero){
pthread_cond_wait(&(mon_D1->condition[i]),&(mon_D1->verrou[i]));
}
mon_D1->IMAGE[i]=mon_D1->IMAGE[i]+5;
printf("Le thread numero %i travail sur la partie %i\\n",3,i);
mon_D1->DernierThreadSurLaZone[i]++;
pthread_cond_broadcast(&(mon_D1->condition[i]));
pthread_mutex_unlock(&(mon_D1->verrou[i]));
}
printf("Je suis le troisième thread j'ai fini mon travail.\\n");
pthread_exit(0);
}
void * Fonction4(void* par){
int ma_fonction_numero = 4;
struct data *mon_D1 = (struct data*)par;
for(int i=0;i<100;i++){
pthread_mutex_lock(&(mon_D1->verrou[i]));
while(mon_D1->DernierThreadSurLaZone[i]!=ma_fonction_numero){
pthread_cond_wait(&(mon_D1->condition[i]),&(mon_D1->verrou[i]));
}
mon_D1->IMAGE[i]=mon_D1->IMAGE[i]+5;
printf("Le thread numero %i travail sur la partie %i\\n",4,i);
mon_D1->DernierThreadSurLaZone[i]++;
pthread_cond_broadcast(&(mon_D1->condition[i]));
pthread_mutex_unlock(&(mon_D1->verrou[i]));
}
printf("Je suis %i le quatrième thread j'ai fini mon travail.\\n",ma_fonction_numero);
pthread_exit(0);
}
int main(){
srand(time(0));
pthread_t T1,T2,T3,T4;
struct data D1;
for(int i=0;i<100;i++){
D1.DernierThreadSurLaZone[i]=0;
D1.IMAGE[i]=0;
}
D1.verrou=malloc(sizeof(pthread_mutex_t)*100);
D1.condition=malloc(sizeof(pthread_cond_t)*100);
for(size_t i=0;i<100;i++){
pthread_mutex_init(&(D1.verrou[i]),0);
pthread_cond_init(&(D1.condition[i]),0);
}
pthread_create(&T2,0,Fonction2,&D1);
pthread_create(&T3,0,Fonction3,&D1);
pthread_create(&T4,0,Fonction4,&D1);
pthread_create(&T1,0,Fonction1,&D1);
pthread_join(T1,0);
pthread_join(T2,0);
pthread_join(T3,0);
pthread_join(T4,0);
printf("IMAGE(");
for(int i=0;i<100 -1;i++){
printf("%i,",D1.IMAGE[i]);
}
printf("%i)\\n\\n\\n",D1.IMAGE[100 -1]);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t the_mutex;
pthread_cond_t condc,condp;
int buffer=0;
int count=0;
void *producer(void *ptr)
{
while(count<=50)
{
pthread_mutex_lock(&the_mutex);
while(buffer>=10)pthread_cond_wait(&condp,&the_mutex);
buffer++;
printf("生产者生产了1件,当前缓冲区中有%d件\\n",buffer );
pthread_cond_signal(&condc);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
void *consumer(void *ptr)
{
while(count<50)
{
pthread_mutex_lock(&the_mutex);
while(buffer==0)pthread_cond_wait(&condc,&the_mutex);
buffer--;
count++;
printf("消费者消费了1件,当前缓冲区中有%d件,消费历史总计%d件\\n",buffer,count);
pthread_cond_signal(&condp);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
int main(int argc,char **argv)
{
pthread_t pro1,pro2,pro3,con1,con2;
pthread_mutex_init(&the_mutex,0);
pthread_cond_init(&condc,0);
pthread_cond_init(&condp,0);
pthread_create(&con1,0,consumer,0);
pthread_create(&con2,0,consumer,0);
pthread_create(&pro1,0,producer,0);
pthread_create(&pro2,0,producer,0);
pthread_create(&pro3,0,producer,0);
pthread_join(pro1,0);
pthread_join(pro2,0);
pthread_join(pro3,0);
pthread_join(con1,0);
pthread_join(con2,0);
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.