text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
char task_id;
int call_num;
int ci;
int ti;
int ci_left;
int ti_left;
int flag;
int arg;
pthread_t th;
}task;
void proc(int* args);
void * idle();
int select_proc();
int task_num=0;
int idle_num=0;
int alg;
int curr_proc=-1;
int demo_time=100;
task* tasks;
pthread_mutex_t proc_wait[100];
pthread_mutex_t main_wait,idle_wait;
float sum=0;
pthread_t idle_proc;
int main(int argc,char** argv)
{
pthread_mutex_init(&main_wait,0);
pthread_mutex_lock(&main_wait);
pthread_mutex_init(&idle_wait,0);
pthread_mutex_lock(&idle_wait);
printf("Please input number of real time tasks:\\n");
scanf("%d",&task_num);
tasks=(task*)malloc(task_num*sizeof(task));
int i;
for(i=0;i<task_num;i++)
{
pthread_mutex_init(&proc_wait[i],0);
pthread_mutex_lock(&proc_wait[i]);
}
for(i=0;i<task_num;i++)
{
printf("Please input task id,followed by Ciand Ti:\\n");
getchar();
scanf("%c,%d,%d,",&tasks[i].task_id,&tasks[i].ci,&tasks[i].ti);
tasks[i].ci_left=tasks[i].ci;
tasks[i].ti_left=tasks[i].ti;
tasks[i].flag=2;
tasks[i].arg=i;
tasks[i].call_num=1;
sum=sum+(float)tasks[i].ci/(float)tasks[i].ti;
}
printf("Please input algorithm,1 for EDF,2 for RMS:");
getchar();
scanf("%d",&alg);
printf("Please inpt demo time:");
scanf("%d",&demo_time);
double r=1;
if(alg==2)
{
r=((double)task_num)*(exp(log(2)/(double)task_num)-1);
printf("r is %lf\\n",r);
}
if(sum>r)
{
printf("(sum=%lf>r=%lf),not schedulable! \\n",sum,r);
exit(2);
}
pthread_create(&idle_proc,0,(void*)idle,0);
for(i=0;i<task_num;i++)
pthread_create(&tasks[i].th,0,(void*)proc,&tasks[i].arg);
for(i=0;i<demo_time;i++)
{
int j;
if((curr_proc=select_proc(alg))!=-1)
{
pthread_mutex_unlock(&proc_wait[curr_proc]);
pthread_mutex_lock(&main_wait);
}
else
{
pthread_mutex_unlock(&idle_wait);
pthread_mutex_lock(&main_wait);
}
for(j=0;j<task_num;j++)
{
if(--tasks[j].ti_left==0)
{
tasks[j].ti_left=tasks[j].ti;
tasks[j].ci_left=tasks[j].ci;
pthread_create(&tasks[j].th,0,(void*)proc,&tasks[j].arg);
tasks[j].flag=2;
}
}
}
printf("\\n");
sleep(10);
};
void proc(int * args)
{
while(tasks[*args].ci_left>0)
{
pthread_mutex_lock(&proc_wait[* args]);
if(idle_num!=0)
{
printf("idle(%d)",idle_num);
idle_num=0;
}
printf("%c%d",tasks[*args].task_id,tasks[*args].call_num);
tasks[*args].ci_left--;
if(tasks[*args].ci_left==0)
{
printf("(%d)",tasks[*args].ci);
tasks[*args].flag=0;
tasks[*args].call_num++;
}
pthread_mutex_unlock(&main_wait);
}
};
void* idle()
{
while(1)
{
pthread_mutex_lock(&idle_wait);
printf("->");
idle_num++;
pthread_mutex_unlock(&main_wait);
}
};
int select_proc(int alg)
{
int j;
int temp1,temp2;
temp1=10000;
temp2=-1;
if((alg==2)&&(curr_proc!=-1)&&(tasks[curr_proc].flag!=0))
return curr_proc;
for(j=0;j<task_num;j++)
{
if(tasks[j].flag==2)
{
switch(alg)
{
case 1:
if(temp1>tasks[j].ti_left)
{
temp1=tasks[j].ti_left;
temp2=j;
}
break;
case 2:
if(temp1>tasks[j].ti)
{
temp1=tasks[j].ti;
temp2=j;
}
break;
}
}
}
return temp2;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
void* thr_func1(void* arg) {
printf("1: In thread function 1\\n1: Getting lock1...\\n");
pthread_mutex_lock(&lock1);
printf("1: Get lock1\\n1: Getting lock2...\\n");
pthread_mutex_lock(&lock2);
printf("1: Get lock2\\n1: Doing some task...\\n1: Releasing lock2...\\n");
pthread_mutex_unlock(&lock2);
printf("1: Lock2 released!\\n1: Releasing lock1...\\n");
pthread_mutex_unlock(&lock1);
printf("1: Done!\\n");
}
void* thr_func2(void* arg) {
printf("2: In thread function 2\\n2: Getting lock2...\\n");
pthread_mutex_lock(&lock2);
printf("2: Get lock2\\n2: Getting lock1...\\n");
pthread_mutex_lock(&lock1);
printf("2: Get lock2\\n2: Doing some task...\\n2: Releasing lock1...\\n");
pthread_mutex_unlock(&lock1);
printf("2: Lock1 released!\\n2: Releasing lock2...\\n");
pthread_mutex_unlock(&lock2);
printf("2: Done!\\n");
}
int main(int argc, char** argv) {
int err;
pthread_t tid1, tid2;
void *rtval;
err = pthread_create(&tid1, 0, thr_func1, 0);
if(err != 0) {
exit(-1);
}
err = pthread_create(&tid2, 0, thr_func2, 0);
if(err != 0) {
exit(-1);
}
err = pthread_join(tid1, &rtval);
if (err != 0) {
exit(-1);
}
err = pthread_join(tid2, &rtval);
if (err != 0) {
exit(-1);
}
pthread_mutex_destroy(&lock1);
pthread_mutex_destroy(&lock2);
exit(0);
}
| 0
|
#include <pthread.h>
char *files[5] = { "./Files/1", "./Files/2", "./Files/3", "./Files/4", "./Files/5"};
void *threadReader(void *arg)
{
struct Info *info = (struct Info *)arg;
void (*lib_function)(int, char *);
*(void **) (&lib_function) = dlsym(info->library, "readFromFile");
for(int i = 0; i < 5; i++)
{
while(info->flag);
pthread_mutex_lock(&info->mutex);
int fd = open(info->fileNames[i], O_RDONLY);
if(fd < 0)
{
printf("File not found");
exit(-1);
}
(*lib_function)(fd, info->buffer);
close(fd);
pthread_mutex_unlock(&info->mutex);
info->size++;
info->flag = 1;
usleep(1);
}
info->threadsNumber--;
return 0;
}
void *threadWriter(void *arg)
{
struct Info *info = (struct Info *)arg;
void (*lib_function)(int, char *);
*(void **) (&lib_function) = dlsym(info->library, "writeToFile");
pthread_mutex_lock(&info->mutex);
int fd = open("./Files/All", O_WRONLY | O_CREAT | O_TRUNC | O_APPEND);
pthread_mutex_unlock(&info->mutex);
usleep(1);
while(!info->flag);
for(int i = 0; i < 5; i++)
{
while(!info->flag);
pthread_mutex_lock(&info->mutex);
(*lib_function)(fd, info->buffer);
pthread_mutex_unlock(&info->mutex);
info->flag = 0;
usleep(1);
}
close(fd);
info->threadsNumber--;
return 0;
}
void initInfo(struct Info *info)
{
info->fileNames = files;
info->size = 0;
info->library = dlopen("./lib_lin.so", RTLD_LAZY);
info->threadsNumber = 0;
info->flag = 0;
}
void createMutex(struct Info *info)
{
pthread_mutex_init(&info->mutex, 0);
}
void runThreads(struct Info *info)
{
pthread_create(&info->readThread, 0, &threadReader, info);
info->threadsNumber++;
pthread_create(&info->writeThread, 0, &threadWriter, info);
info->threadsNumber++;
}
void waitThreads(struct Info *info)
{
while(info->threadsNumber);
printf("All good!\\n");
dlclose(info->library);
}
| 1
|
#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;
void* worker (void) {
pthread_mutex_lock(&mutex_workers);
n++;
pthread_mutex_unlock(&mutex_workers);
char* name = "SVC " + (n + 49);
int worker_minerals = 0;
printf("SCV good to go, sir.");
while (m < 20) {
printf("%s", name, " is mining");
pthread_mutex_lock(&mutex_map_minerals);
map_minerals -= 8;
pthread_mutex_unlock(&mutex_map_minerals);
worker_minerals += 8;
while (worker_minerals > 0) {
}
printf("%s", name, " is transporting minerals");
}
}
void* solder (void) {
}
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_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;
}
| 0
|
#include <pthread.h>
int fumando[3];
int recursos[3];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* administrar(void*);
void* fumador(void*);
int main() {
int i;
for (i = 0; i < 3; ++i) {
fumando[i] = 0;
recursos[i] = 0;
}
srand((int) time(0));
pthread_t agente;
pthread_create(&agente, 0, administrar, 0);
pthread_t fumadores[3];
for (i = 0; i < 3; ++i)
pthread_create(&fumadores[i], 0, fumador, (void*) (intptr_t) i);
for (i = 0; i < 3; ++i)
pthread_join(fumadores[i], 0);
pthread_join(agente, 0);
return 0;
}
void* administrar(void* p) {
int i, ocupado = 1;
while (1) {
for (i = 0; i < 3; ++i) {
pthread_mutex_lock(&mutex);
if (!fumando[i]) {
pthread_mutex_unlock(&mutex);
ocupado = 0;
sleep(15);
pthread_mutex_lock(&mutex);
recursos[i] = 1;
if (i == 0)
printf("Papel en la mesa\\n");
else if (i == 1)
printf("Tabaco en la mesa\\n");
else
printf("Cerillos en la mesa\\n");
}
pthread_mutex_unlock(&mutex);
}
if (ocupado) {
printf("El agente se va a hacer otras actividades\\n");
sleep(10);
}
}
}
void* fumador(void* p) {
int id = (intptr_t) p;
while (1) {
pthread_mutex_lock(&mutex);
if (recursos[0] && recursos[1] && recursos[2]) {
recursos[0] = recursos[1] = recursos[2] = 0;
fumando[id] = 1;
printf("Fumador %d fumando\\n", id);
pthread_mutex_unlock(&mutex);
sleep(10);
printf("Fumador %d acabó de fumar\\n", id);
pthread_mutex_lock(&mutex);
fumando[id] = 0;
pthread_mutex_unlock(&mutex);
sleep(20);
}
else
pthread_mutex_unlock(&mutex);
}
}
| 1
|
#include <pthread.h>
int thread_count;
double a, b, h;
int n, local_n;
double total;
pthread_mutex_t mutex;
double timeval_diff(struct timeval *a, struct timeval *b)
{
return (double)(a->tv_sec + (double)a->tv_usec/1000000) - (double)(b->tv_sec + (double)b->tv_usec/1000000);
}
double Trap(double local_a, double local_b, int local_n, double h)
{
double integral;
double x;
int i;
integral = ((local_a*local_a) + (local_b*local_b))/2.0;
x = local_a;
for (i = 1; i <= local_n-1; i++)
{
x = local_a + i*h;
integral += (x*x);
}
integral = integral*h;
return integral;
}
void *Thread_work(void* rank)
{
double local_a;
double local_b;
double my_int;
long my_rank = (long) rank;
local_a = a + my_rank*local_n*h;
local_b = local_a + local_n*h;
my_int = Trap(local_a, local_b, local_n, h);
pthread_mutex_lock(&mutex);
total += my_int;
pthread_mutex_unlock(&mutex);
return 0;
}
int main(int argc, char** argv) {
long i;
pthread_t* thread_handles;
total = 0.0;
if (argc != 2)
{
fprintf(stderr, "usage: %s <number of threads>\\n", argv[0]);
exit(0);
}
thread_count = strtol(argv[1], 0, 10);
printf("Enter a, b, n\\n");
scanf("%lf %lf %d", &a, &b, &n);
h = (b-a)/n;
local_n = n/thread_count;
thread_handles = malloc (thread_count*sizeof(pthread_t));
if (pthread_mutex_init(&mutex, 0) != 0)
{
printf("\\n mutex init failed\\n");
return 1;
}
struct timeval t_ini, t_fin;
double secs;
gettimeofday(&t_ini, 0);
for (i = 0; i < thread_count; i++)
{
pthread_create(&thread_handles[i], 0, Thread_work, (void*) i);
}
for (i = 0; i < thread_count; i++)
{
pthread_join(thread_handles[i], 0);
}
gettimeofday(&t_fin, 0);
secs = timeval_diff(&t_fin, &t_ini);
printf("%.16g milliseconds\\n", secs * 1000.0);
printf("With n = %d trapezoids, our estimate\\n",n);
printf("of the integral from %f to %f = %19.15e\\n",a, b, total);
pthread_mutex_destroy(&mutex);
free(thread_handles);
return 0;
}
| 0
|
#include <pthread.h>
int val;
struct cell *next;
pthread_mutex_t mutex;
} cell;
cell sentinel = {100, 0, PTHREAD_MUTEX_INITIALIZER};
cell dummy = {-1, &sentinel, PTHREAD_MUTEX_INITIALIZER};
cell *global = &dummy;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void toggle(cell *lst, int r) {
cell *prev = lst;
pthread_mutex_lock(&prev->mutex);
cell *this = prev->next;
pthread_mutex_lock(&this->mutex);
cell *removed = 0;
while (this->val < r) {
pthread_mutex_unlock(&prev->mutex);
prev = this;
this = this->next;
pthread_mutex_lock(&this->mutex);
}
if (this->val == r) {
prev->next = this->next;
removed = this;
} else {
cell *new = malloc(sizeof(cell));
new->val = r;
new->next = this;
pthread_mutex_init(&new->mutex, 0);
prev->next = new;
new = 0;
}
pthread_mutex_unlock(&prev->mutex);
pthread_mutex_unlock(&this->mutex);
if (removed != 0) free(removed);
return;
}
void *bench(void *arg) {
int inc = ((args*)arg)->inc;
int id = ((args*)arg)->id;
cell *lstp = ((args*)arg)->list;
for(int i = 0; i < inc; i++) {
int r = rand() % 100;
toggle(lstp, r);
}
}
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("usage: list <total> <threads>\\n");
exit(0);
}
int n = atoi(argv[2]);
int inc = (atoi(argv[1]) / n);
printf("%d threads doing %d operations each\\n", n, inc);
pthread_mutex_init(&mutex, 0);
args *thra = malloc(n * sizeof(args));
for(int i = 0; i < n; i++) {
thra[i].inc = inc;
thra[i].id = i;
thra[i].list = global;
}
pthread_t *thrt = malloc(n * sizeof(pthread_t));
struct timespec t_start, t_stop;
clock_gettime(CLOCK_MONOTONIC_COARSE, &t_start);
for(int i = 0; i < n; i++) {
pthread_create(&thrt[i], 0, bench, &thra[i]);
}
for(int i = 0; i < n; i++) {
pthread_join(thrt[i], 0);
}
clock_gettime(CLOCK_MONOTONIC_COARSE, &t_stop);
long wall_sec = t_stop.tv_sec - t_start.tv_sec;
long wall_nsec = t_stop.tv_nsec - t_start.tv_nsec ;
long wall_msec = (wall_sec * 1000) + (wall_nsec / 100000);
printf("done in %ld ms\\n", wall_msec);
return 0;
}
| 1
|
#include <pthread.h>
static char buffer[2048];
static unsigned int buffer_count=0;
static int debug_nmea;
static int sock;
static struct addrinfo* addr=0;
static pthread_mutex_t message_mutex;
static int initSocket(const char *host, const char *portname);
struct ais_message {
char *buffer;
struct ais_message *next;
} *ais_messages_head, *ais_messages_tail, *last_message;
static void append_message(const char *buffer)
{
struct ais_message *m = malloc(sizeof *m);
m->buffer = strdup(buffer);
m->next = 0;
pthread_mutex_lock(&message_mutex);
if(!ais_messages_head)
ais_messages_head = m;
else
ais_messages_tail->next = m;
ais_messages_tail = m;
pthread_mutex_unlock(&message_mutex);
}
static void free_message(struct ais_message *m)
{
if(m) {
free(m->buffer);
free(m);
}
}
const char *aisdecoder_next_message()
{
free_message(last_message);
last_message = 0;
pthread_mutex_lock(&message_mutex);
if(!ais_messages_head) {
pthread_mutex_unlock(&message_mutex);
return 0;
}
last_message = ais_messages_head;
ais_messages_head = ais_messages_head->next;
pthread_mutex_unlock(&message_mutex);
return last_message->buffer;
}
void sound_level_changed(float level, int channel, unsigned char high) {
if (high != 0)
fprintf(stderr, "Level on ch %d too high: %.0f %%\\n", channel, level);
else
fprintf(stderr, "Level on ch %d: %.0f %%\\n", channel, level);
}
void nmea_sentence_received(const char *sentence,
unsigned int length,
unsigned char sentences,
unsigned char sentencenum) {
append_message(sentence);
if (sentences == 1) {
if (sock && sendto(sock, sentence, length, 0, addr->ai_addr, addr->ai_addrlen) == -1) abort();
if (debug_nmea) fprintf(stderr, "%s", sentence);
} else {
if (buffer_count + length < 2048) {
memcpy(&buffer[buffer_count], sentence, length);
buffer_count += length;
} else {
buffer_count=0;
}
if (sentences == sentencenum && buffer_count > 0) {
if (sock && sendto(sock, buffer, buffer_count, 0, addr->ai_addr, addr->ai_addrlen) == -1) abort();
if (debug_nmea) fprintf(stderr, "%s", buffer);
buffer_count=0;
};
}
}
int init_ais_decoder(char * host, char * port ,int show_levels,int _debug_nmea,int buf_len,int time_print_stats){
debug_nmea=_debug_nmea;
pthread_mutex_init(&message_mutex, 0);
if(debug_nmea)
fprintf(stderr,"Log NMEA sentences to console ON\\n");
else
fprintf(stderr,"Log NMEA sentences to console OFF\\n");
if (host && port && !initSocket(host, port)) {
return 1;
}
if (show_levels) on_sound_level_changed=sound_level_changed;
on_nmea_sentence_received=nmea_sentence_received;
initSoundDecoder(buf_len,time_print_stats);
return 0;
}
void run_rtlais_decoder(short * buff, int len)
{
run_mem_decoder(buff,len,2048);
}
int free_ais_decoder(void)
{
pthread_mutex_destroy(&message_mutex);
free_message(last_message);
last_message = 0;
while(ais_messages_head) {
struct ais_message *m = ais_messages_head;
ais_messages_head = ais_messages_head->next;
free_message(m);
}
freeSoundDecoder();
freeaddrinfo(addr);
return 0;
}
int initSocket(const char *host, const char *portname) {
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family=AF_UNSPEC;
hints.ai_socktype=SOCK_DGRAM;
hints.ai_protocol=IPPROTO_UDP;
hints.ai_flags=AI_ADDRCONFIG;
int err=getaddrinfo(host, portname, &hints, &addr);
if (err!=0) {
fprintf(stderr, "Failed to resolve remote socket address!\\n");
return 0;
}
sock=socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
if (sock==-1) {
fprintf(stderr, "%s",strerror(errno));
return 0;
}
fprintf(stderr,"AIS data will be sent to %s port %s\\n",host,portname);
return 1;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex[4];
int sum = 0;
void* thread(void* arg) {
int thread_id = (int)arg;
int local_num;
pthread_mutex_lock(&mutex[thread_id]);
printf("Zdravo, ja sam nit broj: %d\\nUnesite jedan ceo broj:\\n", thread_id);
scanf("%d", &local_num);
sum += local_num;
if (thread_id == 4 -1) {
pthread_mutex_unlock(&mutex[0]);
} else {
pthread_mutex_unlock(&mutex[thread_id+1]);
}
pthread_exit(0);
return 0;
}
int main(int argc, char* argv[]) {
int i, rc, num;
pthread_t threads[4];
pthread_attr_t attribute;
for (i = 0; i < 4; i++) {
pthread_mutex_init(&mutex[i], 0);
pthread_mutex_lock(&mutex[i]);
}
pthread_attr_init(&attribute);
pthread_attr_setdetachstate(&attribute, PTHREAD_CREATE_JOINABLE);
for (i = 1; i < 4; i++) {
rc = pthread_create(&threads[i-1], &attribute, thread, (void*)i);
if (rc) {
printf("GRESKA! Povratni kod iz pthread_create() je: %d", rc);
exit(1);
}
}
printf("Zdravo, ja sam glavna nit.\\nUnesite jedan ceo broj:\\n");
scanf("%d", &num);
sum += num;
pthread_mutex_unlock(&mutex[1]);
pthread_mutex_lock(&mutex[0]);
printf("Zbir svih brojeva je: %d\\n", sum);
pthread_mutex_unlock(&mutex[0]);
pthread_attr_destroy(&attribute);
for (i = 0; i < 4; i++)
pthread_mutex_destroy(&mutex[i]);
return 0;
}
| 1
|
#include <pthread.h>
char *src;
char *dst;
} arg;
int count = 0;
pthread_mutex_t lock;
pthread_cond_t done;
void release()
{
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&done);
}
int chkdst(int argc, char **argv) {
int isdir(char *path);
if (argc < 2) {
fprintf(stderr, "Usage: ./copy file-name-1 file-name-2 ... file-name-n dest-dir\\n");
return 0;
}
if (!isdir(argv[argc - 1])) {
fprintf(stderr, "%s : no such file or directory\\n", argv[argc - 1]);
return 0;
}
return 1;
}
int isdir(char *path) {
struct stat buf;
if (stat(path, &buf) == 0 && S_ISDIR(buf.st_mode))
return 1;
return 0;
}
int isregular(char *path) {
struct stat buf;
if (stat(path, &buf) == 0 && S_ISREG(buf.st_mode))
return 1;
return 0;
}
int makecp(char *filedesIn, char *filedesOut) {
int fdin, fdout, retval;
char buf[2048];
ssize_t nread, nwrote;
fdin = open(filedesIn, O_RDONLY);
fdout = open(filedesOut, O_CREAT | O_WRONLY, 0644);
nread = read(fdin, buf, 2048);
nwrote = write(fdout, buf, (size_t)nread);
retval = close(fdin);
retval = close(fdout);
return 1;
}
char* buildpath(char *src, char *dst) {
char *ptr, *tpath;
ptr = malloc(strlen(src) + strlen(dst) + 1);
*ptr = 0;
tpath = basename(src);
if(*tpath == '/')
tpath++;
strcat(ptr, dst);
strcat(ptr, "/");
strcat(ptr, tpath);
return ptr;
}
void die(char *reason){
fprintf(stderr, "%s\\n", reason); exit(1);
}
void *do_copy(void * aStrct) {
int isregular(char *path);
int makecp(char *filedesIn, char *filedesOut);
char* buildpath(char *src, char *dst);
struct arg *args = aStrct;
char *destpath, *filepath;
pthread_mutex_lock(&lock);
count ++;
if (isdir(args->dst)){
filepath = buildpath(args->src, args->dst);
if(!isregular(args->src)){
count --;
fprintf(stderr, "%s: is not a regular file\\n", args->src);
}else{
makecp(args->src, filepath);
}
}
pthread_mutex_unlock(&lock);
pthread_cond_signal(&done);
pthread_exit(0);
}
int main(int argc, char *argv[]) {
int chkdst(int argc, char **argv);
void *do_copy(void * aStrct);
int i,j, status;
struct arg aStrct;
aStrct.dst = argv[argc - 1];
pthread_t threads [argc - 1];
if (!chkdst(argc, argv))
die("Bad arg");
pthread_mutex_init(&lock, 0);
for (i = 1; i < argc - 1; i++) {
aStrct.src = argv[i];
pthread_create(&threads[i - 1], 0, do_copy,(void *) &aStrct);
}
for (j = 0; j < argc - 1; j++) {
pthread_join(threads[j], status);
}
release();
exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t consumer_started = PTHREAD_COND_INITIALIZER;
char s[10000];
int flag;
void *producer (void *a)
{
int i, j;
flag = 0;
pthread_mutex_lock (&mutex);
printf("Prods started: \\n");
for (i = 0; i < 10000; i++)
{
s[i] = 'p';
for (j = 0; j < 10000; j++);
}
if (flag == 0)
{
pthread_cond_wait (&consumer_started, &mutex);
}
pthread_cond_signal (&cond);
pthread_mutex_unlock (&mutex);
}
void *consumer (void *a)
{
int i, j;
pthread_cond_signal (&consumer_started);
flag = 1;
pthread_mutex_lock (&mutex);
printf("Cons started: \\n");
pthread_cond_wait (&cond, &mutex);
for (i = 0; i < 10000; i++)
{
s[i] = 'c';
for (j = 0; j < 10000; j++);
}
pthread_mutex_unlock (&mutex);
}
int main ()
{
pthread_t pid, cid;
int corrupt, i;
while (1)
{
pthread_create (&pid, 0, producer, 0);
pthread_create (&cid, 0, consumer, 0);
pthread_join (pid, 0);
pthread_join (cid, 0);
corrupt = 0;
for (i = 0; i < 10000 - 1; i++) {
if (s[i] != s[i + 1]){
corrupt = 1;
break;
}
}
if (corrupt)
printf ("Memory is corrupted\\n");
else
printf ("Not corrupted\\n");
}
return 0;
}
| 1
|
#include <pthread.h>
int i;
int acount=0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condVar = PTHREAD_COND_INITIALIZER;
int accessible = 1;
void waitMySemaphor();
void signalMySemphor();
void *threadClient(void* args);
void *threadAccount();
void *threadClient(void* args)
{
char* name = (char*) args;
int i;
for (i = 0; i< 10; ++i)
{
waitMySemaphor();
printf("%s: before op: %d\\n",name,acount);
if (acount == 0)
{
sleep(1);
++acount;
}
else
{
sleep(1);
--acount;
}
printf("%s: after op: %d\\n",name,acount);
signalMySemphor();
sleep(1);
}
}
void *threadAccount()
{
int i;
for (i = 0; i< 10; ++i)
{
sleep(1);
}
}
void waitMySemaphor()
{
pthread_mutex_lock(&mutex);
while (accessible == 0)
pthread_cond_wait(&condVar, &mutex);
accessible = 0;
pthread_mutex_unlock(&mutex);
}
void signalMySemphor()
{
pthread_mutex_lock(&mutex);
pthread_cond_signal(&condVar);
accessible = 1;
pthread_mutex_unlock(&mutex);
}
int main(int argc, char* argv[])
{
pthread_t a,b,c,d,e;
char* buff1 = (char*) malloc(15);
char* buff2 = (char*) malloc(15);
char* buff3 = (char*) malloc(15);
char* buff4 = (char*) malloc(15);
sprintf(buff1,"thread_1");
sprintf(buff2,"thread_2");
sprintf(buff3,"thread_3");
sprintf(buff4,"thread_4");
pthread_create(&a,0,threadAccount,0);
pthread_create(&b,0,threadClient,buff1);
pthread_create(&c,0,threadClient,buff2);
pthread_create(&d,0,threadClient,buff3);
pthread_create(&e,0,threadClient,buff4);
pthread_join(a,0);
pthread_join(b,0);
pthread_join(c,0);
pthread_join(d,0);
pthread_join(e,0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t a;
pthread_mutex_t b;
pthread_mutex_t c;
pthread_mutex_t* array[5] = {&a,&b,&c,&a,&c};
void* fn1(void * args){
int x,k,j;
pthread_mutex_lock(array[j]);;
if( x < 0 ){
pthread_mutex_unlock(array[k]);;
j++;
} else {
pthread_mutex_lock(array[x]);;
}
pthread_mutex_lock(&b);;
}
int main() {
pthread_t thread1;
pthread_create(&thread1, 0, &fn1, 0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_barrier_t sum_barrier;
pthread_mutex_t sum_mutex1;
int a[1000], sum;
void initialize_array(int *a, int n) {
int i;
for (i = 1; i <= n; i++) {
a[i-1] = i;
}
}
void i_got_serial(int arg) {
printf("I'm such lucky thread, I got serial : %d\\n", arg);
}
void *thread_add(void *argument) {
int i, thread_sum, arg, ret;
thread_sum = 0;
arg = *(int *)argument;
for (i = ((arg-1)*(1000/4)) ; i < (arg*(1000/4)); i++) {
thread_sum += a[i];
}
ret = pthread_barrier_wait(&sum_barrier);
printf("----------->barrier crossed : thread : %d<---------------\\n", arg);
sleep(1);
if (ret == PTHREAD_BARRIER_SERIAL_THREAD) {
printf("Thread : %d : Sum : %d\\n", arg, thread_sum);
i_got_serial(arg);
}
else if (ret == 0)
printf("Thread : %d : Sum : %d\\n", arg, thread_sum);
else
printf("Barrier failed in thread: %d\\n", arg);
pthread_mutex_lock(&sum_mutex1);
sum += thread_sum;
pthread_mutex_unlock(&sum_mutex1);
}
void print_array(int *a, int size) {
int i;
for(i = 0; i < size; i++)
printf(" %d ", a[i]);
putchar('\\n');
}
void new_parent() {
int i, *range;
pthread_t thread_id[4];
sum = 0;
initialize_array(a, 1000);
printf("New Parent : Array : \\n");
print_array(a, 1000);
for (i = 0; i < 4; i++) {
range = (int *)malloc(sizeof(int));
*range = (i+1);
if (pthread_create(&thread_id[i], 0, thread_add, (void *)range))
printf("New Parent : Thread creation failed for thread num : %d\\n", *range);
}
for (i = 0; i < 4; i++) {
pthread_join(thread_id[i], 0);
}
printf("New Parent : Sum : %d\\n", sum);
}
int main() {
int i, *range;
pthread_t thread_id[4];
sum = 0;
initialize_array(a, 1000);
pthread_barrier_init(&sum_barrier, 0, 4);
printf("Array : \\n");
print_array(a, 1000);
for (i = 0; i < 4; i++) {
range = (int *)malloc(sizeof(int));
*range = (i+1);
if (pthread_create(&thread_id[i], 0, thread_add, (void *)range))
printf("Thread creation failed for thread num : %d\\n", *range);
}
for (i = 0; i < 4; i++) {
pthread_join(thread_id[i], 0);
}
printf("Main : Sum : %d\\n", sum);
return 0;
}
| 0
|
#include <pthread.h>
static char buffer[10];
static unsigned int first;
static unsigned int next;
static int buffer_size;
_Bool send, receive;
pthread_mutex_t m;
void initLog(int max)
{
buffer_size = max;
first = next = 0;
}
int removeLogElement(void)
{
assert(first>=0);
if (next > 0 && first < buffer_size)
{
first++;
return buffer[first-1];
}
else
{
return -1;
}
}
int insertLogElement(int b)
{
if (next < buffer_size && buffer_size > 0)
{
buffer[next] = b;
next = (next+1)%buffer_size;
assert(next<buffer_size);
}
else
{
return -1;
}
return b;
}
void *t1(void *arg)
{
int i;
for(i=0; i<7; i++)
{
pthread_mutex_lock(&m);
if (send)
{
insertLogElement(i);
send=0;
receive=1;
}
pthread_mutex_unlock(&m);
}
}
void *t2(void *arg)
{
int i;
for(i=0; i<7; i++)
{
pthread_mutex_lock(&m);
if (receive)
{
assert(removeLogElement()==i);
receive=0;
send=1;
}
pthread_mutex_unlock(&m);
}
}
int main()
{
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
initLog(10);
send=1;
receive=0;
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 1
|
#include <pthread.h>
int fifo_fd;
void* free_child_processes(void* parameters)
{
int status;
char buf[MAXBUFLEN];
int port;
int* port_iter;
struct server_pop* sp = (struct server_pop*)parameters;
for(;;)
{
sleep(10);
while ((waitpid(-1, 0, WNOHANG)) > 0)
{
memset(buf, 0, MAXBUFLEN);
status = read(fifo_fd, buf, 4);
if (status == -1)
perror("free_child_processes read");
port = (int)strtol(buf, (char**)0, 10);
if (port != 0)
{
printf("clearing port: %d\\n", port);
port_to_array_iter(port, &port_iter,
sp->child_server_pop);
pthread_mutex_lock(&(sp->mutex));
sp->total_pop -= *port_iter;
*port_iter = 0;
pthread_mutex_lock(&sp->empty_servers_mutex);
push_queue(sp->empty_servers, port);
pthread_mutex_unlock(&sp->empty_servers_mutex);
pthread_mutex_unlock(&(sp->mutex));
}
}
}
return 0;
}
void create_match_server(int curr_port)
{
pid_t child_pid;
child_pid = fork();
if (child_pid != 0)
{
}
else
{
int sockfd;
int status;
struct addrinfo* servinfo;
status = setup_connection(&sockfd, servinfo, curr_port);
if (status != 0)
{
printf("Child server at port: %d is already running.\\n",
curr_port);
exit(1);
}
int fd;
char str_curr_port[MAXBUFLEN];
sprintf(str_curr_port, "%d", curr_port);
handle_match_msg(sockfd);
printf("Child server at port: %d has closed.\\n", curr_port);
mkfifo("fifo", S_IFIFO | 0666);
fifo_fd = open("fifo", O_WRONLY);
if (fifo_fd == -1)
{
perror("open fifo in child");
exit(1);
}
printf("writing port: %s\\n", str_curr_port);
status = write(fifo_fd, str_curr_port, 4);
if (status == -1)
perror("create_match_server write");
close(fifo_fd);
close(sockfd);
exit(0);
}
}
int main()
{
int status;
int sockfd;
int sockfd_client;
struct addrinfo* servinfo;
int child_fifo_fd;
int k;
struct server_pop sp;
pthread_mutex_init(&(sp.mutex), 0);
pthread_mutex_init(&(sp.empty_servers_mutex), 0);
for (k = 0; k < MAX_CHILD_SERVERS; k++)
sp.child_server_pop[k] = 0;
struct queue* empty_servers = create_empty_queue();
for (k = LISTENPORT + 1; k < LISTENPORT + 1 + MAX_CHILD_SERVERS; k++)
push_queue(empty_servers, k);
sp.empty_servers = empty_servers;
sp.total_pop = 0;
status = setup_connection(&sockfd, servinfo, LISTENPORT);
if (status != 0)
{
printf("Parent server cannot start.\\n");
return status;
}
int curr_port;
if ((mkfifo("fifo", S_IFIFO | 0666)) == -1)
{
perror("parent mkfifo");
exit(1);
}
fifo_fd = open("fifo", O_RDONLY | O_NDELAY);
if (fifo_fd == -1)
{
perror("open fifo in parent");
exit(1);
}
struct queue* waiting_servers = create_empty_queue();
pthread_t free_child_processes_thread;
pthread_create(&free_child_processes_thread, 0,
&free_child_processes, &sp);
int* port_iter;
for (;;)
{
status = handle_syn_port(sockfd, &curr_port, &sockfd_client,
waiting_servers, &sp);
close(sockfd_client);
if (status == -1)
continue;
port_to_array_iter(curr_port, &port_iter, sp.child_server_pop);
pthread_mutex_lock(&(sp.mutex));
if (*port_iter == 1)
{
pthread_mutex_unlock(&(sp.mutex));
create_match_server(curr_port);
}
else
{
pthread_mutex_unlock(&(sp.mutex));
}
}
close(sockfd);
freeaddrinfo(servinfo);
return 0;
}
| 0
|
#include <pthread.h>
int main(void){
int *x;
int rt;
int shm_id;
char *addnum="myadd";
char *ptr;
pthread_mutex_t mutex;
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_setpshared(&mutexattr,PTHREAD_PROCESS_SHARED);
rt=fork();
if (rt==0){
shm_id=shm_open(addnum,O_RDWR,0);
ptr=mmap(0,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED,shm_id,0);
x=(int *)ptr;
int i;
for (i=0;i<10;i++){
pthread_mutex_lock(&mutex);
(*x)++;
printf("x++:%d\\n",*x);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
else{
shm_id=shm_open(addnum,O_RDWR|O_CREAT,0644);
ftruncate(shm_id,sizeof(int));
ptr=mmap(0,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED,shm_id,0);
x=(int *)ptr;
int i;
for ( i=0;i<10;i++){
pthread_mutex_lock(&mutex);
(*x)+=2;
printf("x+=2:%d\\n",*x);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
shm_unlink(addnum);
munmap(ptr,sizeof(int));
return(0);
}
| 1
|
#include <pthread.h>
extern struct mosaic mosaic;
static int get_tile_name(long int ntile, char * name) {
const char b32[] = "0123456789abcdefghijklmnopqrstuv";
int i, n;
strcpy(name, "....");
for (i = 0; i < 4; i++) {
n = ntile & 0b011111;
ntile = ntile >> 5;
name[7-i-1] = b32[n];
}
memcpy(&name[0],&name[3],2);
return 0;
}
static int close_tile_files() {
long int i;
for (i = 0; i < mosaic.ntiles; i++) {
if (mosaic.fd[i] != 0) {
close(abs(mosaic.fd[i]));
mosaic.nfiles--;
mosaic.fd[i] = 0;
}
}
return 0;
}
static int open_tile_read(const off_t tile_num) {
int fd;
char fpath[PATH_MAX];
char tile_name[32];
if ( mosaic.nfiles == mosaic.nfiles_max)
close_tile_files();
get_tile_name(tile_num, tile_name);
snprintf(fpath, sizeof(fpath), "%s/%s", mosaic.dir, tile_name);
fd = open(fpath,O_RDONLY);
if ( fd < 0 ) {
fd = 0;
}
else {
mosaic.nfiles++;
}
return fd;
}
static int open_tile_write(const off_t tile_num) {
int dir_is_new;
int file_is_new;
int fd;
int rv;
char tile_name[32];
char fpath[PATH_MAX], *dir_name ;
struct stat buf;
if ( mosaic.nfiles == mosaic.nfiles_max)
close_tile_files();
get_tile_name(tile_num, tile_name);
snprintf(fpath, sizeof(fpath), "%s/%s", mosaic.dir, tile_name);
dir_name = strdup(fpath);
dirname(dir_name);
dir_is_new = (stat(dir_name, &buf) !=0 );
if (dir_is_new) {
mkdir(dir_name,S_IRWXU);
}
file_is_new = (stat(fpath, &buf) !=0 );
fd = open(fpath,O_RDWR|O_CREAT,0600);
if ( fd < 0 ) {
fprintf(stderr, "ERROR: could not create tile file %s\\n",fpath);
fprintf(stderr, "ERROR: mosaic_nfiles = %d\\n",mosaic.nfiles);
fprintf(stderr, "ERROR: errno = %d\\n",errno);
exit(-1);
}
mosaic.nfiles++;
if (file_is_new) {
rv = pwrite(fd, "\\0", 1, mosaic.tile_size-1);
if (rv < 0) {
fprintf(stderr, "ERROR writing to tile file %s\\n",fpath);
exit(-1);
}
}
return fd;
}
static int get_tile_read(const off_t tile_num) {
if (mosaic.fd[tile_num] == 0) {
mosaic.fd[tile_num] = -open_tile_read(tile_num);
}
return abs(mosaic.fd[tile_num]);
}
static int get_tile_write(const off_t tile_num) {
if (mosaic.fd[tile_num] < 0) {
close(-mosaic.fd[tile_num]);
mosaic.nfiles--;
mosaic.fd[tile_num] = 0;
}
if (mosaic.fd[tile_num] == 0) {
mosaic.fd[tile_num] = open_tile_write(tile_num);
}
return mosaic.fd[tile_num];
}
static void lock()
{
pthread_mutex_lock(&the_lock);
}
static void unlock()
{
pthread_mutex_unlock(&the_lock);
}
int mosaicfs_getattr(const char *path, struct stat *stbuf)
{
if (strcmp(path, "/") != 0)
return -ENOENT;
stbuf->st_mode = S_IFREG | 0600;
stbuf->st_nlink = 1;
stbuf->st_uid = getuid();
stbuf->st_gid = getgid();
stbuf->st_size = mosaic.size;
stbuf->st_blocks = 0;
stbuf->st_atime = stbuf->st_mtime = stbuf->st_ctime = time(0);
return 0;
}
int mosaicfs_open(const char *path, struct fuse_file_info *fi)
{
if (strcmp(path, "/") != 0)
return -ENOENT;
return 0;
}
int mosaicfs_release(const char * path, struct fuse_file_info * fi)
{
if (strcmp(path, "/") != 0)
return -ENOENT;
return close_tile_files();
}
int mosaicfs_read(const char *path, char *buf, size_t size, off_t offset,
struct fuse_file_info *fi)
{
int fd;
off_t tile_num, tile_offset;
size_t bufpos, r;
if (strcmp(path, "/") != 0)
return -ENOENT;
size = min( size, max(mosaic.size-offset,(off_t)0) );
for (bufpos = 0; bufpos < size; ) {
tile_num = (offset+(off_t)bufpos) / mosaic.tile_size;
tile_offset = (offset+(off_t)bufpos) % mosaic.tile_size;
lock();
fd = get_tile_read(tile_num);
if ( fd > 0 ) {
r = pread(fd,buf+bufpos,size-bufpos,tile_offset);
bufpos += r;
} else {
r = min(size-bufpos,mosaic.tile_size-tile_offset);
memset(buf+bufpos,0,r);
bufpos += r;
}
unlock();
}
return bufpos;
}
int mosaicfs_write(const char *path, const char *buf, size_t size, off_t offset,
struct fuse_file_info *fi)
{
int fd;
off_t tile_num, tile_offset;
size_t bufpos, r, rv;
if (strcmp(path, "/") != 0)
return -ENOENT;
size = min( size, max(mosaic.size-offset, (off_t)0) );
for (bufpos = 0; bufpos < size; ) {
tile_num = (offset+(off_t)bufpos) / mosaic.tile_size;
tile_offset = (offset+(off_t)bufpos) % mosaic.tile_size;
lock();
fd = get_tile_write(tile_num);
r = min(size-bufpos, mosaic.tile_size-tile_offset);
rv = pwrite(fd,buf+bufpos,r,tile_offset);
unlock();
if (rv < 0) {
return -errno;
}
bufpos += r;
}
return bufpos;
}
int mosaicfs_truncate(const char *path, off_t nsize)
{
if (strcmp(path, "/") != 0)
return -ENOENT;
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mymutex=PTHREAD_MUTEX_INITIALIZER;
void * process(void * arg)
{
int i;
fprintf(stderr, "Starting process %s\\n", (char *) arg);
pthread_mutex_lock(&mymutex);
for (i = 0; i < 100; i++) {
write(1, (char *) arg, 1);
}
pthread_mutex_unlock(&mymutex);
return 0;
}
int hello(){
printf("hello");
return 1;
}
int main()
{
int retcode;
pthread_t th_a, th_b;
void * retval;
retcode = pthread_create(&th_a, 0, process, "a");
if (retcode != 0) fprintf(stderr, "create a failed %d\\n", retcode);
retcode = pthread_create(&th_b, 0, process, "b");
if (retcode != 0) fprintf(stderr, "create b failed %d\\n", retcode);
retcode = pthread_join(th_a, &retval);
if (retcode != 0) fprintf(stderr, "join a failed %d\\n", retcode);
retcode = pthread_join(th_b, &retval);
if (retcode != 0) fprintf(stderr, "join b failed %d\\n", retcode);
return 0;
}
| 1
|
#include <pthread.h>
struct producers{
int buffer[4];
pthread_mutex_t lock;
int readpos, writepos;
pthread_cond_t not_empty;
pthread_cond_t not_full;
};
static void init(struct producers *b){
pthread_mutex_init(&b->lock, 0);
pthread_cond_init (&b->not_empty, 0);
pthread_cond_init (&b->not_full, 0);
b->readpos = 0;
b->writepos = 0;
}
static void put(struct producers *b, int data){
pthread_mutex_lock (&b->lock);
while((b->writepos + 1) % 4 == b->readpos){
printf("Producer wait...\\n");
pthread_cond_wait(&b->not_full, &b->lock);
}
b->buffer[b->writepos] = data;
b->writepos++;
if(b->writepos >= 4){
b->writepos = 0;
}
pthread_cond_signal (&b->not_empty);
pthread_mutex_unlock (&b->lock);
}
static int get(struct producers *b){
int data;
pthread_mutex_lock (&b->lock);
while(b->writepos == b->readpos){
printf("Consumer wait...\\n");
pthread_cond_wait (&b->not_empty, &b->lock);
}
data = b->buffer[b->readpos];
b->readpos++;
if(b->readpos >= 4){
b->readpos = 0;
}
pthread_cond_signal (&b->not_full);
pthread_mutex_unlock (&b->lock);
return data;
}
struct producers buffer;
static void *producer(void *data){
int n;
for(n = 0; n < 10; n++){
printf("Producer : %d-->\\n", n);
put(&buffer, n);
printf("Producer :%d-->success\\n", n);
}
put(&buffer, (-1));
return 0;
}
static void *consumer(void *data){
int d;
while(1){
printf("Consumer: -->start get\\n", d);
d = get(&buffer);
if(d == (-1)){
printf("Consumer: --> %d-->over\\n", d);
break;
}
printf("Consumer: --> %d-->success\\n", d);
}
return 0;
}
int pthread_cond_wait_test(){
pthread_t tha, thb;
void *retval;
init(&buffer);
pthread_create (&tha, 0, producer, 0);
pthread_create (&thb, 0, consumer, 0);
pthread_join (tha, &retval);
pthread_join (thb, &retval);
return 0;
}
| 0
|
#include <pthread.h>
int myglobal;
pthread_mutex_t mymutex=PTHREAD_MUTEX_INITIALIZER;
void *thread_function_datarace(void *arg)
{
int i,j;
for ( i=0; i<20; i++ )
{
j=myglobal;
j=j+1;
printf("\\nIn thread_function_datarace..\\t");
sleep(1);
myglobal=j;
}
return 0;
}
void *thread_function_mutex(void *arg)
{
int i,j;
for ( i=0; i<20; i++ )
{
pthread_mutex_lock(&mymutex);
j=myglobal;
j=j+1;
printf("\\nIn thread_function_mutex..\\t");
sleep(0.1);
myglobal=j;
pthread_mutex_unlock(&mymutex);
}
return 0;
}
int main(void)
{
pthread_t mythread;
int i;
if ( pthread_create( &mythread, 0, thread_function_datarace, 0) )
{
printf("error creating thread.");
abort();
}
printf("\\n\\t\\t---------------------------------------------------------------------------");
printf("\\n\\t\\t Centre for Development of Advanced Computing (C-DAC)");
printf("\\n\\t\\t Email : RarchK");
printf("\\n\\t\\t---------------------------------------------------------------------------");
printf("\\n\\t\\t Objective : Pthread code to illustrate data race condition and its solution \\n ");
printf("\\n\\t\\t..........................................................................\\n");
for ( i=0; i<20; i++)
{
myglobal=myglobal+1;
printf("\\nIn main..\\t");
sleep(1);
}
if ( pthread_join ( mythread, 0 ) )
{
printf("error joining thread.");
abort();
}
printf("\\nValue of myglobal in thread_function_datarace is : %d\\n",myglobal);
printf("\\n ----------------------------------------------------------------------------------------------------\\n");
myglobal = 0;
if ( pthread_create( &mythread, 0, thread_function_mutex, 0) )
{
printf("error creating thread.");
abort();
}
for ( i=0; i<20; i++)
{
pthread_mutex_lock(&mymutex);
myglobal=myglobal+1;
pthread_mutex_unlock(&mymutex);
printf("\\nIn main..\\t");
sleep(1);
}
if ( pthread_join ( mythread, 0 ) )
{
printf("error joining thread.");
abort();
}
printf("\\n");
printf("\\nValue of myglobal in thread_function_mutex is : %d\\n",myglobal);
exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t numLock;
int arr[10];
int odd[10/2];
int even[10/2];
void *findOdd(void*);
void *findEven(void*);
void *findOdd(void *tArgs)
{
int j=0;
for(int i=0;i<10;i++)
{
if((arr[i]&1)>0)
odd[j++]=arr[i];
}
return 0;
}
void *findEven(void *tArgs)
{
int j=0;
for(int i=0;i<10;i++)
{
if((arr[i]&1)==0)
even[j++]=arr[i];
}
return 0;
}
int main()
{
for(int i=0;i<10;i++)
{
arr[i] = i;
}
pthread_t pt[2];
pthread_mutex_init(&numLock, 0);
pthread_mutex_lock(&numLock);
pthread_create(&pt[0], 0, findOdd, 0);
pthread_join(pt[0], 0);
pthread_mutex_unlock(&numLock);
pthread_mutex_lock(&numLock);
pthread_create(&pt[1], 0, findEven, 0);
pthread_join(pt[1], 0);
pthread_mutex_unlock(&numLock);
printf("ODD : ");
for (int j=0; j<10/2; j++) {
printf("%d\\t",odd[j]);
}
printf("\\n");
printf("EVEN : ");
for (int j=0; j<10/2; j++) {
printf("%d\\t",even[j]);
}
printf("\\n");
pthread_mutex_destroy(&numLock);
return 0;
}
| 0
|
#include <pthread.h>
{
int data;
struct node *next;
}node_t;
static pthread_key_t thread_log_key;
{
node_t *top;
}stack_t;
stack_t S;
void write_to_thread_log (const char* message)
{
FILE* thread_log = (FILE*) pthread_getspecific (thread_log_key);
fprintf (thread_log, "%s\\t",message);
fflush(thread_log);
}
pthread_mutex_t access = PTHREAD_MUTEX_INITIALIZER;
void printS()
{
pthread_mutex_lock(&access);
node_t *it =S.top;
char log[20]={0};
if(S.top== 0 ) return;
while(it !=0)
{
assert(it!= 0);
printf("\\t %d ",it->data);
it=it->next;
}
printf("\\n");
pthread_mutex_unlock(&access);
}
node_t* getnode(int data)
{
node_t *element =(node_t*) malloc (sizeof(node_t));
assert(element!= 0);
element->next=0;
element->data=data;
return element;
}
void insert(node_t* elm)
{
pthread_mutex_lock(&access);
elm->next = S.top;
S.top =elm;
pthread_mutex_unlock(&access);
}
node_t* delete()
{
pthread_mutex_lock(&access);
node_t *element = S.top;
if(element == 0 ) return 0;
S.top=element->next;
element->next=0;
pthread_mutex_unlock(&access);
return element;
}
void* consumer_routine(void *arg)
{
char thread_log_filename[20];
char log[200];
FILE* thread_log;
sprintf(thread_log_filename, "thread%d.log", (int) pthread_self ());
thread_log = fopen (thread_log_filename, "w");
pthread_setspecific (thread_log_key, thread_log);
while(1)
{
write_to_thread_log("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\\n");
fflush(stdout);
printS();
node_t* elm = delete();
if(elm != 0)
{
snprintf(log,200,"%s%p deleting %d\\n",__func__ ,pthread_self(),elm->data);
write_to_thread_log(log);
}
free(elm);
printS();
write_to_thread_log("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\\n");
fflush(stdout);
}
}
void* producer_routine(void *arg)
{
char thread_log_filename[20];
char log[200];
FILE* thread_log;
sprintf(thread_log_filename, "thread%d.log", (int) pthread_self ());
thread_log = fopen (thread_log_filename, "w");
srand(time(0));
while(1)
{
pthread_mutex_lock(&access);
printf("\\n lock iteration 1");
pthread_mutex_unlock(&access);
pthread_mutex_lock(&access);
printf("\\n lock iteration 2");
pthread_mutex_unlock(&access);
pthread_mutex_lock(&access);
printf("\\n lock iteration 3");
pthread_mutex_unlock(&access);
node_t *element =getnode(rand()%13);
printf("=====================================================================\\n");
fflush(stdout);
printS();
snprintf(log,200,"\\n%s%p inserting %d\\n",__func__ ,pthread_self(),element->data);
insert(element);
printS();
printf("=====================================================================\\n");
fflush(stdout);
}
}
void close_thread_log (void* thread_log)
{
fclose ((FILE*) thread_log);
}
func_type_t func_arr[]={producer_routine , consumer_routine,consumer_routine};
int main()
{
pthread_t tid[3];
int ret=0;
int i=0;
S.top=0;
ret =pthread_mutex_init(&access, 0);
if(ret!=0) return -1;
pthread_mutex_lock(&access);
printf("\\n lock iteration 1");
pthread_mutex_unlock(&access);
pthread_mutex_lock(&access);
printf("\\n lock iteration 2");
pthread_mutex_unlock(&access);
pthread_mutex_lock(&access);
printf("\\n lock iteration 3");
pthread_mutex_unlock(&access);
producer_routine(0);
return 0;
}
| 1
|
#include <pthread.h>
void *Producer();
void *Consumer();
int BufferIndex=0;
char *BUFFER;
pthread_cond_t Buffer_Not_Full=PTHREAD_COND_INITIALIZER;
pthread_cond_t Buffer_Not_Empty=PTHREAD_COND_INITIALIZER;
pthread_mutex_t mVar=PTHREAD_MUTEX_INITIALIZER;
int main()
{
pthread_t ptid,ctid;
BUFFER=(char *) malloc(sizeof(char) * 10);
pthread_create(&ptid,0,Producer,0);
pthread_create(&ctid,0,Consumer,0);
pthread_join(ptid,0);
pthread_join(ctid,0);
return 0;
}
void *Producer()
{
for(;;)
{
pthread_mutex_lock(&mVar);
if(BufferIndex==10)
{
pthread_cond_wait(&Buffer_Not_Full,&mVar);
}
BUFFER[BufferIndex++]='@';
printf("Produce : %d \\n",BufferIndex);
pthread_mutex_unlock(&mVar);
pthread_cond_signal(&Buffer_Not_Empty);
}
}
void *Consumer()
{
for(;;)
{
pthread_mutex_lock(&mVar);
if(BufferIndex==-1)
{
pthread_cond_wait(&Buffer_Not_Empty,&mVar);
}
printf("Consume : %d \\n",BufferIndex--);
pthread_mutex_unlock(&mVar);
pthread_cond_signal(&Buffer_Not_Full);
}
}
| 0
|
#include <pthread.h>
int count=1;
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *counter(void *t)
{
long my_id=(long)t;
int slp;
pthread_mutex_lock(&count_mutex);
count++;
slp=count;
while (slp=sleep(slp));
if (count == 1+3)
{
pthread_cond_broadcast(&count_threshold_cv);
printf("signal\\n");
}
pthread_cond_wait(&count_threshold_cv, &count_mutex);
pthread_mutex_unlock(&count_mutex);
pthread_cond_broadcast(&count_threshold_cv);
pthread_exit(0);
}
int main (int argc, char *argv[])
{
int i;
int flag=1;
long t;
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);
for (i=0; i< 3; i++)
{
t=i;
pthread_create(&threads[i], &attr, counter, (void *)t);
}
for(i=0; i< 3; i++)
{
pthread_join(threads[i], 0);
}
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int buff[10];
int buff_index;
pthread_mutex_t buff_mutex;
int push_front(int val)
{
if (buff_index < 10)
{
buff[buff_index++] = val;
return 0;
}
else
return -1;
}
int pop_front()
{
if (buff_index > 0)
return buff[--buff_index];
else
return -1;
}
void* producer(void* arg)
{
int result;
while (1)
{
for (int i = 0; i < 20; i++)
{
pthread_mutex_lock(&buff_mutex);
result = push_front(i);
printf("producer : %d | result = %d\\n", i, result);
pthread_mutex_unlock(&buff_mutex);
}
}
}
void* consumer(void* arg)
{
int temp;
while (1)
{
pthread_mutex_lock(&buff_mutex);
temp = pop_front();
printf("consumer : %d\\n", temp);
pthread_mutex_unlock(&buff_mutex);
}
}
int main()
{
pthread_t th1, th2;
pthread_mutex_init(&buff_mutex, 0);
pthread_create(&th1, 0, producer, 0);
pthread_create(&th2, 0, consumer, 0);
pthread_join(th1, 0);
pthread_join(th2, 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_t threads[2];
pthread_mutex_t lock[2];
pthread_cond_t cond;
void signal_handler(int signal) {
switch (signal) {
case SIGINT: {
for (int i = 0; i < 2; i++)
pthread_cancel(threads[i]);
} break;
default: break;
}
}
void *thread_a() {
while (1) {
pthread_mutex_lock(&lock[0]);
sleep(1);
printf("thread 1: ping thread 2\\n");
pthread_mutex_unlock(&lock[0]);
pthread_mutex_lock(&lock[1]);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock[1]);
pthread_mutex_lock(&lock[1]);
pthread_cond_wait(&cond, &lock[1]);
pthread_mutex_unlock(&lock[1]);
pthread_mutex_lock(&lock[0]);
sleep(1);
printf("thread 1: pong! thread 2 ping received\\n");
pthread_mutex_unlock(&lock[0]);
}
return 0;
}
void *thread_b() {
while (1) {
pthread_mutex_lock(&lock[1]);
pthread_cond_wait(&cond, &lock[1]);
pthread_mutex_unlock(&lock[1]);
pthread_mutex_lock(&lock[0]);
sleep(1);
printf("thread 2: pong! thread 1 ping received\\n");
sleep(1);
printf("thread 2: ping thread 1\\n");
pthread_mutex_unlock(&lock[0]);
pthread_mutex_lock(&lock[1]);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock[1]);
}
return 0;
}
int main() {
signal(SIGINT, signal_handler);
for (int i = 0; i < 2; i++) {
pthread_mutex_init(&lock[i], 0);
}
pthread_cond_init(&cond, 0);
pthread_create(&threads[0], 0, thread_a, 0);
pthread_create(&threads[1], 0, thread_b, 0);
for(int i = 0; i < 2; i++) {
pthread_join(threads[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static void
bit_test (void)
{
MY_TYPE v;
v = ~0;
printf ("v (all 1's): %llx\\n", v);
((v) = (v) & ~(((MY_TYPE) 1) << (4)));
printf ("v (one 0) : %llx\\n", v);
if ((((v) & (((MY_TYPE) 1) << (4))) == (((MY_TYPE) 1) << (4))))
{
printf ("bit %d is set\\n", 4);
}
else
{
printf ("bit %d is NOT set\\n", 4);
}
if ((((v) & (((MY_TYPE) 1) << (63))) == (((MY_TYPE) 1) << (63))))
{
printf ("bit %d is set\\n", 63);
}
else
{
printf ("bit %d is NOT set\\n", 63);
}
((v) = (v) | (((MY_TYPE) 1) << (4)));
printf ("v (all 1's): %llx\\n", v);
printf ("\\n");
}
static void *
my_thread (void * arg)
{
int * argi;
int i;
int * rtnval;
argi = (int *) arg;
i = *argi;
free (arg);
printf (" %lx: thread started; parameter=%d\\n", pthread_self(), i);
sleep (1);
rtnval = malloc (sizeof (int));
*rtnval = 42;
return (rtnval);
}
static void
thread_test (void)
{
int * parameter;
int * rtnval;
pthread_t thread_id;
parameter = malloc (sizeof (int));
*parameter = 73;
printf ("%lx: starting thread ...\\n", pthread_self());
pthread_create (&thread_id, 0, my_thread, parameter);
sleep (3);
pthread_join (thread_id, (void **) &rtnval);
printf ("%lx: thread ready; return value=%d\\n", pthread_self(), *rtnval);
free (rtnval);
printf ("\\n");
}
static void *
my_mutex_thread (void * arg)
{
printf (" %lx: thread start; wanting to enter CS...\\n", pthread_self());
pthread_mutex_lock (&mutex);
printf (" %lx: thread entered CS\\n", pthread_self());
sleep (10);
printf (" %lx: thread leaves CS\\n", pthread_self());
pthread_mutex_unlock (&mutex);
return (0);
}
static void
thread_mutex_test (void)
{
pthread_t my_threads[2];
printf ("%lx: starting thread-3 ...\\n", pthread_self());
pthread_create (&my_threads[0], 0, my_mutex_thread, 0);
sleep (3);
printf ("%lx: starting thread-5 ...\\n", pthread_self());
pthread_create (&my_threads[1], 0, my_mutex_thread, 0);
pthread_join (my_threads[0], 0);
pthread_join (my_threads[1], 0);
printf ("%lx: threads ready\\n", pthread_self());
printf ("\\n");
}
int main (void)
{
bit_test();
thread_test();
thread_mutex_test();
return (0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
char *s1;
char *s2;
int c;
} SWAP;
SWAP *S = 0;
void initialize(){
printf("init\\n");
S = (SWAP*) malloc(sizeof(SWAP));
S->c = 0;
}
char *swap (char *s){
printf("s:%s\\n",s);
pthread_mutex_lock(&m);
if(S->c%2 == 0){
printf("C:%d\\n",S->c);
S->s1 = (char*)malloc(sizeof(strlen(s)+1));
strcpy(S->s1,s);
S->c++;
while(S->c%2 != 0){
pthread_cond_wait(&cond, &m);
}
pthread_mutex_unlock(&m);
return S->s2;
}
else {
printf("C:%d\\n",S->c);
S->s2 = (char*)malloc(sizeof(strlen(s)+1));
strcpy(S->s2,s);
S->c++;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&m);
return S->s1;
}
return 0;
}
void *cmp(void *p){
char *a = (char *)p;
printf("a: %s Swap: %s \\n",a, swap(a));
return 0;
}
int main(int argc, char *argv[]){
printf("Main\\n");
initialize();
pthread_t t1;
pthread_t t2;
pthread_t t3;
pthread_t t4;
pthread_create(&t1, 0, cmp, "oro");
pthread_create(&t2, 0, cmp, "plata");
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_create(&t3, 0, cmp, "hierro");
pthread_create(&t4, 0, cmp, "magnesio");
pthread_join(t3, 0);
pthread_join(t4, 0);
}
| 1
|
#include <pthread.h>
int nitems;
struct {
pthread_mutex_t mutex;
int buffer[1000000];
int nputs;
int nval;
} shared = {
PTHREAD_MUTEX_INITIALIZER
};
void *producer(void*), *consumer(void*);
int main(int argc, const char** argv)
{
int nthreads, count[100];
pthread_t tid_producer[100], tid_consumer;
if (argc != 3)
{
return -1;
}
nitems = (atoi(argv[1]) < 1000000) ? atoi(argv[1]) : 1000000;
nthreads = (atoi(argv[2]) < 100) ? atoi(argv[2]) : 100;
for (int index = 0; index < nthreads; index++)
{
count[index] = 0;
pthread_create(&tid_producer[index], 0, producer, &count[index]);
}
for (int index = 0; index < nthreads; index++)
{
pthread_join(tid_producer[index], 0);
printf("count[%d]=%d\\n", index, count[index]);
}
pthread_create(&tid_consumer, 0, consumer, 0);
pthread_join(tid_consumer, 0);
return 0;
}
void* producer(void *arg)
{
while (1)
{
pthread_mutex_lock(&shared.mutex);
if (shared.nputs >= nitems)
{
pthread_mutex_unlock(&shared.mutex);
return 0;
}
shared.buffer[shared.nputs] = shared.nval;
shared.nputs++;
shared.nval++;
pthread_mutex_unlock(&shared.mutex);
*((int *)arg) += 1;
}
}
void* consumer(void* arg)
{
for (int index = 0; index < nitems; index++)
{
if (shared.buffer[index] != index)
{
printf("buffer[%d] error!!!", index);
}
}
return 0;
}
| 0
|
#include <pthread.h>
struct json_mode_each_iteration {
pthread_mutex_t mutex;
int cur_iteration;
};
static struct json_mode_each_iteration global_ei;
static int
jc_mode_each_iteration_init(
struct jc_comm *jcc
)
{
global_ei.cur_iteration = jcc->iteration;
if (jcc->mode_type)
free(jcc->mode_type);
jcc->mode_type = strdup("each iteration");
return JC_OK;
}
static int
jc_mode_each_iteration_execute(
struct jc_comm *jcc
)
{
int ret = 0;
pthread_mutex_lock(&global_ei.mutex);
if (jcc->iteration == global_ei.cur_iteration) {
jcc->getvalue = JC_IGNORE_VALUE;
ret = JC_ERR;
} else {
global_ei.cur_iteration = jcc->iteration;
jcc->getvalue = JC_GET_VALUE;
ret = JC_OK;
}
pthread_mutex_unlock(&global_ei.mutex);
if (jcc->mode_type)
free(jcc->mode_type);
jcc->mode_type = strdup("each iteration");
return ret;
}
int
json_config_mode_each_iteration_init()
{
int ret = 0;
struct json_mode_oper oper;
pthread_mutex_init(&global_ei.mutex, 0);
memset(&oper, 0, sizeof(oper));
oper.json_mode_init = jc_mode_each_iteration_init;
oper.json_mode_execute = jc_mode_each_iteration_execute;
return json_mode_module_add("each iteration", 0, &oper);
}
int
json_config_mode_each_iteration_uninit()
{
return JC_OK;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_mutex_t lock2;
int value;
int value2;
sem_t sem;
void *functionWithCriticalSection(int* v2) {
pthread_mutex_lock(&(lock));
pthread_mutex_lock(&(lock2));
value = value2 + *v2;
value2 = value;
pthread_mutex_unlock(&(lock2));
pthread_mutex_unlock(&(lock));
sem_post(&sem);
}
void *otherFunctionWithCriticalSection(int* v2) {
if (v2 != 0) {
pthread_mutex_lock(&(lock));
pthread_mutex_lock(&(lock2));
value = value2 + 1;
value2 = value;
pthread_mutex_unlock(&(lock2));
pthread_mutex_unlock(&(lock));
}
sem_post(&sem);
}
void *thirdFunctionWithCriticalSection(int* v2) {
pthread_mutex_lock(&(lock));
value = value + 1;
pthread_mutex_unlock(&(lock));
sem_post(&sem);
}
int main() {
sem_init(&sem, 0, 0);
value = 0;
value2 = 0;
int v2 = 2;
pthread_mutex_init(&(lock), 0);
pthread_mutex_init(&(lock2), 0);
pthread_t thread1;
pthread_t thread2;
pthread_create (&thread1,0,functionWithCriticalSection,&v2);
pthread_create (&thread2,0,otherFunctionWithCriticalSection,&v2);
sem_wait(&sem);
sem_wait(&sem);
pthread_create (&thread1,0,thirdFunctionWithCriticalSection,&v2);
pthread_create (&thread2,0,thirdFunctionWithCriticalSection,&v2);
sem_wait(&sem);
sem_wait(&sem);
pthread_mutex_destroy(&(lock));
pthread_mutex_destroy(&(lock2));
sem_destroy(&sem);
printf("%d\\n", value);
return 0;
}
| 0
|
#include <pthread.h>
int count;
pthread_mutex_t m;
pthread_cond_t cv;
} barrier_t;
int * input;
int * output;
size_t size = 0;
pthread_t * allThreads;
int threads;
barrier_t ba;
void barrier_init(barrier_t *b, int inThreads){
b->count = inThreads;
pthread_mutex_init(&b->m, 0);
pthread_cond_init(&b->cv, 0);
}
void barrier_wait(barrier_t *b){
pthread_mutex_lock(&b->m);
if(b->count == 1)
pthread_cond_broadcast(&b->cv);
else
{
b->count --;
pthread_cond_wait(&b->cv, &b->m);
}
pthread_mutex_unlock(&b->m);
}
void barrier_destroy(barrier_t *b){
pthread_cond_destroy(&b->cv);
pthread_mutex_destroy(&b->m);
}
int * readIn(char *argv[], size_t size){
int * ret;
int lines=size;
int i=0;
int c;
FILE *f;
ret = malloc(sizeof(int) * lines);
f = fopen(argv[1], "r");
do
{
c = fscanf(f, "%d\\n", &ret[i]);
if(feof(f))
break;
i++;
}while(1);
fclose(f);
return ret;
}
size_t getSize(char *argv[]){
size_t lines=0;
int c=0;
FILE *f;
f = fopen(argv[1], "r");
if(f==0){
printf("Error in opening file.");
return 0;
}
do
{
c = fgetc(f);
if(feof(f))
break;
if(c=='\\n')
lines++;
}while(1);
fclose(f);
return lines;
}
int numThreads (size_t size){
return size / 2;
}
void printArray(int * in, size_t size){
printf("in printArray, size = %d\\n", size);
int i=0;
for(i=0;i<size; i++)
printf("in[%d] = %d\\n", i, in[i]);
}
void * compare (void * arg){
int i = 2 * (int) arg;
int tmp = 0;
if(input[i] > input[i+1])
tmp = input[i];
else
tmp = input[i+1];
output[(int)arg] = tmp;
barrier_wait(&ba);
}
int main(int argc, char *argv[]){
int rounds = 0;
int tindex;
size = getSize(argv);
input = malloc(sizeof(int) * size);
if(size==0){
printf("There are no numbers in the file.\\n");
exit(0);
}
input = readIn(argv, size);
while(size > 1){
threads = numThreads(size);
barrier_init(&ba, threads+1);
allThreads = malloc(sizeof(pthread_t) * threads);
output = malloc(sizeof(int) * threads);
for(tindex=0; tindex<threads; tindex++)
pthread_create(&allThreads, 0, compare, (void*) tindex);
barrier_wait(&ba);
free(input);
input = malloc(sizeof(int) * threads);
memcpy(input, output, sizeof(int) * threads);
free(output);
size = size / 2;
barrier_destroy(&ba);
}
printf("The largest number is %d.\\n", input[0]);
return 0;
}
| 1
|
#include <pthread.h>
struct sunxi_timer_reg {
u32 dummy1[0xc90 / 4];
volatile u32 wdog_ctrl_reg;
volatile u32 wdog_mode_reg;
};
int mem_fd = -1;
volatile unsigned *map_physical_memory(uint32_t addr, size_t len)
{
volatile unsigned *mem;
if (mem_fd == -1 && (mem_fd = open("/dev/mem", O_RDWR|O_SYNC) ) < 0)
{
perror("opening /dev/mem");
exit(1);
}
mem = (volatile unsigned *) mmap(0, len, PROT_READ | PROT_WRITE, MAP_SHARED, mem_fd, (off_t) addr);
if (mem == MAP_FAILED)
{
perror("mmap");
exit (1);
}
return mem;
}
volatile struct sunxi_timer_reg *r;
pthread_mutex_t watchdog_mutex = PTHREAD_MUTEX_INITIALIZER;
volatile int watchdog_timeout_upper_limit;
volatile int watchdog_timeout_counter;
static void deadloop(void)
{
while (1) {}
}
static void simple_memtester(int x)
{
static char buffer1[(1024 * 1024)];
static char buffer2[(1024 * 1024)];
memset(buffer1, (x ^ 0x5A) & 0xFF, (1024 * 1024));
memcpy(buffer2, buffer1, (1024 * 1024));
if (memcmp(buffer2, buffer1, (1024 * 1024)) != 0)
deadloop();
}
static void *watchdog_thread_function(void *ctx)
{
r = (volatile struct sunxi_timer_reg *) map_physical_memory(0x01c20000, 4096);
r->wdog_mode_reg = (5 << 3) | 3;
r->wdog_ctrl_reg = (0x0a57 << 1) | 1;
r->wdog_mode_reg = (5 << 3) | 3;
while (1)
{
pthread_mutex_lock(&watchdog_mutex);
if (watchdog_timeout_counter == -1)
{
r->wdog_mode_reg = 0;
exit(0);
}
if (watchdog_timeout_counter == 0)
{
printf("Boom!\\n");
deadloop();
}
watchdog_timeout_counter--;
pthread_mutex_unlock(&watchdog_mutex);
simple_memtester(watchdog_timeout_counter);
sleep(1);
r->wdog_ctrl_reg = (0x0a57 << 1) | 1;
r->wdog_mode_reg = (5 << 3) | 3;
}
}
int main(int argc, char **argv)
{
pthread_t watchdog_thread;
if (argc < 2 || sscanf(argv[1], "%d", &watchdog_timeout_counter) != 1)
{
printf("Usage: a10-stdin-watchdog [initial_timeout_in_seconds]\\n");
printf("\\n");
printf("This program activates the Allwinner A10 hardware watchdog\\n");
printf("and sets it to trigger after a timeout has elapsed. The initial\\n");
printf("timeout value is provided in the command line. This value\\n");
printf("also sets the upper timeout limit, which can't be overrided!\\n");
printf("\\n");
printf("Also it tries to read numbers from the standard input.\\n");
printf("Whenever a new number is read, it is interpreted as a new\\n");
printf("watchdog timeout value (in seconds). If the magic value\\n");
printf("%d is read, then the watchdog is deactivated.\\n", -1);
exit(1);
}
watchdog_timeout_upper_limit = watchdog_timeout_counter;
pthread_create(&watchdog_thread, 0, watchdog_thread_function, 0);
while (1)
{
int new_counter;
if (scanf("%i", &new_counter) == 1)
{
if (new_counter != -1)
{
if (new_counter < 0)
new_counter = 0;
if (new_counter > watchdog_timeout_upper_limit)
new_counter = watchdog_timeout_upper_limit;
}
pthread_mutex_lock(&watchdog_mutex);
watchdog_timeout_counter = new_counter;
pthread_mutex_unlock(&watchdog_mutex);
}
}
return 0;
}
| 0
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER;
void *thr_fn(void *arg) {
int err, signo;
for (;;) {
err = sigwait(&mask, &signo);
if (err != 0) {
err_exit(err, "sigwait failed");
}
switch (signo) {
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&waitloc);
return 0;
default:
printf("unexpected signal %d\\n", signo);
exit(1);
}
}
}
int main() {
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) {
err_exit(err, "SIG_BLOCK error");
}
err = pthread_create(&tid, 0, thr_fn, 0);
if (err != 0) {
err_exit(err, "can't reate thread");
}
pthread_mutex_lock(&lock);
while (quitflag == 0) {
pthread_cond_wait(&waitloc, &lock);
}
pthread_mutex_unlock(&lock);
quitflag = 0;
if (sigprocmask(SIG_SETMASK, &oldmask, 0) == -1) {
err_sys("sig_seTMASK error");
}
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
int element[(800)];
int head;
int tail;
int amount;
} QType;
pthread_mutex_t m;
int __VERIFIER_nondet_int();
int stored_elements[(800)];
_Bool enqueue_flag, dequeue_flag;
QType queue;
int init(QType *q)
{
q->head=0;
q->tail=0;
q->amount=0;
}
int empty(QType * q)
{
if (q->head == q->tail)
{
printf("queue is empty\\n");
return (-1);
}
else
return 0;
}
int full(QType * q)
{
if (q->amount == (800))
{
printf("queue is full\\n");
return (-2);
}
else
return 0;
}
int enqueue(QType *q, int x)
{
q->element[q->tail] = x;
q->amount++;
if (q->tail == (800))
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == (800))
{
q->head = 1;
}
else
q->head++;
return x;
}
void *t1(void *arg)
{
int value, i;
pthread_mutex_lock(&m);
value = __VERIFIER_nondet_int();
if (enqueue(&queue,value)) {
goto ERROR;
}
stored_elements[0]=value;
if (empty(&queue)) {
goto ERROR;
}
pthread_mutex_unlock(&m);
for(
i=0; i<((800)-1); i++)
{
pthread_mutex_lock(&m);
if (enqueue_flag)
{
value = __VERIFIER_nondet_int();
enqueue(&queue,value);
stored_elements[i+1]=value;
enqueue_flag=(0);
dequeue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
ERROR:
__VERIFIER_error();
}
void *t2(void *arg)
{
int i;
for(
i=0; i<(800); i++)
{
pthread_mutex_lock(&m);
if (dequeue_flag)
{
if (!dequeue(&queue)==stored_elements[i]) {
ERROR:
__VERIFIER_error();
}
dequeue_flag=(0);
enqueue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
}
int main(void)
{
pthread_t id1, id2;
enqueue_flag=(1);
dequeue_flag=(0);
init(&queue);
if (!empty(&queue)==(-1)) {
ERROR:
__VERIFIER_error();
}
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, &queue);
pthread_create(&id2, 0, t2, &queue);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 0
|
#include <pthread.h>
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo
{
int f_count;
pthread_mutex_t f_lock;
int f_id;
struct foo *f_next;
};
struct foo *
foo_alloc(int id)
{
struct foo *fp;
int idx;
if ((fp = malloc(sizeof(struct foo))) != 0)
{
fp->f_count = 1;
fp->f_id = id;
if (pthread_mutex_init(&fp->f_lock, 0) != 0)
{
free(fp);
return(0);
}
idx = (((unsigned long)id)%29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
}
return(fp);
}
void
foo_hold(struct foo *fp)
{
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
struct foo *
foo_find(int id)
{
struct foo *fp;
pthread_mutex_lock(&hashlock);
for (fp = fh[(((unsigned long)id)%29)]; fp != 0; fp = fp->f_next)
{
if (fp->f_id == id)
{
foo_hold(fp);
break;
}
}
pthread_mutex_unlock(&hashlock);
return(fp);
}
void
foo_rele(struct foo *fp)
{
struct foo *tfp;
int idx;
pthread_mutex_lock(&fp->f_lock);
if (fp->f_count == 1)
{
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_lock(&hashlock);
pthread_mutex_lock(&fp->f_lock);
if (fp->f_count != 1)
{
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
return;
}
idx = (((unsigned long)fp->f_id)%29);
tfp = fh[idx];
if (tfp == fp)
{
fh[idx] = fp->f_next;
}
else
{
while (tfp->f_next != fp)
tfp = tfp->f_next;
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
}
else
{
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
}
}
| 1
|
#include <pthread.h>
unsigned int counter = 1;
unsigned int result = 0;
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t result_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t print_mutex = PTHREAD_MUTEX_INITIALIZER;
void* worker( void* );
void main(void)
{
setvbuf(stdout, 0, _IONBF, 0);
int i;
pthread_t thr[4];
for ( i= 0; i < 4; i++ )
{
if( pthread_create( &thr[i], 0, &worker, 0 ))
{
printf("Could not create thread %d.\\n", i);
exit(-1);
}
}
for(i = 0; i < 4; i++)
{
if(pthread_join(thr[i], 0))
{
printf("Could not join thread %d.\\n", i);
exit(-1);
}
}
printf("\\nResult: %d\\n", result);
}
void* worker( void *none )
{
int theSqrt, i, j;
for( ;; )
{
pthread_mutex_lock(&counter_mutex);
if(++counter >= 500000)
{
pthread_mutex_unlock(&counter_mutex);
return;
}
unsigned int checkThis = counter;
pthread_mutex_unlock(&counter_mutex);
if( checkThis % 2500 == 0 )
{
pthread_mutex_lock(&print_mutex);
printf(".");
pthread_mutex_unlock(&print_mutex);
}
if(is_pandig(&checkThis))
{
theSqrt = sqrt(checkThis);
for( i=1; i<=theSqrt; i++ )
{
if(( checkThis % i == 0 ) && ( is_pandig2( &i, &checkThis )))
{
j=checkThis / i;
if( is_pandig3( &i, &j, &checkThis ))
{
pthread_mutex_lock(&result_mutex);
result = result + checkThis;
pthread_mutex_unlock(&result_mutex);
pthread_mutex_lock(&print_mutex);
printf("\\n%d x %d = %d", i, j, checkThis);
pthread_mutex_unlock(&print_mutex);
break;
}
}
}
}
}
}
bool is_pandig3( int* testor, int* testor2, int* testor3 )
{
bool test_array[10];
int i, j, k;
for( i=0; i<=9; i++ )
test_array[i] = 0;
test_array[0] = 1;
for( j=0; j<3; j++ )
{
if(j == 0)
k = *testor;
else if(j == 1)
k = *testor2;
else
k = *testor3;
while( k > 0 )
{
i = k % 10;
if( test_array[i] )
return 0;
else
test_array[i] = 1;
k = k / 10;
}
}
if( test_array[1] && test_array[2] && test_array[3] && test_array[4] && test_array[5] && test_array[6] && test_array[7] && test_array[8] && test_array[9] )
{
return 1;
} else {
return 0;
}
return 1;
}
| 0
|
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
pthread_cond_t a = PTHREAD_COND_INITIALIZER;
pthread_mutex_t b = PTHREAD_MUTEX_INITIALIZER;
int count = 1;
void *eventhread(){
for(;;){
pthread_mutex_lock(&count_mutex);
if(count >= 15){
pthread_mutex_unlock(&count_mutex);
pthread_cond_signal(&condition_var);
return 0;
}
printf("even_thread: thread_id = 1, ");
printf("count = %d \\n",count);
if(count % 2 != 0){
printf("Odd count found, signalling to odd thread \\n");
pthread_mutex_lock(&b);
pthread_mutex_unlock(&count_mutex);
sleep(1);
pthread_cond_signal(&condition_var);
pthread_cond_wait(&a,&b);
pthread_mutex_unlock(&b);
}
else{
count++;
pthread_mutex_unlock(&count_mutex);
}
}
}
void *oddthread(){
for(;;){
pthread_mutex_lock(&count_mutex);
pthread_cond_wait(&condition_var,&count_mutex);
if(count > 15){
pthread_mutex_unlock(&count_mutex);
return 0;
}
printf("odd_thread: thread_id = 2, ");
printf("count = %d \\n",count);
if(count == 15){
printf("Threshold reached \\n");
pthread_mutex_unlock(&count_mutex);
return 0;
}
count++;
pthread_mutex_unlock(&count_mutex);
pthread_cond_signal(&a);
}
}
int main(){
pthread_t thread1,thread2;
pthread_create(&thread1,0,&eventhread,0);
pthread_create(&thread2,0,&oddthread,0);
pthread_join(thread1,0);
pthread_join(thread2,0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
int mean, samples, total;
void *report_stats(void *p)
{
int caught, i;
sigset_t sigs_to_catch;
printf("\\nreport_stats() started.\\n");
sigemptyset(&sigs_to_catch);
sigaddset(&sigs_to_catch, SIGUSR1);
for (;;) {
sigwait(&sigs_to_catch, &caught);
pthread_mutex_lock(&stats_lock);
mean = total/samples;
printf("\\nreport_stats(): mean = %d, samples = %d\\n", mean, samples);
pthread_mutex_unlock(&stats_lock);
}
return 0;
}
void *worker_thread(void *p)
{
time_t now;
for (;;) {
sleep(1 + (*(int*)p) % 2 );
now = time(0);
pthread_mutex_lock(&stats_lock);
total+=((int)now)%60;
samples++;
pthread_mutex_unlock(&stats_lock);
}
return 0;
}
extern int
main(void)
{
int i;
pthread_t threads[10];
int num_threads = 0;
sigset_t sigs_to_block;
printf("main() (pid %d) running in thread 0x%x\\n",
getpid(), (int)pthread_self());
sigemptyset(&sigs_to_block);
sigaddset(&sigs_to_block, SIGUSR1);
pthread_sigmask(SIG_BLOCK, &sigs_to_block, 0);
pthread_create(&threads[num_threads++],
0,
report_stats,
0);
for (i=num_threads; i<10; i++) {
pthread_create(&threads[num_threads++],
0,
worker_thread,
&i);
}
printf("main()\\t\\t\\t\\t%d threads created\\n",num_threads);
for (i = 0; i < num_threads; i++) {
pthread_join(threads[i], 0);
printf("main()\\t\\tjoined to thread %d \\n", i);
}
printf("main()\\t\\tall %d threads have finished. \\n", num_threads);
return 0;
}
| 0
|
#include <pthread.h>
extern FILE *diag;
void *KeyboardThread(void *arg) {
char c=0;
extern pthread_cond_t CommandRecvCond;
extern pthread_mutex_t CommandRecvMutex,CommandGetMutex;
extern int Command;
pthread_setasynccancel(CANCEL_ON);
pthread_setcancel(CANCEL_ON);
while(1) {
Diag("keybthrd: requesting CommandRecvMutex");
pthread_mutex_lock(&CommandRecvMutex);
Diag("keybthrd: got CommandRecvMutex; "
"releasing it and waiting for keystroke");
pthread_mutex_unlock(&CommandRecvMutex);
read(STDIN, &c, 1);
Diag("keybthrd: got a keystroke; requesting CommandRecvMutex");
pthread_mutex_lock(&CommandRecvMutex);
Command = c;
Diag("keybthrd: got CommandRecvMutex; signalling CommandRecvCond");
pthread_cond_signal(&CommandRecvCond);
pthread_mutex_unlock(&CommandRecvMutex);
Diag("keybthrd: requesting CommandGetMutex");
pthread_mutex_lock(&CommandGetMutex);
Diag("keybthrd: got CommandGetMutex; releasing it and continuing");
pthread_mutex_unlock(&CommandGetMutex);
}
}
| 1
|
#include <pthread.h>
struct matriz_e_tamanho {
double** m;
long n;
double sum;
pthread_mutex_t mutex;
pthread_t thread[2];
pthread_cond_t cond;
};
struct timeval tv1, tv2;
long tID = 0;
int controle_linhas=0;
void *ProcessaMatriz(void *m_n) {
struct matriz_e_tamanho *mat_n = (struct matriz_e_tamanho *)m_n;
pthread_mutex_lock(&mat_n->mutex);
long local_tID = tID;
tID++;
while(tID< 2)
pthread_cond_wait( &mat_n->cond, &mat_n->mutex );
pthread_cond_signal(&mat_n->cond);
pthread_mutex_unlock(&mat_n->mutex);
int i=0,
j=0,
tamanho_sub_matriz = mat_n->n / 2;
double local_sum=0;
local_sum=0;
for (i = tamanho_sub_matriz*local_tID; i < ((local_tID+1)*tamanho_sub_matriz) ; ++i) {
for (j = 0; j < mat_n->n; ++j)
{
local_sum += mat_n->m[i][j];
}
}
pthread_mutex_lock(&mat_n->mutex);
mat_n->sum+= local_sum;
pthread_mutex_unlock(&mat_n->mutex);
return 0;
}
void *CriaMatriz(void *tamanhoMatriz) {
long n ;
double confere=0;
n = (long)tamanhoMatriz;
int i, j;
double **matriz = (double**)malloc(n * sizeof(double*));
struct timeval tm;
gettimeofday(&tm, 0);
srandom(tm.tv_sec + tm.tv_usec * 1000000ul);
for (i = 0; i < n; i++){
matriz[i] = (double*) malloc(n * sizeof(double));
for (j = 0; j < n; j++){
confere+= matriz[i][j] = 1.0;
}
}
struct matriz_e_tamanho* mat_n = malloc( sizeof( struct matriz_e_tamanho ));
mat_n->m = matriz;
mat_n->n = n;
mat_n->sum = 0;
pthread_mutex_init(&mat_n->mutex, 0);
pthread_cond_init(&mat_n->cond, 0);
int sub_threads = 2;
void *status;
int t_child =0;
gettimeofday(&tv1, 0);
for(t_child =0; t_child < sub_threads; t_child++) {
pthread_create(&(mat_n->thread[t_child]), 0, ProcessaMatriz, mat_n);
}
for(t_child = 0; t_child < sub_threads; t_child++) {
pthread_join(mat_n->thread[t_child], &status);
}
gettimeofday(&tv2, 0);
printf ("Total time = %f seconds\\n",
(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
(double) (tv2.tv_sec - tv1.tv_sec));
printf("sum==%f\\n",mat_n->sum );
free(matriz);
pthread_exit(0);
return 0;
}
int main (int argc, char *argv[])
{
if (argv[1] == 0 || atoi(argv[1]) < 1) {
printf("ERRO, insira o valor de 'n': \\n");
exit(1);
}
long n = (long)atoi(argv[1]);
pthread_t thread0;
void *status;
pthread_create(&thread0, 0, CriaMatriz, (void *)n);
pthread_join(thread0, &status);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
void *func(void *parm);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int t1_start=0;
int t1_pause=1;
int main()
{
int i, rc;
pthread_t t1;
pthread_create(&t1, 0, func, 0);
while(!t1_start)
sleep(1);
rc = pthread_mutex_trylock(&mutex);
if(rc!=EBUSY) {
fprintf(stderr,"Expected %d(EBUSY), got %d\\n",EBUSY,rc);
printf("Test FAILED\\n");
return PTS_FAIL;
}
t1_pause=0;
for(i=0; i<5; i++) {
rc = pthread_mutex_trylock(&mutex);
if(rc==0) {
pthread_mutex_unlock(&mutex);
break;
}
else if(rc==EBUSY) {
sleep(1);
continue;
}
else {
fprintf(stderr,"Unexpected error code(%d) for pthread_mutex_lock()\\n", rc);
return PTS_UNRESOLVED;
}
}
pthread_join(t1, 0);
pthread_mutex_destroy(&mutex);
if(i>=5) {
fprintf(stderr,"Have tried %d times but failed to get the mutex\\n", i);
return PTS_UNRESOLVED;
}
printf("Test PASSED\\n");
return PTS_PASS;
}
void *func(void *parm)
{
int rc;
if((rc=pthread_mutex_lock(&mutex))!=0) {
fprintf(stderr,"Error at pthread_mutex_lock(), rc=%d\\n",rc);
pthread_exit((void*)PTS_UNRESOLVED);
}
t1_start=1;
while(t1_pause)
sleep(1);
if((rc=pthread_mutex_unlock(&mutex))!=0) {
fprintf(stderr,"Error at pthread_mutex_unlock(), rc=%d\\n",rc);
pthread_exit((void*)PTS_UNRESOLVED);
}
pthread_exit(0);
return (void*)(0);
}
| 1
|
#include <pthread.h>
struct tdata {
int tid;
};
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t unLock = PTHREAD_COND_INITIALIZER;
unsigned locked = 0;
void lock() {
pthread_mutex_lock(&mutex);
while (locked) {
pthread_cond_wait(&unLock, &mutex);
}
locked = 1;
pthread_mutex_unlock(&mutex);
}
void unlock() {
locked = 0;
pthread_cond_signal(&unLock);
}
int counter = 0;
void *count(void *ptr) {
long i, max = 10000000/4;
int tid = ((struct tdata *) ptr)->tid;
for (i=0; i < max; i++) {
lock();
counter += 1;
unlock();
}
printf("End %d counter: %d\\n", tid, counter);
}
int main (int argc, char *argv[]) {
pthread_t threads[4];
int rc, i;
struct tdata id[4];
for(i=0; i<4; i++){
id[i].tid = i;
rc = pthread_create(&threads[i], 0, count, (void *) &id[i]);
}
for(i=0; i<4; i++){
pthread_join(threads[i], 0);
}
printf("Counter value: %d Expected: %d\\n", counter, 10000000);
return 0;
}
| 0
|
#include <pthread.h>
long long int now()
{
struct timeval tv;
gettimeofday(&tv, 0);
return tv.tv_sec*1000LL+tv.tv_usec/1000LL;
}
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_spinlock_t spinlock;
static void test_spinlock(int n)
{
while (n>0)
{
pthread_spin_lock(&spinlock);
pthread_spin_unlock(&spinlock);
n--;
pthread_spin_lock(&spinlock);
pthread_spin_unlock(&spinlock);
n--;
pthread_spin_lock(&spinlock);
pthread_spin_unlock(&spinlock);
n--;
pthread_spin_lock(&spinlock);
pthread_spin_unlock(&spinlock);
n--;
pthread_spin_lock(&spinlock);
pthread_spin_unlock(&spinlock);
n--;
}
}
static void test_mutex(int n)
{
while (n>0)
{
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
n--;
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
n--;
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
n--;
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
n--;
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
n--;
}
}
static void test_empty(int n)
{
while (n>0)
{
n--;
n--;
n--;
n--;
n--;
}
}
void test(char *name, void (*func)(int n), int n)
{
int i;
long long int start, end, stop;
start=now();
end=start;
stop=start+10*1000;
i=0;
while (end<stop)
{
func(n);
i++;
end=now();
}
fprintf(stderr, "%s time: %15.1f lock/s\\n", name, (float)n*i*1000/(end-start));
}
pthread_t loop1_thread, loop2_thread;
pthread_rwlock_t rw_lock=PTHREAD_RWLOCK_INITIALIZER;
pthread_cond_t cond1=PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2=PTHREAD_COND_INITIALIZER;
long long int loop_counter;
int loop_ready;
int loop_quit;
long long int loop_end;
void *loop1(void *ptr)
{
pthread_mutex_lock(&mutex);
while (now()<loop_end)
{
while (loop_ready) pthread_cond_wait(&cond1, &mutex);
loop_ready=1;
pthread_cond_signal(&cond2);
}
loop_quit=1;
pthread_mutex_unlock(&mutex);
return 0;
}
void *loop2(void *ptr)
{
pthread_mutex_lock(&mutex);
while (!loop_quit)
{
while (!loop_ready) pthread_cond_wait(&cond2, &mutex);
loop_ready=0;
loop_counter++;
pthread_cond_signal(&cond1);
}
pthread_mutex_unlock(&mutex);
return 0;
}
void loop_switch()
{
loop_counter=0;
loop_ready=0;
loop_quit=0;
long long int start=now();
loop_end=start+10*1000;
pthread_create(&loop1_thread, 0, &loop1, 0);
pthread_create(&loop2_thread, 0, &loop2, 0);
pthread_join(loop1_thread, 0);
pthread_join(loop2_thread, 0);
long long int end=now();
fprintf(stderr, "thread-switch time: %15.1f switch/s\\n", (float)loop_counter*1000/(end-start));
}
struct table
{
int tn;
long long int tid[16];
};
void tinit(struct table* t)
{
t->tn=0;
}
void tadd(struct table* t, long long int id)
{
t->tid[t->tn]=id;
t->tn++;
}
void tdel(struct table* t, long long int id)
{
int i;
for (i=0; i<t->tn; i++)
{
if (t->tid[i]==id)
{
t->tn--;
if (i!=t->tn) t->tid[i]=t->tid[t->tn];
break;
}
}
}
int main(int argc, char *argv[])
{
int n=1000;
pthread_spin_init(&spinlock, 0);
test("spinlock ", test_spinlock, n);
test("mutex ", test_mutex, n);
test("empty ", test_empty, n);
loop_switch();
return 0;
}
| 1
|
#include <pthread.h>
int itemCount = 0;
int totalProduced = 0;
int itemsConsumed = 0;
int queue[10*100000];
pthread_mutex_t lock;
pthread_cond_t cond;
int locked;
struct timeval tv1, tv2;
static void * consumerThread(void *arg)
{
char *s = (char *) arg;
printf("%s\\n", s);
while(itemsConsumed != 10*100000){
pthread_mutex_lock(&lock);
while(itemCount == 0){
printf("Queue is empty, consumer waiting...\\n");
pthread_cond_wait(&cond,&lock);
}
int getValue = queue[itemsConsumed];
itemCount--;
itemsConsumed++;
pthread_mutex_unlock(&lock);
}
gettimeofday(&tv2, 0);
printf ("Total time = %f seconds\\n",
(double) (tv2.tv_usec - tv1.tv_usec)/1000000 +
(double) (tv2.tv_sec - tv1.tv_sec));
exit(0);
}
static void * producerThread(void *arg)
{
int itemProduced = 0;
int i = (int *) arg;
printf("Producer %i created\\n", i);
while(itemProduced < 100000){
pthread_mutex_lock(&lock);
totalProduced++;
itemProduced++;
itemCount++;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
}
}
int main(int argc, char *argv[]) {
gettimeofday(&tv1, 0);
pthread_t c0;
pthread_t p0[9];
pthread_mutex_init(&lock, 0);
pthread_cond_init(&cond, 0);
int i;
pthread_create(&c0, 0, consumerThread, "Consumer created");
for(i = 0; i < 10; i++)
{
pthread_create(&p0[i], 0, producerThread, (void *) i);
}
pthread_join(c0, 0);
for(i = 0; i < 10; i++)
{
pthread_join(p0[i], 0);
}
}
| 0
|
#include <pthread.h>
double sum;
long thread_count;
long long n;
pthread_mutex_t mutex;
sem_t semaphore;
void * Thread_mutex_sum(void * rank) {
long my_rank = (long) rank;
double factor;
double my_sum = 0.0;
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;
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;
}
void * Thread_sem_sum(void * rank) {
long my_rank = (long) rank;
double factor;
double my_sum = 0.0;
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;
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);
}
sem_wait(&semaphore);
sum += my_sum;
sem_post(&semaphore);
return 0;
}
int main(int argc, char ** argv) {
if (argc != 3) {
printf("Invalid parameters\\n");
exit(1);
}
int mode = strtol(argv[1], 0, 10);
int power = strtol(argv[2], 0, 10);
n = (long long) pow(2.0, (double)power);
sum = 0.0;
thread_count = 16;
long i, err;
struct timeval start, end;
pthread_t * t_ids =
(pthread_t *) malloc(sizeof(pthread_t) * (thread_count - 1));
if (mode == 1) {
pthread_mutex_init(&mutex, 0);
} else {
sem_init(&semaphore, 0, 1);
}
gettimeofday(&start, 0);
for (i = 0; i < thread_count - 1; i++) {
if (mode == 1) {
err = pthread_create(&t_ids[i], 0, Thread_mutex_sum, (void *)i);
} else {
err = pthread_create(&t_ids[i], 0, Thread_sem_sum, (void *)i);
}
if (err) {
perror("Could not start thread");
exit(1);
}
}
if (mode == 1) {
Thread_mutex_sum((void *) (thread_count - 1));
} else {
Thread_sem_sum((void *) (thread_count - 1));
}
for (i = 0; i < thread_count - 1; i++) {
err = pthread_join(t_ids[i], 0);
if (err) {
perror("Could not join thread");
exit(1);
}
}
gettimeofday(&end, 0);
printf("%s thread: %2ld n: %lld est: %2.10f time: %ld\\n", mode == 1 ? "Mutex" : "Semaphore"
, thread_count, n, sum * 4,
((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec)));
return 0;
}
| 1
|
#include <pthread.h>void *graficar()
{ int i,j;
start_color();
init_pair(5,COLOR_RED,COLOR_RED);
init_pair(2,COLOR_GREEN,COLOR_GREEN);
init_pair(6,COLOR_BLUE,COLOR_BLUE);
init_pair(4,COLOR_MAGENTA,COLOR_MAGENTA);
init_pair(1,COLOR_YELLOW,COLOR_YELLOW);
init_pair(3,COLOR_CYAN,COLOR_CYAN);
init_pair(10,COLOR_BLACK,COLOR_WHITE);
init_pair(11,COLOR_BLACK,COLOR_BLACK);
while(1)
{
pthread_mutex_lock(&mutx);
move(0,0);
attron(COLOR_PAIR(10));
for(j=0;j<80;j++)
mvaddch(0,j,32);
move(0,0);
printw("NkTron \\t\\tRonda %d de %d\\t",ronda,rondas);
printw("Ud. es jugador %d, %s ",nrojugador,nombres[nrojugador-1]);
attroff(COLOR_PAIR(10));
attron(COLOR_PAIR(nrojugador));
printw("XXXXXXXX");
attroff(COLOR_PAIR(nrojugador));
move(1,0);
init_color(COLOR_BLACK,1000,0,0);
init_pair(11,COLOR_BLACK,COLOR_BLACK);
for(i=0;i<23;i++)
{ for(j=0;j<80;j++)
{ if(matriz[j][i]==0)
{
attron(COLOR_PAIR(11));
mvaddch(i+1,j,32);
attroff(COLOR_PAIR(11));
}
else
{
attron(COLOR_PAIR(matriz[j][i]));
mvaddch(i+1,j,matriz[j][i]+48 );
attroff(COLOR_PAIR(matriz[j][i]));
}
}
}
init_color(COLOR_BLACK,0,0,0);
init_pair(11,COLOR_BLACK,COLOR_BLACK);
pthread_mutex_unlock(&mutvolver);
refresh();
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int max=3;
int nbthreads=0;
void* thread_func(void* arg) {
pthread_mutex_lock(&mutex);
nbthreads++;
printf ("Nombre de threads : %d\\n",nbthreads);
pthread_mutex_unlock(&mutex);
int i, nb;
int *param;
int *lvl = (int*)arg;
pthread_t *tid;
nb = (*lvl)+1;
if (*lvl < max) {
param = (int*)malloc(sizeof(int));
*param = nb;
tid = calloc(nb, sizeof(pthread_t));
printf("%d cree %d fils\\n", (int)pthread_self(), nb);
for (i = 0; i < nb; i++) {
pthread_create((tid+i), 0, thread_func, param);
}
for (i = 0; i < nb; i++)
pthread_join(tid[i], 0);
}
if (*lvl > 1)
pthread_exit ( (void*)0);
return (void*)0;
}
int main (int argc, char** argv) {
int i;
int b[1];
b[0]=1;
pthread_t tid [1];
pthread_create (&(tid[0]),0,thread_func,b);
pthread_join (tid[0],0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
printf ("\\nFin programme principal\\n");
return 0;
}
| 1
|
#include <pthread.h>
int cubbyhole[ 3 ] = {0};
int load = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER ;
pthread_cond_t notFull = PTHREAD_COND_INITIALIZER ;
pthread_cond_t notEmpty = PTHREAD_COND_INITIALIZER ;
inline void produce() { usleep( rand() % 500000 ); }
inline void consume() { usleep( rand() % 500000 ); }
void *producer( void *args ) {
int i;
for ( i=0; i<5; i++ ) {
pthread_mutex_lock( &mutex );
while ( load == 3 )
pthread_cond_wait( ¬Full, &mutex );
produce();
load += 1;
if ( load == 1 )
pthread_cond_signal( ¬Empty );
pthread_mutex_unlock( &mutex );
}
return 0;
}
void *consumer( void *args ) {
int i;
for ( i=0; i<5; i++ ) {
pthread_mutex_lock( &mutex );
while( load == 0 )
pthread_cond_wait( ¬Empty, &mutex );
consume();
load -= 1;
pthread_cond_signal( ¬Full );
pthread_mutex_unlock( &mutex );
}
return 0;
}
int main()
{
unsigned int iseed = (unsigned int)time(0);
srand( iseed );
pthread_t produce;
pthread_t consume;
if ( pthread_create( &produce, 0, producer, 0 ) ) { printf("\\nError accured in line " "%d in file %s\\n", 89, "single-consumer.c" ); abort(); }
if ( pthread_create( &consume, 0, consumer, 0 ) ) { printf("\\nError accured in line " "%d in file %s\\n", 90, "single-consumer.c" ); abort(); }
if ( pthread_join(produce, 0) ) { printf("\\nError accured in line " "%d in file %s\\n", 92, "single-consumer.c" ); abort(); };
if ( pthread_join(consume, 0) ) { printf("\\nError accured in line " "%d in file %s\\n", 93, "single-consumer.c" ); abort(); };
pthread_mutex_destroy( &mutex );
pthread_cond_destroy ( ¬Full );
pthread_cond_destroy ( ¬Empty);
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t mutexsum;
static pthread_barrier_t barrier;
static int iteration = 1000;
static int max_thr = 1;
static int comp_A = 15;
static int comp_B = 15;
volatile int sum = 0;
volatile int finished = 0;
void stack_prefault(void)
{
unsigned char dummy[(8*1024)];
memset(&dummy, 0, (8*1024));
return;
}
unsigned long
fib(unsigned long n)
{
if (n == 0)
return 0;
if (n == 1)
return 2;
return fib(n-1)+fib(n-2);
}
void *
my_compa(void *v)
{
int i;
int compTime = (int)v;
for ( i = 0; i < iteration; i++) {
int val;
fib(compTime);
pthread_mutex_lock(&mutexsum);
val = sum ++;
pthread_mutex_unlock(&mutexsum);
}
finished = 1;
return 0;
}
void *
my_compb(void *v)
{
int compTime = (int)v;
while ( !finished ) {
int val;
fib(compTime);
pthread_mutex_lock(&mutexsum);
val = sum ++;
pthread_mutex_unlock(&mutexsum);
}
return 0;
}
static void
usage(void)
{
printf("locktest [-n threads] [-i iteration] [-a comp_A] [-b comp_B] [-h]\\n"
"-n thread: number of threads to create (default: 1)\\n"
"-i : iteration \\n");
printf("ex) % ./locktest -n 2 -i 100000 -a 0 -b 0 \\n");
exit(1);
}
int main(int argc, char *argv[])
{
struct sched_param param;
pthread_t allthr[MAX_THR];
int i;
while((i=getopt(argc, argv, "a:b:n:i:h")) != EOF) {
switch(i) {
case 'h':
usage();
return 0;
case 'n':
max_thr = atoi(optarg);
if (max_thr >= MAX_THR)
errx(1, "no more than %d threads", MAX_THR);
break;
case 'i':
iteration = atoi(optarg);
break;
case 'a':
comp_A = atoi(optarg);
break;
case 'b':
comp_B = atoi(optarg);
break;
default:
errx(1, "invalid option");
}
}
param.sched_priority = (49);
if(sched_setscheduler(0, SCHED_RR, ¶m) == -1) {
perror("sched_setscheduler failed");
}
if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
perror("mlockall failed");
}
stack_prefault();
pthread_mutex_init(&mutexsum, 0);
pthread_barrier_init(&barrier, 0, max_thr);
for(i=0; i < max_thr - 1; i++) {
pthread_create(allthr+i, 0, my_compb, (void *)comp_B);
}
my_compa((void *)comp_A);
for (i = 0; i < max_thr - 1; i++) {
pthread_join(allthr[i], 0);
}
printf("sum : %d\\n", sum);
return 0;
}
| 1
|
#include <pthread.h>
int wyniki[100];
int liczbaLiczbPierwszych;
int tablicaLiczbPierwszych[100];
pthread_mutex_t m_p;
void zapisDoTablicy(int argLiczba){
pthread_mutex_lock(&m_p);
tablicaLiczbPierwszych[liczbaLiczbPierwszych] = argLiczba;
liczbaLiczbPierwszych++;
pthread_mutex_unlock(&m_p);
}
void * f(void * i){
int liczba = *(int *)i;
if(liczba<2)
return 0;
int j;
for( j=2 ; j*j<=liczba; j++)
if( liczba % j == 0)
return 0;
zapisDoTablicy(liczba);
return 0;
}
int compare(const void *a,const void *b){
return (*(int*)a - *(int*)b);
}
int main(){
int przedzial[2];
printf("Podaj przedzial dolny\\n");
scanf("%d",&przedzial[0]);
if(przedzial[0]<=0)
przedzial[0]=1;
printf("Podaj przedzial gorny\\n");
scanf("%d",&przedzial[1]);
if(przedzial[1]<=0)
przedzial[1]=przedzial[0]+100;
void *arg[100];
pthread_t threadsArray[100];
int argumenty[100];
int k;
int i;
int iloscPrzeszukiwanychLiczb = przedzial[1] - przedzial[0] + 1;
int calkowityLicznikPrzeszukiwanychLiczb = 0;
int czesciowyLicznikPrzeszukiwanychLiczb;
for( i = przedzial[0]; i <= przedzial[1]; i=i+100){
czesciowyLicznikPrzeszukiwanychLiczb = 0;
for( k = 0;k<100; k++){
if(calkowityLicznikPrzeszukiwanychLiczb== iloscPrzeszukiwanychLiczb)
break;
argumenty[k]=i+k;
arg[k]= &argumenty[k];
pthread_create(&threadsArray[k],0,f,arg[k]);
czesciowyLicznikPrzeszukiwanychLiczb++;
calkowityLicznikPrzeszukiwanychLiczb++;
}
for( k = 0;k<100;k++){
if(czesciowyLicznikPrzeszukiwanychLiczb == k)
break;
pthread_join(threadsArray[k],0);
}
if(calkowityLicznikPrzeszukiwanychLiczb==iloscPrzeszukiwanychLiczb)
break;
}
qsort(tablicaLiczbPierwszych,liczbaLiczbPierwszych,sizeof(int),compare);
for( i = 0; i < liczbaLiczbPierwszych; i++)
printf("Liczba nr %d = %d\\n", i, tablicaLiczbPierwszych[i]);
return 0;
}
| 0
|
#include <pthread.h>
extern void thread_join_int(pthread_t tid, int *rval_pptr);
extern int My_pthread_create(pthread_t *tidp, const pthread_attr_t *attr, void *(*start_rtn)(void *), void *arg);
int My_pthread_cancel(pthread_t tid)
{
int result=pthread_cancel(tid);
if(0!=result)
{
printf("thread(0x%x) call pthread_cancel(0x%x) failed,because %s\\n",
pthread_self(),tid,strerror(result));
}else
{
printf("thread(0x%x) call pthread_cancel(0x%x) ok\\n",
pthread_self(),tid);
}
return result;
}
static pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
static void* thread_func_return (void* arg)
{
pthread_mutex_lock(&mutex);
printf("\\n****** Begin Thread_Return:thread id=0x%x ******\\n",pthread_self());
printf("arg is %d\\n",arg);
printf("****** End Thread_Return:thread id=0x%x ******\\n\\n",pthread_self());
pthread_mutex_unlock(&mutex);
return arg;
}
static void* thread_func_exit (void* arg)
{
pthread_mutex_lock(&mutex);
printf("\\n****** Begin Thread_Exit:thread id=0x%x ******\\n",pthread_self());
printf("arg is %d\\n",arg);
sleep(3);
printf("****** End Thread_Exit:thread id=0x%x ******\\n\\n",pthread_self());
pthread_mutex_unlock(&mutex);
pthread_exit(arg);
}
void test_thread_quit()
{
M_TRACE("--------- Begin test_thread_quit() ---------\\n");
pthread_mutex_lock(&mutex);
pthread_t threads[3];
My_pthread_create(threads+0,0,thread_func_return,(void*)0);
My_pthread_create(threads+1,0,thread_func_exit,(void*)1);
My_pthread_create(threads+2,0,thread_func_exit,(void*)2);
pthread_mutex_unlock(&mutex);
My_pthread_cancel(threads[2]) ;
int values[3];
for(int i=0;i<3;i++)
{
thread_join_int(threads[i],values+i);
}
M_TRACE("--------- End test_thread_quit() ---------\\n\\n");
}
| 1
|
#include <pthread.h>
pthread_t tCentral;
pthread_t * tUads;
pthread_mutex_t mutexes[5 * 2] = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t m_archivo = PTHREAD_MUTEX_INITIALIZER;
void * centralCtrl(void *);
void * threadCtrl(void *);
void cambio(int);
void cambioCritico(int);
FILE * datos;
int medidas[5];
int alarmas[5];
int main(void)
{
srand(time(0));
tUads = (pthread_t*)malloc(sizeof(pthread_t) * 5);
for (int i = 0; i < 5; i++)
pthread_create(tUads + i, 0, threadCtrl, i);
pthread_create(&tCentral, 0, centralCtrl, 0);
for (int i = 0; i < 5; i++)
pthread_join(*(tUads + i), 0);
pthread_join(tCentral, 0);
free(tUads);
return 0;
}
void * threadCtrl(void * arg)
{
int temp;
while (1)
{
sleep(rand() % 3 + 1);
pthread_mutex_lock(&(*(mutexes + (int)arg)));
medidas[(int)arg] = rand() % 10;
pthread_mutex_unlock(&(*(mutexes + (int)arg)));
if (!(temp = rand() % 10))
{
printf("Uad (%d) :: Valor critico, alarma enviada\\n", (int)arg);
pthread_mutex_lock(mutexes + (int)arg + 5);
alarmas[(int)arg]++;
pthread_kill(tCentral, SIGUSR1);
pthread_mutex_unlock(mutexes + (int)arg + 5);
}
}
pthread_exit(0);
}
void * centralCtrl(void * arg)
{
signal(SIGALRM, cambio);
signal(SIGUSR1, cambioCritico);
alarm(rand() % 5);
while (1)
;
pthread_exit(0);
}
void cambio(int ids)
{
printf("Tomando registros\\n");
for (int i = 0; i < 5; i++)
{
pthread_mutex_lock(mutexes + i);
pthread_mutex_lock(&m_archivo);
datos = fopen("datos", "a+");
fprintf(datos, "Uad (%d) :: medida %d\\n", i, medidas[i]);
fclose(datos);
pthread_mutex_unlock(&m_archivo);
pthread_mutex_unlock(mutexes + i);
alarm(rand() % 5);
}
printf("Cerrando archivo\\n");
}
void cambioCritico(int ids)
{
for (int i = 0; i < 5; i++)
{
pthread_mutex_lock(mutexes + 5 + i);
if (alarmas[i])
{
pthread_mutex_lock(&m_archivo);
datos = fopen("datos", "a+");
fprintf(datos, "Uad (%d) :: valor critico\\n", i);
fclose(datos);
pthread_mutex_unlock(&m_archivo);
alarmas[i]--;
}
pthread_mutex_unlock(mutexes + 5 + i);
}
}
| 0
|
#include <pthread.h>
int
srvInitNetTCPPort (unsigned short portnumber)
{
int retval = 0;
struct sockaddr_in myaddr;
int sockfd = 0;
sockfd = socket (AF_INET, SOCK_STREAM, 0 );
if (sockfd < 0)
{
perror ("Unable to create stream socket ");
return -1;
}
bzero ((char *)&myaddr, sizeof(myaddr));
myaddr.sin_family = AF_INET;
myaddr.sin_port = htons (portnumber);
myaddr.sin_addr.s_addr = htonl (INADDR_ANY);
retval = bind (sockfd, (struct sockaddr *)&myaddr, sizeof(myaddr));
if ( retval < 0 )
{
perror ("Unable to bind socket");
return -1;
}
retval = listen (sockfd, 10);
if ( retval < 0 )
{
perror ("Unable to listen on socket");
return -1;
}
return (sockfd);
}
unsigned long
ResolveDNS(char *hostname, int *herror)
{
char fn[] = "ResolveDNS():";
static time_t dns_failed = 0;
static pthread_mutex_t dnsFailedMutex = PTHREAD_MUTEX_INITIALIZER;
int addr_type;
struct hostent hostentry, *hostp;
char buffer[256];
long ipaddr;
char *hostname2;
if((addr_type = DetermineAddrType(hostname)) == IPADDR)
{
return(ntohl(inet_addr(hostname)));
}
else
{
if(!dns_failed)
{
_retry:
switch(addr_type)
{
case HOSTNAME:
case ABS_DN:
hostp = nx_gethostbyname_r(hostname, &hostentry, buffer, 256, herror);
break;
case DN:
if((hostname2 = malloc(strlen(hostname) + 2)) != 0)
{
sprintf(hostname2, "%s.", hostname);
hostp = nx_gethostbyname_r(hostname2, &hostentry, buffer, 256, herror);
free(hostname2);
}
else
{
NETERROR(MFIND, ("%s malloc failed\\n", fn));
*herror = NO_RECOVERY;
return -1;
}
break;
default:
NETERROR(MFIND, ("%s invalid addr type\\n", fn));
*herror = NO_RECOVERY;
return -1;
}
if (hostp)
{
ipaddr = ntohl(*(int *)hostp->h_addr_list[0]);
}
else
{
ipaddr = -1;
if(*herror == TRY_AGAIN || *herror == NO_RECOVERY)
{
NETERROR(MFIND, ("%s DNS failed\\n", fn));
pthread_mutex_lock(&dnsFailedMutex);
dns_failed = time(0) + dns_recovery_timeout;
pthread_mutex_unlock(&dnsFailedMutex);
}
}
return ipaddr;
}
else
{
if(difftime(dns_failed, time(0)) > 0)
{
*herror = TRY_AGAIN;
return -1;
}
else
{
pthread_mutex_lock(&dnsFailedMutex);
dns_failed = 0;
pthread_mutex_unlock(&dnsFailedMutex);
goto _retry;
}
}
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
int value;
}SharedInt;
sem_t sem;
SharedInt* sip;
void *functionWithCriticalSection(int* v2) {
pthread_mutex_lock(&(sip->lock));
sip->value = sip->value + *v2;
if(sip->value = 1) {
pthread_mutex_unlock(&(sip->lock));
printf("Value is currently: %i\\n", sip->value);
pthread_mutex_lock(&(sip->lock));
}
pthread_mutex_unlock(&(sip->lock));
sem_post(&sem);
}
int main() {
sem_init(&sem, 0, 0);
SharedInt si;
sip = &si;
sip->value = 0;
int v2 = 1;
pthread_mutex_init(&(sip->lock), 0);
pthread_t thread1;
pthread_t thread2;
pthread_create (&thread1,0,functionWithCriticalSection,&v2);
pthread_create (&thread2,0,functionWithCriticalSection,&v2);
sem_wait(&sem);
sem_wait(&sem);
pthread_mutex_destroy(&(sip->lock));
sem_destroy(&sem);
printf("%d\\n", sip->value);
return sip->value-2;
}
| 0
|
#include <pthread.h>
int somme_val=0;
int nbre_thread=0;
int signal_envoye=0;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
void *print_thread(){
pthread_mutex_lock(&mutex);
if(signal_envoye==0){
pthread_cond_wait(&cond, &mutex);
}
printf("La valeur générée est %d\\n", somme_val);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void *thread_rand(void *arg) {
int *pt=(int*)arg;
int random_val;
random_val=(int) (10*((double)rand())/32767);
*pt=*pt*2;
pthread_mutex_lock(&mutex);
somme_val+=random_val;
nbre_thread++;
printf("Argument recu : %d, thread_id : %d, random_val : %d\\n", *pt, (int)pthread_self(), random_val);
if(nbre_thread==10){
pthread_cond_signal(&cond);
signal_envoye++;
}
pthread_mutex_unlock(&mutex);
pthread_exit(pt);
}
int main(int argc, char ** argv){
pthread_t tid[10 +1];
pthread_attr_t attr;
int i,res=0;
int* status;
int* pt_ind;
if(pthread_create(&(tid[0]), 0, print_thread, 0)){
printf("pthread_create\\n"); exit(1);
}
for (i=1;i<10 +1;i++) {
pt_ind=(int*)malloc(sizeof(i));
*pt_ind=i;
if (pthread_create(&tid[i],0,thread_rand,(void *)pt_ind)!=0) {
printf("ERREUR:creation\\n");
exit(1);
}
}
for (i=1;i<10 +1;i++) {
if(pthread_join(tid[i],(void **)&status)!=0) {
printf("ERREUR:joindre\\n");
exit(2);
}
else {
printf("Thread %d se termine avec status %d.\\n",i,*status);
res=res+*status;
}
}
if(pthread_join(tid[0], (void**)&status)!=0){
printf("pthread_join");exit(1);
}
else{
printf("Thread %d fini\\n", i);
}
printf("La somme est %d\\n",somme_val);
printf("La valeur renvoyée est %d\\n",res);
return 0;
}
| 1
|
#include <pthread.h>
int *count;
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
struct timeval tv1, tv2;
struct timezone tz1, tz2;
int *duration;
void *inc_count(void *idp)
{
int j,i;
double result=0.0;
for (i=0; i<150; i++) {
pthread_mutex_lock(&count_mutex);
(*count)++;
if (*count == 140) {
gettimeofday(&tv2, &tz2);
*duration = 1000000*(tv2.tv_sec - tv1.tv_sec)+tv2.tv_usec -tv1.tv_usec;
pthread_cond_signal(&count_threshold_cv);
}
pthread_mutex_unlock(&count_mutex);
for (j=0; j<1000000; j++)
result = result + j;
}
pthread_exit(0);
}
void *watch_count(void *idp)
{
pthread_mutex_lock(&count_mutex);
if (*count<140) {
pthread_cond_wait(&count_threshold_cv, &count_mutex);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main (int argc, char *argv[])
{
int i, rc;
pthread_t threads[3];
count = (int *)malloc(sizeof(int));
*count = 0;
duration = (int *)malloc(sizeof(int));
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
gettimeofday(&tv1, &tz1);
for(i=0;i<3 -1;i++)
pthread_create(&threads[i], 0, inc_count, 0);
pthread_create(&threads[3 -1], 0, watch_count, 0);
for (i=0; i<3; i++) {
pthread_join(threads[i], 0);
}
printf("copy time %d usec \\n", *duration);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
}
| 0
|
#include <pthread.h>
int numThreads=0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void * writeFile(void * fname)
{
pthread_mutex_lock(&mutex);
int threadNum = numThreads++;
pthread_mutex_unlock(&mutex);
int writeCnt=0;
FILE *f = fopen( (char*)fname, "wt" );
if ( !f )
{
fprintf( stderr, "Thread %d unable to open file %s\\n",threadNum, (char*)fname );
pthread_exit( (void*) -1 );
}
while (writeCnt<2000)
{
char value = symbols[threadNum];
fprintf(f, "%c", value);
printf("%c", value);
writeCnt++;
}
fclose( f);
return (void*)writeCnt;
}
int main(int argc, char ** argv)
{
int ids[4];
void* readCnts[4];
pthread_t threads[4];
for( int i=0 ; i<4 ; i++)
ids[i] = pthread_create(&threads[i], 0, writeFile, (void *)argv[i+1]);
for( int i=0 ; i<4 ; i++)
pthread_join( threads[i], &readCnts[i] );
printf("\\n\\n");
for (int i=0 ; i < 4 ; ++i )
printf( "Thread %d wrote %d '%c' symbols to file %s\\n", i+1, (int)readCnts[i], symbols[i], argv[i+1] );
return 0;
}
| 1
|
#include <pthread.h>
{
double *a;
double *b;
double sum;
int veclen;
} DOTDATA;
DOTDATA dotstr;
pthread_t callThd[2];
pthread_mutex_t mutexsum;
double wallTime()
{
struct timeval tv;
gettimeofday(&tv, 0);
return tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0;
}
void* dotprod(void *arg)
{
int i, start, end, offset, len ;
double mysum, *x, *y;
offset = (int)arg;
len = dotstr.veclen;
len = len / 2;
start = offset*len;
end = start + len;
x = dotstr.a;
y = dotstr.b;
mysum = 0;
for (i=start; i<end ; i++)
{
mysum += (x[i] * y[i]);
}
printf ("offset %d mysum %f\\n", offset, mysum);
pthread_mutex_lock (&mutexsum);
dotstr.sum += mysum;
pthread_mutex_unlock (&mutexsum);
pthread_exit((void*)0);
}
main (int argc, char* argv[])
{
int i;
double *a, *b;
int status;
int ret;
double start, end;
a = (double*) malloc (1000000*sizeof(double));
b = (double*) malloc (1000000*sizeof(double));
for (i=0; i<1000000; i++)
{
a[i]=1;
b[i]=a[i];
}
dotstr.veclen = 1000000;
dotstr.a = a;
dotstr.b = b;
dotstr.sum=0;
pthread_mutex_init(&mutexsum, 0);
start = wallTime();
for (i = 0; i<2; i++){
ret = pthread_create(&callThd[i], 0, dotprod, (void *)i);
if (ret) printf("Error in thread create \\n");
if (ret) printf("ret = %d i = %d \\n", ret, i);
}
for (i = 0; i<2; i++){
ret = pthread_join(callThd[i], 0);
if (ret) printf("Error in thread join \\n");
if (ret) printf("ret = %d i = %d \\n", ret, i);
}
end = wallTime();
printf ("Runtime = %f msecs \\n", end - start);
printf ("Sum = %f \\n", dotstr.sum);
free (a);
free (b);
pthread_mutex_destroy(&mutexsum);
pthread_exit (0);
}
| 0
|
#include <pthread.h>
volatile long double pi = 0.0;
pthread_mutex_t piLock;
long double intervals;
int numThreads;
void *computePI(void *id)
{
long double x,
width,
localSum = 0;
int i,
threadID = *((int*)id);
width = 1.0 / intervals;
for(i = threadID ; i < intervals; i += numThreads) {
x = (i+0.5) * width;
localSum += 4.0 / (1.0 + x*x);
}
localSum *= width;
pthread_mutex_lock(&piLock);
pi += localSum;
pthread_mutex_unlock(&piLock);
return 0;
}
int main(int argc, char **argv)
{
pthread_t *threads;
void *retval;
int *threadID;
int i;
if (argc == 3) {
intervals = atoi(argv[1]);
numThreads = atoi(argv[2]);
threads = malloc(numThreads*sizeof(pthread_t));
threadID = malloc(numThreads*sizeof(int));
pthread_mutex_init(&piLock, 0);
for (i = 0; i < numThreads; i++) {
threadID[i] = i;
pthread_create(&threads[i], 0, computePI, threadID+i);
}
for (i = 0; i < numThreads; i++) {
pthread_join(threads[i], &retval);
}
printf("Estimation of pi is %32.30Lf \\n", pi);
printf("(actual pi value is 3.141592653589793238462643383279...)\\n");
} else {
printf("Usage: ./a.out <numIntervals> <numThreads>");
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t the_mutex;
pthread_cond_t condp,condc;
int buffer=0;
void* producer(void *ptr)
{
int i;
for(i=1;i<=10;i++)
{ pthread_mutex_lock(&the_mutex);
while(buffer!=0)
pthread_cond_wait(&condp,&the_mutex);
buffer=i;
printf("Producer %d \\n",i);
pthread_cond_signal(&condc);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
void* consumer(void *ptr)
{ int i;
for(i=1;i<=10;i++)
{ pthread_mutex_lock(&the_mutex);
while(buffer==0)
pthread_cond_wait(&condc,&the_mutex);
buffer=0;
printf("Consumer %d \\n",i);
pthread_cond_signal(&condp);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
int main(void)
{ pthread_t pro,con;
pthread_mutex_init(&the_mutex,0);
pthread_cond_init(&condc,0);
pthread_cond_init(&condp,0);
pthread_create(&pro,0,producer,0);
pthread_create(&con,0,consumer,0);
pthread_join(pro,0);
pthread_join(con,0);
pthread_mutex_destroy(&the_mutex);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
}
| 0
|
#include <pthread.h>
unsigned int TEST_VALUE_RA[2 * 8][3];
int VT_mc13783_RA_setup(void) {
int rv = TFAIL;
rv = TPASS;
return rv;
}
int VT_mc13783_RA_cleanup(void) {
int rv = TFAIL;
rv = TPASS;
return rv;
}
int VT_mc13783_test_RA(void) {
int rv = TPASS, fd, i = 0, val;
srand((unsigned)time(0));
fd = open(MC13783_DEVICE, O_RDWR);
if (fd < 0) {
pthread_mutex_lock(&mutex);
tst_resm(TFAIL, "Unable to open %s", MC13783_DEVICE);
pthread_mutex_unlock(&mutex);
return TFAIL;
}
for (i = 0; i < 8; i++) {
val = rand() % 2;
switch (val) {
case 0:
TEST_VALUE_RA[i][0] = CMD_WRITE;
TEST_VALUE_RA[i][1] = rand() % REG_NB;
TEST_VALUE_RA[i][2] = rand() % 0xFFFFFF;
TEST_VALUE_RA[8 + i][0] = CMD_READ;
TEST_VALUE_RA[8 + i][1] =
rand() % REG_NB;
TEST_VALUE_RA[8 + i][2] =
rand() % 0xFFFFFF;
break;
case 1:
TEST_VALUE_RA[i][0] = CMD_SUB;
TEST_VALUE_RA[i][1] = rand() % EVENT_NB;
TEST_VALUE_RA[i][2] = 0;
TEST_VALUE_RA[8 + i][0] = CMD_UNSUB;
TEST_VALUE_RA[8 + i][1] =
rand() % EVENT_NB;
TEST_VALUE_RA[8 + i][2] = 0;
break;
}
}
for (i = 0; i < 2 * 8; i++) {
if (VT_mc13783_opt
(fd, TEST_VALUE_RA[i][0], TEST_VALUE_RA[i][1],
&(TEST_VALUE_RA[i][2])) != TPASS) {
rv = TFAIL;
}
}
if (close(fd) < 0) {
pthread_mutex_lock(&mutex);
tst_resm(TFAIL, "Unable to close file descriptor %d",
fd);
pthread_mutex_unlock(&mutex);
return TFAIL;
}
return rv;
}
| 1
|
#include <pthread.h>
double *_vector;
double _final_sum;
int *_ranges;
pthread_mutex_t _mutex;
double sum(double* vector, int a, int b) {
double sum = 0.0;
int i = 0;
for (i=a; i<b; i++)
sum += vector[i];
return sum;
}
void* sum_and_add(void* arg) {
int *range_a = (int*) arg;
double range_sum = sum(_vector, range_a[0], range_a[1]);
pthread_mutex_lock(&_mutex);
printf("Dodaję %g\\n", range_sum);
_final_sum += range_sum;
pthread_mutex_unlock(&_mutex);
}
int read_vector_from_file(char *file_name) {
int n = 0;
FILE* f = fopen(file_name, "r");
char buffer[80 +1];
fgets(buffer, 80, f);
n = atoi(buffer);
if(n == 0) {
perror("Nie udało się pobrać liczby elementów wektora\\n");
exit(1);
}
printf("Wektor ma %d elementów\\n", n);
prepare_vector(n);
int i;
for(i=0; i<n; i++) {
fgets(buffer, 80, f);
_vector[i] = atof(buffer);
}
fclose(f);
return n;
}
int prepare_vector(int n) {
size_t size = sizeof(double) * n;
_vector = (double*) malloc(size);
if (!_vector) {
perror("malloc in vector");
exit(1);
}
return 0;
}
int prepare_ranges(int n){
size_t size = sizeof(int) * (5 + 1);
_ranges = (int*)malloc(size);
if(!_ranges) {
perror("malloc in ranges");
return 1;
}
int i;
int dn = n/5;
for(i=0; i<5; i++) {
_ranges[i] = i*dn;
}
_ranges[5] = n;
return 0;
}
void clean() {
free(_vector);
free(_ranges);
}
int main(int argc, char **argv) {
int i, n;
_mutex = PTHREAD_MUTEX_INITIALIZER;
_final_sum = 0;
pthread_t threads[5];
n = read_vector_from_file("vector.dat");
prepare_ranges(n);
printf("Suma początkowa: %g\\n", _final_sum);
for (i = 0; i < 5; i++) {
if(pthread_create(&threads[i], 0, &sum_and_add, &_ranges[i]) != 0) {
clean();
perror("Blad podczas tworzenia watku!\\n");
exit(1);
}
}
for (i = 0; i < 5; i++) {
if(pthread_join(threads[i], 0) != 0) {
clean();
printf("Blad podczas czekania na watek %d!\\n", i);
exit(1);
}
}
clean();
printf("Suma końcowa: %g\\n", _final_sum);
return 0;
}
| 0
|
#include <pthread.h>
extern pthread_mutex_t userslock;
void *free_userperm(struct proxy_user *pu) {
struct proxy_user *next_pu;
while( pu ) {
next_pu = pu->next;
free( pu );
pu = next_pu;
}
return 0;
}
void *add_userperm(char* username, char *userspec, struct proxy_user **pu) {
int ccount = 0;
struct proxy_user *user;
char *s;
user = malloc(sizeof(struct proxy_user));
if ( !user ) {
fprintf(stderr, "Failed to allocate user credentials: %s\\n", strerror(errno));
exit(1);
}
memset(user, 0, sizeof (struct proxy_user) );
s = userspec;
strncpy(user->username, username, sizeof(user->username)-1 );
do {
if ( *s == ',' ) {
ccount++;
continue;
}
switch(ccount) {
case 0:
strncat(user->secret, s, 1);
break;
case 1:
strncat(user->channel, s, 1);
break;
case 2:
strncat(user->ocontext, s, 1);
break;
case 3:
strncat(user->icontext, s, 1);
break;
}
} while (*(s++));
user->next = *pu;
*pu = user;
return 0;
}
void *processperm(char *s, struct proxy_user **pu) {
char name[80],value[80];
int nvstate = 0;
memset (name,0,sizeof name);
memset (value,0,sizeof value);
do {
*s = tolower(*s);
if ( *s == ' ' || *s == '\\t')
continue;
break;
if ( *s == '=' ) {
nvstate = 1;
continue;
}
if (!nvstate)
strncat(name, s, 1);
else
strncat(value, s, 1);
} while (*(s++));
if (debug)
debugmsg("perm: %s, %s", name, value);
add_userperm(name,value,pu);
return 0;
}
int ReadPerms() {
FILE *FP;
char buf[1024];
char cfn[80];
struct proxy_user *pu;
pu=0;
sprintf(cfn, "%s/%s", PDIR, PFILE);
FP = fopen( cfn, "r" );
if ( !FP )
{
fprintf(stderr, "Unable to open permissions file: %s/%s!\\n", PDIR, PFILE);
exit( 1 );
}
if (debug)
debugmsg("config: parsing configuration file: %s", cfn);
while ( fgets( buf, sizeof buf, FP ) ) {
processperm(buf,&pu);
}
fclose(FP);
pthread_mutex_lock(&userslock);
free_userperm(pc.userlist);
pc.userlist=pu;
pthread_mutex_unlock(&userslock);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_t main_id;
static pthread_t first_id;
static pthread_t second_id;
static pthread_mutex_t mymutex;
static int sum;
static void *body1(void)
{
int adder=2;
while(sum<300)
{
usleep(100);
pthread_mutex_lock(&mymutex);
sum+=adder;
printf("thread 1 add 2 to sum\\n");
printf("sum=%d\\n",sum);
pthread_mutex_unlock(&mymutex);
}
return 0;
}
static void *body2(void)
{
int adder=3;
while(sum<300)
{
usleep(100);
pthread_mutex_lock(&mymutex);
sum+=adder;
printf("thread 2 add 3 to sum\\n");
printf("sum=%d\\n",sum);
pthread_mutex_unlock(&mymutex);
}
return 0;
}
int main(int argc, char *argv[])
{
pthread_attr_t myattr1;
pthread_attr_t myattr2;
pthread_mutexattr_t mymutexattr;
struct sched_param param;
param.sched_priority=99;
main_id = pthread_self();
pthread_setschedparam(main_id,SCHED_RR,¶m);
puts("main: before pthread_create\\n");
struct sched_param param2;
param2.sched_priority = 10;
struct sched_param param3;
param3.sched_priority = 10;
pthread_attr_init(&myattr2);
pthread_attr_init(&myattr1);
pthread_attr_setinheritsched(&myattr1, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setinheritsched(&myattr2, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setschedpolicy(&myattr1,SCHED_RR);
pthread_attr_setschedpolicy(&myattr2, SCHED_RR);
pthread_attr_setschedparam(&myattr1, ¶m2);
pthread_attr_setschedparam(&myattr2, ¶m3);
pthread_mutexattr_init(&mymutexattr);
pthread_mutex_init(&mymutex, &mymutexattr);
pthread_mutexattr_destroy(&mymutexattr);
pthread_create(&first_id, &myattr1, body1, 0);
pthread_create(&second_id, &myattr2, body2, 0);
pthread_attr_destroy(&myattr1);
pthread_attr_destroy(&myattr2);
pthread_join(first_id, 0);
pthread_join(second_id,0);
printf("main: after pthread_create\\n");
return 0;
}
| 0
|
#include <pthread.h>
struct list {
int data;
pthread_mutex_t lock;
struct list *next;
};
pthread_mutex_t global_lock;
struct list *shared = 0;
void *run(void *arg) {
struct list *cur;
pthread_mutex_lock(&global_lock);
for (cur = shared; cur; cur = cur->next) {
int *data = &cur->data;
struct list *next = cur->next;
cur->next = next;
pthread_mutex_unlock(&global_lock);
pthread_mutex_lock(&cur->lock);
(*data)++;
pthread_mutex_unlock(&cur->lock);
pthread_mutex_lock(&global_lock);
}
pthread_mutex_unlock(&global_lock);
return 0;
}
int main() {
pthread_t t1, t2;
int i;
pthread_mutex_init(&global_lock, 0);
for (i = 0; i < 42; i++) {
struct list *new = (struct list *) malloc(sizeof(struct list));
new->next = shared;
pthread_mutex_init(&new->lock, 0);
shared = new;
}
pthread_create(&t1, 0, run, 0);
pthread_create(&t2, 0, run, 0);
return 1;
}
| 1
|
#include <pthread.h>
double *arrayA;
double *arrayB;
double sumResult = 0;
pthread_mutex_t sb;
void *dot_product(void *tid)
{
long int thid;
int i;
double sumloc = 0;
thid = (long int) tid;
for(i=thid; i<10000000; i+=1)
{
sumloc += arrayA[i]*arrayB[i];
}
printf("\\nthread=%ld,\\tsoma local=%.0f\\n", thid, (float)sumloc);
pthread_mutex_lock(&sb);
sumResult += sumloc;
pthread_mutex_unlock(&sb);
}
int main(void)
{
pthread_t t[1];
int i, tmili;
long int th;
struct timeval inicio, final2;
srand(time(0));
arrayA = (double*) malloc(10000000*sizeof(double));
arrayB = (double*) malloc(10000000*sizeof(double));
for(i=0; i<10000000; i++)
{
arrayA[i] = (double) (rand()%(10 -1))+1;
arrayB[i] = (double) (rand()%(10 -1))+1;
}
gettimeofday(&inicio, 0);
for(th=0; th<1; th++)
{
pthread_create(&t[th], 0, &dot_product, (void *) th);
}
for(th=0; th<1; th++)
{
pthread_join(t[th],0);
}
gettimeofday(&final2, 0);
tmili = (int) (1000 * (final2.tv_sec - inicio.tv_sec) + (final2.tv_usec - inicio.tv_usec) / 1000);
printf("\\n\\ntempo decorrido: %d milisegundos\\n", tmili);
printf("\\nresultado do produto escalar=%g\\n\\n",sumResult);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t chopsticks[5];
void printhelpertabs(int n)
{
int i;
for(i=0; i<n ;i++)
{
printf("\\t");
}
}
void * eat(void *arg)
{
int id = (int)arg;
int eatcount = 0;
int chopsticknum1,chopsticknum2;
while(eatcount < 2)
{
if(id ==0)
{
chopsticknum1 = 5 -1;
}
else
{
chopsticknum1 = id;
}
printhelpertabs(id);printf("Philosopher %d is reaching for first chop stick %d.\\n",id,chopsticknum1);
pthread_mutex_lock(&chopsticks[chopsticknum1]);
printhelpertabs(id);printf("Philosopher %d got first chop stick %d.\\n",id,chopsticknum1);
if(id ==0)
{
chopsticknum2 = 0;
}
else
{
chopsticknum2 = id -1;
}
printhelpertabs(id);printf("Philosopher %d is reaching for second chop stick %d.\\n",id,chopsticknum2);
pthread_mutex_lock(&chopsticks[chopsticknum2]);
printhelpertabs(id);printf("Philosopher %d got second chop stick %d.\\n",id,chopsticknum2);
printhelpertabs(id);printf("Philosopher %d is getting the nom on.\\n",id);
sleep(1);
printhelpertabs(id);printf("Philosopher %d put down first chop stick %d.\\n",id,chopsticknum1);
pthread_mutex_unlock(&chopsticks[chopsticknum1]);
printhelpertabs(id);printf("Philosopher %d put down second chop stick %d.\\n",id,chopsticknum2);
pthread_mutex_unlock(&chopsticks[chopsticknum2]);
eatcount++;
}
}
int main(int argc, char** argv)
{
printf("Tab levels are there to help pick out actions of certain philosophers.\\n");
printf("(Not perfect because there are no locks on printing but slightly helpful)\\n");
pthread_t threads[5];
int i;
for(i = 0; i < 5; ++i)
{
pthread_mutex_init(&chopsticks[i], 0);
}
for(i = 0; i < 5; ++i)
{
if(pthread_create(&threads[i], 0, &eat, (void*)i))
{
printf("Could not create thread %d\\n", i);
return -1;
}
}
for(i = 0; i < 5; ++i)
{
if(pthread_join(threads[i], 0))
{
printf("Could not join thread %d\\n", i);
return -1;
}
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int running = 1;
void signal_handler(int sig)
{
printf( "Signal caught - cleaning up and exiting..\\n" );
running = 0;
}
void *ledControl(void *ptr)
{
struct pollfd fdset[1];
int button_fd, rc;
char buf[64];
unsigned int green_led, red_led, button;
int len, *led_color;
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
if (ptr==0)
perror("ledControl called with null pointer");
led_color = (int *) ptr;
green_led = 49;
red_led = 48;
button = 60;
gpio_export(green_led);
gpio_export(red_led);
gpio_export(button);
gpio_set_dir(green_led, "out");
gpio_set_dir(red_led, "out");
gpio_set_dir(button, "in");
gpio_set_edge(button, "rising");
button_fd = gpio_fd_open(button, O_RDONLY);
while (running) {
memset((void*)fdset, 0, sizeof(fdset));
fdset[0].fd = button_fd;
fdset[0].events = POLLPRI;
rc = poll(fdset, 1, 500);
if (rc < 0) {
printf("\\npoll() failed!\\n");
exit(-1);
}
if ((rc == 0) && DEBUG) {
printf(".");
}
if (fdset[0].revents & POLLPRI) {
lseek(fdset[0].fd, 0, 0);
len = read(fdset[0].fd, buf, 64);
if(DEBUG)
printf("\\npoll() GPIO %d interrupt occurred, value=%c, len=%d\\n",
button, buf[0], len);
pthread_mutex_lock( &mutex1 );
*led_color=GREEN;
pthread_mutex_unlock( &mutex1 );
gpio_set_value(red_led, 0);
}
if (*led_color == GREEN)
gpio_set_value(green_led, 1);
if (*led_color == RED)
gpio_toggle(red_led);
fflush(stdout);
}
gpio_fd_close(button_fd);
gpio_set_value(red_led, 0);
gpio_set_value(green_led, 0);
exit(0);
return 0;
}
| 0
|
#include <pthread.h>
int G_CHUNK_SIZE = 1000;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
large_uint G_current_start;
large_uint G_subset_count;
int G_terminated_flag = 0;
large_uint G_steps = 0;
void increment_step() {
pthread_mutex_lock(&mutex);
G_steps++;
pthread_mutex_unlock(&mutex);
}
struct solution {
large_int* subset;
int size;
};
large_uint get_next_start() {
pthread_mutex_lock(&mutex);
large_uint start = G_current_start;
G_current_start = start + G_CHUNK_SIZE;
pthread_mutex_unlock(&mutex);
return start;
}
void print_set(large_int* set, int size, FILE* out) {
int i;
fprintf(out, "{");
for (i = 0; i < size; i++) {
if (i > 0) {
fprintf(out, ", ");
}
fprintf(out, "%lld", set[i]);
}
fprintf(out, "}\\n");
}
large_int* generate_subset(large_int* set, large_uint elements, int* subset_size) {
large_uint max_elements = (log(elements) / log(2)) + 1;
large_int* subset = malloc(sizeof(large_int) * max_elements);
int i;
int current_index = 0;
for (i = 0; i < max_elements; i++) {
large_uint val = (elements >> i) & 1;
if (val == 1) {
subset[current_index] = set[i];
current_index++;
}
}
*subset_size = current_index;
return subset;
}
large_int calculate_set_sum(large_int* set, int size) {
large_int sum = 0;
int i;
for (i = 0; i < size; i++) {
sum += set[i];
}
return sum;
}
void* find_zero_subset(void* data) {
large_int* set = (large_int*) data;
while (1) {
large_uint start = get_next_start();
large_uint i;
for (i = start; i < start + G_CHUNK_SIZE; i++) {
if (i >= G_subset_count || G_terminated_flag == 1) {
return 0;
}
int size;
large_int* subset = generate_subset(set, i, &size);
large_int sum = calculate_set_sum(subset, size);
if (sum == 0) {
struct solution* sol = (struct solution*) malloc(sizeof(struct solution));
sol->subset = subset;
sol->size = size;
printf("Solution found!\\n");
pthread_mutex_lock(&mutex);
G_terminated_flag = 1;
pthread_mutex_unlock(&mutex);
return ((void*) sol);
}
free(subset);
}
}
return 0;
}
large_int* generate_set(unsigned int set_size, large_int range) {
int i;
large_int* set = malloc(sizeof(large_int) * set_size);
for (i = 0; i < set_size; i++) {
double val = (((double) pcg32_boundedrand(range)) / (range / 2.0)) - 1;
printf("%.5f\\n", val);
large_int value = val * range;
set[i] = value;
}
return set;
}
int main(int argc, char** argv) {
if (argc < 3) {
fprintf(stderr, "Not enough arguments.\\n");
fprintf(stderr, "Usage: setsum <thread count> <set size>\\n");
return 1;
}
int rounds = atoi(argv[0]);
pcg32_srandom(time(0), (intptr_t) &rounds);
int num_threads = atoi(argv[1]);
int set_size = atoi(argv[2]);
large_int range = pow(2, set_size / 2);
pthread_t threads[num_threads];
if (0) {
set_size = 7;
}
clock_t start = clock();
large_int* set = generate_set(set_size, range);
print_set(set, set_size, stdout);
G_subset_count = pow(2, set_size);
G_current_start = 1;
int i;
for (i = 0; i < num_threads; i++) {
pthread_create(&threads[i], 0, find_zero_subset, (void*) set);
}
struct solution* sol = 0;
for (i = 0; i < num_threads; i++) {
void* ret;
pthread_join(threads[i], &ret);
if (ret != 0) {
printf("Thread %d found a solution!\\n", i);
sol = ret;
} else {
printf("Thread %d was not able to find a solution.\\n", i);
}
}
clock_t end = clock();
printf("%.4f\\n", ((double) (end - start)) / CLOCKS_PER_SEC);
printf("Joined with result %x and %d executions\\n", sol, G_steps);
if (sol != 0) {
print_set(sol->subset, sol->size, stdout);
}
return 0;
}
| 1
|
#include <pthread.h>
void shuffle(int* intArray, int arrayLen) {
int i=0;
for (i=0; i<arrayLen; i++) {
int r = rand()%arrayLen;
int temp = intArray[i];
intArray[i] = intArray[r];
intArray[r] = temp;
}
}
int main(int argc, char *argv[]) {
if (argc<3) {
printf("(set to 1 for more detailed output)]\\n");
exit(1);
}
if (argv[1][1]!='\\0' || argv[2][1]!='\\0') {
exit(1);
}
int totNumAdults = argv[1][0]-'0';
int totNumKids = argv[2][0]-'0';
verbose = 0;
if (argc>=4) {
verbose = argv[3][0]-'0';
}
srand(time(0));
init();
const int total = totNumAdults + totNumKids;
int order[total];
int i;
for (i=0; i<totNumAdults; i++) {
order[i] = 1;
}
for (; i<total; i++) {
order[i] = 2;
}
shuffle(order, total);
kidsOahu = 0;
adultsOahu = 0;
start = 0;
pthread_t peeps[total];
for (i=0; i<total; i++) {
if (order[i]==1) pthread_create(&peeps[i], 0, adultThread, 0);
else if (order[i]==2) pthread_create(&peeps[i], 0, childThread, 0);
else printf("something went horribly wrong!!!\\n");
}
pthread_mutex_lock(&lock);
while (kidsOahu != totNumKids || adultsOahu != totNumAdults){
pthread_cond_wait(&allReady, &lock);
}
printf("\\nAll %d adults and %d children on Oahu; crossing may now begin\\n", adultsOahu, kidsOahu);
start = 1;
pthread_cond_broadcast(&mayStart);
while (kidsOahu > 0 || adultsOahu > 0) {
pthread_cond_wait(&allDone, &lock);
}
printf("All people on Malokai; main thread terminating!\\n\\n");
pthread_mutex_unlock(&lock);
}
void boardBoat(int person, int island) {
char* pers;
char* isl;
if (person == ADULT) pers = "adult";
else pers = "child";
if (island == OAHU) isl = "Oahu";
else isl = "Molokai";
printf("%s boards boat on %s\\n", pers, isl);
}
void boatCross(int from, int to) {
char* islFrom;
char* islTo;
if (from == OAHU) islFrom = "Oahu";
else islFrom = "Molokai";
if (to == OAHU) islTo = "Oahu";
else islTo = "Molokai";
printf("boat is rowed across from %s to %s\\n", islFrom, islTo);
}
void leaveBoat(int person, int island) {
char* pers;
char* isl;
if (person == ADULT) pers = "adult";
else pers = "child";
if (island == OAHU) isl = "Oahu";
else isl = "Molokai";
printf("%s exits boat on %s\\n", pers, isl);
}
| 0
|
#include <pthread.h>
struct thread_arg {
int id;
int seats_a;
int* tickets;
pthread_mutex_t* tickets_mut;
};
void* work( void* t_arg);
int rand_20();
int rand_1_4();
int main( int argc, char *argv[]){
if( argc != 4){
printf( "error: not exactly 3 args\\n");
exit( -1);}
size_t threads_n = atoi( argv[1]);
int seats_n = atoi( argv[2]);
float overselling = atof( argv[3]);
int seats_a = seats_n + round( seats_n * overselling / 100.0f);
int* tickets = malloc( sizeof( int));
*tickets = 0;
pthread_mutex_t* tickets_mut = malloc( sizeof( pthread_mutex_t));
pthread_mutex_init( tickets_mut, 0);
pthread_t threads[threads_n];
struct thread_arg thread_args[threads_n];
pthread_attr_t attr;
pthread_attr_init( &attr);
pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE);
srand( time( 0));
int error;
for( size_t i = 0; i < threads_n; i++){
thread_args[i].id = i;
thread_args[i].seats_a = seats_a;
thread_args[i].tickets = tickets;
thread_args[i].tickets_mut = tickets_mut;
error = pthread_create(
&threads[i], &attr, work, (void*) &thread_args[i]);
if( error)
printf( "error creating thread[%d]: %d\\n", i, error);}
pthread_attr_destroy( &attr);
for( size_t i = 0; i < threads_n; i++){
error = pthread_join( threads[i], 0);
if( error)
printf( "error joining thread[%d]: %d\\n", i, error);}
if( ! 1)
printf(
"Summary: %d tickets sold out of %d (%d + %.1f%%)\\n",
*tickets, seats_a, seats_n, overselling);
pthread_mutex_destroy( tickets_mut);
free( tickets_mut);
free( tickets);
exit( 0);
}
void* work( void* t_arg){
struct thread_arg* arg = (struct thread_arg*) t_arg;
bool term = 0;
bool even_id = ( arg->id % 2) == 0;
int threshold = even_id ? 9 : 6;
while( 1){
pthread_mutex_lock( arg->tickets_mut);
int seats_left = ( arg->seats_a - *arg->tickets);
if( seats_left <= 0){
pthread_mutex_unlock( arg->tickets_mut);
break;}
if( rand_20() < threshold){
int tickets_sold = rand_1_4();
if( tickets_sold > seats_left)
tickets_sold = seats_left;
*arg->tickets += tickets_sold;
if( ! 1)
printf(
"Ticket agent %d: Successful transaction - %d tickets sold (%d total)\\n",
arg->id, tickets_sold, *arg->tickets);}
else if( ! 1){
printf( "Ticket agent %d: Unsuccessful transaction\\n", arg->id);}
pthread_mutex_unlock( arg->tickets_mut);}
pthread_exit( 0);}
int rand_20(){
return rand() % 20;}
int rand_1_4(){
return 1 + rand() % 4;}
| 1
|
#include <pthread.h>
const int cells_to_fill = 20000000 / 4;
volatile int running_threads = 0;
pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER;
int array[20000000];
void *startThread(void *vargp)
{
int myid = (int)vargp;
if (0) {
printf("Thread %d starting...\\n", myid);
}
int start = myid * cells_to_fill;
int end = start + cells_to_fill;
int uuid;
int i;
for (i = start; i < end; i++) {
if (0) {
printf("tid %d running\\n");
}
if (get_unique_id(&uuid) != 0) {
printf("get_unique_id returned an error!\\n");
exit(1);
}
array[i] = uuid;
}
pthread_mutex_lock(&running_mutex);
running_threads--;
pthread_mutex_unlock(&running_mutex);
}
void arrayContainsDouble() {
int i;
int j;
for (i = 0; i < 20000000; i++) {
for (j = 0; j < 20000000; j++) {
if ( (array[i] == array[j]) && (i != j) ) {
printf("The element %d was generated twice!\\n", array[i]);
exit(0);
}
}
}
printf("\\nNo repetition found for %d calls!\\n", 20000000);
}
int main()
{
int i;
pthread_t tid;
printf("Creating threads...\\n");
for (i = 0; i < 4 ; i++) {
pthread_mutex_lock(&running_mutex);
running_threads++;
pthread_mutex_unlock(&running_mutex);
pthread_create(&tid, 0, startThread, (void *)i);
}
while (running_threads > 0) {
sleep(1);
}
if (0) {
printf("\\nGenerated UUIDs: \\n");
for (i = 0; i < 20000000; i++) {
printf("%d, ", i, array[i]);
}
}
arrayContainsDouble();
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex_set_state = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_full_dishes = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
int capacity;
void dishes_init(int size) {
capacity = size;
dishes = malloc(sizeof(struct dish) * capacity);
for(int i = 0; i < size; i++) {
dishes[i].state = EMPTY;
}
}
int dishes_get_state(int i) {
return dishes[i].state;
}
void dishes_set_state(int i, int state) {
pthread_mutex_lock(&mutex_set_state);
printf("Set dish %d state to %d\\n", i, state);
dishes[i].state = state;
pthread_mutex_unlock(&mutex_set_state);
}
int dishes_get_size() {
return capacity;
}
void dishes_delete() {
free(dishes);
}
int dishes_get_full_dish(int i) {
int return_value = -1;
pthread_mutex_lock(&mutex_full_dishes);
while(1) {
for(int i = 0; i < capacity; i++) {
if(dishes[i].state == FULL) {
printf("Found dish %d\\n", i);
return_value = i;
break;
}
}
if(return_value != -1) {
break;
}
int k = 0;
for(int i = 0; i < capacity; i++) {
if(dishes[i].state == EMPTY) {
k++;
}
}
if(k == capacity) {
printf("Child %d woke up mom\\n", i);
printf("Waking up mother to fill the dishes\\n");
mother_fill_dishes();
}
}
pthread_mutex_unlock(&mutex_full_dishes);
return return_value;
}
| 1
|
#include <pthread.h>
pthread_mutex_t pelock = PTHREAD_MUTEX_INITIALIZER;
int threadready = 0;
pthread_cond_t peready = PTHREAD_COND_INITIALIZER;
int threadexit = 0;
pthread_cond_t peexit = PTHREAD_COND_INITIALIZER;
void* pe_thread(void* param)
{
int pe;
if ( (pe = pe_init()) < 0 )
{
fprintf(stderr, "Failed to initialize PE!\\n");
return (void*)-1;
}
pe_active(pe);
pthread_mutex_lock(&pelock);
threadready = 1;
pthread_cond_signal(&peready);
pthread_mutex_unlock(&pelock);
pthread_mutex_lock(&pelock);
while ( !threadexit )
{
pthread_cond_wait(&peexit, &pelock);
}
pthread_mutex_unlock(&pelock);
pe_idle(pe);
pe_exit(pe);
return 0;
}
int main(int argc, char *argv[])
{
unsigned int group;
const unsigned int tout = 2;
char file[100];
int talpa;
int rc;
struct TalpaPacket_VettingDetails* details;
int status;
if ( argc > 1 )
{
group = atoi(argv[1]);
strcpy(file, argv[2]);
}
else
{
group = 0;
strcpy(file, "/test/file");
}
if ( (talpa = vc_init(group, tout*1000)) < 0 )
{
fprintf(stderr, "Failed to initialize VC!\\n");
return -1;
}
rc = fork();
if ( !rc )
{
int fd;
int rc;
pthread_t thread;
void *tret;
rc = pthread_create(&thread, 0, pe_thread, 0);
if ( rc )
{
printf("Spawning thread failed (%d)!\\n", errno);
return -2;
}
pthread_mutex_lock(&pelock);
while ( !threadready )
{
pthread_cond_wait(&peready, &pelock);
}
pthread_mutex_unlock(&pelock);
fd = open(file, O_RDONLY);
if ( fd < 0 )
{
return -1;
}
pthread_mutex_lock(&pelock);
threadexit = 1;
pthread_cond_signal(&peexit);
pthread_mutex_unlock(&pelock);
pthread_join(thread, &tret);
if ( tret )
{
return -3;
}
return 0;
}
else if ( rc < 0 )
{
fprintf(stderr, "Fork failed!\\n");
return -1;
}
details = vc_get(talpa);
if ( details )
{
fprintf(stderr, "Unexpected caught!\\n");
vc_respond(talpa, details, TALPA_DENY);
vc_exit(talpa);
wait(0);
return -1;
}
wait(&status);
if ( !WIFEXITED(status) )
{
fprintf(stderr, "Child error!\\n");
vc_exit(talpa);
return -1;
}
if ( WEXITSTATUS(status) )
{
fprintf(stderr, "Child open failed!\\n");
vc_exit(talpa);
return -1;
}
vc_exit(talpa);
return 0;
}
| 0
|
#include <pthread.h>
void usage(char *prog) {
fprintf(stderr, "usage: %s [-v] [-n num]\\n", prog);
exit(-1);
}
int verbose;
int nthread=2;
char *dir="/tmp";
char *file;
struct work_t *next;
} work_t;
work_t *head,*tail;
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void cleanup(void *arg) {
pthread_mutex_unlock(&mtx);
}
void *worker(void *data) {
work_t *w;
sigset_t all;
sigfillset(&all);
pthread_sigmask(SIG_BLOCK, &all, 0);
again:
pthread_mutex_lock(&mtx);
pthread_cleanup_push(cleanup,0);
while (!head) pthread_cond_wait(&cond, &mtx);
w = head;
head = head->next;
if (!head) tail=0;
fprintf(stderr,"thread %d claimed %s\\n", (int)data, w->file);
pthread_cleanup_pop(1);
sleep(1);
free(w->file);
free(w);
goto again;
}
union {
struct inotify_event ev;
char buf[sizeof(struct inotify_event) + PATH_MAX];
} eb;
char *get_file(int fd, void **nx) {
struct inotify_event *ev;
static int rc=0;
size_t sz;
if (*nx) ev = *nx;
else {
rc = read(fd,&eb,sizeof(eb));
if (rc < 0) return 0;
ev = &eb.ev;
}
sz = sizeof(*ev) + ev->len;
rc -= sz;
*nx = (rc > 0) ? ((char*)ev + sz) : 0;
return ev->len ? ev->name : dir;
}
sigjmp_buf jmp;
int sigs[] = {SIGHUP,SIGTERM,SIGINT,SIGQUIT,SIGALRM,SIGUSR1};
void sighandler(int signo) {
siglongjmp(jmp,signo);
}
int main(int argc, char *argv[]) {
int opt, fd, wd, i, n, s;
pthread_t *th;
void *nx=0,*res;
work_t *w;
char *f;
while ( (opt = getopt(argc, argv, "v+n:d:")) != -1) {
switch(opt) {
case 'v': verbose++; break;
case 'n': nthread=atoi(optarg); break;
case 'd': dir=strdup(optarg); break;
default: usage(argv[0]);
}
}
if (optind < argc) usage(argv[0]);
struct sigaction sa;
sa.sa_handler=sighandler;
sa.sa_flags=0;
sigfillset(&sa.sa_mask);
for(n=0; n < sizeof(sigs)/sizeof(*sigs); n++) sigaction(sigs[n], &sa, 0);
sigset_t ss;
sigfillset(&ss);
for(n=0; n < sizeof(sigs)/sizeof(*sigs); n++) sigdelset(&ss, sigs[n]);
pthread_sigmask(SIG_SETMASK, &ss, 0);
th = malloc(sizeof(pthread_t)*nthread);
for(i=0; i < nthread; i++) pthread_create(&th[i],0,worker,(void*)i);
fd = inotify_init();
wd = inotify_add_watch(fd,dir,IN_CLOSE);
int signo = sigsetjmp(jmp,1);
if (signo) goto done;
while ( (f=get_file(fd,&nx))) {
w = malloc(sizeof(*w)); w->file=strdup(f); w->next=0;
pthread_mutex_lock(&mtx);
if (tail) { tail->next=w; tail=w;} else head=tail=w;
if (verbose) fprintf(stderr,"queued %s\\n", w->file);
pthread_mutex_unlock(&mtx);
pthread_cond_signal(&cond);
}
done:
for(i=0; i < nthread; i++) {
pthread_cancel(th[i]);
pthread_join(th[i],&res);
fprintf(stderr,"thread %d %sed\\n",i,res==PTHREAD_CANCELED?"cancel":"exit");
}
close(fd);
}
| 1
|
#include <pthread.h>
double *x;
double *y;
double *z;
int n;
int sub_n;
}mat_mult_t;
double *z;
int n;
int sub_n;
double *global_norm;
pthread_mutex_t *mutex;
}mat_norm_t;
void *matrix_mult(void *arg){
mat_mult_t *thread_mat_mult_data = arg;
int n = thread_mat_mult_data->n;
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, thread_mat_mult_data->sub_n, n, n,
1.0, thread_mat_mult_data->x, n, thread_mat_mult_data->y, n, 0.0, thread_mat_mult_data->z, n);
pthread_exit(0);
}
void *matrix_norm(void *arg){
mat_norm_t *thread_mat_norm_data = arg;
int n = thread_mat_norm_data->n;
int i, j;
double norm = 0.;
for(i=0;i<thread_mat_norm_data->sub_n;i++){
double row_sum = 0.;
for(j=0;j<n;j++){
row_sum += *(thread_mat_norm_data->z+i*n+j);
}
if(row_sum>norm){
norm = row_sum;
}
}
pthread_mutex_lock(thread_mat_norm_data->mutex);
if (norm > *(thread_mat_norm_data->global_norm)){
*(thread_mat_norm_data->global_norm)=norm;
}
pthread_mutex_unlock(thread_mat_norm_data->mutex);
pthread_exit(0);
}
void initMat(int n, double mat[]){
int i, j;
for (i=0;i<n;i++){
for (j=0;j<n;j++){
mat[i*n+j] = i+j;
}
}
}
void printMat(int n, double mat[] , char* matName){
int i, j;
for (i=0;i<n;i++) {
for (j=0;j<n;j++) {
printf("%s[%d][%d]=%.1f ", matName, i, j, mat[i*n+j]);
}
printf("\\n");
}
}
int main(int argc, char *argv[]) {
struct timeval tv1, tv2;
struct timezone tz;
pthread_t *working_thread;
mat_mult_t *thread_mat_mult_data;
mat_norm_t *thread_mat_norm_data;
pthread_mutex_t *mutex;
double *x, *y, *z, norm;
int i, rows_per_thread;
void *status;
int n = atoi(argv[1]);
int num_of_thrds = atoi(argv[2]);
if(n<=num_of_thrds && num_of_thrds < 124){
printf("Matrix dimension must be greater than num of thrds\\nand num of thrds less than 124.\\n");
return (-1);
}
x = malloc(n*n*sizeof(double));
y = malloc(n*n*sizeof(double));
z = malloc(n*n*sizeof(double));
initMat(n, x);
initMat(n, y);
working_thread = malloc(num_of_thrds * sizeof(pthread_t));
thread_mat_mult_data = malloc(num_of_thrds * sizeof(mat_mult_t));
rows_per_thread = n/num_of_thrds;
gettimeofday(&tv1, &tz);
for(i=0;i<num_of_thrds;i++){
thread_mat_mult_data[i].x = x + i * rows_per_thread * n;
thread_mat_mult_data[i].y = y;
thread_mat_mult_data[i].z = z + i * rows_per_thread * n;
thread_mat_mult_data[i].n = n;
thread_mat_mult_data[i].sub_n = (i == num_of_thrds-1) ? n-(num_of_thrds-1)*rows_per_thread : rows_per_thread;
pthread_create(&working_thread[i], 0, matrix_mult, (void *)&thread_mat_mult_data[i]);
}
for(i=0;i<num_of_thrds;i++){
pthread_join(working_thread[i], 0);
}
working_thread = malloc(num_of_thrds * sizeof(pthread_t));
thread_mat_norm_data = malloc(num_of_thrds * sizeof(mat_norm_t));
mutex = malloc(sizeof(pthread_mutex_t));
pthread_mutex_init(mutex, 0);
for(i=0;i<num_of_thrds;i++){
thread_mat_norm_data[i].z = z + i * rows_per_thread * n;
thread_mat_norm_data[i].n = n;
thread_mat_norm_data[i].global_norm = &norm;
thread_mat_norm_data[i].sub_n = (i == num_of_thrds-1) ? n-(num_of_thrds-1)*rows_per_thread : rows_per_thread;
thread_mat_norm_data[i].mutex = mutex;
pthread_create(&working_thread[i], 0, matrix_norm, (void *)&thread_mat_norm_data[i]);
}
for(i=0;i<num_of_thrds;i++){
pthread_join(working_thread[i], &status);
}
gettimeofday(&tv2, &tz);
double elapsed = (double) (tv2.tv_sec-tv1.tv_sec) + (double) (tv2.tv_usec-tv1.tv_usec) * 1.e-6;
printf("Time = %f\\n",elapsed);
free(x);
free(y);
free(z);
free(working_thread);
free(thread_mat_mult_data);
free(thread_mat_norm_data);
pthread_mutex_destroy(mutex);
free(mutex);
return(0);
}
| 0
|
#include <pthread.h>
int sum_diff;
pthread_mutex_t mutex_sum_diff;
int *data;
int element_num;
int element_size;
} qsort_struct;
int *data;
int start;
int end;
} all_sub_struct;
void disp_arr(int *data, int number);
int compare_func(const void *a, const void*b);
void* thread_qsort(void *argument);
void all_sub(int *data, int start, int end);
void* thread_all_sub(void *argument);
int main(int argc, char *argv[])
{
if (argc!=3) {
printf("Input error. Please enter rand_seed(number) & data_size(number).\\n");
return -1;
}
int rand_seed, data_size, *my_array, i;
rand_seed = atoi(argv[1]);
data_size = atoi(argv[2]);
sum_diff=0;
pthread_mutex_init(&mutex_sum_diff,0);
srand(rand_seed);
my_array = calloc(data_size,sizeof(int));
for (i=0; i<data_size; i++)
my_array[i] = rand();
pthread_t thread_for_qsort[4];
qsort_struct thread_qsort_passing[4];
for (i=0;i<4;i++) {
if (i==0) {
thread_qsort_passing[i].data = my_array;
thread_qsort_passing[i].element_num = data_size/4;
thread_qsort_passing[i].element_size = sizeof(int);
}
else if (i==4 -1) {
thread_qsort_passing[i].data = thread_qsort_passing[i-1].data+thread_qsort_passing[i-1].element_num;
thread_qsort_passing[i].element_num = data_size-(4 -1)*thread_qsort_passing[i-1].element_num;
thread_qsort_passing[i].element_size = sizeof(int);
}
else {
thread_qsort_passing[i].data = thread_qsort_passing[i-1].data+thread_qsort_passing[i-1].element_num;
thread_qsort_passing[i].element_num = data_size/4;
thread_qsort_passing[i].element_size = sizeof(int);
}
}
for (i=0;i<4;i++) {
pthread_create(&thread_for_qsort[i],0,thread_qsort,(void*)&thread_qsort_passing[i]);
}
for (i=0;i<4 ;i++)
pthread_join(thread_for_qsort[i],0);
qsort(my_array,data_size,sizeof(int),compare_func);
all_sub_struct all_sub_passing[4];
pthread_t thread_id_all_sub[4];
for (i=0;i<4&&data_size>=8;i++) {
if (i==0) {
all_sub_passing[i].data = my_array;
all_sub_passing[i].start = 0;
all_sub_passing[i].end = data_size/4;
}
else if (i==4 -1) {
all_sub_passing[i].data = my_array;
all_sub_passing[i].start = all_sub_passing[i-1].end;
all_sub_passing[i].end = data_size;
}
else {
all_sub_passing[i].data = my_array;
all_sub_passing[i].start = all_sub_passing[i-1].end;
all_sub_passing[i].end = all_sub_passing[i-1].end+data_size/4;
}
}
for (i=0;i<4;i++)
pthread_create(&thread_id_all_sub[i],0,thread_all_sub,(void*)&all_sub_passing[i]);
for (i=0;i<4;i++)
pthread_join(thread_id_all_sub[i],0);
printf("%d\\n",sum_diff);
pthread_mutex_destroy(&mutex_sum_diff);
free(my_array);
return 0;
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void copy_arr(int *source, int *dest, int number)
{
int i;
for (i=0;i<number;i++)
dest[i] = source[i];
}
void disp_arr(int *data, int number)
{
int i;
for (i=0;i<number;i++) {
printf("%d ",data[i]);
}
printf("\\n");
}
int compare_func(const void *a, const void *b)
{
if (*(int*)a < *(int*)b)
return -1;
else if (*(int*)a > *(int*)b)
return 1;
else
return 0;
}
void* thread_qsort(void *argument)
{
qsort_struct *a = (qsort_struct*)argument;
qsort(a->data,a->element_num,a->element_size,compare_func);
return 0;
}
void all_sub(int *data, int start, int end)
{
int i,temp_sum=0;
for (i=start+1; i<end; i++) {
temp_sum+=data[i]-data[i-1];
}
sum_diff+=temp_sum;
}
void* thread_all_sub(void *argument)
{
all_sub_struct *a = (all_sub_struct*)argument;
int i,temp_sum=0;
for (i=(a->start)+1; i<a->end; i++) {
if (i!=0 && i==((a->start)+1)) {
temp_sum+=a->data[i-1]-a->data[i-2];
}
temp_sum+=a->data[i]-a->data[i-1];
}
pthread_mutex_lock(&mutex_sum_diff);
sum_diff+=temp_sum;
pthread_mutex_unlock(&mutex_sum_diff);
return 0;
}
| 1
|
#include <pthread.h>
int num_threads;
pthread_t p_threads[65536];
pthread_attr_t attr;
int list[268435456];
int list_size;
pthread_mutex_t lock_stat;
double sum;
double sum_square;
int count;
void *compute_sum (void *s) {
int j;
int thread_id = (int) s;
int chunk_size = list_size/num_threads;
int my_start = thread_id*chunk_size;
int my_end = (thread_id+1)*chunk_size-1;
if (thread_id == num_threads-1) my_end = list_size-1;
double my_sum = list[my_start];
double my_sum_square = ((double)list[my_start]) * ((double)list[my_start]);
for (j = my_start+1; j <= my_end; j++) {
my_sum += list[j];
my_sum_square += ((double)list[j]) * ((double)list[j]);
}
pthread_mutex_lock(&lock_stat);
sum += my_sum;
sum_square += my_sum_square;
count++;
pthread_mutex_unlock(&lock_stat);
pthread_exit(0);
}
int main(int argc, char *argv[]) {
struct timeval start, stop;
double total_time;
int i, j;
double true_mean;
if (argc != 3) {
printf("Need two integers as input \\n");
printf("Use: <executable_name> <list_size> <num_threads>\\n");
exit(0);
}
if ((list_size = atoi(argv[argc-2])) > 268435456) {
printf("Maximum list size allowed: %d.\\n", 268435456);
exit(0);
};
if ((num_threads = atoi(argv[argc-1])) > 65536) {
printf("Maximum number of threads allowed: %d.\\n", 65536);
exit(0);
};
if (num_threads > list_size) {
printf("Number of threads (%d) < list_size (%d) not allowed.\\n", num_threads, list_size);
exit(0);
};
pthread_mutex_init(&lock_stat, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
unsigned int seed = 0;
srand(seed);
for (j = 0; j < list_size; j++) list[j] = rand_r(&seed);
count = 0;
gettimeofday(&start, 0);
for (i = 0; i < num_threads; i++) {
pthread_create(&p_threads[i], &attr, compute_sum, (void * )i);
}
for (i = 0; i < num_threads; i++) {
pthread_join(p_threads[i], 0);
}
double mean = sum / ((double)list_size);
double sum_square_mean = sum_square / ((double)list_size);
double std = sqrt(sum_square_mean - mean * mean);
gettimeofday(&stop, 0);
total_time = (stop.tv_sec-start.tv_sec)
+0.000001*(stop.tv_usec-start.tv_usec);
true_mean = 0;
for (j = 0; j < list_size; j++)
true_mean += (list[j]) / ((double)list_size);
if (true_mean != mean)
printf("Houston, we have a problem!\\n");
printf("Threads = %d, Mean: %lf, Standard Deviation: %lf, time (sec) = %8.4f\\n",
num_threads, mean, std, total_time);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&lock_stat);
}
| 0
|
#include <pthread.h>
struct msg {
struct msg *m_next;
};
struct msg *workq;
pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;
void
process_msg(void)
{
struct msg *mp;
for (;;) {
pthread_mutex_lock(&qlock);
while (workq == 0)
pthread_cond_wait(&qready, &qlock);
mp = workq;
workq = mp->m_next;
printf("process one msg\\n");
free(mp);
pthread_mutex_unlock(&qlock);
}
}
void
enqueue_msg(struct msg *mp)
{
pthread_mutex_lock(&qlock);
mp->m_next = workq;
workq = mp;
pthread_mutex_unlock(&qlock);
pthread_cond_signal(&qready);
}
void *
thr_fn1(void *arg)
{
process_msg();
return((void *)0);
}
void *
thr_fn2(void *arg)
{
struct msg *msg1 = malloc(sizeof(struct msg));
enqueue_msg(msg1);
return((void *)0);
}
void *
thr_fn3(void *arg)
{
printf("thr_fn3 start\\n");
pthread_mutex_lock(&qlock);
printf("continual wait! thr_fn1, I will print!!!\\n");
pthread_mutex_unlock(&qlock);
return ((void *)0);
}
int
main(void)
{
struct msg msg1;
pthread_t tid1, tid2, tid3, tid4, tid5, tid6, tid7, tid8;
pthread_create(&tid1, 0, thr_fn1, 0);
pthread_create(&tid2, 0, thr_fn1, 0);
pthread_create(&tid3, 0, thr_fn1, 0);
pthread_create(&tid4, 0, thr_fn1, 0);
pthread_create(&tid5, 0, thr_fn1, 0);
pthread_create(&tid8, 0, thr_fn3, 0);
sleep(2);
pthread_create(&tid6, 0, thr_fn2, 0);
sleep(1);
pthread_create(&tid7, 0, thr_fn2, 0);
sleep(10);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *forfood(void* arg);
int main(void)
{
const int ppl_n = 1000;
pthread_t ppl[ppl_n];
int i;
int count = 0;
for(i=0; i<ppl_n; i++) {
Pthread_create(&ppl[i], 0, forfood, &count);
}
for(i=0; i<ppl_n; i++) {
Pthread_join(ppl[i], 0);
}
printf("The final count is %d\\n", count);
pthread_exit(0);
return 0;
}
void *forfood(void* arg) {
int i;
int* count = (int*)arg;
for(i=0; i<1000; i++) {
pthread_mutex_lock(&mutex);
(*count)++;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error() ;
int table[128];
pthread_mutex_t cas_mutex[128];
pthread_t tids[13];
int cas(int * tab, int h, int val, int new_val)
{
int ret_val = 0;
pthread_mutex_lock(&cas_mutex[h]);
if ( tab[h] == val ) {
tab[h] = new_val;
ret_val = 1;
}
pthread_mutex_unlock(&cas_mutex[h]);
return ret_val;
}
void * thread_routine(void * arg)
{
int tid;
int m = 0, w, h;
tid = *((int *)arg);
while(1){
if ( m < 4 ){
w = (++m) * 11 + tid;
}
else{
pthread_exit(0);
}
h = (w * 7) % 128;
if (h<0)
{
ERROR: __VERIFIER_error();
;
}
while ( cas(table, h, 0, w) == 0){
h = (h+1) % 128;
}
}
return 0;
}
int main()
{
int i, arg;
for (i = 0; i < 128; i++)
pthread_mutex_init(&cas_mutex[i], 0);
for (i = 0; i < 13; i++){
arg=i;
pthread_create(&tids[i], 0, thread_routine, &arg);
}
for (i = 0; i < 13; i++){
pthread_join(tids[i], 0);
}
for (i = 0; i < 128; i++){
pthread_mutex_destroy(&cas_mutex[i]);
}
return 0;
}
| 1
|
#include <pthread.h>
int quitflag ;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER;
void * thr_fn(void * arg){
int err , signo;
for(;;){
err = sigwait(&mask , &signo);
if(err != 0)
err_exit(err,"sigwait error!");
switch(signo){
case SIGINT :
printf("\\n interrput \\n");
break;
case SIGQUIT :
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&waitloc);
return (0);
default:
printf("unexpected sigal &d \\n" , signo);
exit(1);
}
}
}
int main(){
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask,SIGINT);
sigaddset(&mask,SIGQUIT);
if((err = pthread_sigmask(SIG_BLOCK , &mask , &oldmask)) !=0)
err_exit(err,"sigmaks error");
err = pthread_create(&tid , 0 ,thr_fn , 0);
if(err != 0)
err_exit(err,"create thread error");
pthread_mutex_lock(&lock);
while(quitflag == 0){
pthread_cond_wait(&waitloc , &lock);
}
pthread_mutex_unlock(&lock);
quitflag = 0;
if(sigprocmask(SIG_SETMASK , &oldmask , 0) < 0)
err_sys("set mask error");
exit(0);
}
| 0
|
#include <pthread.h>
pthread_cond_t cond;
pthread_mutex_t mutex;
void* p_func(void* p)
{
pthread_mutex_lock(&mutex);
int ret;
printf("I am child,I am here\\n");
ret=pthread_cond_wait(&cond,&mutex);
if(0!=ret)
{
printf("pthread_cond_wait ret=%d\\n",ret);
}
printf("I am child thread,I am wake\\n");
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main()
{
int ret;
ret=pthread_cond_init(&cond,0);
if(0!=ret)
{
printf("pthread_cond_init ret=%d\\n",ret);
return -1;
}
ret=pthread_mutex_init(&mutex,0);
if(0!=ret)
{
printf("pthread_mutex_init ret=%d\\n",ret);
return -1;
}
pthread_t thid;
pthread_create(&thid,0,p_func,0);
sleep(1);
pthread_mutex_lock(&mutex);
printf("I am main thread,I can lock\\n");
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
ret=pthread_join(thid,0);
if(0!=ret)
{
printf("pthread_join ret=%d\\n",ret);
return -1;
}
ret=pthread_cond_destroy(&cond);
if(0!=ret)
{
printf("pthread_cond_destroy ret=%d\\n",ret);
return -1;
}
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
float x;
float y;
float z;
} Point;
struct dist_args {
int start;
int end;
};
static Point cities[20];
static float distances[20];
static int cities_cnt = 0;
static float averageDist = 0;
pthread_mutex_t lock;
pthread_t * threads;
static void *calc_distance(void * func_args) {
struct dist_args * args = (struct dist_args * )func_args;
int start = args->start;
int end = args->end;
for (int i = start; i < end; ++i) {
float x1 = cities[i].x;
float y1 = cities[i].y;
float z1 = cities[i].z;
float x2 = cities[i + 1].x;
float y2 = cities[i + 1].y;
float z2 = cities[i + 1].z;
distances[i] = sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2.0) + pow(z1 - z2, 2.0));
printf("Distance %d-%d: %f\\n", i, i + 1, distances[i]);
pthread_mutex_lock(&lock);
averageDist += distances[i];
pthread_mutex_unlock(&lock);
}
free(args);
pthread_exit(0);
}
static void calc_metrics() {
int procs_cnt = get_nprocs();
threads = (pthread_t *)malloc(sizeof(pthread_t) * procs_cnt);
int thr_cnt = 0;
int step = (cities_cnt - 1) / procs_cnt;
if ((cities_cnt - 1) % procs_cnt != 0) {
++step;
}
if (pthread_mutex_init(&lock, 0) != 0) {
printf("Mutex init failed\\n");
exit(1);
}
for (int i = 0; i < cities_cnt - 1; i += step) {
int start = i;
int end = ((cities_cnt - 1) > (i + step) ? (i + step) : (cities_cnt - 1));
struct dist_args * args = malloc(sizeof *args);
args->start = start;
args->end = end;
int rc = pthread_create(&threads[thr_cnt++],
0,
&calc_distance,
args);
if (rc) {
printf("ERROR. return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
for (int i = 0; i < thr_cnt; ++i) {
int rc = pthread_join(threads[i], 0);
printf("Thread %d exited\\n", i);
}
printf("Average distance: %f\\n", averageDist / (cities_cnt - 1));
free(threads);
}
static void read_input() {
FILE *fp;
fp = fopen("cities-list", "r");
if (fp == 0) {
printf("Error opening file\\n");
exit(1);
}
char city_name[20];
while (fscanf(fp, "%s", &city_name) == 1) {
float x;
float y;
float z;
fscanf(fp, "%f", &x);
fscanf(fp, "%f", &y);
fscanf(fp, "%f", &z);
cities[cities_cnt].x = x;
cities[cities_cnt].y = y;
cities[cities_cnt].z = z;
++cities_cnt;
}
int rc = fclose(fp);
if (rc) {
printf("Failed to close file\\n");
exit(1);
}
}
int main(int argc, char ** argv) {
read_input();
calc_metrics();
}
| 0
|
#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(&mutex2);
pthread_mutex_lock(&mutex1);
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(&mutex2);
pthread_mutex_lock(&mutex1);
critical_section(2, i);
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
}
}
void critical_section(int thread_num, int i)
{
printf("Thread%d: %d\\n", thread_num,i);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int data;
int turn=0;
long int sum=0;
long num=0;
int count=0;
long double sd=0;
long double avg=0;
main()
{
pthread_t thread1;
pthread_t thread2;
pthread_t final_thread;
void *thread1Function();
void *thread2Function();
void *outputResult();
printf("\\nEnter -1 to mark end of data input from user\\n");
pthread_create(&thread1,0,thread1Function,0);
pthread_create(&thread2,0,thread2Function,0);
pthread_join(thread2,0);
if(turn==2) {
pthread_create(&final_thread,0,outputResult,0);
pthread_join(final_thread,0);
}
}
void *outputResult() {
printf("\\n*********************Inside thread 3 : final thread***************************/");
printf("\\nSum final : %ld " ,sum);
printf("\\nAverage final : %Lf ",avg);
printf("\\nStandard deviation final : %Lf \\n",sd);
}
void setBuffer(int i){
data = i;
}
int getBuffer(){
return data ;
}
void *thread1Function() {
int i = 0;
while (1) {
while (turn == 1) ;
pthread_mutex_lock( &mutex1 );
printf("\\nEnter number : ");
scanf("%d",&i);
if(i==-1) {
pthread_mutex_unlock( &mutex1 );
turn = 2;
break;
}
setBuffer(i);
turn = 1;
pthread_mutex_unlock( &mutex1 );
}
pthread_exit(0);
}
void *thread2Function() {
int i,value;
for (i=0;i<100;i++) {
while (turn == 0) ;
pthread_mutex_lock( &mutex1 );
if(turn == 2)
break;
value = getBuffer();
count++;
sum=sum+value;
avg=sum/count;
num=num+((value-avg)*(value-avg));
sd=sqrt(num/count);
turn = 0;
printf("\\nSum till now : %ld ",sum);
printf("\\nAverage till now : %Lf ",avg);
printf("\\nStandard deviation till now : %Lf ",sd);
pthread_mutex_unlock( &mutex1 );
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
{
double *a;
double *b;
double sum;
int veclen;
} DOTDATA;
DOTDATA dotstr;
pthread_t callThd[4];
pthread_mutex_t mutexsum;
void *dotprod(void *arg)
{
int i, start, end, len ;
long offset;
double mysum, *x, *y;
offset = (long)arg;
len = dotstr.veclen;
start = offset*len;
end = start + len;
x = dotstr.a;
y = dotstr.b;
mysum = 0;
for (i=start; i<end ; i++)
{
mysum += (x[i] * y[i]);
}
pthread_mutex_lock (&mutexsum);
dotstr.sum += mysum;
pthread_mutex_unlock (&mutexsum);
pthread_exit((void*) 0);
}
int main (int argc, char *argv[])
{
long i;
double *a, *b;
void *status;
pthread_attr_t attr;
a = (double*) malloc (4*100*sizeof(double));
b = (double*) malloc (4*100*sizeof(double));
for (i=0; i<100*4; i++)
{
a[i]=1.0;
b[i]=a[i];
}
dotstr.veclen = 100;
dotstr.a = a;
dotstr.b = b;
dotstr.sum=0;
pthread_mutex_init(&mutexsum, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i=0; i<4; i++)
{
pthread_create(&callThd[i], &attr, dotprod, (void *)i);
}
pthread_attr_destroy(&attr);
for(i=0; i<4; i++)
{
pthread_join(callThd[i], &status);
}
printf ("Sum = %f \\n", dotstr.sum);
free (a);
free (b);
pthread_mutex_destroy(&mutexsum);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
sem_t items;
sem_t spaces;
pthread_mutex_t mutex;
int item_id = 0;
unsigned long rdnumber()
{
unsigned long number;
number = genrand_int32();
return number;
}
{
int id;
unsigned long waitTime;
int buffer_index;
}Item;
struct Buffer{
Item m_items[32];
unsigned long currSize;
} m_buffer;
void add(Item item)
{
m_buffer.m_items[m_buffer.currSize].buffer_index = m_buffer.currSize;
m_buffer.m_items[m_buffer.currSize].id=item.id;
m_buffer.m_items[m_buffer.currSize].waitTime=item.waitTime;
}
void get(Item * item)
{
item->id= m_buffer.m_items[item->buffer_index].id;
item->waitTime= m_buffer.m_items[item->buffer_index].waitTime;
}
void *produce(int pro_id)
{
while(1) {
unsigned long proWaitTime;
proWaitTime = rdnumber()%5+3;
printf("producer %d wait %lu seconds\\n", pro_id, proWaitTime);
sleep(proWaitTime);
Item item;
unsigned long conWaitTime;
conWaitTime = rdnumber()%8+2;
item.id = item_id;
item.waitTime=conWaitTime;
printf("item %d is generated by producer %d, consumer need to wait %lu seconds\\n",item.id, pro_id ,item.waitTime);
sem_wait(&spaces);
pthread_mutex_lock(&mutex);
add(item);
m_buffer.currSize++;
printf("item %d is added to the buffer by producer %d (space:%d)\\n",item.id, pro_id, m_buffer.currSize);
item_id++;
pthread_mutex_unlock(&mutex);
sem_post(&items);
}
}
void *consume(int con_id)
{
Item item;
while(1) {
sem_wait(&items);
pthread_mutex_lock(&mutex);
get(&item);
m_buffer.currSize--;
printf("Item %d is get by consumer %d (space:%d)\\n",item.id, con_id, m_buffer.currSize);
pthread_mutex_unlock(&mutex);
sem_post(&spaces);
printf("consumer %d wait %lu seconds\\n",con_id, item.waitTime);
sleep(item.waitTime);
printf("Item %d is consumed by consumer %d\\n",item.id, con_id);
}
}
int main(void)
{
int proCount = 3;
int conCount = 6;
printf("There are %d producer and %d consumer\\n", proCount, conCount);
int i;
init_genrand(time(0));
m_buffer.currSize=0;
sem_init(&items, 0, 0);
sem_init(&spaces, 0, 32);
pthread_t producer[proCount];
pthread_t consumer[conCount];
pthread_mutex_init(&mutex, 0);
for(i = 0; i < proCount; i++) {
if(pthread_create(&producer[i], 0, produce, i) !=0)
{
printf("error\\n");
}
}
for(i = 0; i < conCount; i++) {
if(pthread_create(&consumer[i], 0, consume, i)!=0)
{
printf("error\\n");
}
}
for(i = 0; i < proCount; i++)
pthread_join(producer[i],0);
for(i = 0; i < conCount; i++)
pthread_join(consumer[i],0);
return 0;
}
| 0
|
#include <pthread.h>
int Resource = 0;
pthread_mutex_t Mutex;
void *producer(void *arg)
{
while (1)
{
pthread_mutex_lock(&Mutex);
if (Resource == 0)
{
Resource += 5;
printf("producer\\n");
}
pthread_mutex_unlock(&Mutex);
sleep(5);
}
return 0;
}
void *consumer(void *arg)
{
int t = *(int *)arg;
while (1)
{
pthread_mutex_lock(&Mutex);
if (Resource > 0)
{
Resource--;
printf("%d: consumer\\n", t);
}
pthread_mutex_unlock(&Mutex);
sleep(1);
}
return 0;
}
int main()
{
void *retval;
pthread_t tid_p;
pthread_t tid_c1, tid_c2, tid_c3;
int p[3] = {1, 2, 3};
pthread_mutex_init(&Mutex, 0);
pthread_create(&tid_p, 0, producer, 0);
pthread_create(&tid_c1, 0, consumer, &p[0]);
pthread_create(&tid_c2, 0, consumer, &p[1]);
pthread_create(&tid_c3, 0, consumer, &p[2]);
pthread_join(tid_p, &retval);
printf("retval = %d\\n", *(int *)retval);
pthread_join(tid_c1, &retval);
printf("retval = %d\\n", *(int *)retval);
pthread_join(tid_c2, &retval);
printf("retval = %d\\n", *(int *)retval);
pthread_join(tid_c3, &retval);
printf("retval = %d\\n", *(int *)retval);
return 0;
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
unsigned int __VERIFIER_nondet_uint();
static int top=0;
static unsigned int arr[(400)];
pthread_mutex_t m;
_Bool flag=(0);
void error(void)
{
ERROR:
__VERIFIER_error(); return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
(top==0) ? (1) : (0);
}
int push(unsigned int *stack, int x)
{
if (top==(400))
{
printf("stack overflow\\n");
return (-1);
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (top==0)
{
printf("stack underflow\\n");
return (-2);
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for(
i=0; i<(400); i++)
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint()%(400);
if ((push(arr,tmp)==(-1)))
error();
pthread_mutex_unlock(&m);
}
}
void *t2(void *arg)
{
int i;
for(
i=0; i<(400); i++)
{
pthread_mutex_lock(&m);
if (top>0)
{
if ((pop(arr)==(-2)))
error();
}
pthread_mutex_unlock(&m);
}
}
int main(void)
{
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 0
|
#include <pthread.h>
char** theArray;
int num_str;
double total;
int readers;
int writer;
pthread_cond_t readers_proceed;
pthread_cond_t writer_proceed;
int pending_writers;
pthread_mutex_t read_write_lock;
} mylib_rwlock_t;
void mylib_rwlock_init (mylib_rwlock_t *l) {
l -> readers = l -> writer = l -> pending_writers = 0;
pthread_mutex_init(&(l -> read_write_lock), 0);
pthread_cond_init(&(l -> readers_proceed), 0);
pthread_cond_init(&(l -> writer_proceed), 0);
}
void mylib_rwlock_rlock(mylib_rwlock_t *l) {
pthread_mutex_lock(&(l -> read_write_lock));
while ((l -> pending_writers > 0) || (l -> writer > 0))
pthread_cond_wait(&(l -> readers_proceed),
&(l -> read_write_lock));
l -> readers ++;
pthread_mutex_unlock(&(l -> read_write_lock));
}
void mylib_rwlock_wlock(mylib_rwlock_t *l) {
pthread_mutex_lock(&(l -> read_write_lock));
while ((l -> writer > 0) || (l -> readers > 0)) {
l -> pending_writers ++;
pthread_cond_wait(&(l -> writer_proceed),
&(l -> read_write_lock));
l -> pending_writers --;
}
l -> writer ++;
pthread_mutex_unlock(&(l -> read_write_lock));
}
void mylib_rwlock_unlock(mylib_rwlock_t *l) {
pthread_mutex_lock(&(l -> read_write_lock));
if (l -> writer > 0)
l -> writer = 0;
else if (l -> readers > 0)
l -> readers --;
pthread_mutex_unlock(&(l -> read_write_lock));
if ((l -> readers == 0) && (l -> pending_writers > 0))
pthread_cond_signal(&(l -> writer_proceed));
else if (l -> readers > 0)
pthread_cond_broadcast(&(l -> readers_proceed));
}
mylib_rwlock_t *read_write_locks;
void *client_operation(void *args);
int main(int argc, char* argv[]) {
if (argc != 3) {
exit(0);
}
int num_str = atoi(argv[2]);
theArray = (char**) malloc(num_str*sizeof(char*));
int i;
read_write_locks = (mylib_rwlock_t *) malloc(sizeof(mylib_rwlock_t) * num_str);
for (i = 0; i < num_str; i ++) {
theArray[i] = malloc(1000 * sizeof(char));
sprintf(theArray[i], "String %d: the initial value", i);
mylib_rwlock_init(&read_write_locks[i]);
}
struct sockaddr_in sock_var;
int serverFileDescriptor=socket(AF_INET,SOCK_STREAM,0);
int clientFileDescriptor;
pthread_t *thread_handles;
thread_handles = malloc(1000*sizeof(pthread_t));
sock_var.sin_addr.s_addr=inet_addr("127.0.0.1");
sock_var.sin_port = strtol(argv[1],0,10);;
sock_var.sin_family=AF_INET;
if(bind(serverFileDescriptor,(struct sockaddr*)&sock_var,sizeof(sock_var))>=0) {
listen(serverFileDescriptor,2000);
while(1) {
total = 0;
for(i = 0; i < 1000 ; i++) {
clientFileDescriptor=accept(serverFileDescriptor,0,0);
pthread_create(&thread_handles[i], 0, client_operation, (void *)clientFileDescriptor);
}
printf("socket has been created\\n");
for(i = 0; i < 1000; i++) {
pthread_join(thread_handles[i], 0);
}
printf("Total Time: %f\\n", total);
}
close(serverFileDescriptor);
} else {
printf("socket creation failed\\n");
}
for(i = 0; i < num_str; i++){
free(theArray[i]);
}
free(theArray);
free(thread_handles);
free(read_write_locks);
return 0;
}
void *client_operation(void *args) {
double start, end;
int clientFileDescriptor = (int) args;
char* temp;
char str_ser[1000];
char str_cli[1000];
int n;
GET_TIME(start);
n = read(clientFileDescriptor, str_cli, sizeof(str_cli));
if (n < 0){
printf("\\nError Reading from Client");
}
char* token;
token = strtok_r(str_cli, " ", &temp);
int pos = atoi(str_cli);
int r_w = atoi(strtok_r(0, " ", &temp));
if(r_w == 1) {
mylib_rwlock_wlock(&read_write_locks[pos]);
snprintf(str_ser,1000,"%s%d%s", "String ", pos, " has been modified by a write request");
strcpy(theArray[pos],str_ser);
mylib_rwlock_unlock(&read_write_locks[pos]);
write(clientFileDescriptor, str_ser, 1000);
} else {
mylib_rwlock_rlock(&read_write_locks[pos]);
strcpy(str_ser, theArray[pos]);
mylib_rwlock_unlock(&read_write_locks[pos]);
write(clientFileDescriptor, str_ser, 1000);
}
GET_TIME(end);
total += end - start;
close(clientFileDescriptor);
return 0;
}
| 1
|
#include <pthread.h>
int memory[(2*320+1)];
int next_alloc_idx = 1;
pthread_mutex_t m;
int top;
int index_malloc(){
int curr_alloc_idx = -1;
pthread_mutex_lock(&m);
if(next_alloc_idx+2-1 > (2*320+1)){
pthread_mutex_unlock(&m);
curr_alloc_idx = 0;
}else{
curr_alloc_idx = next_alloc_idx;
next_alloc_idx = curr_alloc_idx + 2;
pthread_mutex_unlock(&m);
}
return curr_alloc_idx;
}
void EBStack_init(){
top = 0;
}
int isEmpty() {
if(top == 0)
return 1;
else
return 0;
}
int push(int d) {
int oldTop = -1, newTop = -1;
newTop = index_malloc();
if(newTop == 0){
return 0;
}else{
memory[newTop+0] = d;
pthread_mutex_lock(&m);
oldTop = top;
memory[newTop+1] = oldTop;
top = newTop;
pthread_mutex_unlock(&m);
return 1;
}
}
void init(){
EBStack_init();
}
void __VERIFIER_atomic_assert(int r) {
__atomic_begin();
assert(r && isEmpty());
__atomic_end();
}
void push_loop(){
int r = -1;
int arg = __nondet_int();
while(1){
r = push(arg);
__VERIFIER_atomic_assert(r);
}
}
pthread_mutex_t m2;
int state = 0;
void* thr1(void* arg) {
pthread_mutex_lock(&m2);
switch(state) {
case 0:
EBStack_init();
state = 1;
case 1:
pthread_mutex_unlock(&m2);
push_loop();
break;
}
return 0;
}
int main()
{
pthread_t t1,t2;
pthread_create(&t1, 0, thr1, 0);
pthread_create(&t2, 0, thr1, 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t art_at_ctrMutex = PTHREAD_MUTEX_INITIALIZER;
const char *str_at_res_code[ ] =
{
"OK\\r\\n",
"ERROR",
"NO CARRIER\\r\\n",
"NO DIALTONE\\r\\n",
"BUSY\\r\\n",
"NO ANSWER\\r\\n",
"DELAYED\\r\\n",
"CONNECT\\r\\n",
"RING\\r\\n",
0
};
int resp_is_finished(char * buf)
{
char *str = 0;
char **str_cmp = str_at_res_code;
while(*str_cmp){
if(0 != strstr(buf,*str_cmp)){
return 1;
}else{
str_cmp++;
}
}
return 0;
}
int main(int argc, char *argv[])
{
int ret = 0;
int i=0;
int fd=-1;
char atcmd[CMD_LEN];
int size;
char receive[NV_LENGTH];
char at_resp[RESP_MAX_COUNT];
int at_resp_count=0;
if(argc <= 0){
fprintf(stderr, "I:" "error: argc <= 0");
exit(1);
}
pthread_mutex_lock(&art_at_ctrMutex);
memset(at_resp, 0, sizeof(at_resp));
memset(atcmd, 0, sizeof(atcmd));
memset(receive,0,sizeof(receive));
strcpy(atcmd,argv[1]);
strcat(atcmd,"\\r\\n");
at_resp_count = 0;
fd = open(AT_DIVER_FILE, O_RDWR);
write(fd, atcmd, strlen(atcmd)+1);
while(1){
size = read(fd, receive, sizeof(receive)-1);
if(at_resp_count + size >= sizeof(at_resp)){
printf("%s",at_resp);
memset(at_resp, 0, sizeof(at_resp));
memcpy(at_resp,receive,size);
at_resp_count = size;
at_resp[at_resp_count]=0;
}else{
memcpy(&at_resp[at_resp_count],receive,size);
at_resp_count += size;
at_resp[at_resp_count]=0;
}
if(resp_is_finished(at_resp))
{
printf("%s",at_resp);
break;
}
memset(receive,0,sizeof(receive));
usleep(10);
}
close(fd);
pthread_mutex_unlock(&art_at_ctrMutex);
return 0;
}
| 1
|
#include <pthread.h>
int open_socket(char * hostname, int port);
char *generate_get_command(const char * url, char *buf, size_t size);
int s;
int lines=0;
int maxlines=25;
char buf[4096];
int lowmark=0, highmark=0;
int empty=1, full=0, eof=0;
pthread_mutex_t bufmx=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t bufcond=PTHREAD_COND_INITIALIZER;
static void *reader_thread(void *q) {
int res;
pthread_mutex_lock(&bufmx);
while(!eof) {
while (!full) {
pthread_cond_wait(&bufcond, &bufmx);
}
if (highmark>=lowmark) {
pthread_mutex_unlock(&bufmx);
res=read(s, buf+highmark, sizeof(buf)-highmark);
pthread_mutex_lock(&bufmx);
if (res==0) {
eof=1;
break;
}
highmark+=res;
if (highmark==sizeof(buf)) highmark=0;
} else if (highmark<lowmark) {
int t=lowmark;
pthread_mutex_unlock(&bufmx);
res=read(s, buf+highmark, t-highmark);
pthread_mutex_lock(&bufmx);
if (res==0) {
eof=1;
break;
}
}
if (highmark==lowmark) full=1;
empty=0;
pthread_cond_signal(&bufcond);
}
pthread_mutex_unlock(&bufmx);
return 0;
}
static void *writer_thread(void *q) {
int res;
pthread_mutex_lock(&bufmx);
while(!(eof && empty)) {
char *t=buf+lowmark;
char *l;
char tb[10];
while(!empty) {
pthread_cond_wait(&bufcond, &bufmx);
}
if (lowmark<highmark) {
l=buf+highmark;
} else {
l=buf+sizeof(buf);
}
for(; t<l && *t!='\\n'; t++);
if (t<l) {
t++;
lines++;
}
pthread_mutex_unlock(&bufmx);
if (lines>maxlines) {
read(0, tb, 1);
lines=0;
}
res=write(1, buf+lowmark, t-(buf+lowmark));
pthread_mutex_lock(&bufmx);
if (res<0) {
perror("writing to termial");
exit(0);
}
lowmark+=res;
if (lowmark>=sizeof(buf)) lowmark=0;
if (lowmark==highmark) empty=1;
full=0;
pthread_cond_signal(&bufcond);
}
pthread_mutex_unlock(&bufmx);
return 0;
}
int client_body(char *hostname, int port, char *url) {
pthread_t reader, writer;
s=open_socket(hostname, port);
if (s<0) return 0;
generate_get_command(url, buf, sizeof(buf));
write(s, buf, strlen(buf));
pthread_create(&reader, 0, reader_thread, 0);
pthread_create(&writer, 0, writer_thread, 0);
pthread_join(reader, 0);
pthread_join(writer, 0);
return 0;
}
| 0
|
#include <pthread.h>
{
double *matrix;
double *vector;
double *result;
int n;
int thread_num;
int total_threads;
} ARGS;
static long int threads_total_time = 0;
static pthread_mutex_t threads_total_time_mutex
= PTHREAD_MUTEX_INITIALIZER;
static void * matrix_mult_vector_threaded (void *pa)
{
ARGS *pargs = (ARGS*)pa;
long int t;
int i;
printf ("Thread %d started\\n", pargs->thread_num);
t = get_time ();
for (i = 0; i < 10; i++)
{
matrix_mult_vector (pargs->matrix, pargs->vector,
pargs->result, pargs->n,
pargs->thread_num,
pargs->total_threads);
printf ("Thread %d mult %d times\\n",
pargs->thread_num, i);
}
t = get_time () - t;
pthread_mutex_lock (&threads_total_time_mutex);
threads_total_time += t;
pthread_mutex_unlock (&threads_total_time_mutex);
printf ("Thread %d finished, time = %ld\\n",
pargs->thread_num, t);
return 0;
}
int main (int argc, char * argv[])
{
pthread_t * threads;
ARGS * args;
int nthreads;
long int t_full;
int n;
double *matrix;
double *vector;
double *result;
int i, l;
if (argc != 3
|| !(nthreads = atoi (argv[1]))
|| !(n = atoi (argv[2])))
{
printf ("Usage: %s nthreads n\\n", argv[0]);
return 1;
}
if (!(threads = (pthread_t*)
malloc (nthreads * sizeof (pthread_t))))
{
fprintf (stderr, "Not enough memory!\\n");
return 1;
}
if (!(args = (ARGS*) malloc (nthreads * sizeof (ARGS))))
{
fprintf (stderr, "Not enough memory!\\n");
return 2;
}
if (!(matrix = (double*)
malloc (n * n * sizeof (double))))
{
fprintf (stderr, "Not enough memory!\\n");
return 3;
}
if (!(vector = (double*) malloc (n * sizeof (double))))
{
fprintf (stderr, "Not enough memory!\\n");
return 4;
}
if (!(result = (double*) malloc (n * sizeof (double))))
{
fprintf (stderr, "Not enough memory!\\n");
return 5;
}
init_matrix (matrix, n);
init_vector (vector, n);
printf ("Matrix:\\n");
print_matrix (matrix, n);
printf ("Vector:\\n");
print_vector (vector, n);
l = (n * n + 2 * n) * sizeof (double);
printf ("Allocated %d bytes (%dKb or %dMb) of memory\\n",
l, l >> 10, l >> 20);
for (i = 0; i < nthreads; i++)
{
args[i].matrix = matrix;
args[i].vector = vector;
args[i].result = result;
args[i].n = n;
args[i].thread_num = i;
args[i].total_threads = nthreads;
}
t_full = get_full_time ();
for (i = 0; i < nthreads; i++)
{
if (pthread_create (threads + i, 0,
matrix_mult_vector_threaded,
args + i))
{
i);
return 10;
}
}
for (i = 0; i < nthreads; i++)
{
if (pthread_join (threads[i], 0))
}
t_full = get_full_time () - t_full;
if (t_full == 0)
t_full = 1;
print_vector (result, n);
free (threads);
free (args);
free (matrix);
free (vector);
free (result);
printf ("Total full time = %ld, total threads time = %ld (%ld%%), per thread = %ld\\n",
t_full, threads_total_time,
(threads_total_time * 100) / t_full,
threads_total_time / nthreads);
return 0;
}
| 1
|
#include <pthread.h>
extern char **environ;
pthread_mutex_t env_mutex;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
static void
thread_init(void)
{
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&env_mutex, &mutexattr);
pthread_mutexattr_destroy(&mutexattr);
}
int
getenv_r(const char *name, char *buf, int buflen)
{
int i = 0;
int len = 0;
int olen = 0;
pthread_once(&init_done, thread_init);
len = strlen(name);
pthread_mutex_lock(&env_mutex);
for (i = 0; environ[i] != 0; i++)
{
if ((strncmp(name, environ[i], len) == 0)
&& (environ[i][len] == '='))
{
olen = strlen(&environ[i][len + 1]);
if (olen >= buflen)
{
pthread_mutex_unlock(&env_mutex);
return (ENOSPC);
}
strcpy(buf, &environ[i][len + 1]);
pthread_mutex_unlock(&env_mutex);
return 0;
}
}
pthread_mutex_unlock(&env_mutex);
return (ENOSPC);
}
| 0
|
#include <pthread.h>
struct tdata {
int tid;
};
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int padding[64];
int counter[ARRAY_SIZE];
void *count(void *ptr) {
long i, max = MAX_COUNT/NUM_THREADS;
int tid = ((struct tdata *) ptr)->tid;
for (i=0; i < max; i++) {
pthread_mutex_lock(&mutex);
counter[i % ARRAY_SIZE]++;
pthread_mutex_unlock(&mutex);
}
printf("End %d counter: %d\\n", tid, SUM(counter));
}
int main (int argc, char *argv[]) {
pthread_t threads[NUM_THREADS];
int rc, i;
struct tdata id[NUM_THREADS];
for(i=0; i<NUM_THREADS; i++){
id[i].tid = i;
rc = pthread_create(&threads[i], 0, count, (void *) &id[i]);
}
for(i=0; i<NUM_THREADS; i++){
pthread_join(threads[i], 0);
}
printf("Counter value: %d Expected: %d\\n", SUM(counter), MAX_COUNT);
return 0;
}
| 1
|
#include <pthread.h>
uint64_t TimeNowInSec (void) {
return get_currenttime_in_ms() / 1000;
}
int32_t MsgDup(uint8_t *pMsgIn, uint8_t **ppMsgOut, int32_t iLen )
{
uint8_t *pMsg;
pMsg = malloc(iLen);
if( pMsg == 0 )
return 0;
memcpy(pMsg, pMsgIn, iLen );
*ppMsgOut = pMsg;
return 1;
}
void CharToHex(const char *pIn, uint8_t **ppOut, int32_t *pLen)
{
int32_t iLoopIn=0;
int32_t iLoopOut=0;
uint8_t temp;
uint8_t *pOut;
int32_t iLen;
iLen=strlen(pIn);
LogDbg( "%s",pIn );
if (iLen < 12)
{
LogErr("Invalid cmd: %s", pIn);
*pLen=0;
return;
}
pOut=malloc(iLen/2 +1);
iLoopIn=0;
iLoopOut=0;
while (pIn[iLoopIn] != '\\0')
{
temp=pIn[iLoopIn];
if ((temp>=0x30)&&(temp<=0x39))
{
temp=temp-0x30;
}
else if ((temp>=0x41)&&(temp<=0x46))
{
temp=temp-0x41+0x0A;
}
else if((temp>=0x61)&&(temp<=0x66))
{
temp=temp-0x61+0x0A;
}
else
{
goto Error;
}
pOut[iLoopOut]=temp<<4;
if (pIn[iLoopIn+1] == '\\0')
break;
temp=pIn[iLoopIn+1];
if ((temp>=0x30)&&(temp<=0x39))
{
temp=temp-0x30;
}
else if ((temp>=0x41)&&(temp<=0x46))
{
temp=temp-0x41+0x0A;
pOut[iLoopOut]=pOut[iLoopOut]|temp;
}
else if ((temp>=0x61)&&(temp<=0x66))
{
temp=temp-0x61+0x0A;
}
else
{
goto Error;
}
pOut[iLoopOut]=pOut[iLoopOut]|temp;
iLoopIn=iLoopIn+2;
iLoopOut=iLoopOut+1;
}
*ppOut=pOut;
*pLen=iLoopOut;
if (iLoopOut ==0)
free(pOut);
return;
Error:
LogErr("Invalid cmd: %s", pIn);
*pLen=0;
free(pOut);
return;
}
int32_t seq_generator(uint8_t id)
{
static int32_t s_generator[255 + 1] = {0};
static pthread_mutex_t s_mutex[255 + 1];
pthread_mutex_lock(&s_mutex[id]);
int32_t ret = ++s_generator[id];
if (s_generator[id] <= 0) {
s_generator[id] = 1;
}
pthread_mutex_unlock(&s_mutex[id]);
return ret;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.