text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
static int pipe_in[2];
static int pipe_out[2];
static FILE *fifo_in;
static FILE *fifo_out;
static pid_t npid;
static pthread_t th_fifo;
static pthread_mutex_t nmtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t ncnd = PTHREAD_COND_INITIALIZER;
static pthread_condattr_t cndattr;
static int nradio_st = 0;
static void
send_to_slave(const char *format, ...)
{
va_list va;
if (fifo_in == 0) return;
__builtin_va_start((va));
vfprintf(fifo_in, format, va);
fprintf(fifo_in, "\\n");
fflush(fifo_in);
;
}
static void*
thread_fifo (void *arg)
{
char buffer[256] = {0};
int ecnt = 0;
pthread_detach(pthread_self());
pthread_mutex_lock(&nmtx);
nradio_st = 1;
pthread_cond_signal(&ncnd);
pthread_mutex_unlock(&nmtx);
while (fgets(buffer, 256, fifo_out))
{
DBG("%s", buffer);
if (strstr(buffer, "Starting playback") == buffer) {
ecnt = 0;
media_ack(1);
media_append();
}
else if (strstr(buffer, "Exiting") == buffer) {
DBG("--- exit ---\\n");
break;
}
else if (strstr(buffer, "connect error") == buffer) {
media_ack(0);
}
else if (strstr(buffer, "AUDIO: ") == buffer) {
char *ptr;
int rate;
ptr = buffer + 6;
rate = strtol(ptr, 0, 10);
if (rate < 44100) {
nradio_stop();
DBG("--- rate = %d: error ---\\n", rate);
media_on(0);
}
}
else if (strstr(buffer, "read error:: Resource temporarily unavailable") == buffer
||strstr(buffer, "pre-header read failed") == buffer
||strstr(buffer, "read error:: Connection reset by peer") == buffer) {
DBG("--- player error ---\\n");
if (ecnt == 0) {
media_on(0);
++ecnt;
}
if (ecnt >= 20) {
nradio_stop();
media_ack(0);
}
}
memset(buffer, 0, 256);
}
pthread_mutex_lock(&nmtx);
nradio_st = 0;
pthread_cond_signal(&ncnd);
pthread_mutex_unlock(&nmtx);
pthread_exit (0);
}
int
nradio_init(void)
{
if (pipe(pipe_in))
return -1;
if (pipe(pipe_out))
{
close(pipe_in[0]);
close(pipe_in[1]);
return -1;
}
npid = fork();
switch (npid) {
case 0:
{
char *params[32];
int pp = 0;
close (pipe_in[1]);
close (pipe_out[0]);
dup2 (pipe_in[0], STDIN_FILENO);
close (pipe_in[0]);
dup2 (pipe_out[1], STDERR_FILENO);
dup2 (pipe_out[1], STDOUT_FILENO);
close (pipe_out[1]);
params[pp++] = "netradio";
params[pp++] = "-af-clr";
params[pp++] = "-ac";
params[pp++] = "mad,";
params[pp++] = "-slave";
params[pp++] = "-quiet";
params[pp++] = "-idle";
params[pp++] = "-noconsolecontrols";
params[pp++] = "-vc";
params[pp++] = "null";
params[pp++] = "-vo";
params[pp++] = "null";
params[pp++] = "-ao";
params[pp++] = "alsa";
params[pp++] = "-cache";
params[pp++] = "4096";
params[pp++] = "-cache-min";
params[pp++] = "2";
params[pp++] = "-bandwidth";
params[pp++] = "10000000";
params[pp] = 0;
execvp ("netradio", params);
exit(0);
}
case -1:
break;
default:
{
close (pipe_in[0]);
close (pipe_out[1]);
fifo_in = fdopen(pipe_in[1], "w");
fifo_out = fdopen(pipe_out[0], "r");
pthread_condattr_init(&cndattr);
pthread_condattr_setclock(&cndattr, CLOCK_MONOTONIC);
pthread_cond_init(&ncnd, &cndattr);
pthread_mutex_lock(&nmtx);
pthread_create (&th_fifo, 0, thread_fifo, 0);
while (nradio_st == 0)
pthread_cond_wait(&ncnd, &nmtx);
pthread_mutex_unlock(&nmtx);
return npid;
}
}
return -1;
}
static void
nradio_uninit (void)
{
struct timespec ts;
int r = 0;
if (fifo_in)
{
pthread_mutex_lock(&nmtx);
r = 0;
while (nradio_st != 0&&r == 0) {
clock_gettime(CLOCK_MONOTONIC, &ts);
ts.tv_sec += 3;
r = pthread_cond_timedwait(&ncnd, &nmtx, &ts);
}
pthread_mutex_unlock(&nmtx);
if (r != 0) {
DBG("--- kill nradio process ---\\n");
kill(npid, SIGKILL);
}
waitpid(npid, 0, 0);
close(pipe_in[1]);
close(pipe_out[0]);
fclose(fifo_in);
fclose(fifo_out);
fifo_in = 0;
fifo_out = 0;
DBG("--- netradio exited ---\\n");
}
}
void
nradio_play(char *url)
{
send_to_slave("loadfile %s", url);
}
void
nradio_append(char *url)
{
send_to_slave("loadfile %s 1", url);
}
void
nradio_stop(void)
{
send_to_slave("stop");
}
void
nradio_quit(void)
{
send_to_slave("quit");
nradio_uninit();
}
| 1
|
#include <pthread.h>
int P,H,S,A;
int passenger_no,p_handler,p_screen,p_seat;
int count;
sem_t handler,screener,go_handler,go_screener,go_attendant,seated,M;
pthread_mutex_t mutex;
void *Handler(void *args){
while(1)
{
sem_wait(&go_handler);
sem_post(&handler);
}
}
void *Screener(void *args){
while(1)
{
sem_wait(&go_screener);
sem_post(&screener);
}
}
void *Attendant(void *args){
while(1)
{
sem_wait(&go_attendant);
count++;
sem_post(&seated);
if(count==P)
{
sem_post(&M);
break;
}
}
}
void *Passenger(void *args){
pthread_mutex_lock(&mutex);
passenger_no++;
pthread_mutex_unlock(&mutex);
sem_post(&go_handler);
sem_wait(&handler);
sem_post(&go_screener);
sem_wait(&screener);
sem_post(&go_attendant);
sem_wait(&seated);
pthread_exit(0);
}
int main(int argc,char *argv[])
{
P = atoi(argv[1]);
H = atoi(argv[2]);
S = atoi(argv[3]);
A = atoi(argv[4]);
pthread_t passengers[P],handlers[H],screeners[S],attendants[A];
int rc1,rc2,rc3,rc4;
sem_init(&handler,0,0);
sem_init(&screener,0,0);
sem_init(&go_handler,0,0);
sem_init(&go_screener,0,0);
sem_init(&go_attendant,0,0);
sem_init(&seated,0,0);
sem_init(&M,0,0);
pthread_mutex_init(&mutex,0);
for(int i=1;i<=H;i++)
{
rc1=pthread_create(&handlers[i],0,Handler,0);
if(rc1)
{
printf("Error: return code from pthread_create() is %d\\n",rc1);
exit(-1);
}
}
for(int i=1;i<=S;i++)
{
rc2=pthread_create(&screeners[i],0,Screener,0);
if(rc2)
{
printf("Error: return code from pthread_create() is %d\\n",rc2);
exit(-1);
}
}
for(int i=1;i<=A;i++)
{
rc3=pthread_create(&attendants[i],0,Attendant,0);
if(rc3)
{
printf("Error: return code from pthread_create() is %d\\n",rc3);
exit(-1);
}
}
for(int i=1;i<=P;i++)
{
rc4=pthread_create(&passengers[i],0,Passenger,0);
if(rc4)
{
printf("Error: return code from pthread_create() is %d\\n",rc4);
exit(-1);
}
}
sem_wait(&M);
printf("All passengers on board! Plane finally departs!!!\\n");
for(int i=1;i<=P;i++)
{
pthread_join(passengers[i],0);
}
sem_destroy(&handler);
sem_destroy(&screener);
sem_destroy(&go_handler);
sem_destroy(&go_screener);
sem_destroy(&go_attendant);
sem_destroy(&seated);
sem_destroy(&M);
pthread_mutex_destroy(&mutex);
return 1;
exit(0);
}
| 0
|
#include <pthread.h>
int rank;
pthread_mutex_t mutex;
pthread_cond_t cond;
} thread_data;
thread_data td[20];
void* hello_thread(void *rank) {
int thread_rank = *(int *)rank;
if (thread_rank > 0) {
thread_data *prev = &td[thread_rank - 1];
pthread_mutex_lock(&prev->mutex);
pthread_cond_wait(&prev->cond, &prev->mutex);
pthread_mutex_unlock(&prev->mutex);
}
printf("Hello from thread %d\\n", thread_rank);
if (thread_rank < 20 -1) {
thread_data *curr = &td[thread_rank];
pthread_mutex_lock(&curr->mutex);
pthread_cond_signal(&curr->cond);
pthread_mutex_unlock(&curr->mutex);
}
return 0;
}
int main(void) {
int rank = 0;
int err;
pthread_t thread_ids[20];
while(rank < 20) {
pthread_mutex_init(&td[rank].mutex, 0);
pthread_cond_init(&td[rank].cond, 0);
rank++;
}
rank = 0;
while(rank < 20) {
td[rank].rank = rank;
err = pthread_create(&(thread_ids[rank]), 0, hello_thread, (void*)&td[rank].rank);
if (err != 0) {
printf("Can't create thread error =%d\\n", err);
return 1;
}
rank++;
}
rank = 0;
while(rank < 20) {
pthread_join(thread_ids[rank], 0);
rank++;
}
rank = 0;
while(rank < 20) {
pthread_mutex_destroy(&td[rank].mutex);
pthread_cond_destroy(&td[rank].cond);
rank++;
}
return 0;
}
| 1
|
#include <pthread.h>
double cx_min;
double cx_max;
double cy_min;
double cy_max;
int ix_max;
int iy_max;
double pixel_width;
double pixel_height;
int image_size;
int image_buffer_size;
unsigned char **image_buffer;
int nthreads;
int current_iy;
pthread_mutex_t stacklock = PTHREAD_MUTEX_INITIALIZER;
int colors[16 + 1][3] = {
{66, 30, 15},
{25, 7, 26},
{9, 1, 47},
{4, 4, 73},
{0, 7, 100},
{12, 44, 138},
{24, 82, 177},
{57, 125, 209},
{134, 181, 229},
{211, 236, 248},
{241, 233, 191},
{248, 201, 95},
{255, 170, 0},
{204, 128, 0},
{153, 87, 0},
{106, 52, 3},
{0, 0, 0},
};
void allocate_image_buffer(){
image_buffer = (unsigned char **) malloc(sizeof(unsigned char *) * image_buffer_size);
for (int i = 0; i < image_buffer_size; i++) {
image_buffer[i] = (unsigned char *) malloc(sizeof(unsigned char) * 3);
};
};
void init(int argc, char *argv[]){
if(argc < 6){
printf("usage: ./mandelbrot_pth cx_min cx_max cy_min cy_max nthreads image_size\\n");
printf("examples with image_size = 11500:\\n");
printf(" Full Picture: ./mandelbrot_pth -2.5 1.5 -2.0 2.0 8 11500\\n");
printf(" Seahorse Valley: ./mandelbrot_pth -0.8 -0.7 0.05 0.15 8 11500\\n");
printf(" Elephant Valley: ./mandelbrot_pth 0.175 0.375 -0.1 0.1 8 11500\\n");
printf(" Triple Spiral Valley: ./mandelbrot_pth -0.188 -0.012 0.554 0.754 8 11500\\n");
exit(0);
} else {
sscanf(argv[1], "%lf", &cx_min);
sscanf(argv[2], "%lf", &cx_max);
sscanf(argv[3], "%lf", &cy_min);
sscanf(argv[4], "%lf", &cy_max);
sscanf(argv[5], "%d", &nthreads);
sscanf(argv[6], "%d", &image_size);
ix_max = image_size;
iy_max = image_size;
image_buffer_size = image_size * image_size;
pixel_width = (cx_max - cx_min) / ix_max;
pixel_height = (cy_max - cy_min) / iy_max;
};
};
void update_rgb_buffer(int iteration, int x, int y){
if (iteration == 200) {
image_buffer[(iy_max * y) + x][0] = colors[16][0];
image_buffer[(iy_max * y) + x][1] = colors[16][1];
image_buffer[(iy_max * y) + x][2] = colors[16][2];
} else {
int color = iteration % 16;
image_buffer[(iy_max * y) + x][0] = colors[color][0];
image_buffer[(iy_max * y) + x][1] = colors[color][1];
image_buffer[(iy_max * y) + x][2] = colors[color][2];
};
};
void write_to_file() {
FILE * file;
char * filename = "output.ppm";
int max_color_component_value = 255;
file = fopen(filename,"wb");
fprintf(file, "P6\\n %s\\n %d\\n %d\\n %d\\n", comment,
ix_max, iy_max, max_color_component_value);
for(int i = 0; i < image_buffer_size; i++){
fwrite(image_buffer[i], 1 , 3, file);
};
fclose(file);
};
void *compute_mandelbrot(void *threadid){
int iteration;
double cx;
double cy;
double zx;
double zy;
double zx_squared;
double zy_squared;
int iy;
int row;
pthread_mutex_lock(&stacklock);
iy = current_iy++;
pthread_mutex_unlock(&stacklock);
while (iy < image_size) {
cy = cy_min + iy * pixel_height;
for (int ix = 0; ix < image_size; ix++) {
cx = cx_min + ix * pixel_width;
zx = 0.0;
zy = 0.0;
zx_squared = 0.0;
zy_squared = 0.0;
for(iteration = 0;
iteration < 200 &&
((zx_squared + zy_squared) < 4);
iteration++){
zy = 2 * zx * zy + cy;
zx = zx_squared - zy_squared + cx;
zx_squared = zx * zx;
zy_squared = zy * zy;
};
update_rgb_buffer(iteration, ix, iy);
};
pthread_mutex_lock(&stacklock);
iy = current_iy++;
pthread_mutex_unlock(&stacklock);
};
pthread_exit(0);
};
int main(int argc, char *argv[]){
init(argc, argv);
current_iy = 0;
allocate_image_buffer();
pthread_t threads[nthreads];
int errorcode;
long t;
for(t = 0; t < nthreads; t++) {
errorcode = pthread_create(&threads[t], 0, compute_mandelbrot, (void *) t);
if (errorcode) {
printf("ERROR pthread_create(): %d\\n", errorcode);
exit(-1);
};
};
for(t = 0; t < nthreads; t++) {
pthread_join(threads[t], 0);
}
write_to_file();
return 0;
};
| 0
|
#include <pthread.h>
struct foo {
int f_count;
pthread_mutex_t f_lock;
struct foo *f_next;
int f_id;
};
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo *foo_alloc(int id) {
struct foo *fp;
int idx;
if((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 0;
if(pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return 0;
}
idx = (((unsigned long)fp) % 29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
fp->f_id = id;
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
printf("object id %d at hash index %d\\n", id, idx);
}
return fp;
}
void foo_hold(struct foo *fp) {
pthread_t tid = pthread_self();
if (fp == 0) {
err_msg("get NULL fp in foo_hold\\n");
return;
}
pthread_mutex_lock(&hashlock);
++fp->f_count;
printf("foo_hold: thread %ld gets lock, object id %d, f_count %d\\n",
tid, fp->f_id, fp->f_count);
pthread_mutex_unlock(&hashlock);
}
struct foo *foo_find(struct foo *ifp, int id) {
struct foo *fp;
int idx;
idx = (((unsigned long)ifp) % 29);
pthread_mutex_lock(&hashlock);
for(fp = fh[idx]; fp != 0; fp = fp->f_next) {
if(fp->f_id == id) {
++fp->f_count;
break;
}
}
pthread_mutex_unlock(&hashlock);
return fp;
}
void foo_rele(struct foo *fp) {
struct foo *tfp;
int idx;
pthread_t tid = pthread_self();
pthread_mutex_lock(&hashlock);
if(--fp->f_count == 0) {
idx = (((unsigned long)fp) % 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_destroy(&fp->f_lock);
printf("foo_rele: thread %ld free object id %d\\n",
tid, fp->f_id);
free(fp);
} else {
pthread_mutex_unlock(&hashlock);
}
}
void fh_init() {
int i;
pthread_mutex_lock(&hashlock);
for(i = 0; i < 29; ++i)
fh[i] = 0;
pthread_mutex_unlock(&hashlock);
}
pthread_t thdarr[1000];
void *thr_fn(void *arg) {
int id, i;
pthread_t tid = pthread_self();
struct foo *fp = 0;
id = tid % 100;
for(i = 0; i < 29; ++i) {
if(fh[i] != 0) {
fp = foo_find(fh[i], id);
if(fp != 0){
printf("thread %ld finds object id %d at hash idx %d\\n",
tid, id, i);
break;
}
}
}
if(fp != 0) {
sleep(1);
foo_rele(fp);
} else {
printf("thread %ld can't find id %d\\n", tid, id);
}
printf("thread %ld returns\\n", tid);
return (void *)0;
}
int main(void) {
struct foo *fp;
int i, err, thrjoin;
pthread_t tid;
fh_init();
for (i = 0; i < 100; ++i) {
if ((fp = foo_alloc(i)) == 0)
err_sys("foo_alloc error");
}
for (i = 0; i < 1000; ++i) {
err = pthread_create(&tid, 0, thr_fn, 0);
if (err != 0)
err_quit("can't create thread: %s\\n", strerror(err));
thdarr[i] = tid;
printf("new thread %ld\\n", tid);
}
while(1) {
thrjoin = 0;
for(i = 0; i < 1000; ++i) {
if(thdarr[i] != 0) {
pthread_join(thdarr[i], 0);
thdarr[i] = 0;
thrjoin = 1;
}
}
if(thrjoin == 0)
return 0;
sleep(1);
}
return 0;
}
| 1
|
#include <pthread.h>
long sum=0;
struct interval {
long start;
long end;
int tid;
};
pthread_mutex_t sum_mutex;
void *add(void *arg)
{
intv *myinterval = (intv*) arg;
long start = myinterval->start;
long end = myinterval->end;
printf("I am thread %d and my interval is %ld to %ld\\n",
myinterval->tid,start,end);
long j,mysum=0;
for(j=start;j<=end;j++) {
mysum += j;
}
pthread_mutex_lock(&sum_mutex);
sum += mysum;
pthread_mutex_unlock(&sum_mutex);
printf("Thread %d finished\\n",myinterval->tid);
pthread_exit((void*) 0);
}
int main (int argc, char *argv[])
{
intv *intervals;
intervals = (intv*) malloc(4*sizeof(intv));
void *status;
pthread_t threads[4];
pthread_mutex_init(&sum_mutex,0);
int i;
for(i=0; i<4; i++) {
intervals[i].start = i*(1280000000/4);
intervals[i].end = (i+1)*(1280000000/4) - 1;
intervals[i].tid=i;
pthread_create(&threads[i], 0, add, (void *) &intervals[i]);
}
for(i=0; i<4; i++)
pthread_join(threads[i], &status);
printf ("Final Global Sum=%li\\n",sum);
free (intervals);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int nitems;
int buff[1000000];
struct {
pthread_mutex_t mutex;
int nput;
int nval;
} put = {
PTHREAD_MUTEX_INITIALIZER
};
struct {
pthread_mutex_t mutex;
pthread_cond_t cond;
int nready;
} nready = {
PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER
};
int myMin(int a, int b) {
return a < b ? a : b;
}
void *produce(void *arg) {
for( ; ; ) {
pthread_mutex_lock(&put.mutex);
if(put.nput >= nitems) {
pthread_mutex_unlock(&put.mutex);
return 0;
}
buff[put.nput] = put.nval;
++put.nput;
++put.nval;
pthread_mutex_unlock(&put.mutex);
pthread_mutex_lock(&nready.mutex);
if(nready.nready == 0) {
pthread_cond_signal(&nready.cond);
}
++nready.nready;
pthread_mutex_unlock(&nready.mutex);
*((int *) arg) += 1;
}
}
void *consume(void *arg) {
int i;
for(i = 0; i < nitems; ++i) {
pthread_mutex_lock(&nready.mutex);
while(nready.nready == 0)
pthread_cond_wait(&nready.cond, &nready.mutex);
--nready.nready;
pthread_mutex_unlock(&nready.mutex);
if(buff[i] != i)
printf("buff[%d] = %d\\n", i, buff[i]);
}
return 0;
}
int main(int argc, const char *argv[]) {
int i, nthreads, count[100];
pthread_t tid_produce[100], tid_consume;
if(argc != 3) {
exit(1);
}
nitems = myMin(atoi(argv[1]), 1000000);
nthreads = myMin(atoi(argv[2]), 100);
pthread_setconcurrency(nthreads + 1);
for(i = 0; i < nthreads; ++i) {
count[i] = 0;
pthread_create(&tid_produce[i], 0, produce, &count[i]);
}
pthread_create(&tid_consume, 0, consume, 0);
for(i = 0; i < nthreads; ++i) {
pthread_join(tid_produce[i], 0);
printf("count[%d] = %d\\n", i, count[i]);
}
pthread_join(tid_consume, 0);
exit(0);
}
| 1
|
#include <pthread.h>
int *a;
pthread_mutex_t *mutex;
} args;
void *thread(void *arg){
int *a = ((args*)arg)->a;
pthread_mutex_t *mutex = ((args*)arg)->mutex;
int i;
pthread_mutex_lock(mutex);
for(i=0; i < 1000; i++) {
(*a)++;
}
pthread_mutex_unlock(mutex);
pthread_exit(0);
}
int main(){
clock_t begin, end;
double time_spent;
begin = clock();
int count = 0;
int numOfThreads = 1000;
pthread_t tid[numOfThreads];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
args args1;
args1.a = &count;
args1.mutex = &mutex;
int threadCount = 0;
for(threadCount = 0; threadCount < numOfThreads; threadCount++){
Pthread_create(&tid[threadCount], 0, thread, &args1);
}
int joinCount;
for(joinCount = 0; joinCount < threadCount; joinCount++){
Pthread_join(tid[joinCount],0);
}
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("*********************\\n");
printf("* Lock Outside for *\\n");
printf("*********************\\n");
printf("Threads created: %d\\n", threadCount);
printf("count= %d\\n",count);
printf("Time = %f\\n",time_spent);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t *crypto_lock = 0;
static pthread_t pthread_id_cb()
{
return pthread_self();
}
static void pthread_locking_cb(int mode, int n, const char *file, int line)
{
if(mode & CRYPTO_LOCK)
pthread_mutex_lock(&crypto_lock[n]);
else
pthread_mutex_unlock(&crypto_lock[n]);
}
int pthread_setup()
{
int loop = 0;
crypto_lock = (pthread_mutex_t*)OPENSSL_malloc(CRYPTO_num_locks()*sizeof(pthread_mutex_t));
if(!crypto_lock)
return 0;
for(loop = 0; loop < CRYPTO_num_locks(); loop ++)
pthread_mutex_init(&crypto_lock[loop], 0);
CRYPTO_set_id_callback(pthread_id_cb);
CRYPTO_set_locking_callback(pthread_locking_cb);
return 1;
}
int pthread_cleanup()
{
int loop = 0;
if(!crypto_lock)
return 0;
CRYPTO_set_id_callback(0);
CRYPTO_set_locking_callback(0);
for(loop = 0; loop < CRYPTO_num_locks(); loop ++)
pthread_mutex_destroy(&crypto_lock[loop]);
OPENSSL_free(crypto_lock);
crypto_lock = 0;
return 1;
}
| 1
|
#include <pthread.h>
static pthread_key_t key;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;
extern char **environ;
static void thread_init(){
pthread_key_create(&key, free);
}
char *getenv(const char *name){
int i, len;
char *envbuf;
pthread_once(&init_done, thread_init);
pthread_mutex_lock(&env_mutex);
envbuf = (char *)malloc(ARG_MAX);
if(envbuf == 0){
pthread_mutex_unlock(&env_mutex);
if(envbuf == 0){
pthread_mutex_unlock(&env_mutex);
return 0;
}
pthread_setspecific(key, envbuf);
}
len = strlen(name);
for(i = 0; environ[i] != 0; ++i){
if((strncmp(name, environ[i], len) == 0) &&
(environ[i][len] == '=')){
strcpy(envbuf, &environ[i][len+1]);
pthread_mutex_unlock(&env_mutex);
return envbuf;
}
}
pthread_mutex_unlock(&env_mutex);
return 0;
}
int main(){
char *name = "USER";
char *value = 0;
if((value = getenv(name)) == 0)
printf("There is no value of %s in environment\\n", name);
else
printf("The %s environment's value is : %s\\n", name, value);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t m;
pthread_cond_t cl, ce;
int ecriture;
int nb_lecteurs, nb_lect_att, nb_ecri_att;
} lectred;
int nb;
struct linked_list *next;
} linked_list;
struct lectred sync;
struct linked_list *head;
} linked_list_head;
linked_list_head llh;
void init(lectred* l) {
pthread_mutex_init(&(l->m), 0);
pthread_cond_init(&(l->cl), 0);
pthread_cond_init(&(l->ce), 0);
l->ecriture = 0;
l->nb_lect_att = 0;
l->nb_ecri_att = 0;
l->nb_lecteurs = 0;
}
void begin_read(lectred* l) {
pthread_mutex_lock(&(l->m));
while(l->ecriture == 1 || l->nb_ecri_att > 0){
l->nb_lect_att++;
pthread_cond_wait(&(l->cl), &(l->m));
l->nb_lect_att--;
}
l->nb_lecteurs++;
pthread_mutex_unlock(&(l->m));
}
void end_read(lectred* l) {
pthread_mutex_lock(&(l->m));
l->nb_lecteurs--;
if(l->nb_lect_att == 0 && l->nb_ecri_att > 0){
pthread_cond_signal(&(l->cl));
}
pthread_mutex_unlock(&(l->m));
}
void begin_write(lectred* l) {
pthread_mutex_lock(&(l->m));
while(l->ecriture == 1 || l->nb_lecteurs > 0){
l->nb_ecri_att++;
pthread_cond_wait(&(l->ce), &(l->m));
l->nb_ecri_att--;
}
l->ecriture = 1;
pthread_mutex_unlock(&(l->m));
}
void end_write(lectred* l) {
pthread_mutex_lock(&(l->m));
l->ecriture = 0;
if(l->nb_ecri_att > 0){
pthread_cond_signal(&(l->ce));
}
else if(l->nb_lect_att > 0){
pthread_cond_broadcast(&(l->cl));
}
pthread_mutex_unlock(&(l->m));
}
void list_init(linked_list_head *list) {
list->head = 0;
init(&list->sync);
}
int exists(struct linked_list_head *list, int val) {
begin_read(&list->sync);
printf("thread %u lit\\n", (unsigned int) pthread_self());
sleep(rand() % 5);
end_read(&list->sync);
return 0;
}
linked_list* add_elem(linked_list_head* list, int val) {
begin_write(&list->sync);
printf("thread %u écrit\\n", (unsigned int) pthread_self());
sleep(rand() % 5);
end_write(&list->sync);
return list->head;
}
linked_list* remove_element(struct linked_list_head *list, int val) {
begin_write(&list->sync);
end_write(&list->sync);
return list->head;
}
void* lecteurs() {
int r = rand() % (10-1) + 1;
if (exists(&llh, r)) {}
return (void *) pthread_self();
}
void* redacteurs() {
int r = rand() % (10-1) + 1;
add_elem(&llh, r);
return (void *) pthread_self() ;
}
int main (int argc, char** argv) {
if (argc != 3) {
printf("Usage : <nb_lecteurs> <nb_redacteurs>\\n");
}
int nb_lecteurs = atoi(argv[1]);
int nb_redacteurs = atoi(argv[2]);
int i=0;
list_init(&llh);
printf("liste initialisée\\n");
pthread_t tids[nb_redacteurs + nb_lecteurs];
for (; i < nb_redacteurs; i++){
pthread_create(&tids[i], 0, &redacteurs, 0);
}
printf("rédacteurs créés\\n");
for (; i < nb_lecteurs+nb_redacteurs; i++){
pthread_create(&tids[i], 0, &lecteurs, 0);
}
printf("lecteurs créés\\n");
for (i = 0; i < nb_lecteurs+nb_redacteurs; i++){
pthread_join(tids[i], 0);
}
}
| 1
|
#include <pthread.h>
struct thread_data{
int thread_id;
int sum;
char *message;
};
pthread_mutex_t mutexA[7 +1];
void *PrintHello(void *threadarg)
{
long taskid, sum;
struct thread_data *my_data;
char *message;
my_data = (struct thread_data *) threadarg;
taskid = my_data->thread_id;
sum = my_data->sum;
message = my_data->message;
switch (taskid) {
case 2:
pthread_mutex_lock(&mutexA[1]);
pthread_mutex_unlock(&mutexA[1]);
break;
case 3:
pthread_mutex_lock(&mutexA[1]);
pthread_mutex_unlock(&mutexA[1]);
break;
case 4:
pthread_mutex_lock(&mutexA[2]);
pthread_mutex_unlock(&mutexA[2]);
break;
case 5:
pthread_mutex_lock(&mutexA[4]);
pthread_mutex_unlock(&mutexA[4]);
break;
case 6:
pthread_mutex_lock(&mutexA[3]);
pthread_mutex_unlock(&mutexA[3]);
pthread_mutex_lock(&mutexA[4]);
pthread_mutex_unlock(&mutexA[4]);
break;
case 7:
pthread_mutex_lock(&mutexA[5]);
pthread_mutex_unlock(&mutexA[5]);
pthread_mutex_lock(&mutexA[6]);
pthread_mutex_unlock(&mutexA[6]);
break;
default:
break;
}
if (pthread_mutex_unlock(&mutexA[taskid])) printf("\\nERROR on unlock\\n");
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int arg,i,j,k,m;
pthread_t threads[7 +1];
struct thread_data thread_data_array[7 +1];
int rc;
long t;
char *Messages[7 +1] = {"Zeroth Message",
"First Message",
"Second Message",
"Third Message",
"Fourth Message",
"Fifth Message",
"Sixth Message",
"Seventh Message"};
char dummy[1];
for (i = 0; i <= 7; i++) {
if (pthread_mutex_init(&mutexA[i], 0)) {
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
for (i = 0; i <= 7; i++) {
if (pthread_mutex_lock(&mutexA[i])) {
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
printf("\\n Hello World! It's me, MAIN!\\n");
for (t = 2; t <= 7; t++) {
thread_data_array[t].thread_id = t;
thread_data_array[t].sum = t+28;
thread_data_array[t].message = Messages[t];
rc = pthread_create(&threads[t], 0, PrintHello,
(void*) &thread_data_array[t]);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
sleep(1);
printf("\\n Created threads 2-7, type any character and <enter>\\n");
scanf("%s", dummy);
printf("\\nWaiting for thread 7 to finish, UNLOCK LOCK 1\\n");
if (pthread_mutex_unlock(&mutexA[1])) printf("\\nERROR on unlock\\n");
printf("\\n Done unlocking 1 \\n");
pthread_mutex_lock(&mutexA[7]);
for (t = 2; t <= 7; t++) {
if (pthread_join(threads[t],0)){
printf("\\n ERROR on join\\n");
exit(19);
}
}
printf("\\nAfter joining");
printf("\\nGOODBYE WORLD! \\n");
return(0);
}
| 0
|
#include <pthread.h>
int cont;
int id;
} estrutura;
volatile estrutura estr;
pthread_mutex_t mutex;
pthread_cond_t cond;
volatile int lendo = 0, escrevendo = 0, filaEscrever = 0;
volatile int lido[20];
volatile int continua;
int todasLeram () {
int res = 1, i;
for (i = 0; i < 20; ++i)
res &= lido[i];
return res;
}
void zeraLido () {
int i;
for (i = 0; i < 20; ++i)
lido[i] = 0;
}
void * escrever (void * tid) {
int id = * (int *) tid;
free(tid);
while (1) {
pthread_mutex_lock(&mutex);
printf("Thread %d (escritora) iniciada\\n", id);
while (lendo || escrevendo || !(todasLeram() || estr.id == -1))
pthread_cond_wait(&cond, &mutex);
escrevendo = 1;
estr.cont++;
estr.id = id;
escrevendo = 0;
zeraLido();
pthread_cond_broadcast(&cond);
printf("Thread %d escrevendo\\n", id);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void * ler (void * tid) {
int id = * (int *) tid;
free(tid);
estrutura estrLocal;
while (1) {
pthread_mutex_lock(&mutex);
printf("Thread %d (leitora) iniciada\\n", id);
while (lido[id] || escrevendo) {
pthread_cond_wait(&cond, &mutex);
}
lendo = 1;
estrLocal.cont = estr.cont;
estrLocal.id = estr.id;
lendo = 0;
lido[id] = 1;
pthread_cond_broadcast(&cond);
printf("Thread %d (leitora) - id: %d - cont: %d\\n", id, estrLocal.id, estrLocal.cont);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main(int argc, char const *argv[]) {
pthread_t threads[(20 + 200)];
int i, *tid;
estr.cont = 0;
estr.id = -1;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
for (i = 0; i < 20; ++i)
lido[i] = 1;
for (i = 0; i < 200; ++i) {
tid = malloc(sizeof(int));
*tid = i;
pthread_create(&threads[*tid], 0, ler, (void *) tid);
}
for (i = 0; i < 20; ++i) {
tid = malloc(sizeof(int));
*tid = 200 + i;
pthread_create(&threads[*tid], 0, escrever, (void *) tid);
}
for (i = 0; i < (20 + 200); ++i) {
pthread_join(threads[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int* pData = 0;
static void *WaitThread(void *arg)
{
while (1) {
pthread_mutex_lock(&mtx);
if(pData == 0)
{
pthread_cond_wait(&cond, &mtx);
}
*pData=1;
free(pData);
pData=0;
pthread_mutex_unlock(&mtx);
}
return 0;
}
int main(void)
{
int i;
struct node *p;
pthread_t tid1;
pthread_t tid2;
pthread_t tid3;
pthread_t tid4;
pthread_create(&tid1, 0, WaitThread, 0);
pthread_create(&tid2, 0, WaitThread, 0);
pthread_create(&tid3, 0, WaitThread, 0);
pthread_create(&tid4, 0, WaitThread, 0);
while(1)
{
pthread_mutex_lock(&mtx);
if(pData == 0)
pData = (int*)malloc(sizeof(int));
pthread_mutex_unlock(&mtx);
pthread_cond_signal(&cond);
}
pthread_join(tid1, 0);
pthread_join(tid2, 0);
pthread_join(tid3, 0);
pthread_join(tid4, 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
void *functionCount1();
void *functionCount2();
int count = 0;
int main()
{
pthread_t thread1, thread2;
pthread_create( &thread1, 0, &functionCount1, 0);
pthread_create( &thread2, 0, &functionCount2, 0);
pthread_join( thread1, 0);
pthread_join( thread2, 0);
printf("Final count: %d\\n",count);
exit(0);
}
void *functionCount1()
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
pthread_cond_wait( &condition_var, &count_mutex );
count++;
printf("Counter value functionCount1: %d\\n",count);
pthread_mutex_unlock( &count_mutex );
if(count >= 20)
return(0);
}
pthread_exit(0);
}
void *functionCount2()
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
if( count < 5 || count > 15 )
pthread_cond_signal( &condition_var );
else
{
count++;
printf("Counter value functionCount2: %d\\n",count);
}
pthread_mutex_unlock( &count_mutex );
if(count >= 20)
return(0);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t cond;
data_t data;
struct _node *next;
}node_t,*node_p,**node_pp,*list_head;
list_head head = 0;
static node_p buy_node(data_t _data)
{
node_p new_node = (node_p)malloc(sizeof(node_t));
if( 0 == new_node ){
perror("malloc");
exit(1);
}
new_node->data = _data;
new_node->next = 0;
return new_node;
}
static void delete_node(node_p _node)
{
if(_node){
free(_node);
_node = 0;
}
}
int is_empty(list_head _head)
{
if( _head && 0 == _head->next){
return 1;
}
return 0;
}
void list_init(node_pp _head)
{
*_head = buy_node(-1);
}
void push_head(list_head _head,data_t _data)
{
if(_head){
node_p tmp = buy_node(_data);
tmp->next = _head->next;
_head->next = tmp;
}
}
int pop_head(list_head _head, data_t* _data)
{
if(is_empty(_head)){
return 0;
}
node_p tmp = head->next;
head->next = head->next->next;
*_data = tmp->data;
delete_node(tmp);
return 1;
}
void clear(list_head _head)
{
data_t tmp = 0;
while(!is_empty(_head)){
pop_head(_head,&tmp);
}
delete_node(_head);
}
void show_list(list_head _head)
{
node_p ptr = _head->next;
while(ptr){
printf("%d ",ptr->data);
ptr = ptr->next;
}
}
void* comsumer_data(void* arg)
{
int count = 50;
data_t _data = -1;
while(count){
pthread_mutex_lock(&lock);
while(is_empty(head)){
pthread_cond_wait(&cond,&lock);
}
int ret = pop_head(head,&_data);
pthread_mutex_unlock(&lock);
if(ret == 0){
printf("consumer data failed\\n");
}else{
printf("consumer data done : %d\\n",_data);
}
sleep(1);
count--;
_data = -1;
}
}
void* producter_data(void* arg)
{
int count = 50;
while(count){
pthread_mutex_lock(&lock);
push_head(head,count);
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
printf("data is ready,signal consumer!\\n");
printf("producter data done : %d\\n",count);
sleep(5);
count--;
}
}
int main()
{
pthread_mutex_init(&lock,0);
pthread_cond_init(&cond,0);
list_init(&head);
pthread_t consumer,producter;
pthread_create(&consumer,0,comsumer_data,0);
pthread_create(&producter,0,producter_data,0);
pthread_join(consumer,0);
pthread_join(producter,0);
clear(head);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
void *threadFunc(void *arg)
{
int threadNum = (int)arg;
int delayTime = 0;
int count = 0;
int res;
res = pthread_mutex_lock(&mutex);
if (res)
{
printf("thread %d lock failed\\n",threadNum);
exit(1);
}
printf("thread %d is starting\\n",threadNum);
for (count = 0; count < 3; count++)
{
delayTime = (int)(rand() * 10.0/(32767)) + 1;
sleep(delayTime);
printf("\\tthread %d:job %d delay = %d\\n",threadNum,count,delayTime);
}
printf("thread %d finished \\n",threadNum);
pthread_exit(0);
}
int main()
{
pthread_t thread[3];
int no = 0;
int res;
void *threadRes;
srand(time(0));
pthread_mutex_init(&mutex,0);
for (no = 0; no < 3; no++)
{
res = pthread_create(&thread[no], 0, threadFunc, (void *)no);
if (res != 0)
{
printf("create thread %d failed\\n",no);
exit(1);
}
}
printf("create threads success \\n waiting for threads to finish.....\\n");
for (no = 0; no < 3; no++)
{
res = pthread_join(thread[no], &threadRes);
if (!res)
{
printf("thread %d joined\\n", no);
}
else
{
printf("thread %d join failed\\n", no);
}
pthread_mutex_unlock(&mutex);
}
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
int RingBuf[32]={0};
int step=0;
sem_t semblank;
sem_t semdata;
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
void *product2()
{
int i=0;
while(1){
pthread_mutex_lock(&lock1);
sem_wait(&semblank);
RingBuf[step++]=i;
sem_post(&semdata);
pthread_mutex_unlock(&lock1);
printf("product2 done! %d\\n", i++);
step%=32;
}
}
void *product1()
{
int i=0;
while(1){
pthread_mutex_lock(&lock1);
sem_wait(&semblank);
RingBuf[step++]=i;
sem_post(&semdata);
pthread_mutex_unlock(&lock1);
printf("product1 done! %d\\n", i++);
step%=32;
}
}
void *consume1()
{
int i=0;
while(1){
pthread_mutex_lock(&lock2);
sem_wait(&semdata);
printf("consume1 done !%d\\n", RingBuf[step]);
sem_post(&semblank);
pthread_mutex_unlock(&lock2);
}
}
void *consume2()
{
while(1){
pthread_mutex_lock(&lock2);
sem_wait(&semdata);
printf("consume2 done !%d\\n", RingBuf[step]);
sem_post(&semblank);
pthread_mutex_unlock(&lock2);
sleep(1);
}
}
void Destory()
{
sem_destroy(&semdata);
sem_destroy(&semblank);
printf("destory sem success!\\n");
}
int main()
{
pthread_t c1, c2, p1, p2;
sem_init(&semblank, 0, 32);
sem_init(&semdata, 0, 0);
pthread_create(&c1, 0, consume1, 0);
pthread_create(&c2, 0, consume2, 0);
pthread_create(&p1, 0, product1, 0);
pthread_create(&p2, 0, product2, 0);
pthread_join(c1, 0);
pthread_join(c2, 0);
pthread_join(p1, 0);
pthread_join(p2, 0);
Destory();
return 0;
}
| 0
|
#include <pthread.h>
int queue[20];
int front , rear;
pthread_cond_t produce_cond, consume_cond;
pthread_mutex_t queue_mutex, produce_mutex, left_mutex;
int left_cnt, product_cnt;
void* producer(void* arg);
void* consumer(void* arg);
int main()
{
front = -1;
rear = 0;
srand(getpid());
left_cnt = 20;
product_cnt = 0;
pthread_mutex_init(&queue_mutex, 0);
pthread_mutex_init(&produce_mutex, 0);
pthread_mutex_init(&left_mutex, 0);
pthread_cond_init(&produce_cond, 0);
pthread_cond_init(&consume_cond, 0);
pthread_t tid1, tid2, tid3;
pthread_create(&tid1, 0, producer, 0);
pthread_create(&tid2, 0, consumer, 0);
pthread_create(&tid3, 0, consumer, 0);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
pthread_join(tid3, 0);
pthread_mutex_destroy(&queue_mutex);
pthread_mutex_destroy(&left_mutex);
pthread_mutex_destroy(&produce_mutex);
pthread_cond_destroy(&produce_cond);
pthread_cond_destroy(&consume_cond);
}
void* producer(void* arg)
{
while(1)
{
pthread_mutex_lock(&left_mutex);
if(left_cnt == 0)
{
pthread_cond_wait(&produce_cond, &left_mutex);
}
pthread_mutex_unlock(&left_mutex);
pthread_mutex_lock(&queue_mutex);
pthread_mutex_lock(&produce_mutex);
product_cnt++;
printf("produce in:%d\\n", product_cnt);
if(product_cnt == 1)
{
pthread_cond_signal(&consume_cond);
}
pthread_mutex_unlock(&produce_mutex);
pthread_mutex_lock(&left_mutex);
left_cnt--;
pthread_mutex_unlock(&left_mutex);
pthread_mutex_unlock(&queue_mutex);
sleep(rand()%4+1);
}
}
void* consumer(void* arg)
{
while(1)
{
pthread_mutex_lock(&produce_mutex);
if(product_cnt == 0)
{
pthread_cond_wait(&consume_cond, &produce_mutex);
}
pthread_mutex_unlock(&produce_mutex);
pthread_mutex_lock(&queue_mutex);
pthread_mutex_lock(&left_mutex);
left_cnt++;
if(left_cnt >= 1)
{
pthread_cond_signal(&produce_cond);
}
pthread_mutex_unlock(&left_mutex);
pthread_mutex_lock(&produce_mutex);
product_cnt--;
printf("product out:%d\\n", product_cnt);
pthread_mutex_unlock(&produce_mutex);
pthread_mutex_unlock(&queue_mutex);
sleep(rand()%4+1);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t dataMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t dataPresentCondition = PTHREAD_COND_INITIALIZER;
pthread_cond_t dataVacancyCondition = PTHREAD_COND_INITIALIZER;
pthread_barrier_t hold;
int buffer[10];
int items=0;
void random_delay()
{
int r = rand() % 3;
sleep(r);
}
void *consumerThread(void *threadid)
{
int rc;
int dataItem;
printf("Consumer Thread %.8x: Entered\\n",(int)threadid);
pthread_barrier_wait(&hold);
while (TRUE) {
random_delay();
rc = pthread_mutex_lock(&dataMutex);
{ if (rc) { printf("Failed with %d at %s", rc, "pthread_mutex_lock()\\n"); exit(1); } };
while (!items) {
printf("Consumer Thread %.8x: Wait for data to be produced\\n",(int)threadid);
rc = pthread_cond_wait(&dataPresentCondition, &dataMutex);
if (rc) {
printf("Consumer Thread %.8x: condwait failed, rc=%d\\n",(int)threadid,rc);
pthread_mutex_unlock(&dataMutex);
exit(1);
}
}
dataItem = buffer[items-1];
--items;
printf("consumer %d: consumed data item %d\\n", (int)threadid, dataItem);
rc = pthread_cond_signal(&dataVacancyCondition);
rc = pthread_mutex_unlock(&dataMutex);
}
printf("Consumer Thread %.8x: All done\\n",(int)threadid);
rc = pthread_mutex_unlock(&dataMutex);
{ if (rc) { printf("Failed with %d at %s", rc, "pthread_mutex_unlock()\\n"); exit(1); } };
return 0;
}
void *producerThread(void *threadid)
{
int rc;
int amountOfData = 50;
while(amountOfData--)
{
rc = pthread_mutex_lock(&dataMutex);
{ if (rc) { printf("Failed with %d at %s", rc, "pthread_mutex_lock()\\n"); exit(1); } };
while (items>=10) {
printf("NOTICE: BUFFER FULL\\n");
printf("Producer thread Thread %d: Wait for data to be consumed\\n",(int)threadid);
rc = pthread_cond_wait(&dataVacancyCondition, &dataMutex);
if (rc) {
printf("Producer Thread %d: condwait failed, rc=%d\\n",(int)threadid,rc);
pthread_mutex_unlock(&dataMutex);
exit(1);
}
}
printf("producing data...\\n");
++items;
buffer[items-1] = amountOfData;
rc = pthread_cond_signal(&dataPresentCondition);
if (rc) {
pthread_mutex_unlock(&dataMutex);
printf("Producer: Failed to wake up consumer, rc=%d\\n", rc);
exit(1);
}
rc = pthread_mutex_unlock(&dataMutex);
{ if (rc) { printf("Failed with %d at %s", rc, "pthread_mutex_lock()\\n"); exit(1); } };
}
printf("producer done...\\n");
return 0;
}
int main(int argc, char **argv)
{
pthread_t thread[5];
int rc=0;
int i;
pthread_barrier_init(&hold, 0, 5);
printf("Enter Testcase - %s\\n", argv[0]);
printf("Create/start threads\\n");
for (i=0; i <5; ++i) {
rc = pthread_create(&thread[i], 0, consumerThread, (void *)i);
{ if (rc) { printf("Failed with %d at %s", rc, "pthread_create()\\n"); exit(1); } };
}
rc = pthread_create(&thread[i], 0, producerThread, (void *)i);
printf("Wait for the threads to complete, and release their resources\\n");
for (i=0; i <5; ++i) {
rc = pthread_join(thread[i], 0);
{ if (rc) { printf("Failed with %d at %s", rc, "pthread_join()\\n"); exit(1); } };
}
rc = pthread_join(thread[i], 0);
printf("Clean up\\n");
rc = pthread_mutex_destroy(&dataMutex);
rc = pthread_cond_destroy(&dataPresentCondition);
rc = pthread_barrier_destroy(&hold);
printf("Main completed\\n");
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t lock;
static sem_t semcount, semspace;
static float * buffer;
static int in, out;
static int bufferSize;
int init_ringbuffer(int n) {
in = 0;
out = 0;
bufferSize = n;
if (pthread_mutex_init(&lock, 0)) {
printf("pthread_mutex_init failed, terminating.\\n");
return -1;
}
buffer = (float *) malloc(sizeof(float) * n);
if (buffer == 0) {
return -1;
}
if (sem_init(&semcount, 0, 0)) {
printf("sem_init(&semcount, 0, 0) failed, terminating.\\n");
return -1;
}
if (sem_init(&semspace, 0, n)) {
printf("sem_init(&semspace, 0, 0) failed, terminating.\\n");
return -1;
}
return 0;
}
void enqueue(float value) {
sem_wait(&semspace);
pthread_mutex_lock(&lock);
buffer[in++] = value;
if (in == bufferSize) {
in = 0;
}
pthread_mutex_unlock(&lock);
sem_post(&semcount);
}
float dequeue() {
float value;
sem_wait(&semcount);
pthread_mutex_lock(&lock);
value = buffer[out++];
if (out == bufferSize) {
out = 0;
}
pthread_mutex_unlock(&lock);
sem_post(&semspace);
return value;
}
void deinit_ringbuffer() {
sem_destroy(&semcount);
sem_destroy(&semspace);
pthread_mutex_destroy(&lock);
}
| 1
|
#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(&hashlock);
fp->f_count++;
pthread_mutex_unlock(&hashlock);
}
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) {
fp->f_count++;
break;
}
}
pthread_mutex_unlock(&hashlock);
return fp;
}
void foo_rele(struct foo *fp) {
struct foo *tfp;
int idx;
pthread_mutex_lock(&hashlock);
if (--fp->f_count == 0) {
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_destroy(&fp->f_lock);
free(fp);
} else
pthread_mutex_unlock(&hashlock);
}
| 0
|
#include <pthread.h>
int x = 0;
int y = 0;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mut2 = PTHREAD_MUTEX_INITIALIZER;
void *thread_func (void * arg)
{
while(1)
{
pthread_mutex_lock(&mut);
x=5;
x+=10;
pthread_mutex_lock(&mut2);
y=10;y+=1;
printf("x is %d in thread %lu\\n",x,pthread_self());
printf("y is %d in thread %lu\\n",y,pthread_self());
pthread_mutex_unlock(&mut2);
pthread_mutex_unlock(&mut);
}
}
int main()
{
pthread_t tid1;
pthread_t tid2;
pthread_create(&tid1, 0, &thread_func, 0);
pthread_create(&tid2, 0, &thread_func, 0);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
int buffer;
int estado = 0;
void produtor(int id)
{
int i=0;
int item;
int aguardar;
printf("Inicio produtor %d \\n",id);
while (i < 10)
{
item = i + (id*1000);
do
{
pthread_mutex_lock(&mutex);
aguardar = 0;
if (estado == 1)
{
aguardar = 1;
pthread_mutex_unlock(&mutex);
}
} while (aguardar == 1);
printf("Produtor %d inserindo item %d\\n", id, item);
buffer = item;
estado = 1;
pthread_mutex_unlock(&mutex);
i++;
sleep(2);
}
printf("Produtor %d terminado \\n", id);
}
void consumidor(int id)
{
int item;
int aguardar;
printf("Inicio consumidor %d \\n",id);
while (1)
{
do
{
pthread_mutex_lock(&mutex);
aguardar = 0;
if (estado == 0)
{
aguardar = 1;
pthread_mutex_unlock(&mutex);
}
} while (aguardar == 1);
item = buffer;
estado = 0;
pthread_mutex_unlock(&mutex);
printf("Consumidor %d consumiu item %d\\n", id, item);
sleep(2);
}
printf("Consumidor %d terminado \\n", id);
}
int main()
{
pthread_t prod1;
pthread_t prod2;
pthread_t prod3;
pthread_t cons1;
pthread_t cons2;
printf("Programa Produtor-Consumidor\\n");
printf("Iniciando variaveis de sincronizacao.\\n");
pthread_mutex_init(&mutex,0);
printf("Disparando threads produtores\\n");
pthread_create(&prod1, 0, (void*) produtor,1);
pthread_create(&prod2, 0, (void*) produtor,2);
pthread_create(&prod3, 0, (void*) produtor,3);
printf("Disparando threads consumidores\\n");
pthread_create(&cons1, 0, (void*) consumidor,1);
pthread_create(&cons2, 0, (void*) consumidor,2);
pthread_join(prod1,0);
pthread_join(prod2,0);
pthread_join(prod3,0);
pthread_join(cons1,0);
pthread_join(cons2,0);
printf("Terminado processo Produtor-Consumidor.\\n\\n");
}
| 0
|
#include <pthread.h>
int count = 0;
int thread_ids[3] = {0,1,2};
pthread_mutex_t count_lock=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t count_hit_threshold=PTHREAD_COND_INITIALIZER;
void *inc_count(void *idp)
{
int i=0, save_state, save_type;
int *my_id = idp;
for (i=0; i<10; i++) {
pthread_mutex_lock(&count_lock);
count++;
printf("inc_counter(): thread %d, count = %d, unlocking mutex\\n",
*my_id, count);
if (count == 12) {
printf("inc_count(): Thread %d, count %d\\n", *my_id, count);
pthread_cond_signal(&count_hit_threshold);
}
pthread_mutex_unlock(&count_lock);
}
return(0);
}
void *watch_count(void *idp)
{
int i=0, save_state, save_type;
int *my_id = idp;
printf("watch_count(): thread %d\\n", *my_id);
pthread_mutex_lock(&count_lock);
while (count < 12) {
pthread_cond_wait(&count_hit_threshold, &count_lock);
printf("watch_count(): thread %d, count %d\\n", *my_id, count);
}
pthread_mutex_unlock(&count_lock);
return(0);
}
extern int
main(void)
{
int i;
pthread_t threads[3];
pthread_create(&threads[0], 0, inc_count, (void *)&thread_ids[0]);
pthread_create(&threads[1], 0, inc_count, (void *)&thread_ids[1]);
pthread_create(&threads[2], 0, watch_count, (void *)&thread_ids[2]);
for (i = 0; i < 3; i++) {
pthread_join(threads[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
enum threadstatus {
thread_initialized = 0,
thread_ready = 1,
thread_exit = 2
};
struct threadctrl {
unsigned *free_threads;
unsigned num_free_threads;
pthread_mutex_t mtx;
pthread_cond_t cnd;
};
struct threaddata {
unsigned index;
enum threadstatus status;
int work_time;
pthread_mutex_t mtx;
pthread_cond_t cnd;
struct threadctrl *ctrl;
};
void threadctrl_put(struct threadctrl* ctrl, unsigned index) {
ctrl->free_threads[ctrl->num_free_threads] = index;
++(ctrl->num_free_threads);
}
unsigned threadctrl_get(struct threadctrl* ctrl) {
--(ctrl->num_free_threads);
return ctrl->free_threads[ctrl->num_free_threads];
}
void* threadfunc(void *arg) {
struct threaddata *data;
struct threadctrl *ctrl;
data = arg;
ctrl = data->ctrl;
while (1) {
pthread_mutex_lock(&data->mtx);
data->status = thread_ready;
pthread_cond_wait(&data->cnd, &data->mtx);
if (data->status == thread_exit) break;
fprintf(stderr, "thread %u working for %u microseconds\\n",
data->index, data->work_time);
usleep(data->work_time);
pthread_mutex_lock(&ctrl->mtx);
threadctrl_put(ctrl, data->index);
pthread_cond_signal(&ctrl->cnd);
pthread_mutex_unlock(&ctrl->mtx);
pthread_mutex_unlock(&data->mtx);
}
pthread_exit(0);
}
int main(int argc, char* argv[]) {
const unsigned num_threads = 4;
pthread_t threads[num_threads];
struct threaddata data[num_threads];
unsigned i;
struct threadctrl ctrl = {
.free_threads = malloc(num_threads * sizeof(unsigned)),
.num_free_threads = 0,
.mtx = PTHREAD_MUTEX_INITIALIZER,
.cnd = PTHREAD_COND_INITIALIZER
};
srand(time(0));
for (i = 0; i < num_threads; ++i) {
data[i].index = i;
data[i].status = thread_initialized;
pthread_mutex_init(&data[i].mtx, 0);
pthread_cond_init(&data[i].cnd, 0);
threadctrl_put(&ctrl, i);
data[i].ctrl = &ctrl;
pthread_create(&threads[i], 0, threadfunc, &data[i]);
while (data[i].status != thread_ready)
usleep(500);
}
for (i = 0; i < num_threads * 16; ++i) {
unsigned k;
pthread_mutex_lock(&ctrl.mtx);
if (ctrl.num_free_threads == 0)
pthread_cond_wait(&ctrl.cnd, &ctrl.mtx);
k = threadctrl_get(&ctrl);
pthread_mutex_unlock(&ctrl.mtx);
pthread_mutex_lock(&data[k].mtx);
data[k].work_time = rand() % 100000;
pthread_cond_signal(&data[k].cnd);
pthread_mutex_unlock(&data[k].mtx);
}
for (i = 0; i < num_threads; ++i) {
pthread_mutex_lock(&data[i].mtx);
data[i].status = thread_exit;
pthread_cond_signal(&data[i].cnd);
pthread_mutex_unlock(&data[i].mtx);
}
for (i = 0; i < num_threads; ++i) {
pthread_join(threads[i], 0);
}
free(ctrl.free_threads);
}
| 0
|
#include <pthread.h>
struct list_head {
struct list_head *next ;
struct list_head *prev ;
};
struct s {
int datum ;
struct list_head list ;
};
struct cache {
struct list_head slot[10] ;
pthread_mutex_t slots_mutex[10] ;
};
struct cache c ;
static inline void INIT_LIST_HEAD(struct list_head *list) {
list->next = list;
list->prev = list;
}
struct s *new(int x) {
struct s *p = malloc(sizeof(struct s));
p->datum = x;
INIT_LIST_HEAD(&p->list);
return p;
}
static inline void list_add(struct list_head *new, struct list_head *head) {
struct list_head *next = head->next;
next->prev = new;
new->next = next;
new->prev = head;
head->next = new;
}
inline static struct list_head *lookup (int d) {
int hvalue;
struct list_head *p;
p = c.slot[hvalue].next;
return p;
}
void *f(void *arg) {
struct s *pos ;
int j;
struct list_head const *p ;
struct list_head const *q ;
while (j < 10) {
pthread_mutex_lock(&c.slots_mutex[j]);
p = c.slot[j].next;
pos = (struct s *)((char *)p - (size_t)(& ((struct s *)0)->list));
while (& pos->list != & c.slot[j]) {
pos->datum++;
q = pos->list.next;
pos = (struct s *)((char *)q - (size_t)(& ((struct s *)0)->list));
}
pthread_mutex_unlock(&c.slots_mutex[j]);
j ++;
}
return 0;
}
int main() {
struct list_head *p;
int x;
pthread_t t1, t2;
for (int i = 0; i < 10; i++) {
INIT_LIST_HEAD(&c.slot[i]);
pthread_mutex_init(&c.slots_mutex[i], 0);
for (int j = 0; j < 30; j++) list_add(&new(j*i)->list, &c.slot[i]);
}
p = &c.slot[x];
x = 99;
pthread_create(&t1, 0, f, 0);
pthread_create(&t2, 0, f, 0);
return (long) p;
}
| 1
|
#include <pthread.h>
static sem_t thread_count;
static pthread_mutex_t rand_mutex;
struct quicksort_arg
{
int * left;
int * right;
};
static
void print_array(int array[], size_t size)
{
for ( size_t i = 0u; i < size; ++i )
{
printf("%i\\t", array[i]);
}
putchar('\\n');
}
static
void quicksort(int * left, int * right);
static
void * worker(void * arg)
{
struct quicksort_arg * quicksort_arg = (struct quicksort_arg *)arg;
quicksort(quicksort_arg->left, quicksort_arg->right);
return 0;
}
static
void quicksort(int * left, int * right)
{
if ( right - left < 1 )
{
return;
}
pthread_mutex_lock(&rand_mutex);
int * m = left + rand() % (right - left + 1),
* l = left,
* r = right;
pthread_mutex_unlock(&rand_mutex);
while ( 1 )
{
while ( *l <= *m && l != m )
{
++l;
}
while ( *r >= *m && r != m )
{
--r;
}
if ( l == r )
{
break;
}
*l = *l + *r;
*r = *l - *r;
*l = *l - *r;
if ( l == m )
{
m = r;
++l;
}
else if ( r == m )
{
m = l;
--r;
}
else
{
++l;
--r;
}
}
if ( sem_trywait(&thread_count) != 0 )
{
quicksort(left, m - 1);
quicksort(m + 1, right);
}
else
{
pthread_t left_worker,
right_worker;
struct quicksort_arg left_arg = { .left = left, .right = m - 1 },
right_arg = { .left = m + 1, .right = right };
pthread_create(&left_worker, 0, worker, &left_arg);
pthread_create(&right_worker, 0, worker, &right_arg);
pthread_join(left_worker, 0);
pthread_join(right_worker, 0);
sem_post(&thread_count);
}
}
extern
int main(int argc, char * argv[])
{
if ( argc != 3 )
{
printf("usage: quick_seq size\\n");
return 1;
}
size_t size;
unsigned tc;
if ( sscanf(argv[1], "%u", &tc) != 1 )
{
printf("bad thread number\\n");
return 1;
}
if ( sscanf(argv[2], "%zu", &size) != 1 )
{
printf("bad size\\n");
return 1;
}
unsigned * array = calloc(size, sizeof(unsigned));
if ( array == 0 )
{
printf("no memory\\n");
return 1;
}
for ( size_t i = 0u; i < size ; ++i )
{
*(array + i) = rand() % size;
}
if ( size <= 30 )
{
print_array(array, size);
}
pthread_mutex_init(&rand_mutex, 0);
sem_init(&thread_count, 0, tc);
quicksort(array, array + size - 1);
if ( size <= 30 )
{
print_array(array, size);
}
free(array);
return 0;
}
| 0
|
#include <pthread.h>
int buffer[10];
int counter=0;
int in=0;
int out=0;
int total=0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t semfull;
sem_t semempty;
void *producer(void *junk) {
while(1) {
sem_wait(&semempty);
pthread_mutex_lock(&mutex);
buffer[in] = total++;
printf("Produced %d\\n", buffer[in]);
in = (in + 1) % 10;
counter++;
pthread_mutex_lock(&mutex);
sem_post(&semfull);
}
}
void *consumer(void *junk) {
while(1) {
sem_wait(&semfull);
pthread_mutex_lock(&mutex);
printf("Consumed %d\\n", buffer[out]);
out = (out + 1) % 10;
counter--;
pthread_mutex_unlock(&mutex);
sem_post(&semempty);
}
}
int main() {
pthread_t thread;
sem_init(&semfull, 0, 0);
sem_init(&semempty, 0, 10);
pthread_create(&thread, 0, producer, 0);
consumer(0);
}
| 1
|
#include <pthread.h>
void *find_gif(void *path){
char *file, *file_ext, file_path[1000];
DIR *inDir;
struct dirent *inDirent;
inDir = opendir(path);
if (!inDir) {
fprintf(stderr, "Error while searching for gif files: invalid file path.\\n");
fprintf(stderr, " Unable to open directory at %s\\n", (char *) path);
pthread_exit(0);
}
while ( (inDirent = readdir(inDir)) ) {
file = inDirent->d_name;
file_ext = strrchr(file, '.');
if (!strcmp(file, ".") || !strcmp(file, "..") || !strcmp(file, ".DS_Store") ||
!file_ext) {
continue;
}
if (!strcmp(file_ext, ".gif")) {
strcpy(file_path, path);
strcat(file_path, "/");
strcat(file_path, file);
pthread_mutex_lock(&html_mutex);
generate_html(file_path);
pthread_mutex_unlock(&html_mutex);
}
}
closedir(inDir);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
void *functionCount1();
void *functionCount2();
int count = 0;
main() {
pthread_t thread1, thread2;
pthread_create(&thread1, 0, &functionCount1, 0);
pthread_create(&thread2, 0, &functionCount2, 0);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
printf("Final count: %d\\n", count);
exit(0);
}
void *functionCount1() {
printf("Counter1\\n");
for (;;) {
pthread_mutex_lock(&count_mutex);
pthread_cond_wait(&condition_var, &count_mutex);
count++;
printf("Counter value functionCount1: %d\\n", count);
pthread_mutex_unlock(&count_mutex);
if (count >= 10) return (0);
}
}
void *functionCount2() {
printf("Counter2\\n");
for (;;) {
pthread_mutex_lock(&count_mutex);
if (count < 3 || count > 6) {
pthread_cond_signal(&condition_var);
} else {
count++;
printf("Counter value functionCount2: %d\\n", count);
}
pthread_mutex_unlock(&count_mutex);
if (count >= 10) return (0);
}
}
| 1
|
#include <pthread.h>
struct hadoop_group_info *hadoop_group_info_alloc(int use_reentrant)
{
struct hadoop_group_info *ginfo;
size_t buf_sz;
char *buf;
ginfo = calloc(1, sizeof(struct hadoop_group_info));
if (!use_reentrant) {
ginfo->buf_sz = 0;
ginfo->buf = 0;
} else {
buf_sz = sysconf(_SC_GETGR_R_SIZE_MAX);
if (buf_sz < 1024) {
buf_sz = 1024;
}
buf = malloc(buf_sz);
if (!buf) {
free(ginfo);
return 0;
}
ginfo->buf_sz = buf_sz;
ginfo->buf = buf;
}
return ginfo;
}
void hadoop_group_info_clear(struct hadoop_group_info *ginfo)
{
struct group *group = &ginfo->group;
char **g;
if (!ginfo->buf_sz) {
free(group->gr_name);
free(group->gr_passwd);
if (group->gr_mem) {
for (g = group->gr_mem; *g; g++) {
free(*g);
}
free(group->gr_mem);
}
}
group->gr_name = 0;
group->gr_passwd = 0;
group->gr_gid = 0;
group->gr_mem = 0;
}
void hadoop_group_info_free(struct hadoop_group_info *ginfo)
{
if (!ginfo->buf_sz) {
hadoop_group_info_clear(ginfo);
} else {
free(ginfo->buf);
}
free(ginfo);
}
static int getgrgid_error_translate(int err)
{
if ((err == EIO) || (err == EMFILE) || (err == ENFILE) ||
(err == ENOMEM) || (err == ERANGE)) {
return err;
}
return ENOENT;
}
static int hadoop_group_info_fetch_nonreentrant(
struct hadoop_group_info *ginfo, gid_t gid)
{
struct group *group;
int i, num_users = 0;
char **g;
do {
errno = 0;
group = getgrgid(gid);
} while ((!group) && (errno == EINTR));
if (!group) {
return getgrgid_error_translate(errno);
}
ginfo->group.gr_name = strdup(group->gr_name);
if (!ginfo->group.gr_name) {
hadoop_group_info_clear(ginfo);
return ENOMEM;
}
ginfo->group.gr_passwd = strdup(group->gr_passwd);
if (!ginfo->group.gr_passwd) {
hadoop_group_info_clear(ginfo);
return ENOMEM;
}
ginfo->group.gr_gid = group->gr_gid;
if (group->gr_mem) {
for (g = group->gr_mem, num_users = 0;
*g; g++) {
num_users++;
}
}
ginfo->group.gr_mem = calloc(num_users + 1, sizeof(char *));
if (!ginfo->group.gr_mem) {
hadoop_group_info_clear(ginfo);
return ENOMEM;
}
for (i = 0; i < num_users; i++) {
ginfo->group.gr_mem[i] = strdup(group->gr_mem[i]);
if (!ginfo->group.gr_mem[i]) {
hadoop_group_info_clear(ginfo);
return ENOMEM;
}
}
return 0;
}
static int hadoop_group_info_fetch_reentrant(struct hadoop_group_info *ginfo,
gid_t gid)
{
struct group *group;
int err;
size_t buf_sz;
char *nbuf;
for (;;) {
do {
group = 0;
err = getgrgid_r(gid, &ginfo->group, ginfo->buf,
ginfo->buf_sz, &group);
} while ((!group) && (err == EINTR));
if (group) {
return 0;
}
if (err != ERANGE) {
return getgrgid_error_translate(errno);
}
buf_sz = ginfo->buf_sz * 2;
nbuf = realloc(ginfo->buf, buf_sz);
if (!nbuf) {
return ENOMEM;
}
ginfo->buf = nbuf;
ginfo->buf_sz = buf_sz;
}
}
int hadoop_group_info_fetch(struct hadoop_group_info *ginfo, gid_t gid)
{
int ret;
hadoop_group_info_clear(ginfo);
if (!ginfo->buf_sz) {
static pthread_mutex_t g_getgrnam_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&g_getgrnam_lock);
ret = hadoop_group_info_fetch_nonreentrant(ginfo, gid);
pthread_mutex_unlock(&g_getgrnam_lock);
return ret;
} else {
return hadoop_group_info_fetch_reentrant(ginfo, gid);
}
}
| 0
|
#include <pthread.h>
extern int makepthread(void *(*)(void*), void *);
struct to_info{
void (*to_fn)(void *);
void *to_arg;
struct timespec to_wait;
};
void *timeout_helper(void*arg)
{
struct to_info *tip;
tip = (struct to_info*)arg;
nanosleep(&tip->to_wait, 0);
(*tip->to_fn)(tip->to_arg);
return (0);
}
void timeout(const struct timespec *when, void (*func)(void *), void *arg)
{
struct timespec now;
struct timeval tv;
struct to_info *tip;
int err;
gettimeofday(&tv, 0);
now.tv_sec = tv.tv_sec;
now.tv_nsec = tv.tv_usec * 1000;
if((when->tv_sec > now.tv_sec) ||
(when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)){
tip = malloc(sizeof(struct to_info));
if(tip != 0){
tip->to_fn = func;
tip->to_arg = arg;
tip->to_wait.tv_sec = when->tv_sec - now.tv_sec;
if(when->tv_nsec >= now.tv_nsec){
tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec;
}else{
tip->to_wait.tv_sec --;
tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec;
}
err = makepthread(timeout_helper, (void*)tip);
if(err != 0){
return ;
}
}
}
(*func)(arg);
}
pthread_mutexattr_t attr;
pthread_mutex_t mutex;
void retry(void *arg)
{
pthread_mutex_lock(&mutex);
printf("pthread function retry() get the lock and go to sleep ...\\n");
sleep(4);
pthread_mutex_unlock(&mutex);
printf("pthread function unlock the lock\\n");
}
int main(void)
{
int err, condition = 1, arg = 1;
struct timespec when;
if((err = pthread_mutexattr_init(&attr)) != 0){
perror("pthread_mutexattr_init");
exit(1);
}
if((err = pthread_mutexattr_settype(&attr,
PTHREAD_MUTEX_RECURSIVE)) != 0){
perror("Pthread_mutexattr_settype");
exit(1);
}
if((err = pthread_mutex_init(&mutex,&attr)) != 0){
perror("pthread_mutex_init");
exit(1);
}
pthread_mutex_lock(&mutex);
printf("main get the lock already\\n");
if(condition){
timeout(&when, retry, (void*)arg);
}
printf("timeout returned \\n");
pthread_mutex_unlock(&mutex);
printf("main unlock the mutex\\n");
exit(0);
}
| 1
|
#include <pthread.h>
long ninc_per_thread;
long a;
long b;
long r;
long * p;
pthread_mutex_t * m;
} arg_t;
void * f(void * arg_) {
arg_t * arg = (arg_t *)arg_;
long a = arg->a, b = arg->b;
long ninc_per_thread = arg->ninc_per_thread;
if (b - a == 1) {
int i;
for (i = 0; i < ninc_per_thread; ) {
if (i % 2 == 0) {
pthread_mutex_lock(arg->m);
arg->p[0]++;
pthread_mutex_unlock(arg->m);
i++;
} else {
if (pthread_mutex_trylock(arg->m) == 0) {
arg->p[0]++;
pthread_mutex_unlock(arg->m);
i++;
}
}
}
arg->r = a;
} else {
long c = (a + b) / 2;
arg_t cargs[2] = { { ninc_per_thread, a, c, 0, arg->p, arg->m },
{ ninc_per_thread, c, b, 0, arg->p, arg->m } };
pthread_t tid;
pthread_create(&tid, 0, f, cargs);
f(cargs + 1);
pthread_join(tid, 0);
arg->r = cargs[0].r + cargs[1].r;
}
return 0;
}
int main(int argc, char ** argv) {
int nthreads = (argc > 1 ? atoi(argv[1]) : 100);
long ninc_per_thread = (argc > 2 ? atol(argv[2]) : 10000);
pthread_mutex_t m[1];
pthread_mutex_init(m, 0);
long p[1] = { 0 };
arg_t arg[1] = { { ninc_per_thread, 0, nthreads, 0, p, m } };
pthread_t tid;
pthread_create(&tid, 0, f, arg);
pthread_join(tid, 0);
if (arg->r == (nthreads - 1) * nthreads / 2
&& arg->p[0] == nthreads * ninc_per_thread) {
printf("OK\\n");
return 0;
} else {
printf("NG\\n");
return 1;
}
}
| 0
|
#include <pthread.h>
int tid=0;
int size=20/10;
long media=0;
pthread_mutex_t mutex;
void *calcMedia(void *threadid){
int parcial=0;
int i;
long id = *((long *)threadid);
for(i=(id)*size; i<(id+1)*size;i++)
parcial+=i;
printf("THREAD[%ld] calculated %d\\n", id, parcial);
pthread_mutex_lock(&mutex);
media+=parcial;
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main(int argc, char **argv) {
int i;
long *id = (long *) malloc ( 10 * sizeof (long));
pthread_t threads[10];
pthread_mutex_init(&mutex, 0);
for(i=0;i<20;i++){
id[i]=i;
printf("[%d]= %ld \\n", i, id[i]);
}
for(i=0;i<10;i++){
pthread_create(&threads[i], 0, calcMedia, (void *)(id+i));
}
for(i=0;i<10;i++){
pthread_join(threads[i], 0);
}
media=media/20;
printf ("Mean = %ld \\n", media);
}
| 1
|
#include <pthread.h>
static int work = 0;
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t con = PTHREAD_COND_INITIALIZER;
static void *thread_func(void *arg)
{
int * sec = (int *)arg;
int i;
for(i = 0; i < 1000; i++) {
sleep(*sec);
pthread_mutex_lock(&mtx);
work++;
printf("thread(tid: %x) make a work = %d\\n", (unsigned int)pthread_self(), work);
pthread_mutex_unlock(&mtx);
pthread_cond_signal(&con);
}
pthread_detach(pthread_self());
return 0;
}
void pthread_cond_var()
{
pthread_t t1, t2;
int s;
int sec1, sec2;
sec1 = 1;
s = pthread_create(&t1, 0, thread_func, &sec1);
if(s != 0)
errExitEN(s, "pthread_create");
sec2 = 2;
s = pthread_create(&t2, 0, thread_func, &sec2);
if(s != 0)
errExitEN(s, "pthread_create");
pthread_mutex_lock(&mtx);
while(1) {
while(work == 0)
pthread_cond_wait(&con, &mtx);
while(work > 0) {
work--;
printf("main thread consumed a work = %d\\n", work);
}
}
}
| 0
|
#include <pthread.h>
static char *VersionStr="1.0";
static int test_duration_timer_expired = 0;
static int wakeup_fd[2];
static pid_t *child_pids = 0;
static pthread_mutex_t sync_mutex = PTHREAD_MUTEX_INITIALIZER;
static int set_timer_ms(struct itimerval *val, int ms)
{
val->it_value.tv_sec = ms/1000;
val->it_value.tv_usec = (ms * 1000) % 1000000;
val->it_interval.tv_sec = 0;
val->it_interval.tv_usec = 0;
return setitimer(ITIMER_REAL, val, 0);
}
void handler_fn(int a)
{
printf("Process %x: Received Signal\\n", (unsigned int)getpid());
pthread_mutex_unlock(&sync_mutex);
}
void timer_handler(int a)
{
test_duration_timer_expired = 1;
}
int ping_test(int data_size_words, int test_duration_ms, int num_threads, int num_iterations)
{
struct itimerval test_duration_timer;
int i = 0;
int *status;
int rc = 0;
char data = 0;
pthread_mutex_lock(&sync_mutex);
if(!child_pids)
{
signal(SIGCONT, handler_fn);
write(wakeup_fd[1], &data, 1);
pthread_mutex_lock(&sync_mutex);
printf("Child Process: %x Resumed\\n", (unsigned int)getpid());
}
else
{
while(i < (num_threads - 1))
{
read(wakeup_fd[0], &data, 1);
i++;
}
kill(-1, SIGCONT);
printf("Parent Process Resumed All child Processes\\n");
}
pthread_mutex_unlock(&sync_mutex);
signal(SIGALRM, timer_handler);
rc = set_timer_ms(&test_duration_timer, test_duration_ms);
if(rc)
{
perror("settimer");
close(wakeup_fd[0]);
close(wakeup_fd[1]);
return -1;
}
if(test_duration_ms)
{
while(!test_duration_timer_expired)
{
rc |= ping_data_common(data_size_words);
}
}
else
{
for(i=0;i<num_iterations;i++)
{
rc |= ping_data_common(data_size_words);
}
}
close(wakeup_fd[0]);
close(wakeup_fd[1]);
pthread_mutex_destroy(&sync_mutex);
return rc;
}
int main(int argc, char *argv[])
{
int i;
int numIterations = 0;
int numThreads = NUM_OF_CORES;
int testDurationMs = 2000;
int dataSizeWords = 200;
int rc;
int status = 0;
printf("\\nOncrpc Multi-Core Test 1002, version %s\\n",VersionStr);
printf("Usage: oncrpc_mc_test_1002 <num iterations> [%d] <test duration(ms)> [%d] <num threads> [%d] <data size words> [%d]\\n\\n",
numIterations, testDurationMs, numThreads, dataSizeWords);
switch(argc)
{
case 5:
dataSizeWords = atoi(argv[4]);
case 4:
numThreads = atoi(argv[3]);
case 3:
testDurationMs = atoi(argv[2]);
case 2:
numIterations = atoi(argv[1]);
break;
default:
printf("Using defaults numTestsToRun:%d Test Duration:%d numThreads:%d dataSizeWords:%d\\n",
numIterations, testDurationMs, numThreads, dataSizeWords);
break;
}
if (numIterations > 0)
testDurationMs = 0;
printf("Running for numIterations:%d Test Duration(ms):%d, numThreads:%d dataSizeWords:%d\\n",
numIterations, testDurationMs, numThreads, dataSizeWords);
if(pipe(wakeup_fd) == -1)
return -1;
child_pids = (pid_t *)malloc(numThreads * sizeof(pid_t));
if(!child_pids)
{
close(wakeup_fd[0]);
close(wakeup_fd[1]);
return -1;
}
for(i = 0; i < numThreads - 1; i++)
{
child_pids[i] = fork();
if(!child_pids[i])
{
printf("Child Process %x created\\n", (unsigned int)getpid());
free(child_pids);
child_pids = 0;
break;
}
}
oncrpc_init();
oncrpc_task_start();
if( ping_mdm_rpc_null())
{
printf("Verified ping_mdm_rpc is available \\n");
}
else
{
printf("Error ping_mdm_rpc is not availabe \\n");
close(wakeup_fd[0]);
close(wakeup_fd[1]);
exit(-1);
}
rc = ping_test(dataSizeWords,testDurationMs,numThreads,numIterations);
printf("Process %x: Ping Test Completed\\n", (unsigned int)getpid());
if(rc)
printf("Process %x: Ping Test Failed\\n", (unsigned int)getpid());
oncrpc_task_stop();
oncrpc_deinit();
if(!child_pids)
{
exit(rc);
}
for(i = 0; i < numThreads - 1; i++)
{
waitpid(child_pids[i], &status, 0);
rc |= status;
}
printf("ONCRPC_MC_TEST_1002 COMPLETE...\\n");
if(!rc)
printf("PASS\\n");
else
printf("FAIL\\n");
free(child_pids);
return(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex ;
int var;
void pthread1(void *arg);
void pthread2(void *arg);
int main(int argc,char* argv[]){
pthread_t id1, id2;
int ret;
pthread_mutex_init(&mutex, 0);
ret = pthread_create(&id1, 0, (void*)&pthread1, 0);
if(ret) printf("pthread1 create failed");
ret = pthread_create(&id2, 0, (void*)&pthread2, 0);
if(ret) printf("pthread2 create failed");
pthread_join(id1, 0);
pthread_join(id2, 0);
pthread_mutex_destroy(&mutex);
exit(0);
}
void pthread1(void *arg){
int i=0;
for(i=0;i<2;i++){
pthread_mutex_lock(&mutex);
var ++;
printf("pthread1:第%d次循环,第1次打印var=%d\\n",i,var);
sleep(1);
printf("pthread1:第%d次循环,第2次打印var=%d\\n",i,var);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void pthread2(void *arg){
int i=0;
for(i=0;i<5;i++){
pthread_mutex_lock(&mutex);
sleep(1);
var ++;
printf("pthread2:第%d次循环,第1次打印var=%d\\n",i,var);
sleep(1);
printf("pthread2:第%d次循环,第2次打印var=%d\\n",i,var);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
| 0
|
#include <pthread.h>
char buf[1000];
void PROCESS_PACK(char datagram[],int size)
{
struct iphdr * iph=(struct iphdr *)datagram;
int msg=ntohs(iph->tot_len)-iph->ihl*4,i;
int off=iph->ihl*4;
printf("%d %d\\n",iph->tot_len,ntohs(iph->tot_len));
for(i=0;i<msg;i++)
{
printf("%c",datagram[i+off]);
}
fflush(stdout);
}
pthread_mutex_t mutex;
void advertise(void * arg)
{
char datagram[4096];
int rawfd=*((int *)arg),a;
while(1)
{
a=read(rawfd,datagram,sizeof(datagram));
if(a<0)
{
}
else
{
pthread_mutex_lock(&mutex);
printf("***AD**\\n");
PROCESS_PACK(datagram,a);
pthread_mutex_unlock(&mutex);
}
}
}
void announce_sock(void * arg)
{
char datagram[4096];
int rawfd=*((int *)arg),a;
while(1)
{
a=read(rawfd,datagram,sizeof(datagram));
if(a<0)
{
}
else
{
pthread_mutex_lock(&mutex);
printf("IMPORTANT ANNOUNCMENT TO MAKE\\n");
PROCESS_PACK(datagram,a);
pthread_mutex_unlock(&mutex);
}
}
}
int main(int arg,char * argc[])
{
char buf[1000];
int pid,a,tfd;
pthread_mutex_init(&mutex,0);
scanf("%d",&pid);
pthread_t t1,t2;
int rawfd=socket(AF_INET,SOCK_RAW,196);
int rawfd2=socket(AF_INET,SOCK_RAW,195);
if(rawfd<0)
{
perror("");
return 0;
}
if(rawfd2<0)
{
perror("");
return 0;
}
struct sockaddr_un server;
int sfd=socket(AF_UNIX,SOCK_STREAM,0);
server.sun_family=AF_UNIX;
strcpy(server.sun_path,"backupserver");
while(connect(sfd,(struct sockaddr *)&server,sizeof(server)))
perror("");
pthread_create(&t1,0,advertise,(void *)&rawfd);
pthread_create(&t2,0,announce_sock,(void *)&rawfd2);
while(1)
{
tfd=recv_fd(sfd);
while(1)
{
a=read(tfd,buf,sizeof(buf));
if(a<=0)
{
printf("TRAIN LEFT\\n");
kill(pid,SIGUSR1);
break;
}
else
{
buf[a]='\\0';
printf("%s ",buf[a]);
}
}
}
}
| 1
|
#include <pthread.h>
int memory[(2*960+1)];
int next_alloc_idx = 1;
pthread_mutex_t m;
int top;
int index_malloc(){
int curr_alloc_idx = -1;
pthread_mutex_lock(&m);
if(next_alloc_idx+2-1 > (2*960+1)){
pthread_mutex_unlock(&m);
curr_alloc_idx = 0;
}else{
curr_alloc_idx = next_alloc_idx;
next_alloc_idx = 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>
static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER;
void output_init()
{
return;
}
void output( char * string, ... )
{
va_list ap;
pthread_mutex_lock(&m_trace);
__builtin_va_start((ap));
vprintf(string, ap);
;
pthread_mutex_unlock(&m_trace);
}
void output_fini()
{
return;
}
pthread_mutex_t m;
void * threaded(void * arg)
{
int ret;
ret = pthread_mutex_unlock(&m);
if (ret == 0)
{ UNRESOLVED(ret, "Unlocking a not owned recursive mutex succeeded"); }
if (ret != EPERM)
output("Unlocking a not owned recursive mutex did not return EPERM\\n");
return 0;
}
int main(int argc, char * argv[])
{
int ret;
pthread_mutexattr_t ma;
pthread_t th;
output_init();
ret = pthread_mutexattr_init(&ma);
if (ret != 0)
{ UNRESOLVED(ret, "Mutex attribute init failed"); }
ret = pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_RECURSIVE);
if (ret != 0)
{ UNRESOLVED(ret, "Set type recursive failed"); }
ret = pthread_mutex_init(&m, &ma);
if (ret != 0)
{ UNRESOLVED(ret, "Mutex init failed"); }
ret = pthread_mutex_lock(&m);
if (ret != 0)
{ UNRESOLVED(ret, "Mutex lock failed"); }
ret = pthread_mutexattr_destroy(&ma);
if (ret != 0)
{ UNRESOLVED(ret, "Mutex attribute destroy failed"); }
ret = pthread_create(&th, 0, threaded, 0);
if (ret != 0)
{ UNRESOLVED(ret, "Thread creation failed"); }
ret = pthread_join(th, 0);
if (ret != 0)
{ UNRESOLVED(ret, "Thread join failed"); }
ret = pthread_mutex_unlock(&m);
if (ret != 0)
{ UNRESOLVED(ret, "Mutex unlock failed. Mutex got corrupted?"); }
PASSED;
}
| 1
|
#include <pthread.h>
char *buffer;
int thread_size;
int buf_ptr_idx;
pthread_mutex_t mutex;
pthread_mutex_t prio_mutex;
pthread_barrier_t barrier;
void* thread_run(void *thread_idx){
pthread_mutex_lock(&prio_mutex);
pthread_mutex_unlock(&prio_mutex);
int idx = *((int *) thread_idx);
for (int i = 0; i < thread_size; i++){
pthread_mutex_lock(&mutex);
*(buffer+buf_ptr_idx++) = idx+'A';
pthread_mutex_unlock(&mutex);
}
pthread_barrier_wait(&barrier);
}
void print_sched(int policy){
switch(policy){
case SCHED_FIFO:
printf("SCHED_FIFO\\n");
break;
case SCHED_RR:
printf("SCHED_RR\\n");
break;
case SCHED_OTHER:
printf("SCHED_OTHER\\n");
break;
case SCHED_IDLE:
printf("SCHED_IDLE\\n");
case 7:
printf("SCHED_LOW_IDLE\\n");
break;
default:
printf("unknown\\n");
}
}
void set_priority(pthread_t *thr, int newpolicy, int newpriority){
int policy, ret;
struct sched_param param;
pthread_t t;
if(newpriority > sched_get_priority_max(newpolicy) ||
newpriority < sched_get_priority_min(newpolicy)){
printf("Invalid priority: MIN: %d, MAX: %d\\n", sched_get_priority_min(newpolicy), sched_get_priority_max(newpolicy));
}
pthread_getschedparam(*thr, &policy, ¶m);
param.sched_priority = newpriority;
ret = pthread_setschedparam(*thr, newpolicy, ¶m);
if (ret != 0){
perror("perror(): ");
}
}
int main(int argc, char **argv){
int num_threads = atoi(*(argv+1));
int buf_size = 1000*atoi(*(argv+2));
buffer = (char *) malloc(buf_size*sizeof(char));
char *policy = *(argv+3);
int prio = atoi(*(argv+4));
int new_policy;
if(!strcmp(policy,"SCHED_FIFO")){
new_policy = SCHED_FIFO;
}
else if(!strcmp(policy,"SCHED_RR")){
new_policy = SCHED_RR;
}
else if(!strcmp(policy,"SCHED_OTHER")){
new_policy = SCHED_OTHER;
}
else if(!strcmp(policy,"SCHED_IDLE")){
new_policy = SCHED_IDLE;
}
else if(!strcmp(policy,"SCHED_LOW_IDLE")){
new_policy = 7;
}
thread_size = buf_size/num_threads;
buf_ptr_idx = 0;
pthread_mutex_init(&mutex,0);
pthread_mutex_init(&prio_mutex,0);
pthread_t *threads;
threads = (pthread_t *) malloc(num_threads * sizeof(pthread_t));
pthread_barrier_init(&barrier,0,num_threads+1);
int *thread_indices = (int *) malloc(num_threads * sizeof(int));
for (int i = 0; i < num_threads; ++i){
*(thread_indices+i) = i;
pthread_mutex_lock(&prio_mutex);
pthread_create(threads+i, 0, thread_run, thread_indices+i);
set_priority(threads+i,new_policy,prio);
pthread_mutex_unlock(&prio_mutex);
}
pthread_barrier_wait(&barrier);
int *scheds = (int *) malloc(num_threads * sizeof(int));
(*(scheds + *buffer - 'A'))++;
if(*(argv+5))
printf("%c",*buffer);
for (int i = 1; i < buf_ptr_idx; i++){
if (*(argv+5)){
printf("%c",*(buffer+i));
}
if(*(buffer+i)!=*(buffer+i-1)){
(*(scheds + *(buffer+i) - 'A'))++;
}
}
printf("\\n");
for (int i = 0; i < num_threads; i++){
printf("%c: %d\\n",i+'A',*(scheds+i));
}
return 0;
}
| 0
|
#include <pthread.h>
unsigned int thread_number = 5;
unsigned int require_number = 20;
unsigned int cur_number = 0;
long sum = 0;
const char * inputfile = "input.txt";
const char * outputfile = "output.txt";
const char * splitter1 = "=";
const char * splitter2 = "\\n";
pthread_mutex_t Device_mutex;
void *ret;
void *add(void *arg);
int main()
{
FILE *fp;
if((fp=fopen(inputfile,"r"))==0)
{
printf("Sorry, I can not open the file! Please verify it~~~");
return -1;
}
char buf[1024];
unsigned long tmp[2];
char *p1, *p2;
int i=0;
while(fgets(buf,1024,fp)){
if(i>=2)break;
p1 = strtok(buf,splitter1);
p2 = strtok(0,splitter2);
tmp[i++] = (unsigned long)strtoul(p2,0,10);
}
thread_number = (unsigned int)(tmp[0]<99 ? tmp[0] : 99);
if(tmp[1] > 4294967295U)
{
printf("the require number is too big, I'll set it as UINT_MAX \\n");
tmp[1] = (unsigned long)(4294967295U);
}
require_number = tmp[1] & 4294967295U;
fclose(fp);
pthread_mutex_init(&Device_mutex,0);
pthread_t pthread[99];
for(i = 0; i < thread_number; i++)
{
printf("create the %uth thread~~~\\n", i+1);
pthread_create(&pthread[i],0,add,0);
}
for(i = 0; i < thread_number; i++){
pthread_join(pthread[i],&ret);
}
return 0;
}
void *add(void *arg)
{
while(cur_number <= require_number)
{
pthread_mutex_lock(&Device_mutex);
cur_number++;
sum = sum + cur_number;
printf("the thread id = %u , the current num is %u,\\tthe current sum is %ld\\n" , syscall(SYS_gettid),cur_number,sum);
if(cur_number == require_number)
{
char buf[1024];
sprintf(buf,"%ld",sum);
FILE *fp;
if((fp=fopen(outputfile,"w+"))==0)
{
printf("Sorry, I can not open the file! Please verify it~~~");
return -1;
}
fwrite(buf,strlen(buf),1,fp);
fflush(fp);
printf("write to file...\\n");
fclose(fp);
exit(0);
}
pthread_mutex_unlock(&Device_mutex);
usleep(100);
}
if(cur_number > require_number) printf(">>>>>>>>>>>>\\n");
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct list_node_s{
int data;
struct list_node_s* next;
};
int Member(int value, struct list_node_s* head_p){
struct list_node_s* curr_p = head_p;
while(curr_p != 0 && curr_p->data < value){
curr_p = curr_p->next;
}
if(curr_p == 0 || curr_p->data > value){
return 0;
}
else {
return 1;
}
}
int Insert(int value, struct list_node_s** head_p){
struct list_node_s* curr_p = *head_p;
struct list_node_s* pred_p = 0;
struct list_node_s* temp_p;
while(curr_p != 0 && curr_p->data < value){
pred_p = curr_p;
curr_p = curr_p->next;
}
if(curr_p == 0 || curr_p->data > value){
temp_p = malloc(sizeof(struct list_node_s));
temp_p->data = value;
temp_p->next = curr_p;
if(pred_p == 0)
*head_p = temp_p;
else pred_p->next = temp_p;
return 1;
}
else return 0;
}
int Delete(int value, struct list_node_s** head_p){
struct list_node_s* curr_p = *head_p;
struct list_node_s* pred_p = 0;
while(curr_p != 0 && curr_p->data < value){
pred_p = curr_p;
curr_p = curr_p->next;
}
if(curr_p != 0 && curr_p->data == value){
if(pred_p == 0){
*head_p = curr_p->next;
free(curr_p);
}
else{
pred_p->next = curr_p->next;
free(curr_p);
}
return 1;
}
else{
return 0;
}
}
struct list_node_s* list = 0;
void N_Insert(double ops){
double i;
unsigned int *seedp;
for(i = 0; i < ops; i++) {
pthread_mutex_lock(&mutex);
Insert(1000,&list);
pthread_mutex_unlock(&mutex);
}
return;
}
void N_Member(double ops){
double i;
unsigned int *seedp;
for(i = 0; i < ops; i++) {
pthread_mutex_lock(&mutex);
Member(1000,list);
pthread_mutex_unlock(&mutex);
}
return;
}
void N_Delete(double ops){
double i;
unsigned int *seedp;
for(i = 0; i < ops; i++) {
pthread_mutex_lock(&mutex);
Delete(1000,&list);
pthread_mutex_unlock(&mutex);
}
return;
}
double members, inserts, deletes;
void* N_All(void* rank){
long my_rank = (long) rank;
N_Member(members);
N_Insert(inserts);
N_Delete(deletes);
return 0;
}
int main(int argc, char* argv[]){
long thread;
double thread_count,i, elapsed;
pthread_t *thread_handles;
struct list_node_s* list = 0;
struct timespec begin,end;
srand(4);
thread_count = strtol(argv[1],0,10);
thread_handles = malloc(thread_count* sizeof(pthread_t));
scanf("%lf %lf %lf", &members, &inserts, &deletes);
members = (members * 1000.0)/thread_count;
inserts = (inserts * 1000.0)/thread_count;
deletes = (deletes * 1000.0)/thread_count;
for(i = 0; i < 1000; i++){
Insert(i,&list);
}
clock_gettime(CLOCK_MONOTONIC, &begin);
for(thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], 0, N_All, (void*) thread);
for(thread = 0; thread < thread_count; thread++) pthread_join(thread_handles[thread], 0);
clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = end.tv_sec - begin.tv_sec;
elapsed += (end.tv_nsec - begin.tv_nsec) / 1000000000.0;
printf("%lf\\n", elapsed);
return 0;
}
| 0
|
#include <pthread.h>
{
char *message;
char *dest;
unsigned mod;
} ThreadInfo, *pThreadInfo;
pthread_t tid[2];
int counter;
pthread_mutex_t lock;
void * Proc(void * args)
{
ThreadInfo ti = * (pThreadInfo)args;
int i, j;
for(i = 0; i < 10 + ti.mod; ++i)
{
while(counter % 2 != ti.mod)
;
pthread_mutex_lock(&lock);
counter += 1;
printf("Got %s Writing %s\\n", ti.dest, ti.message);
strcpy(ti.dest, ti.message);
pthread_mutex_unlock(&lock);
}
}
int main(int argc, char** argv)
{
int i;
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("Cannot init mutex!\\n");
return 1;
}
ThreadInfo ti1, ti2;
counter = 1;
char *dest = (char*)malloc(sizeof(char) * 10);
strcpy(dest, "ping");
ti1.mod = 0;
ti1.message = (char*)malloc(sizeof(char) * 10);
strcpy(ti1.message, "ping");
ti1.dest = dest;
printf("creating first thread...\\n");
pthread_create(tid, 0, &Proc, (void*) &ti1);
ti2.mod = 1;
ti2.message = (char*)malloc(sizeof(char) * 10);
strcpy(ti2.message, "pong");
ti2.dest = dest;
printf("creating second thread...\\n");
pthread_create(tid + 1, 0, &Proc, (void*) &ti2);
pthread_join(tid[0], 0);
pthread_join(tid[1], 0);
pthread_mutex_destroy(&lock);
free(dest);
free(ti1.message);
free(ti2.message);
return 0;
}
| 1
|
#include <pthread.h>
struct control_info {
int rounds;
int bWrite;
int pages;
char * addr;
int conflict;
};
char g_buffer[(16 * 1024 + 1) * (4*1024)];
pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
unsigned int overlap_count = 0;
void unit_work(void)
{
int i;
int f,f1,f2;
struct timeinfo begin, end;
f1 =12441331;
f2 = 3245235;
for (i = 47880; i > 0; i--) {
f *= f1;
f1 *= f2;
f1 *= f2;
f2 *= f;
f2 *= f;
f *= f1;
f *= f1;
f1 *= f2;
f1 *= f2;
f2 *= f;
f2 *= f;
f *= f1;
}
}
void dirty_pages(char * start, int num, int content)
{
int i;
if(start == 0 || num == 0)
return;
for(i = 0; i < num; i++)
start[i*(4*1024)] = content;
return;
}
void * child_thread(void * data)
{
struct control_info * pCntrl = (struct control_info *)data;
int rounds;
char * pStart = 0;
int pages = 0;
int i;
pthread_mutex_lock(&g_lock);
if(pCntrl->conflict) {
g_buffer[1] = i;
}
pthread_mutex_unlock(&g_lock);
if(pCntrl->bWrite)
{
pStart = pCntrl->addr;
pages = pCntrl->pages;
}
rounds = pCntrl->rounds;
for(i = 0; i < rounds; i++)
{
unit_work();
}
dirty_pages(pStart, pages, i);
}
const long int A = 48271;
const long int M = 2147483647;
static int random2(unsigned int m_seed)
{
long tmp_seed;
long int Q = M / A;
long int R = M % A;
tmp_seed = A * ( m_seed % Q ) - R * ( m_seed / Q );
if ( tmp_seed >= 0 )
{
m_seed = tmp_seed;
}
else
{
m_seed = tmp_seed + M;
}
return (m_seed%M);
}
void print_help(void)
{
printf("Please check the input\\n");
printf("1, overall workload with units of ms. Normally 16000.\\n");
printf("2, transaction size\\n");
printf("3, share memory pages\\n");
printf("4, conflict rate\\n");
printf("5, number of threads. Not a must, default is 8. It should be set when conflict rate is not 0\\n");
}
int main(int argc,char**argv)
{
double elapse = 0.0;
int i, j;
int workload;
int tran_size;
int mem_pages;
int conflict_rate;
int times;
char * addr = (char *)((unsigned int)g_buffer+(4*1024));
struct control_info *cntrl;
int random_seed = time(0);
start(0);
if(argc < 5) {
print_help();
exit(1);
}
workload = atoi(argv[1]);
tran_size = atoi(argv[2]);
mem_pages = atoi(argv[3]);
conflict_rate = atoi(argv[4]);
const int thr_num = (argc == 6) ? atoi(argv[5]):16;
pthread_t waiters[thr_num];
cntrl = (struct control_info *)malloc(thr_num * sizeof(struct control_info));
if(cntrl == 0)
{
printf("Can not alloc space for control structure\\n");
exit(1);
}
memset((void *)cntrl, 0, (thr_num * sizeof(struct control_info)));
for(i = 0; i < thr_num; i++)
{
struct control_info * control = (struct control_info *)((int)cntrl + i * sizeof(struct control_info));
control->rounds = tran_size;
control->pages = mem_pages;
if(control->pages > 0)
control->bWrite = 1;
else
control->bWrite = 0;
random_seed = random2(random_seed);
if(conflict_rate) {
if(i == 0 || (random_seed%100 < conflict_rate)) {
control->conflict = 1;
}
else {
control->conflict = 0;
}
}
control->addr = (char *)((unsigned long)addr + mem_pages*(4*1024)*i);
}
if((thr_num * tran_size) > workload || (workload%(thr_num * tran_size) != 0)) {
printf("Workload should be multiple times of the product of thread number and transaction size. \\n");
print_help();
exit(1);
}
times = workload/(thr_num * tran_size);
for(i = 0; i < times; i++)
{
for(j = 0; j < thr_num; j++)
pthread_create (&waiters[j], 0, child_thread, (void *)&cntrl[j]);
for(j = 0; j < thr_num; j++) {
pthread_join (waiters[j], 0);
}
}
elapse = stop(0, 0);
printf("%ld\\n", elapse2ms(elapse));
free(cntrl);
return 0;
}
| 0
|
#include <pthread.h>
int NMBR_PLACE_DISPONIBLE=3;
struct n_verrou{
pthread_mutex_t verrou;
pthread_cond_t condition;
int nmbr_place_max;
};
int traitement1(){sleep(1); return 0;}
int traitement2(){sleep(2);return 0;}
int traitement3(){sleep(1);return 0;}
int n_verrou_init(struct n_verrou* v, int n){
v->nmbr_place_max=n;
if(!pthread_mutex_init(&v->verrou,0)) {return -1;}
if(!pthread_cond_init(&v->condition,0)) {return -1;}
if(v->nmbr_place_max!=n){return -1;}
return 0;
}
int n_verrou_lock(struct n_verrou *v){
pthread_mutex_lock(&(v->verrou));
pthread_t moi=pthread_self();
v->nmbr_place_max--;
if(v->nmbr_place_max<0){
printf("Je peux pas executer traitement2 j'attend\\n");
v->nmbr_place_max++;
pthread_cond_wait(&(v->condition),&(v->verrou));
}
printf("Je suis le thread %d j'éxecute traitement2\\n",(int)moi);
printf("Il reste %d places\\n",(v->nmbr_place_max));
pthread_mutex_unlock(&(v->verrou));
traitement2();
pthread_mutex_lock(&(v->verrou));
printf("Je suis le thread %d j'ai fini le traitement2\\n",(int)moi);
struct n_verrou *mon_D1 = (struct n_verrou*)v;
n_verrou_unlock(mon_D1);
return 0;
}
int n_verrou_unlock(struct n_verrou *v){
pthread_t moi= pthread_self();
if(v->nmbr_place_max<0){
printf("Erreur il n'y a pas de thread a libérer\\n");
return -1;
}
else{
v->nmbr_place_max++;
printf("Je libére un thread il reste %d places\\n", v->nmbr_place_max);
pthread_mutex_unlock(&(v->verrou));
pthread_cond_broadcast(&(v->condition));
return 0;
}
}
int n_verrou_destroy(struct n_verrou *v){
free(v);
return 0;
}
void * LesTraitements(void * par){
struct n_verrou *mon_D1 = (struct n_verrou*)par;
int moi=pthread_self();
printf("Je suis le thread %d j'execute traitement1\\n",(int)moi);
traitement1();
n_verrou_lock(mon_D1);
printf("Je suis le thread %d j'execute traitement3\\n",(int)moi);
pthread_exit(0);
}
int main(){
struct n_verrou mon_mut;
n_verrou_init(&mon_mut,NMBR_PLACE_DISPONIBLE);
pthread_t T[5];
for(int i=0;i<5;i++){
pthread_create(&T[i],0,LesTraitements,&mon_mut);
}
for(int i=0;i<5;i++){
pthread_join(T[i],0);
}
return 0;
}
| 1
|
#include <pthread.h>
int buffer[10];
int in;
int out;
int download_complete;
sem_t full;
sem_t empty;
pthread_mutex_t mutex;
int fake_number;
} shared_t;
shared_t g_shared;
int get_block_from_net(int* p) {
pthread_mutex_lock(&g_shared.mutex);
*p = ++ g_shared.fake_number;
pthread_mutex_unlock(&g_shared.mutex);
printf("get %d block from net\\n", *p);
if (g_shared.fake_number >= 20) { return 1; }
return 0;
}
void write_block_to_disk(int* p) {
printf("write %d block to disk ...\\n", *p);
pthread_mutex_lock(&g_shared.mutex);
*p = 0;
pthread_mutex_unlock(&g_shared.mutex);
}
void* procA(void* arg) {
while (1) {
sem_wait(&g_shared.empty);
g_shared.download_complete
= get_block_from_net(g_shared.buffer + g_shared.in);
g_shared.in = (g_shared.in + 1) % 10;
sem_post(&g_shared.full);
if (g_shared.download_complete) { break; }
}
return 0;
}
void* procB(void* arg) {
while (1) {
sem_wait(&g_shared.full);
write_block_to_disk(g_shared.buffer + g_shared.out);
g_shared.out = (g_shared.out + 1) % 10;
sem_post(&g_shared.empty);
if (g_shared.download_complete
&& g_shared.out == g_shared.in) { break; }
}
return 0;
}
int main(int argc, const char *argv[])
{
memset((void*)&g_shared, 0, sizeof(shared_t));
sem_init(&g_shared.empty, 0, 10);
sem_init(&g_shared.full, 0, 0);
pthread_t pa, pb;
if (pthread_create(&pa, 0, procA, 0) != 0) {
printf("pthread error!\\n");
}
if (pthread_create(&pb, 0, procB, 0) != 0) {
printf("pthread error!\\n");
}
pthread_join(pa, 0);
pthread_join(pb, 0);
sem_destroy(&g_shared.empty);
sem_destroy(&g_shared.full);
return 0;
}
| 0
|
#include <pthread.h>
extern int signal_quit;
extern pthread_mutex_t signal_quit_mutex;
void*
loadmonitor(void *loadhistory)
{
struct pmm_loadhistory *h;
struct pmm_load l;
int rc;
int sleep_for = 60;
int sleep_for_counter = 0;
int sleep_for_fraction = 5;
int write_period = 10*60;
int write_period_counter=0;
h = (struct pmm_loadhistory*)loadhistory;
LOGPRINTF("[loadmonitor]: h:%p\\n", h);
for(;;) {
if((l.time = time(0)) == (time_t)-1) {
ERRPRINTF("Error retreiving unix time.\\n");
exit(1);
}
if(getloadavg(l.load, 3) != 3) {
ERRPRINTF("Error retreiving load averages from getloadavg.\\n");
exit(1);
}
if((rc = pthread_rwlock_wrlock(&(h->history_rwlock))) != 0) {
ERRPRINTF("Error aquiring write lock:%d\\n", rc);
exit(1);
}
add_load(h, &l);
rc = pthread_rwlock_unlock(&(h->history_rwlock));
sleep_for_counter = 0;
while(sleep_for_counter<=sleep_for) {
pthread_mutex_lock(&signal_quit_mutex);
if(signal_quit) {
pthread_mutex_unlock(&signal_quit_mutex);
LOGPRINTF("signal_quit set, writing history file ...\\n");
if(write_loadhistory(h) < 0) {
perror("[loadmonitor]");
ERRPRINTF("Error writing history.\\n");
exit(1);
}
return (void*)0;
}
pthread_mutex_unlock(&signal_quit_mutex);
sleep(sleep_for_fraction);
sleep_for_counter += sleep_for_fraction;
}
write_period_counter += sleep_for;
if(write_period_counter == write_period) {
LOGPRINTF("writing history to file ...\\n");
if(write_loadhistory(h) < 0) {
perror("[loadmonitor]");
ERRPRINTF("Error writing history.\\n");
exit(1);
}
write_period_counter = 0;
}
}
}
| 1
|
#include <pthread.h>
static long memory[2][0xFFF];
static pthread_mutex_t locks[2];
static long read(uint16_t section, uint16_t loc) {
pthread_mutex_lock(&locks[section]);
long ret = memory[section][loc];
pthread_mutex_unlock(&locks[section]);
return ret;
}
static void write(uint16_t section, uint16_t loc, long val) {
pthread_mutex_lock(&locks[section]);
memory[section][loc] = val;
pthread_mutex_unlock(&locks[section]);
}
static void xchg(uint16_t section, uint16_t loc1, uint16_t loc2) {
pthread_mutex_lock(&locks[section]);
memory[section][loc1] ^= memory[section][loc2];
memory[section][loc2] ^= memory[section][loc1];
memory[section][loc1] ^= memory[section][loc2];
pthread_mutex_unlock(&locks[section]);
}
void mtmxchg_setup(void) {
bzero(memory, sizeof(memory));
for (uint16_t i = 0; i < 2; i++) {
pthread_mutex_init(&locks[i], 0);
}
}
void* mtmxchg_consensus(void* arg) {
struct consensus_input* input = arg;
size_t id = input->thread_id + 1;
write(0, id, (long) input->input);
write(1, id, id);
xchg(1, 0, id);
uint16_t curr = id;
while (1) {
uint16_t next = read(1, curr);
if (next == 0) {
return (void*) read(0, curr);
}
curr = next;
}
}
| 0
|
#include <pthread.h>
struct npr_symbol *npr_plus_symbol, *npr_minus_symbol;
struct backet {
struct backet *chain;
struct npr_symbol *value;
};
struct table_t {
unsigned int num_backets;
struct backet **backets;
};
static struct table_t table;
static int
hash(const char *string, int len)
{
unsigned int hval = NPR_SYMBOL_FNV1_32A_INIT;
int i;
for (i=0; i<len; i++) {
npr_symbol_hash_push(&hval, string[i]);
}
return hval;
}
static pthread_mutex_t sym_lock = PTHREAD_MUTEX_INITIALIZER;
struct npr_symbol *
npr_intern_with_hash( const char * symstr, size_t str_len, unsigned int hval )
{
pthread_mutex_lock(&sym_lock);
unsigned int h = hval % table.num_backets;
struct backet *chain, **begin = &(table.backets[h]);
struct backet *b;
struct npr_symbol *sym;
chain = *begin;
while ( chain ) {
if ((chain->value->symstr_len == str_len) &&
(memcmp(chain->value->symstr,symstr,str_len) == 0))
return chain->value;
chain = chain->chain;
}
sym = malloc( sizeof(struct npr_symbol) );
sym->symstr = malloc( str_len+1 );
memcpy( sym->symstr, symstr, str_len );
sym->symstr[ str_len ] = '\\0';
sym->symstr_len = str_len;
sym->hashcode = hval;
sym->keyword = 0;
sym->var_value = 0;
sym->tag_value = 0;
b = malloc( sizeof(struct backet) );
b->value = sym;
b->chain = table.backets[h];
table.backets[h] = b;
pthread_mutex_unlock(&sym_lock);
return sym;
}
struct npr_symbol *
npr_intern_with_length( const char *symstr, size_t str_len )
{
unsigned int hval = hash(symstr,str_len);
return npr_intern_with_hash(symstr, str_len, hval);
}
struct npr_symbol *
npr_intern( const char *symstr )
{
return npr_intern_with_length( symstr, strlen(symstr) );
}
const char *
npr_intern_str(const char *symstr)
{
struct npr_symbol *sym = npr_intern(symstr);
return sym->symstr;
}
void
npr_symbol_init( void )
{
static int init = 0;
int i;
if (init) {
return;
}
init = 1;
table.num_backets = 173;
table.backets = (struct backet**)malloc( sizeof(struct backet*) * 173 );
for ( i=0; i<173; i++ ) {
table.backets[i] = 0;
}
}
void
npr_symbol_finish( void )
{
int i;
for ( i=0; i<173; i++ ) {
struct backet *p = table.backets[i], *next;
while ( p ) {
next = p->chain;
free( p->value->symstr );
free( p->value );
free( p );
p = next;
}
}
free( table.backets );
}
| 1
|
#include <pthread.h>
int pencil = 10;
pthread_mutex_t mutex;
void *thread_producer(void *argv)
{
for (int i = 0; i < 100; i++)
{
pthread_mutex_lock(&mutex);
++pencil;
printf("thread produce a pencil %d\\n", pencil);
pthread_mutex_unlock(&mutex);
usleep(500*1000);
}
}
void *thread_consumer(void *argv)
{
int id = (int)argv;
for (;;)
{
pthread_mutex_lock(&mutex);
if (pencil < 1)
{
pthread_mutex_unlock(&mutex);
break;
}
printf("thread consumer[%d] sell a pencil [%d]\\n", id, pencil);
--pencil;
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main()
{
int ret;
pthread_t pth_pro, pth_con1, pth_con2;
pthread_mutex_init(&mutex, 0);
ret = pthread_create(&pth_pro, 0, thread_producer, 0);
assert(ret == 0);
ret = pthread_create(&pth_con1, 0, thread_consumer, (void *)1);
assert(ret == 0);
ret = pthread_create(&pth_con2, 0, thread_consumer, (void*)2);
pthread_join(pth_pro, 0);
pthread_join(pth_con1, 0);
pthread_join(pth_con2, 0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
int producerTotal = 0;
int consumerTotal = 0;
int buffer[100];
int fill_ptr = 0;
int use_ptr = 0;
int count = 0;
int producerSum = 0;
int consumerSum = 0;
int loops = 10000;
pthread_cond_t empty = PTHREAD_COND_INITIALIZER;
pthread_cond_t fill = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void put(int value) {
buffer[fill_ptr] = value;
fill_ptr = (fill_ptr + 1) % 100;
count++;
}
int get() {
int tmp = buffer[use_ptr];
use_ptr = (use_ptr + 1) % 100;
count--;
return tmp;
}
void *producer(void *arg) {
int producerSum = 0;
while(producerTotal < 10000) {
pthread_mutex_lock(&mutex);
while (count == 100) {
if(producerTotal == 10000) {
break;
}
pthread_cond_wait(&empty, &mutex);
}
if (producerTotal < 10000) {
int random = rand();
put(random);
producerSum += random;
producerTotal++;
}
pthread_cond_signal(&fill);
pthread_mutex_unlock(&mutex);
}
return producerSum;
}
void *consumer(void *arg) {
int consumerSum = 0;
while(consumerTotal < 10000) {
pthread_mutex_lock(&mutex);
while (count == 0) {
if(consumerTotal == 10000) {
break;
}
pthread_cond_wait(&fill, &mutex);
}
if (consumerTotal < 10000) {
int tmp = get();
consumerSum += tmp;
consumerTotal++;
}
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
}
return consumerSum;
}
int main() {
int producerSumGlobal = 0;
int consumerSumGlobal = 0;
int prReturn[9222];
int coReturn[9222];
int i = 0;
pthread_t prThread[9222];
pthread_t coThread[9222];
srand(time(0));
for(i = 0; i < 9222; i++) {
pthread_create(&prThread[i], 0, producer, 0);
pthread_create(&coThread[i], 0, consumer, 0);
}
for(i = 0; i < 9222; i++) {
pthread_join(prThread[i], &prReturn[i]);
pthread_join(coThread[i], &coReturn[i]);
}
for (i = 0; i < 9222; i++) {
producerSumGlobal += prReturn[i];
consumerSumGlobal += coReturn[i];
}
printf("producer: %d\\nconsumer: %d\\n", producerSumGlobal,
consumerSumGlobal);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer = 0;
void* producer(void *ptr) {
int i;
for (i = 1; i <= 100000; i++) {
pthread_mutex_lock(&the_mutex);
while (buffer != 0)
pthread_cond_wait(&condp, &the_mutex);
buffer = i;
printf("Producer wrote %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 <= 100000; i++) {
pthread_mutex_lock(&the_mutex);
while (buffer == 0)
pthread_cond_wait(&condc, &the_mutex);
printf("Consumer reads %d\\n", buffer);
buffer = 0;
pthread_cond_signal(&condp);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
int main(int argc, char **argv) {
pthread_t pro, con;
pthread_mutex_init(&the_mutex, 0);
pthread_cond_init(&condc, 0);
pthread_cond_init(&condp, 0);
pthread_create(&con, 0, consumer, 0);
pthread_create(&pro, 0, producer, 0);
pthread_join(con, 0);
pthread_join(pro, 0);
pthread_mutex_destroy(&the_mutex);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
}
| 0
|
#include <pthread.h>
static unsigned int const MIN_TRUCK_WEIGHT = 1;
static unsigned int const MAX_TRUCK_WEIGHT = 5;
static unsigned int const MAX_TRUCKS_PER_TRIP = 5;
static unsigned int const MAX_WEIGHT_PER_TRIP = 15;
static unsigned int const MIN_FERRY_YIELDS = 5;
static unsigned int const MAX_FERRY_YIELDS = 10;
static unsigned int const MIN_TRUCK_YIELDS = 2;
static unsigned int const MAX_TRUCK_YIELDS = 3;
int combustible = 30;
int peso_ferry = 0;
int numero_camiones_ferry = 0;
int ferry_base=1;
int zona_espera_lista=0;
int fin = 0;
pthread_mutex_t ferry_mutex;
pthread_cond_t ferry_cond;
pthread_cond_t zona_espera_cond;
int aleatorio(){
int r;
int t;
r = rand();
t = (r%5)+1;
return t;
}
void
set_random_seed() {
unsigned int seed;
FILE* urandom = fopen("/dev/urandom", "r");
fread(&seed, sizeof(int), 1, urandom);
fclose(urandom);
srand(seed);
}
void random_yields(unsigned int min, unsigned int max) {
if (min + max < min) {
fprintf(stderr, "random_yields: int sum overflow\\n");
exit(1);
}
if (max < min) {
fprintf(stderr, "random_yields: max must be >= min\\n");
exit(1);
}
int range = max - min;
int n = min + (random()%(1+range));
for (int i=0; i<n; i++)
sched_yield();
}
void* ferryfunction() {
while(1){
pthread_mutex_lock (&ferry_mutex);
ferry_base=1;
pthread_cond_signal(&zona_espera_cond);
while (zona_espera_lista==0){
pthread_cond_wait (&ferry_cond, &ferry_mutex);
}
zona_espera_lista=0;
pthread_mutex_unlock(&ferry_mutex);
printf("FERRY> Transporting %d trucks (%d tons).\\n", numero_camiones_ferry, peso_ferry);
random_yields(MIN_FERRY_YIELDS, MAX_FERRY_YIELDS);
combustible = combustible-peso_ferry;
printf("FERRY> Coming back, remaining fuel %d.\\n", combustible);
pthread_mutex_lock (&ferry_mutex);
if (fin==1){
printf("FERRY> OUT OF FUEL, CLOSING FERRY.\\n");
pthread_cond_signal(&zona_espera_cond);
pthread_mutex_unlock (&ferry_mutex);
pthread_exit(0);
}
pthread_mutex_unlock (&ferry_mutex);
}
}
void* puesto_control() {
int fin_control=0;
int peso_camion;
int camiones_espera = 0;
int numero_camiones_espera = 0;
int combustible_control = 30;
int zona_espera_ready = 0;
srand(time(0));
while (1){
peso_camion = aleatorio();
printf("CONTROL> Incoming new truck (%d tons) \\n", peso_camion);
if ((camiones_espera+peso_camion)>=combustible_control){
printf("CONTROL> OUT OF FUEL, CLOSING CONTROL.\\n");
zona_espera_ready=1;
pthread_mutex_lock(&ferry_mutex);
fin_control=1;
pthread_mutex_unlock(&ferry_mutex);
}else
if((numero_camiones_espera+1)==6)
{
printf("CONTROL> Area is full, waiting for next ferry.\\n");
zona_espera_ready=1;
}else
if ((camiones_espera+peso_camion)>15)
{
printf("CONTROL> Truck too heavy, waiting for next ferry.\\n");
zona_espera_ready=1;
}
if(zona_espera_ready ==1)
{
zona_espera_ready=0;
pthread_mutex_lock(&ferry_mutex);
while(ferry_base==0)
{
pthread_cond_wait(&zona_espera_cond, &ferry_mutex);
}
peso_ferry=camiones_espera;
numero_camiones_ferry = numero_camiones_espera;
zona_espera_lista=1;
combustible_control= combustible_control - camiones_espera;
pthread_cond_signal(&ferry_cond);
ferry_base=0;
camiones_espera=0;
numero_camiones_espera=0;
if(fin_control==1)
{
fin=1;
pthread_mutex_unlock(&ferry_mutex);
pthread_exit(0);
}
pthread_mutex_unlock(&ferry_mutex);
}
camiones_espera = camiones_espera + peso_camion;
numero_camiones_espera++;
random_yields(MIN_TRUCK_YIELDS, MAX_TRUCK_YIELDS);
printf("CONTROL> Truck Accepted (%d more tons allowed or %d trucks to go)\\n", (MAX_WEIGHT_PER_TRIP-camiones_espera), (MAX_TRUCKS_PER_TRIP-numero_camiones_espera));
}
}
int main (){
printf("CONFIG> Trucks are between %d and %d\\n", MIN_TRUCK_WEIGHT, MAX_TRUCK_WEIGHT);
printf("CONFIG> Ferry init fuel: %d tons\\n", 30);
printf("CONFIG> Ferry trip limits: %d trucks, %d tons\\n", MAX_TRUCKS_PER_TRIP, MAX_WEIGHT_PER_TRIP);
pthread_t threads[2];
set_random_seed();
pthread_cond_init (&ferry_cond, 0);
pthread_cond_init(&zona_espera_cond, 0);
pthread_create(&threads[0], 0, &puesto_control, 0);
pthread_create(&threads[1], 0, &ferryfunction, 0);
for(int j=0; j<2; j++) {
pthread_join(threads[j], 0);
}
pthread_cond_destroy(&ferry_cond);
pthread_cond_destroy(&zona_espera_cond);
pthread_mutex_destroy(&ferry_mutex);
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t g_Mtx;
int g_Sum;
{
int m_Max;
int m_Num;
pthread_t m_ThrID;
} TTHRARG;
void * thrFunc ( void * arg )
{
int i;
int c = 0;
TTHRARG * data = (TTHRARG *)arg;
for ( i = 0; i < data -> m_Max; i ++ )
c += i+1;
pthread_mutex_lock( &g_Mtx );
g_Sum += c;
pthread_mutex_unlock( &g_Mtx );
return ( 0 );
}
int main ( int argc, char * argv [] )
{
TTHRARG * arg;
pthread_attr_t thrAttr;
int i, thr;
void * dummy;
g_Sum = 0;
thr = argc - 1;
if ( thr <= 0 )
{
printf ( "Usage: %s n1 [n2 [n3 [...]]]\\n", argv[0] );
return ( 1 );
}
pthread_mutex_init( &g_Mtx, 0 );
arg = (TTHRARG *) malloc ( thr * sizeof ( *arg ) );
for ( i = 0; i < thr; i ++ )
{
if ( sscanf ( argv[i+1], "%d", &arg[i] . m_Max) != 1 )
{
free ( arg );
printf ( "Invalid argument %d\\n", i + 1 );
pthread_mutex_destroy( &g_Mtx );
return ( 1 );
}
arg[i] . m_Num = i;
}
pthread_attr_init ( &thrAttr );
pthread_attr_setdetachstate ( &thrAttr, PTHREAD_CREATE_JOINABLE );
for ( i = 0; i < thr; i ++ )
if ( pthread_create ( &arg[i] . m_ThrID, &thrAttr, thrFunc, &arg[i] ) )
{
free ( arg );
perror ( "Create thread\\n" );
pthread_mutex_destroy( &g_Mtx );
pthread_attr_destroy ( &thrAttr );
return ( 1 );
}
pthread_attr_destroy ( &thrAttr );
for ( i = 0; i < thr; i ++ )
pthread_join ( arg[i].m_ThrID, &dummy );
printf("%d", g_Sum);
pthread_mutex_destroy( &g_Mtx );
free ( arg );
return ( 0 );
}
| 0
|
#include <pthread.h>
static pthread_cond_t bufferA_cond=PTHREAD_COND_INITIALIZER;
static pthread_cond_t bufferB_cond=PTHREAD_COND_INITIALIZER;
int indexOfbufferA=0;
int indexOfbufferB=0;
char bufferA[50][100];
char bufferB[50][100];
pthread_mutex_t bufferA_mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t bufferB_mutex=PTHREAD_MUTEX_INITIALIZER;
void *func_read(void *arg);
void *func_write(void *arg);
void *func_convert(void *arg);
void *func_read(void *arg)
{
char str[100];
for(;;)
{
fgets(str,100,stdin);
pthread_mutex_lock(&bufferA_mutex);
strcpy(bufferA[indexOfbufferA],str);
indexOfbufferA++;
pthread_cond_broadcast(&bufferA_cond);
pthread_mutex_unlock(&bufferA_mutex);
}
}
void *func_write(void *arg)
{
char str[100];
for(;;)
{
pthread_mutex_lock(&bufferB_mutex);
while(indexOfbufferB==0)
pthread_cond_wait(&bufferB_cond,&bufferB_mutex);
indexOfbufferB=indexOfbufferB-1;
strcpy(str,bufferB[indexOfbufferB]);
printf(">>");
fputs(str,stdout);
pthread_mutex_unlock(&bufferB_mutex);
}
}
void *func_convert(void *arg)
{
int i=0;
char str[100];
for(;;)
{
pthread_mutex_lock(&bufferA_mutex);
while(indexOfbufferA==0)
pthread_cond_wait(&bufferA_cond,&bufferA_mutex);
strcpy(str,bufferA[indexOfbufferA-1]);
i=0;
while(str[i])
{
if(str[i]==' ')
str[i]='%';
i++;
}
indexOfbufferA=indexOfbufferA-1;
pthread_mutex_unlock(&bufferA_mutex);
pthread_mutex_lock(&bufferB_mutex);
strcpy(bufferB[indexOfbufferB],str);
indexOfbufferB++;
pthread_cond_broadcast(&bufferB_cond);
pthread_mutex_unlock(&bufferB_mutex);
}
}
int main()
{
int i=0;
pthread_t tid_write[3];
pthread_t tid_read[3];
pthread_t tid_convert[3];
for(i=0; i<3; i++)
pthread_create(&tid_read[i],0,func_read,0);
for(i=0; i<3; i++)
pthread_create(&tid_write[i],0,func_write,0);
for(i=0; i<3; i++)
pthread_create(&tid_convert[i],0,func_convert,0);
for(i=0; i<3; i++)
pthread_join(tid_read[i],0);
for(i=0; i<3; i++)
pthread_join(tid_write[i],0);
for(i=0; i<3; i++)
pthread_join(tid_convert[i],0);
}
| 1
|
#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;
printf("Thread %ld did %d to %d: mysum=%f global sum=%f\\n",offset,start,end,mysum,dotstr.sum);
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*100000*sizeof(double));
b = (double*) malloc (4*100000*sizeof(double));
for (i=0; i<100000*4; i++) {
a[i]=1;
b[i]=a[i];
}
dotstr.veclen = 100000;
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);
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error() ;
unsigned int __VERIFIER_nondet_uint();
static int top=0;
static unsigned int arr[(400)];
pthread_mutex_t m;
_Bool flag=(0);
void error(void)
{
ERROR: __VERIFIER_error(); return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
return (top==0) ? (1) : (0);
}
int push(unsigned int *stack, int x)
{
if (top==(400))
{
printf("stack overflow\\n");
return (-1);
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (top==0)
{
printf("stack underflow\\n");
return (-2);
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for(i=0; i<(400); i++)
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint()%(400);
if ((push(arr,tmp)==(-1)))
error();
pthread_mutex_unlock(&m);
}
return 0;
}
void *t2(void *arg)
{
int i;
for(i=0; i<(400); i++)
{
pthread_mutex_lock(&m);
if (top>0)
{
if ((pop(arr)==(-2)))
error();
}
pthread_mutex_unlock(&m);
}
return 0;
}
int main(void)
{
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 1
|
#include <pthread.h>
{
int balance;
pthread_mutex_t mutex;
} Account;
void deposit(Account* account, int amount)
{
pthread_mutex_lock(&(account->mutex));
account->balance += amount;
pthread_mutex_unlock(&(account->mutex));
}
void transfer(Account* accountA, Account* accountB, int amount)
{
if (accountA < accountB)
{
Account* tmp = accountA;
accountA = accountB;
accountB = tmp;
amount = -amount;
}
pthread_mutex_lock(&(accountA->mutex));
pthread_mutex_lock(&(accountB->mutex));
accountA->balance += amount;
accountB->balance -= amount;
pthread_mutex_unlock(&(accountB->mutex));
pthread_mutex_unlock(&(accountA->mutex));
}
Account accountA;
Account accountB;
void *thread_start()
{
int i;
for ( i = 0 ; i < 1000000 ; i++)
{
transfer( &accountA, &accountB, 10 );
transfer( &accountB, &accountA, 10 );
}
pthread_exit(0);
}
int main(int argc, char** argv)
{
accountA.balance = 1000;
pthread_mutex_init( &accountA.mutex, 0 );
accountB.balance = 1000;
pthread_mutex_init( &accountB.mutex, 0 );
pthread_t threads[2];
int i;
for( i = 0 ; i < 2 ; i++ )
{
int res = pthread_create( &threads[i], 0, thread_start, 0 );
if (res)
{
printf("Error: pthread_create() failed with error code %d\\n", res);
exit(-1);
}
}
for( i = 0 ; i < 2 ; i++ )
{
int res = pthread_join(threads[i], 0);
if (res)
{
printf("Error: pthread_join() failed with error code %d\\n", res);
exit(-1);
}
}
printf("Final balance on account A is %d\\n", accountA.balance );
printf("Final balance on account B is %d\\n", accountB.balance );
pthread_mutex_destroy(&accountA.mutex);
pthread_mutex_destroy(&accountB.mutex);
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
static long NUM_ITER = 10;
static double* buffer = 0;
static int buffer_is_empty = 1;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond_producer = PTHREAD_COND_INITIALIZER;
static pthread_cond_t cond_consumer = PTHREAD_COND_INITIALIZER;
void*
func_producer( void* input )
{
long i;
int rand_seed = time( 0 );
for ( i = 0; i < NUM_ITER; i++ )
{
pthread_mutex_lock( &mutex );
while ( !buffer_is_empty )
{
pthread_cond_wait( &cond_producer, &mutex );
}
buffer = malloc( sizeof( *buffer ) );
*buffer = ( double )rand_r( &rand_seed ) / ( double )32767;
printf( "Iteration: %ld Producer produced: %g ", i, *buffer );
buffer_is_empty = 0;
pthread_cond_signal( &cond_consumer );
pthread_mutex_unlock( &mutex );
}
return 0;
}
void*
func_consumer( void* input )
{
long i;
for ( i = 0; i < NUM_ITER; i++ )
{
pthread_mutex_lock( &mutex );
while ( buffer_is_empty )
{
pthread_cond_wait( &cond_consumer, &mutex );
}
printf( "Iteration: %ld Consumer received: %g\\n", i, *buffer );
*buffer = 0.0;
free( buffer );
buffer_is_empty = 1;
pthread_cond_signal( &cond_producer );
pthread_mutex_unlock( &mutex );
}
return 0;
}
int
main( int argc, const char* argv[] )
{
pthread_t producer, consumer;
pthread_mutex_init( &mutex, 0 );
pthread_cond_init( &cond_producer, 0 );
pthread_cond_init( &cond_consumer, 0 );
pthread_create( &producer, 0, func_producer, 0 );
pthread_create( &consumer, 0, func_consumer, 0 );
pthread_join( producer, 0 );
pthread_join( consumer, 0 );
pthread_mutex_destroy( &mutex );
pthread_cond_destroy( &cond_producer );
pthread_cond_destroy( &cond_consumer );
return 0;
}
| 1
|
#include <pthread.h>
struct arg_set {
char *fname;
int count;
};
struct arg_set *mailbox = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t flag = PTHREAD_COND_INITIALIZER;
main(int ac, char *av[])
{
pthread_t t1, t2;
struct arg_set args1, args2;
void *count_words(void *);
int reports_in = 0;
int total_words = 0;
if ( ac != 3 ){
printf("usage: %s file1 file2\\n", av[0]);
exit(1);
}
pthread_mutex_lock(&lock);
args1.fname = av[1];
args1.count = 0;
pthread_create(&t1, 0, count_words, (void *) &args1);
args2.fname = av[2];
args2.count = 0;
pthread_create(&t2, 0, count_words, (void *) &args2);
while( reports_in < 2 ){
printf("MAIN: waiting for flag to go up\\n");
pthread_cond_wait(&flag, &lock);
printf("MAIN: Wow! flag was raised, I have the lock\\n");
printf("%7d: %s\\n", mailbox->count, mailbox->fname);
total_words += mailbox->count;
if ( mailbox == &args1)
pthread_join(t1,0);
if ( mailbox == &args2)
pthread_join(t2,0);
mailbox = 0;
pthread_cond_signal(&flag);
reports_in++;
}
printf("%7d: total words\\n", total_words);
}
void *count_words(void *a)
{
struct arg_set *args = a;
FILE *fp;
int c, prevc = '\\0';
if ( (fp = fopen(args->fname, "r")) != 0 ){
while( ( c = getc(fp)) != EOF ){
if ( !isalnum(c) && isalnum(prevc) )
args->count++;
prevc = c;
}
fclose(fp);
} else
perror(args->fname);
printf("COUNT: waiting to get lock\\n");
pthread_mutex_lock(&lock);
printf("COUNT: have lock, storing data\\n");
if ( mailbox != 0 ){
printf("COUNT: oops..mailbox not empty. wait for signal\\n");
pthread_cond_wait(&flag,&lock);
}
mailbox = args;
printf("COUNT: raising flag\\n");
pthread_cond_signal(&flag);
printf("COUNT: unlocking box\\n");
pthread_mutex_unlock(&lock);
return 0;
}
| 0
|
#include <pthread.h>
static volatile int data;
static pthread_mutex_t mutex_m = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t mutex_j = PTHREAD_MUTEX_INITIALIZER;
static int is_prime(int d)
{
int i;
for (i = 2; i < d / 2; i++) {
if (d % i == 0) {
return 0;
}
}
return 1;
}
void *jobs(void *unuse)
{
while (1) {
pthread_mutex_lock(&mutex_j);
if (is_prime(data)) {
printf("%d ", data);
fflush(0);
} else {
printf("\\033[31m%d\\033[0m ", data);
fflush(0);
}
pthread_mutex_unlock(&mutex_m);
}
}
int main(void)
{
int i;
pthread_t tid[8];
pthread_mutex_lock(&mutex_j);
for (i = 0; i < 8; i++) {
pthread_create(tid + i, 0, jobs, 0);
}
for (i = 10000001; i <= 10000100; i++) {
pthread_mutex_lock(&mutex_m);
data = i;
pthread_mutex_unlock(&mutex_j);
}
for (i = 0; i < 8; i++) {
pthread_join(tid[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
int nitems;
struct {
pthread_mutex_t mutex;
int buff[1000000];
int nput;
int nval;
} shared = {
PTHREAD_MUTEX_INITIALIZER
};
void *produce(void *);
void *consume(void *);
int main(int argc,char *argv[])
{
int i, nthreads, count[100];
pthread_t tid_produce[100], tid_consume;
if (argc != 3) {
exit(1);
}
nitems = min(atoi(argv[1]), 1000000);
nthreads = min(atoi(argv[2]), 100);
set_concurrency(nthreads);
for (i = 0; i < nthreads; i++) {
count[i] = 0;
pthread_create(&tid_produce[i], 0, produce, &count[i]);
}
for (i = 0; i < nthreads; i++) {
pthread_join(tid_produce[i], 0);
printf("count[%d] = %d\\n", i, count[i]);
}
pthread_create(&tid_consume, 0, consume, 0);
pthread_join(tid_consume, 0);
return 0;
}
void *produce(void *arg)
{
for ( ; ; ) {
pthread_mutex_lock(&shared.mutex);
if (shared.nput >= nitems) {
pthread_mutex_unlock(&shared.mutex);
return (0);
}
shared.buff[shared.nput] = shared.nval;
shared.nput++;
shared.nval++;
pthread_mutex_unlock(&shared.mutex);
*((int *) arg) += 1;
}
}
void *consume(void *arg)
{
int i;
for (i = 0; i < nitems; i++)
if (shared.buff[i] != i)
printf("buff[%d] = %d\\n", i, shared.buff[i]);
return (0);
}
| 0
|
#include <pthread.h>
void entry_1()
{
int r = pthread_mutex_lock(&M.mutex);
while(M.first_process_active)
pthread_cond_wait(&M.no_first_process, &M.mutex);
M.first_process_active = 1;
}
void entry_2()
{
int r = pthread_mutex_lock(&M.mutex);
while(M.second_process_active)
pthread_cond_wait(&M.no_second_process, &M.mutex);
M.second_process_active = 1;
}
void entry_3()
{
int r = pthread_mutex_lock(&M.mutex);
while(M.third_process_active)
pthread_cond_wait(&M.no_third_process, &M.mutex);
M.third_process_active = 1;
}
void exit_1()
{
while(!M.second_process_finished)
pthread_cond_wait(&M.atomic_action_ends2, &M.mutex);
pthread_cond_signal(&M.atomic_action_ends1);
pthread_cond_signal(&M.no_first_process);
M.first_process_active = 0;
pthread_mutex_unlock(&M.mutex);
}
void exit_2()
{
while(!M.third_process_finished)
pthread_cond_wait(&M.atomic_action_ends3, &M.mutex);
pthread_cond_signal(&M.atomic_action_ends2);
pthread_cond_signal(&M.no_second_process);
M.second_process_active = 0;
pthread_mutex_unlock(&M.mutex);
}
void exit_3()
{
while(!M.first_process_finished)
pthread_cond_wait(&M.atomic_action_ends1, &M.mutex);
pthread_cond_signal(&M.atomic_action_ends3);
M.third_process_active = 0;
pthread_cond_signal(&M.no_third_process);
pthread_mutex_unlock(&M.mutex);
}
void first_thread()
{
int result;
int thread_no = 1;
for(int i=0; i<10; i++)
{
error = 0;
entry_1(M);
result = aa(thread_no);
M.first_process_finished = 1;
exit_1(M);
vote(result, thread_no);
int rc = pthread_barrier_wait(&M.barr1);
if(rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD)
{
printf("Could not wait on barrier\\n");
exit(-1);
}
if(error == 1)
{
printf("Thread %d detected error after vote! ERROR OCCURED!\\n", thread_no);
result = backtrack(thread_no, result);
rc = pthread_barrier_wait(&M.barr2);
if(rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD)
{
printf("Could not wait on barrier\\n");
exit(-1);
}
printf("Thread %d waiting for other threads after backtrack\\n", thread_no);
}
else
increment();
}
}
void second_thread()
{
int result;
int thread_no = 2;
for(int i=0; i<10; i++)
{
error = 0;
entry_2(M);
result = aa(thread_no);
M.second_process_finished = 1;
exit_2(M);
vote(result, thread_no);
int rc = pthread_barrier_wait(&M.barr1);
if(rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD)
{
printf("Could not wait on barrier\\n");
exit(-1);
}
if(error == 1)
{
printf("Thread %d detected error after vote! ERROR OCCURED!\\n", thread_no);
result = backtrack(thread_no, result);
rc = pthread_barrier_wait(&M.barr2);
if(rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD)
{
printf("Could not wait on barrier\\n");
exit(-1);
}
printf("Thread %d waiting for other threads after backtrack\\n", thread_no);
}
else
increment();
}
}
void third_thread()
{
int result;
int thread_no = 3;
for(int i=0; i<10; i++)
{
error = 0;
entry_3(M);
result = aa(thread_no);
M.third_process_finished = 1;
exit_3(M);
vote(result, thread_no);
int rc = pthread_barrier_wait(&M.barr1);
if(rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD)
{
printf("Could not wait on barrier\\n");
exit(-1);
}
if(error == 1)
{
printf("Thread %d detected error after vote! ERROR OCCURED!\\n", thread_no);
result = backtrack(thread_no, result);
rc = pthread_barrier_wait(&M.barr2);
if(rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD)
{
printf("Could not wait on barrier\\n");
exit(-1);
}
printf("Thread %d waiting for other threads after backtrack\\n", thread_no);
}
else
increment();
}
}
void increment()
{
g_var++;
}
void init()
{
M.first_process_active = 0;
M.second_process_active = 0;
M.third_process_active = 0;
M.first_process_finished = 0;
M.second_process_finished = 0;
M.third_process_finished = 0;
pthread_mutex_init(&M.mutex, 0);
pthread_cond_init(&M.no_first_process, 0);
pthread_cond_init(&M.no_second_process, 0);
pthread_cond_init(&M.no_third_process, 0);
pthread_cond_init(&M.atomic_action_ends1, 0);
pthread_cond_init(&M.atomic_action_ends2, 0);
pthread_cond_init(&M.atomic_action_ends3, 0);
pthread_barrier_init(&M.barr1, 0, THREADS);
pthread_barrier_init(&M.barr2, 0, THREADS);
}
void main()
{
g_var = 0;
error = 0;
pthread_t thread1, thread2, thread3;
printf("\\nInitializing monitor...\\n");
init();
printf("Monitor initialized\\n");
printf("g_var is %d\\n", g_var);
printf("Creating threads...\\n\\n");
pthread_create(&thread1, 0, &first_thread, 0);
pthread_create(&thread2, 0, &second_thread, 0);
pthread_create(&thread3, 0, &third_thread, 0);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
pthread_join(thread3, 0);
printf("g_var is now %d\\n", g_var);
exit(0);
}
| 1
|
#include <pthread.h>
int ptl_timed_wait(long wait_usec){
int timed_wait_result;
struct timespec ts;
pthread_mutex_t timed_wait_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t timed_wait_cond = PTHREAD_COND_INITIALIZER;
ptl_get_future_time(&ts, wait_usec);
pthread_mutex_lock(&timed_wait_mutex);
timed_wait_result = pthread_cond_timedwait(&timed_wait_cond, &timed_wait_mutex, &ts);
pthread_mutex_unlock(&timed_wait_mutex);
pthread_mutex_destroy(&timed_wait_mutex);
pthread_cond_destroy(&timed_wait_cond);
return timed_wait_result;
}
void ptl_get_future_time(struct timespec *ts, long usec){
struct timeval tp;
memset(&tp,0,sizeof(tp));
gettimeofday(&tp, 0);
tp.tv_usec += usec;
TIMEVAL_TO_TIMESPEC(&tp, ts);
}
| 0
|
#include <pthread.h>
int region_length;
int* left;
int* right;
} Region;
pthread_mutex_t lock;
int counter;
sem_t sem;
sem_t sem2;
} Barrier;
void* thread_sort(void*);
Barrier barrier;
int nthreads, *paddr, n;
int main(int argc, char* argv[]) {
if (argc != 2) {
printf("Syntax : %s filename\\n", argv[0]);
return 1;
}
int fd;
if ((fd = open(argv[1], O_RDWR)) == -1) {
printf("Fail opening file\\n");
return 1;
}
struct stat stat_buf;
if (fstat(fd, &stat_buf) == -1) {
printf("Fail executing stat\\n");
return 1;
}
int len = stat_buf.st_size;
n = len / sizeof(int);
paddr = (int*) mmap((void*)0, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, (off_t)0);
if(paddr == (int*)-1) {
printf("Fail while mapping the file in memory\\n");
return 1;
}
close(fd);
nthreads = ceil(log10(n));
printf("nthreads = %i\\n", nthreads);
int region_length = n / nthreads;
pthread_mutex_init(&barrier.lock, 0);
pthread_mutex_lock(&barrier.lock);
barrier.counter = nthreads;
sem_init(&barrier.sem, 0, 0);
sem_init(&barrier.sem2, 0, 0);
pthread_mutex_unlock(&barrier.lock);
Region *regions[nthreads];
pthread_t threads[nthreads];
for (int i = 0; i < nthreads; i++) {
regions[i] = (Region*)malloc(sizeof(Region));
regions[i]->region_length = region_length;
regions[i]->left = paddr + i * region_length;
if (i == nthreads - 1) {
regions[i]->right = paddr + n - 1;
} else {
regions[i]->right = paddr + (i + 1) * region_length - 1;
}
if (pthread_create(&threads[i], 0, thread_sort, regions[i]) != 0) {
printf("Fail creating thread\\n");
return 1;
}
}
void* ret = 0;
pthread_exit(ret);
return 0;
}
void swap(int* a, int* b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
void* thread_sort(void* arg) {
Region* region = (Region*)arg;
while (1) {
int* cur = region->left;
while(cur <= region->right) {
int* tmp = cur;
while(tmp >= region->left + 1 && *(tmp - 1) > *tmp) {
swap(tmp - 1, tmp);
tmp--;
}
cur++;
}
pthread_mutex_lock(&barrier.lock);
barrier.counter--;
if (barrier.counter == 0) {
int swapped = 0;
for (int i = 1; i < nthreads; i++) {
if (*(paddr + i * region->region_length - 1) > *(paddr + i * region->region_length)) {
swap(paddr + i * region->region_length - 1, paddr + i * region->region_length);
swapped = 1;
}
}
if (swapped) {
for (int i = 0; i < nthreads; i++) {
sem_post(&barrier.sem);
}
} else {
cur = paddr;
int i = 0;
while (cur < paddr + n) {
printf("%i : %i\\n", i, *cur);
cur++;
i++;
}
exit(0);
}
}
pthread_mutex_unlock(&barrier.lock);
sem_wait(&barrier.sem);
pthread_mutex_lock(&barrier.lock);
barrier.counter++;
if (barrier.counter == nthreads) {
for (int i = 0; i < nthreads; i++) {
sem_post(&barrier.sem2);
}
}
pthread_mutex_unlock(&barrier.lock);
sem_wait(&barrier.sem2);
}
return arg;
}
| 1
|
#include <pthread.h>
int LOOPS[100000000];
pthread_mutex_t mutex;
pid_t gettid() { return syscall( __NR_gettid ); }
int I = 0;
void *consumer(void *ptr)
{
int local=0;
printf("Consumer TID %lu\\n", (unsigned long)gettid());
while (1)
{
pthread_mutex_lock(&mutex);
if (I >= 100000000)
{
pthread_mutex_unlock(&mutex);
break;
}
LOOPS[I] = 0;
I++;
local++;
pthread_mutex_unlock(&mutex);
}
printf("%d\\n", local);
return 0;
}
int main()
{
int i;
pthread_t thr1, thr2;
struct timeval tv1, tv2;
pthread_mutex_init(&mutex, 0);
for (i = 0; i < 100000000; i++)
LOOPS[i] = 1;
gettimeofday(&tv1, 0);
pthread_create(&thr1, 0, consumer, 0);
pthread_create(&thr2, 0, consumer, 0);
pthread_join(thr1, 0);
pthread_join(thr2, 0);
gettimeofday(&tv2, 0);
if (tv1.tv_usec > tv2.tv_usec)
{
tv2.tv_sec--;
tv2.tv_usec += 1000000;
}
printf("Result - %ld.%ld\\n", tv2.tv_sec - tv1.tv_sec,
tv2.tv_usec - tv1.tv_usec);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t creating_theads_mutex = PTHREAD_MUTEX_INITIALIZER;
int creating_theads = 0;
int *sharedMatrisA;
int *sharedMatrisB;
int *sharedMatrisC;
int m;
int n;
int k;
void *matrisHesapla(int satirno) {
fflush(stdout);
if(creating_theads > 0) {
fflush(stdout);
pthread_mutex_lock( &condition_mutex );
fflush(stdout);
pthread_cond_wait( &condition_cond, &condition_mutex );
fflush(stdout);
pthread_mutex_unlock( &condition_mutex );
fflush(stdout);
} else {
pthread_mutex_unlock(&creating_theads_mutex);
fflush(stdout);
}
int ic1,ic2;
for(ic1=0; ic1<k; ic1++) {
for(ic2=0; ic2<n; ic2++) {
sharedMatrisC[(satirno*k) + ic1] += sharedMatrisA[(satirno*n) + ic2] * sharedMatrisB[(ic2*k)+ic1];
}
}
}
int main() {
printf("TURKIYE\\n");
printf("31-03-2012\\n");
printf("Bugun gunlerden cumartesi\\n");
printf("http://gist.github.com\\n");
printf("Threads\\n\\n");
FILE *fp;
if((fp=fopen("input.txt","r")) == 0) {
printf ("Dosya acilamadi.");
exit(-1);
}
fscanf(fp,"%d %d %d",&m, &n, &k);
int matrisA[m][n];
int matrisB[n][k];
int matrisC[m][k];
sharedMatrisA = &matrisA;
sharedMatrisB = &matrisB;
sharedMatrisC = &matrisC;
int i;
int j;
for(i=0;i<m;i++) {
for(j=0;j<k;j++) {
matrisC[i][j] = 0;
}
}
for(i=0;i<m;i++) {
for(j=0;j<n;j++) {
fscanf(fp,"%d",&matrisA[i][j]);
}
}
for(i=0;i<n;i++) {
for(j=0;j<k;j++) {
fscanf(fp,"%d",&matrisB[i][j]);
}
}
fclose(fp);
printf("Matris A:\\n");
for(i=0;i<m;i++) {
for(j=0;j<n;j++) {
printf("%d\\t", matrisA[i][j]);
}
printf("\\n");
}
printf("\\nMatris B:\\n");
for(i=0;i<n;i++) {
for(j=0;j<k;j++) {
printf("%d\\t", matrisB[i][j]);
}
printf("\\n");
}
printf("\\n");
pthread_t threads[m];
fflush(stdout);
creating_theads = 1;
printf("Threadler yaratılıyor...\\n");
fflush(stdout);
for(i=0;i<m;i++) {
fflush(stdout);
pthread_create(&threads[i], 0, &matrisHesapla, i);
}
pthread_mutex_lock(&creating_theads_mutex);
creating_theads = 0;
pthread_mutex_unlock(&creating_theads_mutex);
printf("Thread yaratimi tamamlamdi. Simdi beklemelerin bitmesi icin mesaj gonderilecek.\\n");
fflush(stdout);
pthread_mutex_lock( &condition_mutex );
pthread_cond_broadcast( &condition_cond );
pthread_mutex_unlock( &condition_mutex );
printf("Beklemekte olabilecek threadlere isleme baslamasini soyleyen mesaj gonderildi.\\n");
fflush(stdout);
for(i=0;i<m;i++) {
pthread_join(threads[i],0);
}
printf("\\nMatris C:\\n");
for(i=0;i<m;i++) {
for(j=0;j<k;j++) {
printf("%d\\t", matrisC[i][j]);
}
printf("\\n");
}
printf("\\n");
printf("...ve bize ayrilan surenin sonuna geldik...\\n");
printf("...bir sonraki odevde gorusmek uzere, esen kalin efendim...\\n");
exit(0);
}
| 1
|
#include <pthread.h>
struct s {
int datum;
struct s *next;
} *A;
void init (struct s *p, int x) {
p -> datum = x;
p -> next = 0;
}
void insert(struct s *p, struct s **list) {
p->next = *list;
*list = p;
}
pthread_mutex_t A_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t B_mutex = PTHREAD_MUTEX_INITIALIZER;
void *t_fun(void *arg) {
struct s *p = malloc(sizeof(struct s));
init(p,7);
pthread_mutex_lock(&A_mutex);
insert(p, &A);
pthread_mutex_unlock(&A_mutex);
pthread_mutex_lock(&B_mutex);
p->datum++;
pthread_mutex_unlock(&B_mutex);
return 0;
}
int main () {
pthread_t t1;
struct s *p;
A = malloc(sizeof(struct s));
init(A,3);
pthread_create(&t1, 0, t_fun, 0);
p = malloc(sizeof(struct s));
init(p,9);
pthread_mutex_lock(&A_mutex);
insert(p, &A);
pthread_mutex_unlock(&A_mutex);
pthread_mutex_lock(&A_mutex);
p = A;
while (p->next)
p = p->next;
printf("%d\\n", p->datum);
pthread_mutex_unlock(&A_mutex);
return 0;
}
| 0
|
#include <pthread.h>
double multiplier = 1.0;
double calculate_multiplier(char *test_image_full_path)
{
gpu_time = -1.0;
cpu_time = 1.0;
running_threads = 0;
pthread_mutex_lock(&running_mutex);
running_threads++;
pthread_mutex_unlock(&running_mutex);
if(pthread_create(&cpu_thread, 0, cpu_filter_thread, 0) != 0)
{
perror("create cpu_thread");
pthread_mutex_lock(&running_mutex);
running_threads = 0;
pthread_mutex_unlock(&running_mutex);
return -1.0;
}
pthread_mutex_lock(&running_mutex);
running_threads++;
pthread_mutex_unlock(&running_mutex);
if(pthread_create(&gpu_thread, 0, gpu_filter_thread, 0) != 0)
{
perror("create gpu_thread");
if(pthread_join(cpu_thread, 0) != 0)
perror("join cpu_thread");
pthread_mutex_lock(&running_mutex);
running_threads = 0;
pthread_mutex_unlock(&running_mutex);
return -1.0;
}
while (running_threads > 0)
{
sleep(1);
}
return ((gpu_time)/cpu_time);
}
int main(int argc, char *argv[])
{
if (argc != 4)
{
fprintf(stdout, "%s", "[RUN]:\\n./initBD </full_path/BDfile> <image_height-width> <step>\\n");
return -1;
}
unsigned long width_height_backup, step;
step = atoi(argv[3]);
width_height_backup = atoi(argv[2]);
printf("step: %ld, max: %ld\\n", step, width_height_backup);
if(width_height_backup <= step)
{
printf("you need to specify <image_height-width> > %ld (you specified %ld)", step, width_height_backup);
return -1;
}
cpu_image = cpu_image_result = gpu_image = 0;
fake_new_wind_image(&cpu_image, width_height_backup, width_height_backup);
fake_new_wind_image(&cpu_image_result, width_height_backup, width_height_backup);
fake_new_wind_image(&gpu_image, width_height_backup, width_height_backup);
unsigned long tmp_ind, tmp_width_height, pixel_count;
char *fileBDbin = (char*)malloc(sizeof(char) * 256);
char *fileBDtxt = (char*)malloc(sizeof(char) * 256);
strcpy(fileBDbin, argv[1]);
strcpy(fileBDtxt, argv[1]);
strcat(fileBDbin, ".bin");
strcat(fileBDtxt, ".txt");
FILE *f_bin = 0, *f_txt = 0;
if((f_bin = fopen(fileBDbin, "wb")) == 0)
{
fprintf(stderr, "error open file %s", fileBDbin);
perror(": ");
return -1;
}
if((f_txt = fopen(fileBDtxt, "wb")) == 0)
{
fprintf(stderr, "error open file %s", fileBDtxt);
perror(":");
return -1;
}
tmp_width_height = step;
unsigned long first_step = step;
while(tmp_width_height <= width_height_backup)
{
cpu_image->height = gpu_image->height = cpu_image->width = gpu_image->width = tmp_width_height;
pixel_count = (cpu_image->height * cpu_image->width);
multiplier = calculate_multiplier(argv[1]);
if(tmp_width_height > 10*step)
step += (tmp_width_height - step)/5;
printf("%ldx%ld %ld pixels %f\\n", cpu_image->height, cpu_image->width, pixel_count, multiplier);
fprintf(f_txt, "%ldx%ld %ld pixels ", cpu_image->height,
cpu_image->width, pixel_count);
fprintf(f_txt, "%f\\n", multiplier);
fwrite(&(cpu_image->height) , sizeof(unsigned long), 1, f_bin);
fwrite(&multiplier , sizeof(double), 1, f_bin);
tmp_width_height += step;
}
fseek(f_txt, -1, 1);
ftruncate(fileno(f_txt), ftell(f_txt));
fclose(f_txt);
fclose(f_bin);
cpu_image->height = cpu_image_result->height = cpu_image_result->width =
gpu_image->height = cpu_image->width = gpu_image->width = width_height_backup;
free_image(&cpu_image);
free_image(&gpu_image);
free_image(&cpu_image_result);
return 0;
}
| 1
|
#include <pthread.h>
void *Allen(void *arg);
void *Bob(void *arg);
pthread_mutex_t book1;
pthread_mutex_t book2;
pthread_cond_t Allenfinish;
int main() {
pthread_t tid1, tid2;
pthread_create(&tid1, 0, &Allen, 0);
pthread_create(&tid2, 0, &Bob, 0);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
return 0;
}
void *Allen(void *arg) {
pthread_mutex_lock(&book1);
sleep(5);
pthread_mutex_lock(&book2);
printf("Allen has collected all books he need, he is going to do homework!\\n");
sleep(5);
printf("Allen has finished his homework, he has returned all books he borrowed!\\n");
pthread_mutex_unlock(&book2);
pthread_mutex_unlock(&book1);
pthread_cond_signal(&Allenfinish);
}
void *Bob(void *arg) {
pthread_mutex_lock(&book2);
pthread_cond_wait(&Allenfinish, &book2);
printf("Bob knows he can borrow those two books now!\\n");
pthread_mutex_lock(&book1);
sleep(5);
printf("Bob has finished his homework now!\\n");
pthread_mutex_unlock(&book1);
pthread_mutex_unlock(&book2);
}
| 0
|
#include <pthread.h>
static FILE *fp = 0;
static char linestr[AU_LINE_MAX];
static char *delim = ":";
static char inacdir = 0;
static char ptrmoved = 0;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static int getstrfromtype(char *name, char **str)
{
char *type, *nl;
char *tokptr;
char *last;
*str = 0;
pthread_mutex_lock(&mutex);
if((fp == 0)
&& ((fp = fopen(AUDIT_CONTROL_FILE, "r")) == 0)) {
pthread_mutex_unlock(&mutex);
return 0;
}
while(fgets(linestr, AU_LINE_MAX, fp) != 0) {
if((nl = strrchr(linestr, '\\n')) != 0) {
*nl = '\\0';
}
tokptr = linestr;
if((type = strtok_r(tokptr, delim, &last)) != 0) {
if(!strcmp(name, type)) {
*str = strtok_r(0, delim, &last);
pthread_mutex_unlock(&mutex);
if(*str == 0) {
return 1;
}
return 0;
}
}
}
pthread_mutex_unlock(&mutex);
return 0;
}
void setac()
{
pthread_mutex_lock(&mutex);
ptrmoved = 1;
if(fp != 0) {
fseek(fp, 0, 0);
}
pthread_mutex_unlock(&mutex);
}
void endac()
{
pthread_mutex_lock(&mutex);
ptrmoved = 1;
if(fp != 0) {
fclose(fp);
fp = 0;
}
pthread_mutex_unlock(&mutex);
}
int getacdir(char *name, int len)
{
char *dir;
int ret = 0;
if(name == 0) {
errno = EINVAL;
return -2;
}
pthread_mutex_lock(&mutex);
if(inacdir && ptrmoved) {
ptrmoved = 0;
if(fp != 0) {
fseek(fp, 0, 0);
}
ret = 2;
}
pthread_mutex_unlock(&mutex);
if(getstrfromtype(DIR_CONTROL_ENTRY, &dir) == 1) {
return -3;
}
if(dir == 0){
return -1;
}
if(strlen(dir) >= len) {
return -3;
}
strcpy(name, dir);
return ret;
}
int getacmin(int *min_val)
{
char *min;
setac();
if(min_val == 0) {
errno = EINVAL;
return -2;
}
if(getstrfromtype(MINFREE_CONTROL_ENTRY, &min) == 1) {
return -3;
}
if(min == 0) {
return 1;
}
*min_val = atoi(min);
return 0;
}
int getacflg(char *auditstr, int len)
{
char *str;
setac();
if(auditstr == 0) {
errno = EINVAL;
return -2;
}
if(getstrfromtype(FLAGS_CONTROL_ENTRY, &str) == 1) {
return -3;
}
if(str == 0) {
return 1;
}
if(strlen(str) >= len) {
return -3;
}
strcpy(auditstr, str);
return 0;
}
int getacna(char *auditstr, int len)
{
char *str;
setac();
if(auditstr == 0) {
errno = EINVAL;
return -2;
}
if(getstrfromtype(NA_CONTROL_ENTRY, &str) == 1) {
return -3;
}
if(str == 0) {
return 1;
}
if(strlen(str) >= len) {
return -3;
}
strcpy(auditstr, str);
return 0;
}
| 1
|
#include <pthread.h>
{
int data;
struct link* next;
}Node;
pthread_mutex_t mutex;
pthread_cond_t cond;
Node *head = 0;
void *producer(void *arg)
{
while(1)
{
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = rand()%99;
newNode->next = head;
pthread_mutex_lock(&mutex);
head = newNode;
printf("%lu ======produce %d\\n",pthread_self(),newNode->data);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
sleep(rand()%3);
}
return 0;
}
void *customer(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
if(head == 0)
{
pthread_cond_wait(&cond,&mutex);
}
Node *ph = head;
head=head->next;
printf("%lu ========concume %d\\n",pthread_self(),ph->data);
free(ph);
pthread_mutex_unlock(&mutex);
}
return 0;
}
int main()
{
pthread_t cre,consumer;
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond,0);
pthread_create(&cre,0,producer,0);
pthread_create(&consumer,0,customer,0);
pthread_join(cre,0);
pthread_join(consumer,0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
| 0
|
#include <pthread.h>
void producer(void);
void consumer(void);
int produce_item(void);
void insert_item(int);
int remove_item(void);
void consume_item(int);
int count = 0;
int items_array[100];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int produce_item() {
return rand();
}
void insert_item(int item) {
items_array[count++] = item;
}
int remove_item() {
return items_array[--count];
}
void consume_item(int item) {
printf("Consumed: %d\\n",item);
}
void producer() {
int item;
while (1) {
item = produce_item();
pthread_mutex_lock(&mutex);
while(count >= 100) {
pthread_cond_wait(&cond,&mutex);
}
insert_item(item);
printf("Produced: %d\\n",item);
if (count == 1) pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
}
void consumer() {
int item;
while (1) {
pthread_mutex_lock(&mutex);
while (count == 0) {
pthread_cond_wait(&cond,&mutex);
}
item = remove_item();
consume_item(item);
if (count == 100 -1) pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
}
int main() {
int i[2];
pthread_t thread_a, thread_b;
i[0] = 1;
i[1] = 2;
pthread_create(&thread_a,0,(void*)&producer,&i[0]);
pthread_create(&thread_b,0,(void*)&consumer,&i[1]);
pthread_join(thread_a,0);
pthread_join(thread_b,0);
return 0;
}
| 1
|
#include <pthread.h>
int
gai_cancel (struct gaicb *gaicbp)
{
int result = 0;
int status;
pthread_mutex_lock (&__gai_requests_mutex);
status = __gai_remove_request (gaicbp);
if (status == 0)
result = EAI_CANCELED;
else if (status > 0)
result = EAI_NOTCANCELED;
else
result = EAI_ALLDONE;
pthread_mutex_unlock (&__gai_requests_mutex);
return result;
}
| 0
|
#include <pthread.h>
pthread_mutex_t atom_add_mutex;
long long atom_add(long long * addr, long long value){
pthread_mutex_lock(&atom_add_mutex);
long long ret = *addr;
*addr += value;
pthread_mutex_unlock(&atom_add_mutex);
return ret;
}
unsigned long long atomicAdd(unsigned long long * addr, long long value){
pthread_mutex_lock(&atom_add_mutex);
long long ret = *addr;
*addr += value;
pthread_mutex_unlock(&atom_add_mutex);
return ret;
}
int atomicCAS(int * addr, int compare, int set){
pthread_mutex_lock(&atom_add_mutex);
int ret = *addr;
if(ret == compare)
*addr = set;
pthread_mutex_unlock(&atom_add_mutex);
return ret;
}
int atomicExch(int * addr, int value){
pthread_mutex_lock(&atom_add_mutex);
int ret = *addr;
*addr = value;
pthread_mutex_unlock(&atom_add_mutex);
return ret;
}
int getThreadId();
void __threadfence(){ }
long long m_Local[2];
int * m_Cache;
| 1
|
#include <pthread.h>
void *philosopher (void *id);
int food_on_table (), numRefeicoes = 0;
pthread_mutex_t chopstick[5], mut;
pthread_mutex_t food_lock;
pthread_t philo[5];
int main (int argn, char **argv)
{
long i;
pthread_mutex_init (&mut, 0);
pthread_mutex_init (&food_lock, 0);
for (i = 0; i < 5; i++)
pthread_mutex_init (&chopstick[i], 0);
for (i = 0; i < 5; i++)
pthread_create (&philo[i], 0, philosopher, (void *)i);
while(1){
sleep (1) ;
pthread_mutex_lock (&mut) ;
printf ("Refeições por segundo: %d\\n", numRefeicoes) ;
numRefeicoes = 0 ;
pthread_mutex_unlock (&mut) ;
}
return 0;
}
void * philosopher (void *num){
long id;
int i, left_chopstick, right_chopstick, menor, maior;
id = (long)num;
left_chopstick = id;
right_chopstick = (id + 1)%5;
if (left_chopstick < right_chopstick){
menor = left_chopstick;
maior = right_chopstick;
}else{
menor = right_chopstick;
maior = left_chopstick;
}
while (1) {
int pause = rand() % 3;
pthread_mutex_lock (&chopstick[menor]);
pthread_mutex_lock (&chopstick[maior]);
numRefeicoes++;
pthread_mutex_unlock (&chopstick[left_chopstick]);
pthread_mutex_unlock (&chopstick[right_chopstick]);
}
return (0);
}
| 0
|
#include <pthread.h>
int ReadWord(FILE*, char*, int);
char *original_filename;
char *new_filename;
char line_buffer[2][50][255];
char filename[2][255];
int buffer_size[2];
bool buffer_full[2];
bool end_of_file[2];
int line_count;
pthread_cond_t buffers_empty;
pthread_mutex_t buffers_empty_lock;
pthread_cond_t buffers_full;
pthread_mutex_t buffers_full_lock;
int numWorkers = 2;
int numArrived = 0;
void *ReadWorker(void *arg) {
int id = (int) arg;
char mode = 'r';
char c;
FILE *file = fopen(filename[id], &mode);
int i = 0;
int char_count = 0;
int end_of_buffer = 49;
int next_word = 0;
char current_word[255];
int count = 0;
while(next_word != -1){
next_word = ReadWord(file, current_word, next_word);
strcpy(line_buffer[id][i], current_word);
i++;
if(i == end_of_buffer) {
buffer_full[id] = 1;
}
if(next_word == -1) {
int size_of_word = sizeof(current_word);
line_buffer[id][i][size_of_word - 1] = '\\0';
end_of_file[id] = 1;
buffer_full[id] = 1;
}
if(buffer_full[id]) {
i = 0;
pthread_mutex_lock(&buffers_full_lock);
if(buffer_full[0] && buffer_full[1]) {
pthread_mutex_unlock(&buffers_full_lock);
pthread_cond_broadcast(&buffers_full);
printf("%d wating\\n", id);
pthread_cond_wait(&buffers_empty, &buffers_empty_lock);
pthread_mutex_unlock(&buffers_empty_lock);
} else {
pthread_mutex_unlock(&buffers_full_lock);
printf("%d wating\\n", id);
pthread_cond_wait(&buffers_empty, &buffers_empty_lock);
pthread_mutex_unlock(&buffers_empty_lock);
}
}
}
if(end_of_file[0] && end_of_file[1]) {
buffer_full[0] = 1;
buffer_full[1] = 1;
pthread_cond_broadcast(&buffers_full);
}
pthread_exit(0);
}
int ReadWord(FILE *fp, char *result, int bytePos ) {
char read_char;
int next_offset;
fseek(fp, bytePos, 0);
fread((void*) &read_char, 1, 1, fp);
next_offset = bytePos;
while((read_char != '\\n') && !feof( fp )) {
*result++ = read_char;
next_offset++;
fread((void*) &read_char, 1, 1, fp);
}
fseek(fp,bytePos,next_offset++);
if(feof(fp)) {
printf("END OF FILE\\n");
}
*result = '\\0';
return (feof(fp) ? -1 : next_offset++);
}
void *CompareLine() {
int i = 0;
line_count = 0;
bool done = 0;
while(!done) {
pthread_cond_wait(&buffers_full,&buffers_full_lock);
printf("Consumer - STARTS CONSUMING!\\n");
int i = 0;
int j = 0;
char line_original[255];
char line_new[255];
for(i = 0; i < 49; i++) {
line_count++;
for(j = 0; j < 255; j++) {
line_original[j] = line_buffer[0][i][j];
line_new[j] = line_buffer[1][i][j];
line_buffer[0][i][j] = '\\0';
line_buffer[1][i][j] = '\\0';
}
if((line_original[0] == '\\0') && (line_new[0] == '\\0')) {
break;
}
if(strcmp(line_original, line_new) != 0) {
if(line_original[0] != '\\0') {
printf("------ %s ------\\n", filename[0]);
printf("%d: ", line_count);
printf(line_original, "%s");
printf("\\n");
}
if(line_new[0] != '\\0') {
printf("------ %s ------\\n", filename[1]);
printf("%d: ", line_count);
printf(line_new, "%s");
printf("\\n");
}
} else {
}
line_original[0] = '\\0';
line_new[0] = '\\0';
}
printf("Consumer - BOTH BUFFERS READ - STOPING CONSUMING\\n");
line_buffer[0][0][0] = '\\0';
line_buffer[1][0][0] = '\\0';
line_buffer[0][0][1] = '\\0';
line_buffer[0][0][1] = '\\0';
if(!end_of_file[0]) {
buffer_full[0] = 0;
}
if(!end_of_file[1]) {
buffer_full[1] = 0;
}
pthread_cond_broadcast(&buffers_empty);
if(end_of_file[0] && end_of_file[1]) {
break;
}
}
printf("CONSUMER - EXITS\\n");
pthread_exit(0);
}
int main(int argc, char *argv[]) {
strcpy(filename[0],argv[1]);
strcpy(filename[1],argv[2]);
char mode = 'r';
char c2;
char new_string[255];
int i;
int count_new;
int line_number = 1;
char line_string;
end_of_file[0] = 0;
end_of_file[1] = 0;
int code_one;
int code_two;
int code_three;
pthread_t threads[3];
pthread_mutex_init(&buffers_full_lock, 0);
pthread_mutex_init(&buffers_empty_lock, 0);
pthread_cond_init(&buffers_empty, 0);
pthread_cond_init(&buffers_full, 0);
long id = 0;
code_one = pthread_create(&threads[0], 0, ReadWorker, (void*) id);
if (code_one) {
printf("Error; return code from pthread_create() is %d\\n", code_one);
exit(-1);
}
id = 1;
code_two = pthread_create(&threads[1], 0, ReadWorker, (void*) id);
if (code_two) {
printf("Error; return code from pthread_create() is %d\\n", code_two);
exit(-1);
}
code_three = pthread_create(&threads[2], 0, CompareLine, 0);
if (code_three) {
printf("Error; return code from pthread_create() is %d\\n", code_three);
exit(-1);
}
pthread_join(threads[0], 0);
pthread_join(threads[1], 0);
pthread_join(threads[2], 0);
printf("Success!\\n");
}
| 1
|
#include <pthread.h>
void
ubik_deque_init(struct ubik_deque *d)
{
pthread_mutex_init(&d->lock, 0);
d->left = 0;
d->right = 0;
}
void
ubik_deque_pushl(struct ubik_deque *d, void *e)
{
struct ubik_deque_elem *elem;
ubik_galloc((void**) &elem, 1, sizeof(struct ubik_deque_elem));
pthread_mutex_lock(&d->lock);
elem->e = e;
elem->left = 0;
elem->right = d->left;
if (elem->right != 0)
elem->right->left = elem;
d->left = elem;
if (d->right == 0)
d->right = elem;
pthread_mutex_unlock(&d->lock);
}
void
ubik_deque_pushr(struct ubik_deque *d, void *e)
{
struct ubik_deque_elem *elem;
ubik_galloc((void**) &elem, 1, sizeof(struct ubik_deque_elem));
pthread_mutex_lock(&d->lock);
elem->e = e;
elem->left = d->right;
elem->right = 0;
if (elem->left != 0)
elem->left->right = elem;
d->right = elem;
if (d->left == 0)
d->left = elem;
pthread_mutex_unlock(&d->lock);
}
void *
ubik_deque_popl(struct ubik_deque *d)
{
struct ubik_deque_elem *e;
void *v;
pthread_mutex_lock(&d->lock);
if (d->left == 0)
{
pthread_mutex_unlock(&d->lock);
return 0;
}
e = d->left;
d->left = e->right;
if (e->right != 0)
e->right->left = 0;
else
d->right = 0;
pthread_mutex_unlock(&d->lock);
v = e->e;
free(e);
return v;
}
void *
ubik_deque_popr(struct ubik_deque *d)
{
struct ubik_deque_elem *e;
void *v;
pthread_mutex_lock(&d->lock);
if (d->left == 0)
{
pthread_mutex_unlock(&d->lock);
return 0;
}
e = d->right;
d->right = e->left;
if (e->left != 0)
e->left->right = 0;
else
d->left = 0;
pthread_mutex_unlock(&d->lock);
v = e->e;
free(e);
return v;
}
bool
ubik_deque_empty(struct ubik_deque *d)
{
struct ubik_deque_elem *l;
pthread_mutex_lock(&d->lock);
l = d->left;
pthread_mutex_unlock(&d->lock);
return l == 0;
}
| 0
|
#include <pthread.h>
int thread_num;
pthread_mutex_t mutex;
long long int number_of_tosses,batch;
long long int number_in_circle=0;
time_t start,end;
double times;
void* toss()
{
long long int sample_num=0;
long long int i=0;
srand(time(0));
unsigned seed=rand();
for(;i<batch;i++)
{
double x,y,dis,times;
x=((double)rand_r(&seed)/(double)32767);
y=((double)rand_r(&seed)/(double)32767);
x=x*2-1;
y=y*2-1;
dis=x*x+y*y;
if(dis<=1)
{
sample_num++;
}
}
pthread_mutex_lock(&mutex);
number_in_circle+=sample_num;
pthread_mutex_unlock(&mutex);
return 0;
}
int main(int argc,char* argv[])
{
long thread;
double pi;
thread_num=get_nprocs();
number_of_tosses=strtoll(argv[1],0,10);
batch=number_of_tosses/thread_num;
pthread_t* handler;
handler=malloc(thread_num*sizeof(pthread_t));
pthread_mutex_init(&mutex,0);
for(thread=0;thread<thread_num;thread++)
pthread_create(&handler[thread],0,toss,0);
for(thread=0;thread<thread_num;thread++)
pthread_join(handler[thread],0);
pi=4*number_in_circle/(double)number_of_tosses;
pthread_mutex_destroy(&mutex);
free(handler);
printf("pi:%f\\n",pi);
return 0;
}
| 1
|
#include <pthread.h>
int g_Count = 0;
int nNum, nLoop;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t my_condition=PTHREAD_COND_INITIALIZER;
void *consume(void* arg) {
int inum = 0;
inum = (int)arg;
while (1) {
pthread_mutex_lock(&mutex);
printf("consum:%d\\n", inum);
while (g_Count == 0)
{
printf("consum:%d 开始等待\\n", inum);
pthread_cond_wait(&my_condition, &mutex);
printf("consum:%d 醒来\\n", inum);
}
printf("consum:%d 消费产品begin\\n", inum);
g_Count--;
printf("consum:%d 消费产品end\\n", inum);
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_exit(0);
}
void *produce(void* arg) {
int inum = 0;
inum = (int)arg;
while (1) {
pthread_mutex_lock(&mutex);
printf("产品数量:%d\\n", g_Count);
printf("produce:%d 生产产品begin\\n", inum);
g_Count++;
printf("produce:%d 生产产品end\\n", inum);
printf("produce:%d 发条件signal begin\\n", inum);
pthread_cond_signal(&my_condition);
printf("produce:%d 发条件signal end\\n", inum);
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_exit(0);
}
int main() {
int i =0;
pthread_t tidArray[2 +4 +10];
for (i=0; i<2; i++) {
pthread_create(&tidArray[i], 0, consume, (void *)i);
}
sleep(1);
for (i=0; i<4; i++) {
pthread_create(&tidArray[i+2], 0, produce, (void*)i);
}
for (i=0; i<2 +4; i++) {
pthread_join(tidArray[i], 0);
}
printf("进程也要结束1233\\n");
return 0;
}
| 0
|
#include <pthread.h>
int bufer [10];
pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER;
void * productor();
void * consumidor();
int main (){
srand(time(0));
pthread_t h1,h2;
pthread_mutex_lock(&m2);
pthread_create(&h1,0,&productor,0);
pthread_create(&h2,0,&consumidor,0);
pthread_join(h1,0);
pthread_join(h2,0);
printf("BUFFER :\\n");
int i;
for(i = 0; i<10; i++){
printf("%d",bufer[i]);
}
printf("\\n");
}
void * productor(){
int i;
for(i = 0; i<10; i++){
int valor = rand()% 9 + 1;
pthread_mutex_lock(&m1);
bufer[i] = valor;
pthread_mutex_unlock(&m2);
}
}
void * consumidor(){
int dato;
int i;
for(i = 0; i<10; i++){
pthread_mutex_lock(&m2);
dato = bufer[i];
printf("dato leido: %d\\n",dato);
pthread_mutex_unlock(&m1);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t up = PTHREAD_COND_INITIALIZER, down = PTHREAD_COND_INITIALIZER;
int max = 3;
int count = 0;
int going_up = 1;
void *sleeper(void *v) {
int i = 0;
pthread_mutex_lock(&mutex);
while(1) {
fprintf(stderr, "%x: alive\\n", (unsigned)pthread_self());
count++;
if (count >= max) {
going_up = 0;
pthread_cond_broadcast(&up);
} else
while(going_up)
pthread_cond_wait(&up,&mutex);
count--;
if (count <= 0) {
going_up = 1;
pthread_cond_broadcast(&down);
} else
while(!going_up)
pthread_cond_wait(&down,&mutex);
i++;
if (i > 3) {
fprintf(stderr, "%x: alive\\n", (unsigned)pthread_self());
i = 0;
}
}
pthread_mutex_unlock(&mutex);
}
int main(int argc, char **argv) {
int i, err;
pthread_t p;
pthread_attr_t a;
int scope = PTHREAD_SCOPE_SYSTEM;
if (argc > 1) {
switch(atoi(argv[1])) {
case 0:
scope = PTHREAD_SCOPE_PROCESS;
break;
case 1:
scope = PTHREAD_SCOPE_SYSTEM;
break;
case 2:
scope = PTHREAD_SCOPE_SYSTEM;
break;
}
}
for(i = 0; i < max; i++) {
pthread_attr_init(&a);
if (err = pthread_attr_setscope(&a,scope)) {
fprintf(stderr, "pthread_attr_setscope: %s\\n", strerror(err));
exit(1);
}
pthread_create(&p,&a,sleeper,0);
}
pthread_join(p,0);
}
| 0
|
#include <pthread.h>
int count = 0;
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *inc_count(void *t)
{
int i;
long my_id = (long)t;
for (i=0; i < 10; i++) {
pthread_mutex_lock(&count_mutex);
count++;
if (count == 12) {
printf("inc_count(): thread %ld, count = %d Threshold reached. ",
my_id, count);
pthread_cond_signal(&count_threshold_cv);
printf("Just sent signal.\\n");
}
printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n",
my_id, count);
pthread_mutex_unlock(&count_mutex);
sleep(1);
}
pthread_exit(0);
}
void *watch_count(void *t)
{
long my_id = (long)t;
printf("Starting watch_count(): thread %ld\\n", my_id);
pthread_mutex_lock(&count_mutex);
while (count < 12) {
printf("watch_count(): thread %ld Count= %d. Going into wait...\\n", my_id,count);
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %ld Condition signal received. Count= %d\\n", my_id,count);
printf("watch_count(): thread %ld Updating the value of count...\\n", my_id,count);
count += 125;
printf("watch_count(): thread %ld count now = %d.\\n", my_id, count);
}
printf("watch_count(): thread %ld Unlocking mutex.\\n", my_id);
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int i, rc;
long t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, watch_count, (void *)t1);
pthread_create(&threads[1], &attr, inc_count, (void *)t2);
pthread_create(&threads[2], &attr, inc_count, (void *)t3);
for (i = 0; i < 3; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited and joined with %d threads. Final value of count = %d. Done.\\n",
3, count);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit (0);
}
| 1
|
#include <pthread.h>
struct job{
char *filename;
double *jobstorage;
double EpsMin;
int elements;
};
pthread_mutex_t lock;
int datagrabber(FILE *fptr, double *storage);
void* scann(void *);
int main(int argc, char *argv[]){
FILE *inPtr;
FILE *outPtr;
int check,i,G;
int tharg,tharg2;
tharg= atoi(argv[3]);
double *memory;
double EPSmin=0;
tharg2= 2*tharg;
char str1[20]="outfile";
char str2[20];
pthread_t tid[tharg];
int iret1, iret2;
char names[tharg][100];
for(i = 0; i < tharg; ++i )
{
char *string;
string[0] = '\\0';
asprintf(&string, "%d", i);
printf("%s\\n", string);
strcat(string,str1);
strcpy(names[i],string);
printf("%s\\n",names[i]);
}
for (i=0;i<tharg;i++)
{
printf("names[%d]= %s\\n",i,names[i]);
}
memory = calloc(tharg2, sizeof(double));
printf("arg3= %d\\n",tharg);
if(argc!=4)
{
puts("Usage: infile outfile size");
}
else
{
inPtr = fopen(argv[1],"r");
if(!inPtr)
{
perror("File could not be opened for reading:");
exit(1);
}
outPtr = fopen(argv[2],"w+");
if(!outPtr)
{
perror("File could not opened for writing:");
exit(1);
}
}
check = datagrabber(inPtr,memory);
if (check == tharg)
printf("check size match\\n");
else if(check > tharg)
printf("check > tharg\\n");
else if(check < tharg)
{
G= tharg - check;
printf("check < tharg G= %d\\n",G);
}
else
printf("The sky is falling\\n");
printf("check = %d \\n",check);
printf("tharg = %d \\n",tharg);
printf("Enter EPSmin: ");
scanf("%lf",&EPSmin);
struct job *jobptr = malloc(sizeof *jobptr);
for(i=0;i<=tharg;i++)
{
if (jobptr != 0)
{
puts("starting thread");
printf("i= %d threadname= %s\\n",i,names[i]);
jobptr->filename = names[i];
jobptr->jobstorage = (memory+(2*i));
jobptr->EpsMin = EPSmin;
jobptr->elements = 2*(tharg-i);
iret1 = pthread_create( &tid[i], 0, scann, jobptr);
if(iret1)
{
fprintf(stderr, "Error - pthread_create() return code: %d\\n",iret1);
exit(1);
}
}
}
int h;
for(h=0;h<tharg;h++)
{
pthread_join(tid[h], 0);
}
puts("scan complete");
fclose(outPtr);
fclose(inPtr);
free (memory);
free (jobptr);
return 0;
}
int datagrabber(FILE *fptr, double *storage)
{
int i=0,j=0;
double temp=0;
char c;
while( (c=fgetc(fptr)) != EOF){
if(c=='\\n')
{
i++;
j++;
}
else if(c==',')
j++;
else
{
temp = (double)c - '0';
c=fgetc(fptr);
if(c=='\\n')
{
*(storage+j)= temp;
i++;
j++;
}
else if(c==',')
{
*(storage+j)= temp;
j++;
}
else
{
temp = (temp*10) + (double)c - '0';
*(storage+j)= temp;
}
}
}
return i;
}
void* scann(void *jobs)
{
puts("thread going");
struct job *jobptr2 = jobs;
pthread_mutex_lock(&lock);
char *fname=jobptr2->filename;
double *storage2=jobptr2->jobstorage;
double epsmin=jobptr2->EpsMin;
int sizes=jobptr2->elements;
pthread_mutex_unlock(&lock);
printf("File name = %s\\n",fname);
FILE *fiptr = fopen(fname,"w");
if(!fiptr)
{
perror("File could not opened for writing:");
exit(1);
}
double x,y,x2,y2,distance,z, tempy, tempx;
int i;
pthread_mutex_lock(&lock);
x=*storage2;
y=*(storage2+1);
pthread_mutex_unlock(&lock);
for(i=2;i <= (sizes-2);i++)
{
pthread_mutex_lock(&lock);
x2=*(storage2+i);
y2=*(storage2+(i+1));
pthread_mutex_unlock(&lock);
tempy= (y2-y);
tempx= (x2-x);
z= tempy*tempy+tempx*tempx;
printf("%.02f\\n",z);
distance = sqrt(z);
printf("%.02f\\n",distance);
printf("%.02f\\n",epsmin);
printf("i= %d size= %d\\n",i,sizes);
if(distance < epsmin)
{
fprintf(fiptr,"x(%lf),y(%lf) -> x'(%lf),y'(%lf) = %lf\\n",x,y,x2,y2,distance);
printf("x(%.02lf),y(%.02lf) -> x'(%.02lf),y'(%.02lf) = %.03lf\\n",x,y,x2,y2,distance);
}
}
free(storage2);
free(jobs);
free(fname);
fclose(fiptr);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutexid;
pthread_mutex_t mutexres;
int idcount = 0;
pthread_mutex_t joinmutex[3];
int join[3];
int result[3];
int target;
int sequence[(3 * 30)];
void *thread (void *arg)
{
int id, i, from, count, l_target;
pthread_mutex_lock (&mutexid);
l_target = target;
id = idcount;
idcount++;
pthread_mutex_unlock (&mutexid);
__VERIFIER_assert (id >= 0);
__VERIFIER_assert (id <= 3);
from = id * 30;
count = 0;
for (i = 0; i < 30; i++)
{
if (sequence[from + i] == l_target)
{
count++;
}
if (count > 30)
{
count = 30;
}
}
printf ("t: id %d from %d count %d\\n", id, from, count);
pthread_mutex_lock (&mutexres);
result[id] = count;
pthread_mutex_unlock (&mutexres);
pthread_mutex_lock (&joinmutex[id]);
join[id] = 1;
pthread_mutex_unlock (&joinmutex[id]);
return 0;
}
int main ()
{
int i;
pthread_t t[3];
int count;
i = __VERIFIER_nondet_int (0, (3 * 30)-1);
sequence[i] = __VERIFIER_nondet_int (0, 3);
target = __VERIFIER_nondet_int (0, 3);
printf ("m: target %d\\n", target);
pthread_mutex_init (&mutexid, 0);
pthread_mutex_init (&mutexres, 0);
for (i = 0; i < 3; i++)
{
pthread_mutex_init (&joinmutex[i], 0);
result[i] = 0;
join[i] = 0;
}
i = 0;
pthread_create (&t[i], 0, thread, 0); i++;
pthread_create (&t[i], 0, thread, 0); i++;
pthread_create (&t[i], 0, thread, 0); i++;
__VERIFIER_assert (i == 3);
int j;
i = 0;
pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; }
pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; }
pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; }
if (i != 3)
{
return 0;
}
__VERIFIER_assert (i == 3);
count = 0;
for (i = 0; i < 3; i++)
{
count += result[i];
printf ("m: i %d result %d count %d\\n", i, result[i], count);
}
printf ("m: final count %d\\n", count);
__VERIFIER_assert (count >= 0);
__VERIFIER_assert (count <= (3 * 30));
return 0;
}
| 1
|
#include <pthread.h>
pthread_t tid1, tid2;
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
void *pthread1(void *), *arg1;
void *pthread2(void *), *arg2;
int theValue = 50;
int main()
{
int err;
if (pthread_mutex_init(&mutex1, 0) != 0)
{
printf("\\n mutex init failed\\n");
return 1;
}
srand (getpid());
err = pthread_create(&tid1, 0, pthread1, arg1);
if(err)
{
printf ("\\nError in creating the thread 1: ERROR code %d \\n", err);
return 1;
}
err = pthread_create(&tid2, 0, pthread2, arg2);
if (err)
{
printf ("\\nError in creating the thread 2: ERROR code %d \\n", err);
return 1;
}
pthread_join(tid1, 0);
pthread_join(tid2, 0);
pthread_mutex_destroy(&mutex1);
printf ("\\nThe final value of theValue is %d \\n\\n", theValue);
}
void *pthread1(void *param)
{
int x;
printf("\\nthread 1 has started\\n");
pthread_mutex_lock( &mutex1 );
sleep(rand() & 1);
x = theValue;
sleep(rand() & 1);
x++;
sleep(rand() & 1);
theValue = x;
pthread_mutex_unlock( &mutex1 );
printf("\\nthread 1 now terminating\\n");
}
void *pthread2(void *param)
{
int y;
printf("\\nthread 2 has started\\n");
pthread_mutex_lock( &mutex1 );
sleep(rand() & 1);
y = theValue;
sleep(rand() & 1);
y--;
sleep(rand() & 1);
theValue = y;
pthread_mutex_unlock( &mutex1 );
printf("\\nthread 2 now terminating\\n");
}
| 0
|
#include <pthread.h>
extern pthread_mutex_t global_data_mutex;
void update_baro_data (int baro_fd) {
char pressure[6];
float realpressure;
int read_rc;
lseek(baro_fd,0,0);
read_rc = read(baro_fd,pressure,5);
if(0 > read_rc)
{
close(baro_fd);
global_config.baro_fd = -1;
return;
}
realpressure = atof(pressure) * 0.02953;
app_debug(debug, "Baro Press:\\t%2.3f\\n", realpressure);
if ((realpressure > (float)33) || (realpressure < (float)26))
{
app_debug(info, "Got garbage from the pressure sensor. Rejecting\\n");
} else
{
pthread_mutex_lock(&global_data_mutex);
global_data.barometer = realpressure;
global_data.updatetime = time(0);
pthread_mutex_unlock(&global_data_mutex);
}
return;
}
| 1
|
#include <pthread.h>
const int NUMBER_OF_ALLOWED_ARGUMENTS = 3;
int counterTicket;
int counterProcess;
struct {
int threads;
int critical;
} arguments;
struct {
pthread_t *pthreads;
pthread_cond_t *cond;
pthread_mutex_t tickets;
pthread_mutex_t mutex;
} thread;
bool controlArguments(int number, char* arguments[]);
bool controlIfDigitsOnly(char* argument);
void await(int aenter);
void advance();
void waiting();
void threadsCreate();
void threadsJoin();
void* threadsRoutine(void* id);
int getticket(void);
int generateNumber();
int main(int argc, char* argv[]) {
if (!controlArguments(argc, argv)) {
fprintf(stderr, "Bad arguments\\n");
return 1;
}
counterTicket = 0;
counterProcess = 0;
thread.pthreads = (pthread_t*) malloc(sizeof(pthread_t) * arguments.threads);
thread.cond = (pthread_cond_t *) malloc(sizeof(pthread_cond_t) * arguments.critical);
pthread_mutex_init(&thread.tickets, 0);
pthread_mutex_init(&thread.mutex, 0);
for (int i = 0; i < arguments.critical; ++i) {
pthread_cond_init(&thread.cond[i], 0);
}
threadsCreate();
threadsJoin();
return 0;
}
void* threadsRoutine(void* id) {
int ticket, idn = (intptr_t) id;
while ((ticket = getticket()) < arguments.critical) {
if (ticket == -1) {
break;
}
waiting();
await(ticket);
printf("%d\\t(%d)\\n", ticket, idn);
fflush(stdout);
advance();
waiting();
}
return 0;
}
int getticket(void) {
int ticket;
pthread_mutex_lock(&thread.tickets);
if (counterProcess >= arguments.critical) {
pthread_mutex_unlock(&thread.tickets);
return -1;
}
ticket = counterTicket++;
pthread_mutex_unlock(&thread.tickets);
return ticket;
}
void await(int aenter) {
pthread_mutex_lock(&thread.mutex);
while (aenter != counterProcess)
pthread_cond_wait(&thread.cond[aenter], &thread.mutex);
}
void advance() {
counterProcess++;
if (counterProcess >= arguments.critical) {
pthread_mutex_unlock(&thread.mutex);
return;
}
pthread_cond_signal(&thread.cond[counterProcess]);
pthread_mutex_unlock(&thread.mutex);
}
int generateNumber() {
unsigned int seed = (unsigned int) time(0);
return (rand_r(&seed) % 500000000 + 1);
}
void waiting() {
struct timespec timespec1 = {
0, generateNumber()
};
struct timespec *timespec2 = ×pec1;
nanosleep(timespec2, 0);
}
void threadsCreate() {
for (int i = 0; i < arguments.threads; i++) {
pthread_create(&thread.pthreads[i], 0, threadsRoutine, (void*) (intptr_t) (i + 1));
}
}
void threadsJoin() {
for (int i = 0; i < arguments.threads; i++) {
pthread_join(thread.pthreads[i], 0);
}
}
bool controlIfDigitsOnly(char* argument) {
for (int i = 0; i < (int) strlen(argument) ; i++) {
if (!isdigit(argument[i]))
return 0;
}
return 1;
}
bool controlArguments(int number, char* params[]) {
if (number != NUMBER_OF_ALLOWED_ARGUMENTS) {
return 0;
}
for (int i = 1; i < NUMBER_OF_ALLOWED_ARGUMENTS; i++) {
if(!controlIfDigitsOnly(params[i])) {
return 0;
}
}
arguments.threads = atoi(params[1]);
arguments.critical = atoi(params[2]);
return 1;
}
| 0
|
#include <pthread.h>
int a = 0;
const int cycle_duration = 1000000;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* my_thread(void* dummy) {
pthread_mutex_lock(&mutex);
for(int i = 0; i < cycle_duration; i++)
a += 1;
pthread_mutex_unlock(&mutex);
return 0;
}
int main()
{
pthread_t thread_id1, thread_id2, my_thread_id;
sem_t *sem = 0;
int result = pthread_create(&thread_id1 ,
(pthread_attr_t *)0 ,
my_thread ,
0);
if (result) {
printf("Can`t create thread, returned value = %d\\n" , result);
exit(-1);
}
result = pthread_create(&thread_id2 ,
(pthread_attr_t *)0 ,
my_thread ,
0);
if (result) {
printf("Can`t create thread, returned value = %d\\n" , result);
exit(-1);
}
my_thread_id = pthread_self();
pthread_join(thread_id1 , (void **) 0);
pthread_join(thread_id2 , (void **) 0);
printf("a is %d\\n", a);
return 0;
}
| 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;
int currvalue = sip->value;
pthread_mutex_unlock(&(sip->lock));
printf("Current value was %i.\\n", currvalue);
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* buffer;
int nb_iter;
} test1_data;
pthread_mutex_t mutex;
void* test1(void* data)
{
test1_data* d = (test1_data*) data;
int i;
pthread_mutex_lock(&mutex);
for (i=0; i < d->nb_iter; i++)
{
(*d->buffer) += 1;
}
pthread_mutex_unlock(&mutex);
return 0;
}
int main()
{
int status, i, buffer;
pthread_t t[4];
test1_data d[4];
if (pthread_mutex_init(&mutex, 0) < 0)
{
perror("pthread_mutex_init");
exit(-10);
}
buffer = 0;
for (i=0; i<4; i++)
{
d[i].buffer = &buffer;
d[i].nb_iter = 1000000;
status = pthread_create(t+i, 0, test1, &d[i]);
if (status != 0) { perror("pthread_create"); exit(-1); }
}
for (i=0; i<4; i++)
{
status = pthread_join(t[i], 0);
if (status != 0) { perror("pthread_join"); exit(-2); }
}
printf("%d/%d\\n", buffer, 4*1000000);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t * disponible;
int tabacos,papeles,fosforos;
pthread_mutex_t tabaco,papel,fosforo;
void administra(){
int hayIngredientes;
while(1){
hayIngredientes=0;
if(pthread_mutex_trylock(disponible)==0){
printf("El agente toma tabaco y lo pone sobre la mesa\\n");
pthread_mutex_lock(&tabaco);
tabacos++;
pthread_mutex_unlock(&tabaco);
hayIngredientes = 1;
pthread_mutex_unlock(disponible);
}else{
printf("No se pudo tomar tabaco porque estan fumando/descansando\\n");
}
if(pthread_mutex_trylock((disponible+1))==0){
printf("El agente toma papel y lo pone sobre la mesa\\n");
pthread_mutex_lock(&papel);
papeles++;
pthread_mutex_unlock(&papel);
hayIngredientes = 1;
pthread_mutex_unlock((disponible+1));
}else{
printf("No se pudo tomar papel porque estan fumando/descansando\\n");
}
if(pthread_mutex_trylock((disponible+2))==0){
printf("El agente toma fosforo y lo pone sobre la mesa\\n");
pthread_mutex_lock(&fosforo);
fosforos++;
pthread_mutex_unlock(&fosforo);
hayIngredientes = 1;
pthread_mutex_unlock((disponible+2));
}else{
printf("No se pudo tomar fosforo porque estan fumando/descansando\\n");
}
if(hayIngredientes==0){
printf("Como no habian ingredientes el agente se va a hacer otras actividades\\n");
sleep(10);
}
sleep(15);
}
}
void fuma(void * p){
int id = (int)p;
int tieneTabaco=0,tienePapel=0,tieneFosforo=0;
while(1){
if(tieneTabaco==0){
pthread_mutex_lock(&tabaco);
if(tabacos>0){
tieneTabaco++;
printf("Fumador %d toma tabaco\\n",id);
tabacos--;
}
pthread_mutex_unlock(&tabaco);
}
if(tienePapel==0){
pthread_mutex_lock(&papel);
if(papeles>0){
tienePapel++;
printf("Fumador %d toma papel\\n",id);
papeles--;
}
pthread_mutex_unlock(&papel);
}
if(tieneFosforo==0){
pthread_mutex_lock(&fosforo);
if(fosforos>0){
tieneFosforo++;
printf("Fumador %d toma fosforo\\n",id);
fosforos--;
}
pthread_mutex_unlock(&fosforo);
}
if(tieneFosforo>0&&tienePapel>0&&tieneTabaco>0){
pthread_mutex_lock((disponible+id));
printf("Fumador %d esta fumando\\n",id);
sleep(10);
printf("Fumador %d ecabo de fumar... esta descansando\\n",id);
sleep(20);
printf("Fumador %d listo para seguir fumando\\n",id);
tieneFosforo=0;tienePapel=0;tieneTabaco=0;
pthread_mutex_unlock((disponible+id));
}
}
}
int main(){
pthread_t agente;
pthread_t * fumador;
pthread_t * aux;
fumador = (pthread_t*)malloc(3*sizeof(pthread_t));
disponible = (pthread_mutex_t*)malloc(3*sizeof(pthread_mutex_t));
pthread_create(&agente,0,administra,0);
for(aux=fumador;aux<(fumador+3);aux++)
pthread_create(aux,0,fuma,(void*)(aux-fumador));
for(aux=fumador;aux<(fumador+3);aux++)
pthread_join(*aux,0);
pthread_join(agente,0);
free(fumador);
free(disponible);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutexid;
pthread_mutex_t mutexres;
int idcount = 0;
pthread_mutex_t joinmutex[3];
int join[3];
int result[3];
int target;
int sequence[(3 * 30)];
void *thread (void *arg)
{
int id, i, from, count, l_target;
pthread_mutex_lock (&mutexid);
l_target = target;
id = idcount;
idcount++;
pthread_mutex_unlock (&mutexid);
__VERIFIER_assert (id >= 0);
__VERIFIER_assert (id <= 3);
from = id * 30;
count = 0;
for (i = 0; i < 30; i++)
{
if (sequence[from + i] == l_target)
{
count++;
}
if (count > 30)
{
count = 30;
}
}
printf ("t: id %d from %d count %d\\n", id, from, count);
pthread_mutex_lock (&mutexres);
result[id] = count;
pthread_mutex_unlock (&mutexres);
pthread_mutex_lock (&joinmutex[id]);
join[id] = 1;
pthread_mutex_unlock (&joinmutex[id]);
return 0;
}
int main ()
{
int i;
pthread_t t[3];
int count;
i = __VERIFIER_nondet_int (0, (3 * 30)-1);
sequence[i] = __VERIFIER_nondet_int (0, 3);
target = __VERIFIER_nondet_int (0, 3);
printf ("m: target %d\\n", target);
pthread_mutex_init (&mutexid, 0);
pthread_mutex_init (&mutexres, 0);
for (i = 0; i < 3; i++)
{
pthread_mutex_init (&joinmutex[i], 0);
result[i] = 0;
join[i] = 0;
}
i = 0;
pthread_create (&t[i], 0, thread, 0); i++;
pthread_create (&t[i], 0, thread, 0); i++;
pthread_create (&t[i], 0, thread, 0); i++;
__VERIFIER_assert (i == 3);
int j;
i = 0;
pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; }
pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; }
pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; }
if (i != 3)
{
return 0;
}
__VERIFIER_assert (i == 3);
count = 0;
for (i = 0; i < 3; i++)
{
count += result[i];
printf ("m: i %d result %d count %d\\n", i, result[i], count);
}
printf ("m: final count %d\\n", count);
__VERIFIER_assert (count >= 0);
__VERIFIER_assert (count <= (3 * 30));
return 0;
}
| 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;
pthread_mutex_t mutex_solders;
pthread_mutex_t mutex_command_centers;
pthread_mutex_t mutex_command_centers_minerals[12];
void* worker (void) {
pthread_mutex_lock(&mutex_workers);
n++;
pthread_mutex_unlock(&mutex_workers);
int worker_minerals = 0;
int i;
if (n > 5) {
printf("SCV good to go, sir.\\n");
}
while (m < 20) {
printf("SVC %d is mining\\n", n);
pthread_mutex_lock(&mutex_map_minerals);
map_minerals -= 8;
pthread_mutex_unlock(&mutex_map_minerals);
worker_minerals += 8;
printf("SVC %d is transporting minerals\\n", n);
while (worker_minerals > 0) {
if (pthread_mutex_trylock(&mutex_minerals) == 0) {
minerals += worker_minerals;
worker_minerals = 0;
pthread_mutex_unlock(&mutex_minerals);
printf("SVC %d delivered minerals to Command Center 1\\n", n);
} else {
for(i = 0; i <= k;i++) {
if (pthread_mutex_trylock(&mutex_command_centers_minerals[i]) == 0) {
command_centers_minerals[i] += worker_minerals;
worker_minerals = 0;
pthread_mutex_unlock(&mutex_command_centers_minerals[i]);
printf("SVC %d delivered minerals to Command Center %d\\n", n, (i + 2));
break;
}
}
}
}
}
}
void* command_center (void) {
pthread_mutex_lock(&mutex_command_centers);
command_centers_minerals[++k] = 0;
pthread_mutex_unlock(&mutex_command_centers);
if (pthread_mutex_init(&mutex_command_centers_minerals[k], 0) != 0) {
perror("Fail to initialize mutex: command_centers_minerals M\\n");
} else {
printf("Command center %d created.\\n", (k + 2));
}
}
void* solder (void) {
printf("You wanna piece of me, boy?\\n");
pthread_mutex_lock(&mutex_solders);
m++;
pthread_mutex_unlock(&mutex_solders);
}
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;
int over;
pthread_t workers[100];
pthread_t solders[20];
pthread_t centers[12];
if (pthread_mutex_init(&mutex_workers, 0) != 0) {
perror("Fail to initialize mutex: workers!");
}
if (pthread_mutex_init(&mutex_command_centers, 0) != 0) {
perror("Fail to initialize mutex: command_center!");
}
if (pthread_mutex_init(&mutex_solders, 0) != 0) {
perror("Fail to initialize mutex: solders!");
}
if (pthread_mutex_init(&mutex_map_minerals, 0) != 0) {
perror("Fail to initialize mutex: minerals!");
}
while(m < 20) {
command = getchar();
if ((command == 'm') || (command == 's') || (command == 'c')) {
pthread_mutex_lock(&mutex_minerals);
all = return_all_minerals();
if (command == 'm') {
if (all > 50) {
minerals -= 50;
} else {
}
}
if (command == 's') {
if (all > 50) {
minerals -= 50;
} else {
}
}
if (command == 'c') {
if (all > 400) {
minerals -= 400;
} else {
}
}
pthread_mutex_unlock(&mutex_minerals);
}
over = (50 * (20 - m) - 1);
if (map_minerals < over) {
printf("No't enough minerals in order to create 20 solders Game Over!\\n");
break;
}
}
all = return_all_minerals();
printf("Game Won !, You successfuly created 20 solders\\n");
printf("Game started with 5000 minerals on the map, %d minerals left on map and you successfuly collected %d minerals", map_minerals, all);
return 0;
}
| 0
|
#include <pthread.h>
void tslog (int level, const char * id, const char * format, ...)
{
va_list ap;
__builtin_va_start((ap));
time_t time_unix;
struct tm time_parsed;
time(&time_unix);
localtime_r(&time_unix, &time_parsed);
time_parsed.tm_year += 1900;
time_parsed.tm_mon += 1;
char *string1, *string2;
int length1 = vasprintf(&string1, format, ap);
int length2 = asprintf(&string2, "%04d-%02d-%02d %02d:%02d:%02d L%X [%s] %s\\n",
time_parsed.tm_year, time_parsed.tm_mon, time_parsed.tm_mday,
time_parsed.tm_hour, time_parsed.tm_min, time_parsed.tm_sec,
level & 0xf, id, string1);
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&mutex);
write(2, string2, length2);
pthread_mutex_unlock(&mutex);
free(string1);
free(string2);
;
}
| 1
|
#include <pthread.h>
int count = 0;
double finalresult=0.0;
pthread_mutex_t count_mutex;
pthread_cond_t count_condvar;
void *sub1(void *t)
{
int i;
long tid = (long)t;
double myresult=0.0;
pthread_mutex_lock(&count_mutex);
if (count < 12) {
printf("sub1: thread=%ld going into wait. count=%d\\n",tid,count);
pthread_cond_wait(&count_condvar, &count_mutex);
printf("sub1: thread=%ld Condition variable signal received.",tid);
printf(" count=%d\\n",count);
sleep(1);
count++;
finalresult += myresult;
printf("sub1: thread=%ld count now equals=%d myresult=%e. Done.\\n",
tid,count,myresult);
}
else {
printf("sub1: count=%d. Not as expected.",count);
printf(" Probably missed signal. Skipping work and exiting.\\n");
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
void *sub2(void *t)
{
int j,i;
long tid = (long)t;
double myresult=0.0;
for (i=0; i<10; i++) {
for (j=0; j<100000; j++)
myresult += sin(j) * tan(i);
pthread_mutex_lock(&count_mutex);
finalresult += myresult;
count++;
if (count == 12) {
printf("sub2: thread=%ld Threshold reached. count=%d. ",tid,count);
pthread_cond_signal(&count_condvar);
printf("Just sent signal.\\n");
}
else {
printf("sub2: thread=%ld did work. count=%d\\n",tid,count);
}
pthread_mutex_unlock(&count_mutex);
}
printf("sub2: thread=%ld myresult=%e. Done. \\n",tid,myresult);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int i, rc;
long t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_condvar, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, sub1, (void *)t1);
pthread_create(&threads[1], &attr, sub2, (void *)t2);
pthread_create(&threads[2], &attr, sub2, (void *)t3);
for (i = 0; i < 3; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited on %d threads. Final result=%e. Done.\\n",
3,finalresult);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_condvar);
pthread_exit (0);
}
| 0
|
#include <pthread.h>
static pthread_key_t key;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;
extern char **environ;
static void thread_init(void) {
pthread_key_create(&key, free);
}
char *getenv(const char *name) {
int i, len;
char * envbuf;
pthread_once(&init_done, thread_init);
pthread_mutex_lock(&env_mutex);
envbuf = (char *)pthread_getspecific(key);
if(envbuf == 0) {
envbuf = malloc(4096);
if(envbuf == 0) {
pthread_mutex_unlock(&env_mutex);
return 0;
}
pthread_setspecific(key, envbuf);
}
len = strlen(name);
for(i = 0; environ[i] != 0; i++) {
if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) {
strncpy(envbuf, &environ[i][len + 1], 4096 - 1);
pthread_mutex_unlock(&env_mutex);
return envbuf;
}
}
pthread_mutex_unlock(&env_mutex);
return 0;
}
| 1
|
#include <pthread.h>
unsigned int totalDePontos = 0;
unsigned int pontosPorThread;
int totalNoCirculo = 0;
pthread_mutex_t lock;
double randf(double menor,double maior);
void *ocorrencias(void *param);
int main(int argc, char **argv) {
pthread_t tid[2];
double pi;
int i;
int erro;
if (pthread_mutex_init(&lock, 0) != 0) {
fprintf(stderr, "\\nInicializacao do semaforo de exlusao mutua (mutex) falhou\\n");
return 1;
}
printf("================== CALCULO DE PI PELA TECNICA DE MONTE CARLO ==================\\n"
"\\nUNIVERSIDADE CATOLICA DE BRASILIA - UCB"
"\\nDISCIPLINA: Sistemas Operacionais (2/2017)"
"\\nPROFESSOR: José Adalberto Gualeve"
"\\nALUNO: Pedro Augusto Resende"
"\\n--------------------------------------------------------------------------------"
"\\nResumo:\\n"
"\\nA tecnica de Monte Carlo define um circulo de raio 1 no plano cartesiano"
"\\npartindo da origem, gera N pontos aleatorios com x,y pertencente ao intervalo"
"\\n[-1, 1] e faz o calculo de pi multiplicando 4 ao total de pontos que fazem"
"\\nparte da area do circulo e dividindo pelo total de pontos gerados.\\n"
"\\n\\n>> pi = (4 * totalNoCirculo)/totalDePontos <<\\n"
"\\n===============================================================================\\n");
printf("\\nDigite a quantidade de pontos a ser gerados: ");
__fpurge(stdin);
scanf("%d", &totalDePontos);
if (totalDePontos % 2 == 0)
pontosPorThread = totalDePontos/2;
else
pontosPorThread = (totalDePontos + 1)/2;
srand(time(0));
for (i = 0; i < 2; i++) {
erro = pthread_create(&tid[i], 0, ocorrencias, argv[1]);
if (erro != 0) {
fprintf(stderr, "Nao foi possivel criar a thread[%d].\\n", i);
return -1;
}
}
for (i = 0; i < 2; i++){
pthread_join(tid[i], 0);
}
pthread_mutex_destroy(&lock);
pi = ((double) 4 * totalNoCirculo)/(double)totalDePontos;
printf("\\n::: RESULTADOS :::\\n"
"* Pontos gerados: %d\\n"
"* Pontos no circulo: %d\\n"
"* Valor de PI: %f\\n",
totalDePontos, totalNoCirculo, pi);
}
double randf(double menor,double maior){
return (rand()/(double)(32767)) * abs(menor - maior) + menor;
}
void *ocorrencias(void *param) {
unsigned int i;
double x, y;
for (i = 0; i < pontosPorThread; i++) {
x = randf(-1.000001, 1.000001);
y = randf(-1.000001, 1.000001);
if (sqrt((x * x) + (y * y)) < 1) {
pthread_mutex_lock(&lock);
totalNoCirculo++;
pthread_mutex_unlock(&lock);
}
}
pthread_exit(0);
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.