text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_var = PTHREAD_COND_INITIALIZER;
int value;
void* collatz_even(void* nothing) {
for(;;) {
pthread_mutex_lock( &mutex );
printf("[EVEN THREAD] LOCK\\n");
if (value % 2 == 0) {
printf("[EVEN THREAD] value: %2d => %2d\\n", value, value/2);
value = value / 2;
printf("%d\\n", value);
} else {
pthread_cond_signal(&cond_var);
printf("[EVEN THREAD] value: %2d => SIGNAL SENT\\n", value);
}
printf("[EVEN THREAD] UNLOCK\\n");
pthread_mutex_unlock( &mutex );
usleep(1000);
if (value == 1) {
pthread_cond_signal(&cond_var);
return 0;
}
}
}
void* collatz_odd(void* nothing) {
for(;;) {
pthread_mutex_lock( &mutex );
printf("[ODD THREAD] LOCK\\n");
printf("[ODD THREAD] WAITING SIGNAL\\n");
pthread_cond_wait(&cond_var, &mutex);
printf("[ODD THREAD] SIGNAL RECEIVED\\n");
if (value != 1) {
printf("[ODD THREAD] value: %2d => %2d\\n",
value, value*3 + 1);
value = value*3 + 1;
printf("%d\\n", value);
}
printf("[ODD THREAD] UNLOCK\\n");
pthread_mutex_unlock( &mutex );
if (value == 1) return 0;
}
}
int main(int argc, char* argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s starting_val\\n", argv[0]);
return -1;
}
value = atoi(argv[1]);
printf("Starting Collatz Conjecture with value:\\n");
printf("%d\\n", value);
pthread_t thread1;
pthread_t thread2;
pthread_create(&thread1, 0, collatz_even, 0);
pthread_create(&thread2, 0, collatz_odd, 0);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t dataMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t dataPresentCondition = PTHREAD_COND_INITIALIZER;
int dataPresent=0;
int sharedData=0;
void *theThread(void *parm)
{
int rc;
int retries=2;
rc = pthread_mutex_lock(&dataMutex);
{ if (rc) { printf("Failed with %d at %s", rc, "pthread_mutex_lock()\\n"); exit(1); } };
while (retries--) {
while (!dataPresent) {
printf("Consumer Thread %.8x %.8x: Wait for data to be produced\\n");
rc = pthread_cond_wait(&dataPresentCondition, &dataMutex);
if (rc) {
printf("Consumer Thread %.8x %.8x: condwait failed, rc=%d\\n",rc);
pthread_mutex_unlock(&dataMutex);
exit(1);
}
}
--sharedData;
if (sharedData==0) {dataPresent=0;}
}
rc = pthread_mutex_unlock(&dataMutex);
{ if (rc) { printf("Failed with %d at %s", rc, "pthread_mutex_unlock()\\n"); exit(1); } };
return 0;
}
int main(int argc, char **argv)
{
pthread_t thread[2];
int rc=0;
int amountOfData=4;
int i;
printf("Enter Testcase - %s\\n", argv[0]);
printf("Create/start threads\\n");
for (i=0; i <2; ++i) {
rc = pthread_create(&thread[i], 0, theThread, 0);
{ if (rc) { printf("Failed with %d at %s", rc, "pthread_create()\\n"); exit(1); } };
}
while (amountOfData--) {
printf("Producer: 'Finding' data\\n");
sleep(3);
rc = pthread_mutex_lock(&dataMutex);
{ if (rc) { printf("Failed with %d at %s", rc, "pthread_mutex_lock()\\n"); exit(1); } };
printf("Producer: Make data shared and notify consumer\\n");
++sharedData;
dataPresent=1;
rc = pthread_cond_signal(&dataPresentCondition);
if (rc) {
pthread_mutex_unlock(&dataMutex);
printf("Producer: Failed to wake up consumer, rc=%d\\n", rc);
exit(1);
}
printf("Producer: Unlock shared data and flag\\n");
rc = pthread_mutex_unlock(&dataMutex);
{ if (rc) { printf("Failed with %d at %s", rc, "pthread_mutex_lock()\\n"); exit(1); } };
}
printf("Wait for the threads to complete, and release their resources\\n");
for (i=0; i <2; ++i) {
rc = pthread_join(thread[i], 0);
{ if (rc) { printf("Failed with %d at %s", rc, "pthread_join()\\n"); exit(1); } };
}
printf("Clean up\\n");
rc = pthread_mutex_destroy(&dataMutex);
rc = pthread_cond_destroy(&dataPresentCondition);
printf("Main completed\\n");
return 0;
}
| 0
|
#include <pthread.h>
pthread_t philosophers[5];
pthread_mutex_t chopsticks[5];
int chopstick_status[5];
void *a_philosopher_s_life(void *arg)
{
int index = *((int *) arg);
int index_next = index == 5 - 1 ? 0 : index + 1;
pthread_mutex_t *chopstick_l = chopsticks + index;
pthread_mutex_t *chopstick_r = chopsticks + index_next;
int i;
while (1) {
printf("chopstick status: \\n");
for (i = 0; i < 5; i++) {
printf("\\t%d : %d\\n", i, chopstick_status[i]);
}
usleep(rand()%10);
pthread_mutex_lock(chopstick_l);
chopstick_status[index] = index;
printf("Philosopher %d fetches chopstick %d\\n", index, index);
if (0 != pthread_mutex_trylock(chopstick_r)) {
pthread_mutex_unlock(chopstick_l);
chopstick_status[index] = -1;
printf("Philosopher %d releases chopstick %d\\n", index, index);
continue;
}
chopstick_status[index_next] = index;
printf("Philosopher %d fetches chopstick %d\\n", index, index_next);
usleep(rand()%10);
pthread_mutex_unlock(chopstick_l);
chopstick_status[index] = -1;
pthread_mutex_unlock(chopstick_r);
chopstick_status[index_next] = -1;
printf("Philosopher %d releases chopstick %d %d\\n", index, index, index_next);
}
}
int main(void)
{
int i;
int index[5];
for (i = 0; i < 5; i++) {
index[i] = i;
chopstick_status[i] = -1;
pthread_create(philosophers+i, 0, a_philosopher_s_life, index+i);
}
for (i = 0; i < 5; i++) {
pthread_join(*(philosophers+i), 0);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t blanks;
sem_t datas;
int ringBuf[30];
void *productRun(void *arg)
{
int i = 0;
while(1)
{
sem_wait(&blanks);
int data = rand()%1234;
ringBuf[i++] = data;
i %= 30;
printf("product is done... data is: %d\\n",data);
sem_post(&datas);
}
}
void *productRun2(void *arg)
{
int i = 0;
while(1)
{
sem_wait(&blanks);
int data = rand()%1234;
ringBuf[i++] = data;
i %= 30;
printf("product2 is done... data is: %d\\n",data);
sem_post(&datas);
}
}
void *consumerRun(void *arg)
{
int i = 0;
while(1)
{
usleep(1456);
pthread_mutex_lock(&mutex);
sem_wait(&datas);
int data = ringBuf[i++];
i %= 30;
printf("consumer is done... data is: %d\\n",data);
sem_post(&blanks);
pthread_mutex_unlock(&mutex);
}
}
void *consumerRun2(void *arg)
{
int i = 0;
while(1)
{
usleep(1234);
pthread_mutex_lock(&mutex);
sem_wait(&datas);
int data = ringBuf[i++];
i %= 30;
printf("consumer2 is done...data2 is: %d\\n",data);
sem_post(&blanks);
pthread_mutex_unlock(&mutex);
}
}
int main()
{
sem_init(&blanks, 0, 30);
sem_init(&datas, 0, 0);
pthread_t tid1,tid2,tid3,tid4;
pthread_create(&tid1, 0, productRun, 0);
pthread_create(&tid4, 0, productRun2, 0);
pthread_create(&tid2, 0, consumerRun, 0);
pthread_create(&tid3, 0, consumerRun2, 0);
pthread_join(tid1,0);
pthread_join(tid2,0);
pthread_join(tid3,0);
pthread_join(tid4,0);
sem_destroy(&blanks);
sem_destroy(&datas);
return 0;
}
int sem_ID;
int customers_count=0;
int eflag=0,fflag=0;
void *barber(void *x)
{
printf("barber started\\n");
while(1)
{
sem_change(sem_ID, 0, -1);
if(customers_count==0)
{
printf("barber sleeping\\n");
eflag=1;
sem_change(sem_ID, 0, 1);
sem_change(sem_ID, 1, -1);
sem_change(sem_ID, 0, -1);
}
customers_count--;
sem_change(sem_ID, 0, 1);
sem_change(sem_ID, 3, 1);
sem_change(sem_ID, 4, -1);
}
}
void *customer(void *arg)
{
sem_change(sem_ID, 0, -1);
if(customers_count==5)
{
int *ptr=(int*)arg;
*ptr=0;
printf("No place for customer %u so leaving\\n", pthread_self());
sem_change(sem_ID, 0, 1);
}
else{
customers_count++;
if(customers_count==1 && eflag==1)
{
sem_change(sem_ID, 1, 1);
eflag=0;
}
sem_change(sem_ID, 0, 1);
printf("Customer %u got a place\\n", pthread_self());
sem_change(sem_ID, 3, -1);
printf("Cutting for %u customer\\n", pthread_self());
sleep(rand()%5+4);
sem_change(sem_ID, 4, 1);
int *ptr=(int*)arg;
*ptr=0;
}
}
int main(int argc, char* argv[])
{
pthread_t barber_thread;
int live_threads[5 +2];
pthread_t customer_thread[5 +2];
for(int i=0; i<5 +2; i++)
live_threads[i]=0;
int array[]={1, 0, 5, 0, 0};
sem_ID=sem_init_diff_val(5,array);
pthread_create(&barber_thread, 0,barber, 0);
sleep(2);
while(1)
{
for(int i=0; i<5 +2; i++)
{
if(live_threads[i]==0)
{
live_threads[i]=1;
pthread_create(&customer_thread[i], 0,customer, (void*)&live_threads[i]);
sleep(rand()%4);
}
}
}
exit(0);
}
| 0
|
#include <pthread.h>
int map_minerals = 5000;
int minerals = 0;
int n = 0;
int m = 0;
int k = -1;
int command_centers_minerals[12] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
pthread_mutex_t mutex_workers;
pthread_mutex_t mutex_map_minerals;
pthread_mutex_t mutex_minerals;
pthread_mutex_t mutex_solders;
pthread_mutex_t mutex_command_centers;
pthread_mutex_t mutex_command_centers_minerals[12];
void* worker (void) {
pthread_mutex_lock(&mutex_workers);
n++;
pthread_mutex_unlock(&mutex_workers);
char* name = "SVC " + (n + 49);
int worker_minerals = 0;
int i;
if (n > 5) {
printf("SCV good to go, sir.\\n");
}
while (m < 20) {
printf("%s", name);
printf(" is mining\\n");
pthread_mutex_lock(&mutex_map_minerals);
map_minerals -= 8;
pthread_mutex_unlock(&mutex_map_minerals);
worker_minerals += 8;
printf("%s", name);
printf(" is transporting minerals\\n");
while (worker_minerals > 0) {
if (pthread_mutex_trylock(&mutex_minerals) == 0) {
minerals += worker_minerals;
worker_minerals = 0;
pthread_mutex_unlock(&mutex_minerals);
printf("delivered minerals to Command Center 1");
} else {
for(i = 0; i <= k;i++) {
if (pthread_mutex_trylock(&mutex_command_centers_minerals[i]) == 0) {
command_centers_minerals[i] += worker_minerals;
worker_minerals = 0;
pthread_mutex_unlock(&mutex_command_centers_minerals[i]);
printf("delivered minerals to Command Center ");
printf("%d\\n", (i + 2));
break;
}
}
}
}
}
}
void* command_center (void) {
pthread_mutex_lock(&mutex_command_centers);
command_centers_minerals[++k] = 0;
pthread_mutex_unlock(&mutex_command_centers);
if (pthread_mutex_init(&mutex_command_centers_minerals[k], 0) != 0) {
perror("Fail to initialize mutex: workers!");
}
}
void* solder (void) {
pthread_mutex_lock(&mutex_solders);
m++;
pthread_mutex_unlock(&mutex_solders);
printf("You wanna piece of me, boy?\\n");
}
int return_all_minerals (void) {
int all = minerals;
int i;
for (i = 0; i <= k; i++) {
all += command_centers_minerals[i];
}
return all;
}
int main (void) {
char command;
int all = 0;
pthread_t workers[100];
pthread_t solders[20];
pthread_t centers[12];
if (pthread_mutex_init(&mutex_workers, 0) != 0) {
perror("Fail to initialize mutex: workers!");
}
if (pthread_mutex_init(&mutex_command_centers, 0) != 0) {
perror("Fail to initialize mutex: command_center!");
}
if (pthread_mutex_init(&mutex_solders, 0) != 0) {
perror("Fail to initialize mutex: solders!");
}
if (pthread_mutex_init(&mutex_map_minerals, 0) != 0) {
perror("Fail to initialize mutex: minerals!");
}
while(m < 20) {
command = getchar();
if ((command == 'm') || (command == 's') || (command == 'c')) {
pthread_mutex_lock(&mutex_minerals);
all = return_all_minerals();
}
if (command == 'm') {
if (all > 50) {
minerals -= 50;
}
}
if (command == 's') {
if (all > 50) {
minerals -= 50;
}
}
if (command == 'c') {
if (all > 400) {
minerals -= 400;
}
}
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t barrier;
pthread_cond_t go;
int numArrivedThreads = 0;
void mai_barrier() {
pthread_mutex_lock(&barrier);
numArrivedThreads++;
if (numArrivedThreads == sinfo.nthreads) {
numArrivedThreads = 0;
pthread_cond_broadcast(&go);
} else
pthread_cond_wait(&go, &barrier);
pthread_mutex_unlock(&barrier);
}
int mai_get_num_nodes()
{
return sinfo.nnodes;
}
int mai_get_num_threads()
{
return sinfo.nthreads;
}
int mai_get_num_cpus()
{
return sinfo.ncpus;
}
unsigned long* mai_get_nodes_id()
{
return sinfo.nodes;
}
unsigned long* mai_get_cpus_id()
{
return sinfo.cpus;
}
void mai_show_nodes()
{
int i,tmp;
unsigned long x;
printf("\\n---Listing nodes----");
for(i=0;i<sinfo.nnodes;i++)
{
x = sinfo.nodes[i];
tmp = convert_node(&x);
printf("\\nNODE: %d",tmp);
}
printf("\\n--------------------\\n");
}
void mai_show_cpus()
{
int i,tmp;
unsigned long x;
printf("\\n---Listing cpus/cores----\\n");
for(i=0;i<sinfo.nthreads;i++)
{
x = sinfo.cpus[i];
tmp = convert_cpu(&x);
printf("\\nCPU/CORE: %d",tmp);
}
printf("\\n-------------------------\\n");
}
int numa_check()
{
int ret=0;
ret = get_mempolicy(0, 0, 0, 0, 0);
if (ret < 0 && errno == ENOSYS)
fprintf(stderr,"upgrade to kernel >= 2.6.7\\n");
return ret;
}
void mai_init(char filename[])
{
if( na_is_numa()) {
pthread_mutex_init(&barrier, 0);
pthread_cond_init(&go, 0);
pthread_mutex_init(&(sinfo.lock_place), 0);
pthread_mutex_init(&mai_mutex,0);
init_var_info();
init_place_info();
load_hash();
main_pid = tid();
set_place_info(filename);
time_last_pmig = time_last_tmig = 0.0;
}
else
exit(-1);
}
void mai_final()
{
struct var_info *aux;
void *pointer=0;
int i=0;
if(numa_check() == 0)
{
while(i<MAI_HASH_SIZE)
{
aux = arraysHash[i];
while(aux!=0)
{
pthread_mutex_destroy(&(aux->lock_var));
mai_free_array(aux->phigh);
aux=aux->child;
}
arraysHash[i]=0;
i++;
}
}
else
exit(-1);
pthread_mutex_destroy(&(sinfo.lock_place));
pthread_mutex_destroy(&(mai_mutex));
}
void mai_change(char filename[])
{
if(numa_check() == 0)
{
sinfo.nnodes=sinfo.nthreads=0;
sinfo.cpus=sinfo.nodes=0;
set_place_info(filename);
time_last_pmig = time_last_tmig = 0.0;
}
else
exit(-1);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex3 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex4 = PTHREAD_MUTEX_INITIALIZER;
static int sequence1 = 0;
static int sequence2 = 0;
int fun1()
{
pthread_mutex_lock(&mutex1);
++sequence1;
sleep(1);
pthread_mutex_lock(&mutex2);
++sequence2;
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
return sequence1;
}
int fun2()
{
pthread_mutex_lock(&mutex1);
++sequence1;
sleep(1);
pthread_mutex_lock(&mutex2);
++sequence2;
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
return sequence2;
}
void *thread1(void *arg)
{
while (1)
{
int ret = fun1();
if (100000 == ret)
{
pthread_exit(0);
}
}
}
void *thread2(void *arg)
{
while (1)
{
int ret = fun2();
if (100000 == ret)
{
pthread_exit(0);
}
}
}
void *thread3(void *arg)
{
while (1)
{
sleep(1);
char buf[128];
memset(buf, 0, sizeof(buf));
strcpy(buf, "thread3");
}
}
void *thread4(void *arg)
{
while (1)
{
sleep(1);
char buf[128];
memset(buf, 0, sizeof(buf));
strcpy(buf, "thread3");
}
}
int main()
{
pthread_t tid[4];
if (0 != pthread_create(&tid[0], 0, &thread1, 0))
{
_exit(1);
}
if (0 != pthread_create(&tid[1], 0, &thread2, 0))
{
_exit(1);
}
if (0 != pthread_create(&tid[2], 0, &thread3, 0))
{
_exit(1);
}
if (0 != pthread_create(&tid[3], 0, &thread4, 0))
{
_exit(1);
}
sleep(5);
pthread_join(tid[0], 0);
pthread_join(tid[1], 0);
pthread_join(tid[2], 0);
pthread_join(tid[3], 0);
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
pthread_mutex_destroy(&mutex3);
pthread_mutex_destroy(&mutex4);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t print_mutex;
pthread_mutex_t wait_chairs_mutex;
int wait_chairs_open = 5;
pthread_cond_t wait_chairs_cv;
sem_t customer;
sem_t barber;
void getHairCut (void *t) {
long my_id = *(long *)t;
pthread_mutex_lock (&print_mutex);
printf ("Customer: %c is getting a hair cut\\n", my_id);
pthread_mutex_unlock (&print_mutex);
}
void balk (void *t) {
long my_id = *(long *)t;
pthread_mutex_lock (&print_mutex);
printf ("Customer: %c is balking, walking away!\\n", my_id);
pthread_mutex_unlock (&print_mutex);
pthread_exit(0);
}
void cutHair (void *t) {
long my_id = (long)t;
int busyTime;
pthread_mutex_lock (&print_mutex);
printf ("Barber is doing a hair cut\\n");
pthread_mutex_unlock (&print_mutex);
srand(time(0));
busyTime = (rand() % 2);
sleep(busyTime);
}
void *barberTask (void *t) {
long my_id = (long)t;
while (1) {
sem_wait ( &customer );
pthread_mutex_lock ( &wait_chairs_mutex );
wait_chairs_open++;
pthread_mutex_unlock ( &wait_chairs_mutex );
cutHair(t);
sem_post ( &barber );
}
}
void *customerTask (void *id) {
long my_id = *(long *)id;
pthread_mutex_lock ( &wait_chairs_mutex );
if (wait_chairs_open > 0) {
wait_chairs_open--;
pthread_mutex_unlock ( &wait_chairs_mutex );
sem_post ( &customer );
sem_wait ( &barber );
getHairCut(id);
} else {
pthread_mutex_unlock ( &wait_chairs_mutex );
balk (id);
}
}
int main (int argc, char *argv[])
{
int i, rc;
int tn[26];
long barber_id = 7;
int customerArrivalDelay;
pthread_t threads[26];
pthread_attr_t attr;
srand(time(0));
for (i=0; i<26; i++)
tn[i] = (long)('A'+i);
sem_init ( &customer, 1, 0 );
sem_init ( &barber, 1, 0 );
pthread_mutex_init( &wait_chairs_mutex, 0 );
pthread_create(&threads[i], 0, barberTask, (void *)&barber_id);
for (i=0; i<26; i++) {
customerArrivalDelay = (rand() % 3);
sleep(customerArrivalDelay);
pthread_create(&threads[i], 0, customerTask, (void *)&tn[i]);
}
for (i=0; i<26; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited on %d threads. Done.\\n", 26);
return 0;
}
| 0
|
#include <pthread.h>
int multi_mutex_unlock(pthread_mutex_t **mutexv, int mutexc)
{
if ((mutexv == 0) || (mutexc < 0)) {
return -1;
}
for (int i = 0; i < mutexc; i++) {
if (mutexv[i]) {
pthread_mutex_unlock(mutexv[i]);
}
}
return 0;
}
int multi_mutex_trylock(pthread_mutex_t **mutexv, int mutexc)
{
if ((mutexv == 0) || (mutexc < 0)) {
return -1;
}
for (int i = 0; i < mutexc; i++) {
if (mutexv[i]) {
int r = pthread_mutex_trylock(mutexv[i]);
if (r == 0) {
continue;
}
}
multi_mutex_unlock(mutexv, i);
return -1;
}
return 0;
}
static int _compare_pointer(const void *a, const void *b)
{
assert(a != 0);
assert(b != 0);
pthread_mutex_t **mutex_a = (pthread_mutex_t **) a;
pthread_mutex_t **mutex_b = (pthread_mutex_t **) b;
return (*mutex_a < *mutex_b) ? -1 : ((*mutex_a == *mutex_b) ? 0 : 1);
}
int multi_mutex_lock(pthread_mutex_t **mutexv, int mutexc)
{
if ((mutexv == 0) || (mutexc < 0)) {
return -1;
} else if (mutexc == 0) {
return 0;
}
size_t size = sizeof(pthread_mutex_t*) * mutexc;
pthread_mutex_t **mutexv_temp;
mutexv_temp = (size > 100) ? malloc(size) : alloca(size);
if (mutexv_temp == 0) {
return -1;
}
memcpy(mutexv_temp, mutexv, size);
qsort(mutexv_temp, mutexc, sizeof(pthread_mutex_t**), _compare_pointer);
pthread_mutex_t *prev = 0;
for (int i = 0; i < mutexc; prev = mutexv_temp[i++]) {
assert(prev <= mutexv_temp[i]);
if ((prev != mutexv_temp[i]) && mutexv_temp[i]) {
int r = pthread_mutex_lock(mutexv_temp[i]);
if (r == 0) {
continue;
}
}
multi_mutex_unlock(mutexv_temp, i);
if (size > 100) {
free(mutexv_temp);
}
return -1;
}
if (size > 100) {
free(mutexv_temp);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t print_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t PATTERN_mutex = PTHREAD_MUTEX_INITIALIZER;
int TotalLines = 0;
char *PATTERN;
void * searchfile(void *);
int main(int argc, char *argv[]){
pthread_t thread_id[10];
int Lines;
if ((argc < 2) || (argc > 10 +1)) {
fprintf(stderr,"%s: [PATTERN],[file1],[file2]...[file%d]\\n", *argv, 10);
exit(1);
}
PATTERN = argv[1];
for(int i = 0; i < argc-2; i++){
if (pthread_create(&thread_id[i], 0, searchfile, (void *) argv[i + 2]) != 0) {
fprintf(stderr, "pthread_create failure\\n");
exit(2);
}
}
for (int i = 0; i < argc-2; i++) {
if ( pthread_join(thread_id[i], (void **)&Lines) > 0){
fprintf(stderr, "pthread_join failure\\n");
}
TotalLines += Lines;
}
printf("Total lines found:" "\\x1B[35m" "%d\\n" "\\x1B[37m", TotalLines);
pthread_mutex_destroy(&print_mutex);
pthread_mutex_destroy(&PATTERN_mutex);
return 0;
}
void * searchfile(void * arg){
int lines = 0, lineFound = 0;
FILE * fp;
char str[2048];
if((fp = fopen((char *)arg, "r")) == 0){
perror("Failed to open input file");
return (void *)(0);
}
while(fgets(str, 2048, fp) != 0){
lines++;
pthread_mutex_lock (&PATTERN_mutex);
if(strstr(str, PATTERN) != 0){
pthread_mutex_lock (&print_mutex);
lineFound++;
printf("%s:""\\x1B[32m" "%d" "\\x1B[37m" ":%s", (char *)arg, lines, str);
pthread_mutex_unlock (&print_mutex);
}
pthread_mutex_unlock (&PATTERN_mutex);
}
pthread_mutex_lock (&print_mutex);
printf("Lines found in %s: " "\\x1B[36m" "%d\\n" "\\x1B[37m", (char *)arg, lineFound);
pthread_mutex_unlock (&print_mutex);
if(fclose(fp)==EOF){
perror("Failed to close input file");
return (void *)(0);
}
pthread_exit((void *)(long)lineFound);
}
| 0
|
#include <pthread.h>
char letter;
int freq;
} tuple;
tuple tup[52];
} alphabet;
alphabet alph;
pthread_mutex_t mutexes[52];
void initialize_alphabet(alphabet* alph){
int i,pos=0;
for(i='A';i<='Z';i++,pos++){
alph->tup[pos].letter=i;
alph->tup[pos].freq=0;
}
for(i='a';i<='z';i++,pos++){
alph->tup[pos].letter=i;
alph->tup[pos].freq=0;
}
}
void print_alphabet(alphabet* alph){
int i;
for(i=0;i<52;i++)
if(alph->tup[i].freq )
printf("%c -> %d\\n",alph->tup[i].letter,alph->tup[i].freq);
}
void* count(char* fileName){
FILE* fileIn=fopen(fileName,"r");
if(fileIn==0)
return 0;
char *buffer=(char*)malloc(128*sizeof(char));
while(fgets(buffer,128,fileIn)){
int i;
for(i=0;i<strlen(buffer);i++){
if(buffer[i]>='A' && buffer[i]<='Z'){
pthread_mutex_lock(&mutexes[buffer[i]-'A']);
alph.tup[buffer[i]-'A'].freq++;
pthread_mutex_unlock(&mutexes[buffer[i]-'A']);
}
else
if(buffer[i]>='a' && buffer[i]<='z'){
pthread_mutex_lock(&mutexes[buffer[i]-'a'+26]);
alph.tup[buffer[i]-'a'+26].freq++;
pthread_mutex_unlock(&mutexes[buffer[i]-'a'+26]);
}
}
}
free(buffer);
fclose(fileIn);
return 0;
}
int main(int argc,char **argv){
int i;
pthread_t threads[argc];
initialize_alphabet(&alph);
for(i=0;i<52;i++)
pthread_mutex_init(&mutexes[i],0);
for(i=1;argv[i];i++)
pthread_create(&threads[i],0,count,argv[i]);
for(i=1;argv[i];i++)
pthread_join(threads[i],0);
print_alphabet(&alph);
for(i=0;i<52;i++)
pthread_mutex_destroy(&mutexes[i]);
return 0;
}
| 1
|
#include <pthread.h>
struct ring_buffer* ring_buffer_init(void *buffer, uint32_t size, pthread_mutex_t *f_lock)
{
assert(buffer);
struct ring_buffer *ring_buf = 0;
if (!IS_POWER_OF_2(size))
{
printf("size must be power of 2.\\n");
return ring_buf;
}
ring_buf = (struct ring_buffer *)malloc(sizeof(struct ring_buffer));
if (!ring_buf)
{
printf("Failed to malloc memory,errno:%u,reason:%s",
errno, strerror(errno));
return ring_buf;
}
memset(ring_buf, 0, sizeof(struct ring_buffer));
ring_buf->buffer = buffer;
ring_buf->size = size;
ring_buf->in = 0;
ring_buf->out = 0;
ring_buf->f_lock = f_lock;
return ring_buf;
}
void ring_buffer_free(struct ring_buffer *ring_buf)
{
if (ring_buf)
{
if (ring_buf->buffer)
{
free(ring_buf->buffer);
ring_buf->buffer = 0;
}
free(ring_buf);
ring_buf = 0;
}
}
uint32_t __ring_buffer_len(const struct ring_buffer *ring_buf)
{
return (ring_buf->in - ring_buf->out);
}
uint32_t __ring_buffer_get(struct ring_buffer *ring_buf, void * buffer, uint32_t size)
{
assert(ring_buf || buffer);
uint32_t len = 0;
size = MIN(size, ring_buf->in - ring_buf->out);
len = MIN(size, ring_buf->size - (ring_buf->out & (ring_buf->size - 1)));
memcpy(buffer, ring_buf->buffer + (ring_buf->out & (ring_buf->size - 1)), len);
memcpy(buffer + len, ring_buf->buffer, size - len);
ring_buf->out += size;
return size;
}
uint32_t __ring_buffer_put(struct ring_buffer *ring_buf, void *buffer, uint32_t size)
{
assert(ring_buf || buffer);
uint32_t len = 0;
size = MIN(size, ring_buf->size - ring_buf->in + ring_buf->out);
len = MIN(size, ring_buf->size - (ring_buf->in & (ring_buf->size - 1)));
memcpy(ring_buf->buffer + (ring_buf->in & (ring_buf->size - 1)), buffer, len);
memcpy(ring_buf->buffer, buffer + len, size - len);
ring_buf->in += size;
return size;
}
uint32_t ring_buffer_len(const struct ring_buffer *ring_buf)
{
uint32_t len = 0;
pthread_mutex_lock(ring_buf->f_lock);
len = __ring_buffer_len(ring_buf);
pthread_mutex_unlock(ring_buf->f_lock);
return len;
}
uint32_t ring_buffer_get(struct ring_buffer *ring_buf, void *buffer, uint32_t size)
{
uint32_t ret;
pthread_mutex_lock(ring_buf->f_lock);
ret = __ring_buffer_get(ring_buf, buffer, size);
if (ring_buf->in == ring_buf->out)
ring_buf->in = ring_buf->out = 0;
pthread_mutex_unlock(ring_buf->f_lock);
return ret;
}
uint32_t ring_buffer_put(struct ring_buffer *ring_buf, void *buffer, uint32_t size)
{
uint32_t ret;
pthread_mutex_lock(ring_buf->f_lock);
ret = __ring_buffer_put(ring_buf, buffer, size);
pthread_mutex_unlock(ring_buf->f_lock);
return ret;
}
| 0
|
#include <pthread.h>
static time_t time_orig;
static time_t time_interval;
static int bool_black = 0;
static pthread_mutex_t mutex_screen = PTHREAD_MUTEX_INITIALIZER;
static char screen_light_buf[4];
static int screen_set_time(time_t time)
{
return_val_if_fail(time > 0, -1);
dd_debug("set time %ld\\n", time);
time_orig = time;
return 0;
}
int screen_set_black(int black)
{
pthread_mutex_lock(&mutex_screen);
if (strlen(acfg()->brightness_path) != 0) {
if ( strcmp(acfg()->brightness_path, "disable") == 0)
return 0;
}
int fd = open(acfg()->brightness_path, O_WRONLY);
if (fd <= 0)
{
dd_error("open %s failed!\\n", acfg()->brightness_path);
}
else
{
bool_black = black;
if (bool_black)
{
if (write(fd,"0", 1) <= 0)
{
dd_error("%s write error: %s\\n", acfg()->brightness_path, strerror(errno));
}
}
else
{
dd_debug("screen_light_buf is %s\\n", screen_light_buf);
if (write(fd,screen_light_buf,strlen(screen_light_buf)) <= 0)
{
dd_error("%s write error: %s\\n", acfg()->brightness_path, strerror(errno));
}
}
close(fd);
}
pthread_mutex_unlock(&mutex_screen);
return 0;
}
int screen_is_black()
{
return bool_black;
}
int screen_set_light(int light)
{
return_val_if_fail(light > 10, -1);
return_val_if_fail(light <= 255, -1);
return_val_if_fail(0 <= snprintf(screen_light_buf,sizeof(screen_light_buf), "%d", light), -1);
return 0;
}
int screen_set_interval(int interval)
{
return_val_if_fail(interval > 0, -1);
time_interval = interval;
return 0;
}
static void *screen_black_thread(void *cookie)
{
while(1)
{
if (difftime(time((time_t *)0), time_orig) > time_interval)
{
if (0 == bool_black)
screen_set_black(1);
}
else if (0 != bool_black)
{
screen_set_black(0);
}
sleep(1);
}
return 0;
}
static pthread_t screen_thread_t;
static int screen_init()
{
time_interval = 150;
screen_set_light(50);
screen_set_time(time((time_t*)0));
screen_set_black(0);
pthread_create(&screen_thread_t, 0, screen_black_thread, 0);
pthread_detach(screen_thread_t);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_t g_thread[(2)];
static pthread_mutex_t g_mtx;
static pthread_cond_t g_cond;
void * threadx_yell (void *param)
{
int t_id = *(int*)param;
while(1)
{
pthread_mutex_lock(&g_mtx);
printf("mutex demo: thread %d entered mutex!\\n", t_id);
usleep(500*1000);
pthread_mutex_unlock(&g_mtx);
printf("mutex demo: thread %d left mutex!\\n", t_id);
usleep(500*1000);
}
}
void * thread1_yell (void *param)
{
int t_id = *(int*)param;
while(1)
{
printf("sync demo: thread %d wait for signal!\\n", t_id);
pthread_cond_wait(&g_cond, &g_mtx);
printf("sync demo: thread %d released!\\n", t_id);
sleep(1);
printf("sync demo: thread %d send the signal!\\n", t_id);
pthread_cond_signal(&g_cond);
}
}
void * thread2_yell (void *param)
{
int t_id = *(int*)param;
while(1)
{
sleep(1);
printf("sync demo: thread %d send the signal!\\n", t_id);
pthread_cond_signal(&g_cond);
printf("sync demo: thread %d wait for signal!\\n", t_id);
pthread_cond_wait(&g_cond, &g_mtx);
printf("sync demo: thread %d released!\\n", t_id);
}
}
int main(int argc, char **argv)
{
int argp = 1;
int t_id1 = 1;
int t_id2 = 2;
int mtx_sync = 0;
if ((argc > 2) || (argc < 1))
{
fprintf(stderr, "Usage:%s [m|s]\\n", argv[0]);
exit(1);
}
else if (argc == 1)
{
mtx_sync = 0;
}
else
{
if (!strcmp("m", argv[argp]))
{
mtx_sync = 0;
}
else if (!strcmp("s", argv[argp]))
{
mtx_sync = 1;
}
else
{
fprintf(stderr, "Usage:%s [m|s]\\n", argv[0]);
exit(1);
}
}
pthread_cond_init(&g_cond, 0);
pthread_mutex_init(&g_mtx, 0);
printf("===== linux multi-thread programming demo =====\\n");
if(mtx_sync)
{
pthread_create(&g_thread[0], 0, thread1_yell, (void *)&t_id1);
pthread_create(&g_thread[1], 0, thread2_yell, (void *)&t_id2);
pthread_join(g_thread[0], 0);
pthread_join(g_thread[1], 0);
}
else
{
pthread_create(&g_thread[0], 0, threadx_yell, (void *)&t_id1);
pthread_create(&g_thread[1], 0, threadx_yell, (void *)&t_id2);
pthread_join(g_thread[0], 0);
pthread_join(g_thread[1], 0);
}
pthread_cond_destroy(&g_cond);
pthread_mutex_destroy(&g_mtx);
return 0;
}
| 0
|
#include <pthread.h>
struct JobData {
int data;
int job_id;
};
struct Node {
struct JobData Job_Data;
struct Node * next;
};
struct Node * rear = 0;
struct Node * front = 0;
int size_actual = 0;
int queue_size;
pthread_mutex_t mutex;
sem_t empty;
sem_t full;
int produce_sleep_max;
int consume_sleep_max;
time_t seconds;
void Enqueue(int x, int id_num){
printf("Enqueueing-------------------\\n");
int i;
struct Node* temp = (struct Node*) malloc(sizeof(struct Node));
struct JobData * job_data = (struct JobData*) malloc(sizeof(struct JobData));
job_data->data = x;
job_data->job_id = id_num;
temp->Job_Data = *job_data;
temp->next = 0;
if(front ==0 && rear == 0){
front = rear = temp;
return;
}
rear->next =temp;
rear = temp;
}
struct JobData Dequeue(){
printf("Dequeueing-------------------\\n");
struct Node* temp = front;
struct JobData want = temp->Job_Data;
if(front == 0){
printf("queue is empty");
}
if(front == rear){
front = rear = 0;
}
else{
front = front->next;
}
free(temp);
return want;
}
void * Consumer(){
seconds= time(0);
while(1){
sem_wait(&full);
pthread_mutex_lock(&mutex);
struct JobData info = Dequeue();
int time2 = info.data;
int job = info.job_id;
pthread_mutex_unlock(&mutex);
unsigned int tid;
tid = (unsigned int) pthread_self();
seconds = time(0);
sleep(time2);
seconds= time(0);
sem_post(&empty);
}
}
void * Producer(){
seconds= time(0);
int id_num =0;
while(1){
sem_wait(&empty);
pthread_mutex_lock(&mutex);
int thread_time = (rand()%(consume_sleep_max+1 -1)) + 1;
seconds= time(0);
printf("Producer enqueing time: %d and id %d at time %ld\\n",thread_time,id_num, seconds);
Enqueue(thread_time, id_num);
pthread_mutex_unlock(&mutex);
sem_post(&full);
id_num ++;
int producer_time = (rand()%(produce_sleep_max+1 -1)) +1;
seconds = time(0);
printf("Producer sleeping for %d at time %ld\\n",producer_time,seconds);
sleep(producer_time);
}
}
int main(int argc, char * argv[]){
pthread_t pro,con;
if(argc < 3){
printf("Usage: <Number of threads (n)>, <Max wait time per request(M)>,<Producer sleep factor>\\n");
return(1);
}
queue_size = atoi(argv[1]);
consume_sleep_max = atoi(argv[2]);
produce_sleep_max = atoi(argv[3]);
pthread_mutex_init(&mutex, 0);
sem_init(&empty, 0, queue_size);
sem_init(&full , 0, 0);
int i;
for(i=0 ; i< queue_size; i++){
pthread_create(&con, 0, Consumer,0);
}
sleep(2);
pthread_create(&pro, 0, Producer,0);
while(1) { }
return 0;
}
| 1
|
#include <pthread.h>
int c;
int PC, DC, CC, DDC, QS;
char *PM;
struct ring_buffer *donut_type;
pthread_mutex_t p_lock;
pthread_mutex_t c_lock;
pthread_cond_t p_cond;
pthread_cond_t c_cond;
struct ring_buffer {
int *donut_queue;
int in;
int out;
int counter;
int space;
int donuts;
};
void* producer(void* arg) {
int j;
if(strcmp(PM, "in-order") == 0)
j = 0;
else
j = rand() % DC;
while(1) {
pthread_mutex_lock(&p_lock);
while(donut_type[j].space <= 0)
pthread_cond_wait(&p_cond, &p_lock);
donut_type[j].donut_queue[donut_type[j].in] = donut_type[j].counter;
donut_type[j].in = (donut_type[j].in + 1) % QS;
donut_type[j].counter++;
if(strcmp(PM, "in-order") == 0)
j = (j + 1) % DC;
else
j = rand() % DC;
donut_type[j].space--;
donut_type[j].donuts++;
pthread_mutex_unlock(&p_lock);
pthread_cond_signal(&p_cond);
}
pthread_exit(0);
}
void* consumer(void* arg) {
int donuts[12];
int type[12];
int i, j, k, m, c_num;
c_num = c++;
if(strcmp(PM, "in-order") == 0)
j = 0;
else
j = rand() % DC;
for(i = 0; i < DDC; i++) {
for(k = 0; k < 12; k++) {
pthread_mutex_lock(&c_lock);
while(donut_type[j].donuts <= 0)
pthread_cond_wait(&c_cond, &c_lock);
donuts[k] = donut_type[j].donut_queue[donut_type[j].out];
type[k] = j;
donut_type[j].out = (donut_type[j].out + 1) % QS;
if(strcmp(PM, "in-order") == 0)
j = (j + 1) % DC;
else
j = rand() % DC;
donut_type[j].donuts--;
donut_type[j].space++;
pthread_mutex_unlock(&c_lock);
pthread_cond_signal(&c_cond);
}
printf("(yum %d %d ( ", c_num, i);
for(m = 0; m < 12; m++) {
printf("[%d %d] ", type[m], donuts[m]);
}
printf(") )\\n");
}
pthread_exit(0);
}
int main(int argc, char* argv[]) {
if(argc != 7) {
printf("Missing command line args -- ./a4 [PC] [PM] [DC] [CC] [DDC] [QS]\\n");
exit(1);
}
c = 0;
int i, fail;
PC = atoi(argv[1]);
PM = argv[2];
DC = atoi(argv[3]);
CC = atoi(argv[4]);
DDC = atoi(argv[5]);
QS = atoi(argv[6]);
pthread_mutex_init(&p_lock, 0);
pthread_mutex_init(&c_lock, 0);
pthread_cond_init(&p_cond, 0);
pthread_cond_init(&c_cond, 0);
struct ring_buffer arr[DC];
pthread_t prod[PC];
pthread_t con[CC];
for(i = 0; i < DC; i++) {
struct ring_buffer rb;
rb.donut_queue = (int*)malloc(QS * sizeof(int));
rb.in = 0;
rb.out = 0;
rb.counter = 1;
rb.space = QS;
rb.donuts = 0;
arr[i] = rb;
}
donut_type = arr;
for(i = 0; i < PC; i++) {
fail = pthread_create(&(prod[i]), 0, &producer, 0);
if(fail != 0) {
perror("producer pthread create failed -- ");
exit(1);
}
}
for(i = 0; i < CC; i++) {
fail = pthread_create(&(con[i]), 0, &consumer, 0);
if(fail != 0) {
perror("consumer pthread create failed -- ");
exit(1);
}
}
for(i = 0; i < CC; i++) {
pthread_join(con[i], 0);
}
for(i = 0; i < PC; i++) {
pthread_cancel(prod[i]);
}
pthread_cond_destroy(&p_cond);
pthread_cond_destroy(&c_cond);
pthread_mutex_destroy(&p_lock);
pthread_mutex_destroy(&c_lock);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
void foo()
{
pthread_mutex_lock(&mutex);
printf("thread = %d\\n", (int)pthread_self());
pthread_mutex_unlock(&mutex);
}
void * func(void* ptr)
{
pthread_mutex_lock(&mutex);
foo();
pthread_mutex_unlock(&mutex);
}
int main()
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutex, &attr);
pthread_t tid;
pthread_create(&tid, 0, func, 0);
void* ret;
pthread_join(tid, &ret);
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 *idp)
{
int j,i;
double result=0;
int *my_id=idp;
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 %d, count=%d threshold reached.\\n",*my_id,count);
}
printf("inc_count():thread %d,count=%d,unlocking mutex\\n",*my_id,count);
pthread_mutex_unlock(&count_mutex);
sleep(1);
}
pthread_exit(0);
}
void *watch_count(void *idp)
{
int *my_id=idp;
printf("Starting watch_count():thread %d\\n",*my_id);
pthread_mutex_lock(&count_mutex);
if(count<12)
{
pthread_cond_wait(&count_threshold_cv,&count_mutex);
printf("watch_count():thread %d Condition signal received.\\n",*my_id);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main(int argc,char *argv[])
{
int i,rc;
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,inc_count,(void *)&thread_ids[0]);
pthread_create(&threads[1],&attr,inc_count,(void *)&thread_ids[1]);
pthread_create(&threads[2],&attr,watch_count,(void *)&thread_ids[2]);
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 thread_id;
int num_elements;
float *vector_a;
float *vector_b;
int offset;
int chunk_size;
double *sum;
pthread_mutex_t *mutex_for_sum;
} ARGS_FOR_THREAD;
float compute_gold(float *, float *, int);
float compute_using_pthreads(float *, float *, int);
void *dot_product(void *);
void print_args(ARGS_FOR_THREAD *);
int
main(int argc, char **argv)
{
if(argc != 2){
printf("Usage: vector_dot_product <num elements> \\n");
exit(1);
}
int num_elements = atoi(argv[1]);
float *vector_a = (float *)malloc(sizeof(float) * num_elements);
float *vector_b = (float *)malloc(sizeof(float) * num_elements);
srand(time(0));
for(int i = 0; i < num_elements; i++){
vector_a[i] = ((float)rand()/(float)32767) - 0.5;
vector_b[i] = ((float)rand()/(float)32767) - 0.5;
}
struct timeval start, stop;
gettimeofday(&start, 0);
float reference = compute_gold(vector_a, vector_b, num_elements);
gettimeofday(&stop, 0);
printf("Reference solution = %f. \\n", reference);
printf("Execution time = %fs. \\n", (float)(stop.tv_sec - start.tv_sec + (stop.tv_usec - start.tv_usec)/(float)1000000));
printf("\\n");
gettimeofday(&start, 0);
float result = compute_using_pthreads(vector_a, vector_b, num_elements);
gettimeofday(&stop, 0);
printf("Pthread solution = %f. \\n", result);
printf("Execution time = %fs. \\n", (float)(stop.tv_sec - start.tv_sec + (stop.tv_usec - start.tv_usec)/(float)1000000));
printf("\\n");
free((void *)vector_a);
free((void *)vector_b);
pthread_exit(0);
}
float
compute_gold(float *vector_a, float *vector_b, int num_elements)
{
double sum = 0.0;
for(int i = 0; i < num_elements; i++)
sum += vector_a[i] * vector_b[i];
return (float)sum;
}
float
compute_using_pthreads(float *vector_a, float *vector_b, int num_elements)
{
pthread_t thread_id[8];
pthread_attr_t attributes;
pthread_mutex_t mutex_for_sum;
pthread_attr_init(&attributes);
pthread_mutex_init(&mutex_for_sum, 0);
int i;
double sum = 0;
ARGS_FOR_THREAD *args_for_thread[8];
int chunk_size = (int)floor((float)num_elements/(float)8);
for(i = 0; i < 8; i++){
args_for_thread[i] = (ARGS_FOR_THREAD *)malloc(sizeof(ARGS_FOR_THREAD));
args_for_thread[i]->thread_id = i;
args_for_thread[i]->num_elements = num_elements;
args_for_thread[i]->vector_a = vector_a;
args_for_thread[i]->vector_b = vector_b;
args_for_thread[i]->offset = i * chunk_size;
args_for_thread[i]->chunk_size = chunk_size;
args_for_thread[i]->sum = ∑
args_for_thread[i]->mutex_for_sum = &mutex_for_sum;
}
for(i = 0; i < 8; i++)
pthread_create(&thread_id[i], &attributes, dot_product, (void *)args_for_thread[i]);
for(i = 0; i < 8; i++)
pthread_join(thread_id[i], 0);
for(i = 0; i < 8; i++)
free((void *)args_for_thread[i]);
return (float)sum;
}
void *
dot_product(void *args)
{
ARGS_FOR_THREAD *args_for_me = (ARGS_FOR_THREAD *)args;
double partial_sum = 0.0;
if(args_for_me->thread_id < (8 - 1)){
for(int i = args_for_me->offset; i < (args_for_me->offset + args_for_me->chunk_size); i++)
partial_sum += args_for_me->vector_a[i] * args_for_me->vector_b[i];
}
else{
for(int i = args_for_me->offset; i < args_for_me->num_elements; i++)
partial_sum += args_for_me->vector_a[i] * args_for_me->vector_b[i];
}
pthread_mutex_lock(args_for_me->mutex_for_sum);
*(args_for_me->sum) += partial_sum;
pthread_mutex_unlock(args_for_me->mutex_for_sum);
pthread_exit((void *)0);
}
void
print_args(ARGS_FOR_THREAD *args_for_thread)
{
printf("Thread ID: %d \\n", args_for_thread->thread_id);
printf("Num elements: %d \\n", args_for_thread->num_elements);
printf("Address of vector A on heap: %p \\n", args_for_thread->vector_a);
printf("Address of vector B on heap: %p \\n", args_for_thread->vector_b);
printf("Offset within the vectors for thread: %d \\n", args_for_thread->offset);
printf("Chunk size to operate on: %d \\n", args_for_thread->chunk_size);
printf("\\n");
}
| 1
|
#include <pthread.h>
int w, h;
v2df zero = { 0.0, 0.0 };
v2df four = { 4.0, 4.0 };
v2df nzero;
double inverse_w;
double inverse_h;
char *whole_data;
int y_pick;
pthread_mutex_t y_mutex = PTHREAD_MUTEX_INITIALIZER;
static void * worker(void *_args) {
char *data;
double x, y;
int bit_num;
char byte_acc = 0;
for (;;) {
pthread_mutex_lock(&y_mutex);
y = y_pick;
y_pick++;
pthread_mutex_unlock(&y_mutex);
if (y >= h)
return 0;
data = &whole_data[(w >> 3) * (int)y];
for(bit_num=0,x=0;x<w;x+=2)
{
v2df Crv = { (x+1.0)*inverse_w-1.5, (x)*inverse_w-1.5 };
v2df Civ = { y*inverse_h-1.0, y*inverse_h-1.0 };
v2df Zrv = { 0.0, 0.0 };
v2df Ziv = { 0.0, 0.0 };
v2df Trv = { 0.0, 0.0 };
v2df Tiv = { 0.0, 0.0 };
int i = 0;
int mask;
do {
Ziv = (Zrv*Ziv) + (Zrv*Ziv) + Civ;
Zrv = Trv - Tiv + Crv;
Trv = Zrv * Zrv;
Tiv = Ziv * Ziv;
v2df delta = (v2df)__builtin_ia32_cmplepd( (Trv + Tiv), four );
mask = __builtin_ia32_movmskpd(delta);
} while (++i < 50 && (mask));
byte_acc <<= 2;
byte_acc |= mask;
bit_num+=2;
if(!(bit_num&7)) {
data[(bit_num>>3) - 1] = byte_acc;
byte_acc = 0;
}
}
if(bit_num&7) {
byte_acc <<= (8-w%8);
bit_num += 8;
data[bit_num>>3] = byte_acc;
byte_acc = 0;
}
}
}
int main (int argc, char **argv)
{
pthread_t ids[8];
int i;
nzero = -zero;
w = h = atoi(argv[1]);
inverse_w = 2.0 / w;
inverse_h = 2.0 / h;
y_pick = 0;
whole_data = malloc(w * (w >> 3));
for (i = 0; i < 8; i++)
pthread_create(&ids[i], 0, worker, 0);
for (i = 0; i < 8; i++)
pthread_join(ids[i], 0);
pthread_mutex_destroy(&y_mutex);
printf("P4\\n%d %d\\n",w,h);
fwrite(whole_data, h, w >> 3, stdout);
free(whole_data);
return 0;
}
| 0
|
#include <pthread.h>
struct critical_data {
int len;
char buf[100];
}data[2];
{
pthread_mutex_t mutex;
pthread_cond_t cond;
unsigned short conditionMet;
unsigned short broadcast;
} my_lock_t;
my_lock_t lock = {PTHREAD_MUTEX_INITIALIZER,PTHREAD_COND_INITIALIZER,0,0};
void * write_thread (void *p)
{
sleep(1);
printf("\\n In Write thread\\n");
if(lock.conditionMet==0)
{
if(pthread_mutex_lock(&lock.mutex)==0)
{
printf("\\n\\t Entering critical section in Write thread \\n");
strcpy(data[0].buf,"Veda Solutions");
data[0].len=strlen("Veda Solutions");
strcpy(data[1].buf,"Solutions");
data[1].len=strlen("Solutions");
lock.broadcast = 1;
pthread_cond_broadcast(&lock.cond);
pthread_mutex_unlock(&lock.mutex);
printf ("\\t Leaving critical section in Write thread\\n");
}
}
pthread_exit(0);
}
void * read_thread1(void *p)
{
printf("\\n In Read thread1 \\n");
if(pthread_mutex_lock(&lock.mutex)==0)
{
while(lock.conditionMet!=1)
{
if(lock.broadcast == 1)
break;
pthread_cond_wait(&lock.cond,&lock.mutex);
}
printf("\\n\\t Entering critical section in Read thread1 \\n");
printf("\\n\\t %d %s \\n",data[0].len,data[0].buf);
pthread_mutex_unlock(&lock.mutex);
}
printf(" Read1 job is over\\n");
pthread_exit(0);
}
void * read_thread2(void *p)
{
printf("\\n In Read thread2 \\n");
if(pthread_mutex_lock(&lock.mutex)==0)
{
while(lock.conditionMet!=1 )
{
if(lock.broadcast == 1)
break;
pthread_cond_wait(&lock.cond,&lock.mutex);
}
printf("\\n\\t Entering critical section in Read2 thread \\n");
printf("\\n\\t %d %s \\n",data[1].len,data[1].buf);
pthread_mutex_unlock(&lock.mutex);
}
printf(" Read2 job is over\\n");
pthread_exit(0);
}
int main ()
{
pthread_t tid1,tid2,tid3;
int rv;
rv = pthread_create(&tid1, 0, write_thread, 0);
if(rv)
puts("Failed to create thread");
rv = pthread_create(&tid2, 0, read_thread1, 0);
if(rv)
puts("Failed to create thread");
rv = pthread_create(&tid3, 0, read_thread2, 0);
if(rv)
puts("Failed to create thread");
pthread_join(tid1,0);
pthread_join(tid2,0);
pthread_join(tid3,0);
puts(" Exit Main");
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
struct food {
struct food *next;
int num;
};
struct food *head=0;
void *producer(void*arg)
{
struct food *fp;
for(;;) {
fp = (struct food*)malloc(sizeof(struct food));
fp->num = rand()%1000 + 1;
printf("-Produce ---%d\\n", fp->num);
pthread_mutex_lock(&lock);
fp->next = head;
head = fp;
pthread_mutex_unlock(&lock);
fp = 0;
pthread_cond_signal(&has_product);
sleep(rand()%5);
}
}
void *consumer(void *arg)
{
struct food *fp;
for (;;) {
pthread_mutex_lock(&lock);
while(head == 0) {
pthread_cond_wait(&has_product, &lock);
}
fp = head;
head = fp->next;
pthread_mutex_unlock(&lock);
printf("-Consume ---%d\\n",fp->num);
free(fp);
fp = 0;
sleep(rand()%5);
}
}
int main()
{
srand(time(0));
pthread_t tid1, tid2;
pthread_create(&tid1, 0, producer, 0);
pthread_create(&tid2, 0, consumer, 0);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
return 0;
}
| 0
|
#include <pthread.h>
int key;
struct _list_node_t *next;
pthread_mutex_t lock;
} list_node_t;
void list_init(list_node_t **head)
{
*head = (list_node_t *)malloc(sizeof(list_node_t));
(*head)->key = INT_MIN;
pthread_mutex_init(&(*head)->lock, 0);
(*head)->next = (list_node_t *)malloc(sizeof(list_node_t));
(*head)->next->key = 32767;
pthread_mutex_init(&(*head)->next->lock, 0);
(*head)->next->next = 0;
}
size_t list_size(list_node_t *head)
{
size_t count = 0;
while (head != 0) {
count++;
head = head->next;
}
return count;
}
int list_add(list_node_t *head, int item)
{
list_node_t *pred, *curr;
pthread_mutex_lock(&head->lock);
pred = head;
curr = head->next;
pthread_mutex_lock(&curr->lock);
while (curr->key < item) {
pthread_mutex_unlock(&pred->lock);
pred = curr;
curr = curr->next;
pthread_mutex_lock(&curr->lock);
}
list_node_t *node = (list_node_t *)malloc(sizeof(list_node_t));
pthread_mutex_init(&node->lock, 0);
node->key = item;
node->next = curr;
pred->next = node;
pthread_mutex_unlock(&curr->lock);
pthread_mutex_unlock(&pred->lock);
return 1;
}
int list_remove(list_node_t *head, int item)
{
list_node_t *pred, *curr;
int retorno = 0;
pthread_mutex_lock(&head->lock);
pred = head;
curr = head->next;
pthread_mutex_lock(&curr->lock);
while (curr->key < item) {
pthread_mutex_unlock(&pred->lock);
pred = curr;
curr = curr->next;
pthread_mutex_lock(&curr->lock);
}
if (item == curr->key) {
pred->next = curr->next;
pthread_mutex_unlock(&curr->lock);
pthread_mutex_destroy(&curr->lock);
free(curr);
retorno = 1;
}
else
pthread_mutex_unlock(&curr->lock);
pthread_mutex_unlock(&pred->lock);
return retorno;
}
int list_contain(list_node_t *head, int item)
{
list_node_t *curr, *pred;
pthread_mutex_lock(&head->lock);
int retorno;
pred = head;
curr = head->next;
curr = head->next;
while (curr->key < item) {
pthread_mutex_unlock(&pred->lock);
pred = curr;
curr = curr->next;
pthread_mutex_lock(&curr->lock);
}
retorno = (item == curr->key);
pthread_mutex_unlock(&curr->lock);
pthread_mutex_unlock(&pred->lock);
return retorno;
}
void list_print(list_node_t *head)
{
if (head == 0) return;
list_node_t *curr = head;
fprintf(stdout, "[%d, ", curr->key);
curr = curr->next;
while (curr->next != 0)
{
fprintf(stdout, "%d, ", curr->key);
curr = curr->next;
}
fprintf(stdout, "%d]\\n", curr->key);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
void *another(void *arg)
{
printf("in child thread, lock the mutex\\n");
pthread_mutex_lock(&mutex);
sleep(5);
pthread_mutex_unlock(&mutex);
return 0;
}
int main(int argc, const char *argv[])
{
pthread_mutex_init(&mutex, 0);
pthread_t id;
pthread_create(&id, 0, another, 0);
sleep(1);
int pid = fork();
if(pid < 0)
{
pthread_join(id, 0);
pthread_mutex_destroy(&mutex);
return 1;
}
else if (pid == 0)
{
printf("I am in the child, want to get the lock\\n");
pthread_mutex_lock(&mutex);
printf("I can not run to here, oop .....\\n");
pthread_mutex_unlock(&mutex);
exit(0);
}
else
{
wait(0);
}
pthread_join(id, 0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
void *find_min(void *list_ptr);
pthread_mutex_t minimum_value_lock;
int minimum_value, partial_list_size;
int main()
{
static long list[100000000],i,n;
minimum_value = 0;
printf("enter the number of threads for which you want to run this program \\n");
scanf("%d",&n);
pthread_t thread1[n];
pthread_mutex_init(&minimum_value_lock, 0);
for(i=0;i<100;i++)
{
list[i]=random(100000000);
}
partial_list_size =100000000/n;
for(i=0;i<n;i++)
pthread_create( &thread1[i], 0, find_min, &list);
for(i=0;i<n;i++)
pthread_join( thread1[i], 0);
printf("The minimum value out of 100 million integers is%d\\n ",minimum_value);
printf("NOTE: This program takes a list of size 100million integers as asked in the programming assighnment\\n");
printf("The number of threads running on this program is %d\\n:",n);
return 0;
}
void *find_min(void *list_ptr)
{
int *partial_list_pointer, my_min, i;
my_min = 0;
partial_list_pointer = (int *) list_ptr;
for (i = 0; i < partial_list_size; i++)
if (partial_list_pointer[i] < my_min)
my_min = partial_list_pointer[i];
pthread_mutex_lock(&minimum_value_lock);
if (my_min < minimum_value)
minimum_value = my_min;
pthread_mutex_unlock(&minimum_value_lock);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int thread_count;
int n;
double sum = 0;
pthread_mutex_t mutex;
void* Thread_sum(void* rank);
int main(int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
thread_count = strtol(argv[1], 0, 10);
n = strtol(argv[2], 0, 10);
thread_handles = malloc(thread_count * sizeof(pthread_t));
for(thread = 0; thread < thread_count; thread++) {
pthread_create(&thread_handles[thread], 0,
Thread_sum, (void*) thread);
}
for(thread = 0; thread < thread_count; thread++) {
pthread_join(thread_handles[thread], 0);
}
free(thread_handles);
printf("%0.10f\\n", sum*4);
return 0;
}
void* Thread_sum(void* rank) {
long my_rank = (long) rank;
double factor;
long long i;
long long my_n = n/thread_count;
long long my_first_i = my_n * my_rank;
long long my_last_i = my_first_i + my_n;
double my_sum = 0.0;
if(my_first_i % 2 == 0)
factor = 1.0;
else
factor = -1.0;
for (i = my_first_i; i < my_last_i; i++, factor = -factor) {
my_sum += factor / (2*i + 1);
}
pthread_mutex_lock(&mutex);
sum += my_sum;
pthread_mutex_unlock(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
extern pthread_mutex_t global_data_mutex;
void create_rrd_file(void);
void start_rrd_logging(void *) {
char *rrd_args[2];
struct stat info;
app_debug("RRD: Starting RRD logging thread\\n");
if (stat(global_config.rrd_file, &info) == -1) {
create_rrd_file();
}
sleep(8);
rrd_args[0] = calloc(255,1);
rrd_args[1] = (char *)0;
while (1) {
pthread_mutex_lock(&global_data_mutex);
app_debug("RRD: Writing data\\n");
sprintf(rrd_args[0],"%i:%.2f:%.2f:%.2f:%i:%i:%.2f:%i",UPDATETM,TEMP,BARO,WINDAVG,WINDAVGDIR,HUMID,WINDGUST,WINDGUSTDIR);
pthread_mutex_unlock(&global_data_mutex);
rrd_update_r(global_config.rrd_file,"temp:baro:windavg:winddir:humidity:windgustspd:windgustdir",1,(const char **)rrd_args);
printf("%s\\n",rrd_get_error());
app_debug("RRD: Data writing complete (DATA BLOCK: %s\\n",rrd_args[0]);
sleep(global_config.rrd_interval);
}
}
void create_rrd_file(void) {
int argc = 8;
char *argv[] = {
"DS:temp:GAUGE:600:-50:150",
"DS:baro:GAUGE:600:26:36",
"DS:windavg:GAUGE:600:0:50",
"DS:winddir:GAUGE:600:0:17",
"DS:humidity:GAUGE:600:0:101",
"DS:windgustspd:GAUGE:600:0:50",
"DS:windgustdir:GAUGE:600:0:17",
"RRA:LAST:0.5:1:86400",
(char*)0
};
time_t start = time(0)-600;
app_debug("RRD: Creating new RRD file %s\\n",global_config.rrd_file);
rrd_create_r(global_config.rrd_file, global_config.rrd_interval, start, argc, (const char **)argv);
app_debug("RRD: Created new RRD file %s\\n",global_config.rrd_file);
}
| 1
|
#include <pthread.h>
int buffer[100];
sem_t s1;
pthread_mutex_t semaphore_mutex;
void *producer_task(void *data);
void *consumer_task();
void print_array();
int main(void){
pthread_t t1,t2,t3,c1,c2;
sem_init(&s1,0,100);
print_array();
int d1=1,d2=2,d3=3;
if (pthread_create(&t1, 0,producer_task,(void *)&d1)){
printf("producerTask creation failed\\n");fflush(stdout);
exit(1);
}
if (pthread_create(&t2, 0,producer_task,(void *)&d2)){
printf("producerTask creation failed\\n");fflush(stdout);
exit(1);
}
if (pthread_create(&t3, 0,producer_task,(void *)&d3)){
printf("producerTask creation failed\\n");fflush(stdout);
exit(1);
}
if (pthread_create(&c1, 0,consumer_task,0)){
printf("consumer Task creation failed\\n");fflush(stdout);
exit(1);
}
if (pthread_create(&c1, 0,consumer_task,0)){
printf("consumer Task creation failed\\n");fflush(stdout);
exit(1);
}
print_array();
if( ~(pthread_join(t1,0) && pthread_join(t2,0) && pthread_join(t3,0) && pthread_join(c1,0) && pthread_join(c2,0) )){
printf("Failed joining the threads\\n");fflush(stdout);
exit(1);
}
print_array();
return 0;
}
void *producer_task(void *data){
int c =0;
while(c<10){
pthread_mutex_lock(&semaphore_mutex);
sem_wait(&s1);
pthread_mutex_unlock(&semaphore_mutex);
int count;
sem_getvalue(&s1,&count);
buffer[count-1] = *((int *)data);
c++;
}
}
void *consumer_task(){
int c=0;
while(c<15){
pthread_mutex_lock(&semaphore_mutex);
int count;
sem_getvalue(&s1,&count);
int data;
if (count>1){
data=buffer[count-1];
buffer[count-1] = 0;
sem_post(&s1);
}
pthread_mutex_unlock(&semaphore_mutex);
if(count>1) { printf("value read by thread id: %d is %d\\n",pthread_self(),data); fflush(stdout); }
}
}
void print_array(){
printf("Array:\\n\\t");fflush(stdout);
for (int i=0;i<100;i++){
printf("%d\\t",buffer[i]);fflush(stdout);
}
printf("\\n");fflush(stdout);
}
| 0
|
#include <pthread.h>
long long array[256];
int cnt, in, out;
pthread_mutex_t lock;
} buffer;
buffer * newBuffer(void) {
buffer * new = calloc(1, sizeof(buffer));
pthread_mutex_init(&new->lock, 0);
return new;
}
int addToBuffer(long long val, buffer * b) {
int rv = -1;
pthread_mutex_lock(&b->lock);
if(b->cnt < 256) {
rv = b->in;
b->array[b->in] = val;
b->in = (b->in + 1) % 256;
b->cnt++;
}
pthread_mutex_unlock(&b->lock);
return rv;
}
long long takeFromBuffer(buffer * b) {
long long rv = -1;
pthread_mutex_lock(&b->lock);
if(b->cnt > 0){
rv = b->array[b->out];
b->out = (b->out + 1) % 256;
b->cnt--;
}
pthread_mutex_unlock(&b->lock);
return rv;
}
void * sieve(void * b) {
pthread_t thread_id;
long long s = -1;
long long n;
long long a = -1;
buffer * in = (buffer * )b;
buffer * out = newBuffer();
while (s == -1)
s = takeFromBuffer(in);
if (pthread_create(&thread_id, 0, &sieve, (void *)out))
printf("Couldnt make thread :(\\n");
printf("%lld\\n", s);
while(1) {
n = takeFromBuffer(in);
if (n != -1 && n % s != 0) {
while(a == -1) {
a = addToBuffer(n, out);
}
a = -1;
}
}
return 0;
}
int main(void) {
buffer * out = newBuffer();
long long n = 2;
int a;
pthread_t thread_id;
pthread_create(&thread_id, 0, &sieve, (void *)out);
while (1) {
a = -1;
while (a == -1)
a = addToBuffer(n, out);
n++;
}
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static int num_workers;
static int box_next;
static int non_box;
static unsigned int *boxcnt = 0;
struct nameround *next;
char *boxname;
int round;
} nameround_t;
static nameround_t *head = 0;
static int findMinBoxes( void)
{
int i;
unsigned int i_min=0, minval=4294967295U;
for (i=0; i<num_workers; i++) {
if (boxcnt[i] < minval) {
minval = boxcnt[i];
i_min = i;
}
}
return i_min;
}
void SNetAssignInit(int lpel_num_workers)
{
int i;
num_workers = lpel_num_workers;
boxcnt = (unsigned int*) SNetMemAlloc( num_workers * sizeof(unsigned int));
for(i=0;i<num_workers;i++) {
boxcnt[i] = 0;
}
non_box = num_workers -1;
box_next = 0;
}
void SNetAssignCleanup( void)
{
SNetMemFree( boxcnt);
while (head != 0) {
nameround_t *n = head;
head = n->next;
SNetMemFree(n->boxname);
SNetMemFree(n);
}
}
int SNetAssignTask(int is_box, const char *boxname)
{
int target = 0;
pthread_mutex_lock( &lock);
if (is_box) {
nameround_t *n = head;
while (n != 0) {
if ( 0 == strcmp(n->boxname, boxname)) break;
n = n->next;
}
if (n == 0) {
n = (nameround_t *) SNetMemAlloc( sizeof(nameround_t));
n->round = findMinBoxes();
n->boxname = strdup(boxname);
n->next = head;
head = n;
}
target = n->round;
n->round = (n->round + 1) % num_workers;
boxcnt[target]++;
} else {
target = non_box;
non_box = (non_box + 1) % num_workers;
}
pthread_mutex_unlock( &lock);
return target;
}
| 0
|
#include <pthread.h>
int material;
int mm1;
int mm2;
int coloca;
pthread_mutex_t zain = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t tutzke = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t yaharadin = PTHREAD_MUTEX_INITIALIZER;
void agente (void* arg)
{
int r1=0;
int r2=0;
while(1){
pthread_mutex_lock(&zain);
pthread_mutex_lock(&tutzke);
pthread_mutex_lock(&yaharadin);
if(coloca)
{
coloca=0;
srand(time(0));
mm1=rand()%3;
do{
mm2=rand()%3;
}while(mm1==mm2);
printf("soy el agente y coloque %d y %d\\n", mm1,mm2);
}
pthread_mutex_unlock(&yaharadin);
pthread_mutex_unlock(&tutzke);
pthread_mutex_unlock(&zain);
}
}
void fumar1(void * arg1)
{
int mine1;
mine1= ((int*)(arg1));
while(1){
pthread_mutex_lock(&zain);
pthread_mutex_lock(&tutzke);
pthread_mutex_lock(&yaharadin);
if(mine1 ==mm1 || mine1==mm2)
{
pthread_mutex_unlock(&yaharadin);
pthread_mutex_unlock(&tutzke);
pthread_mutex_unlock(&zain);
}else{
mm1=-1;
mm2=-1;
coloca=1;
pthread_mutex_unlock(&yaharadin);
pthread_mutex_unlock(&tutzke);
pthread_mutex_unlock(&zain);
printf("soy el fumador %d, y me dio caner\\n", mine1);
}
}
pthread_exit(0);
}
void fumar2(void * arg2)
{
int mine2;
mine2= ((int*)(arg2));
while(1){
pthread_mutex_lock(&zain);
pthread_mutex_lock(&tutzke);
pthread_mutex_lock(&yaharadin);
if(mine2 ==mm1 || mine2==mm2)
{
pthread_mutex_unlock(&yaharadin);
pthread_mutex_unlock(&tutzke);
pthread_mutex_unlock(&zain);
}else{
mm1=-1;
mm2=-1;
coloca=1;
pthread_mutex_unlock(&yaharadin);
pthread_mutex_unlock(&tutzke);
pthread_mutex_unlock(&zain);
printf("soy el fumador %d, y me dio caner\\n", mine2);
}
}
pthread_exit(0);
}
void fumar3(void * arg3)
{
int mine3;
mine3= ((int*)(arg3));
while(1){
pthread_mutex_lock(&zain);
pthread_mutex_lock(&tutzke);
pthread_mutex_lock(&yaharadin);
if(mine3 ==mm1 || mine3==mm2)
{
pthread_mutex_unlock(&yaharadin);
pthread_mutex_unlock(&tutzke);
pthread_mutex_unlock(&zain);
}else{
mm1=-1;
mm2=-1;
coloca=1;
pthread_mutex_unlock(&yaharadin);
pthread_mutex_unlock(&tutzke);
pthread_mutex_unlock(&zain);
printf("soy el fumador %d, y me dio caner\\n", mine3);
}
}
pthread_exit(0);
}
int main()
{
mm1 = 0;
mm2 = 2;
coloca=0;
pthread_t* tids= (pthread_t*)malloc(4*sizeof(pthread_t));
pthread_create((tids),0,agente,1);
pthread_create((tids+1),0,fumar1,0);
pthread_create((tids+2),0,fumar2,1);
pthread_create((tids+3),0,fumar3,2);
pthread_join(*(tids),0);
pthread_join(*(tids+1),0);
pthread_join(*(tids+2),0);
pthread_join(*(tids+3),0);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_t pthid, cthid;
static pthread_cond_t cond;
static pthread_mutex_t mux;
static int release;
static void *thread_for_consume(void *args);
static void *thread_for_produce(void *args);
static void init(void);
static void
init(void) {
release = 0;
pthread_mutex_init(&mux, 0);
pthread_cond_init(&cond, 0);
}
static void *
thread_for_produce(void *args) {
int release_old;
pthid = pthread_self();
pthread_mutex_lock(&mux);
release_old = release;
release = 1;
printf("[produce_thread_%u] release changed, old: %d, new: %d\\n",
(unsigned int)pthid,
release_old,
release);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mux);
}
static void *
thread_for_consume(void *args) {
cthid = pthread_self();
pthread_mutex_lock(&mux);
while( release == 0 ) {
printf("[consume_thread_%u] wait...\\n", (unsigned int)cthid);
pthread_cond_wait(&cond, &mux);
}
pthread_mutex_unlock(&mux);
printf("[consume_thread_%u] current release: %d\\n", (unsigned int)cthid, release);
printf("[consume_thread_%u] todo consume data\\n", (unsigned int)cthid);
}
int main(void) {
init();
pthread_create(&cthid, 0, (void *)thread_for_consume, 0);
sleep(1);
pthread_create(&pthid, 0, (void *)thread_for_produce, 0);
pthread_join(cthid, 0);
pthread_join(pthid, 0);
return 0;
}
| 0
|
#include <pthread.h>
struct _args{
int n;
pthread_mutex_t mutex;
float lat;
} args;
float latency(void (*request)()) {
struct timeval begin, end;
float time_spent;
gettimeofday(&begin, 0);
request();
gettimeofday(&end, 0);
time_spent = (end.tv_sec - begin.tv_sec) * 1000.0f + (end.tv_usec - begin.tv_usec) / 1000.0f;
return time_spent;
}
void connect_get() {
int cnt, m, size = 500;
char buf[500];
char req[32] = " GET / HTTP/1.1 \\r\\n";
int sock = i_socket();
char* host = "localhost";
int port = 1234;
if(i_connect(sock, host, port) < 0) {
printf("Connection refused\\n");
exit(1);
}
send(sock, req, sizeof(req), 0);
m = 0;
while((cnt=read(sock, buf, size)) > 0) {
m += cnt;
if(m >= 12) break;
}
close(sock);
}
void* periodic_client(void* no_args) {
float client_lat = 0.0;
int n = args.n;
for(int i = 0; i < n; i++)
{
client_lat += latency(&connect_get);
sleep(0.3);
}
pthread_mutex_lock(&args.mutex);
args.lat += client_lat;
pthread_mutex_unlock(&args.mutex);
pthread_exit(0);
}
void* aperiodic_client(void* no_args) {
float client_lat = 0.0;
int n = args.n;
for(int i = 0; i < n; i++)
{
client_lat += latency(&connect_get);
sleep(0.3 + (rand() % 4));
}
pthread_mutex_lock(&args.mutex);
args.lat += client_lat;
pthread_mutex_unlock(&args.mutex);
pthread_exit(0);
}
void thread_dispatcher(int scenario, int nb_client) {
int req_n = nb_client * 20;
int i = 0;
pthread_t threads[nb_client];
args.n = 20;
pthread_mutex_init(&args.mutex, 0);
args.lat = 0.0;
while(i < nb_client) {
switch(scenario) {
case 1:
pthread_create(&threads[i], 0, &periodic_client, 0);
break;
case 2:
pthread_create(&threads[i], 0, &aperiodic_client, 0);
break;
}
i++;
}
i = 0;
while (i < nb_client) {
pthread_join(threads[i], 0);
i++;
}
printf("Requests served per second : %.1f\\n"
"Total latency : %.2f ms\\n", req_n/(args.lat * 0.001), args.lat);
}
int main(int argc, char **argv) {
if (argc != 3)
{
printf(" Usage : web_client SCENARIO nCLIENT\\n"
" SCENARIO = 1 (periodic) or 2 (aperiodic)\\n"
" nCLIENT = n (number of clients)\\n");
return -1;
}
thread_dispatcher(atoi(argv[1]), atoi(argv[2]));
return 0;
}
| 1
|
#include <pthread.h>
int asc_code;
int ocorrencias;
}Caracter;
long posicao_global = 0;
long buffleng;
char *buffer;
Caracter *lista_asc;
pthread_mutex_t mutex;
int hashCode(int key) {
return ( key + 61) % 94;
}
int search(int key) {
int hashIndex = hashCode(key);
if(key == lista_asc[hashIndex].asc_code ){
lista_asc[hashIndex].ocorrencias++;
return 1;
}
else
return 0;
}
Caracter* preenche_asc(){
int i;
Caracter *vetor = (Caracter*) malloc(94*sizeof(Caracter));
for(i = 0; i < 94; i++){
vetor[i].asc_code = i + 33;
vetor[i].ocorrencias = 0;
}
return vetor;
}
char* gera_buffer(FILE* arq_entrada ){
fseek(arq_entrada, 0 , 2);
buffleng = ftell(arq_entrada);
rewind(arq_entrada);
char *buffer = (char*) malloc((buffleng )*sizeof(char));
return buffer;
}
void* conta_caracteres(void* args){
static long posicao_local = 0; int tid = *(int*) args;
while(posicao_local < buffleng){
pthread_mutex_lock(&mutex);
posicao_local = posicao_global;
search(buffer[posicao_local]);
posicao_local++;
posicao_global = posicao_local;
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void escreve_saida(FILE* arq_saida){
int i;
fprintf(arq_saida, "Simbolo | Ocorrencias\\n");
for( i = 0; i < 94;i++){
if(lista_asc[i].ocorrencias != 0)
fprintf(arq_saida, " %c, %d\\n", lista_asc[i].asc_code, lista_asc[i].ocorrencias);
}
fclose(arq_saida);
}
int main(int argc, char* argv[]){
if(argc < 4 ){
printf("passe %s <arquivo de texto a ser lido> <nome do arquivo de saida> <número de threads>\\n",argv[0]);
exit(1);
}
FILE* arq_entrada = fopen(argv[1], "rb");
FILE* arq_saida = fopen( argv[2], "w");
buffer = gera_buffer(arq_entrada);
lista_asc = preenche_asc();
fread(buffer, buffleng, 1, arq_entrada);
printf("CONTANDO CARACTERES DO TEXTO...\\n");
int t, nthreads = atoi(argv[3]); double inicio, fim , tempo;
printf("nthreads: %d\\n", nthreads);
pthread_t thread[nthreads];
int *tid;
pthread_mutex_init(&mutex, 0);
GET_TIME(inicio);
for( t=0; t<nthreads; t++){
tid = (int*) malloc(sizeof(int));
*tid = t;
pthread_create(&thread[t], 0, conta_caracteres,(void*) tid);
}
for (t = 0; t < nthreads; t++) {
pthread_join(thread[t], 0);
}
GET_TIME(fim);
tempo = fim - inicio;
fclose(arq_entrada);
escreve_saida(arq_saida);
printf("TEMPO EM MINUTOS COM %d threads: %.8f minutos.\\n", nthreads,tempo/60);
pthread_mutex_destroy(&mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static size_t i_gloabl_n = 0;
void *thr_demo(void *args)
{
printf("this is thr_demo thread, pid: %d, tid: %lu\\n", getpid(), pthread_self());
int i;
size_t t;
size_t tid = pthread_self();
setbuf(stdout, 0);
for (i = 0; i < 10; ++i) {
pthread_mutex_lock(&mutex);
t = i_gloabl_n;
++t;
usleep(1000);
i_gloabl_n = t;
pthread_mutex_unlock(&mutex);
}
return (void *)0;
}
void *thr_demo2(void *args)
{
printf("this is thr_demo2 thread, pid: %d, tid: %lu\\n", getpid(), pthread_self());
int i;
size_t tid = pthread_self();
setbuf(stdout, 0);
for (i = 0; i < 10; ++i) {
pthread_mutex_lock(&mutex);
printf("(tid: %lu):%lu\\n", tid, ++i_gloabl_n);
pthread_mutex_unlock(&mutex);
}
return (void *)10;
}
int main()
{
pthread_t pt1, pt2;
struct timeval time_start, time_end;
int arg = 20;
int ret;
ret = gettimeofday(&time_start, 0);
int *heap = (int *)malloc(sizeof(int));
assert(heap != 0);
ret = pthread_create(&pt1, 0, thr_demo, heap);
if (ret != 0) {
do { perror("pthread_create"); exit(-1); } while(0);
}
ret = pthread_create(&pt2, 0, thr_demo2, heap);
if (ret != 0) {
do { perror("pthread_create"); exit(-1); } while(0);
}
printf("this is main thread, pid = %d, tid = %lu\\n", getpid(), pthread_self());
ret = pthread_join(pt1, (void *)&arg);
if (ret != 0) {
do { perror("pthread_join"); exit(-1); } while(0);
}
printf("arg = %d\\n", arg);
ret = pthread_join(pt2, (void *)&arg);
if (ret != 0) {
do { perror("pthread_join"); exit(-1); } while(0);
}
printf("arg = %d\\n", arg);
pthread_mutex_destroy(&mutex);
ret = gettimeofday(&time_end, 0);
printf("cost time: %lums\\n", (time_end.tv_usec - time_start.tv_usec) / 1000);
free(heap);
return 0;
}
| 1
|
#include <pthread.h>
int num_primos = 0;
int *arrayPrimos = 0;
int incremento = (int)(50/9);
pthread_mutex_t bufferPrimosLock = PTHREAD_MUTEX_INITIALIZER;
void *encontrarPrimos(void *param) {
int low = (int)param * incremento;
int high = low + incremento;
while (low < high) {
int flag = 0;
for (size_t i = 2; i <= low/2; i++) {
if (low % i == 0) {
flag = 1;
break;
}
}
pthread_mutex_lock(&bufferPrimosLock);
if (flag == 0 & low != 1 && low != 0) {
arrayPrimos = realloc((int *) arrayPrimos, (num_primos+1)*sizeof(int));
arrayPrimos[num_primos] = low;
num_primos++;
}
++low;
pthread_mutex_unlock(&bufferPrimosLock);
}
}
int main(int argc, char const *argv[]) {
pthread_t threads[9];
arrayPrimos = (int *) malloc(sizeof(int));
for (size_t i = 0; i < 9; i++)
pthread_create(&threads[i], 0, encontrarPrimos, (void *) i);
for (size_t i = 0; i < 9; i++)
pthread_join(threads[i], 0);
printf("Threads encerraram.\\nArray de primos (são %d):\\n", num_primos);
for (size_t i = 0; i < num_primos; i++)
printf("[%d]\\n", arrayPrimos[i]);
return 0;
}
| 0
|
#include <pthread.h>
static pthread_t guiplayerthread={0};
static pthread_cond_t cond={{0}};
static pthread_mutex_t mutex={{0}};
static pthread_mutex_t guimutex={{0}};
static bool goingtoend=0;
extern struct Root *root;
extern void P2MUpdateSongPosCallBack(void);
static void *PlayerGuiThread(void *arg){
for(;;){
pthread_cond_wait(&cond,&mutex);
if(goingtoend==1) break;
pthread_mutex_lock(&guimutex);
P2MUpdateSongPosCallBack();
UpdateClock(root->song->tracker_windows);
XFlush(x11_display);
pthread_mutex_unlock(&guimutex);
}
return 0;
}
bool StartGuiThread(void){
pthread_mutex_init(&guimutex,0);
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond,0);
if(pthread_create(&guiplayerthread,0,PlayerGuiThread,0)!=0){
fprintf(stderr,"Could not start a thread.\\n");
return 0;
}
return 1;
}
void EndGuiThread(void){
goingtoend=1;
pthread_cond_broadcast(&cond);
pthread_join(guiplayerthread,0);
}
void lockGUI(void){
pthread_mutex_lock(&guimutex);
}
void unlockGUI(void){
pthread_mutex_unlock(&guimutex);
}
void Ptask2Mtask(void){
pthread_cond_broadcast(&cond);
}
| 1
|
#include <pthread.h>
char name[256];
static int name_i = 0;
static int ppi = 0;
pthread_mutex_t number_mutex;
pthread_mutex_t number2_mutex;
void recv_user_info(int con_fd, char *info)
{
if(recv(con_fd, info, sizeof(info), 0) < 0)
{
perror("recv");
exit(1);
}
}
void exe_in(int *con_fd)
{
int i,j;
int flag = 1;
char ret[10][256];
int s = -1;
int newfd[10];
int k = -1;
char quit_name[256];
FILE *fp;
time_t now;
struct tm *timenow;
time(&now);
timenow = localtime(&now);
s++;
k++;
fp = fopen("system_log_q", "a+");
printf("you are the %d people, con_fd:%d, name:%s, time:%s\\n",ppi,*con_fd,name, asctime(timenow));
pthread_mutex_lock(&number2_mutex);
strncpy(quit_name, name, 40);
newfd[k] = *con_fd;
fflush(stdout);
memset(tmpname[name_i], 0, 40);
recv(newfd[k], tmpname[name_i], 40, 0);
fprintf(fp,"user:%s state:%s ", tmpname[name_i], name);
pthread_mutex_unlock(&number2_mutex);
while(flag)
{
recv(newfd[k], ret[s], 256, 0);
printf("s = %d,*con_fd = %d\\n",s,newfd[k]);
printf("服务器收到\\n");
for(i = 0; i < 10; i++)
{
send(people[i].confd, ret[s], strlen(ret[s]), 0);
}
printf("s = %d.people[i].confd = %d\\n",s,people[i].confd);
printf("服务器已发送,%s\\n",people[i].name);
if(strcmp(ret[s], "bye") == 0)
{
for(j = 0; j < 10; j++)
{
if(strcmp(tmpname[j], quit_name) == 0)
{
memset(tmpname, 0, 40);
}
}
pthread_exit(0);
}
memset(ret[s], 0, 256);
}
}
void exe_info(int *con_fd)
{
int i,j;
int flag = 1;
char ret[10][256];
int s = -1;
int newfd[10];
int k = -1;
char quit_name[256];
FILE *fp;
time_t now;
struct tm *timenow;
time(&now);
timenow = localtime(&now);
s++;
k++;
fp = fopen("system_log_s.txt", "a+");
printf("you are the %d people, con_fd:%d, name:%s, time:%s\\n",ppi,*con_fd,name, asctime(timenow));
strncpy(quit_name, name, 40);
newfd[k] = *con_fd;
pthread_mutex_lock (&number_mutex);
fflush(stdout);
memset(tmpname[name_i], 0, 40);
recv(newfd[k], tmpname[name_i], 40, 0);
printf("接收聊天对象->tmp_name:%s\\n",tmpname[name_i]);
fprintf(fp, "user:%s obj:%s time:%s", quit_name, tmpname[name_i], asctime(timenow));
printf("您要和%s聊天,con_fd = %d\\n",tmpname[name_i],newfd[k]);
for(i = 0; i < 10; i++)
{
if(strcmp(tmpname[name_i], people[i].name) == 0)
break;
}
if(i == 10)
{
printf("\\n抱歉!您查找的人不存在!\\n您不能和不存在的人聊天\\n请重新输入\\n");
return;
}
send(people[i].confd, tmpname[name_i], strlen(tmpname[name_i]), 0);
name_i++;
pthread_mutex_unlock (&number_mutex);
fclose(fp);
while(flag)
{
recv(newfd[k], ret[s], 256, 0);
printf("s = %d,*con_fd = %d\\n",s,newfd[k]);
printf("服务器收到\\n");
send(people[i].confd, ret[s], strlen(ret[s]), 0);
printf("s = %d.people[i].confd = %d\\n",s,people[i].confd);
printf("服务器已发送,%s\\n",people[i].name);
if(strcmp(ret[s], "bye") == 0)
{
for(j = 0; j < 10; j++)
{
if(strcmp(tmpname[j], quit_name) == 0)
{
memset(tmpname, 0, 40);
}
}
pthread_exit(0);
}
memset(ret[s], 0, 256);
}
}
void input(char *buf)
{
int i= 0;
char ch;
while((ch = getchar()) != '\\n')
{
buf[i] = ch;
i++;
}
buf[i] = '\\0';
}
int main(int argc, char *argv[])
{
int sock_fd, con_fd, client_len;
struct sockaddr_in my_addr,client_addr;
int i = 0,j, k;
int tmp_confd;
pthread_t thid;
for(k = 0; k < 10; k++)
{
user[k].flag = -1;
}
for(j = 0; j < 10; j++)
{
people[j].confd = -1;
j++;
}
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
memset(&my_addr, 0, sizeof(my_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(4057);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(sock_fd, (struct sockaddr*)&my_addr, sizeof(struct sockaddr_in));
if(listen(sock_fd, 10) < 0)
{
perror("listen");
exit(1);
}
client_len = sizeof(struct sockaddr_in);
while(1)
{
con_fd = accept(sock_fd, (struct sockaddr*)&client_addr, &client_len);
memset(name, 0, sizeof(name));
recv_user_info(con_fd, name);
if(strcmp(name, "group") == 0)
{
printf("要开始群聊啦!!\\n");
pthread_create(&thid, 0, (void *)exe_in, &con_fd);
}
else
{
strcpy(people[ppi].name, name);
people[ppi].confd = con_fd;
ppi++;
printf("%s登陆啦!!\\n",name);
pthread_create(&thid, 0, (void *)exe_info, &con_fd);
}
}
close(sock_fd);
return 0;
}
| 0
|
#include <pthread.h>
char inputFile[100];
int wordCount = 1;
char* wordList[1024];
void* countWordFrequency(void *);
void countWord(char * filename);
void loadWordstoArray(char * filename);
void threadTask();
void consolidateResult();
void cleanupTask();
pthread_mutex_t lock;
pthread_t thread[3];
struct sharedWordStruct{
char word[20];
int frequency;
};
struct sharedWordStruct sharedObj[1024];
int sharedIndex = 0;
void main(void)
{
printf("%s","Enter the filename:");
scanf("%s",inputFile);
countWord(inputFile);
if (wordCount > 1 && wordCount <= 1024)
{
loadWordstoArray(inputFile);
threadTask();
consolidateResult();
cleanupTask();
}
else
{
printf("%s\\n","***ERROR*** File is either too small/large for further processing!");
exit(1);
}
}
void countWord(char * filename)
{
FILE *readFilePtr;
char c;
printf("\\n%s","1. Counting number of words in the file");
readFilePtr = fopen(filename,"r");
if(readFilePtr == 0)
{
printf("%s\\n","***ERROR*** File cannot be opened!");
exit(1);
}
else
{
while((c = fgetc(readFilePtr)) != EOF)
{
if(c == ' ' || c == '\\n' || c == '\\t')
wordCount++;
}
}
}
void loadWordstoArray(char * filename)
{
FILE *readFilePtr;
int size = 0;
int i ,j = 0;
printf("\\n%s","2. Loading words from the file");
readFilePtr = fopen(filename,"r");
if(readFilePtr == 0)
{
printf("%s\\n","***ERROR*** File cannot be opened!");
exit(1);
}
else
{
for (i =0; i < wordCount; ++i)
{
wordList[i] = malloc(20);
fscanf (readFilePtr, "%s", wordList[i]);
}
}
}
void* countWordFrequency(void * tid)
{
int thread_id = * (int*) tid;
int words_per_partition, start_index,end_index,spill_over = 0;
words_per_partition = wordCount / 3;
start_index= thread_id * words_per_partition;
end_index = start_index + (words_per_partition - 1);
if(thread_id == (3 -1))
{
spill_over = wordCount % 3;
if(spill_over>=1)
{
start_index= thread_id * words_per_partition;
end_index = start_index + (words_per_partition + spill_over - 1);
words_per_partition = words_per_partition + spill_over;
}
}
printf("Thread %d - Start_index: %d End_index: %d\\n",thread_id+1,start_index,end_index);
struct wordStruct{
char word[20];
int frequency;
};
struct wordStruct obj[words_per_partition];
int i,j;
int index=0;
for(i=start_index;i<=end_index;i++)
{
int foundIndex = -1;
for(j=0;j<index;j++)
{
if(strcasecmp(obj[j].word, wordList[i])==0){
foundIndex = j;
break;
}
}
if(foundIndex == -1 ){
strcpy(obj[index].word,wordList[i]);
obj[index].frequency = 1;
index++;
} else {
obj[foundIndex].frequency++;
}
}
pthread_mutex_lock(&lock);
printf("\\tThread %d entered critical region\\n", thread_id+1);
for(i=0;i<index;i++)
{
strcpy(sharedObj[sharedIndex].word,obj[i].word);
sharedObj[sharedIndex].frequency = obj[i].frequency;
sharedIndex++;
}
pthread_mutex_unlock(&lock);
printf("\\tThread %d exited critical region\\n", thread_id+1);
free(tid);
}
void threadTask()
{
int i;
printf("%s\\n","3. Initailzing the mutex");
if(pthread_mutex_init(&lock, 0) != 0)
{
printf("%s\\n","***ERROR*** Mutex Initialization error!");
exit(1);
}
printf("%s\\n","4. Thread creation and execution");
for(i=0;i<3;i++)
{
int *temp = malloc(sizeof(*temp));
*temp = i;
if(pthread_create(&thread[i], 0, countWordFrequency, (void *)temp)!=0)
{
printf("%s\\n","***ERROR*** Thread creation failed!");
exit(1);
}
}
for (i=0;i<3;i++)
{
pthread_join(thread[i], 0);
}
}
void consolidateResult()
{
int i=0;
int index = 0;
int j=0;
struct wordStruct{
char word[20];
int frequency;
};
struct wordStruct obj[100];
printf("%s\\n","5. Main thread consolidating the result");
for(i=0;i<sharedIndex;i++)
{
int foundIndex = -1;
for(j=0;j<index;j++)
{
if(strcasecmp(obj[j].word, sharedObj[i].word)==0){
foundIndex = j;
break;
}
}
if(foundIndex == -1 ){
strcpy(obj[index].word,sharedObj[i].word);
obj[index].frequency = sharedObj[i].frequency;
index++;
} else {
obj[foundIndex].frequency += sharedObj[i].frequency;
}
}
printf("\\n-------------------------------------\\n");
printf("%s\\t\\t%s\\n","Word","Frequency");
printf("-------------------------------------\\n");
for(i=0;i<index;i++)
{
printf("%s\\t\\t", obj[i].word);
printf("%d\\n", obj[i].frequency);
}
}
void cleanupTask()
{
pthread_mutex_destroy(&lock);
int i;
for (i =0; i < wordCount; ++i)
free (wordList[i]);
printf("%s\\n","Memory free!");
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
unsigned int __VERIFIER_nondet_uint();
static int top=0;
static unsigned int arr[(5)];
pthread_mutex_t m;
_Bool flag=(0);
void error(void)
{
ERROR: __VERIFIER_error();
return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
return (top==0) ? (1) : (0);
}
int push(unsigned int *stack, int x)
{
if (top==(5))
{
printf("stack overflow\\n");
return (-1);
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (top==0)
{
printf("stack underflow\\n");
return (-2);
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for(i=0; i<(5); i++)
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint()%(5);
if ((push(arr,tmp)==(-1)))
error();
pthread_mutex_unlock(&m);
}
return 0;
}
void *t2(void *arg)
{
int i;
for(i=0; i<(5); i++)
{
pthread_mutex_lock(&m);
if (top>0)
{
if ((pop(arr)==(-2)))
error();
}
pthread_mutex_unlock(&m);
}
return 0;
}
int main(void)
{
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 0
|
#include <pthread.h>
int main()
{
pthread_t thread1;
pthread_create( &thread1, 0, remote, 0);
pthread_join( thread1, 0);
return 0;
}
void remoteControllerCallback(uint16_t code, uint16_t type, uint32_t value)
{
switch(code)
{
case KEYCODE_INFO:
printf("\\nInfo pressed\\n");
if (getCurrentChannelInfo(&channelInfo) == SC_NO_ERROR)
{
printf("\\n********************* Channel info *********************\\n");
printf("Program number: %d\\n", channelInfo.programNumber);
printf("Audio pid: %d\\n", channelInfo.audioPid);
printf("Video pid: %d\\n", channelInfo.videoPid);
printf("**********************************************************\\n");
}
break;
case KEYCODE_P_PLUS:
printf("\\nCH+ pressed\\n");
channelUp();
break;
case KEYCODE_P_MINUS:
printf("\\nCH- pressed\\n");
channelDown();
break;
case KEYCODE_EXIT:
printf("\\nExit pressed\\n");
pthread_mutex_lock(&deinitMutex);
pthread_cond_signal(&deinitCond);
pthread_mutex_unlock(&deinitMutex);
break;
default:
printf("\\nPress P+, P-, info or exit! \\n\\n");
}
}
| 1
|
#include <pthread.h>
const int SIZE = 1024;
const int THREADS = 4;
const int CHUNK_SIZE = 64;
pthread_mutex_t count_lock;
int count;
int* all_nums;
void *dothing(void* data) {
while (1) {
pthread_mutex_lock(&count_lock);
int off = count * CHUNK_SIZE;
printf("%d\\n", count);
count++;
pthread_mutex_unlock(&count_lock);
if(off < SIZE) {
int upper = off+CHUNK_SIZE;
if(upper > SIZE) {
upper = SIZE;
}
for(int i=off; i<upper; ++i) {
all_nums[i] = i;
}
} else {
puts("done");
return 0;
}
}
}
int main() {
pthread_t threads[THREADS];
all_nums = malloc(SIZE);
count = 0;
pthread_mutex_init(&count_lock, 0);
for(int i=0; i<THREADS; ++i) {
pthread_create(&threads[i], 0, dothing, 0);
}
for(int i=0; i<THREADS; ++i) {
pthread_join(threads[i], 0);
}
return 0;
}
| 0
|
#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);
len = strlen(name);
pthread_mutex_lock(&env_mutex);
for (i = 0; environ[i] != 0; i++)
{
if ((strncmp(name, environ[i], len)) &&
(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);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int avail=0;
int consumed=0;
int pause_thread(int pause_count){
int total=0;
for(int i=0;i<pause_count;++i){
total++;
}
return total;
}
void * produce(void * arg){
int id = *((int *)arg);
for(int i=0;i<50;++i){
pause_thread(1000000);
pthread_mutex_lock(&mutex);
avail++;
printf("PRODUCED: thread %d pid: %d val %d\\n", id, getpid(), avail);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}
return 0;
}
void * consume(void * arg){
int id = *((int *)arg);
for(int i=0;i<50;++i){
pause_thread(10000);
pthread_mutex_lock(&mutex);
while(avail<=0){
pthread_cond_wait(&cond, &mutex);
}
avail--;
++consumed;
printf("CONSUMED: thread %d pid %d val %d consumed %d\\n", id, getpid(), avail, consumed);
pthread_mutex_unlock(&mutex);
}
return 0;
}
int main(){
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
pthread_t producers[2];
int producer_ids[2];
for (int i=0;i<2;++i){
producer_ids[i]=i;
pthread_create(&producers[i], 0, produce, &producer_ids[i]);
}
pthread_t consumers[2];
int consumer_ids[2];
for (int i=0;i<2;++i){
consumer_ids[i]=i+2;
pthread_create(&consumers[i], 0, consume, &consumer_ids[i]);
}
for (int i=0;i<2;++i){
pthread_join(producers[i],0);
}
for (int i=0;i<2;++i){
pthread_join(consumers[i],0);
}
if (consumed==2*50 && avail==0){
fprintf(stderr, "condvar_simple: SUCCEEDED\\n");
}
else{
fprintf(stderr, "condvar_simple: FAILED\\n");
}
}
| 0
|
#include <pthread.h>
unsigned int gSharedResource = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gWritePhase = PTHREAD_COND_INITIALIZER;
pthread_cond_t gReadPhase = PTHREAD_COND_INITIALIZER;
int gWaitingReaders = 0, gWriters = 0, gReaders = 0;
void *readerMain(void *threadArgument) {
int id = *((int*)threadArgument);
int i = 0, numReaders = 0;
for (i = 0; i < 5; i++) {
usleep(1000 * (random() % 5 + 5));
pthread_mutex_lock(&m);
gWaitingReaders++;
while (gReaders == -1) {
pthread_cond_wait(&gReadPhase, &m);
}
gWaitingReaders--;
numReaders = ++gReaders;
pthread_mutex_unlock(&m);
fprintf(stdout, "[r%d] reading %u [readers: %2d][writers: %2d]\\n", id, gSharedResource, numReaders, gWriters);
pthread_mutex_lock(&m);
if (--gReaders == 0) {
pthread_cond_signal(&gWritePhase);
}
pthread_mutex_unlock(&m);
}
pthread_exit(0);
}
void *writerMain(void *threadArgument) {
int id = *((int*)threadArgument);
int i = 0, numReaders = 0, numWriters = 0;
for (i = 0; i < 5; i++) {
usleep(1000 * (random() % 5 + 5));
pthread_mutex_lock(&m);
while (gReaders != 0) {
pthread_cond_wait(&gWritePhase, &m);
}
gReaders = -1;
numWriters = ++gWriters;
numReaders = gReaders;
pthread_mutex_unlock(&m);
fprintf(stdout, "[w%d] writing %u [readers: %2d][writers: %2d]\\n", id, gSharedResource, numReaders, numWriters);
pthread_mutex_lock(&m);
gReaders = 0;
gWriters--;
if (gWaitingReaders > 0) {
pthread_cond_broadcast(&gReadPhase);
} else {
pthread_cond_signal(&gWritePhase);
}
pthread_mutex_unlock(&m);
}
pthread_exit(0);
}
int main(int argc, char *argv[]) {
int i;
int numReaders[5];
int numWriters[5];
pthread_t readerThreadIDs[5];
pthread_t writerThreadIDs[5];
srandom((unsigned int)time(0));
for (i = 0; i < 5; i++) {
numReaders[i] = i;
pthread_create(&readerThreadIDs[i], 0, readerMain, &numReaders[i]);
}
for (i = 0; i < 5; i++) {
numWriters[i] = i;
pthread_create(&writerThreadIDs[i], 0, writerMain, &numWriters[i]);
}
for (i = 0; i < 5; i++) {
pthread_join(readerThreadIDs[i], 0);
}
for (i = 0; i < 5; i++) {
pthread_join(writerThreadIDs[i], 0);
}
}
| 1
|
#include <pthread.h>
struct buffer
{
int array[10];
unsigned int front;
unsigned int rear;
pthread_mutex_t m;
}queue;
pthread_cond_t queue_full = PTHREAD_COND_INITIALIZER;
pthread_cond_t queue_empty = PTHREAD_COND_INITIALIZER;
void *puta(void*arg)
{
srand(1092);
int value =0;
while (1)
{
pthread_mutex_lock(&queue.m);
while (((queue.rear+1)%10 )== (queue.front%10))
{
printf("\\n %s 0x%x producer thread rear %d front %d waititng for queue to be empty",__func__,pthread_self(),(queue.rear)%10, queue.front%10);
pthread_cond_wait(&queue_empty,&queue.m);
}
value =rand()%20;
printf("\\n %s 0x%x going to insert at %d value %d",__func__,pthread_self(),(queue.rear+1)%10, value);
queue.array[(++queue.rear)%10]=value;
sleep(5);
pthread_cond_signal(&queue_full);
pthread_mutex_unlock(&queue.m);
}
return 0;
}
void *eata(void*arg)
{
int value=0;
sleep(50);
while (1)
{
pthread_mutex_lock(&queue.m);
while (((queue.rear)%10 ) == (queue.front%10))
{
printf("\\n %s 0x%x consumer thread rear %d front %d waiting for producer to fill the buffer",__func__,pthread_self(),(queue.rear)%10, queue.front%10);
pthread_cond_wait(&queue_full,&queue.m);
}
value = queue.array[(++queue.front)%10];
printf("\\n %s 0x%x going to print at %d value %d",__func__,pthread_self(),(queue.front%10), value);
sleep(5);
pthread_cond_signal(&queue_empty);
pthread_mutex_unlock(&queue.m);
}
return 0;
}
func_type_t func_arr[]={puta,eata,puta,eata};
int main()
{
pthread_t tid[4];
int ret=0;
int i=0;
pthread_mutex_init(&queue.m,0);
queue.rear=10 -1;
queue.front=10 -1;
for(i=0;i<4;i++)
if( ret=pthread_create(&tid[i],0,func_arr[i],0))
{
return -1;
}
for(i=0;i<2;i++)
pthread_join(tid[i],0);
return 0;
}
| 0
|
#include <pthread.h>
void *funcionHilo1(void *p);
void *funcionHilo2(void *p);
volatile int variableGlobal = 10;
pthread_mutex_t m1;
int main(int argc, char **argv){
pthread_mutex_init(&m1, 0);
pthread_mutex_init(&m1, 0);
pthread_t h1;
pthread_t h2;
pthread_create(&h1, 0, funcionHilo1, 0);
pthread_create(&h2, 0, funcionHilo2, 0);
return 0;
}
void *funcionHilo1(void *p){
printf("Soy el hilo1, bloqueo al mutex\\n");
pthread_mutex_lock(&m1);
printf("Mutex bloqueado, hago un sleep\\n");
sleep(2);
printf("Mutex bloqueado, hago un sleep\\n");
pthread_mutex_unlock(&m1);
printf("Mutex desbloqueado\\n");
}
void *funcionHilo1(void *p){
printf("Soy el hilo1, bloqueo al mutex\\n");
pthread_mutex_lock(&m1);
printf("Mutex bloqueado, hago un sleep\\n");
sleep(2);
printf("Mutex bloqueado, hago un sleep\\n");
pthread_mutex_unlock(&m1);
printf("Mutex desbloqueado\\n");
}
| 1
|
#include <pthread.h>
pthread_mutex_t buffer_mutex;
int fill = 0;
char buffer[100][50];
char *fetch(char *link) {
int fd = open(link, O_RDONLY);
if (fd < 0) {
fprintf(stderr, "failed to open file: %s", link);
return 0;
}
int size = lseek(fd, 0, 2);
assert(size >= 0);
char *buf = Malloc(size+1);
buf[size] = '\\0';
assert(buf);
lseek(fd, 0, 0);
char *pos = buf;
while(pos < buf+size) {
int rv = read(fd, pos, buf+size-pos);
assert(rv > 0);
pos += rv;
}
close(fd);
return buf;
}
void edge(char *from, char *to) {
if(!from || !to)
return;
char temp[50];
temp[0] = '\\0';
char *fromPage = parseURL(from);
char *toPage = parseURL(to);
strcpy(temp, fromPage);
strcat(temp, "->");
strcat(temp, toPage);
strcat(temp, "\\n");
pthread_mutex_lock(&buffer_mutex);
strcpy(buffer[fill++], temp);
pthread_mutex_unlock(&buffer_mutex);
}
int main(int argc, char *argv[]) {
pthread_mutex_init(&buffer_mutex, 0);
int rc = crawl("/u/c/s/cs537-1/ta/tests/4a/tests/files/complex_loop/pagea", 5, 4, 15, fetch, edge);
assert(rc == 0);
return compareOutput(buffer, fill, "/u/c/s/cs537-1/ta/tests/4a/tests/files/output/complex_loop.out");
}
| 0
|
#include <pthread.h>
static void * routine_threads (void * argument);
static int aleatoire (int maximum);
pthread_mutex_t mutex_stdout = PTHREAD_MUTEX_INITIALIZER;
int main (void)
{
int i;
pthread_t thread;
for (i = 0; i < 5; i ++)
pthread_create(& thread, 0, routine_threads, (void *) i);
pthread_exit(0);
}
static void * routine_threads (void * argument)
{
int numero = (int) argument;
int nombre_iterations;
int i;
nombre_iterations = 1 + aleatoire(3);
for (i = 0; i < nombre_iterations; i ++) {
sleep(aleatoire(3));
pthread_mutex_lock(& mutex_stdout);
fprintf(stdout, "Le thread %d a obtenu le mutex\\n", numero);
sleep(aleatoire(3));
fprintf(stdout, "Le thread %d relache le mutex\\n", numero);
pthread_mutex_unlock(& mutex_stdout);
}
return 0;
}
static int aleatoire (int maximum)
{
double d;
d = (double) maximum * rand();
d = d / (32767 + 1.0);
return ((int) d);
}
| 1
|
#include <pthread.h>
long int chunk;
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,0, chunk);
pthread_exit(0);
}
int run_m(char **fname)
{
int i;
long int num,size=0;
FILE *ptr_myfile;
pthread_t tid[4];
void *status;
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);
printf("\\n----------- sorted -----------\\n");
pthread_mutex_init(&lock_x, 0);
for ( i = 1; i <= 4; i++)
{
chunk = (size/4)*i;
pthread_create(&tid[i], 0, &th_qs, (void*)arr);
}
for ( i = 1; i <= 4; i++)
pthread_join(tid[i], &status);
for(i=0;i<size;i++)
printf("%d - %lu\\n",i,arr[i]);
return 0;
}
int run_s(char **fname){
int i;
long int num,size=0;
FILE *ptr_myfile;
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);
printf("\\n----------- sorted -----------\\n");
quickSortM(arr,0, size);
for(i=0;i<size;i++)
printf("%d - %lu\\n",i,arr[i]);
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-m run with multiprocess support\\n\\t-s 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.20\\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 3:
opt = getopt(argc, argv, "s:m:");
if(opt == 's')
rtn=run_s(&argv[2]);
else if (opt == 'm')
rtn=run_m(&argv[2]);
else
{
help();
rtn=1;
}
break;
default:
help();
rtn=1;
break;
}
return rtn;
}
| 0
|
#include <pthread.h>
char domain_suffix[][32] = {
"AC",
"AD",
"AE",
"AERO",
"AF",
"AG",
"AI",
"AL",
"AM",
"AN",
"AO",
"AQ",
"AR",
"ARPA",
"AS",
"ASIA",
"AT",
"AU",
"AW",
"AX",
"AZ",
"BA",
"BB",
"BD",
"BE",
"BF",
"BG",
"BH",
"BI",
"BIZ",
"BJ",
"BM",
"BN",
"BO",
"BR",
"BS",
"BT",
"BV",
"BW",
"BY",
"BZ",
"CA",
"CAT",
"CC",
"CD",
"CF",
"CG",
"CH",
"CI",
"CK",
"CL",
"CM",
"CN",
"CO",
"COM",
"COOP",
"CR",
"CU",
"CV",
"CX",
"CY",
"CZ",
"DE",
"DJ",
"DK",
"DM",
"DO",
"DZ",
"EC",
"EDU",
"EE",
"EG",
"ER",
"ES",
"ET",
"EU",
"FI",
"FJ",
"FK",
"FM",
"FO",
"FR",
"GA",
"GB",
"GD",
"GE",
"GF",
"GG",
"GH",
"GI",
"GL",
"GM",
"GN",
"GOV",
"GP",
"GQ",
"GR",
"GS",
"GT",
"GU",
"GW",
"GY",
"HK",
"HM",
"HN",
"HR",
"HT",
"HU",
"ID",
"IE",
"IL",
"IM",
"IN",
"INFO",
"INT",
"IO",
"IQ",
"IR",
"IS",
"IT",
"JE",
"JM",
"JO",
"JOBS",
"JP",
"KE",
"KG",
"KH",
"KI",
"KM",
"KN",
"KP",
"KR",
"KW",
"KY",
"KZ",
"LA",
"LB",
"LC",
"LI",
"LK",
"LR",
"LS",
"LT",
"LU",
"LV",
"LY",
"MA",
"MC",
"MD",
"ME",
"MG",
"MH",
"MIL",
"MK",
"ML",
"MM",
"MN",
"MO",
"MOBI",
"MP",
"MQ",
"MR",
"MS",
"MT",
"MU",
"MUSEUM",
"MV",
"MW",
"MX",
"MY",
"MZ",
"NA",
"NAME",
"NC",
"NE",
"NET",
"NF",
"NG",
"NI",
"NL",
"NO",
"NP",
"NR",
"NU",
"NZ",
"OM",
"ORG",
"PA",
"PE",
"PF",
"PG",
"PH",
"PK",
"PL",
"PM",
"PN",
"PR",
"PRO",
"PS",
"PT",
"PW",
"PY",
"QA",
"RE",
"RO",
"RS",
"RU",
"RW",
"SA",
"SB",
"SC",
"SD",
"SE",
"SG",
"SH",
"SI",
"SJ",
"SK",
"SL",
"SM",
"SN",
"SO",
"SR",
"ST",
"SU",
"SV",
"SY",
"SZ",
"TC",
"TD",
"TEL",
"TF",
"TG",
"TH",
"TJ",
"TK",
"TL",
"TM",
"TN",
"TO",
"TP",
"TR",
"TRAVEL",
"TT",
"TV",
"TW",
"TZ",
"UA",
"UG",
"UK",
"UM",
"US",
"UY",
"UZ",
"VA",
"VC",
"VE",
"VG",
"VI",
"VN",
"VU",
"WF",
"WS",
"XN--0ZWM56D",
"XN--11B5BS3A9AJ6G",
"XN--80AKHBYKNJ4F",
"XN--9T4B11YI5A",
"XN--DEBA0AD",
"XN--G6W251D",
"XN--HGBK6AJ7F53BBA",
"XN--HLCJ6AYA9ESC7A",
"XN--JXALPDLP",
"XN--KGBECHTV",
"XN--ZCKZAH",
"YE",
"YT",
"YU",
"ZA",
"ZM",
"ZW",
};
int suffixNum = 0;
pthread_mutex_t suffix_mutex = PTHREAD_MUTEX_INITIALIZER;
static int compmi(const void *m1, const void *m2)
{
return strcasecmp((char *) m1, (char *) m2);
}
int get_domainnames(char *domain, char *domainnames)
{
int pos = 0, flag = 0;
char *res, *token;
char tmpdomain[128];
if (suffixNum == 0)
{
suffixNum = sizeof(domain_suffix) / sizeof(domain_suffix[0]);
qsort(domain_suffix, suffixNum, sizeof(domain_suffix[0]), compmi);
}
snprintf(tmpdomain, 128, "%s", domain);
token = strtok(tmpdomain, ".");
while (token != 0)
{
res =
bsearch(token, domain_suffix, suffixNum,
sizeof(domain_suffix[0]), compmi);
if (res == 0)
{
flag = 0;
pos = token - tmpdomain;
} else
{
flag = 1;
}
token = strtok(0, ".");
}
if (flag > 0)
{
strcpy(domainnames, domain + pos);
return 0;
}
return -1;
}
int insite_check(char *srcUrl, char *linkUrl)
{
int ret, len;
char *p, *t;
char domain[128], dm1[128], dm2[128];
t = strstr(srcUrl, "://");
if (t == 0)
return -1;
else
t += 3;
p = t;
while (*p)
{
if (*p == ':' || *p == '/')
break;
p++;
}
len = p - t;
if (len >= 128)
return -1;
memcpy(domain, t, len);
*(domain + len) = 0;
pthread_mutex_lock(&suffix_mutex);
ret = get_domainnames(domain, dm1);
pthread_mutex_unlock(&suffix_mutex);
if (ret == -1)
return -1;
t = strstr(linkUrl, "://");
if (t == 0)
return -1;
else
t += 3;
p = t;
while (*p)
{
if (*p == ':' || *p == '/')
break;
p++;
}
len = p - t;
if (len >= 128)
return -1;
memcpy(domain, t, len);
*(domain + len) = 0;
pthread_mutex_lock(&suffix_mutex);
ret = get_domainnames(domain, dm2);
pthread_mutex_unlock(&suffix_mutex);
if (ret == -1)
return -1;
if (strcasecmp(dm1, dm2) != 0)
return 0;
else
return 1;
}
| 1
|
#include <pthread.h>
void main_constructor( void )
;
void main_destructor( void )
;
void __cyg_profile_func_enter( void *, void * )
;
void __cyg_profile_func_exit( void *, void * )
;
char* join3(char *s1, char *s2);
pthread_mutex_t mut;
void (*callback)() = 0;
double register_function( void (*in_main_func)())
{
callback = in_main_func;
}
void function_needing_callback()
{
if(callback != 0) callback();
}
void main_constructor( void )
{
}
void main_deconstructor( void )
{
}
void __cyg_profile_func_enter( void *this, void *callsite )
{
function_needing_callback();
pthread_mutex_lock(&mut);
char* filename = "";
char pid[15];
sprintf(pid, "%d", syscall(SYS_gettid));
char tid[15];
sprintf(tid, "%d", getpid());
filename = join3(filename, tid);
filename = join3(filename, "_");
filename = join3(filename, "trace.txt");
FILE *fp = fopen( filename, "a" );
if (fp == 0) exit(-1);
fprintf(fp, "E%p\\n", (int *)this);
fclose( fp );
pthread_mutex_unlock(&mut);
}
void __cyg_profile_func_exit( void *this, void *callsite )
{
pthread_mutex_lock(&mut);
char* filename = "";
char pid[15];
sprintf(pid, "%d", syscall(SYS_gettid));
char tid[15];
sprintf(tid, "%d", getpid());
filename = join3(filename, tid);
filename = join3(filename, "_");
filename = join3(filename, "trace.txt");
FILE *fp = fopen( filename, "a" );
if (fp == 0) exit(-1);
fprintf(fp, "X%p\\n", (int *)this);
fclose( fp );
pthread_mutex_unlock(&mut);
}
char* join3(char *s1, char *s2)
{
char *result = malloc(strlen(s1)+strlen(s2)+1);
if (result == 0) exit (1);
strcpy(result, s1);
strcat(result, s2);
return result;
}
| 0
|
#include <pthread.h>
char data = 'A';
int nb_lecteurs = 0;
pthread_mutex_t reading;
pthread_mutex_t writing;
pthread_mutex_t fifo;
void* lecteur(void *arg) {
int id = *((int*) arg);
int i;
for (i = 0; i < 5; i++) {
printf("Lecteur %d veut consulter la ressource\\n", id);
pthread_mutex_lock(&fifo);
pthread_mutex_lock(&reading);
nb_lecteurs += 1;
if(nb_lecteurs ==1) {
pthread_mutex_lock(&writing);
}
pthread_mutex_unlock(&reading);
pthread_mutex_unlock(&fifo);
printf("Lecteur %d consulte la ressource : %c\\n", id, data);
sleep(rand() % 2);
printf("Lecteur %d a fini de consulter la ressource : %c\\n", id, data);
pthread_mutex_lock(&reading);
nb_lecteurs -= 1;
if (nb_lecteurs == 0) {
pthread_mutex_unlock(&writing);
}
pthread_mutex_unlock(&reading);
sleep(rand() % 3);
}
printf("Lecteur %d : s'en va\\n", id);
return 0;
}
void* ecrivain(void *arg) {
int id = *((int*) arg);
int i;
for (i = 0; i < 5; i++) {
printf("Ecrivain %d veut modifier la ressource\\n", id);
pthread_mutex_lock(&fifo);
pthread_mutex_lock(&writing);
pthread_mutex_unlock(&fifo);
printf("Ecrivain %d modifie la ressource : %c\\n", id, data);
sleep(rand() % 2);
data++;
printf("Ecrivain %d : maintenant la ressource est %c\\n", id, data);
pthread_mutex_unlock(&writing);
sleep(rand() % 3);
}
printf("Ecrivain %d : s'en va\\n", id);
return 0;
}
int main() {
int i, nb[8];
srand(time(0));
pthread_t tid[8];
for (i = 0; i < 5; i++) {
nb[i] = i;
pthread_create(&tid[i], 0, lecteur, (void*) &nb[i]);
}
for (i = 0; i < 3; i++) {
nb[i+5] = i;
pthread_create(&tid[i+5], 0, ecrivain, (void*) &nb[i+5]);
}
for (i = 0; i < 8; i++) {
pthread_join(tid[i], 0);
}
puts("Consultation et modifications terminées");
pthread_mutex_destroy(&reading);
pthread_mutex_destroy(&writing);
pthread_mutex_destroy(&fifo);
return 0;
}
| 1
|
#include <pthread.h>
{
unsigned char* srcfileaddres;
unsigned char* destfileaddres;
unsigned int startfilepos;
unsigned int blocksize;
}fileblock;
unsigned char * g_srcfilestartp=0;
unsigned char * g_destfilestartp=0;
pthread_mutex_t g_mutex=PTHREAD_MUTEX_INITIALIZER;
void output_sys_errmsg(const char* errmsg)
{
perror(errmsg);
}
unsigned int get_file_size(unsigned int fd)
{
unsigned int filesize=lseek(fd,0,2);
lseek(fd,0,0);
return filesize;
}
unsigned int get_file_block_cnt(unsigned int fd)
{
unsigned int fileblockcnt=0;
unsigned int filesize=get_file_size(fd);
unsigned int fileremaindsize=filesize%(1024*1024*2);
fileblockcnt=filesize/(1024*1024*2);
if(fileremaindsize>0)
{
fileblockcnt=fileblockcnt+1;
}
return fileblockcnt;
}
unsigned int get_remainsize(unsigned int fd)
{
unsigned int remainsize=0;
unsigned int filesize=get_file_size(fd);
if(filesize%(1024*1024*2)>0)
{
remainsize=filesize%(1024*1024*2);
}
return remainsize;
}
fileblock* get_file_block(unsigned int fd)
{
unsigned int fileblockcnt=get_file_block_cnt(fd);
unsigned int fileremaindsize=get_remainsize(fd);
fileblock* fileblockarray=(fileblock*)malloc(fileblockcnt*sizeof(fileblock));
if(fileblockarray==0)
{
output_sys_errmsg("get_file_block malloc:");
exit(-1);
}
int i;
for(i=0;i<fileblockcnt-1;i++)
{
fileblockarray[i].startfilepos=i*(1024*1024*2);
fileblockarray[i].blocksize=(1024*1024*2);
}
fileblockarray[i].startfilepos=i*(1024*1024*2);
fileblockarray[i].blocksize=fileremaindsize>0?fileremaindsize:(1024*1024*2);
return fileblockarray;
}
unsigned char * get_srcfile_map_addres(unsigned int fd)
{
unsigned int filesize=get_file_size(fd);
g_srcfilestartp=(unsigned char*)mmap(0,filesize,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if(g_srcfilestartp==0)
{
output_sys_errmsg("get_srcfile_map_addres mmap:");
exit(-1);
}
return g_srcfilestartp;
}
void set_srcfile_munmap(int fd)
{
unsigned int filesize=get_file_size(fd);
if(g_srcfilestartp!=0)
{
munmap(g_srcfilestartp,filesize);
}
}
void set_destfile_munmap(int fd)
{
unsigned int filesize=get_file_size(fd);
if(g_destfilestartp!=0)
{
munmap(g_destfilestartp,filesize);
}
}
unsigned char * get_destfile_map_addres(unsigned int srcfd,unsigned int destfd)
{
unsigned int filesize=get_file_size(srcfd);
lseek(destfd,filesize,0);
write(destfd," ",1);
g_destfilestartp=(unsigned char*)mmap(0,filesize,PROT_READ|PROT_WRITE,MAP_SHARED,destfd,0);
if(g_destfilestartp==0)
{
output_sys_errmsg("get_destfile_map_addres mmap:");
exit(-1);
}
return g_destfilestartp;
}
void* pthread_copy_work(void* arg)
{
fileblock * blockstruct=(fileblock*)arg;
pthread_mutex_lock(&g_mutex);
memcpy((void*)&g_destfilestartp[blockstruct->startfilepos],(void*)&g_srcfilestartp[blockstruct->startfilepos],blockstruct->blocksize);
pthread_mutex_unlock(&g_mutex);
return 0;
}
void init_copy_pthread(unsigned int fd)
{
unsigned int blockcnt=get_file_block_cnt(fd);
fileblock *fileblockarray=get_file_block(fd);
pthread_t *pthreads=0;
pthreads=(pthread_t*)malloc(blockcnt*sizeof(pthread_t));
if(pthreads==0)
{
output_sys_errmsg("init_copy_pthread malloc:");
exit(-1);
}
int i;
int ret;
for(i=0;i<blockcnt;i++)
{
ret=pthread_create(&pthreads[i],0,pthread_copy_work,(void*)&fileblockarray[i]);
while(ret==-1)
{
ret=pthread_create(&pthreads[i],0,pthread_copy_work,(void*)&fileblockarray[i]);
}
}
for(i=0;i<blockcnt;i++)
{
pthread_join(pthreads[i],0);
}
}
int main(int argc, char const *argv[])
{
int srcfd=open("maishu.3gp",O_RDWR);
if(srcfd==-1)
{
output_sys_errmsg("main open srcfd:");
exit(-1);
}
int destfd=open("maishu1.3gp",O_CREAT|O_EXCL|O_RDWR,0777);
if(destfd==-1)
{
output_sys_errmsg("main open destfd:");
exit(-1);
}
get_srcfile_map_addres(srcfd);
get_destfile_map_addres(srcfd,destfd);
init_copy_pthread(srcfd);
set_srcfile_munmap(srcfd);
set_destfile_munmap(srcfd);
return 0;
}
| 0
|
#include <pthread.h>
int
pthread_barrier_init(pthread_barrier_t *barrier, pthread_barrierattr_t *attr,
unsigned int count) {
int rc = 0;
pthread_barrier_t b = 0;
if (barrier == 0)
return (EINVAL);
if (attr != 0) {
if (*attr == 0)
return (EINVAL);
if ((*attr)->pshared != PTHREAD_PROCESS_PRIVATE)
return (ENOTSUP);
}
b = calloc(1, sizeof *b);
if (b == 0)
return (ENOMEM);
if ((rc = pthread_mutex_init(&b->mutex, 0)))
goto err;
if ((rc = pthread_cond_init(&b->cond, 0)))
goto err;
b->threshold = count;
*barrier = b;
return (0);
err:
if (b) {
if (b->mutex)
pthread_mutex_destroy(&b->mutex);
if (b->cond)
pthread_cond_destroy(&b->cond);
free(b);
}
return (rc);
}
int
pthread_barrier_destroy(pthread_barrier_t *barrier)
{
int rc;
pthread_barrier_t b;
if (barrier == 0 || *barrier == 0)
return (EINVAL);
if ((rc = pthread_mutex_lock(&(*barrier)->mutex)))
return (rc);
b = *barrier;
if (b->out > 0 || b->in > 0) {
pthread_mutex_unlock(&b->mutex);
return (EBUSY);
}
*barrier = 0;
pthread_mutex_unlock(&b->mutex);
pthread_mutex_destroy(&b->mutex);
pthread_cond_destroy(&b->cond);
free(b);
return (0);
}
int
pthread_barrier_wait(pthread_barrier_t *barrier)
{
pthread_barrier_t b;
int rc, old_state, gen;
int done = 0;
if (barrier == 0 || *barrier == 0)
return (EINVAL);
if ((rc = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state)))
return (rc);
b = *barrier;
if ((rc = pthread_mutex_lock(&b->mutex)))
goto cancel;
_rthread_debug(6, "in: %d, threshold: %d\\n", b->in, b->threshold);
if (++b->in == b->threshold) {
b->out = b->in - 1;
b->in = 0;
b->generation++;
if ((rc = pthread_cond_signal(&b->cond)))
goto err;
done = 1;
_rthread_debug(6, "threshold reached\\n");
} else {
gen = b->generation;
_rthread_debug(6, "waiting on condition\\n");
do {
if ((rc = pthread_cond_wait(&b->cond, &b->mutex)))
goto err;
} while (gen == b->generation);
b->out--;
if ((rc = pthread_cond_signal(&b->cond)))
goto err;
}
err:
if ((rc = pthread_mutex_unlock(&b->mutex)))
return (rc);
cancel:
rc = pthread_setcancelstate(old_state, 0);
if (rc == 0 && done)
rc = PTHREAD_BARRIER_SERIAL_THREAD;
return (rc);
}
| 1
|
#include <pthread.h>
int ncount;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* do_loop(void *data)
{
int i;
pthread_mutex_lock(&mutex);
for (i = 0; i < 10; i++)
{
printf("loop1 : %d", ncount);
ncount ++;
sleep(1);
}
pthread_mutex_unlock(&mutex);
}
void* do_loop2(void *data)
{
int i;
pthread_mutex_lock(&mutex);
for (i = 0; i < 10; i++)
{
printf("loop2 : %d", ncount);
ncount ++;
sleep(1);
}
pthread_mutex_unlock(&mutex);
}
int main()
{
int thr_id;
pthread_t p_thread[2];
int status;
int a = 1;
ncount = 0;
thr_id = pthread_create(&p_thread[0], 0, do_loop, (void *)&a);
sleep(1);
thr_id = pthread_create(&p_thread[1], 0, do_loop2, (void *)&a);
pthread_join(p_thread[0], (void *) &status);
pthread_join(p_thread[1], (void *) &status);
status = pthread_mutex_destroy(&mutex);
printf("code = %d", status);
printf("programing is end");
return 0;
}
| 0
|
#include <pthread.h>
static int s_num_threads = 10;
static int s_num_iterations = 1000;
static pthread_mutex_t s_mutex;
static long long s_grand_sum;
static pthread_rwlock_t s_rwlock;
static int s_counter;
static void* thread_func(void* arg)
{
int i, r;
int sum1 = 0, sum2 = 0;
for (i = s_num_iterations; i > 0; i--)
{
r = pthread_rwlock_rdlock(&s_rwlock);
assert(! r);
sum1 += s_counter;
r = pthread_rwlock_unlock(&s_rwlock);
assert(! r);
r = pthread_rwlock_wrlock(&s_rwlock);
assert(! r);
sum2 += s_counter++;
r = pthread_rwlock_unlock(&s_rwlock);
assert(! r);
}
pthread_mutex_lock(&s_mutex);
s_grand_sum += sum2;
pthread_mutex_unlock(&s_mutex);
return 0;
}
int main(int argc, char** argv)
{
pthread_attr_t attr;
pthread_t* tid;
int threads_created;
int optchar;
int err;
int i;
int expected_counter;
long long expected_grand_sum;
while ((optchar = getopt(argc, argv, "i:t:")) != EOF)
{
switch (optchar)
{
case 'i':
s_num_iterations = atoi(optarg);
break;
case 't':
s_num_threads = atoi(optarg);
break;
default:
fprintf(stderr, "Error: unknown option '%c'.\\n", optchar);
return 1;
}
}
pthread_mutex_init(&s_mutex, 0);
pthread_rwlock_init(&s_rwlock, 0);
pthread_attr_init(&attr);
err = pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN + 4096);
assert(err == 0);
tid = calloc(s_num_threads, sizeof(*tid));
threads_created = 0;
for (i = 0; i < s_num_threads; i++)
{
err = pthread_create(&tid[i], &attr, thread_func, 0);
if (err)
printf("failed to create thread %d: %s\\n", i, strerror(err));
else
threads_created++;
}
pthread_attr_destroy(&attr);
for (i = 0; i < s_num_threads; i++)
{
if (tid[i])
pthread_join(tid[i], 0);
}
free(tid);
expected_counter = threads_created * s_num_iterations;
fprintf(stderr, "s_counter - expected_counter = %d\\n",
s_counter - expected_counter);
expected_grand_sum = 1ULL * expected_counter * (expected_counter - 1) / 2;
fprintf(stderr, "s_grand_sum - expected_grand_sum = %lld\\n",
s_grand_sum - expected_grand_sum);
fprintf(stderr, "Finished.\\n");
return 0;
}
| 1
|
#include <pthread.h>
sem_t footman;
void *philosopher (void*);
double delta, pi = 0.0;
int intervals = 100000;
static pthread_mutex_t forks[5];
int main() {
int i, id[5];
pthread_t tid[5];
for (i=0; i<5; i++)
pthread_mutex_init(&(forks[i]), 0);
sem_init(&footman, 0, 5 -1);
for (i=0; i<5; i++) {
id[i] = i;
pthread_create (&tid[i], 0, philosopher,
(void *)&id[i]);
}
for (i=0; i<5; i++)
pthread_join(tid[i], 0);
}
void *philosopher (void *id) {
int philosopher_id = *(int *)id;
while ( 1 ) {
sem_wait (&footman);
pthread_mutex_lock ( &(forks[philosopher_id]) );
pthread_mutex_lock ( &(forks[(philosopher_id+1)%5]) );
printf ("Philosopher %d is eating\\n", philosopher_id);
printf ("Philosopher %d is done\\n", philosopher_id);
pthread_mutex_unlock ( &(forks[(philosopher_id+1)%5]) );
pthread_mutex_unlock ( &(forks[philosopher_id]) );
sem_post (&footman);
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
sem_t riders_waiting;
sem_t bus_arrival;
sem_t bus_depart;
int waiting = 0;
void * rider(){
while(1){
sem_wait(&riders_waiting);
pthread_mutex_lock(&mutex);
waiting = waiting + 1;
printf("RIDERS: riders waiting = %d \\n",waiting);
sleep(1);
pthread_mutex_unlock(&mutex);
sem_wait(&bus_arrival);
sem_post(&riders_waiting);
printf("RIDER: bus is here. \\n riders waiting: %d \\n",waiting--);
sleep(1);
if(waiting ==0){
sem_post(&bus_depart);
}else{
sem_post(&bus_arrival);
}
}
}
void * bus(){
while(1){
pthread_mutex_lock(&mutex);
if(waiting >0){
sem_post(&bus_arrival);
sem_wait(&bus_depart);
}
printf("BUS: departing! \\n riders waiting: %d \\n",waiting);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void main(int argc, char * argv[]){
pthread_t riders [100];
pthread_t b1;
pthread_mutex_init(&mutex,0);
sem_init(&riders_waiting,0,50);
sem_init(&bus_arrival,0,0);
sem_init(&bus_depart,0,0);
int t_id;
pthread_create(&b1,0,bus,0);
for(t_id=0; t_id< 100 ;t_id++){
pthread_create(&riders[t_id],0,rider,0);
}
pthread_join(b1,0);
}
| 1
|
#include <pthread.h>
static uint64_t global_int;
static pthread_mutex_t lock;
void bounds_error()
{
printf("Argument out of bounds:\\n"
"t must be between %lu and %lu,\\n"
"n must be between %lu and %lu.\\n",
1l, 16l, 1l, 1000000000l);
exit(1);
}
void *add_to_global(void *argument)
{
int i, n;
n = *((int *) argument);
pthread_mutex_lock(&lock);
for (i = 1; i <= n; ++i) {
global_int += i;
}
pthread_mutex_unlock(&lock);
return 0;
}
int main(int argc, char *argv[])
{
int t, n, i, rc;
pthread_t threads[16l];
if (argc != 3) {
printf("You must specify exactly two arguments.\\n");
} else {
t = strtol(argv[1], 0, 0);
n = strtol(argv[2], 0, 0);
if (1l > t || t > 16l)
bounds_error();
if (1l > n || t > 1000000000l)
bounds_error();
global_int = 0;
if (pthread_mutex_init(&lock, 0) != 0) {
printf("Mutex init failed\\n");
exit(1);
}
for (i=0; i<t; ++i) {
rc = pthread_create(&threads[i], 0, add_to_global, (void *)&n);
if (rc != 0) {
printf("Failed to create thread %d\\n", i);
exit(1);
}
}
for (i=0; i<t; ++i) {
rc = pthread_join(threads[i], 0);
if (rc != 0) {
printf("Failed to join thread %d\\n", i);
exit(1);
}
}
pthread_mutex_destroy(&lock);
printf("%llu\\n", global_int);
}
return 0;
}
| 0
|
#include <pthread.h>
struct sublist {
int start;
int end;
};
int N;
int P;
int args[64];
int A[0x500000];
struct sublist sublist_info[(0x500000 / 1024)];
volatile int head, tail;
volatile int sort_complete, sleepcount;
pthread_mutex_t mut;
pthread_cond_t cond_empty, cond_full;
pthread_barrier_t barr;
void insert_sublist(int start, int end)
{
pthread_mutex_lock(&mut);
while (((tail + 1) % (0x500000 / 1024)) == head)
{
pthread_cond_wait(&cond_empty, &mut);
}
sublist_info[tail].start = start;
sublist_info[tail].end = end;
tail = (tail + 1) % (0x500000 / 1024);
pthread_cond_signal(&cond_full);
pthread_mutex_unlock(&mut);
}
struct sublist remove_sublist(void)
{
struct sublist retval;
pthread_mutex_lock(&mut);
while ((head == tail) && (!sort_complete))
{
sleepcount++;
if (sleepcount < P)
{
pthread_cond_wait(&cond_full, &mut);
sleepcount--;
}
else
{
sort_complete = 1;
pthread_cond_broadcast(&cond_full);
}
}
if (sort_complete == 0)
{
retval = sublist_info[head];
head = (head + 1) % (0x500000 / 1024);
pthread_cond_signal(&cond_empty);
}
else
{
retval.start = 0;
retval.end = 0;
}
pthread_mutex_unlock(&mut);
return retval;
}
void insertionsort(int start, int end)
{
int i, j, val;
for (i=start+1; i<=end; i++)
{
val = A[i];
j = i-1;
while (j >= start && A[j] > val)
{
A[j+1] = A[j];
j--;
}
A[j+1] = val;
}
}
int partition(int start, int end)
{
int i, j, pivotpos;
int pivot = A[end];
int done = 0, temp;
i = start;
j = end - 1;
while (!done)
{
while (i < j && A[i] < pivot) i++;
while (i < j && A[j] > pivot) j--;
if (i < j)
{
temp = A[i];
A[i] = A[j];
A[j] = temp;
}
else
{
if (A[i] > pivot)
{
A[end] = A[i];
A[i] = pivot;
pivotpos = i;
}
else pivotpos = end;
done = 1;
}
}
return pivotpos;
}
void quicksort(int start, int end)
{
int i, n, pivot;
int lo, hi;
quicksort_1:
if (end <= start) return;
if ((tail % 50) == 0)
printf("Quick sort called : %d, %d, (%d, %d)\\n",start,end,head,tail);
if ((end - start + 1) < 1024)
{
insertionsort(start, end);
}
else
{
pivot = partition(start, end);
if (pivot-1 > start && pivot+1 < end)
{
if ((pivot-start-1) < (end - pivot - 1))
{
insert_sublist(start, pivot-1);
start = pivot+1;
goto quicksort_1;
}
else
{
insert_sublist(pivot+1, end);
end = pivot-1;
goto quicksort_1;
}
}
else
{
if (pivot-1 > start)
{
end = pivot-1;
goto quicksort_1;
}
else if (pivot+1 < end)
{
start = pivot+1;
goto quicksort_1;
}
else printf("Both sublists wont exist! Should not happen!\\n");
}
}
}
void *thread_func(void *arg)
{
struct sublist s;
int done = 0;
char mesg[100];
int fd;
int procno;
procno = *(int *)arg;
pthread_barrier_wait(&barr);
printf("Thread id : %d - sublistlise : %d\\n",procno, (0x500000 / 1024));
if (procno == 0)
{
s.start = 0;
s.end = N-1;
}
else s = remove_sublist();
do {
if (s.start == 0 && s.end == 0) done = 1;
else
{
quicksort(s.start, s.end);
s = remove_sublist();
}
} while (!done);
printf("Terminating the thread function\\n");
return 0;
}
int main(int argc, char **argv)
{
int i,j, mcmodel;
int t1, t2, t3, t4;
int t;
pthread_t thr[64];
if (argc != 3)
{
printf("Usage : quiksort <NPROC> <NELEMENTS>\\n");
exit(0);
}
P = atoi(argv[1]);
N = atoi(argv[2]);
pthread_barrier_init(&barr, 0, P);
sleepcount = 0;
sort_complete = 0;
for (i=0; i<64; i++) args[i] = i;
pthread_mutex_init(&mut, 0);
pthread_cond_init(&cond_empty, 0);
pthread_cond_init(&cond_full, 0);
for (i=0; i<N; i++)
A[i] = i;
j = 1137;
for (i=0; i<N; i = i++)
{
t = A[j];
A[j] = A[i];
A[i] = t;
j = (j + 337) % N;
}
t3 = time(0);
for (i=1; i<P; i++)
pthread_create(&thr[i], 0, thread_func, &args[i]);
t1 = time(0);
thread_func(&args[0]);
t4 = time(0);
for (i=1; i<P; i++)
pthread_join(thr[i], 0);
t2 = time(0);
printf("\\nTime elapsed : creation %d, sort : %d, joining : %d\\n",t1-t3, t4-t1, t2-t4);
return 0;
}
| 1
|
#include <pthread.h>
ZERO = 0,
BLUE = 1,
RED = 2,
YELLOW = 3,
INVALID = 4,
} color;
char *colors[] = { "zero",
"blue",
"red",
"yellow",
"invalid"
};
char *digits[] = { "zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine"
};
sem_t at_most_two;
sem_t mutex;
sem_t sem_priv;
sem_t sem_print;
pthread_mutex_t print_mutex;
int meetings_left = 0;
int first_arrived = 0;
int done = 0;
color my_color;
pthread_t id;
int number_of_meetings;
} chameos;
chameos A;
chameos B;
static color
compliment_color(color c1, color c2) {
color result;
switch(c1) {
case BLUE:
switch(c2) {
case BLUE:
result = BLUE;
break;
case RED:
result = YELLOW;
break;
case YELLOW:
result = RED;
break;
default:
printf("error complementing colors: %d, %d\\n", c1, c2);
exit(1);
}
break;
case RED:
switch(c2) {
case BLUE:
result = YELLOW;
break;
case RED:
result = RED;
break;
case YELLOW:
result = BLUE;
break;
default:
printf("error complementing colors: %d, %d\\n", c1, c2);
exit(2);
}
break;
case YELLOW:
switch(c2) {
case BLUE:
result = RED;
break;
case RED:
result = BLUE;
break;
case YELLOW:
result = YELLOW;
break;
default:
printf("error complementing colors: %d, %d\\n", c1, c2);
exit(3);
}
break;
default:
printf("error complementing colors: %d, %d\\n", c1, c2);
exit(4);
}
return result;
}
static void
spell_the_number(int prefix, int number) {
char *string_number;
int string_length;
int i;
int digit;
int output_so_far = 0;
char buff[1024];
if(prefix != -1) {
output_so_far = sprintf(buff, "%d", prefix);
}
string_number = malloc(sizeof(char)*10);
string_length = sprintf(string_number, "%d", number);
for(i = 0; i < string_length; i++) {
digit = string_number[i] - '0';
output_so_far += sprintf(buff+output_so_far, " %s", digits[digit]);
}
printf("%s\\n",buff);
}
static chameos *
meeting(chameos c) {
chameos *other_critter;
other_critter = malloc(sizeof(chameos));
sem_wait(&at_most_two);
if(done == 1) {
sem_post(&at_most_two);
return 0;
}
sem_wait(&mutex);
if(done == 1) {
sem_post(&mutex);
sem_post(&at_most_two);
return 0;
}
if(first_arrived == 0) {
first_arrived = 1;
A.my_color = c.my_color;
A.id = c.id;
sem_post(&mutex);
sem_wait(&sem_priv);
other_critter->my_color = B.my_color;
other_critter->id = B.id;
meetings_left--;
if(meetings_left == 0) {
done = 1;
}
sem_post(&mutex);
sem_post(&at_most_two); sem_post(&at_most_two);
} else {
first_arrived = 0;
B.my_color = c.my_color;
B.id = c.id;
other_critter->my_color = A.my_color;
other_critter->id = A.id;
sem_post(&sem_priv);
}
return other_critter;
}
static void *
creature(void *arg) {
chameos critter;
critter.my_color = (color)arg;
critter.id = pthread_self();
critter.number_of_meetings = 0;
chameos *other_critter;
int met_others = 0;
int met_self = 0;
int *total_meetings = 0;
while(done != 1) {
other_critter = meeting(critter);
if(other_critter == 0) {
break;
}
if(critter.id == other_critter->id) {
met_self++;
}else{
met_others++;
}
critter.my_color = compliment_color(critter.my_color, other_critter->my_color);
free(other_critter);
}
sem_wait(&sem_print);
pthread_mutex_lock(&print_mutex);
spell_the_number(met_others + met_self, met_self);
pthread_mutex_unlock(&print_mutex);
total_meetings = malloc(sizeof(int));
*total_meetings =met_others + met_self;
pthread_exit((void *)total_meetings);
}
void
print_colors(void) {
int i, j;
color c;
for(i = 1; i < INVALID; i++) {
for(j = 1; j < INVALID; j++) {
c = compliment_color(i,j);
printf("%s + %s -> %s\\n",colors[i],colors[j], colors[c]);
}
}
printf("\\n");
}
void
run_the_meetings(color *starting_colors, int n_colors, int total_meetings_to_run) {
struct sched_param priority;
priority.sched_priority = 1;
pthread_t pid_tab[10];
memset(pid_tab, 0, sizeof(pthread_t)*10);
int i;
int total = 0;
void *rslt = 0;
sem_init(&at_most_two, 0, 2);
sem_init(&mutex, 0, 1);
sem_init(&sem_priv, 0, 0);
sem_init(&sem_print, 0, 0);
pthread_mutex_init(&print_mutex, 0);
meetings_left = total_meetings_to_run;
first_arrived = 0;
done = 0;
sched_setscheduler(0, SCHED_FIFO, &priority);
for(i = 0; i < n_colors; i++) {
printf(" %s", colors[starting_colors[i]]);
pthread_create(&pid_tab[i], 0, &creature, (void *)starting_colors[i]);
}
printf("\\n");
for(i = 0; i < n_colors; i++) {
sem_post(&sem_print);
}
for(i = 0; i < n_colors; i++) {
pthread_join(pid_tab[i], &rslt);
total += *(int *)rslt;
free(rslt);
}
spell_the_number(-1, total);
printf("\\n");
}
int
main(int argc, char **argv) {
color first_generation[3] = { BLUE, RED, YELLOW };
color second_generation[10] = {BLUE, RED, YELLOW, RED, YELLOW,
BLUE, RED, YELLOW, RED, BLUE};
int number_of_meetings_to_run = 600;
if(argc > 1) {
number_of_meetings_to_run = strtol(argv[1], 0, 10);
}
print_colors();
run_the_meetings(first_generation, 3, number_of_meetings_to_run);
run_the_meetings(second_generation, 10, number_of_meetings_to_run);
return 0;
}
| 0
|
#include <pthread.h>
struct data
{
double *a;
double *b;
int len;
int offset;
};
pthread_t threads[8];
pthread_mutex_t mutex_sum;
double sum;
void *dot(void *arg)
{
int start;
int end;
int length;
double *x;
double *y;
double sub_sum;
struct data *d = (struct data*) arg;
length = d->len;
start = d->offset * length;
end = start + length;
x = d->a;
y = d->b;
sub_sum = 0.0;
for(int i=start; i<end; ++i)
{
sub_sum += x[i] * y[i];
}
pthread_mutex_lock(&mutex_sum);
sum += sub_sum;
pthread_mutex_unlock(&mutex_sum);
pthread_exit((void*) 0);
}
int main(int argc, char **argv)
{
double *a = (double*)malloc(8 * 1000000 * sizeof(double));
double *b = (double*)malloc(8 * 1000000 * sizeof(double));
struct data d[8];
pthread_attr_t attr;
for(int i=0; i<1000000 * 8; ++i)
{
a[i] = 1.0;
b[i] = 1.0;
}
sum = 0.0;
pthread_mutex_init(&mutex_sum, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(int i=0; i<8; ++i)
{
d[i].a = a;
d[i].b = b;
d[i].offset = i;
d[i].len = 1000000;
pthread_create(&threads[i], &attr, dot, (void*)&d[i]);
}
pthread_attr_destroy(&attr);
for(int i=0; i<8; ++i)
{
pthread_join(threads[i], 0);
}
printf("Sum is %f\\n", sum);
free(a);
free(b);
pthread_mutex_destroy(&mutex_sum);
return 0;
}
| 1
|
#include <pthread.h>
int sum;
pthread_mutex_t mutex;
}Ticket,*Ticketpoint;
void* pthfunc1(void *p)
{
Ticketpoint ptic=(Ticketpoint)p;
while(1)
{
pthread_mutex_lock(&ptic->mutex);
if(ptic->sum>0)
{
printf("I am salewindow1,sum=%d\\n",ptic->sum);
sleep(2);
ptic->sum--;
printf("I am salewindow1,sale successful,sum=%d\\n",ptic->sum);
pthread_mutex_unlock(&ptic->mutex);
}else{
pthread_mutex_unlock(&ptic->mutex);
printf("The ticket is over,salewindow1 closed\\n");
break;
}
}
pthread_exit(0);
}
void* pthfunc2(void *p)
{
Ticketpoint ptic=(Ticketpoint)p;
while(1)
{
pthread_mutex_lock(&ptic->mutex);
if(ptic->sum>0)
{
printf("I am salewindow2,sum=%d\\n",ptic->sum);
sleep(2);
ptic->sum--;
printf("I am salewindow2,sale successful,sum=%d\\n",ptic->sum);
pthread_mutex_unlock(&ptic->mutex);
}else{
pthread_mutex_unlock(&ptic->mutex);
printf("The ticket is over,salewindow2 closed\\n");
break;
}
}
pthread_exit(0);
}
int main()
{
Ticket tic;
tic.sum=20;
pthread_mutex_init(&tic.mutex,0);
pthread_t pthid1,pthid2;
pthread_create(&pthid1,0,pthfunc1,(void*)&tic);
pthread_create(&pthid2,0,pthfunc2,(void*)&tic);
pthread_join(pthid1,0);
pthread_join(pthid2,0);
return 0;
}
| 0
|
#include <pthread.h>
int nitems;
struct
{
pthread_mutex_t mutex;
int buff[1000000];
int nput;
int nval;
} shared = {
PTHREAD_MUTEX_INITIALIZER
};
void *produce(void*);
void *consume(void*);
void consume_wait(int);
int main(int argc,char *argv[])
{
int i,nthreads,count[100];
pthread_t tid_produce[100],tid_consume;
if(argc != 3)
{
exit(0);
}
nitems = atoi(argv[1]);
nthreads = atoi(argv[2]);
pthread_setconcurrency(nthreads+1);
for(i=0;i<nthreads;++i)
{
count[i] = 0;
pthread_create(&tid_produce[i],0,produce,&count[i]);
}
pthread_create(&tid_consume,0,consume,0);
for(i=0;i<nthreads;i++)
{
pthread_join(tid_produce[i],0);
printf("thread exit, count[%d] = %d\\n",i,count[i]);
}
pthread_join(tid_consume,0);
exit(0);
}
void *produce(void *arg)
{
for(; ;)
{
pthread_mutex_lock(&shared.mutex);
if(shared.nput >= nitems)
{
pthread_mutex_unlock(&shared.mutex);
return 0;
}
shared.buff[shared.nput] = shared.nval;
shared.nput++;
shared.nval++;
pthread_mutex_unlock(&shared.mutex);
*((int*) arg) += 1;
}
}
void *consume(void *arg)
{
int i;
for(i=0;i<nitems;i++)
{
consume_wait(i);
if(shared.buff[i] != i)
printf("buff[%d] = %d\\n",i,shared.buff[i]);
}
return 0;
}
void consume_wait(int i)
{
for(; ;)
{
pthread_mutex_lock(&shared.mutex);
if(i<shared.nput)
{
printf("consume %d\\n", i);
pthread_mutex_unlock(&shared.mutex);
return;
}
pthread_mutex_unlock(&shared.mutex);
}
}
| 1
|
#include <pthread.h>
char ipaddr[]="192.168.250.0";
int ipactual=1;
pthread_mutex_t p;
int ping(void) {
char *command = 0;
char buffer[1024];
FILE *fp;
int stat = 0;
asprintf (&command, "%s %s -c 1", "ping", ipaddr);
printf("%s\\n", command);
fp = popen(command, "r");
if (fp == 0) {
fprintf(stderr, "Failed to execute fping command\\n");
free(command);
return -1;
}
while(fread(buffer, sizeof(char), 1024, fp)) {
if (strstr(buffer, "1 received"))
return 0;
}
stat = pclose(fp);
free(command);
return 1;
}
void* pingtest(void* actual){
int *ptr= (int*) actual;
pthread_mutex_lock (&p);
ipaddr[12]=ipactual+'0';
ipactual++;
int status=ping();
if (status == 0) {
printf("Could ping %s successfully, status %d\\n", ipaddr, status);
}
else {
printf("Machine not reachable, status %d\\n", status);
}
pthread_mutex_unlock (&p);
pthread_exit(0);
}
int main(int argc, char *argv[]){
int i, start, tids[10];
pthread_t threads[10];
pthread_attr_t attr;
pthread_mutex_init(&p, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (i=0; i<10; i++) {
tids[i] = i;
pthread_create(&threads[i], &attr, pingtest, (void *) &ipactual);
}
for (i=0; i<10; i++) {
pthread_join(threads[i], 0);
}
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&p);
pthread_exit (0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
void prepare(void)
{
printf("parent locks...\\n");
pthread_mutex_lock(&lock1);
pthread_mutex_lock(&lock2);
}
void parent(void)
{
printf("parent unlocking locks...\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void child(void)
{
printf("child unlocking locks...\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void *thr_fn(void *arg)
{
printf("thread started...\\n");
pause();
return (0);
}
int main(void)
{
int err;
pid_t pid;
pthread_t tid;
if ((err = pthread_atfork(prepare, parent, child))!=0)
{
err_exit(err,"can't install fork handlers");
}
err = pthread_create(&tid, 0, thr_fn,0);
if (err!=0)
{
err_exit(err, "can't create thread");
}
sleep(2);
printf("parent about to fork...\\n");
if ((pid =fork())<0)
{
err_quit("fork failed");
}
else if (pid == 0)
{
printf("child returnd from fork\\n");
}
else
{
printf("parent returned from fork\\n");
}
exit(0);
}
| 1
|
#include <pthread.h>
int inn,inn_size;
int rl,fl,ry,fy,type;
pthread_mutex_t mutex;
pthread_cond_t lc[20];
pthread_cond_t yc[20];
int lqueue[20];
int yqueue[20];
pthread_t tid[20];
pthread_attr_t attr;
void initializeData() {
pthread_mutex_init(&mutex, 0);
pthread_attr_init(&attr);
int i;
inn_size = 2;
inn=0;
rl=fl=ry=fy=0;
type=rand()%2;
}
void _enterq(int clan,int id){
if(clan==0){
lqueue[rl]=id;
rl=(rl+1)%20;
}
else{
yqueue[ry]=id;
ry=(ry+1)%20;
}
}
int _exitq(int clan){
int tmp;
if(clan==0){
tmp=lqueue[fl];
fl=(fl+1)%20;
}
else{
tmp=yqueue[fy];
fy=(fy+1)%20;
}
return tmp;
}
int _inviteq(int clan){
int tmp;
if(clan==0){
tmp=lqueue[fl];
}
else{
tmp=yqueue[fy];
}
return tmp;
}
void *pub(void *param) {
int clan=rand()%2;
int id=param,inv;
pthread_mutex_lock(&mutex);
_enterq(clan,id);
if(inn==inn_size||type!=clan){
if(clan==0){
printf("%d:Lacannaster waiting\\n",id);
pthread_cond_wait(&lc[id], &mutex);
}
else{
printf("%d:York waiting\\n",id);
pthread_cond_wait(&yc[id], &mutex);
}
}
inv=_exitq(clan);
inn++;
if(inn==0)
{
type=clan;
}
if(clan==0)
printf("%d:Lacannaster entered\\n",id);
else
printf("%d:York entered\\n",id);
pthread_mutex_unlock(&mutex);
sleep(rand()%5);
pthread_mutex_lock(&mutex);
inn--;
if(clan==0){
printf("%d:Lacannaster exited\\n",id);
if(rl-fl>0&&inn!=1){
inv=_inviteq(clan);
pthread_cond_signal(&lc[inv]);
}
else if(ry-fy>0&&!inn){
inv=_inviteq(clan^1);
type^=1;
pthread_cond_signal(&yc[inv]);
}
}
else{
printf("%d:York exited\\n",id);
if(ry-fy>0&&inn!=1){
inv=_inviteq(clan);
pthread_cond_signal(&yc[inv]);
}
else if(rl-fl>0&&!inn)
{
inv=_inviteq(clan^1);
type^=1;
pthread_cond_signal(&lc[inv]);
}
}
pthread_mutex_unlock(&mutex);
}
int main() {
int i;
int *arg = malloc(sizeof(*arg));
initializeData();
int n=10;
for(i = 0; i < n; i++) {
arg=i;
pthread_create(&tid[i],&attr,pub,arg);
}
for(i = 0; i < n; i++) {
pthread_join(tid[i], 0);
}
return 0;
}
| 0
|
#include <pthread.h>
void *functionC();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 1;
int main() {
int rc1, rc2;
pthread_t thread1, thread2;
if ((rc1 = pthread_create(&thread1, 0, &functionC, 0))) {
printf("Thread creation failed: %d\\n", rc1);
}
if ((rc2 = pthread_create(&thread2, 0, &functionC, 0))) {
printf("Thread creation failed: %d\\n", rc2);
}
pthread_join(thread1, 0);
pthread_join(thread2, 0);
exit(0);
}
void *functionC() {
pthread_mutex_lock(&mutex1);
counter++;
printf("Counter value: %d\\n", counter);
pthread_mutex_unlock(&mutex1);
}
| 1
|
#include <pthread.h>
pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t creating_theads_mutex = PTHREAD_MUTEX_INITIALIZER;
int creating_theads = 0;
static int **matris;
static int **matris2;
static int **matrisc;
static int satir, kolon, satir2, kolon2;
static int s, k, c, toplam;
static int i;
static void init() {
fflush(stdout);
if(creating_theads > 0) {
fflush(stdout);
pthread_mutex_lock( &condition_mutex );
fflush(stdout);
pthread_cond_wait( &condition_cond, &condition_mutex );
fflush(stdout);
pthread_mutex_unlock( &condition_mutex );
fflush(stdout);
} else {
pthread_mutex_unlock(&creating_theads_mutex);
fflush(stdout);
}
int ic1,ic2;
for(ic1=0; ic1<k; ic1++) {
for(ic2=0; ic2<c; ic2++) {
matrisc[(satirno*k) + ic1] += matris[(satirno*c) + ic2] * matris2[(ic2*k)+ic1];
}
}
}
int main(void)
{
printf("NOT:iki matrisin carpilmasi icin birinci matrisin kolon sayisi ile ikinci matrisin satir sayisi esit olmak zorunda lufen bunu goz onunde bulundurarak carpma isleminizi yapiniz.\\n\\n");
printf("1. Matrisin satir sayisi: ");
scanf("%d", &satir);
printf("1. Matrisin kolon sayisi: ");
scanf("%d", &kolon);
matris = (int **) calloc(satir, sizeof(int));
for(i = 0; i < satir; i++)
matris[i] = (int *) calloc(kolon, sizeof(int));
for(s = 0; s < satir; s++)
for(k = 0; k < kolon; k++) {
printf("Matrisin elemani girin: matris[%d][%d] = ", s, k);
scanf("%d", &(matris[s][k]));
}
printf("\\nGirilen matris:\\n");
for(s = 0; s < satir; s++) {
for(k = 0; k < kolon; k++)
printf("%4d", matris[s][k]);
printf("\\n\\n");
}
printf("2. Matrisin satir sayisi: ");
scanf("%d", &satir2);
printf("2. Matrisin kolon sayisi: ");
scanf("%d", &kolon2);
matris2 = (int **) calloc(satir2, sizeof(int));
for(i = 0; i < satir2; i++)
matris2[i] = (int *) calloc(kolon2, sizeof(int));
for(s = 0; s < satir2; s++)
for(k = 0; k < kolon2; k++) {
printf("Matrisin elemani girin: matris[%d][%d] = ", s, k);
}
printf("\\nGirilen matris:\\n");
for(s = 0; s < satir2; s++) {
for(k = 0; k < kolon2; k++)
printf("%4d", matris2[s][k]);
printf("\\n");
}
printf("\\nCarpim matirisi:\\n");
matrisc = (int **) calloc(satir, sizeof(int));
for(i = 0; i < satir; i++)
matrisc[i] = (int *) calloc(kolon2, sizeof(int));
for(s=0; s<satir; s++){
for(k=0; k<kolon2; k++){
for(toplam=0, c=0; c<satir2; c++)
toplam += matris[s][c]*matris2[c][k];
matrisc[s][k] = toplam;
printf("%4d",matrisc[s][k]);
}
printf("\\n");
}
printf("\\n");
pthread_t threads[m];
fflush(stdout);
creating_theads = 1;
printf("Threadler yaratiliyor...\\n");
fflush(stdout);
for(i=0;i<m;i++) {
fflush(stdout);
pthread_create(&threads[i], 0, &init, i);
}
pthread_mutex_lock(&creating_theads_mutex);
creating_theads = 0;
pthread_mutex_unlock(&creating_theads_mutex);
printf("Thread yaratimi tamamlamdi. Simdi beklemelerin bitmesi icin mesaj gonderilecek.\\n");
fflush(stdout);
pthread_mutex_lock( &condition_mutex );
pthread_cond_broadcast( &condition_cond );
pthread_mutex_unlock( &condition_mutex );
printf("Beklemekte olabilecek threadlere isleme baslamasini soyleyen mesaj gonderildi.\\n");
fflush(stdout);
for(i=0;i<m;i++) {
pthread_join(threads[i],0);
}
printf("\\nMatris C:\\n");
for(i=0;i<m;i++) {
for(j=0;j<k;j++) {
printf("%d\\t", matrisC[i][j]);
}
printf("\\n");
}
}
| 0
|
#include <pthread.h>
char buf[30];
pthread_mutex_t lock;
pthread_t threads[2];
struct data
{
int threadId;
int filedesc;
};
struct data data1,data2;
void *write_func(void *arg)
{
struct data *i = (struct data*)arg;
int id = i->threadId;
int fd0 = i->filedesc;
char buffer[30];
printf("\\n Thread id %d has started writing device \\n", id);
printf("Write trying to acquire lock \\n");
pthread_mutex_lock(&lock);
printf("Write inside crtical region \\n");
strcpy(buffer,buf);
write(fd0,buffer,sizeof(buf));
pthread_mutex_unlock(&lock);
printf("Write released lock \\n");
printf("Data Written using thread %d to device \\n",id);
pthread_exit(0);
}
void *read_func(void *arg)
{
struct data *i = (struct data*)arg;
int id = i->threadId;
int fd0 = i->filedesc;
char buffer[30];
printf("\\n Thread id %d has started reading device \\n", id);
read(fd0,buffer,sizeof(buffer));
printf("Read trying to acquire lock \\n");
pthread_mutex_lock(&lock);
strcpy(buf,buffer);
printf("Read inside critical region \\n");
pthread_mutex_unlock(&lock);
printf("Read released lock \\n");
printf("Data Read using thread %d from device \\n",id);
pthread_exit(0);
}
int main()
{
int fd0;
char* msg;
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("\\n mutex init failed\\n");
return 1;
}
fd0 = open("/dev/a5", O_RDWR);
if(fd0 == -1)
{
msg = strerror(errno);
printf("File %s either does not exist or has been locked by another process\\n", "/dev/a5");
fprintf(stderr, "open failed: %s\\n", msg);
exit(-1);
}
printf(" Device opened from main thread file descriptor = %d \\n",fd0);
data1.threadId = 0;
data1.filedesc = fd0;
pthread_create(&(threads[0]), 0, write_func, (void*)&data1);
data2.threadId = 1;
data2.filedesc = fd0;
pthread_create(&(threads[1]), 0, read_func, (void*)&data2);
pthread_join(threads[0], 0);
pthread_join(threads[1], 0);
close(fd0);
printf(" Device closed from main thread \\n");
pthread_mutex_destroy(&lock);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mx;
pthread_mutex_t my;
pthread_mutex_t mz;
int x = 0;
void *ta(void *arg)
{
pthread_mutex_lock(&mx);
x = 1;
pthread_mutex_unlock(&mx);
pthread_mutex_lock(&mz);
pthread_mutex_unlock(&mz);
return 0;
}
void *tb(void *arg)
{
pthread_mutex_lock (&mx);
if (x)
{
pthread_mutex_lock (&my);
pthread_mutex_unlock (&my);
}
pthread_mutex_unlock (&mx);
return 0;
}
void *tc(void *arg)
{
pthread_mutex_lock (&my);
pthread_mutex_lock (&mz);
pthread_mutex_unlock (&mz);
pthread_mutex_unlock (&my);
return 0;
}
int main()
{
pthread_t ida;
pthread_t idb;
pthread_t idc;
pthread_mutex_init(&mx, 0);
pthread_mutex_init(&my, 0);
pthread_mutex_init(&mz, 0);
pthread_create(&idc, 0, tc, 0);
pthread_create(&idb, 0, tb, 0);
pthread_create(&ida, 0, ta, 0);
pthread_exit (0);
return 0;
}
| 0
|
#include <pthread.h>
int counter = 0;
int thread_ids[3] = {0, 1, 2};
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *inc_counter(void *data_in);
void *watch_counter(void *data_in);
int main(int argc, char *argv[])
{
int i;
long t1 = 1, t2 = 2, t3 = 3;
pthread_t threads[3];
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init(&count_threshold_cv, 0);
pthread_create(&threads[0], 0, watch_counter, (void *) t1);
pthread_create(&threads[1], 0, inc_counter, (void *) t2);
pthread_create(&threads[2], 0, inc_counter, (void *) t3);
for(i = 0; i < 3; i++)
{
pthread_join(threads[i], 0);
}
printf ("Main(): Waited on %d threads. Done.\\n", 3);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit(0);
}
void *inc_counter(void *data_in)
{
int i;
long my_id;
my_id = (long) data_in;
for(i = 0; i < 10; i++)
{
pthread_mutex_lock(&count_mutex);
counter++;
if(counter == 12)
{
pthread_cond_signal(&count_threshold_cv);
printf("[inc_counter()]: thread %ld, counter = %d. Threshold reached\\n", my_id, counter);
}
printf("[inc_counter()]: thread %ld, counter = %d. Unlocking mutex\\n", my_id, counter);
pthread_mutex_unlock(&count_mutex);
sleep(1);
}
pthread_exit(0);
}
void *watch_counter(void *data_in)
{
long my_id;
my_id = (long) data_in;
printf("Starting watch_count(): thread %ld\\n", my_id);
pthread_mutex_lock(&count_mutex);
while(counter < 12)
{
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("[watch_count()]: thread %ld Condition signal received.\\n", my_id);
counter += 125;
printf("[watch_count()]: thread %ld count now = %d.\\n", my_id, counter);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
struct person
{
int num;
double sum;
}Person;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
void creat_ret()
{
int num ;
double sum ;
printf("请输入红包的个数和金额:");
scanf("%d %lf",&num,&sum);
pthread_mutex_lock(&mutex);
Person.num = num;
Person.sum = sum *100;
pthread_mutex_unlock(&mutex);
usleep(1);
}
void *consumer(void *arg)
{
int money =0;
int i = * (int *) arg;
pthread_mutex_lock(&mutex);
if(Person.num < 1 )
{
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
else if(Person.num == 1)
{
money = Person.sum;
}
else if(Person.sum/Person.num==1)
{
money ==1;
}
else
{
money = Person.sum *(rand()%((200) - (1) ) + 1)/100/Person.num;
}
Person.sum -= money;
Person.num--;
printf("%dth thread\\tget %d.%d%d money\\n",i,money/100,(money/10)%10,money%10);
pthread_mutex_unlock(&mutex);
return 0;
}
int main()
{
int ret;
pthread_t ctid[100];
srand(time(0));
creat_ret();
int arr[100];
int i;
for(i = 0;i < 100;i++)
{
arr[i] = i+1;
if( ( ret = pthread_create(&ctid[i],0,consumer,&arr[i])) !=0)
{
printf("线程%d创建失败\\n",i);
}
else
{
}
}
for(i =0;i<100;i++)
{
pthread_join(ctid[i],0);
}
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
void* salewin2(void *p){
int *t=(int*) p;
while(1){
pthread_mutex_lock(&mutex);
if(*t>0){
printf(" salewin2 starts %d\\n",*t);
sleep(2);
(*t)--;
pthread_mutex_unlock(&mutex);
printf(" salewin2 over %d\\n",*t);
}else{
pthread_mutex_unlock(&mutex);
printf("salewin2 overall\\n");
pthread_exit(0);
}
}
}
void* salewin1(void *p){
int *t=(int*) p;
while(1){
pthread_mutex_lock(&mutex);
if(*t>0){
printf("salewin1 starts %d\\n",*t);
sleep(2);
(*t)--;
pthread_mutex_unlock(&mutex);
printf("salewin1 over %d\\n",*t);
}else{
pthread_mutex_unlock(&mutex);
printf("salewin1 overall\\n");
pthread_exit(0);
}
}
}
int main(){
pthread_t pthid1, pthid2;
int tickets=20;
pthread_mutex_init(&mutex,0);
pthread_create(&pthid1,0,salewin1,&tickets);
pthread_create(&pthid2,0,salewin2,&tickets);
pthread_join(pthid1,0);
pthread_join(pthid2,0);
printf("over tickets=%d\\n",tickets);
return 0;
}
| 1
|
#include <pthread.h>
static void
dbgprintf (const char *fmt, ...)
{
struct timespec tp;
va_list ap;
if (clock_gettime (CLOCK_MONOTONIC, &tp) == 0)
printf ("%lu.%lu ", tp.tv_sec, tp.tv_nsec);
__builtin_va_start((ap));
vprintf (fmt, ap);
;
}
static int ready[10];
static pthread_mutex_t ready_lock[10];
static pthread_rwlock_t fire_signal[50000];
static const pthread_once_t fresh_once = PTHREAD_ONCE_INIT;
static pthread_once_t once_control;
static int performed;
static pthread_mutex_t performed_lock = PTHREAD_MUTEX_INITIALIZER;
static void
once_execute (void)
{
pthread_mutex_lock (&performed_lock);
performed++;
pthread_mutex_unlock (&performed_lock);
}
static void *
once_contender_thread (void *arg)
{
int id = (int) (long) arg;
int repeat;
for (repeat = 0; repeat <= 50000; repeat++)
{
pthread_mutex_lock (&ready_lock[id]);
ready[id] = 1;
pthread_mutex_unlock (&ready_lock[id]);
if (repeat == 50000)
break;
dbgprintf ("Contender %p waiting for signal for round %d\\n",
pthread_self (), repeat);
pthread_rwlock_rdlock (&fire_signal[repeat]);
pthread_rwlock_unlock (&fire_signal[repeat]);
dbgprintf ("Contender %p got the signal for round %d\\n",
pthread_self (), repeat);
pthread_once (&once_control, once_execute);
}
return 0;
}
static void
test_once (void)
{
int i, repeat;
pthread_t threads[10];
for (i = 0; i < 10; i++)
{
ready[i] = 0;
pthread_mutex_init (&ready_lock[i], 0);
}
for (i = 0; i < 50000; i++)
pthread_rwlock_init (&fire_signal[i], 0);
for (i = 50000 -1; i >= 0; i--)
pthread_rwlock_wrlock (&fire_signal[i]);
for (i = 0; i < 10; i++)
pthread_create (&threads[i], 0, once_contender_thread, (void *) (long) i);
for (repeat = 0; repeat <= 50000; repeat++)
{
dbgprintf ("Main thread before synchronizing for round %d\\n", repeat);
for (;;)
{
int ready_count = 0;
for (i = 0; i < 10; i++)
ready_count += ready[i];
if (ready_count == 10)
break;
pthread_yield ();
}
dbgprintf ("Main thread after synchronizing for round %d\\n", repeat);
if (repeat > 0)
{
if (performed != 1)
abort ();
}
if (repeat == 50000)
break;
memcpy (&once_control, &fresh_once, sizeof (pthread_once_t));
performed = 0;
for (i = 0; i < 10; i++)
{
pthread_mutex_lock (&ready_lock[i]);
ready[i] = 0;
pthread_mutex_unlock (&ready_lock[i]);
}
dbgprintf ("Main thread giving signal for round %d\\n", repeat);
pthread_rwlock_unlock (&fire_signal[repeat]);
}
for (i = 0; i < 10; i++)
pthread_join (threads[i], 0);
}
int
main ()
{
printf ("Starting test_once ..."); fflush (stdout);
test_once ();
printf (" OK\\n"); fflush (stdout);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int a = 0;
void *thread_a(void *arg) {
while(1) {
pthread_mutex_lock(&mutex);
a = 1;
if(1) {
printf("a %d\\n", a);
}
usleep(10000);
}
return 0;
}
void *thread_b(void *arg) {
while(1) {
pthread_mutex_unlock(&mutex);
a = 2;
if(1) {
printf("b %d\\n", a);
}
usleep(10000);
}
return 0;
}
void *thread_c(void *arg) {
while(1) {
pthread_mutex_lock(&mutex);
a = 3;
if(1) {
printf("c %d\\n", a);
}
usleep(10000);
}
return 0;
}
int main() {
pthread_t id;
pthread_create(&id, 0, thread_a, 0);
pthread_create(&id, 0, thread_b, 0);
pthread_create(&id, 0, thread_c, 0);
while(1) {
sleep(100);
}
return 0;
}
| 1
|
#include <pthread.h>
int sockfd;
int cameraFd;
char unsigned *devconfp;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void sig_handler(int signo)
{
if(SIGINT == signo){
printf("SIGINT will be exist!\\n");
close(sockfd);
exit(1);
}
}
unsigned char *temp;
ssize_t length;
void get_frame(int cameraFd)
{
void *start;
size_t length;
}VideoBuffer;
VideoBuffer *buffers;
struct v4l2_buffer buf;
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
if(ioctl(cameraFd,VIDIOC_DQBUF,&buf) == -1){
perror("dqbuf");
exit(1);
}
length = buf.bytesused;
temp = (unsigned char *)malloc(length);
memset(temp,0,sizeof(temp));
memcpy(temp,buffers[buf.index].start,length);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
if(ioctl(cameraFd,VIDIOC_QBUF,&buf) == -1){
perror("qbuf");
exit(1);
}
exit(0);
}
int stop = 0;
void *th_fn1(void *arg)
{
int cameraFd = (int)arg;
enum v4l2_buf_type type;
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
while(!stop){
get_frame(cameraFd);
devconfp = (unsigned char*)malloc(length);
memset(devconfp,0,length);
pthread_mutex_lock(&mutex);
memcpy(devconfp,temp,length);
pthread_mutex_unlock(&mutex);
pthread_cond_broadcast(&cond);
usleep(1500);
free(temp);
}
if(ioctl(cameraFd,VIDIOC_STREAMOFF,&type) == -1){
perror("streamoff");
exit(1);
}
return (void*)0;
}
void send_msg(int fd)
{
ssize_t size;
char readbuffer[1024] = {'\\0'};
char writebuffer[1024] = {'\\0'};
if((size = read(fd,readbuffer,1024)) < 0){
perror("read");
exit(1);
}
char respbuffer[1024] = "HTTP/1.0.200 OK\\r\\nConnetctiion:close\\r\\nServer:Net-camera-1-0\\r\\nCache=Control:no-store,no-cache,muset-revalidate, pre-check=0;post-check=0,max-age=0\\r\\nPragma:no-cache\\r\\nContent-type: multipart/x-mixed-replace;boundarpy = www.briup.com\\r\\n\\r\\n";
if(write(fd,respbuffer,strlen(respbuffer)) != size){
perror("write");
exit(1);
}
printf("read: %s\\n",readbuffer);
printf("size: %d\\n",size);
printf("%s\\n",respbuffer);
if(strstr(readbuffer,"snapshot"))
{
sprintf(writebuffer,"--www.briup.com\\nContent-type:image/jpeg\\nContern-Length:%d\\n\\n",length+432);
if(write(fd,writebuffer,strlen(writebuffer)) != size){
printf("size: %d\\n",size);
perror("write");
exit(1);
}
printf("writebuffer:%s",writebuffer);
pthread_mutex_lock(&mutex);
if(pthread_cond_wait(&cond,&mutex) != 0){
perror("condwait");
exit(1);
}
int file = open("mpge.pig",O_CREAT|O_RDWR|O_TRUNC,0777);
if(file < 0){
perror("open");
exit(1);
}
print_picture(fd,devconfp,length);
free(devconfp);
pthread_mutex_unlock(&mutex);
}else{
while(1){
memset(writebuffer,0,sizeof(writebuffer));
sprintf(writebuffer,"--www.briup.com\\nContent-type:image/jpeg\\nContent-Length:%d\\n\\n",length+432);
pthread_mutex_lock(&mutex);
if(pthread_cond_wait(&cond,&mutex) != 0){
perror("condwait");
exit(1);
}
write(fd,writebuffer,strlen(writebuffer));
print_picture(fd,devconfp,length);
sleep(1);
free(devconfp);
pthread_mutex_unlock(&mutex);
}
}
}
void *th_fn2(void *arg)
{
int fd = (int)arg;
send_msg(fd);
close(fd);
exit(0);
}
void *service_fn(void *arg)
{
int fd = (int)arg;
pthread_t th1,th2;
int err;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
err = pthread_create(&th1,&attr,th_fn1,(void*)fd);
if(err < 0){
perror("pthread_create");
exit(1);
}
err = pthread_create(&th2,&attr,th_fn2,(void*)fd);
if(err < 0){
perror("pthread_create");
exit(1);
}
return (void*)0;
}
int main(int argc,char *argv[])
{
if(argc != 3){
fprintf(stderr,"-usage:%s devname\\n",argv[0]);
exit(1);
}
printf("***program begin***\\n");
get_dev(argv[1]);
printf("devname:%s\\n",argv[1]);
if((cameraFd = open(argv[1],O_RDWR)) < 0){
perror("open");
exit(1);
}
printf("cameraFd:%d\\n",cameraFd);
get_capability(cameraFd);
select_input(cameraFd);
set_frame(cameraFd);
do_frame(cameraFd);
sockfd = socket(AF_INET,SOCK_STREAM,0);
if(sockfd < 0){
perror("sockfd");
exit(1);
}
if(signal(SIGINT,sig_handler) == SIG_ERR){
perror("signal");
exit(1);
}
int err;
pthread_t th;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
struct sockaddr_in saddr;
memset(&saddr,0,sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(atoi(argv[2]));
saddr.sin_addr.s_addr = INADDR_ANY;
if(bind(sockfd,(struct sockaddr *)&saddr,sizeof(saddr)) < 0){
perror("bind");
exit(1);
}
if(listen(sockfd,10) <0){
perror("listen");
exit(1);
}
if(signal(SIGINT,sig_handler) == SIG_ERR){
perror("signal");
exit(1);
}
while(1){
int fd = accept(sockfd,0,0);
if(fd < 0){
perror("accept");
exit(1);
}else {
err = pthread_create(&th,&attr,service_fn,(void*)fd);
if(err != 0){
fprintf(stderr,"usage:%s\\n",strerror(err));
}
}
}
exit(1);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mymutex;
float * px = 0;
static void * affiche_max_fois_valeur_px (void * p_data)
{
int max = (int) p_data;
int i;
for (i = 0; i < max; i++) {
pthread_mutex_lock(&mymutex);
printf("[thread] %f\\n", *px);
pthread_mutex_unlock(&mymutex);
}
char *resultChild = malloc(20);
strcpy(resultChild, "statusFinChild");
pthread_exit(resultChild);
return 0;
}
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("erreur de parametres\\n");
return -1;
}
int max = atoi(argv[1]);
pthread_mutex_init(&mymutex, 0);
float x = 1;
px = &x;
pthread_t myThread;
int ret = pthread_create (
& myThread, 0,
affiche_max_fois_valeur_px, (void *) max
);
int i;
for (i = 0; i < max; i++) {
pthread_mutex_lock(&mymutex);
px = 0;
printf("[main] %i\\n", i);
px = &x;
pthread_mutex_unlock(&mymutex);
}
printf("termine\\n");
char* retChildThread;
pthread_join(myThread, (void**)&retChildThread);
printf("child ended : %s\\n", retChildThread);
pthread_mutex_destroy(&mymutex);
return(0);
}
| 1
|
#include <pthread.h>
pthread_cond_t buffer_cheio = PTHREAD_COND_INITIALIZER;
pthread_cond_t buffer_vazio = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int posicoes_ocupadas=0;
int valor=0;
int buffer[50];
void *produtor(void *argumentos){
while (1){
pthread_mutex_lock(&mutex);
if (posicoes_ocupadas == 50) {
printf("!!! Produtor Esperando !!!\\n");
pthread_cond_wait(&buffer_cheio, &mutex);
}
buffer[posicoes_ocupadas] = valor;
printf("Valor produzido: %d\\n", buffer[posicoes_ocupadas]);
valor++;
posicoes_ocupadas++;
if (posicoes_ocupadas==1){
pthread_cond_signal(&buffer_vazio);
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void *consumidor(void *argumentos){
int leitura;
while(1){
pthread_mutex_lock(&mutex);
if (posicoes_ocupadas == 0) {
printf("!!! Consumidor Esperando !!!\\n");
pthread_cond_wait(&buffer_vazio, &mutex);
}
leitura = buffer[posicoes_ocupadas];
printf("Valor lido: %d\\n", leitura);
posicoes_ocupadas--;
if (posicoes_ocupadas== 50 -1){
pthread_cond_signal(&buffer_cheio);
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main (){
pthread_t thread_produtor;
pthread_t thread_consumidor;
pthread_mutex_init(&mutexC, 0);
pthread_mutex_init(&mutexP, 0);
pthread_create(&thread_produtor, 0, produtor, 0);
pthread_create(&thread_consumidor, 0, consumidor, 0);
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t cerrojo;
pthread_mutex_t lectores;
int dato = 5;
int n_lect = 0;
void *Lector(void *arg);
void *Escritor(void *arg);
int main(int argc, char *argv[]) {
pthread_t th1, th2, th3, th4;
pthread_mutex_init(&cerrojo, 0);
pthread_create(&th1, 0, Lector, 0);
pthread_create(&th2, 0, Escritor, 0);
pthread_create(&th3, 0, Lector, 0);
pthread_create(&th4, 0, Escritor, 0);
pthread_join(th1, 0); pthread_join(th2, 0);
pthread_join(th3, 0); pthread_join(th4, 0);
pthread_mutex_destroy(&cerrojo);
exit(0);
}
void *Lector(void *arg) {
while(1){
pthread_mutex_lock(&cerrojo);
n_lect ++;
printf("%d\\n", dato);
n_lect--;
pthread_mutex_unlock(&cerrojo);
}
}
void *Escritor(void *arg){
while(1){
pthread_mutex_lock(&cerrojo);
dato = dato + 5;
printf("modificando %d\\n", dato);
pthread_mutex_unlock(&cerrojo);
sleep(3);
}
}
| 1
|
#include <pthread.h>
int buf[64];
sem_t space_nums;
sem_t data_nums;
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
void *product(void *arg)
{
int index = 0;
while(1){
sem_wait(&space_nums);
pthread_mutex_lock(&lock1);
buf[index] = rand() %1234;
printf("producter done,data is %d\\n",buf[index]);
index++;
index %= 64;
sem_post(&data_nums);
pthread_mutex_unlock(&lock1);
}
}
void *consume(void *arg)
{
int index = 0;
while(1){
sem_wait(&data_nums);
pthread_mutex_lock(&lock2);
int data = buf[index];
printf("consumer done,data is %d\\n",data);
index++;
index %= 64;
sem_post(&space_nums);
sleep(1);
pthread_mutex_unlock(&lock2);
}
}
int main()
{
sem_init(&space_nums,0,64);
sem_init(&data_nums,0,0);
pthread_t producter1,producter2,producter3,producter4;
pthread_t consumer1,consumer2,consumer3;
pthread_create(&producter1,0,product,0);
pthread_create(&producter2,0,product,0);
pthread_create(&producter3,0,product,0);
pthread_create(&producter4,0,product,0);
pthread_create(&consumer1,0,consume,0);
pthread_create(&consumer2,0,consume,0);
pthread_create(&consumer3,0,consume,0);
pthread_join(producter1,0);
pthread_join(producter2,0);
pthread_join(producter3,0);
pthread_join(producter4,0);
pthread_join(consumer1,0);
pthread_join(consumer2,0);
pthread_join(consumer3,0);
sem_destroy(&space_nums);
sem_destroy(&data_nums);
pthread_mutex_destroy(&lock1);
pthread_mutex_destroy(&lock2);
return 0;
}
| 0
|
#include <pthread.h>
enum Protocol {
UPLOAD_PROTO = 0, INFO_PROTO = 1, AUDIO_PROTO = 2, VIDEO_PROTO = 3, INTERN_PROTO = 4
};
static struct libwebsocket_protocols protocols[] = { { "upload", callback_upload, sizeof(struct upload_user), RX_BUFFER_SIZE }, { "info",
callback_info, sizeof(struct toSend), RX_BUFFER_SIZE }, { "audio", callback_audio, sizeof(struct toSend), RX_BUFFER_SIZE }, { "video",
callback_video, sizeof(struct toSend), RX_BUFFER_SIZE }, { "intern", callback_intern, sizeof(peer), RX_BUFFER_SIZE }, { 0, 0, 0 } };
void sighandler(int sig) {
force_exit = 1;
}
int main(int argc, char *argv[]) {
int res, c, nsPort;
char *nameServer, *streamToDist;
char *envVars[NR_ENV_VARS];
struct lws_context_creation_info info;
struct libwebsocket_context *context;
struct libwebsocket *nameServerWsi;
signal(SIGINT, sighandler);
envVars[0] = VIDEO_DIR_ENV_VAR;
envVars[1] = BENTO4_ENV_VAR;
envVars[2] = CRS_ENV_VAR;
envVars[3] = SCRIPT_ENV_VAR;
res = verifyEnvironmentSettings(envVars, NR_ENV_VARS);
if (res < 0) {
exit(1);
}
nameServer = 0;
myPort = -1;
nsPort = -1;
while ((c = getopt(argc, argv, "s:t:p:")) != -1) {
switch (c) {
case 's':
nameServer = (char *) malloc((strlen(optarg) + 1) * sizeof(char));
if (nameServer != 0) {
strcpy(nameServer, optarg);
}
break;
case 't':
res = str2int(optarg, &nsPort);
break;
case 'p':
res = str2int(optarg, &myPort);
break;
case '?':
print_usage(argv[0]);
exit(1);
break;
default:
print_usage(argv[0]);
exit(1);
}
if (res < 0) {
break;
}
}
if (res < 0 || nameServer == 0 || nsPort == -1 || myPort < 1024) {
print_usage(argv[0]);
if (nameServer != 0) {
free(nameServer);
}
exit(1);
}
snprintf(myPortStr, MAX_PORT_LEN, "%d", myPort);
res = pthread_mutex_init(&fmux, 0);
if (res != 0) {
perror("pthread_mutex_init");
free(nameServer);
exit(1);
}
res = pthread_mutex_init(&lmux, 0);
if (res != 0) {
perror("pthread_mutex_init");
pthread_mutex_destroy(&fmux);
free(nameServer);
exit(1);
}
memset(&info, 0, sizeof(info));
info.port = myPort;
info.gid = -1;
info.uid = -1;
info.protocols = protocols;
printf("starting server...\\n");
context = libwebsocket_create_context(&info);
if (context == 0) {
fprintf(stderr, "libwebsocket init failed\\n");
free(nameServer);
pthread_mutex_destroy(&fmux);
pthread_mutex_destroy(&lmux);
return 1;
}
toDist = llist_empty(free);
nameServerWsi = libwebsocket_client_connect(context, nameServer, nsPort, 0, "/", nameServer, "origin", "intern", -1);
if (nameServerWsi == 0) {
fprintf(stderr, "Could not connect to the nameserver\\n");
llist_free(toDist);
free(nameServer);
pthread_mutex_destroy(&fmux);
pthread_mutex_destroy(&lmux);
libwebsocket_context_destroy(context);
return 1;
}
while (!force_exit) {
libwebsocket_service(context, 500);
pthread_mutex_lock(&lmux);
if (!llist_isEmpty(toDist)) {
streamToDist = llist_inspect(llist_first(toDist));
res = distribute(streamToDist);
if (res == 0) {
llist_remove(llist_first(toDist), toDist);
}
}
pthread_mutex_unlock(&lmux);
}
printf("stopping server...\\n");
llist_free(toDist);
free(nameServer);
pthread_mutex_destroy(&fmux);
pthread_mutex_destroy(&lmux);
libwebsocket_context_destroy(context);
return 0;
}
int verifyEnvironmentSettings(char **envVars, size_t nrVars) {
int i, res;
char *dest;
res = 0;
for (i = 0; i < nrVars; i++) {
dest = getenv(envVars[i]);
if (dest == 0) {
fprintf(stderr, "%s environment variable not set!\\n", envVars[i]);
res = -1;
break;
}
if (dest[strlen(dest) - 1] != '/') {
fprintf(stderr, "%s environment variable must end in /!\\n", envVars[i]);
res = -1;
break;
}
}
return res;
}
void print_usage(char *prog) {
fprintf(stderr, "%s -s <nameServerURL> -t <nameServerPort> -p <listenPort>\\n", prog);
}
| 1
|
#include <pthread.h>
int valoresA[16], valoresB[16];
int separacao;
int sum = 0;
pthread_mutex_t mutex;
int calcularFinal(int threadAtual, int inicio){
if(threadAtual == 4 - 1){
int maiorFinalPossivel = 4 * separacao;
if(maiorFinalPossivel < 16){
return 16;
}
}
return inicio + separacao;
}
void *calculo(void *arg){
long int classificacaoThread = (long int) arg;
int inicio = (classificacaoThread * separacao);
int final = calcularFinal(classificacaoThread, inicio);
if(final <= 16){
int i, somaParcial = 0;
for(i = inicio; i < final; i++){
somaParcial += valoresA[i] * valoresB[i];
}
printf("Soma parcial da Thread[%d].. entre %d e %d eh igual a = %d\\n", classificacaoThread, inicio, (final-1) ,somaParcial);
pthread_mutex_lock(&mutex);
sum += somaParcial;
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
}
void criarEpopularVetores(){
int i;
for(i = 0; i < 16; i++){
valoresA[i] = rand()%10;
valoresB[i] = rand()%10;
}
separacao = 16/4;
}
void aguardarTerminoDeThreads(pthread_t thread[]){
int i;
for(i = 0; i < 4; i++){
pthread_join(thread[i], 0);
}
}
void printarVetores(){
int i;
printf("Valores de A = ");
for(i = 0; i < 16; i++){
if(i == (16 - 1)){
printf("%d", valoresA[i]);
}else{
printf("%d, ", valoresA[i]);
}
}
printf("\\n");
printf("Valores de B = ");
for(i = 0; i < 16; i++){
if(i == (16 - 1)){
printf("%d", valoresB[i]);
}else{
printf("%d, ", valoresB[i]);
}
}
printf("\\n");
}
int main(){
int *numeroThread, i;
srand(time(0));
pthread_mutex_init(&mutex, 0);
pthread_t vetorThreads[4];
criarEpopularVetores();
printarVetores();
if((16 >= 4) || separacao != 0){
for(i = 0; i < 4; i++){
long int numeroThread = i;
pthread_create(&vetorThreads[i], 0, calculo, (void *)numeroThread);
}
} else {
printf("O número de threads é maior que o vetor!");
return -1;
}
pthread_mutex_destroy(&mutex);
aguardarTerminoDeThreads(vetorThreads);
printf("Soma total = %d\\n", sum);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_attr_t attr;
pthread_t thread_id, thread_id2, thread_id3, thread_id4, thread_id5;
sem_t items, spaces;
int x = 1;
struct buffer_item {
int value;
int wait_time;
};
struct args{
long tid;
long sleep_time;
};
struct buffer_item buffer[32];
void *producer_c(void *tid){
int sem_num, val, rwait, pwait;
int thread_num = (int)tid;
while(x==1){
val = generate_rand(1,9);
rwait = generate_rand(2,9);
pwait = generate_rand(3,7);
printf("PRODUCER %d: Sleep for %d seconds\\n", thread_num+1, pwait);
sleep(pwait);
struct buffer_item event= { val, rwait };
sem_wait(&spaces);
pthread_mutex_lock(&mutex);
sem_getvalue(&items, &sem_num);
buffer[sem_num]=event;
pthread_mutex_unlock(&mutex);
sem_post(&items);
printf("PRODUCER %d: New event added!\\n", thread_num+1);
}
}
int main(int argc, char **argv){
int num_p, num_c;
int i, j;
num_p=generate_rand(2,7);
num_c=generate_rand(2,7);
pthread_mutex_init(&mutex, 0);
sem_init(&items, 0, 0);
sem_init(&spaces, 0, 3);
pthread_create(&thread_id, &attr, producer_c, (void*)1);
pthread_create(&thread_id, &attr, producer_c, (void*)2);
pthread_create(&thread_id, &attr, producer_c, (void*)3);
pthread_join(thread_id, 0);
return 0;
}
| 1
|
#include <pthread.h>
void *avoid(long droneid, int *homeRow, int *homeCol, int *targetRow, int *targetCol){
printf("Drone %d Avoiding Drone Near (%d, %d)!!!\\n", droneid, *homeRow, *homeCol);
pthread_mutex_lock(&mutex3);
if(d.grid[*homeRow+1][*homeCol]==0)
increaseRow(droneid, homeRow, homeCol, targetRow, targetCol);
else if(d.grid[*homeRow][*homeCol+1]==0)
increaseCol(droneid, homeRow, homeCol, targetRow, targetCol);
else if(d.grid[*homeRow][*homeCol-1]==0)
decreaseCol(droneid, homeRow, homeCol, targetRow, targetCol);
else if(d.grid[*homeRow-1][*homeCol]==0)
decreaseRow(droneid, homeRow, homeCol, targetRow, targetCol);
else{
abrt(droneid);
}
pthread_mutex_unlock(&mutex3);
}
void *abrt(long arg){
printf(" Warning: Drone %d is aborting!!\\n", arg);
}
| 0
|
#include <pthread.h>
pthread_mutex_t a;
pthread_mutex_t c;
pthread_mutex_t f;
pthread_mutex_t g;
int k;
int j;
void* fn1(void * args){
pthread_mutex_lock(&a);;
if( k == 25 ){
pthread_mutex_unlock(&f);;
pthread_mutex_lock(&g);;
if( j )
printf("hola\\n");
else
printf("adios\\n");
} else {
pthread_mutex_lock(&c);;
}
}
void* fn2(void * args){
pthread_mutex_unlock(&a);;
if( k == 12 ){
j = 1;
pthread_mutex_unlock(&c);;
} else {
j = 0;
pthread_mutex_lock(&f);;
j = 1;
pthread_mutex_unlock(&g);;
}
}
int main() {
pthread_t thread1;
pthread_t thread2;
pthread_create(&thread1, 0, &fn1, 0);
pthread_create(&thread2, 0, &fn2, 0);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
return 0;
}
| 1
|
#include <pthread.h>
int fd_list_open(struct shfs *fs, const char *name, size_t length)
{
char tmp_fname[1024];
char main_fname[1024];
size_t i;
fprintf(stderr, "FD_LIST opening %d bytes '%s'\\n", (int)length, name);
pthread_mutex_lock(&fs->fdlock);
if (fs->fdsize <= fs->fdlen) {
fprintf(stderr, "fd_list_open(%s): full\\n", name);
pthread_mutex_unlock(&fs->fdlock);
return -1;
}
sprintf(tmp_fname, "%s/%s", fs->tmpdir, name);
sprintf(main_fname, "%s/%s", fs->maindir, name);
for (i = 0; i < fs->fdlen; i++)
if (0 == strcmp(fs->fdlist[i].name, name)) {
fprintf(stderr, "FD_LIST already open '%s'\\n", name);
pthread_mutex_unlock(&fs->fdlock);
return -1;
}
memset(&fs->fdlist[i], 0, sizeof(fs->fdlist[i]));
strcpy(fs->fdlist[i].name, name);
fs->fdlist[i].offset = 0;
fs->fdlist[i].length = length;
fs->fdlist[i].lastrecv = time(0);
fs->fdlist[i].fd_tmp = fopen(tmp_fname, "wb");
if (0 == fs->fdlist[i].fd_tmp) {
fprintf(stderr, "FD_LIST could not open '%s'\\n", tmp_fname);
if (0 != fs->fdlist[i].fd_tmp)
fclose(fs->fdlist[i].fd_tmp);
if (0 != fs->fdlist[i].fd_main)
fclose(fs->fdlist[i].fd_main);
pthread_mutex_unlock(&fs->fdlock);
return -1;
}
fs->fdlist[i].fd_main = fopen(main_fname, "wb");
if (0 == fs->fdlist[i].fd_main) {
fprintf(stderr, "FD_LIST could not open '%s'\\n", main_fname);
if (0 != fs->fdlist[i].fd_tmp)
fclose(fs->fdlist[i].fd_tmp);
if (0 != fs->fdlist[i].fd_main)
fclose(fs->fdlist[i].fd_main);
pthread_mutex_unlock(&fs->fdlock);
return -1;
}
fs->fdlen++;
pthread_mutex_unlock(&fs->fdlock);
return 0;
}
int fd_list_write(struct shfs *fs, const char *name,
size_t offset, const void *buf, size_t len)
{
size_t i;
fprintf(stderr, "FD_LIST writing\\n");
pthread_mutex_lock(&fs->fdlock);
for (i = 0; i < fs->fdlen; i++) {
if (0 != strcmp(fs->fdlist[i].name, name))
continue;
if (fs->fdlist[i].offset != offset) {
fprintf(stderr, "FD_LIST Bad offset %d vs [%d]@'%s'\\n",
(int)offset, (int)fs->fdlist[i].offset, name);
continue;
}
if (fs->fdlist[i].length <= offset) {
fprintf(stderr, "FD_LIST offset %d/%d overflow '%s'\\n",
(int)offset, (int)fs->fdlist[i].length, name);
continue;
}
if (0 != fs->fdlist[i].fd_tmp)
fwrite(buf, 1, len, fs->fdlist[i].fd_tmp);
if (0 != fs->fdlist[i].fd_main)
fwrite(buf, 1, len, fs->fdlist[i].fd_main);
fprintf(stderr, "FD_LIST offset+len %d += %d '%s'\\n",
(int)offset, (int)len, name);
fs->fdlist[i].offset += len;
fs->fdlist[i].lastrecv = time(0);
pthread_mutex_unlock(&fs->fdlock);
return 0;
}
pthread_mutex_unlock(&fs->fdlock);
fprintf(stderr, "FD_LIST writing finish\\n");
return 0;
}
int fd_list_close(struct shfs *fs, const char *name)
{
size_t i;
fprintf(stderr, "FD_LIST closing '%s'\\n", name);
pthread_mutex_lock(&fs->fdlock);
for (i = 0; i < fs->fdlen; i++) {
if (0 != strcmp(fs->fdlist[i].name, name))
continue;
fprintf(stderr, "FD_LIST closed '%s' at %d/%d bytes\\n",
name,
(int)fs->fdlist[i].offset,
(int)fs->fdlist[i].length);
if (0 != fs->fdlist[i].fd_tmp)
fclose(fs->fdlist[i].fd_tmp);
if (0 != fs->fdlist[i].fd_main)
fclose(fs->fdlist[i].fd_main);
fs->fdlist[i].fd_tmp = 0;
fs->fdlist[i].fd_main = 0;
pthread_mutex_unlock(&fs->fdlock);
return 0;
}
pthread_mutex_unlock(&fs->fdlock);
return -1;
}
int fd_list_has(struct shfs *fs, const char *name)
{
size_t i;
pthread_mutex_lock(&fs->fdlock);
for (i = 0; i < fs->fdlen; i++) {
if (0 != strcmp(fs->fdlist[i].name, name))
continue;
pthread_mutex_unlock(&fs->fdlock);
return 1;
}
pthread_mutex_unlock(&fs->fdlock);
return 0;
}
int fd_list_remove(struct shfs *fs, const char *name)
{
size_t i;
size_t j;
fprintf(stderr, "FD_LIST removing '%s'\\n", name);
pthread_mutex_lock(&fs->fdlock);
for (i = j = 0; i < fs->fdlen; i++) {
if (0 != strcmp(fs->fdlist[i].name, name)) {
j++;
continue;
}
break;
}
if (i == fs->fdlen)
return -1;
for (j = i + 1; j < fs->fdlen; i++, j++)
memcpy(&fs->fdlist[i], &fs->fdlist[j], sizeof(fs->fdlist[i]));
fs->fdlen--;
pthread_mutex_unlock(&fs->fdlock);
return 0;
}
int fd_list_request_next_offset(struct shfs *fs, const char *name)
{
struct shfs_message m_alloc = {0};
struct shfs_message *m = &m_alloc;
size_t i;
pthread_mutex_lock(&fs->fdlock);
for (i = 0; i < fs->fdlen; i++) {
if (0 != strcmp(fs->fdlist[i].name, name))
continue;
fprintf(stderr, "FD_LIST next %d/%d '%s'\\n",
(int)fs->fdlist[i].offset,
(int)fs->fdlist[i].length,
fs->fdlist[i].name);
memset(m, 0, sizeof(*m));
m->id = fs->id;
m->key = fs->key;
m->opcode = MESSAGE_READ;
m->offset = (uint32_t)fs->fdlist[i].offset;
strcpy(m->name, fs->fdlist[i].name);
socket_sendto(fs->sock, m, sizeof(*m), fs->group_addr);
pthread_mutex_unlock(&fs->fdlock);
return 0;
}
pthread_mutex_unlock(&fs->fdlock);
return -1;
}
| 0
|
#include <pthread.h>
int w, h;
v2df zero = { 0.0, 0.0 };
v2df four = { 4.0, 4.0 };
v2df nzero;
double inverse_w;
double inverse_h;
char *whole_data;
int y_pick;
pthread_mutex_t y_mutex = PTHREAD_MUTEX_INITIALIZER;
static void * worker(void *_args) {
char *data;
double x, y;
int bit_num;
char byte_acc = 0;
for (;;) {
pthread_mutex_lock(&y_mutex);
y = y_pick;
y_pick++;
pthread_mutex_unlock(&y_mutex);
if (y >= h)
return 0;
data = &whole_data[(w >> 3) * (int)y];
for(bit_num=0,x=0;x<w;x+=2)
{
v2df Crv = { (x+1.0)*inverse_w-1.5, (x)*inverse_w-1.5 };
v2df Civ = { y*inverse_h-1.0, y*inverse_h-1.0 };
v2df Zrv = { 0.0, 0.0 };
v2df Ziv = { 0.0, 0.0 };
v2df Trv = { 0.0, 0.0 };
v2df Tiv = { 0.0, 0.0 };
int i = 0;
int mask;
do {
Ziv = (Zrv*Ziv) + (Zrv*Ziv) + Civ;
Zrv = Trv - Tiv + Crv;
Trv = Zrv * Zrv;
Tiv = Ziv * Ziv;
v2df delta = (v2df)__builtin_ia32_cmplepd( (Trv + Tiv), four );
mask = __builtin_ia32_movmskpd(delta);
} while (++i < 50 && (mask));
byte_acc <<= 2;
byte_acc |= mask;
bit_num+=2;
if(!(bit_num&7)) {
data[(bit_num>>3) - 1] = byte_acc;
byte_acc = 0;
}
}
if(bit_num&7) {
byte_acc <<= (8-w%8);
bit_num += 8;
data[bit_num>>3] = byte_acc;
byte_acc = 0;
}
}
}
int main (int argc, char **argv)
{
pthread_t ids[8];
int i;
nzero = -zero;
w = h = atoi(argv[1]);
inverse_w = 2.0 / w;
inverse_h = 2.0 / h;
y_pick = 0;
whole_data = malloc(w * (w >> 3));
for (i = 0; i < 8; i++)
pthread_create(&ids[i], 0, worker, 0);
for (i = 0; i < 8; i++)
pthread_join(ids[i], 0);
pthread_mutex_destroy(&y_mutex);
printf("P4\\n%d %d\\n",w,h);
fwrite(whole_data, h, w >> 3, stdout);
free(whole_data);
return 0;
}
| 1
|
#include <pthread.h>
struct handler_list {
void (*handler)(void);
struct handler_list * next;
};
static pthread_mutex_t pthread_atfork_lock = PTHREAD_MUTEX_INITIALIZER;
static struct handler_list * pthread_atfork_prepare = 0;
static struct handler_list * pthread_atfork_parent = 0;
static struct handler_list * pthread_atfork_child = 0;
static void pthread_insert_list(struct handler_list ** list,
void (*handler)(void),
struct handler_list * newlist,
int at_end)
{
if (handler == 0) return;
if (at_end) {
while(*list != 0) list = &((*list)->next);
}
newlist->handler = handler;
newlist->next = *list;
*list = newlist;
}
struct handler_list_block {
struct handler_list prepare, parent, child;
};
int pthread_atfork(void (*prepare)(void),
void (*parent)(void),
void (*child)(void))
{
struct handler_list_block * block =
(struct handler_list_block *) malloc(sizeof(struct handler_list_block));
if (block == 0) return ENOMEM;
pthread_mutex_lock(&pthread_atfork_lock);
pthread_insert_list(&pthread_atfork_prepare, prepare, &block->prepare, 0);
pthread_insert_list(&pthread_atfork_parent, parent, &block->parent, 1);
pthread_insert_list(&pthread_atfork_child, child, &block->child, 1);
pthread_mutex_unlock(&pthread_atfork_lock);
return 0;
}
static inline void pthread_call_handlers(struct handler_list * list)
{
for ( ; list != 0; list = list->next) (list->handler)();
}
extern int __fork(void);
int fork(void)
{
int pid;
struct handler_list * prepare, * child, * parent;
pthread_mutex_lock(&pthread_atfork_lock);
prepare = pthread_atfork_prepare;
child = pthread_atfork_child;
parent = pthread_atfork_parent;
pthread_mutex_unlock(&pthread_atfork_lock);
pthread_call_handlers(prepare);
pid = __fork();
if (pid == 0) {
__pthread_reset_main_thread();
__fresetlockfiles();
pthread_call_handlers(child);
} else {
pthread_call_handlers(parent);
}
return pid;
}
| 0
|
#include <pthread.h>
int q[5];
int qsiz;
pthread_mutex_t mq;
void queue_init ()
{
pthread_mutex_init (&mq, 0);
qsiz = 0;
}
void queue_insert (int x)
{
int done = 0;
printf ("prod: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz < 5)
{
done = 1;
q[qsiz] = x;
qsiz++;
}
pthread_mutex_unlock (&mq);
}
}
int queue_extract ()
{
int done = 0;
int x = -1, i = 0;
printf ("consumer: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz > 0)
{
done = 1;
x = q[0];
qsiz--;
for (i = 0; i < qsiz; i++) q[i] = q[i+1];
__VERIFIER_assert (qsiz < 5);
q[qsiz] = 0;
}
pthread_mutex_unlock (&mq);
}
return x;
}
void swap (int *t, int i, int j)
{
int aux;
aux = t[i];
t[i] = t[j];
t[j] = aux;
}
int findmaxidx (int *t, int count)
{
int i, mx;
mx = 0;
for (i = 1; i < count; i++)
{
if (t[i] > t[mx]) mx = i;
}
__VERIFIER_assert (mx >= 0);
__VERIFIER_assert (mx < count);
t[mx] = -t[mx];
return mx;
}
int source[8];
int sorted[8];
void producer ()
{
int i, idx;
for (i = 0; i < 8; i++)
{
idx = findmaxidx (source, 8);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 8);
queue_insert (idx);
}
}
void consumer ()
{
int i, idx;
for (i = 0; i < 8; i++)
{
idx = queue_extract ();
sorted[i] = idx;
printf ("m: i %d sorted = %d\\n", i, sorted[i]);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 8);
}
}
void *thread (void * arg)
{
(void) arg;
producer ();
return 0;
}
int main ()
{
pthread_t t;
int i;
__libc_init_poet ();
for (i = 0; i < 8; i++)
{
source[i] = __VERIFIER_nondet_int(0,20);
printf ("m: init i %d source = %d\\n", i, source[i]);
__VERIFIER_assert (source[i] >= 0);
}
queue_init ();
pthread_create (&t, 0, thread, 0);
consumer ();
pthread_join (t, 0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t *mutex;
int canHebras;
void *listarHebras (void *args){
int *i = (int *) args;
pthread_mutex_lock(&mutex[*i]);
printf("Soy una hebra y mi tid es: %d\\n",*i);
pthread_mutex_unlock(&mutex[*i+1]);
pthread_exit(0);
}
int main(int argc, char *argv[]){
int i;
canHebras = atoi(argv[1]);
pthread_t *arrThread = (pthread_t*)malloc(sizeof(pthread_t)*canHebras);
mutex = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t)*canHebras);
for(i=0;i<canHebras;i++){
pthread_mutex_init(&mutex[i],0);
pthread_mutex_lock(&mutex[i]);
}
pthread_mutex_unlock(&mutex[0]);
int *numeros = (int*)malloc(sizeof(int)*canHebras);
for(i=0;i<canHebras;i++){
numeros[i] = i;
}
for(i=0;i<canHebras;i++){
pthread_create(&arrThread[i],0,&listarHebras, &numeros[i]);
}
for(i=0;i<canHebras;i++){
pthread_join(arrThread[i],0);
}
return 0;
}
| 0
|
#include <pthread.h>
void sighandler(int signum);
void* countdown_thread(void *unused);
void* keyevents_thread(void *unused);
void thread_create_error(char* threadname);
void init_param(void);
int main();
int countdown;
int timeout;
int threads_active = 1;
int fd;
char* kbd_events_device;
pthread_t thread_countdown;
pthread_t thread_keyevents;
pthread_mutex_t mut;
void sighandler(int signum)
{
DEBUG_PRINT2("Received signal: %d\\n", signum);
threads_active = 0;
exit(0);
}
void* countdown_thread(void *unused)
{
do {
pthread_mutex_lock(&mut);
if (countdown > 0)
{
countdown--;
if (countdown == 0)
{
kbd_light_set(0);
}
}
pthread_mutex_unlock(&mut);
if (threads_active) sleep(1);
} while (threads_active);
pthread_exit(0);
}
void* keyevents_thread(void *unused)
{
ssize_t rd;
struct input_event ev;
fd = open(kbd_events_device, O_RDONLY);
if (fd == -1)
{
fprintf(stderr, "ERROR: Could not open %s as read-only device. You need to be root.\\n", kbd_events_device);
exit(1);
}
do {
rd = read(fd, &ev, sizeof(struct input_event));
if (!threads_active) break;
if (rd == -1)
{
fprintf(stderr, "ERROR: Reading error for device %s\\n", kbd_events_device);
exit(1);
}
DEBUG_PRINT2("Read something new from %s\\n", kbd_events_device);
pthread_mutex_lock(&mut);
if (countdown < 2)
{
kbd_light_set(1);
}
countdown = timeout;
pthread_mutex_unlock(&mut);
} while(threads_active);
close(fd);
pthread_exit(0);
}
void thread_create_error(char* threadname)
{
fprintf(stderr, "ERROR: thread %s could not be created and started!\\n", threadname);
exit(1);
}
void init_param(void)
{
char *s = 0;
s = getenv("KBD_BACKLIGHT_CTRL_TIMEOUT");
if (s != 0)
{
timeout = atoi(s);
}
else timeout = KBD_BACKLIGHT_TIMEOUT_DEFAULT;
if ((timeout < 2) || (timeout > 7200))
timeout = KBD_BACKLIGHT_TIMEOUT_DEFAULT;
DEBUG_PRINT2("Timeout set to %d\\n", timeout);
countdown = timeout;
s = 0;
s = getenv("KBD_BACKLIGHT_CTRL_INDEVICE");
if (s != 0)
{
kbd_events_device = s;
}
else kbd_events_device = KBD_EVENTS_DEVICE_DEFAULT;
if( access(kbd_events_device, R_OK) != -1 )
{
DEBUG_PRINT2("%s is readable\\n", kbd_events_device);
}
else
{
fprintf(stderr, "ERROR: %s is not readable!\\n", kbd_events_device);
exit(1);
}
}
int main()
{
int rc;
pthread_attr_t attr;
signal(SIGINT, sighandler);
signal(SIGTERM, sighandler);
init_param();
dbus_setup();
kbd_light_set(1);
pthread_mutex_init(&mut, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
DEBUG_PRINT1("Creating threads\\n");
rc = pthread_create(&thread_countdown, &attr, &countdown_thread, 0);
if (rc) thread_create_error("thread_countdown");
rc = pthread_create(&thread_keyevents, &attr, &keyevents_thread, 0);
if (rc) thread_create_error("thread_keyevents");
pthread_join(thread_countdown, 0);
DEBUG_PRINT1("Joined thread_countdown\\n");
pthread_join(thread_keyevents, 0);
DEBUG_PRINT1("Joined thread_keyevents\\n");
close(fd);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&mut);
DEBUG_PRINT1("End program\\n");
return 0;
}
| 1
|
#include <pthread.h>
int mulFactor;
pthread_mutex_t lock;
pthread_cond_t lockCond;
void *PrintMulTable()
{
pthread_mutex_lock(&lock);
while(mulFactor==0)
pthread_cond_wait(&lockCond,&lock);
int i;
for(i=0; i<11;i++){
printf("%d",i*mulFactor);
}
printf("\\n");
pthread_mutex_unlock(&lock);
}
void *FetMulFac()
{
pthread_mutex_lock(&lock);
int i;
printf("please enter multiplication Factor \\n");
int enteredVal;
scanf("%d", &enteredVal);
printf("enterd multiplication Factor is %d \\n",enteredVal);
mulFactor=enteredVal;
pthread_cond_signal(&lockCond);
pthread_mutex_unlock(&lock);
}
int main (int argc, char *argv[])
{
pthread_t threads[2];
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("\\n mutex init failed\\n");
return 1;
}
if (pthread_cond_init(&lockCond, 0) != 0)
{
printf("\\n conditional variable init failed\\n");
return 1;
}
pthread_create(&threads[0], 0, PrintMulTable, 0);
pthread_create(&threads[1], 0, FetMulFac, 0);
pthread_join(threads[0], 0);
pthread_join(threads[1], 0);
printf ("Multiplication Table Printed \\n");
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
void tdb_init
(FILE* logger, int* argc, char** argv)
{
td = malloc(sizeof(*td));
if (td == 0) {
(void)fputs("\\n[EE] Not enough memory to start\\n", stderr);
pthread_exit(0);
}
pthread_mutex_init(&td->logger_lock, 0);
td->logger = logger;
if (td->logger == 0) {
td->logger = stderr;
}
td->argc = argc;
td->argv = argv;
}
void tdb_exit
(void)
{
tdb_die_if(td == 0, "exiting without initing first");
free(td), td=0;
pthread_exit(0);
}
size_t tdb_getcpucount
(void)
{
long ret;
ret = sysconf(_SC_NPROCESSORS_CONF);
if (ret == -1) {
tdb_debug("Failed to guess processor count: %s", strerror(errno));
ret = 1;
} else {
tdb_debug("Autoselected workers count (linux): %i", ret);
}
return (size_t)ret;
}
size_t tdb_interval_set_min
(struct tdb_interval* interval, size_t val)
{
if (val<=interval->max) {
interval->min=val;
}
return interval->min;
}
size_t tdb_interval_set_max
(struct tdb_interval* interval, size_t val)
{
if (val>=interval->min) {
interval->max=val;
}
return interval->max;
}
float tdb_rand
(void)
{
return rand()/(32767 +1.0l);
}
size_t tdb_interval_rand
(const struct tdb_interval* interval)
{
return interval->min+(size_t)((interval->max-interval->min)*(rand()/(32767 +1.0l)));
}
int* tdb_get_argc
(void)
{
return td->argc;
}
char** tdb_get_argv
(void)
{
return td->argv;
}
void tdb_fprintf(FILE *stream, const char* format, ...)
{
int ret;
va_list args, backup_args;
__builtin_va_start((args));
va_copy(backup_args, args);
ret = vfprintf(stream, format, args);
if ((ret < 0) && (stream!=stderr)) {
(void)fputs("[EE] Can't write to standard logger", stderr);
(void)vfprintf(stderr, format, backup_args);
}
;
;
}
int tdb_vfprintf(FILE *stream, const char* format, va_list args)
{
int ret;
va_list backup_args;
va_copy(backup_args, args);
ret = vfprintf(stream, format, args);
if ((ret < 0) && (stream!=stderr)) {
(void)fputs("[EE] Can't write to standard logger", stderr);
(void)vfprintf(stderr, format, backup_args);
}
;
return ret;
}
void tdb_die
(const char* msg, int lineno, const char* filename)
{
pthread_mutex_lock(&td->logger_lock);
tdb_fprintf(td->logger, "[EE] %s:%i: %s\\n", filename, lineno, msg);
pthread_mutex_unlock(&td->logger_lock);
exit(1);
}
void tdb_warn
(const char* msg)
{
int check;
pthread_mutex_lock(&td->logger_lock);
tdb_fprintf(td->logger, "[WW] %s\\n", msg);
pthread_mutex_unlock(&td->logger_lock);
}
void tdb_debug
(const char* msg, ...)
{
va_list args;
__builtin_va_start((args));
pthread_mutex_lock(&td->logger_lock);
tdb_fprintf(td->logger,"[DD] ");
tdb_vfprintf(td->logger, msg, args);
tdb_fprintf(td->logger,"\\n");
;
pthread_mutex_unlock(&td->logger_lock);
}
void* tdb_malloc
(size_t size)
{
void* ptr;
ptr = malloc(size);
tdb_die_if(ptr == 0, "Not nough memory");
return ptr;
}
void* tdb_calloc
(size_t nmemb, size_t size)
{
void* ptr;
ptr = calloc(nmemb, size);
tdb_die_if(ptr == 0, "Not enough memory");
return ptr;
}
void* tdb_realloc
(void* ptr, size_t size)
{
ptr = realloc(ptr, size);
tdb_die_if(ptr == 0, "Not enough memory");
return ptr;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condizione = PTHREAD_COND_INITIALIZER;
int n=0;
int glob=0;
int i=0;
int j=0;
int **matrice=0;
int numT=0;
int flag=0;
void *funzione(void *param){
int indice =*(int*)param;
for (int j = 0; j < 5; j++)
{
pthread_mutex_lock(&mutex);
matrice[indice][j]=glob;
numT --;
pthread_mutex_unlock(&mutex);
}
printf("thread id %d\\n",(int)pthread_self());
if (numT<=0)
{
pthread_mutex_lock(&mutex);
pthread_cond_signal(&condizione);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void *funzione2(void *param){
pthread_mutex_lock(&mutex);
while(numT>0){
pthread_cond_wait(&condizione,&mutex);
}
pthread_mutex_unlock(&mutex);
flag=1;
for (int i = 0; i < 5; i++)
{
for (int j=0;j<5;j++){
printf("%d \\t",matrice[i][j] );
}
printf("\\n");
}
pthread_exit(0);
}
void *funzione3(void *param){
while(flag==0){
pthread_mutex_lock(&mutex);
glob=1+rand()%100;
pthread_mutex_unlock(&mutex);
sleep(3);
}
pthread_exit(0);
}
int main(int argc, char const *argv[])
{
if (argc <2)
{
perror("Errore argonento");
exit(0);
}
n=atoi(argv[1]);
pthread_t threads[n];
numT=n;
pthread_create(&threads[n-1],0,funzione3,0);
matrice = (int**)malloc(sizeof(int*)*5);
for(i=0;i<5;i++){
matrice[i]=(int*)malloc(sizeof(int)*5);
for(j=0;j<5;j++){
matrice[i][j]=0;
}
}
for (i=0;i<n-1;i++){
int *indice=malloc(sizeof(int));
*indice=i;
pthread_create(&threads[i],0,funzione,indice);
}
pthread_create(&threads[n],0,funzione2,0);
for (i=0;i<=n;i++){
pthread_join(threads[i],0);
}
return 0;
}
| 0
|
#include <pthread.h>
void* pthTextCode_run(void *arg){
int sock_fd;
int flag;
int ret;
int option;
int *retval;
int low = 1e5;
int high = 1e6;
int rand_number;
char *buff;
struct sockaddr_in udpaddr;
struct sockaddr_in client;
retval = 0;
buff = 0;
sock_fd = socket(AF_INET,SOCK_DGRAM,0);
if(sock_fd < 0){
pthPrint();
perror("sock_fd create failed: ");
exit(1);
}
flag = fcntl(sock_fd,F_GETFL);
ret = setsockopt(sock_fd,SOL_SOCKET,SO_REUSEADDR,&option,sizeof(option));
if(ret < 0){
pthPrint();
perror("sock_fd setsockopt failed: ");
exit(1);
}
memset(&udpaddr,0,sizeof(struct sockaddr_in));
udpaddr.sin_family = AF_INET;
udpaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
udpaddr.sin_port = htons(2000);
if(bind(sock_fd,(struct sockaddr*)&udpaddr,sizeof(struct sockaddr_in)) < 0){
close(sock_fd);
pthPrint();
perror("pthTextCode_run bind failed: ");
exit(1);
}
buff = (char *)malloc(50);
if(buff == 0){
pthPrint();
fprintf(stderr,"malloc failed, line: %d\\n",67);
close(sock_fd);
exit(1);
}
while(1){
int client_len;
client_len = sizeof(client);
memset(buff,0,50);
ret = recvfrom(sock_fd,buff,50,0,(struct sockaddr*)&client,&client_len);
pthread_mutex_lock(&mutex_output);
pthPrint();
printf("ret: %d, recv buff: %s\\n",ret,buff);
pthread_mutex_unlock(&mutex_output);
if(ret > 0){
if(strcmp(buff,"encrypt") == 0) {
rand_number = my_random(low,high);
resolve(rand_number);
char prime_created_msg[] = "prime numbers created!";
short prime_msg_len = strlen(prime_created_msg);
if(sendto(sock_fd,prime_created_msg,prime_msg_len,0,(struct sockaddr*)&client,client_len) < prime_msg_len){
pthPrint();
perror("\\"prime numbers created!\\" send to main failed: ");
}
else {
pthread_mutex_lock(&mutex_output);
pthPrint();
fprintf(stdout,"pthTextCode -> main \\"prime numbers created\\" ok.\\n");
pthread_mutex_unlock(&mutex_output);
break;
}
}
else if(strcmp(buff,"decrypt") == 0){
break;
}
else {
pthPrint();
fprintf(stderr,"command neither \\"encrypt\\" nor \\"decrypt\\" received.\\n");
exit(-1);
}
}
}
close(sock_fd);
free(buff);
buff = 0;
retval = (int *)malloc(sizeof(int));
*retval = 1;
pthread_exit((void *)retval);
}
void resolve(int number){
int i;
int goal_number;
get_prime();
prime_stack_cnt = 0;
goal_number = number;
for (i=0; i<prime_cnt; i++){
while(goal_number%prime_number[i] == 0){
prime_stack[prime_stack_cnt++] = prime_number[i];
goal_number /= prime_number[i];
}
}
}
int my_random(int low_boundary,int high_boundary){
srand(time(0));
return (int)((double)rand()/32767*(high_boundary-low_boundary)+0.5) + low_boundary;
}
static void pthPrint(){
printf("\\033[1;33m[textCodeThread]\\033[0m ");
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t empty = PTHREAD_COND_INITIALIZER;
pthread_cond_t fill = PTHREAD_COND_INITIALIZER;
int pos = 0;
int black_list[4];
int buffer[120];
int qtd_hackers=4, blocked=0;
int hackwin = 0;
void *producer(void *id){
while(1){
pthread_mutex_lock(&mutex);
if(pos>=100){
hackwin = 1;
break;
}
if( black_list[ (int)id ] >= 10){
blocked++;
pthread_cond_broadcast(&fill);
break;
}
buffer[pos] = (int) id;
pos++;
if(pos == 1) pthread_cond_broadcast(&fill);
pthread_mutex_unlock(&mutex);
}
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void *consumer(void *id){
while(1){
pthread_mutex_lock(&mutex);
while(pos <= 0){
if(blocked==qtd_hackers || hackwin) {
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
pthread_cond_wait(&fill, &mutex);
}
if(hackwin){
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
if(pos>0){
pos--;
black_list[ buffer[pos] ]++;
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void teste(void* id){
int i;
printf("executei");
pthread_exit(0);
}
int main(){
pthread_t hacker[4], consumidor0, consumidor1;
int i,j ;
int VITORIAS_HACK=0, VITORIAS_SERVER=0;
int TOTAL_HACK=0, TOTAL_SERVER =0;
for(qtd_hackers=1; qtd_hackers<=4; qtd_hackers++){
for(j=0; j<400; j++){
pthread_create(&consumidor0, 0, consumer,(void *) 0);
pthread_create(&consumidor1, 0, consumer,(void *) 1);
for(i=0; i<qtd_hackers; i++) {
pthread_create(&hacker[i], 0, producer, (void *) i);
}
pthread_join(consumidor0, 0);
pthread_join(consumidor1, 0);
for(i=0; i<qtd_hackers; i++) {
pthread_join(hacker[i], 0);
}
if(hackwin==1) VITORIAS_HACK++;
else VITORIAS_SERVER++;
pos = 0;
memset(black_list,0,4);
blocked=0;
hackwin = 0;
}
printf("O servidor venceu %.2f%% das batalhas contra %d computadores de hackers.\\n",
(float) VITORIAS_SERVER*100/(VITORIAS_HACK+VITORIAS_SERVER), qtd_hackers);
TOTAL_HACK += VITORIAS_HACK;
TOTAL_SERVER += VITORIAS_SERVER;
VITORIAS_HACK = 0;
VITORIAS_SERVER = 0;
}
printf("No total o servidor venceu %.2f%% das batalhas\\n", (float) TOTAL_SERVER*100/(TOTAL_HACK+TOTAL_SERVER) );
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mymutex_px;
pthread_mutex_t mymutex_py;
float * px = 0;
float * py = 0;
static void * affiche_max_fois_valeur_px (void * p_data)
{
int max = (int) p_data;
int i;
for (i = 0; i < max; i++) {
pthread_mutex_lock(&mymutex_px);
printf("[thread1] %f\\n", *px);
pthread_mutex_unlock(&mymutex_px);
sleep(1);
}
char *resultChild = malloc(20);
strcpy(resultChild, "statusFinChild");
pthread_exit(resultChild);
return 0;
}
static void * affiche_max_fois_valeur_py (void * p_data)
{
int max = (int) p_data;
int i;
for (i = 0; i < max; i++) {
pthread_mutex_lock(&mymutex_py);
printf("[thread2] %f\\n", *py);
pthread_mutex_unlock(&mymutex_py);
sleep(1);
}
char *resultChild = malloc(20);
strcpy(resultChild, "statusFinChild");
pthread_exit(resultChild);
return 0;
}
static void * affiche_max_fois_valeur_px_py (void * p_data)
{
int max = (int) p_data;
int i;
for (i = 0; i < max; i++) {
int allMutexOk = 0;
while (allMutexOk == 0) {
pthread_mutex_lock(&mymutex_px);
if (pthread_mutex_trylock(&mymutex_py) == 0) {
allMutexOk = 1;
}
else {
pthread_mutex_unlock(&mymutex_px);
}
}
printf("[thread3] %f %f\\n", *px, *py);
pthread_mutex_unlock(&mymutex_px);
pthread_mutex_unlock(&mymutex_py);
sleep(1);
}
char *resultChild = malloc(20);
strcpy(resultChild, "statusFinChild");
pthread_exit(resultChild);
return 0;
}
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("erreur de parametres\\n");
return -1;
}
int max = atoi(argv[1]);
pthread_mutex_init(&mymutex_px, 0);
pthread_mutex_init(&mymutex_py, 0);
float x = 1;
float y = 2;
px = &x;
py = &y;
pthread_t myThread1;
int ret = pthread_create (
& myThread1, 0,
affiche_max_fois_valeur_px, (void *) max
);
pthread_t myThread2;
ret = pthread_create (
& myThread2, 0,
affiche_max_fois_valeur_py, (void *) max
);
pthread_t myThread3;
ret = pthread_create (
& myThread3, 0,
affiche_max_fois_valeur_px_py, (void *) max
);
int i;
for (i = 0; i < max; i++) {
pthread_mutex_lock(&mymutex_px);
px = 0;
printf("[main] %i\\n", i);
px = &x;
pthread_mutex_unlock(&mymutex_px);
}
printf("termine\\n");
pthread_exit(0);
pthread_mutex_destroy(&mymutex_px);
pthread_mutex_destroy(&mymutex_py);
return(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
void* thread_worker(void*);
void critical_section(int thread_num, int i);
int main(void)
{
int rtn, i;
pthread_t pthread_id = 0;
rtn = pthread_create(&pthread_id,0, thread_worker, 0 );
if(rtn != 0)
{
printf("pthread_create ERROR!\\n");
return -1;
}
for (i=0; i<10000; i++)
{
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2);
critical_section(1, i);
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
}
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
return 0;
}
void* thread_worker(void* p)
{
int i;
for (i=0; i<10000; i++)
{
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2);
critical_section(2, i);
pthread_mutex_unlock(&mutex1);
pthread_mutex_unlock(&mutex2);
}
}
void critical_section(int thread_num, int i)
{
printf("Thread%d: %d\\n", thread_num,i);
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.