text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
pthread_cond_t* cond;
pthread_cond_t* ready;
pthread_mutex_t* mutex;
char ExistUserDB(char * user){
cond = (pthread_cond_t*) (shmPointer + COND_OFFSET);
ready = (pthread_cond_t*) (shmPointer + COND2_OFFSET);
mutex = (pthread_mutex_t*)(shmPointer + MUTEX_OFFSET);
pthread_mutex_lock(mutex);
shmPointer[TYPEPOS] = ISUSER;
memcpy(shmPointer + FIRSTARGUMENT,user,strlen(user));
shmPointer[strlen(user) + 1 ] = 0;
pthread_cond_signal(cond);
while(shmPointer[TYPEPOS] != READY){
pthread_cond_wait(ready,mutex);
}
char c = shmPointer[RETURNPOS];
pthread_mutex_unlock(mutex);
return c;
}
int validPasswordDB(char* user, char* password){
pthread_mutex_lock(mutex);
shmPointer[TYPEPOS] = ISPASSWORD;
memcpy(shmPointer + FIRSTARGUMENT,user,strlen(user)+1);
memcpy(shmPointer + SECONDARGUMENT,password, strlen(password) + 1);
pthread_cond_signal(cond);
while(shmPointer[TYPEPOS] != READY){
pthread_cond_wait(ready,mutex);
}
char c = shmPointer[RETURNPOS];
pthread_mutex_unlock(mutex);
return c;
}
int getHighScoreDB(char * user){
pthread_mutex_lock(mutex);
shmPointer[TYPEPOS] = GETHIGHSCORE;
memcpy(shmPointer + FIRSTARGUMENT,user,strlen(user) + 1);
pthread_cond_signal(cond);
while(shmPointer[TYPEPOS] != READY){
pthread_cond_wait(ready,mutex);
}
int i = atoi(shmPointer+ RETURNPOS);
pthread_mutex_unlock(mutex);
return i;
}
int setHighscoreDB(char* user, int value){
pthread_mutex_lock(mutex);
shmPointer[TYPEPOS] = SETHIGHSCORE;
memcpy(shmPointer + FIRSTARGUMENT, user, strlen(user) + 1);
sprintf(shmPointer + SECONDARGUMENT,"%d", value);
pthread_cond_signal(cond);
while(shmPointer[TYPEPOS] != READY){
pthread_cond_wait(ready,mutex);
}
int ret = shmPointer[RETURNPOS];
pthread_mutex_unlock(mutex);
return ret;
}
int createUserDB(char* user, char* password){
pthread_mutex_lock(mutex);
shmPointer[TYPEPOS] = CREATEUSER;
memcpy(shmPointer + FIRSTARGUMENT,user, strlen(user) + 1);
memcpy(shmPointer + SECONDARGUMENT,password, strlen(password) + 1);
pthread_cond_signal(cond);
while(shmPointer[TYPEPOS] != READY){
pthread_cond_wait(ready,mutex);
}
int ret = shmPointer[RETURNPOS];
pthread_mutex_unlock(mutex);
return ret;
}
| 1
|
#include <pthread.h>
int myglobal=0;
pthread_mutex_t mymutex=PTHREAD_MUTEX_INITIALIZER;
void *thread_function(void *arg) {
int i,j;
for ( i=0; i<20; i++ ) {
pthread_mutex_lock(&mymutex);
j=myglobal;
j=j+1;
printf(".");
fflush(stdout);
sleep(1);
myglobal=j;
pthread_mutex_unlock(&mymutex);
}
return 0;
}
int main() {
pthread_t mythread;
int i,r;
r = pthread_create( &mythread, 0, thread_function, 0);
if( r !=0) {
perror("error creating thread.\\n");
exit(1);
}
for ( i=0; i<20; i++) {
pthread_mutex_lock(&mymutex);
myglobal=myglobal+1;
pthread_mutex_unlock(&mymutex);
printf("o");
fflush(stdout);
sleep(1);
}
r = pthread_join ( mythread, 0 );
if( r != 0) {
perror("error joining thread.\\n");
exit(1);
}
printf("\\nmyglobal equals %d\\n",myglobal);
exit(0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t m;
int s;
void* thr1(void* arg)
{
int l = __VERIFIER_nondet_int(0, 1000);
l = 4;
pthread_mutex_lock (&m);
s = l;
__VERIFIER_assert (s == l);
pthread_mutex_unlock (&m);
return 0;
}
int main()
{
s = __VERIFIER_nondet_int(0, 1000);
pthread_t t[5];
pthread_mutex_init (&m, 0);
int i = 0;
pthread_create (&t[i], 0, thr1, 0); i++;
pthread_create (&t[i], 0, thr1, 0); i++;
pthread_create (&t[i], 0, thr1, 0); i++;
pthread_create (&t[i], 0, thr1, 0); i++;
pthread_create (&t[i], 0, thr1, 0);
return 0;
}
| 1
|
#include <pthread.h>
void *functionA();
void *functionB();
int var_A, var_B = 0;
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
int main(){
pthread_t thread1, thread2;
int rc1, rc2;
printf("\\033[2J");
printf("Deadlock experiment with MUTEX. Does this program lead to deadlock?\\n");
printf("===========================================================\\n");
if( rc1=pthread_create(&thread1, 0, &functionA, 0)){
printf("Error in creating thread %d\\n", rc1 );
}
if( rc2=pthread_create(&thread2, 0, &functionB, 0)){
printf("Error in creating thread %d\\n", rc2 );
}
pthread_join(thread1, 0);
pthread_join(thread2, 0);
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
exit(0);
}
void *functionA(){
int x = 0;
while(1){
pthread_mutex_lock(&mutex1);
printf("I'm T1, just locked mutex1\\n");
pthread_mutex_lock(&mutex2);
printf("I'm T1, just locked mutex2\\n");
var_A++;
var_B++;
printf("I am Thread1: var_A = %d, var_B = %d\\n", var_A, var_B);
pthread_mutex_unlock(&mutex1);
printf("I'm T1, just freed mutex1\\n");
pthread_mutex_unlock(&mutex2);
printf("I'm T1, just freed mutex2\\n");
x++;
}
pthread_exit(0);
}
void *functionB(){
int x = 0;
while(1){
pthread_mutex_lock(&mutex2);
printf("I'm T2, just locked mutex2\\n");
pthread_mutex_lock(&mutex1);
printf("I'm T2, just locked mutex1\\n");
var_A++;
var_B++;
printf("I am Thread2: var_A = %d, var_B = %d\\n", var_A, var_B);
pthread_mutex_unlock(&mutex2);
printf("I'm T2, just freed mutex2\\n");
pthread_mutex_unlock(&mutex1);
printf("I'm T2, just freed mutex1\\n");
x++;
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t coarse_mutex;
void* value;
int key;
volatile struct _setos_node* next;
pthread_mutex_t mutex;
} setos_node;
setos_node* head;
int setos_init(void)
{
if (pthread_mutex_init(&coarse_mutex, 0) != 0) {
printf("mutex init failed\\n");
}
head = (setos_node*) malloc(sizeof(setos_node));
head->next = 0;
head->key = INT_MIN;
return 0;
}
int setos_free(void)
{
free(head);
return 0;
}
int setos_add(int key, void* value)
{
pthread_mutex_lock(&head->mutex);
volatile setos_node* node = head->next;
volatile setos_node* prev = head;
while ((node != 0) && (node->key < key)) {
pthread_mutex_lock(&node->next->mutex);
pthread_mutex_unlock(&prev->mutex);
prev = node;
node = node->next;
}
if ((node != 0) && (node->key == key))
return 0;
setos_node* new_node = (setos_node*) malloc(sizeof(setos_node));
new_node->key = key;
new_node->value = value;
new_node->next = node;
prev->next = new_node;
pthread_mutex_unlock(&node->mutex);
pthread_mutex_unlock(&prev->mutex);
return 1;
}
int setos_remove(int key, void** value)
{
pthread_mutex_lock(&head->mutex);
volatile setos_node* node = head->next;
volatile setos_node* prev = head;
while (node != 0) {
if (node->key == key) {
if (value != 0)
*value = node->value;
prev->next = node->next;
return 1;
}
pthread_mutex_lock(&node->next->mutex);
pthread_mutex_unlock(&prev->mutex);
prev = node;
node = node->next;
}
pthread_mutex_unlock(&node->mutex);
pthread_mutex_unlock(&prev->mutex);
return 0;
}
int setos_contains(int key)
{
volatile setos_node* node = head->next;
while (node != 0) {
if (node->key == key)
return 1;
node = node->next;
}
return 0;
}
int main(void)
{
int x = 1;
setos_init();
setos_add(1, &x);
setos_add(2, &x);
setos_add(3, &x);
assert(setos_contains(2));
assert(!setos_contains(4));
assert(!setos_remove(4,0));
assert(setos_remove(2,0));
assert(!setos_contains(2));
setos_free();
return 0;
}
| 1
|
#include <pthread.h>
int wait_reply_server_greeter(struct ssh_session_s *session, struct timespec *expire, unsigned int *error)
{
struct ssh_receive_s *receive=&session->receive;
struct rawdata_queue_s *queue=&receive->rawdata_queue;
int result=0;
pthread_mutex_lock(&queue->mutex);
while (session->data.greeter_server.ptr==0) {
result=pthread_cond_timedwait(&queue->cond, &queue->mutex, expire);
if (session->data.greeter_server.ptr) {
*error=0;
break;
} else if (result==ETIMEDOUT) {
*error=result;
result=-1;
break;
}
}
pthread_mutex_unlock(&queue->mutex);
return result;
}
void signal_reply_server(struct ssh_session_s *session)
{
struct ssh_receive_s *receive=&session->receive;
struct rawdata_queue_s *queue=&receive->rawdata_queue;
pthread_mutex_lock(&queue->mutex);
pthread_cond_broadcast(&queue->cond);
pthread_mutex_unlock(&queue->mutex);
}
| 0
|
#include <pthread.h>
const long long infinity = 1e8;
long long *primes;
long long *notPrime;
long long N, K, n, last, last1;
pthread_mutex_t mutex;
long long min(long long a, long long b) {
return a <= b ? a : b;
}
struct Segment {
long long start, finish;
};
void* findPrimeNumbersOnSegment(void* args) {
struct Segment* seg = args;
for (long long i = 0; i < last1; ++i)
for (long long j = seg->start - seg->start % primes[i];
j <= seg->finish; j += primes[i]) {
if (j < seg->start)
continue;
notPrime[j] = 1;
}
for (long long j = seg->start; j <= seg->finish; ++j)
if (!notPrime[j]) {
pthread_mutex_lock(&mutex);
primes[last++] = j;
pthread_mutex_unlock(&mutex);
}
}
int main(int argc, char** argv) {
pthread_mutex_init(&mutex, 0);
if (argc < 2) {
printf("error: the number of threads is not given\\n");
exit(11);
}
K = atoll(argv[1]);
N = argc > 2 ? atoll(argv[2]) : infinity;
primes = calloc(N + 1, sizeof(long long));
if (!primes) {
perror("calloc");
exit(1);
}
notPrime = calloc(N + 1, sizeof(long long));
if (!notPrime) {
perror("calloc");
exit(1);
}
notPrime[1] = 1;
primes[0] = 2;
last = 1;
last1 = 1;
n = 2;
while (n < N) {
long long up = min(n * n, N);
long long k = min(K, up - n);
long long size = (up - n) / k;
long long x = up - n - size * k;
pthread_t* threads = calloc(k, sizeof(pthread_t));
if (!threads) {
perror("calloc");
exit(1);
}
for (int i = 0; i < k; ++i) {
struct Segment* seg = calloc(1, sizeof(struct Segment));
if (!seg) {
perror("calloc");
exit(1);
}
if (i < k - x) {
seg->start = n + 1LL + size * i;
seg->finish = min(up, seg->start + size - 1LL);
}
else {
seg->start = n + 1LL + size * (k - x) + (size + 1LL) * (i - k + x);
seg->finish = min(up, seg->start + size);
}
if (pthread_create(threads + i, 0,
findPrimeNumbersOnSegment, seg)) {
perror("pthread_create");
exit(1);
}
}
for (long long i = 0; i < k; ++i)
pthread_join(threads[i], 0);
for (long long i = n; i <= up; ++i)
if (!notPrime[i])
printf("%lld ", i);
n = up;
last1 = last;
free(threads);
}
free(primes);
free(notPrime);
}
| 1
|
#include <pthread.h>
const int RMAX = 100;
int offsetValue[20];
pthread_t thread[20];
int iThread[20];
int numLockThread[20];
int changeThread[20];
int tempThread[20];
pthread_mutex_t locks[20 +1];
void Usage(char* prog_name);
void Get_args(int argc, char* argv[], int* n_p, char* g_i_p);
void Generate_list(int a[], int n);
void Print_list(int a[], int n, char* title);
void Read_list(int a[], int n);
void Bubble_sort(int a[], int n);
void Bubble_sort_parallel(int a[]);
int main(int argc, char* argv[]) {
int n;
char g_i;
int* a;
int bloco;
Get_args(argc, argv, &n, &g_i);
a = (int*) malloc(n*sizeof(int));
if (g_i == 'g') {
Generate_list(a, n);
Print_list(a, n, "Before sort");
} else {
Read_list(a, n);
}
int i=0;
for(i=0; i<20;i++)
pthread_mutex_init(&locks[i], 0);
bloco=n/20;
for (i=0;i<20;i++)
offsetValue[i]=(i+1)*bloco;
for(i = 0; i < 20; i++){
pthread_create(&thread[i], 0, &Bubble_sort, a);
}
for(i = 0; i < 20; i++){
pthread_join(thread[i], 0);
}
Print_list(a, n, "After sort");
free(a);
return 0;
}
void Usage(char* prog_name) {
fprintf(stderr, "usage: %s <n> <g|i>\\n", prog_name);
fprintf(stderr, " n: number of elements in list\\n");
fprintf(stderr, " 'g': generate list using a random number generator\\n");
fprintf(stderr, " 'i': user input list\\n");
}
void Get_args(int argc, char* argv[], int* n_p, char* g_i_p) {
if (argc != 3 ) {
Usage(argv[0]);
exit(0);
}
*n_p = atoi(argv[1]);
*g_i_p = argv[2][0];
if (*n_p <= 0 || (*g_i_p != 'g' && *g_i_p != 'i') ) {
Usage(argv[0]);
exit(0);
}
}
void Generate_list(int a[], int n) {
int i;
srandom(0);
for (i = 0; i < n; i++)
a[i] = random() % RMAX;
}
void Print_list(int a[], int n, char* title) {
int i;
printf("%s:\\n", title);
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\\n\\n");
}
void Read_list(int a[], int n) {
int i;
printf("Please enter the elements of the list\\n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
}
void Bubble_sort(
int a[] ,
int n ) {
int list_length, i, temp;
for (list_length = n; list_length >= 2; list_length--)
for (i = 0; i < list_length-1; i++)
if (a[i] > a[i+1]) {
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}
void Bubble_sort_parallel(int a[]) {
int list_length=n, i, temp;
int numLock=0;
int ordered=0;
int change=0;
while (!ordered){
change = 0;
numLock = 0;
pthread_mutex_lock(&(locks[0]));
for (i = 0; i < list_length-1; i++){
if (a[i] > a[i+1]) {
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
change=1;
}
if (i==offsetValue[numLock]) {
pthread_mutex_lock(&(locks[(numLock+1)]));
pthread_mutex_unlock(&(locks[(numLock)]));
numLock++;
}
}
if (change==0)
ordered=1;
list_length--;
pthread_mutex_unlock(&(locks[(numLock)]));
}
}
| 0
|
#include <pthread.h>
double start_time, end_time;
pthread_mutex_t palindromicsMutex;
pthread_mutex_t wordsMutex;
long amountWords;
long position;
struct thread_data {
long noPalindromes;
char** words;
FILE* palindromicsfd;
};
double read_timer()
{
static bool initialized = 0;
static struct timeval start;
struct timeval end;
if( !initialized )
{
gettimeofday( &start, 0 );
initialized = 1;
}
gettimeofday( &end, 0 );
return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec);
}
void reverseStr(char* str)
{
if(str) {
int i, length, last_pos;
length = strlen(str);
last_pos = length - 1;
for(i=0; i<length/2; i++) {
char tmp = str[i];
str[i] = str[last_pos - i];
str[last_pos - i] = tmp;
}
}
}
long countlines(FILE* fp)
{
long lines = 0;
int ch;
while (EOF != (ch=fgetc(fp)))
if (ch=='\\n')
++lines;
rewind(fp);
return lines;
}
void* work(void *threadarg)
{
struct thread_data* my_data;
my_data = (struct thread_data *) threadarg;
while(1) {
char* word;
long i;
pthread_mutex_lock(&wordsMutex);
if(position < amountWords) {
word = *(my_data->words+position);
position++;
} else {
pthread_mutex_unlock(&wordsMutex);
pthread_exit(0);
}
pthread_mutex_unlock(&wordsMutex);
char* copy = malloc(strlen(word)+1);
strcpy(copy, word);
reverseStr(copy);
for(i=0; i<amountWords; i++) {
if(!strcasecmp(copy, *(my_data->words+i))) {
my_data->noPalindromes += 1;
pthread_mutex_lock(&palindromicsMutex);
fprintf(my_data->palindromicsfd, "%s\\n", word);
pthread_mutex_unlock (&palindromicsMutex);
break;
}
}
free(copy);
}
}
int main(int argc, char* argv[])
{
if (argc != 2) {
printf("Usage: %s <number of worker processes>\\n", argv[0]);
exit(0);
}
int noThreads = atoi(argv[1]);
pthread_t threads[noThreads];
pthread_attr_t attr;
struct thread_data thread_data_array[noThreads];
int rc;
void *status;
FILE* fd = fopen("palindromics", "w");
if(!fd) {
perror("Error opening palindromics file in master: ");
exit(-1);
}
FILE* wordsFile = fopen("words", "r");
if(!wordsFile) {
perror("Error opening words file in master: ");
exit(-1);
}
amountWords = countlines(wordsFile);
position = 0;
char* words[amountWords];
ssize_t read;
char* line = 0;
size_t len = 0;
long i = 0;
while((read = getline(&line, &len, wordsFile)) != -1) {
line[read-1] = 0;
words[i] = line;
i++;
line = 0;
len = 0;
}
fclose(wordsFile);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
start_time = read_timer();
for (i=0; i<noThreads; i++)
{
thread_data_array[i].noPalindromes = 0;
thread_data_array[i].words = &words[0];
thread_data_array[i].palindromicsfd = fd;
rc = pthread_create(&threads[i], &attr, work, (void *)&thread_data_array[i]);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
pthread_attr_destroy(&attr);
long noPalindromics = 0;
for(i=0; i<noThreads; i++) {
rc = pthread_join(threads[i], &status);
if (rc) {
printf("ERROR; return code from pthread_join() is %d\\n", rc);
exit(-1);
}
printf("Thread %ld found %ld palindromics\\n",i,thread_data_array[i].noPalindromes);
noPalindromics += thread_data_array[i].noPalindromes;
}
end_time = read_timer();
fclose(fd);
for (i=0; i<amountWords; i++) {
free(words[i]);
}
printf("Found total of %ld palindromics\\n", noPalindromics);
printf("The execution time is %g sec\\n", end_time - start_time);
exit(0);
}
| 1
|
#include <pthread.h>
struct sockaddr_in addr;
int fd;
int uid;
char name[64];
} client_t;
pthread_mutex_t thread_mutex = PTHREAD_MUTEX_INITIALIZER;
volatile int thread_count = 0;
static int connfd;
void *handle_input(void *arg) {
char input[1024];
memset(input, 0, sizeof(input));
while (fgets(input, 1024, stdin)) {
if (strlen(input) > 1) {
input[strlen(input)-1] = '\\0';
write(connfd, input, strlen(input));
if (strcmp(input, "/quit") == 0) {
pthread_mutex_lock(&thread_mutex);
thread_count--;
pthread_mutex_unlock(&thread_mutex);
return 0;
}
}
memset(input, 0, sizeof(input));
}
}
int main(int argc, char *argv[]) {
char *servIP;
struct sockaddr_in serv_addr;
char buffer[1024];
pthread_t tinput;
servIP = argv[1];
if (strlen(servIP) < 7)
return -1;
connfd = socket(AF_INET, SOCK_STREAM, 0);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(servIP);
serv_addr.sin_port = htons(5000);
if (connect(connfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
close(connfd);
perror("Error connecting to server!");
return -2;
}
printf("Connected to server.\\n");
pthread_mutex_lock(&thread_mutex);
thread_count++;
pthread_mutex_unlock(&thread_mutex);
pthread_create(&tinput, 0, &handle_input, 0);
memset(buffer, 0, 1024);
while (thread_count > 0) {
memset(buffer, 0, 1024);
if (recv(connfd, buffer, sizeof(buffer), 0) > 0) {
printf("Server: %s\\n", buffer);
}
}
close(connfd);
}
| 0
|
#include <pthread.h>
void *philosopher(void *arg);
int food_left();
void pick_chop(int p, int c);
void drop_chop(int c1, int c2);
int get_ticket();
void return_ticket();
pthread_mutex_t food_lock;
pthread_mutex_t chopstick[5];
pthread_t philos[5];
sem_t phil_sem;
int main(int argn, char* argv[]){
pthread_attr_t attr;
int rc;
long t;
void* status;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
sem_init(&phil_sem, 0, 5 - 1);
pthread_mutex_init(&food_lock, 0);
for(t = 0; t<5; t++){
pthread_mutex_init(&chopstick[t],0);
}
for(t = 0; t<5; t++){
rc = pthread_create(&philos[t], &attr, philosopher, (void*)t);
if(rc){
printf("ERROR: Return from pthread_create() is %d\\n", rc);
}
}
for(t=0; t<5; t++){
rc = pthread_join(philos[t], &status);
if(rc){
printf("ERROR: Return from pthread_join() is %d\\n", rc);
}
}
printf("FOOD Finished!\\nExiting..");
return 0;
}
void *philosopher(void *arg){
int left_chop, right_chop, f = 200;
int tid = (int*)arg;
right_chop = tid;
left_chop = tid+1;
printf("Food left = %d\\n",f);
if(left_chop == 5){
left_chop = 0;
}
while(f = food_left()){
char c = getchar();
printf("Philosopher %d is now thinking..\\n", tid);
usleep(5000*(f-1));
printf("Philosopher %d is now hungry..\\n", tid);
get_ticket();
pick_chop(tid, right_chop);
pick_chop(tid, left_chop);
printf("Philosopher %d is now eating..\\n", tid);
usleep(5000 * (200 - f + 1));
drop_chop(left_chop, right_chop);
return_ticket();
}
pthread_exit(0);;
}
int food_left(){
static int food = 200;
int myfood;
pthread_mutex_lock(&food_lock);
if(food>0){
food--;
}
myfood = food;
pthread_mutex_unlock(&food_lock);
return myfood;
}
void pick_chop(int id, int c){
pthread_mutex_lock(&chopstick[c]);
printf("Philosspher %d picked Chopstick %d\\n",id,c);
}
void drop_chop(int c1, int c2){
pthread_mutex_unlock(&chopstick[c1]);
pthread_mutex_unlock(&chopstick[c2]);
}
int get_ticket()
{
sem_wait(&phil_sem);
}
void return_ticket()
{
sem_post(&phil_sem);
}
| 1
|
#include <pthread.h>
int sumTotal;
pthread_mutex_t mymutex=PTHREAD_MUTEX_INITIALIZER;
void *thread_function(void *arg) {
unsigned int index;
unsigned int sum = 0;
index = *((unsigned int *) (arg));
for ( unsigned int i = index * 25; i < ((index+1)*25); i++ )
sum += i;
pthread_mutex_lock(&mymutex);
sumTotal += sum;
pthread_mutex_unlock(&mymutex);
return 0;
}
int main(void) {
pthread_t mythreads[4];
unsigned int threadName[4];
for (unsigned int i = 0; i < 4; i++){
threadName[i] = i;
if (pthread_create(&mythreads[i], 0, thread_function,
&threadName[i]) != 0)
perror("error creating thread.");
}
for (unsigned int i = 0; i < 4; i++){
if (pthread_join ( mythreads[i], 0 ) != 0)
perror("error joining thread.");
}
printf("\\nThe total sum equals %u\\n",sumTotal);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
void* funcCount1();
void* funcCount2();
int count = 0;
int main(){
pthread_t thread1, thread2;
pthread_create(&thread1, 0, &funcCount1, 0);
pthread_create(&thread2, 0, &funcCount2, 0);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
printf("Final count %d\\n", count);
exit(0);
}
void* funcCount1(){
for(;;){
pthread_mutex_lock(&count_mutex);
pthread_cond_wait(&condition_var, &count_mutex);
count++;
printf("counter value function 1 %d\\n", count);
pthread_mutex_unlock(&count_mutex);
if(count >= 10) return(0);
}
}
void* funcCount2(){
for(;;){
pthread_mutex_lock(&count_mutex);
if(count < 3 || count > 6){
pthread_cond_signal(&condition_var);
}
else{
count++;
printf("counter value function 2 %d\\n", count);
}
pthread_mutex_unlock(&count_mutex);
if(count >= 10) return(0);
}
}
| 1
|
#include <pthread.h>
void pthread_barrier ();
void create_threads ();
void join_threads ();
void read_x ();
void read_a ();
void print_y ();
void * Pth_mat_vect (void * rank);
void get_offset (int rank, int threads, long rows, long * start, long * end);
int thread_count;
pthread_t * t_ids;
sem_t * semaphores;
long m, n;
double * x, * A, * y;
pthread_mutex_t mutex;
pthread_cond_t cond_var;
int counter = 0;
int main(int argc, char ** argv) {
if (argc != 2) {
printf("Invalid arguments\\n");
exit(1);
}
scanf("%ld %ld", &m, &n);
struct timeval start, end;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond_var, 0);
thread_count = strtol(argv[1], 0, 10);
t_ids = (pthread_t *) malloc(sizeof(pthread_t) * thread_count);
x = (double *) malloc(sizeof(double) * n);
A = (double *) malloc(sizeof(double) * (n * m));
y = (double *) malloc(sizeof(double) * m);
read_x();
read_a();
create_threads();
pthread_barrier();
gettimeofday(&start, 0);
pthread_barrier();
gettimeofday(&end, 0);
long t = (end.tv_sec * 1000000 + end.tv_usec) -
(start.tv_sec * 1000000 + start.tv_usec);
join_threads();
printf("t: %d m: %ld n: %ld time: %ld\\n", thread_count, m, n, t);
free(x);
free(t_ids);
return 0;
}
void pthread_barrier() {
pthread_mutex_lock(&mutex);
counter++;
if (counter == (thread_count + 1)) {
counter = 0;
pthread_cond_broadcast(&cond_var);
} else {
while (pthread_cond_wait(&cond_var, &mutex) != 0);
}
pthread_mutex_unlock(&mutex);
}
void create_threads() {
long i, err;
for (i = 0; i < thread_count; i++) {
err = pthread_create(&t_ids[i], 0, Pth_mat_vect, (void *) i);
if (err) {
perror("Could not create thread");
exit(1);
}
}
}
void join_threads() {
int i, err;
for (i = 0; i < thread_count; i++) {
err = pthread_join(t_ids[i], 0);
if (err) {
perror("Could not join thread");
exit(1);
}
}
}
void read_x() {
int i;
for (i = 0; i < n; i++) {
scanf("%lf", &x[i]);
}
}
void read_a() {
int i;
for (i = 0; i < (n * m); i++) {
scanf("%lf", &A[i]);
}
}
void print_y() {
long i;
for (i = 0; i < m; i++) {
printf("y[%ld] %lf\\n", i, y[i]);
}
}
void * Pth_mat_vect(void * rank) {
long my_rank = (long) rank;
int i, j;
long my_first_row, my_last_row;
get_offset(my_rank, thread_count, m, &my_first_row, &my_last_row);
pthread_barrier();
for (i = my_first_row; i < my_last_row; i++) {
y[i] = 0.0;
for (j = 0; j < n; j++) {
y[i] += A[i * n + j] * x[j];
}
}
pthread_barrier();
return 0;
}
void get_offset( int rank, int threads, long rows, long * start, long * end) {
long r = rows % threads;
long offset, step, idx;
if (rank < r) {
offset = 0;
step = (rows / threads) + 1;
idx = rank;
} else {
offset = ((rows / threads) + 1) * r;
step = rows / threads;
idx = rank - r;
}
*start = offset + (step * idx);
*end = (*start) + step;
}
| 0
|
#include <pthread.h>
int n = 100;
pthread_cond_t sig1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t sig2 = PTHREAD_COND_INITIALIZER;
int flag1 = 0, flag2 = 0;
pthread_mutex_t mut1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mut2 = PTHREAD_MUTEX_INITIALIZER;
void* thread_function1(void* unused)
{
int i;
printf("\\n");
for (i = 0; i < n; i++)
{
printf("a ");
}
printf("\\n");
printf("\\nthread_function1 sends signal sig2 for the thread_function2\\n");
pthread_mutex_lock(&mut2);
flag2 = 1;
pthread_cond_signal(&sig2);
pthread_mutex_unlock(&mut2);
printf("\\nSignal sig2 is sent!\\n");
printf("\\nthread_function1 waits for receiving of the signal sig1\\n");
pthread_mutex_lock(&mut1);
while (flag1 == 0)
{
printf("\\nthread_function1 is waiting\\n");
pthread_cond_wait(&sig1,&mut1);
}
pthread_mutex_unlock(&mut1);
printf("\\nthread_function1 works after receiving of the signal sig1\\n");
printf("\\n");
for (i = 0; i < n; i++)
{
printf("b ");
}
printf("\\n");
return 0;
}
void* thread_function2(void* unused)
{
int i;
printf("\\n");
for (i = 0; i < n; i++)
{
printf("1 ");
}
printf("\\n");
printf("\\nthread_function2 sends signal sig1 for the thread_function1\\n");
pthread_mutex_lock(&mut1);
flag1 = 1;
pthread_cond_signal(&sig1);
pthread_mutex_unlock(&mut1);
printf("\\nSignal sig1 is sent!\\n");
printf("\\nthread_function2 waits for receiving of the signal sig2\\n");
pthread_mutex_lock(&mut2);
while (flag2 == 0)
{
printf("\\nthread_function2 is waiting\\n");
pthread_cond_wait(&sig2,&mut2);
}
pthread_mutex_unlock(&mut2);
printf("\\nthread_function2 works after receiving of the signal sig2\\n");
printf("\\n");
for (i = 0; i < n; i++)
{
printf("2 ");
}
printf("\\n");
return 0;
}
int main()
{
pthread_t thread1;
pthread_t thread2;
pthread_create (&thread1, 0, &thread_function1, 0);
pthread_create (&thread2, 0, &thread_function2, 0);
pthread_join (thread1, 0);
pthread_join (thread2, 0);
printf("\\nProgram Finished !!!\\n");
return 0;
}
| 1
|
#include <pthread.h>
int count = 0;
int thread_ids[3] = {0,1,2};
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *inc_count(void *t)
{
int i;
long my_id = (long)t;
for (i=0; i<10; i++) {
pthread_mutex_lock(&count_mutex);
count++;
if (count == 12) {
pthread_cond_signal(&count_threshold_cv);
printf("inc_count(): thread %ld, count = %d Threshold reached.\\n",
my_id, count);
}
printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n",
my_id, count);
pthread_mutex_unlock(&count_mutex);
sleep(1);
}
pthread_exit(0);
}
void *watch_count(void *t)
{
long my_id = (long)t;
printf("Starting watch_count(): thread %ld\\n", my_id);
pthread_mutex_lock(&count_mutex);
while (count<12) {
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %ld Condition signal received.\\n", my_id);
count += 125;
printf("watch_count(): thread %ld count now = %d.\\n", my_id, count);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main (int argc, char *argv[])
{
int i, rc;
long t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, watch_count, (void *)t1);
pthread_create(&threads[1], &attr, inc_count, (void *)t2);
pthread_create(&threads[2], &attr, inc_count, (void *)t3);
for (i=0; i<3; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited on %d threads. Done.\\n", 3);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int test_phil(struct dining_room *room, int phil)
{
if(room->phil_state[phil] == HUNGRY && room->phil_state[right_neighbor(room, phil)] != EATING && room->phil_state[left_neighbor(room,phil)] != EATING){
room->phil_state[phil] = EATING;
display_states(room);
return 1;
}
else return 0;
}
void run_simulation(struct dining_room *room)
{
display_headings(room);
display_states(room);
int i;
for (i = 0; i < room->num_phils; i++){
pthread_create(&room->phil_threads[i], 0, start_philosopher, &room->phil_args[i]);
}
for (i = 0; i < room->num_phils; i++){
pthread_join(room->phil_threads[i], 0);
}
wait();
}
void grab_forks(struct dining_room *room, int phil)
{
pthread_mutex_lock(&room->table_lock);
room->phil_state[phil] = HUNGRY;
display_states(room);
if (!test_phil(room, phil)){
pthread_cond_wait(&room->safe_to_eat[phil], &room->table_lock);
}
pthread_mutex_unlock(&room->table_lock);
}
void release_forks(struct dining_room *room, int phil )
{
pthread_mutex_lock(&room->table_lock);
room->phil_state[phil] = THINKING;
display_states(room);
if (test_phil(room, right_neighbor(room,phil))){
pthread_cond_signal(&room->safe_to_eat[right_neighbor(room,phil)]);
}
if (test_phil(room, left_neighbor(room,phil))) {
pthread_cond_signal(&room->safe_to_eat[left_neighbor(room,phil)]);
}
pthread_mutex_unlock(&room->table_lock);
}
void display_headings(struct dining_room *room)
{
int phil;
for(phil = 0; phil < room->num_phils; phil++)
printf("PHIL %-5d", phil);
printf("\\n");
}
void display_states(struct dining_room *room)
{
int phil;
for(phil = 0; phil < room->num_phils; phil++) {
switch(room->phil_state[phil]) {
case THINKING: printf("%-10s", "THINKING"); break;
case HUNGRY: printf("%-10s", "HUNGRY"); break;
case EATING: printf("%-10s", "EATING"); break;
default: printf("%-10s", "CONFUSED");
}
}
printf("\\n");
fflush(stdout);
}
int left_neighbor(struct dining_room *room, int phil )
{
return phil == room->num_phils - 1? 0 : phil + 1;
}
int right_neighbor(struct dining_room *room, int phil )
{
return phil == 0 ? room->num_phils - 1 : phil - 1;
}
void think( )
{
unsigned int seed = time(0);
srand(seed);
usleep(rand() % 500000);
}
void eat( )
{
unsigned int seed = time(0);
srand(seed);
usleep(rand() % 500000);
}
void *start_philosopher( void *the_args )
{
struct p_args *args = (struct p_args *)the_args;
int i;
for(i = 0; i < args->num_cycles; i++) {
think();
grab_forks(args->room, args->phil_num);
eat();
release_forks(args->room, args->phil_num);
}
return 0;
}
void init_dining_room(struct dining_room *room, int num_phils, int num_cycles )
{
if(num_phils > MAX_PHILS || num_phils < 1) {
fprintf(stderr, "Error: invalid number of philosophers");
exit(1);
}
if(num_cycles < 1) {
fprintf(stderr, "Error: invalid number of philosophers");
exit(1);
}
room->num_phils = num_phils;
room->num_cycles = num_cycles;
pthread_mutex_init(&room->table_lock, 0);
int phil;
for(phil = 0; phil < num_phils; phil++) {
room->phil_state[phil] = THINKING;
pthread_cond_init(&room->safe_to_eat[phil], 0);
room->phil_args[phil].phil_num = phil;
room->phil_args[phil].num_cycles = num_cycles;
room->phil_args[phil].room = room;
}
}
| 1
|
#include <pthread.h>
void *process1(void * arge);
void *process2(void * arge);
void *process3(void * arge);
pthread_mutex_t mux;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond3 = PTHREAD_COND_INITIALIZER;
int main()
{
pthread_t id1,id2,id3;
pthread_cond_init(&cond1,0);
pthread_cond_init(&cond2,0);
pthread_cond_init(&cond3,0);
pthread_mutex_init(&mux,0);
pthread_create(&id1,0,process1,(void *)0);
pthread_create(&id2,0,process2,(void *)0);
pthread_create(&id3,0,process3,(void *)0);
sleep(1);
pthread_cond_signal(&cond1);
pthread_join(id1,0);
pthread_join(id2,0);
pthread_join(id3,0);
return 0;
}
void * process1(void * arge)
{
int i;
for(i=0;i<10;i++)
{
pthread_mutex_lock(&mux);
pthread_cond_wait(&cond1,&mux);
printf("A");
pthread_mutex_unlock(&mux);
pthread_cond_signal(&cond2);
}
}
void * process2(void * arge)
{
int i;
for(i=0;i<10;i++)
{
pthread_mutex_lock(&mux);
pthread_cond_wait(&cond2,&mux);
printf("B");
pthread_mutex_unlock(&mux);
pthread_cond_signal(&cond3);
}
}
void * process3(void * arge)
{
int i;
for(i=0;i<10;i++)
{
pthread_mutex_lock(&mux);
pthread_cond_wait(&cond3,&mux);
printf("C");
pthread_mutex_unlock(&mux);
pthread_cond_signal(&cond1);
}
}
| 0
|
#include <pthread.h>
sem_t producer_sem;
sem_t consumer_sem;
pthread_mutex_t mutex;
int buffer[10];
int duration = 20;
int length = 0;
void *producer(void *arg)
{
int str;
str=(int)arg;
for(int i = 0; i < duration; i++) {
sem_wait(&producer_sem);
pthread_mutex_lock(&mutex);
buffer[length] = i;
length++;
printf("Producer %d length %d\\n",str, length);
pthread_mutex_unlock(&mutex);
sem_post(&consumer_sem);
}
return 0;
}
void *consumer(void *arg)
{
int str;
str=(int)arg;
for(int i = 0; i < duration; i++) {
sem_wait(&consumer_sem);
pthread_mutex_lock(&mutex);
length--;
int temp = buffer[length];
printf("Consumer %d at %d, value %d\\n",str, length, temp);
pthread_mutex_unlock(&mutex);
sem_post(&producer_sem);
}
return 0;
}
int main(int argc, char *argv[]) {
pthread_t producer_thread[2];
pthread_t consumer_thread[2];
sem_init(&producer_sem, 0, 10);
sem_init(&consumer_sem, 0, 0);
for(int i = 0; i < 2; i++) {
pthread_create(&producer_thread[i], 0, producer, (void *)(uintptr_t) i);
pthread_create(&consumer_thread[i], 0, consumer, (void *)(uintptr_t) i);
}
for(int i = 0; i < 2; i++) {
pthread_join(producer_thread[i], 0);
pthread_join(consumer_thread[i], 0);
}
sem_destroy(&producer_sem);
sem_destroy(&consumer_sem);
return 0;
}
| 1
|
#include <pthread.h>
int valoare = 5;
int contor = 0;
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
void * func(void * val) {
int v;
v = *(int*)val;
for(;;) {
pthread_mutex_lock(&mtx);
if (contor == 20) exit(1);
if(v == valoare){
printf("%d \\n",valoare);
printf("%d \\n \\n",contor);
contor++;
valoare = rand()%9+0;
}
pthread_mutex_unlock(&mtx);
}
return 0;
}
int main(int argc,char * argv[]) {
int i;
valoare = rand()%9+0;
pthread_t threads[10];
pthread_mutex_init(&mtx,0);
for(i=0;i<=9;++i) {
int * a = (int*)malloc(sizeof(int));
*a = i;
pthread_create(&threads[i],0,func,a);
}
for(i=0;i<10;++i) {
pthread_join(threads[i],0);
}
printf("%d \\n \\n",contor);
pthread_mutex_destroy(&mtx);
return 0;
}
| 0
|
#include <pthread.h>
char** theArray;
pthread_mutex_t mutex;
int aSize = 100;
int usr_port;
void* ServerEcho(void *args);
int main(int argc, char * argv []){
int n = atoi(argv[2]);
usr_port = atoi(argv[1]);
if( (n==10)||(n==100)||(n==1000)||(n==10000) ){
aSize=n;
}
struct sockaddr_in sock_var;
int serverFileDescriptor=socket(AF_INET,SOCK_STREAM,0);
int clientFileDescriptor;
sock_var.sin_addr.s_addr=inet_addr("127.0.0.1");
sock_var.sin_port=usr_port;
sock_var.sin_family=AF_INET;
pthread_t* thread_handles;
double start,end,time;
if(bind(serverFileDescriptor,(struct sockaddr*)&sock_var,sizeof(sock_var))>=0)
{
printf("socket has been created \\n");
listen(serverFileDescriptor,2000);
while(1){
pthread_mutex_init(&mutex,0);
thread_handles = malloc(1000*sizeof(pthread_t));
theArray=malloc(aSize*sizeof(char*));
for (int i=0; i<aSize;i++){
theArray[i]=malloc(100*sizeof(char));
sprintf(theArray[i], "%s%d%s", "String ", i, ": the initial value" );
}
GET_TIME(start);
for(int i=0;i<1000;i++){
clientFileDescriptor=accept(serverFileDescriptor,0,0);
pthread_create(&thread_handles[i],0,ServerEcho,(void*)clientFileDescriptor);
}
for(int i = 0;i<1000;i++){
pthread_join(thread_handles[i],0);
}
GET_TIME(end);
time = end-start;
printf(" %f \\n",time);
for (int i=0; i<aSize;i++){
free(theArray[i]);
}
free(theArray);
free(thread_handles);
pthread_mutex_destroy(&mutex);
}
}
else{
printf("socket creation failed \\n");
return 1;
}
return 0;
}
void* ServerEcho(void* args){
long clientFileDescriptor = (long) args;
char buff[100];
read(clientFileDescriptor,buff,100);
int pos;
char operation;
int CSerror;
sscanf(buff, "%d %c", &pos,&operation);
if(operation=='r'){
char msg[100];
pthread_mutex_lock(&mutex);
CSerror=snprintf(msg,100, "%s", theArray[pos] );
pthread_mutex_unlock(&mutex);
if(CSerror<0){
printf("ERROR: could not read from position: %d \\n", pos);
sprintf(msg, "%s %d","Error writing to pos: ", pos );
}
write(clientFileDescriptor,msg,100);
close(clientFileDescriptor);
}
else if(operation=='w'){
char msg[100];
snprintf(msg,100, "%s%d%s","String ", pos, " has been modified by a write request \\n" );
pthread_mutex_lock(&mutex);
CSerror=snprintf(theArray[pos],100,"%s",msg);
pthread_mutex_unlock(&mutex);
if(CSerror<0){
printf("ERROR: could not write to array \\n");
sprintf(msg, "%s %d","Error writing to pos: ", pos );
}
write(clientFileDescriptor,msg,100);
close(clientFileDescriptor);
}
else{
printf("ERROR: could not communicate with client %ld \\n",clientFileDescriptor);
}
return 0;
}
| 1
|
#include <pthread.h>
void mwmr_read( struct mwmr_s *fifo, void *mem, size_t len )
{
struct mwmr_status_s *state = fifo->status;
size_t got = 0;
uint8_t *ptr = (uint8_t *)mem;
assert ( len % fifo->width == 0 );
pthread_mutex_lock( &(state->lock) );
while ( got < len ) {
while ( ! state->usage ) {
pthread_cond_wait( &(state->nempty), &(state->lock) );
}
memcpy( ptr, fifo->buffer + state->rptr, fifo->width );
state->rptr += fifo->width;
if ( state->rptr == fifo->gdepth )
state->rptr = 0;
state->usage -= fifo->width;
assert( state->rptr < fifo->gdepth );
assert( state->usage <= fifo->gdepth );
pthread_cond_signal( &(state->nfull) );
got += fifo->width;
ptr += fifo->width;
}
pthread_mutex_unlock( &(state->lock) );
pthread_cond_signal( &(state->nfull) );
pthread_yield();
}
void mwmr_write( struct mwmr_s *fifo, const void *mem, size_t len )
{
struct mwmr_status_s *state = fifo->status;
size_t put = 0;
uint8_t *ptr = (uint8_t *)mem;
assert ( len % fifo->width == 0 );
pthread_mutex_lock( &(state->lock) );
while ( put < len ) {
while ( state->usage == fifo->gdepth ) {
pthread_cond_wait( &(state->nfull), &(state->lock) );
}
memcpy( fifo->buffer + state->wptr, ptr, fifo->width );
state->wptr += fifo->width;
if ( state->wptr == fifo->gdepth )
state->wptr = 0;
state->usage += fifo->width;
assert( state->wptr < fifo->gdepth );
assert( state->usage <= fifo->gdepth );
pthread_cond_signal( &(state->nempty) );
put += fifo->width;
ptr += fifo->width;
}
pthread_mutex_unlock( &(state->lock) );
pthread_cond_signal( &(state->nempty) );
pthread_yield();
}
size_t mwmr_try_read( struct mwmr_s *fifo, void *mem, size_t len )
{
struct mwmr_status_s *state = fifo->status;
size_t got = 0;
uint8_t *ptr = (uint8_t *)mem;
assert ( len % fifo->width == 0 );
if ( pthread_mutex_trylock( &(state->lock) ) ) {
return 0;
}
while ( got < len ) {
if ( ! state->usage ) {
pthread_mutex_unlock( &(state->lock) );
pthread_cond_signal( &(state->nfull) );
return got;
}
memcpy( ptr, fifo->buffer + state->rptr, fifo->width );
state->rptr += fifo->width;
if ( state->rptr == fifo->gdepth )
state->rptr = 0;
state->usage -= fifo->width;
got += fifo->width;
ptr += fifo->width;
}
pthread_mutex_unlock( &(state->lock) );
pthread_cond_signal( &(state->nfull) );
pthread_yield();
return got;
}
size_t mwmr_try_write( struct mwmr_s *fifo, const void *mem, size_t len )
{
struct mwmr_status_s *state = fifo->status;
size_t put = 0;
uint8_t *ptr = (uint8_t *)mem;
assert( len % fifo->width == 0 );
if ( pthread_mutex_trylock( &(state->lock) ) ) {
return 0;
}
while ( put < len ) {
if ( state->usage == fifo->gdepth ) {
pthread_mutex_unlock( &(state->lock) );
pthread_cond_signal( &(state->nempty) );
return put;
}
memcpy( fifo->buffer + state->wptr, ptr, fifo->width );
state->wptr += fifo->width;
if ( state->wptr == fifo->gdepth )
state->wptr = 0;
state->usage += fifo->width;
put += fifo->width;
ptr += fifo->width;
}
pthread_mutex_unlock( &(state->lock) );
pthread_cond_signal( &(state->nempty) );
pthread_yield();
return put;
}
void mwmr_init( struct mwmr_s *fifo )
{
struct mwmr_status_s *state = fifo->status;
pthread_cond_init(&state->nempty, 0);
pthread_cond_init(&state->nfull, 0);
pthread_mutex_init(&state->lock, 0);
}
| 0
|
#include <pthread.h>
int N;
int ID;
} thread_args;
pthread_mutex_t trava;
int n_workers = 0;
pthread_t workers[4];
int worker_status[4];
int fibo(int N) {
if (N<=2) return 1;
else return (fibo(N-1) + fibo(N-2));
}
void* worker(void *arg) {
thread_args *info = (thread_args *)arg;
int M = fibo(info->N);
printf("Fibo(%d)=%d\\n", info->N, M);
pthread_mutex_lock(&trava);
n_workers -= 1;
worker_status[info->ID] = 0;
free(info);
pthread_mutex_unlock(&trava);
return 0;
}
int main(int argc, char **argv) {
int numero_recebido;
thread_args *send_args;
int j;
while (1) {
scanf("%d", &numero_recebido);
printf("Recebi: %d\\n", numero_recebido);
if (numero_recebido<0) break;
if (n_workers >= 4) {
printf("Muitas tarefas sendo executadas. Ingnorando entrada\\n");
} else {
pthread_mutex_lock(&trava);
printf("Iniciando nova thread\\n");
send_args = (thread_args*)malloc(sizeof(thread_args));
send_args->N = numero_recebido;
j = 0;
while (worker_status[j] == 1) j++;
send_args->ID = j;
worker_status[j] = 1;
n_workers += 1;
printf("Threads ativas: %d de %d\\n", n_workers, 4);
pthread_create(& (workers[j]), 0, worker, (void*) send_args);
pthread_mutex_unlock(&trava);
}
}
printf("Terminando programa. Esperando threads terminarem...\\n");
for (int i=0; i<4; i++) {
if (worker_status[i]==1) {
pthread_join(workers[i], 0);
}
}
printf("FIM!\\n");
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t *lock_cs;
long *lock_count;
pthread_mutex_t locker = PTHREAD_MUTEX_INITIALIZER;
int mtctr;
unsigned long id_function(void)
{
return ((unsigned long) pthread_self());
}
void locking_function(int mode, int type, const char *file, int line)
{
if (mode & CRYPTO_LOCK) {
pthread_mutex_lock(&lock_cs[type]);
lock_count[type]++;
} else {
pthread_mutex_unlock(&lock_cs[type]);
}
}
void ssl_thread_setup(void)
{
int num = CRYPTO_num_locks();
int ctr;
lock_cs = (pthread_mutex_t*) OPENSSL_malloc(num * sizeof(pthread_mutex_t));
lock_count = (long*) OPENSSL_malloc(num * sizeof(long));
for (ctr = 0; ctr < num; ctr++) {
lock_count[ctr] = 0;
pthread_mutex_init(&lock_cs[ctr], 0);
}
CRYPTO_set_id_callback(id_function);
CRYPTO_set_locking_callback(locking_function);
}
void ssl_thread_cleanup(void)
{
int ctr;
CRYPTO_set_locking_callback(0);
for (ctr = 0; ctr < CRYPTO_num_locks(); ctr++) {
pthread_mutex_destroy(&lock_cs[ctr]);
}
OPENSSL_free(lock_cs);
OPENSSL_free(lock_count);
}
| 0
|
#include <pthread.h>
struct work_q
{
int job;
struct work_q *next;
};
struct work_q_args
{
struct work_q **curr, **tail;
int *work;
int *waiting;
int num_threads;
pthread_mutex_t *work_mutex;
pthread_cond_t *cond_mutex;
};
void *do_work(void *ptr)
{
struct work_q_args *p = (struct work_q_args *)ptr;
while (1) {
pthread_mutex_lock(p->work_mutex);
while (*(p->work) == 0) {
*(p->waiting) = *(p->waiting) + 1;
if (*(p->waiting) == p->num_threads) {
*(p->work) = -1;
pthread_mutex_unlock(p->work_mutex);
pthread_cond_signal(p->cond_mutex);
return;
}
pthread_cond_wait(p->cond_mutex, p->work_mutex);
*(p->waiting) = *(p->waiting) - 1;
}
if (*(p->work) < 0) {
pthread_mutex_unlock(p->work_mutex);
pthread_cond_signal(p->cond_mutex);
return;
}
struct work_q *my_work = *(p->curr);
*(p->curr) = (*(p->curr))->next;
*(p->work) = *(p->work) - 1;
pthread_mutex_unlock(p->work_mutex);
printf("%d\\n", my_work->job);
usleep(10000);
struct work_q *new_work_head = 0,
*new_work_tail = 0;
int i;
for (i = 0; i < my_work->job; ++i) {
struct work_q *new_work =
(struct work_q *)malloc(sizeof(struct work_q));
new_work->job = my_work->job - 1;
new_work->next = 0;
if (new_work_head == 0)
new_work_head = new_work;
else
new_work_tail->next = new_work;
new_work_tail = new_work;
}
pthread_mutex_lock(p->work_mutex);
if (my_work->job > 0) {
if ((*(p->curr))->job == -1) {
new_work_tail->next = *(p->curr);
*(p->curr) = new_work_head;
*(p->tail) = new_work_tail;
} else {
(*(p->tail))->next = new_work_head;
*(p->tail) = new_work_tail;
}
*(p->work) = *(p->work) + my_work->job;
}
pthread_mutex_unlock(p->work_mutex);
pthread_cond_signal(p->cond_mutex);
free(my_work);
}
}
int main(int argc, char **argv)
{
int num_threads = atoi(argv[1]);
pthread_t threads[num_threads];
struct work_q_args thread_args[num_threads];
static pthread_cond_t cond_mutex = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t work_mutex = PTHREAD_MUTEX_INITIALIZER;
int i,rc;
struct work_q *head, *tail;
struct work_q *caboose = (struct work_q *) malloc(sizeof(struct work_q));
caboose->job = -1;
caboose->next = 0;
head = (struct work_q *) malloc(sizeof(struct work_q));
head->job = 5;
head->next = caboose;
tail = head;
int work = 1;
int waiting = 0;
for (i = 0; i< num_threads; ++i) {
thread_args[i].curr = &head;
thread_args[i].tail = &tail;
thread_args[i].work = &work;
thread_args[i].num_threads = num_threads;
thread_args[i].waiting = &waiting;
thread_args[i].work_mutex = &work_mutex;
thread_args[i].cond_mutex = &cond_mutex;
rc = pthread_create(&threads[i],
0,
do_work,
(void *) &thread_args[i]);
assert( 0 == rc);
}
for (i = 0; i < num_threads; ++i) {
rc = pthread_join(threads[i], 0);
assert( 0 == rc);
}
}
| 1
|
#include <pthread.h>
int width;
int height;
unsigned * board;
} universe;
universe * universe1;
universe * universe2;
int * count;
pthread_mutex_t * mutex;
pthread_cond_t * cond;
int start;
int rows;
int num_threads;
} threadinfo;
void show(universe * univ) {
int h = univ->height, w = univ->width;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
printf( univ->board[y * w + x] ? "@" : " " );
}
printf("\\n");
}
printf("\\n");
}
void evolve(universe * univ, universe * next_gen, int start, int end){
int w = univ->width, h = univ->height;
for (int y = start; y < end; y++) {
for (int x = 0; x < w; x++) {
int n = 0;
for (int j = y - 1; j <= y + 1; j++) {
for (int i = x - 1; i <= x + 1; i++) {
if ( univ->board[((j+h) % h) * w + ((i+w) % w)] && !( j == y && i == x )) n++;
}}
next_gen->board[y*w + x] = (n == 3 || (n == 2 && univ->board[y * w + x])) ? 1 : 0;
}}
}
void *game_t(threadinfo * ti) {
for (int i = 0; i < 50; i++){
if (i % 2) {
evolve(ti->universe2, ti->universe1, ti->start, ti->start + ti->rows);
} else {
evolve(ti->universe1, ti->universe2, ti->start, ti->start + ti->rows);
}
pthread_mutex_lock(ti->mutex);
*(ti->count) = *(ti->count) + 1;
if (*(ti->count) < ti->num_threads) pthread_cond_wait(ti->cond,ti->mutex);
if (*(ti->count) == ti->num_threads) {
*(ti->count) = *(ti->count) - 1;
for (0; *(ti->count) > 0; *(ti->count) = *(ti->count) - 1) pthread_cond_signal(ti->cond);}
pthread_mutex_unlock(ti->mutex);
}
return 0;
}
int main (int argc, char **argv){
int i;
int w = 0, h = 0;
int ts = 4;
pthread_t tid[ts];
threadinfo info[ts];
int count = 0;
pthread_mutex_t mutex;
pthread_cond_t all_done;
pthread_mutex_init(&mutex,0);
pthread_cond_init(&all_done,0);
void *rv;
if (argc > 1) w = atoi(argv[1]);
if (argc > 2) h = atoi(argv[2]);
if (w <= 0) w = 250;
if (h <= 0) h = 250;
universe * univ = (universe *)malloc(sizeof(universe));
univ->board = (unsigned *)malloc(sizeof(unsigned) * w * h);
univ->width = w;
univ->height = h;
universe * univ2 = (universe *)malloc(sizeof(universe));
univ2->board = (unsigned *)malloc(sizeof(unsigned) * w * h);
univ2->width = w;
univ2->height = h;
for (int y = 0; y < univ->height; y++) {
for (int x = 0; x < univ->width; x++) {
univ->board[y * univ->width + x] = rand() % 2;
}}
show(univ);
for (i=0; i<ts; i++) {
info[i].universe1 = univ;
info[i].universe2 = univ2;
info[i].count = &count;
info[i].mutex = &mutex;
info[i].num_threads = ts;
info[i].cond = &all_done;
info[i].start = i*h/ts;
info[i].rows = h/ts;
if (i == ts - 1) info[i].rows = h/ts + h%ts;
Pthread_create(&tid[i],0,(thread_main_t *)game_t,(void *)&info[i]);
}
for (i=0; i<ts; i++) {
Pthread_join(tid[i],&rv);
}
show(univ);
printf("\\n");
Pthread_exit(0);
}
| 0
|
#include <pthread.h>
struct queue_type
{
int buff[9];
int front;
int rear;
}Q={{0},0,0};
sem_t empty;
sem_t full;
pthread_mutex_t mutex;
int producer_id = 0;
int consumer_id = 0;
void print()
{
int i;
for(i = 0; i < 9; i++)
printf("%d ", Q.buff[i]);
printf("\\n");
}
void *producer()
{
int id=++producer_id;
srand((int)time(0));
while(1)
{
sleep(1);
int item=1+10*rand()/(32767 +1);
sem_wait(&empty);
pthread_mutex_lock(&mutex);
Q.buff[Q.rear] = item;
printf("producer number<%d> \\t put %d into buffer[%d].\\nThe buffer is like: \\t", id, item ,Q.rear+1);
print();
Q.rear = (Q.rear+1) % 9;
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void *consumer()
{
int id=++consumer_id;
while(1)
{
sleep(3);
sem_wait(&full);
pthread_mutex_lock(&mutex);
printf("consumer number<%d> \\t get %d from buffer[%d].\\nThe buffer is now: \\t", id, Q.buff[Q.front], Q.front+1);
Q.buff[Q.front] = 0;
print();
Q.front = (Q.front+1) % 9;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
int main()
{
int M,N;
printf("please input the producers number: ");
scanf("%d",&M);
printf("please input the consumers number: ");
scanf("%d",&N);
pthread_t id1[M];
pthread_t id2[N];
int i;
int ret1[M],ret2[N];
int ini1 = sem_init(&empty, 0, 9);
int ini2 = sem_init(&full, 0, 0);
if((ini1 || ini2)!=0)
{
printf("sem init failed \\n");
exit(1);
}
int ini3 = pthread_mutex_init(&mutex, 0);
if(ini3 != 0)
{
printf("mutex init failed \\n");
exit(1);
}
for(i = 0; i < M; i++)
{
ret1[i] = pthread_create(&id1[i], 0, producer, 0);
if(ret1[i] != 0)
{
printf("producer%d creation failed \\n", i);
exit(1);
}
}
for(i = 0; i < N; i++)
{
ret2[i] = pthread_create(&id2[i], 0, consumer, 0);
if(ret2[i] != 0)
{
printf("consumer%d creation failed \\n", i);
exit(1);
}
}
for(i = 0; i < M; i++)
{
pthread_join(id1[i],0);
}
for(i = 0; i < N; i++)
{
pthread_join(id2[i],0);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t ca_log_lock=PTHREAD_MUTEX_INITIALIZER;
int dumpmsg_to_file(char *module_name, char *proc_name, const char *filename,
int line, const char *funcname, char *fmt, ...)
{
char mesg[4096]={0};
char buf[4096]={0};
char filepath[1024] = {0};
time_t t=0;
struct tm * now=0;
va_list ap;
time(&t);
now = localtime(&t);
__builtin_va_start((ap));
vsprintf(mesg, fmt, ap);
;
snprintf(buf, 4096, "===%04d%02d%02d-%02d%02d%02d,%s[%d]=== %s\\n",
now -> tm_year + 1900, now -> tm_mon + 1,
now -> tm_mday, now -> tm_hour, now -> tm_min, now -> tm_sec,
funcname, line, mesg);
make_path(filepath, module_name, proc_name);
pthread_mutex_lock(&ca_log_lock);
out_put_file(filepath, buf);
pthread_mutex_unlock(&ca_log_lock);
return 0;
}
int out_put_file(char *path, char *buf)
{
int fd;
fd = open(path, O_RDWR | O_CREAT | O_APPEND, 0777);
if(write(fd, buf, strlen(buf)) != (int)strlen(buf)) {
fprintf(stderr, "write error!\\n");
close(fd);
} else {
close(fd);
}
return 0;
}
int make_path(char *path, char *module_name, char *proc_name)
{
time_t t;
struct tm *now = 0;
char top_dir[1024] = {"."};
char second_dir[1024] = {"./logs"};
char third_dir[1024] = {0};
char y_dir[1024] = {0};
char m_dir[1024] = {0};
char d_dir[1024] = {0};
time(&t);
now = localtime(&t);
snprintf(path, 1024, "./logs/%s/%04d/%02d/%s-%02d.log", module_name, now -> tm_year + 1900, now -> tm_mon + 1, proc_name, now -> tm_mday);
sprintf(third_dir, "%s/%s", second_dir, module_name);
sprintf(y_dir, "%s/%04d/", third_dir, now -> tm_year + 1900);
sprintf(m_dir, "%s/%02d/", y_dir, now -> tm_mon + 1);
sprintf(d_dir,"%s/%02d/", m_dir, now -> tm_mday);
if(access(top_dir, 0) == -1) {
if(mkdir(top_dir, 0777) == -1) {
fprintf(stderr, "create %s failed!\\n", top_dir);
} else if(mkdir(second_dir, 0777) == -1) {
fprintf(stderr, "%s:create %s failed!\\n", top_dir, second_dir);
} else if(mkdir(third_dir, 0777) == -1) {
fprintf(stderr, "%s:create %s failed!\\n", top_dir, third_dir);
} else if(mkdir(y_dir, 0777) == -1) {
fprintf(stderr, "%s:create %s failed!\\n", top_dir, y_dir);
} else if(mkdir(m_dir, 0777) == -1) {
fprintf(stderr, "%s:create %s failed!\\n", top_dir, m_dir);
}
} else if(access(second_dir, 0) == -1) {
if(mkdir(second_dir, 0777) == -1) {
fprintf(stderr, "create %s failed!\\n", second_dir);
} else if(mkdir(third_dir, 0777) == -1) {
fprintf(stderr, "%s:create %s failed!\\n", second_dir, third_dir);
} else if(mkdir(y_dir, 0777) == -1) {
fprintf(stderr, "%s:create %s failed!\\n", second_dir, y_dir);
} else if(mkdir(m_dir, 0777) == -1) {
fprintf(stderr, "%s:create %s failed!\\n", second_dir, m_dir);
}
} else if(access(third_dir, 0) == -1) {
if(mkdir(third_dir, 0777) == -1) {
fprintf(stderr, "create %s failed!\\n", third_dir);
} else if(mkdir(y_dir, 0777) == -1) {
fprintf(stderr, "%s:create %s failed!\\n", third_dir, y_dir);
} else if(mkdir(m_dir, 0777) == -1) {
fprintf(stderr, "%s:create %s failed!\\n", third_dir, m_dir);
}
} else if (access(y_dir, 0) == -1) {
if(mkdir(y_dir, 0777) == -1) {
fprintf(stderr, "create %s failed!\\n", y_dir);
} else if(mkdir(m_dir, 0777) == -1) {
fprintf(stderr, "%s:create %s failed!\\n", y_dir, m_dir);
}
} else if (access(m_dir, 0) == -1) {
if(mkdir(m_dir, 0777)) {
fprintf(stderr, "create %s failed!\\n", m_dir);
}
}
return 0;
}
| 0
|
#include <pthread.h>
sem_t mayProduce, mayConsume;
pthread_t prod[10], cons[10];
pthread_mutex_t mutex;
int counter;
int buffer[10];
void initialize();
void *producer();
void *consumer();
int main()
{
int np, nc, i;
initialize();
printf("\\nEnter No. of Producers : ");
scanf("%d", &np);
printf("Enter No. of Consumers : ");
scanf("%d", &nc);
for(i=0; i<np; i++) pthread_create(&prod[i], 0, producer, 0);
for(i=0; i<nc; i++) pthread_create(&cons[i], 0, consumer, 0);
for(i=0; i<np; i++) pthread_join(prod[i], 0);
for(i=0; i<nc; i++) pthread_join(cons[i], 0);
return 0;
}
void initialize()
{
pthread_mutex_init(&mutex, 0);
sem_init(&mayProduce, 1, 0);
sem_init(&mayConsume, 1, 10);
counter = 0;
}
void *producer()
{
sem_wait(&mayConsume);
pthread_mutex_lock(&mutex);
buffer[counter++] = rand()%10;
printf("Producer produced a value\\n");
pthread_mutex_unlock(&mutex);
sem_post(&mayProduce);
}
void *consumer(){
if(counter==0) exit(0);
sem_wait(&mayProduce);
pthread_mutex_lock(&mutex);
printf("Consumer used value : %d\\n", buffer[--counter]);
pthread_mutex_unlock(&mutex);
sem_post(&mayConsume);
}
| 1
|
#include <pthread.h>
int* vet;
pthread_mutex_t mutex;
} Data;
int threshold;
Data data;
void
merge(int *vet, int left, int middle, int right) {
int i, j, k;
int n1 = middle - left + 1;
int n2 = right - middle;
int L[n1], R[n2];
for (i = 0; i <= n1; i++)
L[i] = vet[left + i];
for (j = 0; j <= n2; j++)
R[j] = vet[middle + 1 + j];
i = 0;
j = 0;
k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j])
vet[k++] = L[i++];
else
vet[k++] = R[j++];
}
while (i < n1)
vet[k++] = L[i++];
while (j < n2)
vet[k++] = R[j++];
}
void* threaded_sort(void* args) {
int* arg = args;
int left, right, middle;
void* ret = 0;
left = arg[0];
right = arg[1];
if (left < right) {
middle = left + (right - left)/2;
if ((right - left) >= threshold) {
pthread_t thread1, thread2;
int arg1[2] = {left, middle};
pthread_create(&thread1, 0, threaded_sort, arg1);
int arg2[2] = {middle + 1, right};
pthread_create(&thread2, 0, threaded_sort, arg2);
pthread_join(thread1, &ret);
pthread_join(thread2, &ret);
} else {
int arg1[2] = {left, middle};
int arg2[2] = {middle + 1, right};
threaded_sort(arg1);
threaded_sort(arg2);
}
pthread_mutex_lock(&data.mutex);
merge(data.vet, left, middle, right);
pthread_mutex_unlock(&data.mutex);
}
return ret;
}
int main(int argc, char ** argv) {
int i, n;
if (argc != 3) {
printf ("Syntax: %s dimension threshold\\n", argv[0]);
return (1);
}
n = atoi(argv[1]);
threshold = atoi(argv[2]);
data.vet = (int*) malloc(n * sizeof(int));
pthread_mutex_init(&data.mutex, 0);
pthread_mutex_lock(&data.mutex);
for(i = 0;i < n;i++) {
data.vet[i] = rand() % 100;
printf("%d\\n",data.vet[i]);
}
pthread_mutex_unlock(&data.mutex);
printf("\\n");
int arg[2] = {0, n-1};
threaded_sort(arg);
pthread_mutex_lock(&data.mutex);
for(i = 0;i < n;i++)
printf("%d\\n",data.vet[i]);
pthread_mutex_unlock(&data.mutex);
return 0;
}
| 0
|
#include <pthread.h>
int value;
pthread_mutex_t mutex;
pthread_cond_t cond;
} sema_t;
void sema_init(sema_t *sema, int value)
{
sema->value = value;
pthread_mutex_init(&sema->mutex, 0);
pthread_cond_init(&sema->cond, 0);
}
void sema_wait(sema_t *sema)
{
pthread_mutex_lock(&sema->mutex);
sema->value--;
while (sema->value < 0)
pthread_cond_wait(&sema->cond, &sema->mutex);
pthread_mutex_unlock(&sema->mutex);
}
void sema_signal(sema_t *sema)
{
pthread_mutex_lock(&sema->mutex);
++sema->value;
pthread_cond_signal(&sema->cond);
pthread_mutex_unlock(&sema->mutex);
}
int buffer[4];
int in;
int out;
int buffer_is_empty()
{
return in == out;
}
int buffer_is_full()
{
return (in + 1) % 4 == out;
}
int get_item()
{
int item;
item = buffer[out];
out = (out + 1) % 4;
return item;
}
void put_item(int item)
{
buffer[in] = item;
in = (in + 1) % 4;
}
sema_t mutex_sema;
sema_t empty_buffer_sema;
sema_t full_buffer_sema;
void *consume(void *arg)
{
int i;
int item;
for (i = 0; i < (4 * 2); i++) {
sema_wait(&full_buffer_sema);
sema_wait(&mutex_sema);
item = get_item();
sema_signal(&mutex_sema);
sema_signal(&empty_buffer_sema);
printf(" consume item: %c\\n", item);
}
return 0;
}
void produce()
{
int i;
int item;
for (i = 0; i < (4 * 2); i++) {
sema_wait(&empty_buffer_sema);
sema_wait(&mutex_sema);
item = i + 'a';
put_item(item);
sema_signal(&mutex_sema);
sema_signal(&full_buffer_sema);
printf("produce item: %c\\n", item);
}
}
int main()
{
pthread_t consumer_tid;
sema_init(&mutex_sema, 1);
sema_init(&empty_buffer_sema, 4 - 1);
sema_init(&full_buffer_sema, 0);
pthread_create(&consumer_tid, 0, consume, 0);
produce();
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
int thread_num;
int* counter;
pthread_t* thread;
int* a[1000];
int pSum[1000];
int sum = 0;
void* parallel_calculate(void* arg) {
int i = 0, j = 0;
int n = *((int*)arg);
for (j = n; j < 1000; j += thread_num) {
for (i = 0; i < 100000; ++i) {
pSum[j] += a[j][i] * i;
}
}
for (j = n; j < 1000; j += thread_num) {
pthread_mutex_lock(&mutex);
sum += pSum[j];
pthread_mutex_unlock(&mutex);
}
return 0;
}
void verify() {
int i = 0, j = 0;
sum = 0;
memset(&pSum, 0, 1000 * sizeof(int));
for (j = 0; j < 1000; j += 1) {
for (i = 0; i < 100000; ++i) {
pSum[j] += a[j][i] * i;
}
}
for (j = 0; j < 1000; j += 1) {
sum += pSum[j];
}
printf("verified sum is: %d\\n", sum);
}
int main(int argc, char** argv) {
int i = 0, j = 0;
if (argc == 1) {
thread_num = 1024;
} else {
if (atoi(argv[1]) < 1) {
printf("enter a valid thread number\\n");
return 0;
} else
thread_num = atoi(argv[1]);
}
counter = (int*)malloc(thread_num * sizeof(int));
for (i = 0; i < thread_num; ++i) counter[i] = i;
thread = (pthread_t*)malloc(thread_num * sizeof(pthread_t));
for (i = 0; i < 1000; ++i) a[i] = (int*)malloc(100000 * sizeof(int));
for (i = 0; i < 1000; ++i)
for (j = 0; j < 100000; ++j) a[i][j] = j;
memset(&pSum, 0, 1000 * sizeof(int));
assert(!pthread_mutex_init(&mutex, 0));
for (i = 0; i < thread_num; ++i)
assert(!pthread_create(&thread[i], 0, ¶llel_calculate, &counter[i]));
for (i = 0; i < thread_num; ++i) assert(!pthread_join(thread[i], 0));
printf("sum is: %d\\n", sum);
assert(!pthread_mutex_destroy(&mutex));
verify();
free(thread);
free(counter);
for (i = 0; i < 1000; ++i) free(a[i]);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t bucket_mutex[15];
int buckets[15];
pthread_t equalizer;
pthread_t randomizer;
void transfer_value(int from, int to, int howmuch)
{
bool swapped = 0;
if ( (from == to) || ( howmuch < 0 ) ||
(from < 0 ) || (to < 0) || (from >= 15) || (to >= 15) ) return;
if ( from > to ) {
int temp1 = from;
from = to;
to = temp1;
swapped = 1;
howmuch = -howmuch;
}
pthread_mutex_lock(&bucket_mutex[from]);
pthread_mutex_lock(&bucket_mutex[to]);
if ( howmuch > buckets[from] && !swapped )
howmuch = buckets[from];
if ( -howmuch > buckets[to] && swapped )
howmuch = -buckets[to];
buckets[from] -= howmuch;
buckets[to] += howmuch;
pthread_mutex_unlock(&bucket_mutex[from]);
pthread_mutex_unlock(&bucket_mutex[to]);
}
void print_buckets()
{
int i;
int sum=0;
for(i=0; i < 15; i++) pthread_mutex_lock(&bucket_mutex[i]);
for(i=0; i < 15; i++) {
printf("%3d ", buckets[i]);
sum += buckets[i];
}
printf("= %d\\n", sum);
for(i=0; i < 15; i++) pthread_mutex_unlock(&bucket_mutex[i]);
}
void *equalizer_start(void *t)
{
for(;;) {
int b1 = rand()%15;
int b2 = rand()%15;
int diff = buckets[b1] - buckets[b2];
if ( diff < 0 )
transfer_value(b2, b1, -diff/2);
else
transfer_value(b1, b2, diff/2);
}
return 0;
}
void *randomizer_start(void *t)
{
for(;;) {
int b1 = rand()%15;
int b2 = rand()%15;
int diff = rand()%(buckets[b1]+1);
transfer_value(b1, b2, diff);
}
return 0;
}
int main()
{
int i, total=0;
for(i=0; i < 15; i++) pthread_mutex_init(&bucket_mutex[i], 0);
for(i=0; i < 15; i++) {
buckets[i] = rand() % 100;
total += buckets[i];
printf("%3d ", buckets[i]);
}
printf("= %d\\n", total);
pthread_create(&equalizer, 0, equalizer_start, 0);
pthread_create(&randomizer, 0, randomizer_start, 0);
for(;;) {
sleep(1);
print_buckets();
}
for(i=0; i < 15; i++) pthread_mutex_destroy(bucket_mutex+i);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
void *thread_1(void *arg)
{
pthread_mutex_lock(&mutex);
DPRINTF(stdout,"Thread 1 locked the mutex\\n");
pthread_exit(0);
return 0;
}
void *thread_2(void *arg)
{
int state;
int rc;
pthread_t self = pthread_self();
int policy = SCHED_FIFO;
struct sched_param param;
param.sched_priority = sched_get_priority_min(policy);
rc = pthread_setschedparam(self, policy, ¶m);
if (rc != 0) {
EPRINTF("UNRESOLVED: pthreadsetschedparam: %d %s",
rc, strerror(rc));
exit(UNRESOLVED);
}
if (pthread_mutex_lock(&mutex) != EOWNERDEAD) {
EPRINTF("FAIL:pthread_mutex_lock didn't return EOWNERDEAD");
exit(FAIL);
}
DPRINTF(stdout,"Thread 2 lock the mutex and return EOWNERDEAD \\n");
state = 0;
if (pthread_mutex_setconsistency_np(&mutex,state) == 0) {
pthread_mutex_unlock(&mutex);
if (pthread_mutex_lock(&mutex) != 0) {
EPRINTF("FAIL: The mutex didn't transit to normal "
"state when the calling to "
"pthread_mutex_setconsistency_np is "
"successful in x-mode");
pthread_mutex_unlock(&mutex);
exit(FAIL);
}
else {
DPRINTF(stdout,"PASS: The mutex transitted to "
"normal state when the calling to "
"pthread_mutex_setconsistency_np is "
"successful in x-mode \\n");
pthread_mutex_unlock(&mutex);
}
}
else {
pthread_mutex_unlock(&mutex);
if (pthread_mutex_lock(&mutex) != EOWNERDEAD) {
EPRINTF("FAIL:The mutex should remain as EOWNERDEAD "
"if the calling to "
"pthread_mutex_setconsistency_np fails, "
"unlock the mutex will not change the state "
"in x-mode");
pthread_mutex_unlock(&mutex);
exit(FAIL);
}
else {
DPRINTF(stdout,"UNRESOLVED: The mutex remains in "
"EOWNERDEAD state when the calling to "
"pthread_mutex_setconsistency_np fails "
"(why fails?) in x-mode\\n");
pthread_mutex_unlock(&mutex);
}
}
pthread_exit(0);
return 0;
}
int main()
{
pthread_mutexattr_t attr;
pthread_t threads[2];
pthread_attr_t threadattr;
int rc;
rc = pthread_mutexattr_init(&attr);
if (rc != 0) {
EPRINTF("UNRESOLVED: pthread_mutexattr_init: %d %s",
rc, strerror(rc));
return UNRESOLVED;
}
rc = pthread_mutexattr_setrobust_np(&attr, PTHREAD_MUTEX_ROBUST_NP);
if (rc != 0) {
EPRINTF("UNRESOLVED: pthread_mutexattr_setrobust_np %d %s",
rc, strerror(rc));
return UNRESOLVED;
}
rc = pthread_mutex_init(&mutex, &attr);
if (rc != 0) {
EPRINTF("UNRESOLVED: pthread_mutex_init %d %s",
rc, strerror(rc));
return UNRESOLVED;
}
rc = pthread_attr_init(&threadattr);
if (rc != 0) {
EPRINTF("UNRESOLVED: pthread_attr_init %d %s",
rc, strerror(rc));
return UNRESOLVED;
}
rc = pthread_create(&threads[0], &threadattr, (void *)thread_1, 0);
if (rc != 0) {
EPRINTF("UNRESOLVED: pthread_create %d %s",
rc, strerror(rc));
return UNRESOLVED;
}
pthread_join(threads[0], 0);
DPRINTF(stdout,"Thread 1 exit without unlock the mutex...\\n");
rc = pthread_create(&threads[1], &threadattr, (void *)thread_2, 0);
if (rc != 0) {
EPRINTF("UNRESOLVED: pthread_create %d %s",
rc, strerror(rc));
return UNRESOLVED;
}
pthread_join(threads[1], 0);
DPRINTF(stdout,"Thread 2 exit...\\n");
DPRINTF(stdout,"PASS: Test PASSED\\n");
return PASS;
}
| 0
|
#include <pthread.h>
int sum=0;
int numArray[6];
pthread_mutex_t sum_mutex;
void *thread_sum(void *tid)
{
int start;
int *mytid;
int end;
int mysum=0;
mytid = (int *) tid;
start = (*mytid * 6 / 2);
end = start + 6 / 2;
int i;
for (i=start; i < end ; i++) {
mysum = mysum + numArray[i];
}
pthread_mutex_lock (&sum_mutex);
sum = sum + mysum;
pthread_mutex_unlock (&sum_mutex);
pthread_exit(0);
}
void main(int argc, char *argv[])
{
int i;
for(i=0; i<argc; i++){
numArray[i] = atoi(argv[i]);
}
pthread_t threads[2];
pthread_attr_t attr;
pthread_mutex_init(&sum_mutex, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
int tids[2];
for (i=0; i<2; i++) {
tids[i] = i;
pthread_create(&threads[i], &attr, thread_sum, (void *) &tids[i]);
}
for (i=0; i<2; i++) {
pthread_join(threads[i], 0);
}
printf ("%d", sum);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&sum_mutex);
pthread_exit (0);
}
| 1
|
#include <pthread.h>
unsigned char *src = 0, *dest = 0;
int pthread_count;
int rate = 0, rate1 = 0;
struct stat buf;
pthread_mutex_t rate_mutex = PTHREAD_MUTEX_INITIALIZER;
void *mycp_pthread(void *arg)
{
int i, a = 0, b = 0;
int count = *(int *)arg;
a = ((int)buf.st_size/pthread_count)*count;
b = a + (int)buf.st_size/pthread_count;
for (i = a; i < b; i++)
{
memcpy(dest + i, src + i, 1);
pthread_mutex_lock(&rate_mutex);
rate++;
pthread_mutex_unlock(&rate_mutex);
}
return (void *)1;
}
void *mycp_rate(void *arg)
{
int i;
for (i = ((int)buf.st_size/pthread_count)*(*(int *)arg); i < (int)buf.st_size; i++)
{
memcpy(dest + i, src + i, 1);
pthread_mutex_lock(&rate_mutex);
rate++;
if (rate < (int)buf.st_size)
{
if ((rate*100/(int)buf.st_size) > rate1)
{
printf("rate = %d\\n",rate);
printf("buf.st_size = %d\\n",(int)buf.st_size);
rate1 = rate*100/(int)buf.st_size;
printf("%d%%\\n",rate1);
}
}
if (rate == (int)buf.st_size)
{
printf("100%%\\n");
printf("rate = %d\\n",rate);
printf("buf.st_size = %d\\n",(int)buf.st_size);
pthread_mutex_unlock(&rate_mutex);
return (void *)1;
}
pthread_mutex_unlock(&rate_mutex);
}
return (void *)1;
}
int main(int argc, const char *argv[])
{
int fd1, fd2;
int i = 0, k = 0;
void *tret = 0;
int error;
pthread_count = atoi(argv[3]);
pthread_t tid[pthread_count + 1];
system("clear");
if (argc != 4)
{
printf("input wrong !\\n");
printf("format is:%s srcfile destfile pthread_number\\n",argv[0]);
exit(1);
}
fd1 = open(argv[1], O_RDONLY);
if (fd1 < 0)
{
perror("open");
exit(1);
}
fd2 = open(argv[2], O_RDWR | O_CREAT, 00776);
if (fd2 < 0)
{
perror("open");
exit(1);
}
stat(argv[1], &buf);
src = mmap(0, (int)buf.st_size, PROT_READ, MAP_SHARED, fd1, 0);
if (src == MAP_FAILED)
{
perror("map");
exit(1);
}
lseek(fd2, buf.st_size-1, 0);
write(fd2, "0", 1);
dest = mmap(0, (int)buf.st_size, PROT_WRITE | PROT_READ, MAP_SHARED, fd2, 0);
if (dest == MAP_FAILED)
{
perror("map");
exit(1);
}
for (k = 0; k < pthread_count-1; k++)
{
error = pthread_create(&tid[k], 0, mycp_pthread, &k);
if (error != 0)
{
fprintf(stderr, "can't create thread:%s",strerror(error));
exit(1);
}
}
for (i = ((int)buf.st_size/pthread_count)*k; i < (int)buf.st_size; i++)
{
memcpy(dest + i, src + i, 1);
pthread_mutex_lock(&rate_mutex);
rate++;
if (rate < (int)buf.st_size)
{
if ((rate*100/(int)buf.st_size) > rate1)
{
rate1 = rate*100/(int)buf.st_size;
printf("%d%%\\n",rate1);
}
}
pthread_mutex_unlock(&rate_mutex);
}
while (rate != (int)buf.st_size)
{
if ((rate*100/(int)buf.st_size) > rate1)
{
rate1 = rate*100/(int)buf.st_size;
printf("%d%%\\n",rate1);
}
}
printf("100%%\\n");
printf("rate = %d\\n",rate);
printf("buf.st_size = %d\\n",(int)buf.st_size);
for (i = 0; i < pthread_count-1; i++)
{
error = pthread_join(tid[i], &tret);
if (error != 0)
{
fprintf(stderr, "can't pthread_join thread:%s",strerror(error));
exit(1);
}
}
munmap(src, (int)buf.st_size);
munmap(dest, (int)buf.st_size);
close(fd1);
close(fd2);
printf("File copy finished\\n\\n");
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int i, n, last = -1;
int *ids;
int token;
void *Number( void * );
int main( int argc, char **argv ) {
if ( argc != 2 ) {
printf( "Wrong numbers of parameters. Add n.\\n" );
return -1;
}
n = atoi( argv[ 1 ] );
int i = 0;
if ( !( ids = ( int * ) malloc( sizeof( int ) * n ) ) ) {
printf( "Error of allocating memory\\n" );
return -1;
}
pthread_t tids[ n ];
for ( i = 0; i < n; i++ ) {
ids[ i ] = i;
if ( pthread_create( &tids[ i ], 0, Number, ( void * ) &ids[ i ] ) ) {
printf( "Error of creating thread: %s\\n", strerror( errno ) );
return -1;
}
}
for ( i = 0; i < n; i++ ) {
if ( pthread_join( tids[ i ], 0 ) ) {
printf( "Error of joining thread: %s\\n", strerror( errno ) );
exit( -1 );
}
}
return 0;
}
void *Number( void *arg ) {
int id = *( int * ) arg;
if ( id == 0 ) {
pthread_mutex_lock( &mutex );
last = id;
token = 123;
pthread_mutex_unlock( &mutex );
} else {
while (last < id - 1) {
continue;
}
printf("Thread %d received token %d from thread %d\\n",
id, token, id - 1);
pthread_mutex_lock( &mutex );
last = id;
token += 1;
pthread_mutex_unlock( &mutex );
}
if ( id == 0 ) {
while ( last < n - 1 ) {
continue;
}
printf("Thread %d received token %d from thread %d\\n",
id, token, n - 1 );
}
pthread_exit( 0 );
}
| 1
|
#include <pthread.h>
static char *time_fmt = "%04d%02d%02d-%02d:%02d:%02d-%06dus";
static char *file_str = FILE_STR;
static pthread_mutex_t lock;
void get_time_str(char time_str[])
{
time_t t;
time(&t);
struct tm *tp = localtime(&t);
struct timeval tv;
gettimeofday(&tv, 0);
sprintf(time_str, time_fmt, tp->tm_year + 1900, tp->tm_mon + 1, tp->tm_mday,
tp->tm_hour, tp->tm_min, tp->tm_sec, tv.tv_usec);
}
void function_status(const char *func)
{
pthread_mutex_lock(&lock);
FILE *fp = fopen(file_str, "a");
if (0 == fp) {
pthread_mutex_unlock(&lock);
return;
}
char time_str[30];
get_time_str(time_str);
pid_t pid = getpid();
pthread_t tid = pthread_self();
fprintf(fp, "%s, ", time_str);
fprintf(fp, "PID:%05u, ", pid);
fprintf(fp, "TID:%010lu, ", tid);
fprintf(fp, "FUNC:%s", func);
fprintf(fp, "\\n");
fclose(fp);
pthread_mutex_unlock(&lock);
}
| 0
|
#include <pthread.h>
{
void *(*process) (void *arg);
void *arg;
struct worker *next;
} CThread_worker;
{
pthread_mutex_t queue_lock;
pthread_cond_t queue_ready;
CThread_worker *queue_head;
int shutdown;
pthread_t *threadid;
int max_thread_num;
int cur_queue_size;
} CThread_pool;
int pool_add_worker (void *(*process) (void *arg), void *arg);
void *thread_routine (void *arg);
static CThread_pool *pool = 0;
void
pool_init (int max_thread_num)
{
pool = (CThread_pool *) malloc (sizeof (CThread_pool));
pthread_mutex_init (&(pool->queue_lock), 0);
pthread_cond_init (&(pool->queue_ready), 0);
pool->queue_head = 0;
pool->max_thread_num = max_thread_num;
pool->cur_queue_size = 0;
pool->shutdown = 0;
pool->threadid =
(pthread_t *) malloc (max_thread_num * sizeof (pthread_t));
int i = 0;
for (i = 0; i < max_thread_num; i++)
{
pthread_create (&(pool->threadid[i]), 0, thread_routine,
0);
}
}
int
pool_add_worker (void *(*process) (void *arg), void *arg)
{
CThread_worker *newworker =
(CThread_worker *) malloc (sizeof (CThread_worker));
newworker->process = process;
newworker->arg = arg;
newworker->next = 0;
pthread_mutex_lock (&(pool->queue_lock));
CThread_worker *member = pool->queue_head;
if (member != 0)
{
while (member->next != 0)
member = member->next;
member->next = newworker;
}
else
{
pool->queue_head = newworker;
}
assert (pool->queue_head != 0);
pool->cur_queue_size++;
pthread_mutex_unlock (&(pool->queue_lock));
pthread_cond_signal (&(pool->queue_ready));
return 0;
}
int
pool_destroy ()
{
if (pool->shutdown)
return -1;
pool->shutdown = 1;
pthread_cond_broadcast (&(pool->queue_ready));
int i;
for (i = 0; i < pool->max_thread_num; i++)
pthread_join (pool->threadid[i], 0);
free (pool->threadid);
CThread_worker *head = 0;
while (pool->queue_head != 0)
{
head = pool->queue_head;
pool->queue_head = pool->queue_head->next;
free (head);
}
pthread_mutex_destroy(&(pool->queue_lock));
pthread_cond_destroy(&(pool->queue_ready));
free (pool);
pool=0;
return 0;
}
void *
thread_routine (void *arg)
{
printf ("starting thread 0x%x\\n", pthread_self ());
while (1)
{
pthread_mutex_lock (&(pool->queue_lock));
while (pool->cur_queue_size == 0 && !pool->shutdown)
{
printf ("thread 0x%x is waiting\\n", pthread_self ());
pthread_cond_wait (&(pool->queue_ready), &(pool->queue_lock));
}
if (pool->shutdown)
{
pthread_mutex_unlock (&(pool->queue_lock));
printf ("thread 0x%x will exit\\n", pthread_self ());
pthread_exit (0);
}
printf ("thread 0x%x is starting to work\\n", pthread_self ());
assert (pool->cur_queue_size != 0);
assert (pool->queue_head != 0);
pool->cur_queue_size--;
CThread_worker *worker = pool->queue_head;
pool->queue_head = worker->next;
pthread_mutex_unlock (&(pool->queue_lock));
(*(worker->process)) (worker->arg);
free (worker);
worker = 0;
}
pthread_exit (0);
}
void *
myprocess (void *arg)
{
printf ("threadid is 0x%x, working on task %d\\n", pthread_self (),*(int *) arg);
sleep (1);
return 0;
}
int
main (int argc, char **argv)
{
pool_init (3);
int *workingnum = (int *) malloc (sizeof (int) * 10);
int i;
for (i = 0; i < 10; i++)
{
workingnum[i] = i;
pool_add_worker (myprocess, &workingnum[i]);
}
sleep (50);
pool_destroy ();
free (workingnum);
return 0;
}
| 1
|
#include <pthread.h>
int val;
struct node * next;
} node_t;
int debug = 0;
int count;
int buffer = 0;
pthread_mutex_t mutex;
pthread_cond_t condc, condp;
node_t * head = 0;
void push(int val) {
node_t * new_node;
new_node = malloc(sizeof(node_t));
new_node->val = val;
new_node->next = head;
head = new_node;
}
void print_list() {
node_t * current = head;
while (current != 0) {
printf("%d\\n", current->val);
current = current->next;
}
}
void *store_value(void *num) {
int j;
for (j = 0; j < count; j++) {
pthread_mutex_lock(&mutex);
while (buffer == 0)
pthread_cond_wait(&condc, &mutex);
int val = *(int *)num;
push(val);
if (debug)
printf("Value %i added to linked list\\n", val);
buffer = 0;
pthread_cond_signal(&condp);
pthread_mutex_unlock(&mutex);
}
return 0;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage Error: %s requires 1 argument\\n", argv[0]);
exit(1);
} else {
count = atoi(argv[1]);
if (count < 0 || count > 32) {
printf("Usage Error: %s requires a count between 0 and %i\\n", argv[0], 32);
exit(1);
}
int array[count];
int i;
srand (time(0));
pthread_t store_thread;
int val;
pthread_cond_init(&condc, 0);
pthread_cond_init(&condp, 0);
if(pthread_create(&store_thread, 0, store_value, &val)) {
fprintf(stderr, "Error creating thread\\n");
return 1;
}
for (i = 0; i < count; i++) {
pthread_mutex_lock(&mutex);
while (buffer != 0)
pthread_cond_wait(&condp, &mutex);
val = rand() % 32;
buffer = 1;
if (debug)
printf("Number %i generated\\n", val);
pthread_cond_signal(&condc);
pthread_mutex_unlock(&mutex);
}
if(pthread_join(store_thread, 0)) {
fprintf(stderr, "Error joining thread\\n");
return 2;
}
print_list();
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
}
}
| 0
|
#include <pthread.h>
sem_t semaphore;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int queue[200];
int queueLength;
void * producer(void * param)
{
int i;
for( i = 0; i < 250; i++)
{
pthread_mutex_lock(&mutex);
queue[queueLength++] = i;
pthread_mutex_unlock(&mutex);
printf("Proceducer : %d ", i);
sem_post(&semaphore);
}
printf("End of producer \\n");
}
void *consumer(void * param)
{
int i;
for(i = 0; i < 250; i++)
{
int item;
if(queueLength == 0)
{
printf("Consumer wait... \\n");
sem_wait(&semaphore);
}
pthread_mutex_lock(&mutex);
item = queue[queueLength--];
pthread_mutex_unlock(&mutex);
printf("Received : %i ", item);
}
printf("End of consumer \\n");
}
int main()
{
pthread_t threads[2];
sem_init(&semaphore, 0, 0);
pthread_create(&threads[0], 0, producer, 0);
pthread_create(&threads[1], 0, consumer, 0);
pthread_join(threads[0], 0);
pthread_join(threads[1], 0);
sem_destroy(&semaphore);
}
| 1
|
#include <pthread.h>
struct thread_data{
int thread_id;
int *balance;
};
pthread_mutex_t myMutex;
void *PrintHello(void *threadarg)
{
long int taskid;
struct thread_data *my_data;
int *balance, save;
my_data = (struct thread_data *) threadarg;
taskid = my_data->thread_id;
balance = my_data->balance;
sleep(1);
pthread_mutex_lock(&myMutex);
if (taskid % 2 == 0) *balance += 1;
else *balance -= 1;
pthread_mutex_unlock(&myMutex);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int arg,i,j,k,m;
pthread_t threads[1000];
struct thread_data thread_data_array[1000];
int rc;
long t;
int account = 1000;
if (pthread_mutex_init(&myMutex, 0)) {
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
printf("\\n Hello World! It's me, MAIN!\\n");
for (t = 0; t < 1000; t++) {
thread_data_array[t].thread_id = t+1;
thread_data_array[t].balance = &account;
rc = pthread_create(&threads[t], 0, PrintHello,
(void*) &thread_data_array[t]);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
for (i = 0; i < 1000; i++) {
if (pthread_join(threads[i],0)){ exit(19);
}
}
printf("\\n MAIN --> balance = %d\\n", account);
pthread_mutex_destroy(&myMutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t g_GpioMutex;
int g_StartupInitGpioMutex = 1;
void Gpio_InitMutex(void )
{
StdThread_InitMutex(&g_GpioMutex);
}
void Gpio_UnlockMutex_Accident(void)
{
int ret;
ret = pthread_mutex_unlock(&g_GpioMutex);
}
int Gpio_SetValue(int gpio, int value)
{
int fd = -1;
int res;
int len = 0;
char str[10];
if(gpio >= IO_TOTAL&& gpio < GPIO0_C0)
return -1;
if(g_StartupInitGpioMutex == 1)
{
g_StartupInitGpioMutex = 0;
Gpio_InitMutex( );
}
pthread_mutex_lock(&g_GpioMutex);
fd = open(GPIO_ADDR, O_RDWR);
if(fd == -1)
{
return;
}
if(value == SET_LOW)
len = sprintf(str, "s:%c%c", gpio+'A', OUT_PULL_LOW);
else
len = sprintf(str, "s:%c%c", gpio+'A', OUT_PULL_HIGH);
res = write(fd, str, len+1);
if(res < 0)
{
LOGE("Gpio_SetValue ioctl gpio=%d errorno=%d", gpio, errno);
}
close(fd);
pthread_mutex_unlock(&g_GpioMutex);
return 0;
}
int Gpio_GetValue(int gpio)
{
int fd = -1;
int res;
int len = 100;
int value =0;
char str[100];
if(gpio >= IO_TOTAL&& gpio < GPIO0_C0)
return -1;
if(g_StartupInitGpioMutex == 1)
{
g_StartupInitGpioMutex = 0;
Gpio_InitMutex( );
}
pthread_mutex_lock(&g_GpioMutex);
fd = open(GPIO_ADDR, O_RDWR);
if(fd == -1)
{
LOGE("Gpio_SetValue open gpio=%d errorno=%d", gpio, errno);
}
len = sprintf(str, "s:%c%c", gpio+'A', INPUT);
res = write(fd, str, len+1);
if(res < 0)
{
LOGE("Gpio_SetValue ioctl gpio=%d errorno=%d", gpio, errno);
}
len = read(fd, str, 100);
if(len < 0 || len > 50)
{
LOGE("Gpio_SetValue ioctl gpio=%d errorno=%d", gpio, errno);
}
close(fd);
pthread_mutex_unlock(&g_GpioMutex);
if(str[gpio*2+1] == '0')
value = LOW;
else if(str[gpio*2+1] == '1')
value = HIGH;
return value;
}
| 1
|
#include <pthread.h>
int g_itemnum;
int g_buff[(100000)];
struct
{
pthread_mutex_t mutex;
int nindex;
int nvalue;
} shared = { PTHREAD_MUTEX_INITIALIZER };
struct
{
pthread_mutex_t mutex;
pthread_cond_t cond;
int ready;
} ready = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER };
void* producer(void*);
void* consumer(void*);
int main(int argc, char **argv)
{
int i;
int threadnum, threadcount[(10)];
pthread_t tid_producer[(10)], tid_consumer;
if (3 != argc) {
printf("usage: %s <item_num> <thread_num>\\n", argv[0]);
}
g_itemnum = ((atoi(argv[1])) > ((100000)) ? ((100000)) : (atoi(argv[1])));
threadnum = ((atoi(argv[2])) > ((10)) ? ((10)) : (atoi(argv[2])));
printf("item = %d, thread = %d\\n", g_itemnum, threadnum);
pthread_setconcurrency(threadnum + 1);
for (i = 0; i < threadnum; ++i) {
threadcount[i] = 0;
if (0 != pthread_create(&tid_producer[i], 0, producer, (void*)&threadcount[i])) {
printf("pthread_create error producer %d\\n", i);
exit(1);
}
printf("producer: thread[%lu] created, threadcount[%d] = %d\\n", tid_producer[i], i, threadcount[i]);
}
if (0 != pthread_create(&tid_consumer, 0, consumer, 0)) {
printf("pthread_create error consumer\\n");
}
printf("consumer: thread[%lu] created\\n", tid_consumer);
for (i = 0; i < threadnum; ++i) {
if (0 != pthread_join(tid_producer[i], 0)) {
printf("pthread_join error producer %d\\n", i);
exit(1);
}
printf("producer: thread[%lu] done, threadcount[%d] = %d\\n", tid_producer[i], i, threadcount[i]);
}
if (0 != pthread_join(tid_consumer, 0)) {
printf("pthread_join error consumer\\n");
}
printf("consumer: thread[%lu] done\\n", tid_consumer);
exit(0);
}
void* producer(void *arg)
{
for (;;) {
pthread_mutex_lock(&shared.mutex);
if (shared.nindex >= g_itemnum) {
pthread_mutex_unlock(&shared.mutex);
return 0;
}
g_buff[shared.nindex] = shared.nvalue;
shared.nindex++;
shared.nvalue++;
pthread_mutex_unlock(&shared.mutex);
pthread_mutex_lock(&ready.mutex);
if (0 == ready.ready) {
pthread_cond_signal(&ready.cond);
}
ready.ready++;
pthread_mutex_unlock(&ready.mutex);
*((int*)arg) += 1;
}
return 0;
}
void* consumer(void *arg)
{
int i;
for (i = 0; i < g_itemnum; ++i) {
pthread_mutex_lock(&ready.mutex);
while (0 == ready.ready) {
pthread_cond_wait(&ready.cond, &ready.mutex);
}
ready.ready--;
pthread_mutex_unlock(&ready.mutex);
if (g_buff[i] != i) {
printf("error: buff[%d] = %d\\n", i, g_buff[i]);
}
}
return 0;
}
| 0
|
#include <pthread.h>
struct data {
long counter[65536];
};
const int SIZE = sizeof(struct data);
static pthread_mutex_t mutex_arr[65536];
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];
unsigned short *sarr = (unsigned short *) buffer;
size_t pos = 0;
while (1) {
ssize_t size_read = read(fd, buffer+pos, 16384 -pos);
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);
}
if (size_read == 0 && pos > 0) {
buffer[pos] = (char) 0;
pos++;
}
size_t byte_size = size_read + pos;
size_t short_size = byte_size / 2;
pos = byte_size % 2;
for (unsigned int i = 0; i < short_size; i++) {
unsigned short s = sarr[i];
time_t t0 = time(0);
retcode = pthread_mutex_lock(&(mutex_arr[s]));
time_t dt = time(0) - t0;
total_mutex_wait += dt;
handle_error(retcode, "error while getting mutex", 1);
long *counter = data.counter;
counter[s]++;
retcode = pthread_mutex_unlock(& (mutex_arr[s]));
handle_error(retcode, "error while releasing mutex", 1);
}
if (size_read == 0) {
break;
}
if (pos > 0) {
buffer[0] = buffer[byte_size - 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 < 65536; 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");
}
printf("%6d: %10ld ", (int) (unsigned short) 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 < 65536; i++) {
data.counter[i] = 0L;
}
for (i = 0; i < 65536; 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 < 65536; 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 candado;
pthread_cond_t producido;
pthread_cond_t consumido;
char buffer[3];
int contador;
int entrada;
int salida;
int posFrase;
int posLlave;
int producidos;
int consumidos;
FILE *file;
FILE *cesar;
char *llave;
char dato;
static char *archivo;
void getElement(void);
void putElement(void);
void init();
int readChar(FILE *file);
void writeChar(FILE *Cesar, char dato);
int getTamFile(FILE *file);
char * substract(char *s);
char * substract(char *s) {
int len = strlen(s);
char buf[len-1];
int i;
for(i = 0; i < len-6; i++){
buf[i] = s[i];
}
buf[i] = 0;
return strdup(buf);
}
void writeChar(FILE *Cesar, char dato) {
fprintf(Cesar, "%c", dato);
}
int readChar(FILE *file) {
return fgetc(file);
}
int getTamFile(FILE *file) {
fseek(file, 0, 2);
int aux = ((ftell(file)));
fseek(file, 0, 0);
return aux;
}
void init() {
printf("Inicializando Variables \\n");
entrada = 0;
salida = 0;
contador = 0;
posLlave = 0;
consumidos = getTamFile(file);
producidos = getTamFile(file);
pthread_mutex_init(&candado, 0);
pthread_cond_init(&producido, 0);
pthread_cond_init(&consumido, 0);
}
void getElement(void) {
while (consumidos != 0) {
pthread_mutex_lock(&candado);
while (contador == 0) {
pthread_cond_wait(&producido, &candado);
}
if (consumidos > 0) {
char dato = buffer[salida];
salida = (salida + 1) % 3;
contador = contador - 1;
consumidos = consumidos > 0 ? (consumidos - 1) : 0;
writeChar(cesar, dato);
}
pthread_mutex_unlock(&candado);
pthread_cond_signal(&consumido);
}
}
void putElement(void) {
while (!feof(file)) {
pthread_mutex_lock(&candado);
while (contador == 3) {
pthread_cond_wait(&consumido, &candado);
}
if (!feof(file)) {
int val = readChar(file);
char dato = val - llave[posLlave] == 0 ? val : val - llave[posLlave];
buffer[entrada] = dato;
posLlave = (posLlave + 1) % strlen(llave);
producidos = producidos - 1;
entrada = (entrada + 1) % 3;
contador = contador + 1;
}
pthread_mutex_unlock(&candado);
pthread_cond_signal(&producido);
}
}
int main(int argc, char **argv) {
archivo = argv[1];
file = fopen(archivo, "rb");
if (!file) {
printf("El archivo no existe..");
} else {
archivo = substract(archivo);
cesar = fopen(archivo, "w");
init();
printf("Inicio del programa \\n");
printf("Digite la llave para el cifrado del archivo: ");
llave = (char*) malloc(sizeof (char*));
scanf("%[^\\n]", llave);
fflush(stdin);
fflush(stdout);
int numHilos;
printf("Digite el numero de hilos: ");
scanf("%i", &numHilos);
fflush(stdin);
fflush(stdout);
pthread_t thread[numHilos];
for (int i = 1; i <= numHilos; i++) {
if (i % 2 == 0) {
pthread_create(&thread[i], 0, (void *) &getElement, 0);
} else {
pthread_create(&thread[i], 0, (void *) &putElement, 0);
}
}
for (int i = 1; i <= numHilos; i++) {
pthread_join(thread[i], 0);
}
pthread_mutex_destroy(&candado);
pthread_cond_destroy(&producido);
pthread_cond_destroy(&consumido);
free(llave);
fclose(file);
fclose(cesar);
printf("\\n<=Archivo Descodificado=>");
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock;
int count;
int next_index;
void * chunk(void * thread_id){
int id=*(int *) thread_id;
int counter=0;
int i, start=0;
while(1){
pthread_mutex_lock(&lock);
start=next_index;
next_index+=5000;
pthread_mutex_unlock(&lock);
if((start+5000)>(100000*8)){
break;
}
for(i=start;i<start+5000;i++){
if(is_prime(i))
counter++;
}
}
pthread_mutex_lock(&lock);
count+=counter;
pthread_mutex_unlock(&lock);
}
int main(){
pthread_t threads[8];
int i;
int thread_num[8];
int time;
next_index=0;
count=0;
time=get_time_sec();
for(i=0;i<8;i++){
thread_num[i]=i;
pthread_create(&threads[i],0,chunk,(void*)&thread_num[i]);
}
for(i=0;i<8;i++){
pthread_join(threads[i],0);
}
printf("Number of primes=%d, took %fs\\n",count, get_time_sec()-time);
return 0;
}
| 1
|
#include <pthread.h>
void *myfunc1(void *ptr);
void *myfunc2(void *ptr);
int A[100];
pthread_mutex_t lock;
int main() {
printf("Starting program!\\n\\n\\n");
pthread_t thread1, thread2;
void **retval;
char *msg1 = "First thread";
char* msg2 = "Second thread";
pthread_create(&thread1, 0, myfunc1, msg1);
pthread_create(&thread2, 0, myfunc2, msg2);
pthread_join(thread1, retval);
pthread_join(thread2, retval);
printf("Ending program!\\n");
return 0;
}
void* myfunc1( void *ptr) {
char *msg1 = (char*)ptr;
printf("Thread 1 %s\\n", msg1);
int i;
pthread_mutex_lock(&lock);
for (i = 0; i < 100; i++) {
printf("X");
A[i] = i;
}
pthread_mutex_unlock(&lock);
}
void* myfunc2( void *ptr) {
char *msg2 = (char*)ptr;
printf("Thread 1, %s\\n", msg2);
int i;
pthread_mutex_lock(&lock);
for (i = 0; i < 100; i++) {
printf("%d ", A[i]);
}
pthread_mutex_unlock(&lock);
}
| 0
|
#include <pthread.h>
struct entry {
int key;
int value;
struct entry *next;
};
struct entry *table[5];
int keys[100000];
int nthread = 1;
volatile int done;
pthread_mutex_t mutex;
double
now()
{
struct timeval tv;
gettimeofday(&tv, 0);
return tv.tv_sec + tv.tv_usec / 1000000.0;
}
static void
print(void)
{
int i;
struct entry *e;
for (i = 0; i < 5; i++) {
printf("%d: ", i);
for (e = table[i]; e != 0; e = e->next) {
printf("%d ", e->key);
}
printf("\\n");
}
}
static void
insert(int key, int value, struct entry **p, struct entry *n)
{
struct entry *e = malloc(sizeof(struct entry));
e->key = key;
e->value = value;
e->next = n;
*p = e;
}
static
void put(int key, int value)
{
struct entry *n, **p;
pthread_mutex_lock(&mutex);
for (p = &table[key%5], n = table[key % 5]; n != 0; p = &n->next, n = n->next) {
if (n->key > key) {
insert(key, value, p, n);
goto done;
}
}
insert(key, value, p, n);
done:
pthread_mutex_unlock(&mutex);
return;
}
static struct entry*
get(int key)
{
struct entry *e = 0;
for (e = table[key % 5]; e != 0; e = e->next) {
if (e->key == key) break;
}
return e;
}
static void *
thread(void *xa)
{
long n = (long) xa;
int i;
int b = 100000/nthread;
int k = 0;
double t1, t0;
t0 = now();
for (i = 0; i < b; i++) {
put(keys[b*n + i], n);
}
t1 = now();
printf("%ld: put time = %f\\n", n, t1-t0);
__sync_fetch_and_add(&done, 1);
while (done < nthread) ;
t0 = now();
for (i = 0; i < 100000; i++) {
struct entry *e = get(keys[i]);
if (e == 0) k++;
}
t1 = now();
printf("%ld: lookup time = %f\\n", n, t1-t0);
printf("%ld: %d keys missing\\n", n, k);
}
int
main(int argc, char *argv[])
{
pthread_t *tha;
void *value;
long i;
double t1, t0;
if (argc < 2) {
fprintf(stderr, "%s: %s nthread\\n", argv[0], argv[0]);
exit(-1);
}
nthread = atoi(argv[1]);
pthread_mutex_init(&mutex, 0);
tha = malloc(sizeof(pthread_t) * nthread);
srandom(0);
assert(100000 % nthread == 0);
for (i = 0; i < 100000; i++) {
keys[i] = random();
}
t0 = now();
for(i = 0; i < nthread; i++) {
assert(pthread_create(&tha[i], 0, thread, (void *) i) == 0);
}
for(i = 0; i < nthread; i++) {
assert(pthread_join(tha[i], &value) == 0);
}
t1 = now();
printf("completion time = %f\\n", t1-t0);
}
| 1
|
#include <pthread.h>
pthread_rwlock_t progress_rwlock = PTHREAD_RWLOCK_INITIALIZER;
static pthread_mutex_t stdout_mutex = PTHREAD_MUTEX_INITIALIZER;
void generateRequestHead(const struct DownloadInfo *info, char *head) {
sprintf(head, "GET %s HTTP/1.1\\r\\n", info->uri);
sprintf(head, "%sAccept: */*\\r\\n", head);
sprintf(head, "%sAccept-Encoding: identity\\r\\n", head);
sprintf(head, "%sHost: %s\\r\\n", head, info->host);
sprintf(head, "%sRange: bytes=%lu-%lu\\r\\n", head, info->start, info->end);
sprintf(head, "%sConnection: Keep-Alive\\r\\n", head);
sprintf(head, "%s\\r\\n", head);
}
void pthread_println(const char *str) {
pthread_mutex_lock(&stdout_mutex);
Rio_writen(STDOUT_FILENO, str, strlen(str));
char a[2] = "\\n";
Rio_writen(STDOUT_FILENO, a, strlen(a));
pthread_mutex_unlock(&stdout_mutex);
}
void pthread_write(struct DownloadInfo *info, const char *response, size_t n, __off_t *pos) {
pwrite(info->fd, response, n, *pos);
(*pos) += n;
pthread_rwlock_wrlock(&progress_rwlock);
(*info->progress) += n;
pthread_rwlock_unlock(&progress_rwlock);
}
void printAddress(const struct addrinfo *ailist) {
char abuf[INET_ADDRSTRLEN];
struct sockaddr_in *sinp = (struct sockaddr_in *) ailist->ai_addr;
const char *addr = inet_ntop(AF_INET, &sinp->sin_addr, abuf, INET_ADDRSTRLEN);
pthread_println(addr);
}
void showInTerminal(const struct DownloadInfo *downloadInfo) {
size_t progressTemp = 0;
while (progressTemp < downloadInfo->length) {
int barWidth = 70;
printf("[");
int pos = 1.0 * barWidth * progressTemp / downloadInfo->length;
for (int i = 0; i < barWidth; ++i) {
if (i < pos) printf("=");
else if (i == pos) printf(">");
else printf(" ");
}
printf("]%d%%\\r", (int) (1.0 * progressTemp / downloadInfo->length * 100));
fflush(stdout);
sleep(1);
pthread_rwlock_rdlock(&progress_rwlock);
progressTemp = *(downloadInfo->progress);
pthread_rwlock_unlock(&progress_rwlock);
}
printf("\\n");
}
void setLength(struct DownloadInfo *downloadInfo) {
char *head = (char *) Malloc(MAX_HEAD_SIZE);
sprintf(head, "HEAD %s HTTP/1.1\\r\\n", downloadInfo->uri);
sprintf(head, "%sAccept: */*\\r\\n", head);
sprintf(head, "%sAccept-Encoding: identity\\r\\n", head);
sprintf(head, "%sHost: %s\\r\\n", head, downloadInfo->host);
sprintf(head, "%sConnection: Keep-Alive\\r\\n", head);
sprintf(head, "%s\\r\\n", head);
int sockfd = Socket(AF_INET, SOCK_STREAM, 0);
Connect(sockfd, downloadInfo->sockaddr, sizeof(struct sockaddr));
Rio_writen(sockfd, head, strlen(head));
char newBuf[MAX_HEAD_SIZE];
Rio_readn(sockfd, newBuf, sizeof(newBuf));
pthread_println("get length over");
char *s = strstr(newBuf, "Content-Length");
sscanf(s + sizeof("Content-Length:"), " %lu", &downloadInfo->length);
}
| 0
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t wait = PTHREAD_COND_INITIALIZER;
void*
thr_fn(void* arg)
{
int err, signo;
for(;;)
{
err = sigwait(&mask, &signo);
if(err != 0)
printf("sigwait failed");
switch(signo)
{
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&wait);
return 0;
default:
printf("unexpected singal :%d\\n",signo);
exit(1);
}
}
}
void
sig_int_handler()
{
printf("u r in sig_int_handler\\n");
}
void
sig_quit_handler()
{
printf("u r in sig_quit_handler\\n");
}
int main(int argc, char* argv[])
{
int err;
sigset_t oldmask;
pthread_t tid;
signal(SIGINT, sig_int_handler);
signal(SIGQUIT, sig_quit_handler);
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0)
printf("SIG_BLOCK err");
err = pthread_create(&tid, 0, thr_fn, 0);
if(err != 0)
printf("cannot create thread");
pthread_mutex_lock(&lock);
while(quitflag == 0)
pthread_cond_wait(&wait, &lock);
pthread_mutex_unlock(&lock);
quitflag = 0;
if(sigprocmask(SIG_SETMASK, &oldmask, 0) < 0)
printf("SIG_SETMASK err");
exit(0);
}
| 1
|
#include <pthread.h>
struct {
int max_steps;
int nb_steps_done;
int position;
pthread_mutex_t lock;
} _global_data;
void
progress_init(int max_steps)
{
int i;
int err;
if (max_steps == -1) {
_global_data.max_steps = -1;
return;
}
err = pthread_mutex_init(&_global_data.lock, 0);
if (err) {
fprintf(stderr, "pthread_mutex_init failed [%d]\\n",
err);
return;
}
_global_data.max_steps = max_steps;
_global_data.nb_steps_done = 0;
_global_data.position = 0;
printf("[");
for (i=0; i<40; i++) {
printf (" ");
}
printf("]\\r[");
fflush(stdout);
}
void
progress_destroy()
{
if (_global_data.max_steps == -1) {
return;
}
pthread_mutex_destroy(&_global_data.lock);
printf("\\n");
_global_data.max_steps = -1;
}
void
progress_step()
{
int position_goal;
if (_global_data.max_steps == -1) {
return;
}
pthread_mutex_lock(&_global_data.lock);
_global_data.nb_steps_done++;
position_goal = _global_data.nb_steps_done*40/_global_data.max_steps;
while (_global_data.position < position_goal) {
printf(".");
_global_data.position++;
fflush(stdout);
}
pthread_mutex_unlock(&_global_data.lock);
}
| 0
|
#include <pthread.h>
int row1;
int col1;
int row2, col2, currentRow, **InMat1, **InMat2, **ResMat;
int numberOfThreads;
pthread_t * threads;
pthread_mutex_t mutex_Row = PTHREAD_MUTEX_INITIALIZER;
void * doMyWork(int thread_id)
{
int i, j, myRow;
while(1) {
printf("\\n %d: Locking ... ", thread_id);
pthread_mutex_lock(&mutex_Row);
if (currentRow >= row1) {
pthread_mutex_unlock(&mutex_Row);
printf("\\n %d: Unlocking... \\n I am Thread No.: %d. I have no work to do.", thread_id, thread_id);
if (thread_id == 0)
return;
pthread_exit(0);
}
myRow = currentRow;
currentRow++;
printf("\\n I am Thread No.: %d. I have work to do.", thread_id);
pthread_mutex_unlock(&mutex_Row);
printf("\\n %d: unlocking... Operating on Row: %d.\\n", thread_id, myRow);
for (j = 0; j < col2; ++j)
for (i = 0; i < col1; ++i)
ResMat[myRow][j] += InMat1[myRow][i] * InMat2[i][j];
}
}
int main(int argc, char *argv[])
{
int i, j;
if (argc < 6){
printf("\\n Insufficient arguments. \\n Usage:");
printf("./a.out row1 col1 row2 col2 thread. \\n");
}
row1 = abs(atoi(argv[1]));
col1 = abs(atoi(argv[2]));
row2 = abs(atoi(argv[3]));
col2 = abs(atoi(argv[4]));
if (col1 != row2){
printf("Cannot multiply matrices of given type. Aborting \\n");
exit(0);
}
numberOfThreads = abs(atoi(argv[5]));
printf("Row1: %d. Col1: %d, Row2: %d, Col2: %d. Number of Threads: %d. \\n", row1, col1, row2, col2, numberOfThreads);
InMat1 = (int **) malloc(sizeof(int *) * row1);
for (i = 0; i < row1; ++i)
InMat1[i] = (int *) malloc(sizeof(int) * col1);
InMat2 = (int **) malloc(sizeof(int *) * row2);
for (i = 0; i < row2; ++i)
InMat2[i] = (int *) malloc(sizeof(int) * col2);
ResMat = (int **) malloc(sizeof(int *) * row1);
for (i = 0; i < row1; ++i)
ResMat[i] = (int *) malloc(sizeof(int) * col2);
for (i = 0; i < row1; ++i)
for (j = 0; j < col1; ++j)
InMat1[i][j] = 1;
for (i = 0; i < row2; ++i)
for (j = 0; j < col2; ++j)
InMat2[i][j] = 2;
for (i = 0; i < row1; ++i)
for (j = 0; j < col2; ++j)
ResMat[i][j] = 0;
threads = (pthread_t *) malloc(sizeof(pthread_t) * numberOfThreads);
currentRow = 0;
for (i = 0; i < numberOfThreads; ++i){
pthread_create(&threads[i], 0, (void *(*) (void *)) doMyWork, (void *) (i + 1));
printf("Thread %d created. \\n", i+1);
}
for (i = 0; i < numberOfThreads; ++i){
printf("Joning Thread %d \\n", i+1);
pthread_join(threads[i], 0);
printf("Thread %d joined \\n", i + 1);
printf("\\n");
}
for (i = 0; i < row1; ++i) {
for (j = 0; j < col2; ++j)
printf("%d ", ResMat[i][j]);
printf("\\n");
}
printf("Program is Done \\n");
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t Mutex;
pthread_cond_t Condition;
int Value;
} semaphore_type;
void Wait(semaphore_type *Semaphore) {
pthread_mutex_lock(&(Semaphore->Mutex));
Semaphore->Value--;
if (Semaphore->Value < 0) {
pthread_cond_wait(&(Semaphore->Condition),&(Semaphore->Mutex));
}
pthread_mutex_unlock(&(Semaphore->Mutex));
}
void Signal(semaphore_type *Semaphore) {
pthread_mutex_lock(&(Semaphore->Mutex));
Semaphore->Value++;
if (Semaphore->Value <= 0) {
pthread_cond_signal(&(Semaphore->Condition));
}
pthread_mutex_unlock(&(Semaphore->Mutex));
}
void *Incrementer(void *Dummy) {
extern int CommonInt;
extern semaphore_type MySemaphore;
extern pthread_mutex_t IntMutex;
sleep(rand() % 4);
Wait(&MySemaphore);
pthread_mutex_lock(&IntMutex);
CommonInt--;
printf("The common integer is now down to %d\\n",CommonInt);
pthread_mutex_unlock(&IntMutex);
sleep(rand() % 2);
pthread_mutex_lock(&IntMutex);
CommonInt++;
printf("The common integer is now up to %d\\n",CommonInt);
pthread_mutex_unlock(&IntMutex);
Signal(&MySemaphore);
return(0);
}
int main(int argc,char *argv[]) {
extern int CommonInt;
extern semaphore_type MySemaphore;
extern pthread_mutex_t IntMutex;
int Index;
pthread_t NewThread;
pthread_mutex_init(&MySemaphore.Mutex,0);
pthread_cond_init(&MySemaphore.Condition,0);
MySemaphore.Value = atoi(argv[2]);
pthread_mutex_init(&IntMutex,0);
CommonInt = atoi(argv[2]);
srand(atoi(argv[3]));
for (Index=0;Index<atoi(argv[1]);Index++) {
if (pthread_create(&NewThread,0,Incrementer,0) != 0) {
perror("Creating thread");
exit(1);
}
if (pthread_detach(NewThread) != 0) {
perror("Detaching thread");
exit(1);
}
}
printf("Exiting the main program, leaving the threads running\\n");
pthread_exit(0);
}
| 0
|
#include <pthread.h>
FILE *ctx_msg_out = 0;
pthread_mutex_t ctx_biglock;
char ctx_cmdcode[4] = "000";
static void err_msg(const char *type, const char *path, const char *func,
int line, const char *fmt, va_list argptr)
{
(void)func;
char *filename = strdup(path);
fflush(stdout);
fflush(stderr);
timestampf(stderr);
fprintf(stderr, "[%s:%i] %s: ", basename(filename), line, type);
vfprintf(stderr, fmt, argptr);
if(*(fmt + strlen(fmt) - 1) != '\\n') fputc('\\n', stderr);
free(filename);
}
void dief(const char *file, const char *func, int line, const char *fmt, ...)
{
va_list argptr;
pthread_mutex_lock(&ctx_biglock);
__builtin_va_start((argptr));
err_msg("Fatal Error", file, func, line, fmt, argptr);
;
exit(1);
}
void warnf(const char *file, const char *func, int line, const char *fmt, ...)
{
va_list argptr;
pthread_mutex_lock(&ctx_biglock);
__builtin_va_start((argptr));
err_msg("Warn", file, func, line, fmt, argptr);
;
pthread_mutex_unlock(&ctx_biglock);
}
void messagef(FILE *fh, const char *fmt, ...)
{
if(fh != 0) {
va_list argptr;
__builtin_va_start((argptr));
vfprintf(fh, fmt, argptr);
;
fflush(fh);
}
}
void timestampf(FILE *fh)
{
time_t t;
char tstr[200];
if(fh != 0) {
time(&t);
strftime(tstr, 100, "[%d %b %Y %H:%M:%S", localtime(&t));
fprintf(fh, "%s-%s]", tstr, ctx_cmdcode);
}
}
void statusf(FILE *fh, const char *fmt, ...)
{
va_list argptr;
if(fh != 0) {
pthread_mutex_lock(&ctx_biglock);
timestampf(fh);
if(fmt[0] != ' ' && fmt[0] != '[') fputc(' ', fh);
__builtin_va_start((argptr));
vfprintf(fh, fmt, argptr);
;
if(fmt[strlen(fmt)-1] != '\\n') fputc('\\n', fh);
fflush(fh);
pthread_mutex_unlock(&ctx_biglock);
}
}
void print_usage(const char *msg, const char *errfmt, ...)
{
if(errfmt != 0) {
pthread_mutex_lock(&ctx_biglock);
fprintf(stderr, "Error: ");
va_list argptr;
__builtin_va_start((argptr));
vfprintf(stderr, errfmt, argptr);
;
if(errfmt[strlen(errfmt)-1] != '\\n') fputc('\\n', stderr);
}
fputs(msg, stderr);
exit(1);
}
void ctx_output_init()
{
if(!ctx_msg_out) ctx_msg_out = stderr;
static const char consonants[]
= "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
static const char vowels[] = "aeiouAEIOU";
if(pthread_mutex_init(&ctx_biglock, 0) != 0) {
printf("%s:%i: mutex init failed\\n", "ctx_output.c", 116);
exit(1);
}
ctx_cmdcode[0] = consonants[rand() % strlen(consonants)];
ctx_cmdcode[1] = vowels[rand() % strlen(vowels)];
ctx_cmdcode[2] = consonants[rand() % strlen(consonants)];
ctx_cmdcode[3] = '\\0';
}
void ctx_output_destroy()
{
pthread_mutex_destroy(&ctx_biglock);
}
void ctx_update(const char *job_name, size_t niter)
{
if(niter % CTX_UPDATE_REPORT_RATE == 0)
{
char num_str[100];
long_to_str(niter, num_str);
status("[%s] Read %s entries (reads / read pairs)", job_name, num_str);
}
}
void ctx_update2(const char *job_name, size_t nold, size_t nnew, size_t nreport)
{
char num_str[100];
ctx_assert2(nnew >= nold, "%zu %zu", nold, nnew);
if((nnew - nold) >= nreport - (nold % nreport)) {
long_to_str(nnew, num_str);
status("[%s] Read %s entries (reads / read pairs)", job_name, num_str);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutexExit = PTHREAD_MUTEX_INITIALIZER;
static int exitThread=0;
pthread_mutex_t mutexBrake = PTHREAD_MUTEX_INITIALIZER;
static int isBreaking = 0;
void setBrake()
{
pthread_mutex_lock(&mutexBrake);
isBreaking = 1;
pthread_mutex_unlock(&mutexBrake);
}
void resetBrake()
{
pthread_mutex_lock(&mutexBrake);
isBreaking = 0;
pthread_mutex_unlock(&mutexBrake);
}
static int getBrakeStatus()
{
int curBrake;
pthread_mutex_lock(&mutexBrake);
curBrake = isBreaking;
pthread_mutex_unlock(&mutexBrake);
return curBrake;
}
void *proximityThreadFunc(void *pa){
unsigned long res;
struct timeval start,stop;
int cnt=0, obstacle = 0;
int oldDC=0;
int quit = 0;
while(1) {
if (pthread_mutex_trylock(&mutexExit) == 0) {
quit = exitThread;
pthread_mutex_unlock(&mutexExit);
}
if (quit) {
break;
} else if(!quit){
GPIO_low(PROXIMITY_TRIGGER);
usleep(20);
GPIO_high(PROXIMITY_TRIGGER);
usleep(20);
GPIO_low(PROXIMITY_TRIGGER);
cnt=0;
while((GPIO_PIN_LEVEL & GPIO_BIT_SET(PROXIMITY_ECHO))==0);
gettimeofday(&start,0);
while((GPIO_PIN_LEVEL & GPIO_BIT_SET(PROXIMITY_ECHO))!=0);
gettimeofday(&stop,0);
res = (stop.tv_usec - start.tv_usec)/58;
if(res > 250){
continue;
}
if(res < 20){
GPIO_high(STOP_PIN);
if(!obstacle) {
oldDC = getDC();
pwm_sw_setDutyCycle(FORWARD_PIN,0);
usleep(1000);
pwm_sw_setDutyCycle(BACKWARD_PIN,100);
usleep(100000);
pwm_sw_setDutyCycle(BACKWARD_PIN,0);
}
pwm_sw_setDutyCycle(FORWARD_PIN,0);
obstacle=1;
}else if (obstacle) {
obstacle=0;
GPIO_low(STOP_PIN);
pwm_sw_setDutyCycle(FORWARD_PIN,oldDC);
}
usleep(100000);
}
}
pthread_exit(0);
exitThread = 0;
return 0;
}
void closeProximity()
{
pthread_mutex_lock(&mutexExit);
exitThread=1;
pthread_mutex_unlock(&mutexExit);
}
| 0
|
#include <pthread.h>
int count = 10;
pthread_mutex_t mutex1;
pthread_mutex_t mutex2;
void *print_a(void)
{
int i;
for(i = 0; i< 10; i++)
{
printf("A!\\n");
pthread_mutex_lock(&mutex1);
sleep(1);
}
}
void *print_b(void)
{
int i;
for(i = 0; i< 10; i++)
{
pthread_mutex_lock(&mutex1);
printf("B!\\n");
sleep(1);
pthread_mutex_lock(&mutex2);
}
}
void *print_c(void)
{
int i;
for(i = 0; i< 10; i++)
{
pthread_mutex_unlock(&mutex2);
printf("C!\\n");
sleep(1);
}
}
int main()
{
pthread_t id[3];
int ret;
int i;
pthread_mutex_init(&mutex1,0);
pthread_mutex_init(&mutex2,0);
ret = pthread_create(&id[1],0,(void *)print_a,0);
ret = pthread_create(&id[2],0,(void *)print_b,0);
ret = pthread_create(&id[3],0,(void *)print_c,0);
pthread_join(id[0],0);
pthread_join(id[1],0);
pthread_join(id[2],0);
return 0;
}
| 1
|
#include <pthread.h>
int buffer1[4];
int buffer2[4];
int in1, out1;
int in2, out2;
int buffer1_is_empty()
{
return in1 == out1;
}
int buffer1_is_full()
{
return (in1 + 1) % 4 == out1;
}
int buffer2_is_empty()
{
return in2 == out2;
}
int buffer2_is_full()
{
return (in2 + 1) % 4 == out2;
}
int get_item_from_buffer1()
{
int item;
item = buffer1[out1];
out1 = (out1 + 1) % 4;
return item;
}
void put_item_in_buffer1(int item)
{
buffer1[in1] = item;
in1 = (in1 + 1) % 4;
}
int get_item_from_buffer2()
{
int item;
item = buffer2[out2];
out2 = (out2 + 1) % 4;
return item;
}
void put_item_in_buffer2(int item)
{
buffer2[in2] = item;
in2 = (in2 + 1) % 4;
}
pthread_mutex_t mutex1, mutex2;
pthread_cond_t wait_empty_buffer1, wait_empty_buffer2;
pthread_cond_t wait_full_buffer1, wait_full_buffer2;
void *consume(void *arg)
{
int i;
int item;
for (i = 0; i < (4 * 2); i++) {
pthread_mutex_lock(&mutex2);
while (buffer2_is_empty()) {
pthread_cond_wait(&wait_full_buffer2, &mutex2);
}
item = get_item_from_buffer2();
printf("Consumer :\\tconsume item from buffer2: %c\\n", item);
sleep(1);
pthread_cond_signal(&wait_empty_buffer2);
pthread_mutex_unlock(&mutex2);
}
return 0;
}
void produce()
{
int i;
int item;
for (i = 0; i < (4 * 2); i++) {
pthread_mutex_lock(&mutex1);
while (buffer1_is_full()) {
pthread_cond_wait(&wait_empty_buffer1, &mutex1);
}
item = i + 'a';
printf("Producer :\\tproduce item put in buffer1: %c\\n", item);
put_item_in_buffer1(item);
sleep(1);
pthread_cond_signal(&wait_full_buffer1);
pthread_mutex_unlock(&mutex1);
}
}
void *compute()
{
int i;
int item;
for (i = 0; i < (4 * 2); i++) {
pthread_mutex_lock(&mutex1);
while (buffer1_is_empty()) {
pthread_cond_wait(&wait_full_buffer1, &mutex1);
}
item = get_item_from_buffer1();
printf("Computer :\\tget item from buffer1: %c\\n", item);
pthread_cond_signal(&wait_empty_buffer1);
pthread_mutex_unlock(&mutex1);
pthread_mutex_lock(&mutex2);
while (buffer2_is_full()) {
pthread_cond_wait(&wait_empty_buffer2, &mutex2);
}
item = i + 'A';
printf("Computer :\\tput item in buffer2: %c\\n", item);
put_item_in_buffer2(item);
sleep(1);
pthread_cond_signal(&wait_full_buffer2);
pthread_mutex_unlock(&mutex2);
}
return 0;
}
int main()
{
pthread_t compute_tid, consumer_tid;
pthread_mutex_init(&mutex1, 0);
pthread_mutex_init(&mutex2, 0);
pthread_cond_init(&wait_empty_buffer1, 0);
pthread_cond_init(&wait_full_buffer1, 0);
pthread_cond_init(&wait_empty_buffer2, 0);
pthread_cond_init(&wait_full_buffer2, 0);
pthread_create(&compute_tid, 0, compute, 0);
pthread_create(&consumer_tid, 0, consume, 0);
produce();
pthread_join(compute_tid, 0);
pthread_join(consumer_tid, 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mtx;
pthread_cond_t cond;
int how_many = 10;
int pool = 0;
void * producer(void * ptr);
void * consumer(void * ptr);
int main(int argc, char ** argv) {
pthread_t prod, cons;
pthread_mutex_init(&mtx, 0);
pthread_cond_init(&cond, 0);
pthread_create(&cons, 0, consumer, 0);
pthread_create(&prod, 0, producer, 0);
pthread_join(prod, 0);
pthread_join(cons, 0);
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&mtx);
return 0;
}
void * producer(void * ptr) {
while (how_many > 0) {
pthread_mutex_lock(&mtx);
printf("producer: %d\\n", how_many);
pool = how_many;
how_many--;
pthread_mutex_unlock(&mtx);
pthread_cond_signal(&cond);
}
pthread_exit(0);
}
void * consumer(void * ptr) {
while (how_many > 0) {
pthread_mutex_lock(&mtx);
pthread_cond_wait(&cond, &mtx);
printf("consumer: %d\\n", pool);
pool = 0;
pthread_mutex_unlock(&mtx);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mesa = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t papel_sem = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t cerillos_sem = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t tabaco_sem = PTHREAD_MUTEX_INITIALIZER;
void fumar(){
printf("Estoy fumando\\n");
sleep(5);
printf("Termine de fumar\\n");
}
void colocar_materiales(){
srand(time(0));
int r = rand() % 3;
if (r==0){
pthread_mutex_lock(&cerillos_sem);
pthread_mutex_lock(&tabaco_sem);
printf("Estoy poniendo materiales");
pthread_mutex_unlock(&cerillos_sem);
pthread_mutex_unlock(&tabaco_sem);
}
else if (r==1){
pthread_mutex_lock(&papel_sem);
pthread_mutex_lock(&tabaco_sem);
printf("Estoy poniendo materiales");
pthread_mutex_unlock(&papel_sem);
pthread_mutex_unlock(&tabaco_sem);
}
else {
pthread_mutex_lock(&papel_sem);
pthread_mutex_lock(&cerillos_sem);
printf("Estoy poniendo materiales");
pthread_mutex_unlock(&papel_sem);
pthread_mutex_unlock(&cerillos_sem);
}
}
void *agente(void *arg){
while (1){
pthread_mutex_lock(&mesa);
colocar_materiales();
pthread_mutex_unlock(&mesa);
}
pthread_exit(0);
}
void *fumador_papel(void *arg){
while(1){
pthread_mutex_lock(&mesa);
pthread_mutex_lock(&cerillos_sem);
while (pthread_mutex_trylock(&tabaco_sem)){
pthread_mutex_unlock(&cerillos_sem);
pthread_mutex_lock(&cerillos_sem);
}
fumar();
pthread_mutex_unlock(&tabaco_sem);
pthread_mutex_unlock(&cerillos_sem);
pthread_mutex_unlock(&mesa);
}
pthread_exit(0);
}
void *fumador_tabaco(void *arg){
while(1){
pthread_mutex_lock(&mesa);
pthread_mutex_lock(&cerillos_sem);
while (pthread_mutex_trylock(&papel_sem)){
pthread_mutex_unlock(&cerillos_sem);
pthread_mutex_lock(&cerillos_sem);
}
fumar();
pthread_mutex_unlock(&papel_sem);
pthread_mutex_unlock(&cerillos_sem);
pthread_mutex_unlock(&mesa);
}
pthread_exit(0);
}
void *fumador_cerillos(void *arg){
while(1){
pthread_mutex_lock(&mesa);
pthread_mutex_lock(&papel_sem);
while (pthread_mutex_trylock(&tabaco_sem)){
pthread_mutex_unlock(&papel_sem);
pthread_mutex_lock(&papel_sem);
}
fumar();
pthread_mutex_unlock(&tabaco_sem);
pthread_mutex_unlock(&papel_sem);
pthread_mutex_unlock(&mesa);
}
pthread_exit(0);
}
int main()
{
srand(time(0));
pthread_t agente_tid;
pthread_t fumador_papel_tid;
pthread_t fumador_tabaco_tid;
pthread_t fumador_cerillos_tid;
pthread_create(&agente_tid,0,agente,0);
pthread_create(&fumador_papel_tid,0,fumador_papel,0);
pthread_create(&fumador_tabaco_tid,0,fumador_tabaco,1);
pthread_create(&fumador_cerillos_tid,0,fumador_cerillos,2);
pthread_join(agente_tid,0);
pthread_join(fumador_papel_tid,0);
pthread_join(fumador_cerillos_tid,0);
pthread_join(fumador_tabaco_tid,0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
int parking_spots = 0;
int get_parking_spots() {
pthread_mutex_lock(&mutex);
int result = parking_spots;
pthread_mutex_unlock(&mutex);
return result;
}
void inc_parking_spots() {
pthread_mutex_lock(&mutex);
parking_spots++;
pthread_mutex_unlock(&mutex);
}
void dec_parking_spots() {
pthread_mutex_lock(&mutex);
parking_spots--;
pthread_mutex_unlock(&mutex);
}
void *entry_controller(void *args) {
bool entry_request;
bool entry_sensor_state;
while (1) {
read_entry_request(&entry_request);
if (entry_request) {
if (get_parking_spots() < NUM_PARKING_SPOTS) {
inc_parking_spots();
write_entry_gate_state(GATE_OPEN);
entry_sensor_state = 1;
while (entry_sensor_state) {
read_entry_sensor_state(&entry_sensor_state);
delay_ms(100);
}
write_entry_gate_state(GATE_CLOSED);
}
}
delay_ms(100);
}
return 0;
}
void *exit_controller(void *args) {
bool exit_request;
bool exit_sensor_state;
while (1) {
read_exit_request(&exit_request);
if (exit_request) {
dec_parking_spots();
write_exit_gate_state(GATE_OPEN);
exit_sensor_state = 1;
while (exit_sensor_state) {
read_exit_sensor_state(&exit_sensor_state);
delay_ms(100);
}
write_exit_gate_state(GATE_CLOSED);
}
delay_ms(100);
}
return 0;
}
void *signal_controller(void *args) {
while (1) {
if (get_parking_spots() < NUM_PARKING_SPOTS) {
write_signal_state(SIGNAL_FREE);
} else {
write_signal_state(SIGNAL_FULL);
}
delay_ms(100);
}
return 0;
}
int main() {
init_simulator();
pthread_mutex_init(&mutex, 0);
pthread_t entry_controller_thread;
pthread_t exit_controller_thread;
pthread_t signal_controller_thread;
if (pthread_create(&entry_controller_thread, 0, entry_controller, 0) != 0) exit(1);
if (pthread_create(&exit_controller_thread, 0, exit_controller, 0) != 0) exit(1);
if (pthread_create(&signal_controller_thread, 0, signal_controller, 0) != 0) exit(1);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
void *thread_function(void *arg);
pthread_mutex_t work_mutex;
char work_area[1024];
int time_to_exit = 0;
int main() {
int res;
pthread_t a_thread;
void *thread_result;
res = pthread_mutex_init(&work_mutex, 0);
if (res != 0) {
perror("Mutex initialization failed");
exit(1);
}
res = pthread_create(&a_thread, 0, thread_function, 0);
if (res != 0) {
perror("Thread creation failed");
exit(1);
}
pthread_mutex_lock(&work_mutex);
printf("Input some text. Enter ‘end’ to finish\\n");
while(!time_to_exit) {
fgets(work_area, 1024, stdin);
pthread_mutex_unlock(&work_mutex);
while(1) {
pthread_mutex_lock(&work_mutex);
if (work_area[0] != '\\0') {
pthread_mutex_unlock(&work_mutex);
sleep(1);
}
else {
break;
}
}
}
pthread_mutex_unlock(&work_mutex);
printf("\\nWaiting for thread to finish...\\n");
res = pthread_join(a_thread, &thread_result);
if (res != 0) {
perror("Thread join failed");
exit(1);
}
printf("Thread joined\\n");
pthread_mutex_destroy(&work_mutex);
exit(0);
}
void *thread_function(void *arg) {
sleep(1);
pthread_mutex_lock(&work_mutex);
while(strncmp("end", work_area, 3) != 0) {
printf("You input %d characters\\n", strlen(work_area) -1);
work_area[0] = '\\0';
pthread_mutex_unlock(&work_mutex);
sleep(1);
pthread_mutex_lock(&work_mutex);
while (work_area[0] == '\\0' ) {
pthread_mutex_unlock(&work_mutex);
sleep(1);
pthread_mutex_lock(&work_mutex);
}
}
time_to_exit = 1;
work_area[0] = '\\0';
pthread_mutex_unlock(&work_mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int i, j;
int tenedor[5]={1,1,1,1,1};
pthread_mutex_t m[5];
int p[5]={0,1,2,3,4};
int numComidas[5]={0,0,0,0,0};
int comidaCont = 0;
void *filosofos(void *);
int main(){
pthread_t tid[5];
srand((long)time(0));
for(i=0; i<5; i++){
if(pthread_create( tid+i, 0,filosofos, p + i ) != 0){
perror("pthread_create() error al Crear hilo.");
exit(1);
}
}
for (i=0;i<5;i++){
if(!pthread_join(tid[i], 0)==0){
perror("falla en el pthread_join() .");
exit(1);
}
}
printf("\\n");
for(i=0;i<5;i++)
printf("El Filosofo %d comio %d veces.\\n", i, numComidas[i]);
printf("\\nprincipal(): Los filósofos se han ido. Voy a salir!\\n\\n");
return (0);
}
void *filosofos(void *arg){
int sub = *(int*)arg;
while(comidaCont < 20){
printf("Filosofo %d: ¡Voy a comer!\\n", sub);
pthread_mutex_lock( m + sub );
if( tenedor[sub] == 1 ){
printf("Filosofo %d: izquierda=%d\\n",sub,tenedor[sub]);
printf("Filosofo %d: tengo tenedor!\\n", sub);
tenedor[sub]=0;
pthread_mutex_unlock( m + sub );
pthread_mutex_lock(m+((sub+1)%5));
if( tenedor[(sub+1)%5]==1){
printf("filosofo %d: derecho=%d\\n", sub,tenedor[(sub+1)%5]);
tenedor[(sub+1)%5]=0;
pthread_mutex_unlock(m+((sub+1)%5));
printf("Filosofo %d: Tengo un tenedor y una cuchara!\\n", sub);
printf("Filosofo %d: ¡Estoy comiendo!\\n\\n", sub);
numComidas[sub]++;
comidaCont++;
usleep(rand() % 3000000);
pthread_mutex_lock(m+sub);
pthread_mutex_lock(m+((sub+1)%5));
tenedor[sub]=1;
tenedor[(sub+1)%5]=1;
pthread_mutex_unlock ( &m[sub]);
pthread_mutex_unlock (&m[(sub+1)%5]);
usleep(rand() % 3000000);
}
else{
printf("Filosofo %d: derecha=%d\\n",
sub, tenedor[(sub+1)%5]);
printf("Filosofo %d: cuchara ocupada!\\n\\n", sub);
pthread_mutex_unlock(&m[(sub+1)%5]);
pthread_mutex_lock(&m[sub]);
tenedor[sub]=1;
pthread_mutex_unlock(&m[sub]);
usleep(rand() % 3000000);
}
}
else{
printf("filosofo %d: derecho=%d\\n",sub,tenedor[sub]);
printf("filosofo %d: No puedo conseguir la cuchara!\\n\\n",sub);
pthread_mutex_unlock(&m[sub]);
usleep(rand() % 3000000);
}
sched_yield();
}
printf("Filosofo %d ha terminado de cenar y se está despidiendo!\\n", sub);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int NUM_THREADS;
long int chunk_end;
long int chunk_init;
pthread_mutex_t lock_x;
void swapM(long int* a, long int* b)
{
long int aux;
aux = *a;
*a = *b;
*b = aux;
}
long int divideM(long int *vec, int left, int right)
{
int i, j;
i = left;
for (j = left + 1; j <= right; ++j)
{
if (vec[j] < vec[left])
{
++i;
pthread_mutex_lock(&lock_x);
swapM(&vec[i], &vec[j]);
pthread_mutex_unlock(&lock_x);
}
}
pthread_mutex_lock(&lock_x);
swapM(&vec[left], &vec[i]);
pthread_mutex_unlock(&lock_x);
return i;
}
void quickSortM(long int *vec, int left, int right)
{
int r;
if (right > left)
{
r = divideM(vec, left, right);
quickSortM(vec, left, r - 1);
quickSortM(vec, r + 1, right);
}
}
void *th_qs(void *vect)
{
long int *vec = (long int *) vect;
quickSortM(vec,chunk_init, chunk_end);
pthread_exit(0);
}
int run_t(char **fname)
{
int i;
long int num,size=0;
FILE *ptr_myfile;
pthread_t tid[NUM_THREADS];
void *status;
char str[30];
struct timeval time;
ptr_myfile=fopen(*fname,"rb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
while(fread(&num,sizeof(long int),1,ptr_myfile))
size++;
size--;
long int arr[size];
fseek(ptr_myfile, sizeof(long int), 0 );
for(i=0;i<size;i++)
fread(&arr[i],sizeof(long int),1,ptr_myfile);
fclose(ptr_myfile);
gettimeofday(&time, 0);
double dTime1 = time.tv_sec+(time.tv_usec/1000000.0);
pthread_mutex_init(&lock_x, 0);
for ( i = 1; i < NUM_THREADS; i++)
{
chunk_init = chunk_end;
chunk_end = (size/NUM_THREADS)*i;
pthread_create(&tid[i], 0, &th_qs, (void*)arr);
}
for ( i = 1; i < NUM_THREADS; i++)
pthread_join(tid[i], &status);
chunk_init=0;
chunk_end = size;
pthread_create(&tid[NUM_THREADS], 0, &th_qs, (void*)arr);
pthread_join(tid[NUM_THREADS], &status);
gettimeofday(&time, 0);
double dTime2 = time.tv_sec+(time.tv_usec/1000000.0);
strcpy(str, *fname);
strcat(str, ".out");
ptr_myfile=fopen(str,"wb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( i=0; i < size; i++)
fwrite(&arr[i], sizeof(long int), 1, ptr_myfile);
fclose(ptr_myfile);
printf("\\n\\t - Quicksearch -\\n");
printf("\\n %.6lf seconds elapsed \\n", dTime2 - dTime1);
printf("\\n Output file = %s \\n\\n",str);
return 0;
}
int run_p(char **fname){
int i,wpid,status;
long int num,size=0;
FILE *ptr_myfile;
char str[30];
struct timeval time;
ptr_myfile=fopen(*fname,"rb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
while(fread(&num,sizeof(long int),1,ptr_myfile))
size++;
size--;
long int arr[size];
fseek(ptr_myfile, sizeof(long int), 0 );
for(i=0;i<size;i++)
fread(&arr[i],sizeof(long int),1,ptr_myfile);
fclose(ptr_myfile);
gettimeofday(&time, 0);
double dTime1 = time.tv_sec+(time.tv_usec/1000000.0);
for ( i = 1; i < NUM_THREADS; i++)
{
chunk_init = chunk_end;
chunk_end = (size/NUM_THREADS)*i;
if ( i==2 || i== 4 || i==6)
wpid = fork();
if(wpid>0)
break;
quickSortM(arr,chunk_init, chunk_end);
wait(&status);
}
quickSortM(arr,0, size);
gettimeofday(&time, 0);
double dTime2 = time.tv_sec+(time.tv_usec/1000000.0);
strcpy(str, *fname);
strcat(str, ".out");
ptr_myfile=fopen(str,"wb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( i=0; i < size; i++)
fwrite(&arr[i], sizeof(long int), 1, ptr_myfile);
fclose(ptr_myfile);
printf("\\n\\t - Quicksearch -\\n");
printf("\\n %.6lf seconds elapsed \\n", dTime2 - dTime1);
printf("\\n Output file = %s \\n\\n",str);
return 0;
}
void help(){
printf("\\nUsage: fqs [OPTION]... [FILE]...\\nSort with quicksort algoritm a file with random long ints, OPTION and FILE are mandatory, OPTION must be [-s/-m], a default run displays this help and exit.\\n\\t-t run with thread support\\n\\t-p run without multiprocess support\\n\\t\\t-h display this help and exit\\n\\t\\t-v output version information and exit\\n\\n");
}
void vers(){
printf("\\nqs 1.35\\nCopyright (C) 2015 Free Software Foundation, Inc.\\nLicense GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\\nThis is free software: you are free to change and redistribute it.\\nThere is NO WARRANTY, to the extent permitted by law.\\n\\nWritten by Gonçalo Faria, Luis Franco, and Vitor Filipe \\n\\n");
}
int main (int argc, char *argv[]) {
int rtn,total,opt;
switch(argc){
case 2:
opt = getopt(argc, argv, "v");
if(opt == 'v')
{
vers();
rtn=0;
}
else
{
help();
rtn=1;
}
break;
case 4:
NUM_THREADS=atoi(argv[3]);
opt = getopt(argc, argv, "t:p:");
if(opt == 'p')
rtn=run_p(&argv[2]);
else if (opt == 't')
rtn=run_t(&argv[2]);
else
{
help();
rtn=1;
}
break;
default:
help();
rtn=1;
break;
}
return rtn;
}
| 0
|
#include <pthread.h>
void write(int number, FILE* file){
switch(number){
case A:
printf("A");
fputc('A', file);
break;
case C:
printf("C");
fputc('C', file);
break;
case G:
printf("G");
fputc('G', file);
break;
case T:
printf("T");
fputc('T', file);
break;
}
}
long getPow(int base, unsigned short int power){
long result = 1;
int i;
for(i = 0; i<power; i++) result*=base;
return result;
}
void ask(int* lenght, char* name, pthread_mutex_t* mutualExclusion){
pthread_mutex_lock(mutualExclusion);
do{
printf("%s\\n",LENGHT_SENTENCE);
scanf("%d",lenght);
}while(*lenght > MAX_SEQUENCE_LENGHT);
printf("%s\\n",FILE_NAME_SENTENCE);
scanf("%s",name);
pthread_mutex_unlock(mutualExclusion);
}
void generate(int* lenght, char* name, pthread_mutex_t* mutualExclusion){
pthread_mutex_lock(mutualExclusion);
FILE* sequence;
char* tmpName = malloc(strlen(PROJECT_PATH)+MAX_NAME_LENGHT+4);
strcpy(tmpName,PROJECT_PATH);
strcat(tmpName,name);
strcat(tmpName,FILE_EXT);
printf("%s \\n", tmpName);
if(sequence = fopen(tmpName,"w+")) {
printf(SUCCESSFUL);
int i;
for (i = 0; i < *lenght; i++) {
write(rand() % ENCODING_BASE, sequence);
}
printf("\\n");
}else printf(FILE_ALREADY_EXISTS);
free(tmpName);
fclose(sequence);
pthread_mutex_unlock(mutualExclusion);
}
void* receiverThread(void* detach){
createDirectory();
printf("%s %s \\n",HELLO,PROJECT_NAME);
srand(time(0));
pthread_mutex_t* mutualExclusion = (pthread_mutex_t*)(malloc(sizeof(pthread_mutex_t)));
pthread_mutex_init(mutualExclusion,0);
char* fileName = (char*)malloc(sizeof(char));
int* sequenceLenght = (int*)malloc(sizeof(int));
char* excecuting = (char*)malloc(sizeof(char));
*excecuting = 1;
while(*excecuting){
ask(sequenceLenght, fileName, mutualExclusion);
generate(sequenceLenght, fileName, mutualExclusion);
printf("%s \\n",DO_YOU_WANT_TO_CONTINUE);
scanf("%s",excecuting);
}
free(mutualExclusion);
free(sequenceLenght);
free(excecuting);
free(fileName);
printf("%s",GOODBYE);
return detach;
}
| 1
|
#include <pthread.h>
{
float arrivalTime ;
float transTime ;
int priority ;
int id ;
} flow;
flow flowList[50];
flow *queueList[50];
pthread_t thrList[50];
pthread_mutex_t trans_mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t trans_cvar = PTHREAD_COND_INITIALIZER;
int queueMin, queueMax, usingID, numFlow;
bool available;
time_t startTime, endTime, begin, end;
void printQueue(){
int i;
printf("-----QUEUELIST----- %d\\n", queueMin);
for(i = queueMin; i < queueMax; i++){
printf("%d\\n",(*queueList[i]).id);
}
printf("-----QUEUELIST-----%d\\n",queueMax);
}
void swap(int a, int b){
flow *temp = queueList[a];
queueList[a] = queueList[b];
queueList[b] = temp;
}
void sort(){
int i, j;
for(i = queueMin; i < queueMax; i++){
for(j = i+1; j < queueMax; j++){
if((*queueList[i]).priority > (*queueList[j]).priority){
swap(i,j);
}else if((*queueList[i]).priority == (*queueList[j]).priority){
if((*queueList[i]).arrivalTime > (*queueList[j]).arrivalTime){
swap(i,j);
}else if((*queueList[i]).arrivalTime == (*queueList[j]).arrivalTime){
if((*queueList[i]).transTime > (*queueList[j]).transTime){
swap(i,j);
}else if((*queueList[i]).transTime == (*queueList[j]).transTime){
if((*queueList[i]).id > (*queueList[j]).id){
swap(i,j);
}
}
}
}
}
}
}
void requestPipe(flow *item) {
pthread_mutex_lock(&trans_mtx);
if(available && queueMax == 0){
usingID = (*item).id;
available = 0;
pthread_mutex_unlock(&trans_mtx);
return;
}
queueList[queueMax] = item;
queueMax++;
sort();
if(!available){
printf("Flow %2d waits for the finish of flow %2d\\n", (*item).id,usingID);
}
while(!available && (*item).id != (*queueList[queueMin]).id){
pthread_cond_wait(&trans_cvar, &trans_mtx);
}
printf("Out of wait with id: %d\\n", (*item).id);
available = 0;
usingID = (*item).id;
queueMin = queueMin +1;
pthread_mutex_unlock(&trans_mtx);
}
void releasePipe() {
pthread_mutex_lock(&trans_mtx);
available = 1;
pthread_cond_broadcast(&trans_cvar);
pthread_mutex_unlock(&trans_mtx);
}
void *thrFunction(void *flowItem) {
flow *item = (flow *)flowItem;
usleep((*item).arrivalTime * 1000000);
startTime = time(0);
printf("Flow %2d arrives: arrival time (%.2f), transmission time (%.1f), priority (%2d)\\n", (*item).id, (*item).arrivalTime, (*item).transTime, (*item).priority);
end = time(0);
float startDuration = (time_t)difftime(end, begin);
requestPipe(item);
printf("Flow %2d starts its transmission at time %.2f.\\n", (*item).id, startDuration);
usleep((*item).transTime * 100000);
releasePipe(item);
endTime = time(0);
int flowDuration = (time_t)difftime(endTime, startTime);
printf("Flow %2d finishes its transmission at time %d\\n", (*item).id, flowDuration);
pthread_exit(0);
}
int main(int argc, char* argv[]) {
if(argc !=2){
perror("Too many arguments!\\n");
return -1;
}
int i, j, error;
char line[500], fileName[50];
char *token = (char *)malloc(sizeof(char));
char ar[50];
queueMin = queueMax = 0;
available = 1;
begin = time(0);
FILE *fp = fopen(argv[1], "r");
if(!fp){
perror("File open error\\n");
return -1;
}
fgets(ar, 15, fp);
numFlow = atoi(ar);
for(i = 0; i < numFlow; i++){
fgets(line,15,fp);
token = strtok(line, ":");
flowList[i].id = atoi(token);
token = strtok(0, ",");
flowList[i].arrivalTime = atof(token);
token = strtok(0, ",");
flowList[i].transTime = atof(token);
token = strtok(0, "\\n");
flowList[i].priority = atoi(token);
}
fclose(fp);
for(i = 0; i < numFlow; i++){
error = pthread_create(&thrList[i], 0, thrFunction, (void *)&flowList[i]);
if(error != 0){
printf("Can't create thread! Exiting\\n");
exit(0);
}
}
for(j = 0; j < numFlow; j++){
error = pthread_join(thrList[j],0);
if(error != 0){
printf("Can't joine thread! Exiting\\n");
exit(0);
}
}
pthread_mutex_destroy(&trans_mtx);
pthread_cond_destroy(&trans_cvar);
return 0;
}
| 0
|
#include <pthread.h>
int num_iterations;
pthread_mutex_t* mutex;
} ctx;
void* worker_thread(void* ptr) {
ctx* c = (ctx*)ptr;
int num_iterations = c->num_iterations;
while(num_iterations-->0) {
pthread_mutex_lock(c->mutex);
pthread_mutex_unlock(c->mutex);
}
}
void perform_mutex_test(int num_iterations, pthread_mutex_t* mutex) {
ctx* c = malloc(sizeof(c[0]));
c->num_iterations = num_iterations;
c->mutex = mutex;
pthread_t pid1;
pthread_t pid2;
pthread_create(&pid1, 0, worker_thread, c);
pthread_create(&pid2, 0, worker_thread, c);
pthread_join(pid1, 0);
pthread_join(pid2, 0);
free(c);
}
void mutex_test(int num_iterations) {
pthread_mutex_t* mutex = malloc(sizeof(mutex[0]));
pthread_mutex_init(mutex, 0);
perform_mutex_test(num_iterations, mutex);
pthread_mutex_destroy(mutex);
free(mutex);
}
int main(int argc, char** argv) {
int num_iterations = 1000000;
struct timeval start;
struct timeval end;
gettimeofday(&start, 0);
mutex_test(num_iterations);
gettimeofday(&end, 0);
time_t elapsed_time_us = end.tv_usec - start.tv_usec;
elapsed_time_us += 1000000l * (end.tv_sec - start.tv_sec);
double elapsed_time = (double)(elapsed_time_us / 1000000.);
printf("%d iterations took %.3fs\\n", num_iterations, elapsed_time);
return 0;
}
| 1
|
#include <pthread.h>
extern char ** environ;
pthread_mutex_t env_mutex;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
static void thread_init(void) {
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&env_mutex, &attr);
pthread_mutexattr_destroy(&attr);
}
int getenv_r(const char *name, char *buf, int buflen) {
int i, len, olen;
pthread_once(&init_done, thread_init);
len = strlen(name);
pthread_mutex_lock(&env_mutex);
for ( i = 0; environ[i] != 0; i++) {
if ((strncmp(name, environ[i], len) == 0) &&
(environ[i][len] == '=')) {
olen = strlen(&environ[i][len+1]);
if (olen >= buflen) {
pthread_mutex_unlock(&env_mutex);
return(ENOSPC);
}
strcpy(buf, &environ[i][len+1]);
pthread_mutex_unlock(&env_mutex);
return(0);
}
}
pthread_mutex_unlock(&env_mutex);
return(ENOENT);
}
| 0
|
#include <pthread.h>
const char *names[5] = { "Aristoteles", "Kant", "Platon", "Marx", "Aquin" };
pthread_mutex_t forks[5];
const char *topic[5] = { "Spaghetti!", "Life", "Universe", "Everything", "Bathroom" };
void print(int y, int x, const char *fmt, ...)
{
static pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER;
va_list ap;
__builtin_va_start((ap));
pthread_mutex_lock(&screen);
printf("\\033[%d;%dH", y + 1, x), vprintf(fmt, ap);
printf("\\033[%d;%dH", 5 + 1, 1), fflush(stdout);
pthread_mutex_unlock(&screen);
}
void eat(int id)
{
int f[2], ration, i;
f[0] = f[1] = id;
f[id & 1] = (id + 1) % 5;
print(id, 12, "\\033[K");
print(id, 12, "..oO (forks, need forks)");
for (i = 0; i < 2; i++) {
pthread_mutex_lock(forks + f[i]);
if (!i) print(id, 12, "\\033[K");
print(id, 12 + (f[i] != id) * 6, "fork%d", f[i]);
sleep(1);
}
for (i = 0, ration = 3 + rand() % 8; i < ration; i++)
print(id, 24 + i * 4, "nom"), sleep(1);
for (i = 0; i < 2; i++) pthread_mutex_unlock(forks + f[i]);
}
void think(int id)
{
int i, t;
char buf[64] = {0};
do {
print(id, 12, "\\033[K");
sprintf(buf, "..oO (%s)", topic[t = rand() % 5]);
for (i = 0; buf[i]; i++) {
print(id, i+12, "%c", buf[i]);
if (i < 5) usleep(200000);
}
usleep(500000 + rand() % 1000000);
} while (t);
}
void* philosophize(void *a)
{
int id = *(int*)a;
print(id, 1, "%10s", names[id]);
while(1) think(id), eat(id);
}
int main()
{
int i, id[5];
pthread_t tid[5];
for (i = 0; i < 5; i++)
pthread_mutex_init(forks + (id[i] = i), 0);
for (i = 0; i < 5; i++)
pthread_create(tid + i, 0, philosophize, id + i);
return pthread_join(tid[0], 0);
}
| 1
|
#include <pthread.h>
char *NODES_POOL = "1000";
char *key = "node_res";
const int LOOKUP_SIZE = 1024 * 2;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int lookup_nodes() {
size_t ln;
char *result = (char*) calloc(LOOKUP_SIZE, sizeof(char));
if (result != 0) {
int lret = c_zht_lookup2(key, result, &ln);
fprintf(stdout,
"[%lu] c_zht_lookup, return {key}:{value}=> {%s}:{%s}, rc(%d)\\n",
pthread_self(), key, result, lret);
}
int nodes = atoi(result);
free(result);
return nodes;
}
int compare_swap_internal() {
int nodes_avail = lookup_nodes();
int nodes_left = nodes_avail - 100;
if (nodes_left < 0)
return -1000;
char p_nodes_avail[20];
sprintf(p_nodes_avail, "%d", nodes_avail);
char p_nodes_left[20];
sprintf(p_nodes_left, "%d", nodes_left);
int rc = c_zht_compare_and_swap(key, p_nodes_avail, p_nodes_left);
fprintf(stdout,
"[%lu] c_zht_compare_and_swap, {seen_value}:{new_value} => {%s}:{%s}, rc(%d)\\n",
pthread_self(), p_nodes_avail, p_nodes_left, rc);
return rc;
}
void* compare_swap(void *arg) {
pthread_mutex_lock(&mutex);
int rc = compare_swap_internal();
if (rc == 1) {
} else if (rc == -1000) {
} else {
while (rc == 0) {
compare_swap_internal();
}
}
pthread_mutex_unlock(&mutex);
}
void compare_swap_final() {
int nodes_avail = lookup_nodes();
int nodes_pool = atoi(NODES_POOL);
assert(nodes_avail == (nodes_pool - 5 * 100));
}
void insert_resource() {
char *nodes = NODES_POOL;
int rc = c_zht_insert2(key, nodes);
fprintf(stdout, "[%lu] init [%s] nodes available, rc(%d)\\n", pthread_self(),
nodes, rc);
}
void test_compare_swap() {
insert_resource();
int tc = 5;
pthread_t threads[tc];
int i;
for (i = 0; i < tc; i++) {
int th_num = i + 1;
pthread_create(&threads[i], 0, compare_swap, (void*) &th_num);
}
for (i = 0; i <= tc; i++) {
pthread_join(threads[i], 0);
}
compare_swap_final();
}
void printUsage(char *argv_0);
int main(int argc, char **argv) {
extern char *optarg;
double us = 0;
int printHelp = 0;
char *neighbor = 0;
char *zht_cfg = 0;
char *protocol = 0;
int is_init = 0;
int is_lookup = 0;
int c;
while ((c = getopt(argc, argv, "n:z:p:ilh")) != -1) {
switch (c) {
case 'n':
neighbor = optarg;
break;
case 'z':
zht_cfg = optarg;
break;
case 'p':
protocol = optarg;
break;
case 'i':
is_init = 1;
break;
case 'l':
is_lookup = 1;
break;
case 'h':
printHelp = 1;
break;
default:
fprintf(stdout, "Illegal argument \\"%c\\"\\n", c);
printUsage(argv[0]);
exit(1);
}
}
if (printHelp) {
printUsage(argv[0]);
exit(1);
}
if (neighbor != 0 && zht_cfg != 0 && protocol != 0) {
bool useTCP = 0;
if (!strcmp("TCP", protocol)) {
useTCP = 1;
} else {
useTCP = 0;
}
c_zht_init(neighbor, zht_cfg, useTCP);
if (is_init) {
insert_resource();
} else if (is_lookup) {
lookup_nodes();
} else {
test_compare_swap();
}
c_zht_teardown();
} else {
printUsage(argv[0]);
exit(1);
}
return 0;
}
void printUsage(char *argv_0) {
fprintf(stdout, "Usage:\\n%s %s\\n", argv_0,
"{-n neighbor -z zht.cfg -p TCP|UDP -i(init)} | -l(lookup) | {-h(help)}");
}
| 0
|
#include <pthread.h>
pthread_mutex_t mut;
pthread_mutex_t *cb_lock = &mut;
void *pneum_handle = 0;
int (*orig_pneum_connect)(char *name, char *chroot_prefix) = 0;
int (*orig_pneum_connect_sync)(char *name, char *chroot_prefix) = 0;
int (*orig_pneum_disconnect)(void) = 0;
int (*orig_pneum_read)(char **data, int *l) = 0;
int (*orig_pneum_write)(char *data, int len) = 0;
int (*orig_pneum_has_data)(void) = 0;
int (*orig_pneum_data_free)(char *data) = 0;
arbitrary my_function = 0;
u8 *cough_read_buffer;
u32 cough_read_buffer_size = 1000000;
u32 cough_read_head = 0;
u32 cough_read_lock_start = 0;
u32 cough_read_tail = 0;
int wrap_pneum_callback(char *data, int len) {
pthread_mutex_lock(cb_lock);
if(cough_read_lock_start == cough_read_head) {
cough_read_head = 0;
cough_read_tail = 0;
cough_read_lock_start = 0;
}
u32 store_len = len;
memcpy(cough_read_buffer + cough_read_head, &store_len, sizeof(u32));
cough_read_head += sizeof(u32);
memcpy(cough_read_buffer + cough_read_head, data, len);
cough_read_head += len;
pthread_mutex_unlock(cb_lock);
return len;
}
int cough_pneum_attach(char *pneum_fname, char *cough_fname) {
pneum_handle = dlopen(cough_fname, RTLD_NOW|RTLD_GLOBAL);
pneum_handle = dlopen(pneum_fname, RTLD_NOW|RTLD_GLOBAL);
if (pneum_handle) {
*(void**)(&orig_pneum_connect) = dlsym(pneum_handle,"pneum_connect");
*(void**)(&orig_pneum_connect_sync) = dlsym(pneum_handle,"pneum_connect_sync");
*(void**)(&orig_pneum_disconnect) = dlsym(pneum_handle,"pneum_disconnect");
*(void**)(&orig_pneum_read) = dlsym(pneum_handle,"pneum_read");
*(void**)(&orig_pneum_write) = dlsym(pneum_handle,"pneum_write");
*(void**)(&orig_pneum_has_data) = dlsym(pneum_handle,"pneum_has_data");
*(void**)(&orig_pneum_data_free) = dlsym(pneum_handle,"pneum_data_free");
orig_pneum_connect_sync = 0;
cough_read_buffer = malloc(cough_read_buffer_size);
} else {
printf("Could not get cough handle\\n");
printf("Error: %s", dlerror());
return -1;
}
*(void**)(&my_function) = dlsym(pneum_handle,"something");
}
int pneum_connect(char *name, char *chroot_prefix) {
if(orig_pneum_connect) {
return(orig_pneum_connect(name, chroot_prefix));
} else {
printf("COUGH: pneum_connect\\n");
return -1;
}
}
int pneum_connect_sync(char *name, char *chroot_prefix) {
if(orig_pneum_connect_sync) {
int ret = (orig_pneum_connect_sync(name, chroot_prefix));
return ret;
} else {
return(orig_pneum_connect(name, chroot_prefix));
}
}
int pneum_disconnect(void) {
if(orig_pneum_disconnect) {
return orig_pneum_disconnect();
} else {
printf("COUGH: pneum_disconnect\\n");
return -1;
}
}
int pneum_has_data(void) {
if (orig_pneum_connect_sync) {
return 1;
} else {
return (cough_read_head != cough_read_tail);
}
}
int pneum_read(char **data, int *l) {
if(orig_pneum_connect_sync) {
return orig_pneum_read(data, l);
} else {
while(!pneum_has_data());
u32 n_bytes;
pthread_mutex_lock(cb_lock);
memcpy(&n_bytes, cough_read_buffer + cough_read_tail, sizeof(u32));
cough_read_tail += sizeof(u32);
void * dataptr = (void *) (cough_read_buffer + cough_read_tail);
*data = dataptr;
cough_read_tail += n_bytes;
*l = n_bytes;
pthread_mutex_unlock(cb_lock);
return n_bytes;
}
}
int pneum_write(char *data, int len) {
if(orig_pneum_write) {
return(orig_pneum_write(data, len));
} else {
printf("COUGH: pneum_write\\n");
return -1;
}
}
void pneum_data_free(char *data) {
if (orig_pneum_connect_sync) {
if(orig_pneum_data_free) {
orig_pneum_data_free(data);
} else {
printf("COUGH: pneum_data_free\\n");
}
} else {
u32 *len;
uint32_t index = ((u8*)data) - cough_read_buffer;
pthread_mutex_lock(cb_lock);
if ((index < cough_read_head) && (index > cough_read_lock_start)) {
len = (void *)(data - sizeof(u32));
cough_read_lock_start = index + *len;
}
pthread_mutex_unlock(cb_lock);
}
}
| 1
|
#include <pthread.h>
void EnterCar(char *CarDir);
void ExitCar (char *CarDir);
void * Car(void* carDir);
char currDir;
pthread_mutex_t leftDir, rightDir, mtxCheck, mtxExit, mtxend;
int countl, countr, flag;
int carsPassed, carsleft, flag,waiting,startflag;
int main (int argc, char *argv[]){
char directions[100];
int i,thrCheck;
pthread_t *p_thrd;
flag=0;
startflag=0;
countl=0, countr=0;
carsPassed= 5;
carsleft=0;
printf ("Please type the directions of the cars. l for left r for right:");
scanf ("%s", directions);
printf ("\\n");
for (i=0; i< strlen(directions); i++){
if (directions[i]=='r'){
countr++;
}
else if(directions[i]=='l'){
countl++;
}
}
if (pthread_mutex_init(&mtxExit, 0) != 0)
{
perror ("Mutex error");
return 1;
}
if (pthread_mutex_init(&mtxend, 0) != 0)
{
perror ("Mutex error");
return 1;
}
pthread_mutex_lock (&mtxend);
if (pthread_mutex_init(&rightDir, 0) != 0)
{
perror ("Mutex error");
return 1;
}
if (pthread_mutex_init(&leftDir, 0) != 0)
{
perror ("Mutex error");
return 1;
}
if (pthread_mutex_init(&mtxCheck, 0) != 0)
{
perror ("Mutex error");
return 1;
}
if (0==(p_thrd= (pthread_t*)malloc(strlen(directions)*sizeof(pthread_t)))){
perror ("Memory allocation error");
}
for (i=0; i< strlen(directions); i++){
thrCheck = pthread_create( &p_thrd[i], 0, Car , (void *)(&directions[i]));
if(thrCheck){
fprintf(stderr,"Error - pthread_create() return code: %d\\n",thrCheck);
exit(1);
}
}
pthread_mutex_lock(&mtxend);
pthread_mutex_destroy(&mtxend);
pthread_mutex_destroy(&leftDir);
pthread_mutex_destroy(&rightDir);
pthread_mutex_destroy(&mtxCheck);
pthread_mutex_destroy(&mtxExit);
free (p_thrd);
return 0;
}
void EnterCar(char *CarDir){
carsPassed--;
printf ("%c car on bridge\\n",*CarDir);
if ((carsPassed!=0)&&(currDir=='l')){
pthread_mutex_unlock (&leftDir);
}
else if ((carsPassed!=0)&&(currDir=='r')){
pthread_mutex_unlock (&rightDir);
}
}
void ExitCar(char *CarDir){
pthread_mutex_lock (&mtxExit);
printf ("%c car leaving bridge\\n", *CarDir);
carsleft++;
if (*CarDir=='l'){
countl--;}
if (*CarDir=='r'){
countr--;
}
if (countl==0){
currDir='r';
flag=1;
}
if (countr==0){
currDir='l';
flag=1;
}
if (flag==0){
if ((carsleft==5)&&(currDir=='r')){
carsleft=0;
carsPassed= 5;
printf("ADEIASMA\\n");
if (countl>0){
currDir='l';
pthread_mutex_unlock(&leftDir);}
}
if ((carsleft==5)&&(currDir=='l')){
carsleft=0;
carsPassed= 5;
printf("ADEIASMA\\n");
if (countr>0){
currDir='r';
pthread_mutex_unlock(&rightDir);
}
}
}else {
if (carsleft==5){
carsleft=0;
carsPassed= 5;
if ((currDir=='r')){
pthread_mutex_unlock(&rightDir);
}else if(carsleft!=5){
pthread_mutex_unlock(&leftDir);
}
printf("ADEIASMA\\n");
}
}
pthread_mutex_unlock (&mtxExit);
}
void * Car(void* carDir){
char * CarDir;
CarDir =(char*)carDir;
pthread_mutex_lock (&mtxCheck);
if (startflag==0){
if ('r'== *CarDir){
currDir='r';
pthread_mutex_lock (&leftDir);
}
else if ('l'== *CarDir){
currDir='l';
pthread_mutex_lock (&rightDir);
}
startflag=1;
}
pthread_mutex_unlock (&mtxCheck);
if ('r'== *CarDir){
pthread_mutex_lock (&rightDir);
}
if ('l'== *CarDir){
pthread_mutex_lock(&leftDir);
}
EnterCar (CarDir);
ExitCar (CarDir);
if ((countl==0) && (countr==0)){
pthread_mutex_unlock (&mtxend);
}
return (carDir);
}
| 0
|
#include <pthread.h>
int _N_BUFFER = 0;
struct node {
size_t node_size;
node* next;
};
node* head;
node* tail;
char init;
} llist;
char* buff;
pthread_mutex_t mutex;
size_t b_size;
int m_size;
int n_msg;
llist list;
} mtb_struct;
int mtb_num_msg(int buf_index);
int mt_buffer_init(size_t size);
int mtb_enqueue(int buf_index, size_t size, void *addr);
int mtb_dequeue(int index,void** addr, size_t *ret_size);
void* mtb_get_buffer(int index);
static int enqueue(int index, size_t size, void* addr);
static int first_msg(int index, size_t size, void *addr);
static size_t pop_node_check_n_msg(int index);
static void pop_data(int index, char* addr, size_t size);
size_t peek(int index);
mtb_struct* mtbs;
int mt_buffer_init(size_t size){
if(_N_BUFFER==0){
mtbs = malloc(sizeof(mtb_struct));
mtbs[0].buff = malloc(sizeof(char)*size);
mtbs[0].b_size = size;
mtbs[0].list.init = 0;
_N_BUFFER++;
pthread_mutex_init(&(mtbs[0].mutex),0);
}
else if(_N_BUFFER>0){
mtbs = realloc(mtbs,(sizeof(mtb_struct)*(_N_BUFFER+1)));
_N_BUFFER++;
mtbs[_N_BUFFER-1].buff = malloc(sizeof(char)*size);
mtbs[_N_BUFFER-1].b_size = size;
mtbs[_N_BUFFER-1].list.init = 0;
pthread_mutex_init(&(mtbs[_N_BUFFER-1].mutex),0);
}
return (_N_BUFFER-1);
}
int mtb_enqueue(int index, size_t size, void *addr){
int ret = -1;
if(index >= _N_BUFFER || index < 0 ){
ret = -1;
}
else{
pthread_mutex_lock(&(mtbs[index].mutex));
if(mtbs[index].m_size+size <= mtbs[index].b_size){
ret = enqueue(index,size,addr);
}
pthread_mutex_unlock(&(mtbs[index].mutex));
}
return ret;
}
static int enqueue(int index, size_t size, void* addr){
int ret = -1;
if (mtbs[index].n_msg == 0){
ret = first_msg(index,size,addr);
}
else{
node *last = mtbs[index].list.tail;
node *temp;
temp = malloc(sizeof(node));
temp->node_size = size;
last->next = temp;
mtbs[index].list.tail = temp;
char *ptr;
ptr = mtbs[index].buff;
ptr += mtbs[index].m_size;
memcpy(ptr,addr,size);
mtbs[index].m_size += size;
mtbs[index].n_msg++;
ret = mtbs[index].n_msg;
}
return ret;
}
int mtb_dequeue(int index,void **addr, size_t *ret_size){
int ret = -1;
*ret_size = 0;
if(index >= _N_BUFFER || index < 0 ){
ret = -1;
}
else{
pthread_mutex_lock(&(mtbs[index].mutex));
int pop_size = pop_node_check_n_msg(index);
if( pop_size > 0 ){
char* msg;
msg = malloc(pop_size);
pop_data(index,msg,pop_size);
*addr = msg;
*ret_size = pop_size;
ret = 1;
}
pthread_mutex_unlock(&(mtbs[index].mutex));
}
return ret;
}
static void pop_data(int index, char* addr, size_t size){
memcpy(addr,mtbs[index].buff,size);
size_t slide = mtbs[index].m_size - size;
memmove(mtbs[index].buff,(mtbs[index].buff+size),slide);
mtbs[index].m_size -= size;
}
size_t peek(int index){
size_t ret = 0;
if(index >= _N_BUFFER || index < 0 ){
ret = 0;
}
else {
pthread_mutex_lock(&(mtbs[index].mutex));
if(mtbs[index].n_msg > 0) {
ret = mtbs[index].list.head->node_size;
}
pthread_mutex_unlock(&(mtbs[index].mutex));
}
return ret;
}
static size_t pop_node_check_n_msg(int index){
size_t ret = 0;
node* pop;
if(mtbs[index].n_msg > 0 ){
pop = mtbs[index].list.head;
if (mtbs[index].n_msg > 1){
mtbs[index].list.head = pop->next;
}
mtbs[index].n_msg--;
ret = pop->node_size;
free(pop);
}
return ret;
}
static int first_msg(int index, size_t size, void *addr){
memcpy(mtbs[index].buff,addr,size);
mtbs[index].n_msg = 1;
mtbs[index].m_size = size;
node * temp;
temp = malloc(sizeof(node));
temp->node_size = size;
mtbs[index].list.head = temp;
mtbs[index].list.tail = temp;
mtbs[index].list.init = 1;
return 1;
}
int mtb_num_msg(int index){
int ret = -1;
if(index >= _N_BUFFER || index < 0 ){
ret = -1;
printf("I %d\\n",ret);
}
else{
ret = mtbs[index].n_msg;
printf("I %d\\n",ret);
}
return ret;
}
void* mtb_get_buffer(int index){
if(index >= _N_BUFFER || index < 0 ){
return 0;
}
else{
return mtbs[index].buff;
}
}
| 1
|
#include <pthread.h>
int threadsNum;
char *fileName;
int recordsNum;
char *searched;
int file;
int signr;
pthread_t *threads;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *threadFunction(void *);
void signalHandler(int signal) {
printf("PID: %d TID: %ld received signal no %d\\n", getpid(), pthread_self(), signal);
return;
}
int main(int argc, char *argv[]) {
fileName = (char *)malloc(MAXFILENAME * sizeof(char));
searched = (char *) malloc(MAXSEARCH * sizeof(char));
if (argc != 6) {
printf("Wrong arguments! Threads number, file name, number of records, searched word required and signal number\\n");
return 1;
}
threadsNum = atoi(argv[1]);
fileName = argv[2];
recordsNum = atoi(argv[3]);
searched = argv[4];
signr = atoi(argv[5]);
if ((file = open(fileName, O_RDONLY)) == -1) {
printf("Error while open a file\\n");
return 2;
}
threads = (pthread_t *)malloc(threadsNum * sizeof(pthread_t));
for (int i = 0; i < threadsNum; i++) {
if (pthread_create(&threads[i], 0, threadFunction, 0) != 0) {
printf("pthread_create(): %d: %s\\n", errno, strerror(errno));
exit(-1);
}
}
pthread_kill(threads[0], signr);
for (int i = 0; i < threadsNum; i++) {
pthread_join(threads[i], 0);
}
free(threads);
close(file);
return 0;
}
void * threadFunction(void *unused) {
signal(SIGUSR1, SIG_IGN);
signal(SIGTERM, SIG_IGN);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
sleep(1);
char **readRecords = calloc(recordsNum, sizeof(char *));
for (int i = 0; i < recordsNum; i++) {
readRecords[i] = calloc(1024, sizeof(char));
}
char *num = (char *) malloc(MAXIDDIGITS * sizeof(char));
pthread_mutex_lock(&mutex);
for (int i = 0; i < recordsNum; i++) {
if (read(file, readRecords[i], BUFFERSIZE) == -1) {
printf("read(): %d: %s\\n", errno, strerror(errno));
exit(-1);
}
}
pthread_mutex_unlock(&mutex);
for (int i = 0; i < recordsNum; i++) {
if (strstr(readRecords[i], searched) != 0) {
strncpy(num, readRecords[i], MAXIDDIGITS);
printf("Thread with TID=%ld: found word in record number %d\\n", pthread_self(), atoi(num));
for (int j = 0; j < threadsNum; j++) {
if (threads[j] != pthread_self()) {
pthread_cancel(threads[j]);
}
}
break;
}
}
return 0;
}
| 0
|
#include <pthread.h>
void manual_conflict_resolution(struct FileSector *obj1, char contents[], int conflict_choice);
void all_or_nothing_get(char file_to_read[])
{
char read_cmd[MAX];
struct FileSector obj1;
int ret = 1;
int conflict_choice=0;
char temp[MAX];
char contents_s1[MAX];
char contents_s2[MAX];
char contents_s3[MAX];
find_sectors(file_to_read, &obj1);
compute_md5sum(&obj1);
pthread_mutex_lock(&lock);
if(!strcmp(obj1.cs1, obj1.cs2))
{
printf("\\n\\n************************************************************************\\n\\n");
sprintf(read_cmd, "cat %s", obj1.fs1);
ret = system(read_cmd);
printf("\\n\\n************************************************************************\\n\\n");
if(ret != 0)
{
printf("Failure Reading from Sector\\n");
}
else
{
printf("Read Successful\\n");
}
pthread_mutex_unlock(&lock);
}
else if (!strcmp(obj1.cs2, obj1.cs3))
{
printf("\\n\\n************************************************************************\\n\\n");
sprintf(read_cmd, "cat %s", obj1.fs3);
ret = system(read_cmd);
printf("\\n\\n************************************************************************\\n\\n");
if(ret != 0)
{
printf("Failure Reading from Sector\\n");
}
else
{
printf("Read Successful\\n");
}
pthread_mutex_unlock(&lock);
}
else
{
printf("\\n\\n***Warning! An error might have occured during last Write operation***\\n\\n");
printf("\\n\\nPlease resolve the conflict manually from among the following options :\\n\\n");
struct last_transaction lt;
lt = search_log_record_entry(file_to_read);
if(!strcmp(lt.status, "pending"))
{
memset(temp, 0, MAX);
memset(contents_s1, 0, MAX);
printf("---------------------------------------------------------------------------------------------\\n");
printf("\\nContents of Sector 1\\n");
printf("---------------------------------------------------------------------------------------------\\n");
sprintf(read_cmd, "cat %s", obj1.fs1);
FILE *ls1 = popen(read_cmd, "r");
while(fgets(temp, sizeof(temp), ls1) != 0)
{
strcat(contents_s1, temp);
}
pclose(ls1);
printf("%s", contents_s1);
memset(temp, 0, MAX);
memset(contents_s2, 0, MAX);
printf("----------------------------------------------------------------------------------------------\\n");
printf("\\nContents of Sector 2\\n");
printf("----------------------------------------------------------------------------------------------\\n");
sprintf(read_cmd, "cat %s", obj1.fs2);
ls1 = popen(read_cmd, "r");
while(fgets(temp, sizeof(temp), ls1) != 0)
{
strcat(contents_s2, temp);
}
pclose(ls1);
printf("%s", contents_s2);
memset(temp, 0, MAX);
memset(contents_s3, 0, MAX);
printf("-----------------------------------------------------------------------------------------------\\n");
printf("\\nContents of Sector 3\\n");
printf("-----------------------------------------------------------------------------------------------\\n");
sprintf(read_cmd, "cat %s", obj1.fs3);
ls1 = popen(read_cmd, "r");
while(fgets(temp, sizeof(temp), ls1) != 0)
{
strcat(contents_s3, temp);
}
pclose(ls1);
printf("%s", contents_s3);
printf("***********************************************************************************************\\n");
while(1)
{
printf("\\nSelect a sector to resolve conflict - Enter 1, 2 or 3\\n");
scanf("%d", &conflict_choice);
if(conflict_choice <1 || conflict_choice >3)
{
printf("Invalid choice. Pick Again. Enter 1, 2 or 3\\n");
}
else
{
if(conflict_choice == 1)
{
manual_conflict_resolution(&obj1, contents_s1, conflict_choice);
}
else if(conflict_choice == 2)
{
manual_conflict_resolution(&obj1, contents_s2, conflict_choice);
}
else if(conflict_choice == 3)
{
manual_conflict_resolution(&obj1, contents_s3, conflict_choice);
}
break;
}
}
pthread_mutex_unlock(&lock);
add_log_record_entry(lt.operation, "commit", lt.fname, lt.tid);
add_log_record_entry(lt.operation,"end", lt.fname, lt.tid);
}
}
}
void manual_conflict_resolution(struct FileSector *obj1, char contents[], int conflict_choice)
{
int ret;
char conflict_cmd[MAX];
if(conflict_choice == 1)
{
sprintf(conflict_cmd, "echo '%s' > %s", contents, obj1->fs2);
ret = system(conflict_cmd);
memset(conflict_cmd, 0, MAX);
sprintf(conflict_cmd, "echo '%s' > %s", contents, obj1->fs3);
ret = system(conflict_cmd);
}
else if(conflict_choice == 2)
{
sprintf(conflict_cmd, "echo -e \\'%s\\' > %s", contents, obj1->fs1);
ret = system(conflict_cmd);
memset(conflict_cmd, 0, MAX);
sprintf(conflict_cmd, "echo '%s' > %s", contents, obj1->fs3);
ret = system(conflict_cmd);
}
else if(conflict_choice == 3)
{
sprintf(conflict_cmd, "echo '%s' > %s", contents, obj1->fs1);
ret = system(conflict_cmd);
memset(conflict_cmd, 0, MAX);
sprintf(conflict_cmd, "echo '%s' > %s", contents, obj1->fs2);
ret = system(conflict_cmd);
}
}
| 1
|
#include <pthread.h>
int philoNum[] = {0,1,2,3,4};
int semID;
pthread_mutex_t chopsticks[5];
int randomGaussian_r(int mean, int stddev, unsigned int* state) {
double mu = 0.5 + (double) mean;
double sigma = fabs((double) stddev);
double f1 = sqrt(-2.0 * log((double) rand_r(state) / (double) 32767));
double f2 = 2.0 * 3.14159265359 * (double) rand_r(state) / (double) 32767;
if (rand_r(state) & (1 << 5))
return (int) floor(mu + sigma * cos(f2) * f1);
else
return (int) floor(mu + sigma * sin(f2) * f1);
}
void* activity(void *philoNum)
{
int id = *(int*)philoNum;
int chopLeft = id;
int chopRight = (id+1)%4;
int temp;
int nomTime = 0;
int thinkTime = 0;
while(nomTime<100)
{
pthread_mutex_lock(&chopsticks[id]);
if(!pthread_mutex_trylock(&chopsticks[chopRight])==0)
{
pthread_mutex_unlock(&chopsticks[id]);
temp = abs(randomGaussian_r(1, 5, (unsigned int*) philoNum));
printf("Philosopher %d is thinking for %d seconds\\n",id,temp);
sleep(temp);
}
else
{
temp = abs(randomGaussian_r(9,3, (unsigned int*) philoNum));
nomTime += temp;
printf("Philosopher %d is eating for %d seconds\\n",id,temp);
sleep(temp);
pthread_mutex_unlock(&chopsticks[id]);
pthread_mutex_unlock(&chopsticks[chopRight]);
temp = abs(randomGaussian_r(11,7, (unsigned int*) philoNum));
printf("Philosopher %d is thinking for %d seconds\\n",id,temp);
sleep(temp);
}
}
printf("Philosopher %d has left the table\\n",id);
return 0;
}
int main (void)
{
int i, rd;
int pid;
pthread_t philosopher[5];
for(i = 0; i < 5; i++)
{
if(pthread_mutex_init(&chopsticks[i], 0) != 0)
printf("Failed to initialize mutex\\n");
}
for(i = 0; i < 5; i++)
{
if(pthread_create(&philosopher[i], 0, activity, (void *) &philoNum[i]) != 0)
printf("Failed to initialize thread\\n") ;
}
for(i = 0; i < 5; i++)
{
pthread_join(philosopher[i], 0);
}
for(i = 0; i < 5; i++)
{
pthread_mutex_destroy(&chopsticks[i]);
}
return 0;
}
| 0
|
#include <pthread.h>
void *pooling(void* argp) {
int i, queue_size;
char *path;
struct Return_values *rvalues;
struct Thread_args *args_pool = (struct Thread_args*) argp;
queue_size = args_pool->queue_size;
while (1) {
pthread_mutex_lock(&mtx);
while(count(queue_size) == -1) {
pthread_cond_wait(&cond_nonempty, &mtx);
}
rvalues = removeFromQueue(queue_size);
pthread_mutex_unlock(&mtx);
pthread_cond_signal(&cond_nonfull);
pthread_mutex_lock(rvalues->mtx);
sendResponse(rvalues->newsock, rvalues->path);
pthread_mutex_unlock(rvalues->mtx);
free(rvalues->path);
free(rvalues);
}
}
void sendResponse(int newsock, char *path) {
int length, nread, fd, file_size, bla = 1;
char temp;
length = strlen(path) + 1;
if (write(newsock, &length, sizeof(int)) < 0) {
perror("write");
}
if (write(newsock, path, length) < 0) {
perror("write");
}
if ((fd = open(path, O_RDONLY)) < 0) {
perror("open");
exit (1) ;
}
long size = sysconf (_SC_PAGESIZE);
send_data(newsock, fd, size);
}
void send_data(int newsock, int fd, int size) {
long file_size;
int counter=0;
struct stat statbuf;
fstat(fd, &statbuf);
file_size = statbuf.st_size;
write(newsock, &file_size, sizeof(long));
while(1) {
char buff[size];
int nread = read(fd, buff, size);
counter = counter + nread;
if(nread > 0) {
buff[nread] = '\\0';
write(newsock, buff, size);
}
buff[0] = '\\0';
if (nread == 0) {
break;
}
}
printf("READ : %d\\n", counter);
close(fd);
}
| 1
|
#include <pthread.h>
int num_threads;
pthread_t p_threads[65536];
pthread_attr_t attr;
pthread_mutex_t lock_barrier;
int list[200000000];
int list_size;
int prefix_sum_list[200000000];
int mylist_sum[65536];
int wait_list[65536];
void *prefix_sum (void *s) {
int j, sum, offset;
int thread_id = (int) s;
int chunk_size = list_size/num_threads;
int my_start = thread_id*chunk_size;
int my_end = (thread_id+1)*chunk_size-1;
if (thread_id == num_threads-1) my_end = list_size-1;
sum = list[my_start];
prefix_sum_list[my_start] = sum;
for (j = my_start + 1; j <= my_end; j++) {
sum += list[j];
prefix_sum_list[j] = sum;
}
mylist_sum[thread_id] = sum;
if (thread_id > 0) {
while(wait_list[thread_id-1] != 1) {
struct timespec sleeptime;
sleeptime.tv_sec = 0.0; sleeptime.tv_nsec = 10;
nanosleep(&sleeptime, 0);
}
pthread_mutex_lock(&lock_barrier);
offset = mylist_sum[0];
for (j = 1; j <= thread_id - 1; j++) {
offset += mylist_sum[j];
}
for(j = my_start; j <= my_end; j++) {
prefix_sum_list[j] += offset;
}
pthread_mutex_unlock(&lock_barrier);
}
wait_list[thread_id] = 1;
pthread_exit(0);
}
int main(int argc, char *argv[]) {
struct timeval start, stop;
double total_time;
int i, j;
int error;
if (argc != 3) {
printf("Need two integers as input \\n");
printf("Use: <executable_name> <list_size> <num_threads>\\n");
exit(0);
}
if ((list_size = atoi(argv[argc-2])) > 200000000) {
printf("Maximum list size allowed: %d.\\n", 200000000);
exit(0);
};
if ((num_threads = atoi(argv[argc-1])) > 65536) {
printf("Maximum number of threads allowed: %d.\\n", 65536);
exit(0);
};
if (num_threads > list_size) {
printf("Number of threads (%d) < list_size (%d) not allowed.\\n", num_threads, list_size);
exit(0);
};
pthread_mutex_init(&lock_barrier, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
unsigned int seed = 0;
srand(seed);
for (j = 0; j < list_size; j++) list[j] = rand_r(&seed) % 10;
gettimeofday(&start, 0);
for (i = 0; i < num_threads; i++) {
pthread_create(&p_threads[i], &attr, prefix_sum, (void * )i);
}
for (i = 0; i < num_threads; i++) {
pthread_join(p_threads[i], 0);
}
gettimeofday(&stop, 0);
total_time = (stop.tv_sec-start.tv_sec)
+0.000001*(stop.tv_usec-start.tv_usec);
error = 0;
if (list[0] != prefix_sum_list[0]) error = 1;
for (j = 1; j < list_size; j++) {
if (list[j] != (prefix_sum_list[j]-prefix_sum_list[j-1])) error = 1;
if (prefix_sum_list[j] < 0) {
printf("switch over %d at j %d", prefix_sum_list[j], j);
break;
}
}
if (error) {
printf("Houston, we have a problem!\\n");
exit(0);
} else {
printf("Congratulations. Prefix sum computed correctly\\n");
}
printf("Threads = %d, list size = %d, time (sec) = %8.4f\\n",
num_threads, list_size, total_time);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&lock_barrier);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex_bano = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_hom = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_fem = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_hom = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_fem = PTHREAD_COND_INITIALIZER;
int personas_dentro = 0;
int espera_mujeres = 0;
int espera_hombres = 0;
int estado = 0;
void fem_busca();
void hom_busca();
void fem_sale();
void hom_sale();
void *mujer();
void *hombre();
int main(){
printf("Baño vacio\\n");
pthread_t *hombres_t = (pthread_t*)malloc(4*sizeof(pthread_t));
pthread_t *mujeres_t = (pthread_t*)malloc(4*sizeof(pthread_t));
int i;
for (i = 0; i<4; ++i){
pthread_create(mujeres_t+i,0,mujer,0);
pthread_create(hombres_t+i,0,hombre,0);
}
sleep(5);
srand(time(0));
int sexo;
pthread_t *random_t = (pthread_t*)malloc(8*sizeof(pthread_t));
for (i=0;i<8;++i){
sexo = rand() % 2;
if (sexo == 0)
pthread_create(random_t+i,0,mujer,0);
else
pthread_create(random_t+i,0,hombre,0);
}
for (i=0;i<4;++i){
pthread_join(*(hombres_t+i),0);
pthread_join(*(mujeres_t+i),0);
}
for (i=0;i<8;++i){
pthread_join(*(random_t+i),0);
}
free(hombres_t);
free(mujeres_t);
free(random_t);
return 0;
}
void *mujer(){
fem_busca();
sleep(3);
fem_sale();
pthread_exit(0);
}
void fem_busca(){
pthread_mutex_lock(&mutex_fem);
printf("Llega mujer, %d en espera\\n",++espera_mujeres);
pthread_mutex_unlock(&mutex_fem);
int listo = 0;
while (!listo){
pthread_mutex_lock(&mutex_bano);
if (estado == 2){
pthread_cond_wait(&cond_fem,&mutex_bano);
}
if (estado == 0){
estado = 1;
printf("Entra mujer, %d espera\\n",--espera_mujeres);
++personas_dentro;
printf("Baño ocupado por mujeres\\n");
listo = 1;
}
else if (estado == 1) {
printf("Entra mujer, %d espera\\n",--espera_mujeres);
++personas_dentro;
listo = 1;
}
pthread_mutex_unlock(&mutex_bano);
}
}
void fem_sale(){
pthread_mutex_lock(&mutex_bano);
printf("Sale mujer\\n");
--personas_dentro;
if (personas_dentro == 0){
estado = 0;
pthread_cond_broadcast(&cond_hom);
printf("Baño vacio\\n");
}
pthread_mutex_unlock(&mutex_bano);
}
void *hombre(){
hom_busca();
sleep(2);
hom_sale();
pthread_exit(0);
}
void hom_busca(){
pthread_mutex_lock(&mutex_hom);
printf("Llega hombre, %d espera\\n",++espera_hombres);
pthread_mutex_unlock(&mutex_hom);
int listo = 0;
while (!listo){
pthread_mutex_lock(&mutex_bano);
if (estado == 1){
pthread_cond_wait(&cond_hom,&mutex_bano);
}
if (estado == 0){
estado = 2;
printf("Entra hombre, %d espera\\n",--espera_hombres);
++personas_dentro;
printf("Baño ocupado por hombres\\n");
listo = 1;
}
else if (estado == 2){
printf("Entra hombre, %d en espera\\n",--espera_hombres);
++personas_dentro;
listo = 1;
}
pthread_mutex_unlock(&mutex_bano);
}
}
void hom_sale(){
pthread_mutex_lock(&mutex_bano);
--personas_dentro;
printf("Sale hombre\\n");
if (personas_dentro == 0){
estado = 0;
pthread_cond_broadcast(&cond_fem);
printf("Baño vacio\\n");
}
pthread_mutex_unlock(&mutex_bano);
}
| 1
|
#include <pthread.h>
double pe_final;
double *a;
double *b;
pthread_mutex_t gate;
pthread_mutex_t S;
int count = 8;
void *semgeral(void *threadarg)
{
pthread_mutex_lock(&gate);
pthread_mutex_lock(&S);
count -= 1;
if(count>0)
{
pthread_mutex_unlock(&gate);
}
pthread_mutex_unlock(&S);
printf("Critical Section %ld\\n",(intptr_t)threadarg);
printf("Critical Section %ld\\n",(intptr_t)threadarg);
sleep(1);
printf("Critical Section %ld\\n",(intptr_t)threadarg);
pthread_mutex_lock(&S);
count+=1;
if(count==1)
{
pthread_mutex_unlock(&gate);
}
pthread_mutex_unlock(&S);
}
int main(int argc, char *argv[]){
int j,t,cj=0,rc;
pthread_t th[8];
struct timeval inicio, final2;
gettimeofday(&inicio, 0);
pthread_mutex_unlock(&gate);
pthread_mutex_unlock(&S);
for(j=0;j<8;j++){
rc = pthread_create(&(th[j]),0, &semgeral,(void* )(intptr_t) j);
if(rc){
printf("ERROR,%d",rc);
exit(-1);
}
}
for(j=0; j<8; j++) {
rc = pthread_join(th[j],0);
if(rc){
printf("ERROR,%d",rc);
exit(-1);
}
}
gettimeofday(&final2, 0);
printf("%lf\\n",pe_final);
printf("%lf:milisegundos",(double) (1000.0 * (final2.tv_sec - inicio.tv_sec) + (final2.tv_usec - inicio.tv_usec) / 1000.0));
return 0;
}
| 0
|
#include <pthread.h>
void
lvm_pool_init(struct lvm_pool *pool) {
pool->head = pool->tail = 0;
pool->sleep = 0;
pthread_mutex_init(&pool->mutex, 0);
pthread_cond_init(&pool->cond, 0);
}
void
lvm_pool_destroy(struct lvm_pool *pool) {
pthread_cond_broadcast(&pool->cond);
if (pthread_mutex_lock(&pool->mutex) == 0) {
while (pool->head != pool->tail) {
int head = pool->head;
pool->head = (pool->head + 1) % LVM_POOL_MAX;
lua_close(pool->queue[head].L);
}
pthread_mutex_unlock(&pool->mutex);
}
pthread_mutex_destroy(&pool->mutex);
pthread_cond_destroy(&pool->cond);
}
int
lvm_pool_count(struct lvm_pool* pool) {
int count = pool->tail - pool->head;
count = count < 0 ? LVM_POOL_MAX + count : count;
return count;
}
void
lvm_pool_add(struct lvm_pool* pool, struct lvm vm) {
pool->queue[pool->tail] = vm;
__sync_synchronize();
pool->tail = (pool->tail + 1) % LVM_POOL_MAX;
if (pool->sleep && lvm_pool_count(pool) > 10) {
pthread_cond_signal(&pool->cond);
}
}
int
lvm_pool_remove(struct lvm_pool* pool, struct lvm* vm) {
if (pool->head == pool->tail)
return QS_NOK;
*vm = pool->queue[pool->head];
pool->queue[pool->head].L = 0;
pool->head = (pool->head + 1) % LVM_POOL_MAX;
return QS_OK;
}
int
lvm_pool_remove_wait(struct lvm_pool* pool, struct lvm* vm, int seconds) {
int result = lvm_pool_remove(pool, vm);
if (result == QS_OK)
return result;
if (pthread_mutex_lock(&pool->mutex) == 0) {
struct timeval now;
struct timespec timeout;
result = lvm_pool_remove(pool, vm);
if(result == QS_OK) {
pthread_mutex_unlock(&pool->mutex);
return result;
}
gettimeofday(&now,0);
timeout.tv_sec = now.tv_sec + seconds;
timeout.tv_nsec = now.tv_usec * 1000;
pool->sleep = 1;
pthread_cond_timedwait(&pool->cond, &pool->mutex, &timeout);
pool->sleep = 0;
pthread_mutex_unlock(&pool->mutex);
}
return lvm_pool_remove(pool, vm);
}
| 1
|
#include <pthread.h>
void createTask(struct Writer *w){
int sleepTime = 100;
int prio = (int) ((double)rand() * (long)w->queue->NumPriorities / ((double) 32767 +1));
struct Task *t;
t = malloc(sizeof(struct Task));
t->id = w->task_id;
w->task_id = w->task_id +1;
t->nextTask = 0;
t->priority = prio;
pthread_mutex_lock(&mutex);
addTaskToQueue(w->queue, t);
pthread_mutex_unlock(&mutex);
printf("Writer %02d: Created task with priority %d, id:%05d\\n",w->id,prio,t->id);
if((sleepTime = (int)((prio/w->queue->NumPriorities) * 300)) < 100 )
sleepTime = 100;
usleep(sleepTime * 1000);
}
void createTasks(struct Writer *w){
while(run == TRUE){
createTask(w);
}
}
| 0
|
#include <pthread.h>
struct foo
{
int a,b,c,d;
pthread_mutex_t lock;
};
struct foo foo = {1,2,3,4};
int i =0;
void printfoo(const char *s,const struct foo *fp)
{
printf("%s\\n",s );
printf("struct at 0x%lx\\n",(unsigned long)fp );
printf("foo.a=%d\\n", fp->a);
printf("foo.b=%d\\n", fp->b);
printf("foo.c=%d\\n", fp->c);
printf("foo.d=%d\\n", fp->d);
}
void * fn1(void * arg)
{
pthread_mutex_lock(&foo.lock);
printfoo("thread1:\\n",&foo);
printf("thread1:%d\\n", i);
i++;
pthread_mutex_unlock(&foo.lock);
pthread_exit((void *)&foo);
}
void * fn2(void * arg)
{
printf("thread2:%lu\\n",(unsigned long)pthread_self());
printfoo("thread2:\\n",&foo);
printf("thread2:%d\\n", i);
i++;
pthread_exit((void *)0);
}
int main(int argc, char const *argv[])
{
int err = 0;
pthread_t tid1,tid2;
void * ret =0;
struct foo *fp;
fp =( struct foo *)calloc(sizeof(struct foo),1);
err = pthread_mutex_init(&fp->lock,0);
if(err){
free(fp);
}
err = pthread_create(&tid1,0,fn1,0);
if (err!=0)
{
perror("not create thread1");
}else{
printf("thread1:%d\\n", i);
}
err = pthread_join(tid1,&ret);
if (err!=0)
{
perror("not join thread1");
}else{
printf("the thread1 return code ;%d\\n", err);
}
sleep(1);
printf("parent starting second thread2\\n");
err = pthread_create(&tid2,0,fn2,0);
if (err!=0)
{
perror("not create thread2");
}else{
printf("thread2:%d\\n", i);
}
printf("main 1 thread:%d\\n", i);
err = pthread_join(tid2,(void *)&fp);
if (err!=0)
{
perror("not join thread2");
}else{
printf("the thread2 return code ;%d\\n", err);
}
printf("main 2 thread:%d\\n", i);
sleep(1);
printf("main 3 thread:%d\\n", i);
return 0;
}
| 1
|
#include <pthread.h>
sem_t full,empty;
int * applicants;
int peps=0;
int noOfLine;
int regDur;
int regs=0;
pthread_mutex_t mutex[3];
void* registerP() {
while(1) {
sem_wait(&empty);
printf("Applicant %d applied to receptionist.\\n", regs+1);
sleep(regDur);
printf("Applicant %d's registration is done.\\n",regs+1);
regs++;
sem_post(&full);
sleep(1);
if(regs==noOfLine){
pthread_exit(0);
break;}
}
pthread_exit(0);
}
void* interview(void *i) {
while(1) {
int m=(intptr_t)i;
sem_wait(&full);
pthread_mutex_lock(&mutex[m]);
peps++;
long id=(long)i+1;
printf("Interviewer %ld started interview with Applicant %d\\n", id,peps);
int current=peps;
sleep(applicants[current-1]);
printf("Interviewer %ld finished interview with Applicant %d\\n", id,current);
pthread_mutex_unlock(&mutex[m]);
sleep(1);
if(current==noOfLine)
{
pthread_exit(0);
break;
}
}
pthread_exit(0);
}
int main(int argc, char *argv[]) {
char * fname=argv[1];
FILE *myFile = fopen(fname,"r");
regDur=atoi(argv[2]);
noOfLine=0;
char cont;
if(myFile==0)
printf("error");
while(!feof(myFile)){
cont=fgetc(myFile);
if(cont=='\\n'){
noOfLine++;
}
}
noOfLine--;
applicants=(int*)malloc(noOfLine*sizeof(int));
rewind(myFile);
int read;
int a;
for(a=0;a<noOfLine;a++){
fscanf(myFile,"%d",&applicants[a]);
}
sem_init(&full,1,0);
sem_init(&empty,1,noOfLine);
pthread_mutex_init(&mutex[0],0);
pthread_mutex_init(&mutex[1],0);
pthread_mutex_init(&mutex[2],0);
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
pthread_t recepcionist, interviewer[3];
pthread_create(&recepcionist, &attr, registerP,0);
pthread_create(&interviewer[0], &attr, interview, (void*)(intptr_t)0);
pthread_create(&interviewer[1], &attr, interview, (void*)(intptr_t)1);
pthread_create(&interviewer[2], &attr, interview, (void*)(intptr_t)2);
pthread_join(interviewer[2], 0);
pthread_join(interviewer[1], 0);
pthread_join(interviewer[0], 0);
pthread_join(recepcionist, 0);
pthread_exit(0);
if(regs==noOfLine)
printf("All applicants have been interviewed succesfully\\n");
free(applicants);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mtx_lock;
int main(int argc, char **argv) {
host *thisHost;
host *nextHost;
dataContainer *dataTransfer;
struct addrinfo *res;
char* sendBuffer = (char*) calloc(100, sizeof(char));
int election = 1;
int *mode = &election;
int newMessage = 1;
int *gotMessage = &newMessage;
int finished = 1;
int send_socket = -1;
if (argc != 4) {
printWrongParams(argv[0]);
return 1;
}
pthread_mutex_init(&mtx_lock, 0);
nextHost = malloc(sizeof(host));
nextHost->name = argv[2];
nextHost->port = getIntFromStr(argv[3]);
thisHost = malloc(sizeof(host));
thisHost->name = getCurrentHostName();
thisHost->port = getIntFromStr(argv[1]);
dataTransfer = malloc(sizeof(dataContainer));
dataTransfer->host = &thisHost;
dataTransfer->finished = &finished;
dataTransfer->sendBuffer = &sendBuffer;
dataTransfer->gotMessage = &gotMessage;
dataTransfer->mode = &mode;
pthread_t listenerThread;
if (pthread_create(&listenerThread, 0, &receiver_init, dataTransfer) < 0) {
perror("Error creating listener-thread");
return 1;
}
res = get_server_address(nextHost);
send_socket = setup_send_socket();
int connected = -1;
createElectionMessage(argv[1], &sendBuffer);
while(connected < 0){
connected = connect_to_server(send_socket, nextHost, res);
printf("waiting to get send connection\\n");
sleep(2);
}
send_message(send_socket, res, sendBuffer);
pthread_mutex_lock(&mtx_lock);
*gotMessage = 0;
pthread_mutex_unlock(&mtx_lock);
while(dataTransfer->finished){
if(*gotMessage == 1){
if (*mode == 1){
send_message(send_socket, res, sendBuffer);
} else if (*mode == 2){
send_message(send_socket, res, sendBuffer);
} else if (*mode == 3 || *mode == 4){
send_message(send_socket, res, sendBuffer);
}
pthread_mutex_lock(&mtx_lock);
*gotMessage = 0;
pthread_mutex_unlock(&mtx_lock);
}
}
pthread_join(listenerThread, 0);
free(dataTransfer);
free(thisHost);
free(nextHost);
fprintf(stderr, "Exit-message received, goodbye!\\n");
return 0;
}
void printWrongParams(char *progName) {
fprintf(stderr,
"%s\\n%s %s\\n",
"Invalid parameters",
progName,
"<LISTEN_PORT> <SEND_TO_HOST> <SEND_TO_PORT>");
}
| 1
|
#include <pthread.h> static char rcsId[]="$Id: csda.c,v 0.1 1999/10/27 10:31:28 lanzm Exp $";
extern pthread_mutex_t cs_thread_exit;
extern int cs_threads_should_exit;
void csda_best_node_server_thread(void)
{
int should_exit;
int server_id, client_id;
struct bn_request req;
struct bn_response resp;
char* best_node;
char* app_name;
char* hostname;
int error;
server_id = msgget(7768, S_IRWXU | S_IWGRP | S_IWOTH | IPC_CREAT);
if(server_id == -1) {
cs_log_err(CS_LOG, "csda: unable to create the message queue\\n");
exit(-1);
}
best_node = (char *) malloc(NODE_SIZE * sizeof(char));
app_name = (char *) malloc(APP_SIZE * sizeof(char));
hostname = getenv("HOSTNAME");
for(;;) {
if( msgrcv(server_id, &req, MSQ_MAX_NAME, 0, 0) == -1) {
cs_log_err(CS_LOG, "csda_best_node_server_thread: unable to receive a message\\n");
continue;
}
error = sscanf(req.msg, "%d %s", &client_id, app_name);
error = csda_best_node_for_app(app_name, &best_node);
if(error == -1)
strcpy(best_node, hostname);
cs_log_err(CS_LOG, "best_node is: %s error is: %d\\n", best_node, error);
strcpy(resp.msg, best_node);
resp.mtype = 1;
msgsnd(client_id, &resp, MSQ_MAX_NODE, 0);
pthread_mutex_lock(&cs_thread_exit);
should_exit = cs_threads_should_exit;
pthread_mutex_unlock(&cs_thread_exit);
if(should_exit) {
msgctl(server_id, IPC_RMID, 0);
pthread_exit(0);
}
}
msgctl(server_id, IPC_RMID, 0);
free(best_node);
free(app_name);
}
int csda_register_app(char* app)
{
csc_scan_libs_for_app(app);
csc_update_cap_nodes_for_app(app);
return 0;
}
double csda_calc_bench(char* node)
{
char key[KSIZE];
double load1, load5, load15;
int error;
char* load1_s, *load5_s, *load15_s;
double bench;
bench = 0;
error = 0;
sprintf(key, ".node.%s.load.avg1", node);
error = csdb_get_value_for_key(key, &load1_s);
if(error < 0) return 0;
else {
load1 = atof(load1_s);
free(load1_s);
}
sprintf(key, ".node.%s.load.avg5", node);
error = csdb_get_value_for_key(key, &load5_s);
if(error < 0) return 0;
else {
load5 = atof(load5_s);
free(load5_s);
}
sprintf(key, ".node.%s.load.avg15", node);
error = csdb_get_value_for_key(key, &load15_s);
if(error < 0) return 0;
else {
load15 = atof(load15_s);
free(load15_s);
}
bench = (1/(1+load1)) * 0.7 + (1/(1+load5)) * 0.2 + (1/(1+load15)) * 0.1;
return bench;
}
int csda_best_node_for_app(char* app_name, char** node_name)
{
char* node;
char* cap_nodes_db;
char* cap_nodes;
char key[KSIZE];
char delims[] = " ";
double max_bench, bench;
int error;
sprintf(key, ".app.%s.capnodes", app_name);
if(csdb_key_exist(key))
error = csdb_get_value_for_key(key, &cap_nodes_db);
else
return -1;
if(error < 0)
return -1;
cap_nodes = (char *) malloc((strlen(cap_nodes_db) + 1)*sizeof(char));
strcpy(cap_nodes, cap_nodes_db);
node = strtok(cap_nodes, delims);
max_bench = -1;
while(node != 0) {
if(csc_node_is_alive(node) == 0) {
node = strtok(0, delims);
continue;
}
bench = csda_calc_bench(node);
if(bench > max_bench) {
max_bench = bench;
strcpy(*node_name, node);
}
node = strtok(0, delims);
}
free(cap_nodes_db);
free(cap_nodes);
return max_bench;
}
| 0
|
#include <pthread.h>
static const struct dot_matrix_data empty_dot_data = { .data = { { 0, } } };
struct mode_draw_board_status
{
int output_pipe_fd;
pthread_mutex_t mutex;
bool cur_show;
int cur_pos_x, cur_pos_y;
char cur_val;
struct dot_matrix_data dot_data;
int input_count;
pthread_t background_worker;
bool terminated;
};
static void *background_worker_main (void *arg);
struct mode_draw_board_status *mode_draw_board_construct (int output_pipe_fd)
{
struct mode_draw_board_status *status;
status = malloc (sizeof (*status));
status->output_pipe_fd = output_pipe_fd;
pthread_mutex_init (&status->mutex, 0);
status->cur_show = 1;
status->cur_pos_x = status->cur_pos_y = 0;
status->cur_val = 0;
status->dot_data = empty_dot_data;
status->input_count = 0;
status->terminated = 0;
pthread_create (&status->background_worker, 0, &background_worker_main, status);
return status;
}
void mode_draw_board_destroy (struct mode_draw_board_status *status)
{
atomic_store_bool (&status->terminated, 1);
pthread_join (status->background_worker, 0);
pthread_mutex_destroy (&status->mutex);
free (status);
}
int mode_draw_board_switch (struct mode_draw_board_status *status, union switch_data data)
{
pthread_mutex_lock (&status->mutex);
int next_x = status->cur_pos_x;
int next_y = status->cur_pos_y;
bool invalidated = 0;
if (data.bit_fields.s1)
{
status->cur_show = 1;
next_x = next_y = 0;
status->dot_data = empty_dot_data;
invalidated = 1;
}
if (data.bit_fields.s2)
{
next_y = status->cur_pos_y - 1;
}
if (data.bit_fields.s3)
{
status->cur_show = !status->cur_show;
invalidated = 1;
}
if (data.bit_fields.s4)
{
next_x = status->cur_pos_x - 1;
}
if (data.bit_fields.s5)
{
status->cur_val = (status->cur_val + 1) % 2;
invalidated = 1;
}
if (data.bit_fields.s6)
{
next_x = status->cur_pos_x + 1;
}
if (data.bit_fields.s7)
{
status->dot_data = empty_dot_data;
invalidated = 1;
}
if (data.bit_fields.s8)
{
next_y = status->cur_pos_y + 1;
}
if (data.bit_fields.s9)
{
for (int i = 0; i < DOT_MATRIX_HEIGHT; ++i)
{
for (int j = 0; j < DOT_MATRIX_WIDTH; ++j)
{
if (i == status->cur_pos_y && j == status->cur_pos_x)
continue;
status->dot_data.data[i][j] = (status->dot_data.data[i][j] + 1) % 2;
}
}
status->cur_val = (status->cur_val + 1) % 2;
invalidated = 1;
}
if (0 <= next_x && next_x < DOT_MATRIX_WIDTH &&
0 <= next_y && next_y < DOT_MATRIX_HEIGHT &&
(next_x != status->cur_pos_x || next_y != status->cur_pos_y))
{
status->dot_data.data[status->cur_pos_y][status->cur_pos_x] = status->cur_val;
status->cur_pos_x = next_x;
status->cur_pos_y = next_y;
status->cur_val = status->dot_data.data[status->cur_pos_y][status->cur_pos_x];
invalidated = 1;
}
status->input_count = (status->input_count + 1) % FND_NUMBER_UPPER_BOUND;
if (invalidated)
{
if (!status->cur_show)
status->dot_data.data[status->cur_pos_y][status->cur_pos_x] = status->cur_val;
output_message_dot_matrix_send (status->output_pipe_fd, &status->dot_data);
}
output_message_fnd_send (status->output_pipe_fd, status->input_count);
pthread_mutex_unlock (&status->mutex);
return 0;
}
static void *background_worker_main (void *arg)
{
struct mode_draw_board_status *status = arg;
long long prev_blink_time = get_nano_time () - 2 * (1000*1000*1000);
while (!atomic_load_bool (&status->terminated))
{
long long cur_time = get_nano_time ();
pthread_mutex_lock (&status->mutex);
if (cur_time >= prev_blink_time + (1000*1000*1000) && status->cur_show)
{
LOG (LOGGING_LEVEL_DEBUG, "[Main Process - Background Worker] blink!");
status->dot_data.data[status->cur_pos_y][status->cur_pos_x] =
(status->dot_data.data[status->cur_pos_y][status->cur_pos_x] + 1) % 2;
output_message_dot_matrix_send (status->output_pipe_fd, &status->dot_data);
prev_blink_time = cur_time;
}
pthread_mutex_unlock (&status->mutex);
usleep ((10*1000));
}
return 0;
}
| 1
|
#include <pthread.h>
struct to_info {
void (*to_fn)(void *);
void * to_arg;
struct timespec to_wait;
};
void * timeout_helper(void * arg) {
struct to_info * tip;
tip = (struct to_info *)arg;
nanosleep(&tip->to_wait, 0);
(*tip->to_fn)(tip->to_arg);
return 0;
}
int make_thread(void *(*fn)(void *), void * arg) {
int err;
pthread_t tid;
pthread_attr_t attr;
if((err = pthread_attr_init(&attr)) != 0)
return err;
if(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) == 0)
err = pthread_create(&tid, &attr, fn, arg);
pthread_attr_destroy(&attr);
return err;
}
void timeout(const struct timespec * when, void (*func)(void *), void * arg) {
struct timespec now;
struct to_info * tip;
int err;
clock_gettime(CLOCK_REALTIME, &now);
if(when->tv_sec > now.tv_sec ||
(when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) {
tip =(struct to_info *) malloc(sizeof(struct to_info));
if(tip != 0) {
tip->to_fn = func;
tip->to_arg = arg;
tip->to_wait.tv_sec = when->tv_sec - now.tv_sec;
printf("make detach thread ...\\n");
err = make_thread(timeout_helper, (void *)tip);
if (err == 0)
return;
else
free(tip);
}
}
(*func)(arg);
}
pthread_mutexattr_t attr;
pthread_mutex_t mutex;
void retry(void * arg) {
pthread_mutex_lock(&mutex);
printf("timeout retry...\\n");
pthread_mutex_unlock(&mutex);
}
int main(int argc, char * argv[]) {
int err, condition, arg;
struct timespec when;
if((err = pthread_mutexattr_init(&attr)) != 0)
err_quit("pthread_mutexattr_init failed");
if((err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) != 0)
err_quit("can't set recursive type");
if((err = pthread_mutex_init(&mutex, &attr)) != 0)
err_quit("can't create recursive type");
condition = 1;
arg = 1;
pthread_mutex_lock(&mutex);
if(condition) {
printf("begin setting clock...\\n");
clock_gettime(CLOCK_REALTIME, &when);
when.tv_sec += 10;
timeout(&when, retry, (void *)((unsigned long) arg));
printf("timeout returned...\\n");
}
pthread_mutex_unlock(&mutex);
sleep(20);
printf("main thread exit...\\n");
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t m;
void* thr1(void* arg)
{
int x;
int y;
int z;
x = __VERIFIER_nondet_int(0, 1000);
y = __VERIFIER_nondet_int(0, 1000);
pthread_mutex_lock (&m);
if(x == y)
{
z = 0;
} else {
z = 1;
}
printf ("thr1: x=%d, y=%d, z=%d\\n", x,y,z);
if(z == 0)
{
__VERIFIER_assert (x == y);
} else {
__VERIFIER_assert (x != y);
}
pthread_mutex_unlock (&m);
return 0;
}
int main()
{
pthread_t t[5];
pthread_mutex_init (&m, 0);
int i = 0;
pthread_create (&t[i], 0, thr1, 0); i++;
pthread_create (&t[i], 0, thr1, 0); i++;
pthread_create (&t[i], 0, thr1, 0); i++;
pthread_create (&t[i], 0, thr1, 0); i++;
pthread_create (&t[i], 0, thr1, 0);
return 0;
}
| 1
|
#include <pthread.h>
const char *shm_name = "/my_shm";
{
pthread_cond_t cond;
pthread_mutex_t mutex;
} cond_var;
cond_var fill_cond;
cond_var empty_cond;
pthread_mutex_t sync_mutex;
pthread_t *tid;
volatile int *ptr;
int work;
int shm_fd;
size_t workersNumber;
size_t storageSize;
void* producer(void *args)
{
while(work)
{
int product;
pthread_mutex_lock(&empty_cond.mutex);
while(*ptr == storageSize)
{
pthread_cond_wait(&empty_cond.cond, &empty_cond.mutex);
}
pthread_mutex_lock(&sync_mutex);
product = rand() % 10000;
printf("I put product %d to room %d\\n", product, *ptr+1);
ptr[++*ptr] = product;
if (*ptr == 1)
pthread_cond_signal(&fill_cond.cond);
pthread_mutex_unlock(&sync_mutex);
sleep(1);
pthread_mutex_unlock(&empty_cond.mutex);
}
printf("producer is done\\n");
}
void* consumer(void *args)
{
while(work)
{
pthread_mutex_lock(&fill_cond.mutex);
while(*ptr == 0)
{
pthread_cond_wait(&fill_cond.cond, &fill_cond.mutex);
}
pthread_mutex_lock(&sync_mutex);
printf("I got product %d from room %d\\n", ptr[*ptr], *ptr);
--*ptr;
if (*ptr == 9)
pthread_cond_signal(&empty_cond.cond);
pthread_mutex_unlock(&sync_mutex);
sleep(1);
pthread_mutex_unlock(&fill_cond.mutex);
}
printf("consumer is done\\n");
}
void InitResources()
{
pthread_cond_init(&empty_cond.cond, 0);
pthread_cond_init(&fill_cond.cond, 0);
pthread_mutex_init(&empty_cond.mutex, 0);
pthread_mutex_init(&fill_cond.mutex, 0);
pthread_mutex_init(&sync_mutex, 0);
shm_fd = shm_open(shm_name, O_RDWR | O_CREAT, 0666);
ftruncate(shm_fd, 1024);
}
void DestroyResources()
{
pthread_cond_destroy(&empty_cond.cond);
pthread_cond_destroy(&fill_cond.cond);
pthread_mutex_destroy(&empty_cond.mutex);
pthread_mutex_destroy(&fill_cond.mutex);
pthread_mutex_destroy(&sync_mutex);
shm_unlink(shm_name);
}
void signalHandler(int signal)
{
if (signal == SIGINT)
{
int i;
work = 0;
printf("wait while operations will be complete...\\n");
for(i = 0; i < workersNumber; ++i)
pthread_join(tid[i], 0);
DestroyResources();
exit(-1);
}
}
int main(int argc, char *argv[])
{
if (argc < 4)
{
printf("Usage: prod producerNumber consumerNumber storageCapacity\\n");
return 0;
}
signal(SIGINT, &signalHandler);
work = 1;
int prodNumber, consNumber;
size_t i;
prodNumber = atoi(argv[1]);
consNumber = atoi(argv[2]);
storageSize = atoi(argv[3]);
workersNumber = prodNumber + consNumber;
InitResources();
ptr = mmap(0, 512, PROT_WRITE | PROT_READ, MAP_SHARED, shm_fd, 0);
tid = (pthread_t *)malloc(workersNumber * sizeof(pthread_t));
for(i = 0; i < prodNumber; ++i)
{
pthread_create(tid + i, 0, &producer, 0);
}
for(i = prodNumber; i < workersNumber; ++i)
{
pthread_create(tid + i, 0, &consumer, 0);
}
while(1)
;
return 0;
}
| 0
|
#include <pthread.h>
int prod = 0;
int cons = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
char caracteres[10];
pthread_t hilos[2];
int v = 1;
char caracAleatorio(void){
return ((rand() % 57) + 65);
}
pthread_t hilos[2];
void *consumidor(void *arreglo){
while(1){
pthread_mutex_lock(&mutex);
while(prod != cons){
printf("%d, %d, %c\\n",prod, cons, caracteres[cons]);
usleep(500000);
cons++;
if (cons == 10){
cons = 0;
}
}
pthread_mutex_unlock(&mutex);
while(prod==cons);
}
pthread_exit((void *)0);
}
void *generador (void *arg){
int retval = pthread_create(&hilos[1], 0, &consumidor, 0);
if(retval != 0)
exit(1);
while(1){
if (prod != (cons-1)){
caracteres[prod] = caracAleatorio();
prod++;
if(prod == 10){
prod = 0;
}
} else {
while(prod == (cons-1));
}
}
pthread_exit((void *)0);
}
int main(void){
srand(getpid());
int retval = pthread_create(&hilos[0], 0, &generador, 0);
if(retval != 0)
exit(1);
pthread_join(hilos[0],0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t condition;
int counter;
} barrier_t;
barrier_t barrier = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0};
void *my_thread(void *);
void barrier_sync(barrier_t *);
int main(int argc, char **argv)
{
pthread_t thread_id[5];
int i;
for(i = 0; i < 5; i++){
pthread_create(&thread_id[i], 0, my_thread, (void *)i);
}
for(i = 0; i < 5; i++)
pthread_join(thread_id[i], 0);
pthread_exit(0);
}
void *
my_thread(void *args)
{
int thread_number = (int)args;
int num_iterations;
for(num_iterations = 0; num_iterations < 5; num_iterations++){
printf("Thread number %d is processing for iteration %d. \\n", thread_number, num_iterations);
sleep(ceil((float)rand()/(float)32767 * 10));
printf("Thread %d is at the barrier. \\n", thread_number);
barrier_sync(&barrier);
}
pthread_exit(0);
}
void barrier_sync(barrier_t *barrier)
{
pthread_mutex_lock(&(barrier->mutex));
barrier->counter++;
if(barrier->counter == 5){
barrier->counter = 0;
pthread_cond_broadcast(&(barrier->condition));
}
else{
while((pthread_cond_wait(&(barrier->condition), &(barrier->mutex))) != 0);
}
pthread_mutex_unlock(&(barrier->mutex));
}
| 0
|
#include <pthread.h>
int qtd = 0;
pthread_cond_t empty, full;
pthread_mutex_t mutex;
void *producer()
{
printf("Produtor!\\n");
while(1)
{
pthread_mutex_lock(&mutex);
if(qtd == 20)
{
printf("Maximo atingido!\\n");
pthread_cond_wait(&full, &mutex);
}
qtd++;
printf("Produtor com %d itens\\n", qtd);
if(qtd == 1)
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void *consumer()
{
printf("Consumidor\\n");
while(1)
{
pthread_mutex_lock(&mutex);
if(qtd == 0)
{
printf("Minimo atingido!\\n");
pthread_cond_wait(&empty, &mutex);
}
qtd--;
printf("Consumidor com %d itens\\n", qtd);
if(qtd == 20 -1)
pthread_cond_signal(&full);
pthread_mutex_unlock(&mutex);
sleep(3);
}
}
int main()
{
pthread_t producers[1];
pthread_t consumers[1];
pthread_create(&consumers[1], 0, consumer, 0);
pthread_create(&producers[1], 0, producer, 0);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int keepgoing = 1;
void signal_handler(int sig);
void *ThreadFunction(void *param);
void SendI2C(int chipAddress, int bellNumber, int deg);
void InitI2C(void);
void InitAIN(void);
pthread_t tid;
int id;
pthread_mutex_t mutex;
} Thread;
void signal_handler(int sig){
printf("Ctrl-C pressed, cleaning up and exiting...\\n");
keepgoing = 0;
}
void main(int argc, char *argv[])
{
struct pollfd fdset[1];
int nfds = 1, rc;
int timeout;
char buf[64];
int i = 0;
pthread_mutex_t i2c_mutex;
Thread threads[6];
signal(SIGINT, signal_handler);
timeout = (3*1000);
InitI2C();
InitAIN();
pthread_mutex_init(&i2c_mutex,0);
for(i = 0; i < 6; i++){
threads[i].id = i;
threads[i].mutex = i2c_mutex;
pthread_create(&threads[i].tid, 0, ThreadFunction, (threads+i));
}
while(keepgoing){
memset((void*)fdset,0,sizeof(fdset));
fdset[0].fd = STDIN_FILENO;
fdset[0].events = POLLIN;
rc = poll(fdset, nfds, timeout);
if(fdset[0].revents & POLLPRI){
(void)read(fdset[0].fd,buf,1);
printf("\\npoll() stdin read 0x%2.2X\\n", (unsigned int) buf[0]);
}
}
i = 0;
while(i < 6){
pthread_join(threads[i].tid, 0);
i++;
}
}
void *ThreadFunction(void *param){
Thread *t = param;
int ain = t->id;
pthread_mutex_t i2c_mutex = t->mutex;
int ain_value;
int chipAddress = ain * 2 / 6;
int bell = (ain - chipAddress*6/2) * 4;
int dir = 0, i;
printf("Thread %d chipAddress %d ain %d\\n", ain, chipAddress, ain);
while(keepgoing){
ain_get_value(ain, &ain_value);
if(ain_value > 1000){
} else{
if(dir){
for(i = 0; i < 4; i++){
pthread_mutex_lock(&i2c_mutex);
SendI2C(chipAddress, i + bell, 90-30/2);
pthread_mutex_unlock(&i2c_mutex);
}
}else{
for(i = 0; i < 4; i++){
pthread_mutex_lock(&i2c_mutex);
SendI2C(chipAddress, i + bell, 90+30/2);
pthread_mutex_unlock(&i2c_mutex);
}
}
dir = (dir + 1) % 2;
}
if(1){
usleep(ain_value * 250);
} else {
usleep(15000);
}
}
}
void SendI2C(int chipAddress, int bellNumber, int deg){
char buffer[50];
int raw = deg * 386 / 180 + 145;
int rawH = raw / 256;
int rawL = raw % 256;
sprintf(buffer, "i2cset -y 2 %d %d %d", 0x40 + chipAddress, 8 + bellNumber*4, rawL);
system(buffer);
sprintf(buffer, "i2cset -y 2 %d %d %d", 0x40 + chipAddress, 9 + bellNumber*4, rawH);
system(buffer);
}
void InitI2C(){
system("echo BB-I2C1 > /sys/devices/bone_capemgr.9/slots");
printf("echo BB-I2C1 > /sys/devices/bone_capemgr.9/slots\\n");
system("i2cset -y 2 0x40 0x00 0x11");
printf("i2cset -y 2 0x40 0x00 0x11\\n");
system("i2cset -y 2 0x41 0x00 0x11");
printf("i2cset -y 2 0x41 0x00 0x11\\n");
system("i2cset -y 2 0x40 0xfe 121");
printf("i2cset -y 2 0x40 0xfe 121\\n");
system("i2cset -y 2 0x41 0xfe 121");
printf("i2cset -y 2 0x41 0xfe 121\\n");
system("i2cset -y 2 0x40 0x00 0x01");
printf("i2cset -y 2 0x40 0x00 0x01\\n");
system("i2cset -y 2 0x41 0x00 0x01");
printf("i2cset -y 2 0x41 0x00 0x01\\n");
}
void InitAIN(){
system("echo cape-bone-iio > /sys/devices/bone_capemgr.9/slots");
printf("echo cape-bone-iio > /sys/devices/bone_capemgr.9/slots\\n");
}
| 0
|
#include <pthread.h>
pthread_mutex_t IO_mutex;
pthread_mutex_t QUEUE_mutex;
pthread_mutex_t NETWORK_mutex;
pthread_cond_t NETWORK_cond;
static pthread_t ClientThread, ServerThread;
static struct Server_arg ServerArg = { .listen = 1025 };
static struct Client_arg ClientArg = {
.peerIP = "127.0.0.1", .peerPort = 1025
};
static void
usage(void)
{
extern char *__progname;
fprintf(stderr, "Usage: %s\\n"
"\\t [-v] for versioning information\\n"
"\\t [-l] local port to listen on\\n"
"\\t [-p] remote port to connect to\\n"
"\\t [-h] remote host to connect to\\n",
__progname);
}
void
cleanup(void)
{
pthread_join(ClientThread, 0);
pthread_join(ServerThread, 0);
free(n1);
free(n2);
while (head.lh_first != 0)
LIST_REMOVE(head.lh_first, entries);
}
static void *
init(void)
{
LIST_INIT(&head);
n1 = malloc(sizeof *n1);
LIST_INSERT_HEAD(&head, n1, entries);
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&ServerThread, &attr, server_start, (void *)&ServerArg);
pthread_create(&ClientThread, &attr, client_start, (void *)&ClientArg);
pthread_attr_destroy(&attr);
return 0;
}
static int
chatter(const char *prompt)
{
char *line = malloc(BUFLENGTH);
char *exitSTR = TERMSTRING;
extern int errno;
size_t len = 0;
ssize_t read = 0;
while (strstr(line, exitSTR) == 0) {
pthread_mutex_lock(&IO_mutex);
printf("%s", prompt);
pthread_mutex_unlock(&IO_mutex);
errno = 0;
if ((read = getline(&line, &len, stdin)) == -1) {
warn("%ld: EOF recieved: %s", (unsigned long) read, strerror(errno));
} else {
line[read] = '\\0';
}
n2 = malloc(sizeof *n2);
pthread_mutex_lock(&QUEUE_mutex);
strncpy(n2->msg, line, BUFLENGTH);
LIST_INSERT_HEAD(&head, n2, entries);
pthread_mutex_unlock(&QUEUE_mutex);
}
free(line);
return (0);
}
int
main(int argc, char **argv)
{
extern char *__progname;
setlocale(LC_ALL, "");
atexit(cleanup);
int opt = 0;
while ((opt = getopt(argc, argv, "h:l:np:v")) != -1) {
switch (opt)
{
case 'h':
strncpy(ClientArg.peerIP, optarg, sizeof(ClientArg.peerIP));
break;
case 'l':
ServerArg.listen = strtol(optarg, 0, 0);
break;
case 'p':
ClientArg.peerPort = strtol(optarg, 0, 0);
break;
case 'v':
printf("%s: version number undefined\\n", __progname);
exit(0);
break;
default:
usage();
exit(1);
}
}
argc -= optind;
argv += optind;
init();
chatter("> ");
return (0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
void *functionCount1();
void *functionCount2();
int count = 0;
int 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 );
printf("Final Count: %d \\n", count);
}
void *functionCount1()
{
for (;;)
{
pthread_mutex_lock( &count_mutex );
pthread_cond_wait( &condition_var, &count_mutex );
count++;
printf("Counter Value functionCount1: %d \\n", count);
pthread_mutex_unlock( &count_mutex );
if (count >= 10) return(0);
}
}
void *functionCount2()
{
for(;;)
{
if ( count < 3 || count > 6 )
{
pthread_cond_signal( &condition_var );
}
else
{
count++;
printf("Counter value functionCount2: %d \\n", count);
}
pthread_mutex_unlock( &count_mutex );
if(count >= 10) return(0);
}
}
| 0
|
#include <pthread.h>
int waarde;
char uitspraak[10];
} cijfer_t;
cijfer_t buf[1];
cijfer_t in;
cijfer_t out;
sem_t full;
sem_t empty;
pthread_mutex_t mutex;
} package_t;
cijfer_t ctarray[] = {{0, "Zero"}, {1, "One"}, {2, "Two"}, {3, "Three"},
{4, "Four"}, {5, "Five"}, {6, "Six"}, {7, "Seven"},
{8, "Eight"}, {9, "Nine"}};
package_t shared;
void *Producer() {
int i;
cijfer_t item;
for (;;) {
for (i = 0; i < 10; i++) {
item = ctarray[i];
sem_wait(&shared.empty);
pthread_mutex_lock(&shared.mutex);
shared.buf[0] = item;
shared.in = ctarray[i];
printf("Producing: waarde: %d uitspraak: %s\\n", item.waarde,
item.uitspraak);
fflush(stdout);
pthread_mutex_unlock(&shared.mutex);
sem_post(&shared.full);
usleep(500);
}
}
return 0;
}
void *Consumer() {
int i;
cijfer_t item;
for (;;) {
for (i = 10; i > 0; i--) {
sem_wait(&shared.full);
pthread_mutex_lock(&shared.mutex);
item = ctarray[i];
item = shared.buf[0];
shared.out = ctarray[i];
printf("Consuming: waarde: %d uitspraak: %s\\n", item.waarde,
item.uitspraak);
fflush(stdout);
pthread_mutex_unlock(&shared.mutex);
sem_post(&shared.empty);
usleep(500);
}
}
return 0;
}
int main() {
pthread_t producure, consumer;
int index;
sem_init(&shared.full, 0, 0);
sem_init(&shared.empty, 0, 1);
pthread_mutex_init(&shared.mutex, 0);
pthread_create(&producure, 0, Producer, 1);
pthread_create(&consumer, 0, Consumer, 1);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_t *tid;
int target;
char *text;
int thread_number;
int record_number;
pthread_mutex_t mutex;
int forks[5];
unsigned int microseconds = 1000;
pthread_cond_t conditions[5];
void getForkLeft(int idno){
pthread_mutex_lock(&mutex);
if(idno == 0) idno = 5;
while(forks[idno-1] == 1){
pthread_cond_wait(&conditions[idno-1], &mutex);
}
forks[idno-1] = 1;
pthread_mutex_unlock(&mutex);
}
void getForkRight(int idno){
pthread_mutex_lock(&mutex);
while(forks[idno] == 1){
pthread_cond_wait(&conditions[idno], &mutex);
}
forks[idno] = 1;
pthread_mutex_unlock(&mutex);
}
void putForkLeft(int idno){
pthread_mutex_lock(&mutex);
if(idno == 0) idno = 5;
forks[idno - 1] = 0;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&conditions[idno-1]);
}
void putForkRight(int idno){
pthread_mutex_lock(&mutex);
forks[idno] = 0;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&conditions[idno]);
}
void* doSomeThing(void *arg)
{
pthread_t id = pthread_self();
int timesEaten = 0;
int idno;
for(idno = 0; idno < thread_number; idno++){
if(pthread_equal(id,tid[idno])){
break;
}
}
while(1){
usleep(microseconds);
if(idno == 0 || idno == 2){
getForkLeft(idno);
getForkRight(idno);
timesEaten = timesEaten+1;
printf("Philosopher %i is eating %i times!\\n", idno, timesEaten);
usleep(microseconds);
putForkRight(idno);
putForkLeft(idno);
}else{
getForkRight(idno);
getForkLeft(idno);
timesEaten = timesEaten+1;
printf("Philosopher %i is eating %i times!\\n", idno, timesEaten);
usleep(microseconds);
putForkLeft(idno);
putForkRight(idno);
}
}
return 0;
}
int main(int argc, char* argv[])
{
pthread_mutex_init(&mutex, 0);
int i = 0;
int err;
thread_number = 5;
tid = malloc(thread_number * sizeof(pthread_t));
printf("Creating %i threads\\n", thread_number);
for(i = 0; i < 5; i++){
forks[i] = 0;
pthread_cond_init(&conditions[i], 0);
}
i = 0;
while(i < thread_number)
{
err = pthread_create(&(tid[i]), 0, &doSomeThing, 0);
if (err != 0)
printf("\\ncan't create thread :[%s]", strerror(err));
else
i++;
}
for(i = 0; i < thread_number; i++){
pthread_join(tid[i], 0);
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int condition = 0;
int count = 0;
int put = 0;
int get = 0;
int BUFFER[8];
int consume( void )
{
while( 1 )
{
pthread_mutex_lock( &mutex );
while( condition == 0 )
pthread_cond_wait( &cond, &mutex );
if(BUFFER[get] != 0 ){
if(get == 0 )
printf("get == 0 ! \\n");
int temp = BUFFER[get];
printf("consumed %d", temp);
get++;
if(get == 7 ){
printf("get == 7 ! \\n");
}
}
condition = 0;
pthread_cond_signal( &cond );
pthread_mutex_unlock( &mutex );
}
return( 0 );
}
void* produce( void * arg )
{
while( 1 )
{
pthread_mutex_lock( &mutex );
while( condition == 1 )
pthread_cond_wait( &cond, &mutex );
if(put < 8){
count++;
printf( "Produced %d\\n", count );
BUFFER[put] = count;
put++;
}
condition = 1;
pthread_cond_signal( &cond );
pthread_mutex_unlock( &mutex );
}
return( 0 );
}
int main( void )
{
pthread_create( 0, 0, &produce, 0 );
return consume();
}
| 1
|
#include <pthread.h>
static inline unsigned int gfifo_unused(struct gfifo *fifo)
{
return (fifo->mask + 1) - (fifo->in - fifo->out);
}
static inline unsigned int min(unsigned int a, unsigned int b)
{
return (a < b) ? a : b;
}
int gfifo_alloc(struct gfifo *fifo, unsigned int size,
size_t esize)
{
fifo->in = 0;
fifo->out = 0;
fifo->esize = esize;
if (size < 2) {
fifo->data = 0;
fifo->mask = 0;
return -1;
}
fifo->data = malloc(size * esize);
if (!fifo->data) {
fifo->mask = 0;
return -1;
}
fifo->mask = size - 1;
pthread_mutex_init(&(fifo->mutex), 0);
return 0;
}
void gfifo_free(struct gfifo *fifo)
{
pthread_mutex_lock(&(fifo->mutex));
if(fifo->data != 0)
{
free(fifo->data);
}
fifo->in = 0;
fifo->out = 0;
fifo->esize = 0;
fifo->data = 0;
fifo->mask = 0;
pthread_mutex_unlock(&(fifo->mutex));
pthread_mutex_destroy(&(fifo->mutex));
}
void gfifo_reset(struct gfifo *fifo)
{
pthread_mutex_lock(&(fifo->mutex));
fifo->in = 0;
fifo->out = 0;
pthread_mutex_unlock(&(fifo->mutex));
}
int gfifo_init(struct gfifo *fifo, void *buffer,
unsigned int size, size_t esize)
{
size /= esize;
fifo->in = 0;
fifo->out = 0;
fifo->esize = esize;
fifo->data = buffer;
if (size < 2) {
fifo->mask = 0;
return -1;
}
fifo->mask = size - 1;
pthread_mutex_init(&(fifo->mutex), 0);
return 0;
}
static void gfifo_copy_in(struct gfifo *fifo, const void *src,
unsigned int len, unsigned int off)
{
unsigned int size = fifo->mask + 1;
unsigned int esize = fifo->esize;
unsigned int l;
off &= fifo->mask;
if (esize != 1) {
off *= esize;
size *= esize;
len *= esize;
}
l = min(len, size - off);
memcpy(fifo->data + off, src, l);
memcpy(fifo->data, src + l, len - l);
}
unsigned int gfifo_in(struct gfifo *fifo,
const void *buf, unsigned int len)
{
unsigned int l;
pthread_mutex_lock(&(fifo->mutex));
l = gfifo_unused(fifo);
if (len > l)
len = l;
gfifo_copy_in(fifo, buf, len, fifo->in);
fifo->in += len;
pthread_mutex_unlock(&(fifo->mutex));
return len;
}
static void gfifo_copy_out(struct gfifo *fifo, void *dst,
unsigned int len, unsigned int off)
{
unsigned int size = fifo->mask + 1;
unsigned int esize = fifo->esize;
unsigned int l;
off &= fifo->mask;
if (esize != 1) {
off *= esize;
size *= esize;
len *= esize;
}
l = min(len, size - off);
memcpy(dst, fifo->data + off, l);
memcpy(dst + l, fifo->data, len - l);
}
unsigned int gfifo_out_peek(struct gfifo *fifo,
void *buf, unsigned int len)
{
unsigned int l;
l = fifo->in - fifo->out;
if (len > l)
len = l;
gfifo_copy_out(fifo, buf, len, fifo->out);
return len;
}
unsigned int gfifo_out(struct gfifo *fifo,
void *buf, unsigned int len)
{
pthread_mutex_lock(&(fifo->mutex));
len = gfifo_out_peek(fifo, buf, len);
fifo->out += len;
pthread_mutex_unlock(&(fifo->mutex));
return len;
}
unsigned int gfifo_out_block(struct gfifo *fifo,
void *buf, unsigned int len)
{
int nTotal = len;
do
{
len = len - gfifo_out(fifo, buf + nTotal - len, len);
if(len > 0)
{
usleep(10 * 1000);
}
}while(len != 0);
return len;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.