text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
int tableau[4] = {0};
pthread_mutex_t verrou = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condi = PTHREAD_COND_INITIALIZER;
void* T1(){
int i;
for (i=0; i<4; i++){
printf("Début de traitement de la zone %i par T1\\n", i);
sleep(1);
pthread_mutex_lock(&verrou);
tableau[i] = 1;
pthread_mutex_unlock(&verrou);
printf("Zone %d traitée par T1\\n", i);
pthread_cond_broadcast(&condi);
}
pthread_exit(0);
}
void* T2(){
int j;
for (j=0; j<4; j++){
pthread_mutex_lock(&verrou);
while(tableau[j] != 1) {
pthread_cond_wait(&condi, &verrou);
}
pthread_mutex_unlock(&verrou);
printf("Début de traitement de la zone %i par T2\\n", j);
sleep(3);
pthread_mutex_lock(&verrou);
tableau[j] = 2;
pthread_mutex_unlock(&verrou);
printf("Zone %d traitée par T2\\n", j);
}
pthread_exit(0);
}
void main(){
pthread_t id1;
pthread_t id2;
if (pthread_create(&id2, 0, T2, 0) != 0){
perror("Erreur T1");
}
if (pthread_create(&id1, 0, T1, 0) != 0){
perror("Erreur T1");
}
pthread_join(id2, 0);
pthread_join(id1, 0);
}
| 1
|
#include <pthread.h>
int q_main, flag_main;
pthread_mutex_t mtx_main;
pthread_mutex_t cond_main;
int q_roll, flag_roll;
pthread_mutex_t mtx_roll;
pthread_mutex_t cond_roll;
int q_pass, flag_pass;
pthread_mutex_t mtx_pass;
pthread_mutex_t cond_pass;
int wait_pas = 0;
void *passenger();
void *roller_coaster();
int main(int argc, char *argv[]) {
int check, k, i;
int number;
char command[10];
pthread_t p_rc, *p_pass;
k = 0;
q_main=0;
flag_main=0;
pthread_mutex_init(&mtx_main, 0);
pthread_mutex_init(&cond_main, 0);
pthread_mutex_lock(&cond_main);
q_roll=0;
flag_roll=0;
pthread_mutex_init(&mtx_roll, 0);
pthread_mutex_init(&cond_roll, 0);
pthread_mutex_lock(&cond_roll);
flag_pass=0;
pthread_mutex_init(&mtx_pass, 0);
pthread_mutex_init(&cond_pass, 0);
pthread_mutex_lock(&cond_pass);
check = pthread_create(&p_rc, 0, &roller_coaster, 0);
if(check!=0) {
printf("Problem to create roller_coaster thread\\n");
return(7);
}
while(1) {
printf("For new passengers press 'new' and the number of passengers\\n");
printf("Else for exit press 'exit'\\n");
printf("wait_pas: %d\\n",wait_pas);
scanf(" %9s",command);
if(strcmp(command,"new")==0){
scanf("%d",&number);
wait_pas = wait_pas + number;
p_pass = (pthread_t *)malloc(sizeof(pthread_t)*number);
if(p_pass==0){
printf("Problem with memory allocation\\n");
return(2);
}
for(i=0;i<number;i++){
pthread_mutex_lock(&mtx_main);
k++;
check = pthread_create(&p_pass[i], 0, &passenger, &k);
if(check!=0) {
printf("Problem to create %d thread\\n", i);
free(p_pass);
return(7);
}
if(flag_main>0){
flag_main--;
q_main--;
pthread_mutex_unlock(&cond_main);
}
q_main++;
pthread_mutex_unlock(&mtx_main);
pthread_mutex_lock(&cond_main);
if(flag_main>0){
flag_main--;
q_main--;
pthread_mutex_unlock(&cond_main);
}
else{
pthread_mutex_unlock(&mtx_main);
}
}
free(p_pass);
}
else if(strcmp(command,"exit")==0){
printf("Roller coaster has closed for today!\\n");
break;
}
else{
printf("Try again!\\n");
continue;
}
printf("wait_pas: %d\\n",wait_pas);
pthread_mutex_lock(&mtx_roll);
if(q_roll>0) {
flag_roll ++;
}
if(flag_roll>0){
flag_roll--;
q_roll--;
pthread_mutex_unlock(&cond_roll);
}
else{
pthread_mutex_unlock(&mtx_roll);
}
pthread_mutex_lock(&mtx_main);
if(flag_main>0){
flag_main--;
q_main--;
pthread_mutex_unlock(&cond_main);
}
q_main++;
pthread_mutex_unlock(&mtx_main);
pthread_mutex_lock(&cond_main);
if(flag_main>0){
flag_main--;
q_main--;
pthread_mutex_unlock(&cond_main);
}
else{
pthread_mutex_unlock(&mtx_main);
}
}
return (0);
}
void *roller_coaster(){
int i;
int count;
count = 0;
while(1) {
pthread_mutex_lock(&mtx_roll);
if(flag_roll>0){
flag_roll--;
q_roll--;
pthread_mutex_unlock(&cond_roll);
}
q_roll++;
pthread_mutex_unlock(&mtx_roll);
pthread_mutex_lock(&cond_roll);
if(flag_roll>0){
flag_roll--;
q_roll--;
pthread_mutex_unlock(&cond_roll);
}
else{
pthread_mutex_unlock(&mtx_roll);
}
while(wait_pas>=10){
printf("The roller coaster is ready for new ride!\\n");
for(i=0; i<10; i++) {
count++;
pthread_mutex_lock(&mtx_pass);
if(q_pass>0) {
flag_pass ++;
}
if(flag_pass>0){
flag_pass--;
q_pass--;
pthread_mutex_unlock(&cond_pass);
}
else{
pthread_mutex_unlock(&mtx_pass);
}
}
wait_pas = wait_pas - 10;
sleep(1);
printf("The roller coaster begin!\\n");
sleep(2);
printf("Passengers abord the roller_coaster!\\n");
sleep(1);
}
pthread_mutex_lock(&mtx_main);
if(q_main>0) {
flag_main ++;
}
if(flag_main>0){
flag_main--;
q_main--;
pthread_mutex_unlock(&cond_main);
}
else{
pthread_mutex_unlock(&mtx_main);
}
}
return (0);
}
void *passenger(void *num_p){
int k;
pthread_mutex_lock(&mtx_main);
k = *(int *)(num_p);
if(q_main>0) {
flag_main ++;
}
if(flag_main>0){
flag_main--;
q_main--;
pthread_mutex_unlock(&cond_main);
}
else{
pthread_mutex_unlock(&mtx_main);
}
pthread_mutex_lock(&mtx_pass);
if(flag_pass>0){
flag_pass--;
q_pass--;
pthread_mutex_unlock(&cond_pass);
}
q_pass++;
pthread_mutex_unlock(&mtx_pass);
pthread_mutex_lock(&cond_pass);
if(flag_pass>0){
flag_pass--;
q_pass--;
pthread_mutex_unlock(&cond_pass);
}
else{
pthread_mutex_unlock(&mtx_pass);
}
printf("i am passenger %d\\n", k);
return (0);
}
| 0
|
#include <pthread.h>
static int logging = 0;
static int loglevel = LYWARN;
static FILE *LOGFH = 0;
static char logFile[PATH_MAX];
static pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;
int logfile(const char *file, int in_loglevel)
{
if (in_loglevel >= LYDEBUG && in_loglevel <= LYINFO)
printf("logging started\\n");
logging = 0;
if (in_loglevel >= LYDEBUG && in_loglevel <= LYFATAL) {
loglevel = in_loglevel;
}
else {
loglevel = LYDEBUG;
}
if (file == 0) {
LOGFH = 0;
}
else {
if (LOGFH != 0) {
fclose(LOGFH);
}
snprintf(logFile, PATH_MAX, "%s", file);
LOGFH = fopen(file, "a");
if (LOGFH) {
logging = 1;
}
}
return (1 - logging);
}
int logsimple(const char *format, ...)
{
pthread_mutex_lock(&log_mutex);
va_list ap;
int rc;
FILE *file;
rc = 1;
__builtin_va_start((ap));
if (logging) {
file = LOGFH;
}
else {
file = stdout;
}
rc = vfprintf(file, format, ap);
fflush(file);
;
pthread_mutex_unlock(&log_mutex);
return (rc);
}
int logprintf(const char *format, ...)
{
pthread_mutex_lock(&log_mutex);
va_list ap;
int rc;
char buf[27], *eol;
time_t t;
FILE *file;
rc = 1;
__builtin_va_start((ap));
if (logging) {
file = LOGFH;
}
else {
file = stdout;
}
t = time(0);
if (ctime_r(&t, buf)) {
eol = strchr(buf, '\\n');
if (eol) {
*eol = '\\0';
}
fprintf(file, "[%s] ", buf);
}
rc = vfprintf(file, format, ap);
fflush(file);
;
pthread_mutex_unlock(&log_mutex);
return (rc);
}
static int lylogprintfl(int level, const char *format, va_list ap)
{
int rc, fd;
char buf[27], *eol;
time_t t;
struct stat statbuf;
FILE *file;
if (level < loglevel) {
return (0);
}
pthread_mutex_lock(&log_mutex);
rc = 1;
if (logging) {
file = LOGFH;
fd = fileno(file);
if (fd >= 0) {
rc = fstat(fd, &statbuf);
if (!rc && ((int) statbuf.st_size > MAXLOGFILESIZE)) {
int i;
char oldFile[PATH_MAX], newFile[PATH_MAX];
rc = stat(logFile, &statbuf);
if (!rc && ((int) statbuf.st_size > MAXLOGFILESIZE)) {
for (i = 4; i >= 0; i--) {
snprintf(oldFile, PATH_MAX, "%s.%d", logFile, i);
snprintf(newFile, PATH_MAX, "%s.%d", logFile,
i + 1);
rename(oldFile, newFile);
}
snprintf(oldFile, PATH_MAX, "%s", logFile);
snprintf(newFile, PATH_MAX, "%s.%d", logFile, 0);
rename(oldFile, newFile);
}
fclose(LOGFH);
LOGFH = fopen(logFile, "a");
if (LOGFH) {
file = LOGFH;
}
else {
file = stdout;
}
}
}
}
else {
file = stdout;
}
t = time(0);
if (ctime_r(&t, buf)) {
eol = strchr(buf, '\\n');
if (eol) {
*eol = '\\0';
}
fprintf(file, "[%s]", buf);
}
if (level == LYDEBUG) {
fprintf(file, "[DD] ");
}
else if (level == LYINFO) {
fprintf(file, "[II] ");
}
else if (level == LYWARN) {
fprintf(file, "[WW] ");
}
else if (level == LYERROR) {
fprintf(file, "[EE] ");
}
else if (level == LYFATAL) {
fprintf(file, "[FF] ");
}
else {
fprintf(file, "[DD] ");
}
rc = vfprintf(file, format, ap);
fflush(file);
pthread_mutex_unlock(&log_mutex);
return (rc);
}
int logerror(const char *format, ...)
{
int rc;
va_list ap;
__builtin_va_start((ap));
rc = lylogprintfl(LYERROR, format, ap);
;
return (rc);
}
int logdebug(const char *format, ...)
{
int rc;
va_list ap;
__builtin_va_start((ap));
rc = lylogprintfl(LYDEBUG, format, ap);
;
return (rc);
}
int loginfo(const char *format, ...)
{
int rc;
va_list ap;
__builtin_va_start((ap));
rc = lylogprintfl(LYINFO, format, ap);
;
return (rc);
}
int logwarn(const char *format, ...)
{
int rc;
va_list ap;
__builtin_va_start((ap));
rc = lylogprintfl(LYWARN, format, ap);
;
return (rc);
}
int logclose(void)
{
if (LOGFH != 0){
fclose(LOGFH);
LOGFH = 0;
}
return 0;
}
| 1
|
#include <pthread.h>
void *philosopher (void *id);
int food_on_table (), numRefeicoes = 0;
pthread_mutex_t chopstick[5], mut, saleiro;
pthread_mutex_t food_lock;
pthread_t philo[5];
int main (int argn, char **argv)
{
long i;
pthread_mutex_init (&saleiro, 0);
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;
id = (long)num;
left_chopstick = id;
right_chopstick = (id + 1)%5;
while (1) {
int pause = rand() % 3;
pthread_mutex_lock (&saleiro);
pthread_mutex_lock (&chopstick[left_chopstick]);
pthread_mutex_lock (&chopstick[right_chopstick]);
numRefeicoes++;
pause = rand() % 3;
pthread_mutex_unlock (&chopstick[left_chopstick]);
pthread_mutex_unlock (&chopstick[right_chopstick]);
pthread_mutex_unlock (&saleiro);
}
return (0);
}
| 0
|
#include <pthread.h>
{
int data;
struct node* next;
}node_t;
int c=0;
void *thread1(void *);
void *thread2(void *);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void insert(int data,node_t * head)
{
node_t * last = head;
pthread_mutex_lock(&mutex);
c++;
while(last->next != 0)
{
last = last->next;
}
if(last == head && c == 1)
{
last->data = data;
}
else if(c>1)
{
node_t * n = malloc(sizeof(struct node));
n->data = data;
last->next = n;
n->next = 0;
}
pthread_mutex_unlock(&mutex);
}
void printlist(node_t * head)
{
do
{
printf("\\t%d",head->data);
head = head->next;
}while(head != 0);
}
void deleteElement(node_t *head, int pos)
{
int var;
node_t * prev;
node_t * node = head;
node_t head1 = *head;
pthread_mutex_lock(&mutex);
for (var = 0; var < pos; ++var)
{
prev = node;
node = node->next;
}
if(node == head)
{
node_t * temp = head->next;
*head = *temp;
free(temp);
}
else
{
prev->next = node->next;
free(node);
}
pthread_mutex_unlock(&mutex);
}
node_t *init_list()
{
node_t * head = malloc(sizeof(node_t));
head->next = 0;
return head;
}
int main(void)
{
node_t * head = init_list();
pthread_t t1,t2;
pthread_create (&t2, 0, thread2, (void *)head);
pthread_create (&t1, 0, thread1, (void *)head);
pthread_join (t1, 0);
pthread_join (t2, 0);
printlist(head);
return 0;
}
void * thread1(void * args)
{
node_t * head = args;
insert(12,head);
insert(14,head);
deleteElement(head,0);
}
void * thread2(void * args)
{
node_t * head = args;
insert(22,head);
insert(24,head);
deleteElement(head,1);
}
| 1
|
#include <pthread.h>
pthread_t tid[10];
int lletres;
int n_veg;
pthread_mutex_t mutex= PTHREAD_MUTEX_INITIALIZER;
void * caracter(void *id)
{
int i;
for (i=0; i < n_veg; i++)
{
sleep(1 + rand() % 3);
pthread_mutex_lock(&mutex);
if (lletres > 0)
{
printf("%c",'a'+(int)id);
lletres--;
pthread_mutex_unlock(&mutex);
}
else
{
pthread_mutex_unlock(&mutex);
pthread_exit((void *) i);
}
}
return((void *) i);
}
int main(int n_args, char * ll_args[])
{
int i,n,t,t_total,n_thr;
if (n_args != 4)
{ fprintf(stderr,"comanda: mf_mutex num_threads n_vegades n_lletres\\n");
exit(1);
}
n_thr = atoi(ll_args[1]);
n_veg = atoi(ll_args[2]);
lletres = atoi(ll_args[3]);
if (n_thr < 1) n_thr = 1;
if (n_thr > 10) n_thr = 10;
if (n_veg < 1) n_veg = 1;
if (n_veg > 50) n_veg = 50;
if (lletres < 1) lletres = 1;
if (lletres > 100) lletres = 100;
srand(getpid());
setbuf(stdout,0);
printf("Main thread [%d] del proces (%d) : ", pthread_self(),getpid());
pthread_mutex_init(&mutex, 0);
n = 0;
for ( i = 0; i < n_thr; i++)
{
if (pthread_create(&tid[n],0,caracter,(void *) i+1) == 0)
n++;
}
printf("he creat %d threads, espero que acabin!\\n\\n",n);
t_total = 0;
for ( i = 0; i < n; i++)
{
pthread_join(tid[i], (void **)&t);
printf("el thread (%d) ha escrit %d lletres\\n",i+1,t);
t_total += t;
}
pthread_mutex_destroy(&mutex);
printf("\\nJa han acabat tots els threads creats!\\n");
printf("Entre tots els threads han escrit %d lletres.\\n",t_total);
return(0);
}
| 0
|
#include <pthread.h>
struct info {
int id;
int loops;
};
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static volatile int glob = 0;
static void *
threadFunc(void *arg)
{
struct info *i = (struct info *) arg;
int loops = i->loops;
int loc, j;
for (j = 0; j < loops; j++) {
pthread_mutex_lock(&mtx);
loc = glob;
loc++;
glob = loc;
pthread_mutex_unlock(&mtx);
}
printf("Thread %d - glob total: %d\\n", i->id, glob);
return 0;
}
int
main(int argc, char *argv[])
{
pthread_t t1, t2;
int loops, s;
loops = (argc > 1) ? getInt(argv[1], GN_GT_0, "num-loops") : 10000000;
struct info info1;
info1.id = 1;
info1.loops = loops;
struct info info2;
info2.id = 2;
info2.loops = loops;
s = pthread_create(&t1, 0, threadFunc, (void *) &info1);
if (s != 0)
errExitEN(s, "pthread_create");
s = pthread_create(&t2, 0, threadFunc, (void *) &info2);
if (s != 0)
errExitEN(s, "pthread_create");
s = pthread_join(t1, 0);
if (s != 0)
errExitEN(s, "pthread_join");
s = pthread_join(t2, 0);
if (s != 0)
errExitEN(s, "pthread_join");
printf("glob = %d\\n", glob);
exit(0);
}
| 1
|
#include <pthread.h>
int thread_count;
double dx = 0.1e-2;
double dt = 0.1e-6;
int timcnt = 250;
double sum = 0;
pthread_mutex_t mutex;
int rank;
double *uc;
double *un;
double *sum;
}thread_parm_t;
void* uc_init(void *parm){
thread_parm_t *p = (thread_parm_t *)parm;
int i, start, end;
int rank = p->rank;
double *uc = p->uc;
start = rank*400000/thread_count;
end = (rank + 1) *400000/thread_count;
for (i=start; i<end; i++){
uc[i] = 1.0;
}
return 0;
}
void* uc_r(void *parm){
thread_parm_t *p = (thread_parm_t *)parm;
int i, start, end;
int rank = p->rank;
double *uc = p->uc;
double *un = p->un;
double r = dt/(dx*dx);
double r1 = 1-2*r;
start = rank*400000/thread_count;
end = (rank + 1) *400000/thread_count;
if (rank == 0){
start = 1;
}
for( i=start; i<end; i++ ) {
un[i] = r*(uc[i-1]+uc[i+1])+r1*uc[i];
}
return 0;
}
void* uc_un(void *parm){
thread_parm_t *p = (thread_parm_t *)parm;
int i, start, end;
int rank = p->rank;
double *uc = p->uc;
double *un = p->un;
start = rank*400000/thread_count;
end = (rank + 1) *400000/thread_count;
if (rank == 0){
start = 1;
}
for( i=start; i<end; i++ ) {
uc[i] = un[i];
}
return 0;
}
void* sum_1(void *parm){
thread_parm_t *p = (thread_parm_t *)parm;
int i, start, end;
int rank = p->rank;
double *uc = p->uc;
double local_sum = 0;
start = rank*400000/thread_count;
end = (rank + 1) *400000/thread_count;
if (rank == 0){
start = 1;
}
if (rank == thread_count -1){
end = 400000 -1;
}
for( i=start; i<end; i++ ) {
local_sum += uc[i];
}
pthread_mutex_lock(&mutex);
sum += local_sum;
pthread_mutex_unlock(&mutex);
return 0;
}
int main(int argc, char **argv) {
double uc[400000 +1], un[400000 +1];
int i,j;
thread_count = strtol(argv[1], 0, 10);
if (400000 % thread_count != 0){
printf("M (400000) has to be a multiple of the number of threads\\n");
return 0;
}
thread_parm_t *parm[thread_count];
pthread_t thread[thread_count];
for (i=0; i<thread_count; i++){
parm[i] = (thread_parm_t*) malloc(sizeof(thread_parm_t));
parm[i]->rank = i;
parm[i]->uc = uc;
parm[i]->un = un;
}
for (i=0; i<thread_count; i++){
pthread_create(&thread[i], 0, uc_init, (void *)parm[i]);
}
for (i=0; i<thread_count; i++){
pthread_join(thread[i],0);
}
uc[0] = 0.0;
uc[400000] = 0.0;
for( j=0; j<timcnt; j++ ) {
for (i=0; i<thread_count; i++){
pthread_create(&thread[i], 0, uc_r, (void *)parm[i]);
}
for (i=0; i<thread_count; i++){
pthread_join(thread[i],0);
}
for (i=0; i<thread_count; i++){
pthread_create(&thread[i], 0, uc_un, (void *)parm[i]);
}
for (i=0; i<thread_count; i++){
pthread_join(thread[i],0);
}
}
pthread_mutex_init(&mutex, 0);
for (i=0; i<thread_count; i++){
pthread_create(&thread[i], 0, sum_1, (void *)parm[i]);
}
for (i=0; i<thread_count; i++){
pthread_join(thread[i],0);
}
printf( "sum %9.8f\\n", sum );
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t mutex_initialize = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t condition_init = PTHREAD_COND_INITIALIZER;
extern void queue_init(struct scheduler_queue* queue) {
queue->lock = mutex_initialize;
queue->not_empty = condition_init;
}
extern void scheduler_enqueue(struct scheduler_queue* queue, struct rcb* req_control_block) {
req_control_block->next_rcb = 0;
pthread_mutex_lock(&queue->lock);
if(!queue->head) {
queue->head = req_control_block;
} else {
queue->tail->next_rcb = req_control_block;
}
queue->tail = req_control_block;
pthread_cond_signal(&queue->not_empty);
pthread_mutex_unlock(&queue->lock);
}
extern struct rcb* scheduler_dequeue(struct scheduler_queue* queue, int wait) {
struct rcb* req_control_block;
pthread_mutex_lock(&queue->lock);
if (wait && !queue->head) {
pthread_cond_wait(&queue->not_empty, &queue->lock);
}
req_control_block = queue->head;
if(queue->head) {
queue->head = queue->head->next_rcb;
req_control_block->next_rcb = 0;
}
pthread_mutex_unlock(&queue->lock);
return req_control_block;
}
| 1
|
#include <pthread.h>
pthread_attr_t attr;
pthread_t idth[10];
pthread_mutex_t mtx;
pthread_cond_t varcond;
int turno=1;
void *hilo1(void *num) {
int cont=1;
while (cont <=10){
pthread_mutex_lock (&mtx);
while (turno!=1) pthread_cond_wait(&varcond, &mtx);
printf ("th1:%d\\n", cont);
cont=cont+2;
turno = 2;
pthread_cond_signal(&varcond);
pthread_mutex_unlock (&mtx);
}
pthread_exit(0);
}
void *hilo2(void *num) {
int cont=2;
while (cont <=10){
pthread_mutex_lock (&mtx);
while (turno!=2) pthread_cond_wait(&varcond, &mtx);
printf ("th2:%d\\n", cont);
cont=cont+2;
turno = 1;
pthread_cond_signal(&varcond);
pthread_mutex_unlock (&mtx);
}
pthread_exit(0);
}
int main(){
int i;
pthread_mutex_init (&mtx, 0);
pthread_attr_init(&attr);
pthread_create(&idth[0],&attr,hilo1,&i);
pthread_create(&idth[1],&attr,hilo2,&i);
for (i=0; i<2; i++)
pthread_join(idth[i],0);
return(0);
}
| 0
|
#include <pthread.h>
pthread_t callThd[2];
pthread_mutex_t mutexpi;
static long num_steps = 1000000;
double sum = 0.0;
double step;
void *calpi(void *arg)
{
int i;
double x, sum_parcial = 0.0;
int offset;
offset = (int)arg;
int len = (int) num_steps/(int)2;
int start = len * (int) offset;
int fim = (start + len) -1;
printf("thread %i com start %i e fim %i\\n", offset,start,fim);
for (i=start; i<=fim; i++)
{
x = (i+0.5)*step;
sum_parcial = sum_parcial + 4.0/(1.0+x*x);
}
pthread_mutex_lock (&mutexpi);
sum = sum_parcial + sum;
pthread_mutex_unlock (&mutexpi);
pthread_exit((void*) 0);
}
int main ()
{
double pi;
int i;
void *status;
pthread_attr_t attr;
pthread_mutex_init(&mutexpi, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
step = 1.0/(double) num_steps;
for(i=0; i<2; i++)
{
pthread_create(&callThd[i], &attr, calpi, (void *)i);
}
pthread_attr_destroy(&attr);
for(i=0; i<2; i++)
{
pthread_join(callThd[i], &status);
}
printf("sum %lf e step %lf\\n", sum,step);
pi = step * sum;
printf("Valor de pi: %.30f\\n", pi);
pthread_mutex_destroy(&mutexpi);
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
size_t num_bins;
size_t *bins;
double min_value;
double max_value;
double bin_width;
} histogram_t;
histogram_t *hist = 0;
pthread_mutex_t mutexsum;
size_t count = 0;
int thread_count;
int flag = 0;
double *data;
size_t search_for_bin(double value, histogram_t *hist)
{
size_t i = 0;
while (i < hist->num_bins && value >= (i+1)*hist->bin_width) i++;
return i >= hist->num_bins ? hist->num_bins-1 : i;
}
void* create_histogram_parallel(void* rank) {
long my_rank = (long) rank;
unsigned long i, my_sum;
unsigned long local_N = count / thread_count;
unsigned long first_i = my_rank * local_N;
unsigned long last_i = (my_rank + 1) * local_N - 1;
for (i = first_i; i <= last_i; i++)
{
size_t bin_index = search_for_bin(data[i], hist);
pthread_mutex_lock (&mutexsum);
hist->bins[bin_index]++;
pthread_mutex_unlock (&mutexsum);
}
return 0;
}
histogram_t *create_histogram(double min_meas, double max_meas, size_t bin_count, int thread_count)
{
size_t i;
long thread;
hist = (histogram_t *) malloc(sizeof(histogram_t));
if (hist == 0) {
perror("Error");
exit(1);
}
hist->num_bins = bin_count;
hist->min_value = min_meas;
hist->max_value = max_meas;
hist->bin_width = (max_meas - min_meas)/bin_count;
if ((hist->bins = ((size_t *)calloc(bin_count, sizeof(size_t)))) == 0) {
perror("Error");
exit(1);
}
pthread_t* thread_handles = malloc (thread_count*sizeof(pthread_t));
for (thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread], 0, create_histogram_parallel, (void*) thread);
for (thread = 0; thread < thread_count; thread++)
pthread_join(thread_handles[thread], 0);
free(thread_handles);
return hist;
}
void print_histogram(histogram_t *hist)
{
size_t i;
for (i=0; i<hist->num_bins; i++)
fprintf(stdout, "bin[%zu] = %zu\\n", i, hist->bins[i]);
}
void read_data(char *filename, size_t *count, double *min, double *max)
{
FILE *fp;
if ((fp = fopen(filename, "r")) == 0) {
perror(filename);
exit(1);
}
char buf[100];
fgets(buf, 100, fp);
*count = strtol(buf, 0, 10);
fgets(buf, 100, fp);
*min = strtod(buf, 0);
fgets(buf, 100, fp);
*max = strtod(buf, 0);
if ((data = (double *)malloc(*count*sizeof(double))) == 0) {
perror("Error");
exit(1);
}
size_t i;
for (i=0; i<*count; i++) {
fgets(buf, 100, fp);
data[i] = strtod(buf, 0);
}
fclose(fp);
}
int main(int argc, char *argv[])
{
histogram_t *myhist;
struct timeval start, stop;
double min, max;
if (argc < 4) {
fprintf(stderr, "Invalid number of parameters\\n");
exit(1);
}
char *filename;
size_t bin_count = strtol(argv[1], 0, 10);
filename = argv[2];
thread_count = atoi(argv[3]);
read_data(filename, &count, &min, &max);
pthread_mutex_init(&mutexsum, 0);
gettimeofday(&start, 0);
myhist = create_histogram(min, max, bin_count, thread_count);
gettimeofday(&stop, 0);
double t = (((double)(stop.tv_sec)*1000.0 + (double)(stop.tv_usec / 1000.0)) -
((double)(start.tv_sec)*1000.0 + (double)(start.tv_usec / 1000.0)));
fprintf(stdout, "Time elapsed = %g ms\\n", t);
print_histogram(myhist);
return 0;
}
| 0
|
#include <pthread.h>
int buffer[100];
int fill = 0;
int use = 0;
int count = 0;
void put(int value) {
buffer[fill] = value;
fill = (fill + 1) % 100;
count ++;
}
int get () {
int tmp = buffer[use];
use = (use + 1) % 100;
count--;
return tmp;
}
pthread_cond_t empty, full;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *producer(void *arg) {
int i;
for (i = 0; i < 1000; i++) {
pthread_mutex_lock(&mutex);
while(count == 100) {
pthread_cond_wait(&empty, &mutex);
}
put(i);
pthread_cond_signal(&full);
pthread_mutex_unlock(&mutex);
}
return 0;
}
void *consumer(void *arg) {
int i;
int tmp;
for (i = 0; i < 1000; i++) {
while (count == 0) {
pthread_cond_wait(&full, &mutex);
}
tmp = get();
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
printf("\\n%d", tmp);
}
return 0;
}
int main () {
pthread_t producer_t, consumer_t;
printf("\\nmain begin");
pthread_create(&producer_t, 0, producer, 0);
pthread_create(&consumer_t, 0, consumer, 0);
pthread_join(producer_t, 0);
pthread_join(consumer_t, 0);
printf("\\nmain end");
}
| 1
|
#include <pthread.h>
int memory[(2*32+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*32+1)){
pthread_mutex_unlock(&m);
curr_alloc_idx = 0;
}else{
curr_alloc_idx = next_alloc_idx;
next_alloc_idx += 2;
pthread_mutex_unlock(&m);
}
return curr_alloc_idx;
}
void EBStack_init(){
top = 0;
}
int isEmpty() {
if(top == 0)
return 1;
else
return 0;
}
int push(int d) {
int oldTop = -1, newTop = -1;
newTop = index_malloc();
if(newTop == 0){
return 0;
}else{
memory[newTop+0] = d;
while (1) {
oldTop = top;
memory[newTop+1] = oldTop;
if(__sync_bool_compare_and_swap(&top,oldTop,newTop)){
return 1;
}
}
}
}
void __VERIFIER_atomic_assert(int r)
{
__atomic_begin();
assert(!r || !isEmpty());
__atomic_end();
}
void push_loop(){
int r = -1;
int arg = __nondet_int();
while(1){
r = push(arg);
__VERIFIER_atomic_assert(r);
}
}
pthread_mutex_t m2;
int state = 0;
void* thr1(void* arg)
{
pthread_mutex_lock(&m2);
switch(state)
{
case 0:
EBStack_init();
state = 1;
case 1:
pthread_mutex_unlock(&m2);
push_loop();
break;
}
return 0;
}
int main()
{
pthread_t t1,t2;
pthread_create(&t1, 0, thr1, 0);
pthread_create(&t2, 0, thr1, 0);
return 0;
}
| 0
|
#include <pthread.h>
int mediafirefs_rmdir(const char *path)
{
printf("FUNCTION: rmdir. path: %s\\n", path);
const char *key;
int retval;
struct mediafirefs_context_private *ctx;
ctx = fuse_get_context()->private_data;
pthread_mutex_lock(&(ctx->mutex));
key = folder_tree_path_get_key(ctx->tree, ctx->conn, path);
if (key == 0) {
fprintf(stderr, "key is NULL\\n");
pthread_mutex_unlock(&(ctx->mutex));
return -ENOENT;
}
retval = mfconn_api_folder_delete(ctx->conn, key);
if (retval != 0) {
fprintf(stderr, "mfconn_api_folder_create unsuccessful\\n");
pthread_mutex_unlock(&(ctx->mutex));
return -EAGAIN;
}
folder_tree_update(ctx->tree, ctx->conn, 1);
pthread_mutex_unlock(&(ctx->mutex));
return 0;
}
| 1
|
#include <pthread.h>
int tasks = 0, done = 0;
pthread_mutex_t lock;
void dummy_task(void *arg) {
usleep(10000);
pthread_mutex_lock(&lock);
char *Buf;
Buf= (char *)arg;
printf("Buf: %s\\n", Buf);
done++;
pthread_mutex_unlock(&lock);
}
int main(int argc, char **argv)
{
threadpool_t *pool;
pthread_mutex_init(&lock, 0);
assert((pool = threadpool_create(32, 256, 0)) != 0);
fprintf(stderr, "Pool started with %d threads and "
"queue size of %d\\n", 32, 256);
char *buf = "tibco sms";
printf("buf: %s\\n", buf);
while(threadpool_add(pool, &dummy_task, (void *)buf, 0) == 0) {
pthread_mutex_lock(&lock);
tasks++;
pthread_mutex_unlock(&lock);
}
fprintf(stderr, "Added %d tasks\\n", tasks);
while((tasks / 2) > done) {
usleep(10000);
}
assert(threadpool_destroy(pool, 0) == 0);
fprintf(stderr, "Did %d tasks\\n", done);
return 0;
}
| 0
|
#include <pthread.h>
int source[30];
int minBound[6];
int maxBound[6];
int channel[6];
int th_id = 0;
pthread_mutex_t mid;
pthread_mutex_t ms[6];
void sort (int x, int y)
{
int aux = 0;
for (int i = x; i < y; i++)
{
for (int j = i; j < y; j++)
{
if (source[i] > source[j])
{
aux = source[i];
source[i] = source[j];
source[j] = aux;
}
}
}
}
void *sort_thread (void * arg)
{
int id = -1;
int x, y;
pthread_mutex_lock (&mid);
id = th_id;
th_id++;
pthread_mutex_unlock (&mid);
x = minBound[id];
y = maxBound[id];
__VERIFIER_assert (x >= 0);
__VERIFIER_assert (x < 30);
__VERIFIER_assert (y >= 0);
__VERIFIER_assert (y < 30);
printf ("t%d: min %d max %d\\n", id, x, y);
sort (x, y);
pthread_mutex_lock (&ms[id]);
channel[id] = 1;
pthread_mutex_unlock (&ms[id]);
return 0;
}
int main ()
{
pthread_t t[6];
int i;
__libc_init_poet ();
for (i = 0; i < 30; i++)
{
source[i] = __VERIFIER_nondet_int (0, 20);
printf ("m: source[%d] = %d\\n", i, source[i]);
__VERIFIER_assert (source[i] >= 0);
}
pthread_mutex_init (&mid, 0);
int j = 0;
int delta = 30/6;
__VERIFIER_assert (delta >= 1);
i = 0;
channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++;
channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++;
channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++;
channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++;
channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++;
channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++;
__VERIFIER_assert (i == 6);
int k = 0;
while (k < 6)
{
i = 0;
pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++;
pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++;
pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++;
pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++;
pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++;
pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++;
__VERIFIER_assert (i == 6);
}
__VERIFIER_assert (th_id == 6);
__VERIFIER_assert (k == 6);
sort (0, 30);
printf ("==============\\n");
for (i = 0; i < 30; i++)
printf ("m: sorted[%d] = %d\\n", i, source[i]);
i = 0;
pthread_join (t[i], 0); i++;
pthread_join (t[i], 0); i++;
pthread_join (t[i], 0); i++;
pthread_join (t[i], 0); i++;
pthread_join (t[i], 0); i++;
pthread_join (t[i], 0); i++;
__VERIFIER_assert (i == 6);
return 0;
}
| 1
|
#include <pthread.h>
int g1, g2, g3, g4;
int found = 1;
float goertzel(int N,int Ft, float* input) {
int k, i;
float floatN;
float omega, sine, cosine, q0, q1, q2, power;
float scalingFactor = N / 2.0;
floatN = (float) N;
k = (int) (0.5 + ((floatN * Ft) / Fs));
omega = (2.0 * M_PI * k) / floatN;
sine = sin(omega);
cosine = 2.0 *cos(omega);
q0=0;
q1=0;
q2=0;
for(i=0; i<N; i++)
{
q0 = cosine * q1 - q2 + input[i];
q2 = q1;
q1 = q0;
}
power = (q2 *q2 + q1 * q1 - cosine * q1 * q2) / scalingFactor;
return power;
}
void *finding_freq() {
double elapsed;
int err;
usleep(100000);
start = clock();
while(1) {
pthread_mutex_lock(&mutex_f);
{
g1 = goertzel(2048, freq_up, buffer_f);
g2 = goertzel(2048, freq_down, buffer_f);
}
if ((g1>TH) &
(g2>TH)){
if(found) {
found = 0;
dial_num[num_det] = num_jef[num_det];
num_det++;
digit = num_jef[num_det];
set_station();
start = clock();
}
}
else {
found = 1;
}
pthread_mutex_unlock(&mutex_f);
pthread_mutex_lock(&mutex_s);
{
g3 = goertzel(2048, freq_up, buffer_s);
g4 = goertzel(2048, freq_down, buffer_s);
}
if ((g3>TH) &
(g4>TH)){
if(found) {
found = 0;
dial_num[num_det] = num_jef[num_det];
num_det++;
digit = num_jef[num_det];
set_station();
start = clock();
}
}
else {
found = 1;
}
pthread_mutex_unlock(&mutex_s);
end = clock();
elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;
if(abs(elapsed) > 3) {
digit = num_jef[0];
num_det = 0;
set_station();
}
if(num_det == 8) {
if ((err = snd_pcm_open(&handle_w, "default", SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
printf("Playback open error: %s\\n", snd_strerror(err));
exit(1);
}
if ((err = snd_pcm_set_params(handle_w,
SND_PCM_FORMAT_FLOAT,
SND_PCM_ACCESS_RW_INTERLEAVED,
1,
Fs,
1,
100000)) < 0) {
printf("Playback open error: %s\\n", snd_strerror(err));
exit(1);
}
pthread_create( &thread2, 0, write_, 0);
num_det = 0;
}
}
}
void *write_() {
usleep(100000);
while((mode==0) & (ch1 != 'q'))
{
pthread_mutex_lock(&mutex_w1);
(void) snd_pcm_writei(handle_w, buffer_f, 2048);
pthread_mutex_unlock(&mutex_w1);
(void) snd_pcm_writei(handle_w, buffer_s, 2048);
}
snd_pcm_close(handle_w);
usleep(100000);
}
void set_station() {
switch ( digit ) {
case 0:
freq_up = 1336; freq_down = 941;
break;
case 1:
freq_up = 1209; freq_down = 697;
break;
case 2:
freq_up = 1336; freq_down = 697;
break;
case 3:
freq_up = 1477; freq_down = 697;
break;
case 4:
freq_up = 1209; freq_down = 770;
break;
case 5:
freq_up = 1336; freq_down = 770;
break;
case 6:
freq_up = 1477; freq_down = 770;
break;
case 7:
freq_up = 1209; freq_down = 852;
break;
case 8:
freq_up = 1336; freq_down = 852;
break;
case 9:
freq_up = 1477; freq_down = 852;
break;
case 10:
freq_up = 1633; freq_down = 697;
break;
case 11:
freq_up = 1633; freq_down = 770;
break;
case 12:
freq_up = 1633; freq_down = 852;
break;
case 13:
freq_up = 1333; freq_down = 941;
break;
case 14:
freq_up = 1209; freq_down = 941;
break;
case 15:
freq_up = 1477; freq_down = 941;
break;
default:
freq_up = 10000; freq_down = 10000;
break;
}
}
unsigned long get_time_usec() {
struct timeval tv;
gettimeofday(&tv,0);
unsigned long time_in_micros = 1000000 * tv.tv_sec + tv.tv_usec;
return time_in_micros;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
void threadcleanup(void *p)
{
printf("i am the %ld thread's cleaner,i unlock mutex\\n",(long int)p);
pthread_mutex_unlock(&mutex);
}
void * threadfunc(void *p)
{
pthread_cleanup_push(threadcleanup,p);
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond,&mutex);
pthread_mutex_unlock(&mutex);
pthread_cleanup_pop(0);
return p;
}
int main()
{
pthread_t thid[5];
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_settype(&mutexattr,PTHREAD_MUTEX_TIMED_NP);
pthread_mutex_init(&mutex,&mutexattr);
pthread_cond_init(&cond,0);
printf("creat 5 child thread\\n");
for(long int i=0;i<5;i++)
{
if(pthread_create(&thid[i],0,threadfunc,(void*)i)!=0)
printf("cread thread %ld falied\\n",i);
else
printf("creat the chid thread id is%ld\\n",thid[i]);
}
printf("creat child thread finish\\n");
sleep(3);
pthread_cancel(thid[3]);
pthread_cond_broadcast(&cond);
printf("signal have been sending\\n");
long int ret;
for(int i=0;i<5;i++)
{
pthread_join(thid[i],(void**)&ret);
printf("the %d child thread %ld return value is %ld\\n",i,thid[i],ret);
}
return 0;
}
| 1
|
#include <pthread.h>
{
int id;
char name[20];
int flag;
int money;
}Person;
Person per[20];
double money = 0.0;
int num = 0;
pthread_mutex_t lock;
void *producer(void* value)
{
double n = *(double*)value;
pthread_mutex_lock(&lock);
money = n;
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
void *consumer(void *n)
{
int nn = *(int*)n;
pthread_mutex_lock(&lock);
printf("number%d\\n",nn);
if(money > 0)
{
if(num > 1)
{
srand((unsigned)time(0));
double avg = money / num;
double t = avg*2;
double randmoney = (rand()%(int)(t*100) + (int)0.01*100)/100.00 + 0.01;
money-=randmoney;
printf("%s取走%.2lf元\\n",per[nn].name,randmoney);
printf("剩余%.2lf元\\n",money);
per[nn].id = nn;
per[nn].money = randmoney;
per[nn].flag = 1;
num--;
}
else
{
printf("%s取走%.2lf元\\n",per[nn].name,money);
printf("剩余0元\\n");
money = 0;
per[nn].id = nn;
per[nn].money = money;
per[nn].flag = 1;
num--;
}
}
pthread_mutex_unlock(&lock);
pthread_cancel(pthread_self());
}
int main()
{
char *name[] = {"zy","tom","alice","tony","sam","fred","amy","zyu","ll","yl","eh","dh","tjm","lk","sx","jx","gl","yj","gc","efw"};
int i = 0;
double value = 0.0;
pthread_mutex_init(&lock,0);
while(1)
{
printf("请输入红包的金额:\\n");
scanf("%lf",&value);
printf("请输入红包个数:\\n");
scanf("%d",&num);
if(value >= 0.01 && value <= 200 && num > 0)
{
break;
}
printf("输入有误,请重输!\\n");
}
for(i = 0; i < 20; i++)
{
strcpy(per[i].name,name[i]);
per[i].flag = 0;
per[i].id = -1;
}
pthread_t th_a,th_b[20];
pthread_create(&th_a,0,producer,(void*)&value);
pthread_join(th_a,0);
int args[20];
for(i = 0; i < 20;i++)
{
args[i] = i;
if(per[i].flag == 0)
{
pthread_create(&th_b[i],0,consumer,(void*)&args[i]);
}
}
for(i = 0; i < 20; i++)
{
pthread_join(th_b[i],0);
}
pthread_mutex_destroy(&lock);
return 0;
}
| 0
|
#include <pthread.h>
void *consumeTen();
void *consumeFifteen();
struct data
{
pthread_t threadID;
char name;
int pearlsTaken;
int *pearls;
};
int pearls = 1000;
int occupied = 0;
pthread_mutex_t mutex;
pthread_cond_t full_cond;
pthread_cond_t empty_cond;
struct data threadData[4];
int main()
{
int i, j;
threadData[0].name = 'A';
threadData[0].pearlsTaken = 0;
threadData[1].name = 'B';
threadData[1].pearlsTaken = 0;
threadData[2].name = 'C';
threadData[2].pearlsTaken = 0;
threadData[3].name = 'D';
threadData[3].pearlsTaken = 0;
pthread_setconcurrency(4);
pthread_create(&threadData[0].threadID, 0, (void *(*)(void *))consumeTen, &threadData[0]);
pthread_create(&threadData[1].threadID, 0, (void *(*)(void *))consumeTen, &threadData[1]);
pthread_create(&threadData[2].threadID, 0, (void *(*)(void *))consumeFifteen, &threadData[2]);
pthread_create(&threadData[3].threadID, 0, (void *(*)(void *))consumeFifteen, &threadData[3]);
pthread_exit(0);
}
void *consumeTen()
{
double pearlsToTake = 0;
while(pearls != 0)
{
pthread_mutex_lock(&mutex);
occupied = 1;
if(occupied == 1)
{
printf("There is already a pirate in the cave, this thread cannot enter \\n");
pthread_cond_wait(&full_cond, &mutex);
}
else
{
pearlsToTake = (.10) * pearls;
pearlsToTake = ceil(pearlsToTake);
printf("Pirate %c took %d pearls from the chest \\n", threadData->name, pearlsToTake);
pearls -= pearlsToTake;
threadData->pearlsTaken += pearlsToTake;
}
occupied = 0;
pthread_cond_broadcast(&full_cond);
pthread_mutex_unlock(&mutex);
}
}
void *consumeFifteen()
{
double pearlsToTake = 0;
while(pearls != 0)
{
pthread_mutex_lock(&mutex);
occupied = 1;
if(occupied == 1)
{
printf("There is already a pirate in the cave,sdasd this thread cannot enter \\n");
pthread_cond_wait(&full_cond, &mutex);
}
else
{
pearlsToTake = (.15) * pearls;
pearlsToTake = ceil(pearlsToTake);
printf("Pirate %c took %d pearls from the chest \\n", threadData->name, pearlsToTake);
pearls -= pearlsToTake;
threadData->pearlsTaken += pearlsToTake;
}
occupied = 0;
pthread_cond_broadcast(&full_cond);
pthread_mutex_unlock(&mutex);
}
}
| 1
|
#include <pthread.h>
int circle_count;
int total_points = 10000000;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
double random_double();
void * start_routine();
int main(void){
double est_pi;
pthread_t workers[4];
pthread_attr_t attr;
pthread_attr_init(&attr);
for(int i = 0; i < 4; i++){
pthread_create(&workers[i], &attr, start_routine, 0);
}
for(int i = 0; i < 4; i++){
pthread_join(workers[i], 0);
}
total_points = total_points * 4;
est_pi = (4 * ((double)circle_count/(double)total_points));
printf("%f\\n", est_pi);
return 0;
}
void * start_routine(){
int hit_count = 0;
double x, y;
srandom((unsigned)time(0));
for(int i = 0; i < total_points; i++){
x = random_double() * 2.0 -1.0;
y = random_double() * 2.0 -1.0;
if( sqrt(x*x + y*y) < 1.0){
++hit_count;
}
}
pthread_mutex_lock(&mutex);
circle_count += hit_count;
pthread_mutex_unlock(&mutex);
return;
}
double random_double(){
return (random() / ((double)32767 +1));
}
| 0
|
#include <pthread.h>
double *x;
double *y;
double sum;
int vectorLength;
} DOTDATA;
DOTDATA dotprod;
pthread_t threads[4];
pthread_mutex_t mutex;
void *dotProduct (void *arg) {
int i, start, end, length;
long offset;
double sum, *x, *y;
offset = (long) arg;
length = dotprod.vectorLength;
start = offset * length;
end = start + length;
x = dotprod.x;
y = dotprod.y;
sum = 0;
for(i=start; i<end; i++) {
sum += (x[i]*y[i]);
}
pthread_mutex_lock(&mutex);
dotprod.sum += sum;
printf("\\n\\nThread %ld computed sum between indices %d and %d",offset, start, end);
printf("\\n\\tLocal sum = %f",sum);
printf("\\n\\tGlobal sum = %f",dotprod.sum);
pthread_mutex_unlock(&mutex);
pthread_exit((void*) 0);
}
int main() {
long i;
double *a, *b;
void *status;
pthread_attr_t attr;
a = (double*) malloc(4*10000*sizeof(double));
b = (double*) malloc(4*10000*sizeof(double));
for(i=0; i<10000*4; i++) {
a[i] = 1;
b[i] = 3;
}
printf("\\n\\nVector X consists of %d elements with value = 1", (10000*4));
printf("\\nVector Y consists of %d elements with value = 3", (10000*4));
dotprod.vectorLength = 10000;
dotprod.x = a;
dotprod.y = b;
dotprod.sum = 0;
pthread_mutex_init(&mutex, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i=0; i<4; i++)
pthread_create(&threads[i], &attr, dotProduct, (void *)i);
pthread_attr_destroy(&attr);
for(i=0; i<4; i++)
pthread_join(threads[i], &status);
printf("\\n\\nDOT PRODUCT (X.Y) = %f\\n\\n",dotprod.sum);
free(a);
free(b);
pthread_mutex_destroy(&mutex);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
void *threadFunction(void *p);
int counter;
pthread_mutex_t lock;
int main(){
pthread_t thread_id[5];
int i, ret;
counter = 0;
if( pthread_mutex_init(&lock, 0) != 0){
fprintf(stderr, "Erro ao criar mutex.\\n");
exit(1);
}
for(i=0; i<5; ++i){
ret = pthread_create(&thread_id[i], 0, threadFunction, 0);
if(ret != 0){
fprintf(stderr, "Erro thread %d. Código %d: %s\\n", (i+1), ret, strerror(ret));
exit(1);
}
}
for(i=0; i<5; ++i)
pthread_join(thread_id[i], 0);
pthread_mutex_destroy(&lock);
return 0;
}
void *threadFunction(void *p){
unsigned long i = 0;
pthread_mutex_lock(&lock);
counter++;
printf("Trabalho %d iniciado.\\n", counter);
for(i=0; i<0xFFFFFFF; ++i);
printf("Trabalho %d finalizado.\\n", counter);
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int initial_shareMemory(int key, struct shared_use_st **shared)
{
int shmid = shmget((key_t)key, sizeof(struct shared_use_st), 0666 | IPC_CREAT);
if (shmid == -1) {
debug_msg("initialize share memory failed!");
return -1;
}
void *memoryAdd = shmat(shmid, 0, 0);
if (memoryAdd == (void*)-1) {
debug_msg("set address failed!");
return -1;
}
*shared = (struct shared_use_st*)memoryAdd;
(*shared)->written = 0;
return 0;
}
void *shareMemoryRead(void *args)
{
pthread_detach(pthread_self());
while (1) {
if (g_sharedRead->written == 1) {
}else{
usleep(5000);
}
}
pthread_exit((void*)0);
}
void *shareMemoryWrite(void *args){
pthread_detach(pthread_self());
while(1){
if (g_sharedWrite->written == 0 && g_sharedWriteBuf[0] == 0xFF) {
pthread_mutex_lock(&g_pthSharedWrite);
memcpy(g_sharedWrite->text, g_sharedWriteBuf, 5);
memset(g_sharedWriteBuf, 0, SHARED_TEXT_SIZE);
g_sharedWrite->written = 1;
pthread_mutex_unlock(&g_pthSharedWrite);
sleep(1);
}else{
usleep(5000);
}
}
pthread_exit((void*)0);
}
| 1
|
#include <pthread.h>
void *thread_dis01(void *arg) {
int running = 1;
int DIS01fd = 0;
enum paritymark parity = 'N';
DIS01fd = openSerial(DIS01_SEIRAL_FILE, O_RDWR, B9600, parity, 8, 1);
float factor = 40.0f;
float value=0.0f;
float current=0.0f;
while (running) {
value = sendSerialTextCurrent(DIS01fd);
current = (value - 2.5f) * factor;
pthread_mutex_lock(&s800bm_mutex);
group_battery.group_current = current;
pthread_mutex_unlock(&s800bm_mutex);
AddCurrentData(current);
sleep(1);
}
return 0;
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error() ;
static int iTThreads = 2;
static int iRThreads = 1;
static int data1Value = 0;
static int data2Value = 0;
pthread_mutex_t *data1Lock;
pthread_mutex_t *data2Lock;
void lock(pthread_mutex_t *);
void unlock(pthread_mutex_t *);
void *funcA(void *param) {
pthread_mutex_lock(data1Lock);
data1Value = 1;
pthread_mutex_unlock(data1Lock);
pthread_mutex_lock(data2Lock);
data2Value = data1Value + 1;
pthread_mutex_unlock(data2Lock);
return 0;
}
void *funcB(void *param) {
int t1 = -1;
int t2 = -1;
pthread_mutex_lock(data1Lock);
if (data1Value == 0) {
pthread_mutex_unlock(data1Lock);
return 0;
}
t1 = data1Value;
pthread_mutex_unlock(data1Lock);
pthread_mutex_lock(data2Lock);
t2 = data2Value;
pthread_mutex_unlock(data2Lock);
if (t2 != (t1 + 1)) {
fprintf(stderr, "Bug found!\\n");
ERROR:
__VERIFIER_error();
;
}
return 0;
}
int main(int argc, char *argv[]) {
int i,err;
if (
argc != 1) {
if (argc != 3) {
fprintf(stderr, "./twostage <param1> <param2>\\n");
exit(-1);
} else {
sscanf(argv[1], "%d", &iTThreads);
sscanf(argv[2], "%d", &iRThreads);
}
}
data1Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
data2Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
if (0 != (err = pthread_mutex_init(data1Lock, 0))) {
fprintf(stderr, "pthread_mutex_init error: %d\\n", err);
exit(-1);
}
if (0 != (err = pthread_mutex_init(data2Lock, 0))) {
fprintf(stderr, "pthread_mutex_init error: %d\\n", err);
exit(-1);
}
pthread_t tPool[iTThreads];
pthread_t rPool[iRThreads];
for (
i = 0; i < iTThreads; i++) {
if (0 != (err = pthread_create(&tPool[i], 0, &funcA, 0))) {
fprintf(stderr, "Error [%d] found creating 2stage thread.\\n", err);
exit(-1);
}
}
for (
i = 0; i < iRThreads; i++) {
if (0 != (err = pthread_create(&rPool[i], 0, &funcB, 0))) {
fprintf(stderr, "Error [%d] found creating read thread.\\n", err);
exit(-1);
}
}
for (
i = 0; i < iTThreads; i++) {
if (0 != (err = pthread_join(tPool[i], 0))) {
fprintf(stderr, "pthread join error: %d\\n", err);
exit(-1);
}
}
for (
i = 0; i < iRThreads; i++) {
if (0 != (err = pthread_join(rPool[i], 0))) {
fprintf(stderr, "pthread join error: %d\\n", err);
exit(-1);
}
}
return 0;
}
void lock(pthread_mutex_t *lock) {
int err;
if (0 != (err = pthread_mutex_lock(lock))) {
fprintf(stderr, "Got error %d from pthread_mutex_lock.\\n", err);
exit(-1);
}
}
void unlock(pthread_mutex_t *lock) {
int err;
if (0 != (err = pthread_mutex_unlock(lock))) {
fprintf(stderr, "Got error %d from pthread_mutex_unlock.\\n", err);
exit(-1);
}
}
| 1
|
#include <pthread.h>
extern int errno;
struct param_list{
char *ip;
int sockfd;
};
void *peer_deal(void *i)
{
struct param_list *my_param = (struct param_list *)i;
int sockfd = my_param->sockfd;
int close_bit = 1;
printf("Child created for dealing with client request\\n");
char *buf = (char *)malloc(HANDSHAKE_LEN);
memset(buf,0,HANDSHAKE_LEN);
int n;
while(n=recv(sockfd,buf,HANDSHAKE_LEN,0) > 0)
{
struct handshake_packet *my_packet = (struct handshake_packet *)buf;
if(my_packet->len != strlen(BT_PROTOCOL))
{
printf("len is not match\\n");
break;
}
if(strncmp(my_packet->name,BT_PROTOCOL,strlen(BT_PROTOCOL)) != 0)
{
printf("BT_PROTOCOL is not match\\n");
break;
}
int i = 0,flag = 1;
unsigned char *buf_info = my_packet->info_hash;
for(; i<5; i++)
{
int j = 0;
int part = reverse_byte_orderi(g_infohash[i]);
unsigned char *p = (unsigned char *)∂
for(; j<4; j++)
{
if(*buf_info != p[j])
{
printf("buf_info is %x and p[j] is %x\\n",*buf_info,p[j]);
flag = 0;
goto END;
}
buf_info ++;
}
}
END:
if(flag != 1)
{
printf("\\033[33m buf_info is not match\\n \\033[m");
break;
}
printf("waiting client get info\\n");
pthread_mutex_lock(&g_mutex);
for(i=0; i<MAXPEERS; i++)
{
if(peers_pool[i].used == 1 && strncmp(peers_pool[i].ip,my_param->ip,strlen(my_param->ip)) == 0)
{
printf("find you\\n");
break;
}
}
pthread_mutex_unlock(&g_mutex);
if(i == MAXPEERS || peers_pool[i].sockfd > 0)
{
printf("not you\\n");
break;
}
printf("i is %d\\n",i);
pthread_mutex_lock(&peers_pool[i].sock_mutex);
if(peers_pool[i].status == 1)
{
pthread_mutex_unlock(&peers_pool[i].sock_mutex);
printf("I already some shake hand to peer\\n");
break;
}
peers_pool[i].status = 2;
peers_pool[i].sockfd = sockfd;
memcpy(peers_pool[i].id,my_packet->peer_id,20);
printf("peers_pool 0 status is %d in listen_peers\\n",peers_pool[0].status);
pthread_mutex_unlock(&peers_pool[i].sock_mutex);
printf("send handshake packet return \\n");
memcpy(my_packet->peer_id,g_my_id,20);
send(sockfd,buf,HANDSHAKE_LEN,0);
close_bit = 0;
pthread_t thread;
int rc = pthread_create(&thread, 0, recv_from_peer, (void *)i);
if(rc)
{
printf("Error, return code from pthread_create() is %d\\n", rc);
exit(-1);
}
printf("shake hands succeed\\n");
sendBitField(sockfd);
pthread_t thread_1;
pthread_create(&thread_1, 0, check_and_keepalive, (void*)i);
break;
}
if(n<0)
{
printf("%s\\n",strerror(errno));
}
if(close_bit)
close(sockfd);
free(buf);
}
void *listen_peers(void *p)
{
int listenfd = make_listen_port(g_peerport);
while(1)
{
struct sockaddr_in cliaddr;
int clilen = sizeof(cliaddr);
int sockfd = accept(listenfd, (struct sockaddr*)&cliaddr, &clilen);
struct param_list my_param;
char *ip = (char*)malloc(17*sizeof(char));
memset(ip,0,17);
strcpy(ip, inet_ntoa(cliaddr.sin_addr));
my_param.ip = ip;
my_param.sockfd = sockfd;
pthread_t thread;
printf("I listen a peer\\n");
pthread_create(&thread,0,peer_deal,(void *)&my_param);
}
}
| 0
|
#include <pthread.h>
void dump (uint32_t pid, int screen_log, int reporte_memoria, int reporte_tabla){
FILE *reporte = fopen ("reporte.txt", "a+");
generar_reporte(reporte, pid, reporte_memoria, reporte_tabla, screen_log);
fclose(reporte);
}
void retardo (int segundos){
pthread_mutex_lock(&retardo_mutex);
config->retraso = segundos;
pthread_mutex_unlock(&retardo_mutex);
}
void print_retardo(){
pthread_mutex_lock(&retardo_mutex);
printf("Retardo actual: %d\\n",config->retraso);
pthread_mutex_unlock(&retardo_mutex);
}
void error_comando(char* comando)
{
printf("Comando inexistente %s\\n", comando);
}
void limpiar_pantalla(){
system("clear");
}
void fin_programa(){
continua = 0;
}
int parsear_comando(char * comando, char *** comando_parseado_p){
int i=0,
contador = 0,
letras = 0;
char *tmp = comando,
** comando_parseado=0;
while(comando[i] != '\\0'){
if(comando[i] == 32){
if(letras != 0){
comando_parseado=realloc(comando_parseado,sizeof(char*)*(contador+1));
comando_parseado[contador] = malloc(sizeof(char)*letras+1);
strncpy(comando_parseado[contador],tmp,letras);
comando_parseado[contador][letras] = '\\0';
contador ++;
}
tmp=tmp+letras+1;
letras = 0;
}else letras++;
i++;
}
comando_parseado=realloc(comando_parseado,sizeof(char*)*(contador+1));
comando_parseado[contador]= malloc(sizeof(char)*letras+1);
strncpy(comando_parseado[contador],tmp,letras+1);
*comando_parseado_p = comando_parseado;
return contador+1;
}
void intepretarComando(char* comando){
char **comando_parseado;
int cantidad, i=0;
cantidad=parsear_comando(comando, &comando_parseado);
if(!strcmp(*comando_parseado,"dump")){
switch(cantidad){
case 1:
dump(0,1,1,1);
break;
case 2:
dump(atoi(comando_parseado[1]),1,1,1);
break;
case 3:
dump(atoi(comando_parseado[1]),comando_parseado[2][0]-'0',comando_parseado[2][1]-'0',comando_parseado[2][2]-'0');
break;
default:
error_comando(comando);
}
}else if(!strcmp(*comando_parseado,"flush") && (cantidad == 2))
if(!strcmp(*(comando_parseado+1),"tlb")) flush_tlb();
else if (!strcmp(*(comando_parseado+1),"memory")) flush_memory();
else error_comando(comando);
else if(!strcmp(*comando_parseado,"retardo"))
if(cantidad == 2) retardo(atoi(*(comando_parseado + 1)));
else print_retardo();
else if(!strcmp(*comando_parseado,"clear")) limpiar_pantalla();
else if(!strcmp(*comando_parseado,"exit")) fin_programa();
else error_comando(comando);
for(i=0; i<cantidad; i++){
free(comando_parseado[i]);
}
free(comando_parseado);
}
void handleComandos(){
char * comando;
size_t size_buff=0;
pthread_mutex_init(&continua_mutex,0);
pthread_mutex_lock(&continua_mutex);
while(continua){
comando = 0;
printf("ml-umc>");
getline(&comando,&size_buff,stdin);
comando[strlen(comando)-1]='\\0';
intepretarComando(comando);
free(comando);
}
pthread_mutex_unlock(&continua_mutex);
}
| 1
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER;
void *thr_fn(void *arg) {
int err, signo;
for(;;) {
err = sigwait(&mask, &signo);
if (err != 0) {
err_exit(err, "sigwait failed");
}
switch(signo) {
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&waitloc);
return(0);
default:
printf("unexpected signal %d\\n", signo);
exit(1);
}
}
}
int main(void) {
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) {
err_exit(err, "SIG_BLOCK error");
}
err = pthread_create(&tid, 0, thr_fn, 0);
if (err != 0) {
err_exit(err, "can't create thread");
}
pthread_mutex_lock(&lock);
while(quitflag == 0) {
pthread_cond_wait(&waitloc, &lock);
}
pthread_mutex_unlock(&lock);
quitflag = 0;
if(sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) {
err_sys("SIG_SETMASK error");
}
exit(0);
}
| 0
|
#include <pthread.h>
extern int makethread(void *(*)(void *), void *);
struct to_info
{
void (*to_fn)(void *);
void *to_arg;
struct timespec to_wait;
};
void clock_gettime(int id, struct timespec *tsp)
{
struct timeval tv;
gettimeofday(&tv, 0);
tsp->tv_sec = tv.tv_sec;
tsp->tv_nsec = tv.tv_usec * 1000;
}
void *timeout_helper(void *arg)
{
struct to_info *tip;
tip = (struct to_info *)arg;
nanosleep((ERQ), (0));
(*tip->to_fn)(tip->to_arg);
free(arg);
return 0;
}
void timeout(const struct timespec *when, void (*func)(void *), void *arg)
{
struct timespec now;
struct to_info *tip;
int err;
clock_gettime(0, &now);
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 = makethread(timeout_helper, (void *)tip);
if(err == 0)
return;
else
free(tip);
}
}
(*func)(arg);
}
pthread_mutexattr_t attr;
pthread_mutex_t mutex;
void retry(void *arg)
{
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
}
int main(void)
{
int err, condition, arg;
struct timespec when;
if((err = pthread_mutexattr_init(&attr)) != 0)
err_exit(err, "pthread_mutexattr_init failed");
if((err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) != 0)
err_exit(err, "can't set recursive type");
if((err = pthread_mutex_init(&mutex, &attr)) != 0)
err_exit(err, "can't create recursive mutex");
pthread_mutex_lock(&mutex);
if(condition)
{
clock_gettime(0, &when);
when.tv_sec += 10;
timeout(&when, retry, (void *)((unsigned long)arg));
}
pthread_mutex_unlock(&mutex);
exit(0);
}
| 1
|
#include <pthread.h>
int race;
pthread_mutex_t mutex1;
void* adder(void* r){
int i;
pthread_mutex_lock(&mutex1);
for(i = 0; i < 20000000; i++){
race++;
}
pthread_mutex_unlock(&mutex1);
printf("%d\\n", race);
return 0;
}
void* subtractor(void* r){
int i;
pthread_mutex_lock(&mutex1);
for(i = 0; i < 20000000; i++){
race--;
}
pthread_mutex_unlock(&mutex1);
printf("%d\\n", race);
return 0;
}
int main(){
int counter = 0;
race = 0;
pthread_t thread1, thread2;
pthread_create(&thread1, 0, adder, 0);
pthread_create(&thread2, 0, subtractor, 0);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
return 0;
}
| 0
|
#include <pthread.h>
void aluout_register(void *not_used){
pthread_barrier_wait(&threads_creation);
while(1){
pthread_mutex_lock(&control_sign);
if(!cs.isUpdated){
while(pthread_cond_wait(&control_sign_wait,&control_sign) != 0);
}
pthread_mutex_unlock(&control_sign);
if(cs.invalidInstruction){
pthread_barrier_wait(&update_registers);
pthread_exit(0);
}
pthread_barrier_wait(¤t_cycle);
aluout = alu_result.value;
pthread_barrier_wait(&update_registers);
}
}
| 1
|
#include <pthread.h>
pthread_cond_t condition_alarme=PTHREAD_COND_INITIALIZER ;
pthread_mutex_t mutex_alarme=PTHREAD_MUTEX_INITIALIZER ;
static void* thread_temperature (void *inutile) ;
static void * thread_alarme (void *inutile) ;
int main(void)
{
int limit=5;
pthread_t thr ;
pthread_create (&thr, 0, thread_temperature, 0) ;
pthread_create (&thr, 0, thread_alarme, 0) ;
pthread_exit (0) ;
}
double aleatoire (const int limit)
{
return (((double)rand() / 32767)* limit);
}
static void * thread_temperature (void *inutile)
{
int temperature = 20 ;
while (1) {
temperature += aleatoire(5) -2 ;
fprintf(stdout, " Temperature : %d \\n ", temperature) ;
if ((temperature < 16 )|| (temperature > 24 )) {
pthread_mutex_lock (&mutex_alarme) ;
pthread_cond_signal(&condition_alarme) ;
pthread_mutex_unlock (&mutex_alarme) ;
}
sleep(1) ;
}
return (0) ;
}
static void * thread_alarme (void * inutile)
{
while (1) {
pthread_mutex_lock (&mutex_alarme) ;
pthread_cond_wait (&condition_alarme, &mutex_alarme) ;
pthread_mutex_unlock (&mutex_alarme) ;
fprintf(stdout, " ALARME \\n ") ;
}
return (0) ;
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
void prepare(void){
printf("prepare() lock....\\n");
pthread_mutex_lock(&lock1);
pthread_mutex_lock(&lock2);
}
void parent(void){
printf("parent() ....\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void child(void){
printf("child() ....\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void* thr_fn(void* arg){
printf("thread started ...\\n");
pause();
printf("pause done \\n");
return 0;
}
int main(void){
int err;
pid_t pid;
pthread_t tid;
if((err=pthread_atfork(prepare,parent,child)) != 0)
err_exit(err,"can't install fork handlers");
err = pthread_create(&tid,0,thr_fn,0);
if(err !=0)
err_exit(err,"pthread_create error");
sleep(2);
printf("parent about to fork....\\n");
if((pid=fork()) <0)
err_quit("fork failed");
else if(pid == 0)
printf("child returned from fork \\n");
else
printf("parent returned from fork \\n");
exit(0);
}
| 1
|
#include <pthread.h>
int store_num;
pthread_mutex_t mutex;
pthread_cond_t cond;
void *consumer(void *arg)
{
printf("开始消费\\n");
int need= (int)arg;
pthread_mutex_lock(&mutex);
while(need > store_num)
{
pthread_cond_wait(&cond,&mutex);
}
store_num = store_num - need;
printf("消费者消耗了%d 目前剩余 %d\\n",need,store_num);
pthread_mutex_unlock(&mutex);
}
void *producer(void *arg)
{
int p_num = (int)arg;
pthread_mutex_lock(&mutex);
while(p_num + store_num > 100)
{
printf("生产数量 %d 超过仓库容量 %d 不能生产\\n",p_num,p_num + store_num - 100);
pthread_cond_wait(&cond,&mutex);
}
store_num = store_num + p_num;
printf("生产了 %d 仓库余量 %d\\n",p_num,store_num);
pthread_mutex_unlock(&mutex);
pthread_cond_broadcast(&cond);
}
int main()
{
pthread_t con_id;
pthread_t pro_id;
pthread_t store_id;
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond,0);
store_num = 30;
pthread_create(&con_id,0,(void *)consumer,(void *)10);
pthread_create(&con_id,0,(void *)consumer,(void *)30);
pthread_create(&con_id,0,(void *)consumer,(void *)50);
pthread_create(&pro_id,0,(void *)producer,(void *)10);
pthread_create(&pro_id,0,(void *)producer,(void *)10);
pthread_create(&pro_id,0,(void *)producer,(void *)10);
pthread_create(&pro_id,0,(void *)producer,(void *)10);
pthread_create(&pro_id,0,(void *)producer,(void *)10);
pthread_create(&pro_id,0,(void *)producer,(void *)40);
pthread_create(&pro_id,0,(void *)producer,(void *)80);
sleep(10);
printf("ssssss");
}
| 0
|
#include <pthread.h>
pthread_t tid[2];
int counter;
pthread_mutex_t lock;
void* doSomeThing1(void *arg)
{
printf("%s entering...", __func__);
fflush(stdout);
pthread_mutex_lock(&lock);
printf("%s done\\n", __func__);
unsigned long i = 0;
counter += 1;
printf("\\n Job %d started, tid = %ld\\n", counter, pthread_self());
for(i=0; i<(0xFFFFFFFF);i++);
printf("\\n Job %d finished, tid = %ld\\n", counter, pthread_self());
pthread_mutex_unlock(&lock);
return 0;
}
void* doSomeThing2(void *arg)
{
printf("%s entering...", __func__);
fflush(stdout);
pthread_mutex_lock(&lock);
printf("%s done\\n", __func__);
unsigned long i = 0;
counter += 1;
printf("\\n Job %d started, tid = %ld\\n", counter, pthread_self());
for(i=0; i<(0xFFFFFFFF);i++);
printf("\\n Job %d finished, tid = %ld\\n", counter, pthread_self());
pthread_mutex_unlock(&lock);
return 0;
}
int main(void)
{
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("\\n mutex init failed\\n");
return 1;
}
pthread_create(&tid[0], 0, doSomeThing1, 0);
pthread_create(&tid[1], 0, doSomeThing2, 0);
pthread_join(tid[0], 0);
pthread_join(tid[1], 0);
pthread_mutex_destroy(&lock);
return 0;
}
| 1
|
#include <pthread.h>
int buzzer_on;
int buzz_cnt;
extern pthread_mutex_t mtx;
extern int level;
void* buzzer()
{
int fd;
int buzzer_control = 1;
int null_integer = 0;
int temp = 0;
fd = open("/dev/cnbuzzer",O_RDWR);
if ( fd < 0 )
{
perror("driver (//dev//cnbuzzer) open error.\\n");
exit(1);
}
while(level!=6) {
pthread_mutex_lock(&mtx);
if(temp == level) {
buzzer_on = 1;
temp++;
}
if(buzzer_on==1)
{
printf("I'm in buzzer!!!\\n");
write(fd,&buzzer_control,4);
usleep(500000);
write(fd,&null_integer, 4);
buzzer_on=0;
if(buzzer_control==5)
buzzer_control++;
else if(buzzer_control==12)
buzzer_control=1;
else
buzzer_control=buzzer_control+2;
buzz_cnt++;
}
pthread_mutex_unlock(&mtx);
usleep(100000);
}
close(fd);
return;
}
| 0
|
#include <pthread.h>
void sigHandlerQuit(int);
void *find_file(void *arg);
void *dispatch_executer(void *arg);
int filesSent, filesFound = 0;
pthread_mutex_t mutexTotalTime, retrieved, sent;
int totalTime = 0;
int main() {
srand(time(0));
pthread_mutex_init(&mutexTotalTime, 0);
pthread_mutex_init(&retrieved, 0);
pthread_mutex_init(&sent, 0);
int status;
pthread_t dispatch;
if ((status = pthread_create(&dispatch, 0, dispatch_executer, 0)) != 0) {
fprintf(stderr, "Uh oh...something went wrong creating thread %d: %s\\n",
status, strerror(status));
exit(1);
}
if ((status = pthread_join(dispatch, 0)) != 0) {
fprintf(stderr, "Uh oh...something went wrong joining thread %d: %s\\n",
status, strerror(status));
exit(1);
}
pthread_mutex_destroy(&mutexTotalTime);
pthread_mutex_destroy(&retrieved);
pthread_mutex_destroy(&sent);
return 0;
}
void *dispatch_executer(void *arg) {
signal(SIGINT, sigHandlerQuit);
while (1) {
printf("Enter a file name: \\n");
char *buf = malloc(sizeof(char) * 1024);
if (fgets(buf, 1024, stdin) == 0) {
perror("Uh oh...something went wrong reading input");
exit(1);
}
buf = realloc(buf, sizeof(char) * strlen(buf));
int status;
pthread_t workers;
if ((status = pthread_create(&workers, 0, find_file, (void *) buf)) != 0) {
fprintf(stderr, "thread create error %d: %s\\n", status, strerror(status));
exit(1);
}
if ((status = pthread_detach(workers)) != 0) {
fprintf(stderr, "thread detach error %d: %s\\n", status, strerror(status));
exit(1);
}
pthread_mutex_lock(&retrieved);
filesFound++;
pthread_mutex_unlock(&retrieved);
}
return arg;
}
void *find_file(void *arg) {
char *filename = (char *) arg;
filename[strlen(filename) - 1] = '\\0';
pthread_mutex_lock(&sent);
filesSent++;
pthread_mutex_unlock(&sent);
int randTime = rand();
if ((randTime % 5) == 0) {
randTime = (rand() % 4) + 7;
sleep(randTime);
printf("Found the file %s in %d seconds.\\n", filename, randTime);
} else {
randTime = 1;
sleep(randTime);
printf("Found the file %s in %d second.\\n", filename, randTime);
}
pthread_mutex_lock(&mutexTotalTime);
totalTime += randTime;
pthread_mutex_unlock(&mutexTotalTime);
pthread_exit((void *) arg);
}
void sigHandlerQuit(int sigNum) {
printf(" received. Exiting the program\\n");
printf("The amount of files asked for is: %d\\n", filesSent);
printf("The amount of files found is: %d\\n", filesFound);
if (totalTime == 1) {
printf("The amount of time it took was %d second.\\n", totalTime);
} else {
printf("The amount of time it took was %d seconds.\\n", totalTime);
}
exit(0);
}
| 1
|
#include <pthread.h>
static pthread_t tacho_thread;
static pthread_mutex_t tacho_mutex = PTHREAD_MUTEX_INITIALIZER;
static FILE *logfile;
static char *tacho_dev;
static double tottachodist;
static double totdyndist;
static double rotlen=2.125;
static unsigned int tacholimit=250000;
static int oldtachotimer;
static int olddyntimer;
static int dyncounter;
static int dynpertacho;
static int lastdisplaytime;
static double lastspeed;
static struct timeval lastspeedtime;
static int tacho_active;
static void read_tacho_timings(unsigned char *buf)
{
unsigned int timer;
double speed=0;
timer=((buf[1]*256)+buf[2])*256+buf[3];
if ((buf[0]&0x40)||(buf[0]&0x10)) {
EVT_INIT(evt_tacho_t, EVENT_DYNAMO,evt);
pthread_mutex_lock(&tacho_mutex);
gettimeofday(&lastspeedtime,0);
pthread_mutex_unlock(&tacho_mutex);
evt.head.tv=lastspeedtime;
evt.counter=timer;
distribute_evt(&evt.head);
totdyndist+=(rotlen/28);
dyncounter++;
if ((((timer-lastdisplaytime)&0xffffff)>(1000000/2))) {
fprintf(stderr,"dyn %d %9d %9d us %.1f\\n",dyncounter,timer,((timer-olddyntimer)&0xffffff)*2,
totdyndist);
lastdisplaytime=timer;
}
if (logfile) {
fprintf(logfile,"%d.%03d dyn %d %9d %9d us %.1f\\n",
(int)lastspeedtime.tv_sec,(int)lastspeedtime.tv_usec/1000,
dyncounter,timer,((timer-olddyntimer)&0xffffff)*2,
totdyndist);
}
olddyntimer=timer;
dynpertacho++;
}
if ((buf[0]&0x80)||(buf[0]&0x20)) {
unsigned int timediff=((timer-oldtachotimer)&0xffffff)*2;
if ((timediff>tacholimit)||(dynpertacho>10)) {
EVT_INIT(evt_tacho_t,EVENT_TACHO,evt);
EVT_INIT(evt_speed_t,EVENT_SPEED,evts);
if ((tacholimit==250000) && (timediff<350000)) {
tacholimit=100000;
} else if ((tacholimit==100000) && (timediff>350000)) {
tacholimit=250000;
}
speed=(int)timediff;
speed/=1000000.0;
speed=rotlen/speed;
pthread_mutex_lock(&tacho_mutex);
lastspeed=speed;
gettimeofday(&lastspeedtime,0);
pthread_mutex_unlock(&tacho_mutex);
evt.head.tv=lastspeedtime;
evt.counter=timer;
distribute_evt(&evt.head);
evts.head.tv=lastspeedtime;
evts.speed=speed*100.0;
distribute_evt(&evts.head);
tottachodist+=rotlen;
printf("tacho %9d %9d us %.1f km/h %d %.1f m\\n",timer,timediff,
speed*3.6,dynpertacho,tottachodist);
if (logfile) {
fprintf(logfile,"%d.%03d tacho %9d %9d us %.1f km/h %d %.1f m\\n",
(int)lastspeedtime.tv_sec,(int)lastspeedtime.tv_usec/1000,
timer,timediff,
speed*3.6,dynpertacho,tottachodist);
fflush(logfile);
}
oldtachotimer=timer;
dynpertacho=0;
}
}
}
void *tacho_loop(void *data)
{
unsigned char buf[256];
int l,i;
int pos;
while(1) {
int fd;
if (logfile) {
fprintf(logfile,"opening device\\n");
fflush(logfile);
}
fd=open(tacho_dev,O_RDONLY);
if (fd<0) {
if (logfile) {
fprintf(logfile,"opening device failed\\n");
fflush(logfile);
}
sleep(1);
continue;
}
tacho_active=1;
pos=0;
while((l=read(fd,buf+pos,sizeof(buf)-pos))>0) {
if (buf[0]!=0xfa) {
pos=0;
printf("got crap from %s\\n",tacho_dev);
} else {
pos+=l;
for(i=0;i<=(pos-6);i+=6) {
if (buf[i]==0xfa) {
read_tacho_timings(buf+i+1);
}
}
if (pos!=i) {
memmove(buf,buf+i,pos-i);
pos=pos-i;
} else {
pos=0;
}
}
}
close(fd);
tacho_active=0;
if (logfile) {
fprintf(logfile,"closing device");
}
sleep(2);
}
}
void init_tacho(int argc, char **argv)
{
if (argc>0) {
tacho_dev=argv[0];
if (argc>1)
logfile=fopen(argv[1],"a");
pthread_create(&tacho_thread,0,
tacho_loop,0);
}
}
int tacho_get_speed(float *speed)
{
struct timeval tv;
struct timeval tvs;
if (!tacho_active)
return 0;
pthread_mutex_lock(&tacho_mutex);
tvs=lastspeedtime;
*speed=(float)lastspeed;
pthread_mutex_unlock(&tacho_mutex);
(*speed)*=(3.6/1.852);
gettimeofday(&tv,0);
tv.tv_sec-=tvs.tv_sec;
tv.tv_usec-=tvs.tv_usec;
if (tv.tv_usec < 0) {
tv.tv_sec--;
tv.tv_usec+=1000000;
}
if (tv.tv_sec!=0)
*speed=0;
return 1;
}
| 0
|
#include <pthread.h>
struct buffer_t {
char data[20];
int in;
int out;
pthread_mutex_t mutex;
pthread_cond_t empty;
pthread_cond_t full;
} buffer;
int totalItems = 0;
pthread_t producer[2], consumer[2];
pthread_t terminatorThread;
void *produce(void *tid) {
int i;
for(i=0; i<100; i++) {
printf("producer %ld going to grab the lock\\n", (long)tid);
pthread_mutex_lock(&(buffer.mutex));
while (((buffer.in + 1) % 20 == buffer.out)) {
printf("producer %ld is waiting\\n", (long)tid);
pthread_cond_wait(&(buffer.full), &(buffer.mutex));
}
if ((buffer.in == buffer.out))
pthread_cond_signal(&(buffer.empty));
buffer.data[buffer.in] = rand();
printf("producer %ld inserted an item: %d\\n", (long)tid, buffer.data[buffer.in]);
buffer.in = (buffer.in + 1) % 20;
pthread_mutex_unlock(&(buffer.mutex));
}
printf("producer %ld is done!\\n", (long)tid);
pthread_exit(0);
}
void *consume(void *tid) {
int done = 0;
int i;
while(1) {
printf("consumer %ld will grab the lock\\n", (long)tid);
pthread_mutex_lock(&(buffer.mutex));
if ((totalItems == 100 * 2)) {
done = 1;
printf("consumer %ld done 1\\n", (long)tid);
pthread_mutex_unlock(&(buffer.mutex));
}
else {
while ((buffer.in == buffer.out) && !(totalItems == 100 * 2)) {
printf("consumer %ld waiting\\n", (long)tid);
pthread_cond_wait(&(buffer.empty), &(buffer.mutex));
}
pthread_cond_signal(&(buffer.full));
if ((totalItems == 100 * 2)) {
done = 1;
printf("consumer %ld done 2\\n", (long)tid);
pthread_mutex_unlock(&(buffer.mutex));
}
else {
printf("consumer %ld removing an item: %d count=%d\\n", (long)tid, buffer.data[buffer.out], totalItems);
buffer.out = (buffer.out + 1) % 20;
totalItems++;
if ((totalItems == 100 * 2)) {
printf("consumer %ld is the lucky one!\\n", (long)tid);
done = 1;
for(i=0; i < 2; i++)
pthread_cond_signal(&(buffer.empty));
}
pthread_mutex_unlock(&(buffer.mutex));
}
}
if (done) break;
}
pthread_exit(0);
}
int main(char *argc[], int argv) {
int failed, i;
void *status;
srand(time(0));
pthread_mutex_init(&(buffer.mutex), 0);
pthread_cond_init(&(buffer.empty), 0);
pthread_cond_init(&(buffer.full), 0);
buffer.in = 0;
buffer.out = 0;
for(i=0; i<2; i++) {
failed = pthread_create(&(producer[i]), 0,produce, (void*)(long)i);
if (failed) {
printf("thread_create failed!\\n");
return -1;
}
}
for(i=0; i<2; i++) {
failed = pthread_create(&consumer[i], 0,consume,(void*)(long)i);
if (failed) {
printf("thread_create failed!\\n");
return -1;
}
}
for(i=0; i<2; i++)
pthread_join(producer[i], &status);
for(i=0; i<2; i++)
pthread_join(consumer[i], &status);
pthread_join(terminatorThread, &status);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int buffer[1024];
int count=0;
pthread_mutex_t mutex1;
pthread_mutex_t mutex2;
pthread_mutex_t mutex3;
void *threadFun1(void *arg)
{
int i;
while(1)
{
pthread_mutex_lock(&mutex1);
printf("Thread 1\\n");
count++;
if((count%2)==1)
{
pthread_mutex_unlock(&mutex3);
}
else
{
pthread_mutex_unlock(&mutex2);
}
}
}
void *threadFun2(void *arg)
{
int i;
while(1)
{
pthread_mutex_lock(&mutex2);
printf("Thread 2:%d\\n",count);
pthread_mutex_unlock(&mutex1);
}
}
void *threadFun3(void *arg)
{
int i;
while(1)
{
pthread_mutex_lock(&mutex3);
printf("Thread 3:%d\\n",count);
pthread_mutex_unlock(&mutex1);
}
}
int main()
{
pthread_t tid[3];
int ret=0;
int i;
int t_value[3];
void *(*threadFun[])(void*) =
{threadFun1, threadFun2,threadFun3};
ret = pthread_mutex_init(&mutex1,0);
if(ret!=0)
{
fprintf(stderr, "pthread mutex init error:%s",
strerror(ret));
return 1;
}
ret = pthread_mutex_init(&mutex2,0);
if(ret!=0)
{
fprintf(stderr, "pthread mutex init error:%s",
strerror(ret));
return 1;
}
pthread_mutex_lock(&mutex2);
ret = pthread_mutex_init(&mutex3,0);
if(ret!=0)
{
fprintf(stderr, "pthread mutex init error:%s",
strerror(ret));
return 1;
}
pthread_mutex_lock(&mutex3);
printf("Main thread before pthread create\\n");
for(i=0; i<3; i++)
{
t_value[i]=i;
ret=pthread_create( &(tid[i]), 0,
threadFun[i], (void*)&(t_value[i]));
if(ret!=0)
{
fprintf(stderr, "pthread create error:%s",
strerror(ret));
return 1;
}
}
printf("Main thread after pthread create\\n");
for(i=0; i<3; i++)
{
ret = pthread_join(tid[i],0);
if(ret!=0)
{
fprintf(stderr, "pthread join error:%s",
strerror(ret));
return 2;
}
}
ret = pthread_mutex_destroy(&mutex1);
if(ret!=0)
{
fprintf(stderr, "pthread mutex destroy error:%s",
strerror(ret));
return 1;
}
ret = pthread_mutex_destroy(&mutex2);
if(ret!=0)
{
fprintf(stderr, "pthread mutex destroy error:%s",
strerror(ret));
return 1;
}
ret = pthread_mutex_destroy(&mutex3);
if(ret!=0)
{
fprintf(stderr, "pthread mutex destroy error:%s",
strerror(ret));
return 1;
}
printf("All threads are over!\\n");
return 0;
}
| 0
|
#include <pthread.h>
pthread_t tid[2];
int counter=0;
pthread_cond_t condition1,condition2;
pthread_mutex_t lock1,lock2;
void *mutex_cond_fn1(void *arg)
{
pthread_mutex_lock(&lock1);
unsigned long i=0;
counter+=1;
printf("\\n Job %d has started\\n",counter);
for(i=0;i<(0xffffffff);i++);
printf("\\njob %d has been finished\\n",counter);
pthread_mutex_unlock(&lock2);
return 0;
}
void *mutex_cond_fn2(void *arg)
{
pthread_mutex_lock(&lock2);
unsigned long i=2;
counter+=1;
printf("\\n Job %d has started\\n",counter);
for(i=0;i<(0xffffffff);i++);
printf("\\njob %d has been finished\\n",counter);
pthread_mutex_unlock(&lock1);
return 0;
}
int main(int argc, char *argv[])
{
int i=0;
int error;
if(pthread_mutex_init(&lock1, 0)!=0)
{
perror("Mutex1 initialisation failed!\\n");
exit(1);
}
if(pthread_mutex_init(&lock2, 0)!=0)
{
perror("Mutex2 initialisation failed!\\n");
exit(1);
}
{
error=pthread_create(&(tid[0]), 0, &mutex_cond_fn1, 0);
if(error!=0)
printf("Thread cant be created [%s]",strerror(error));
i++;
}
{
error=pthread_create(&(tid[1]), 0, &mutex_cond_fn2, 0);
if(error!=0)
printf("Thread cant be created [%s]",strerror(error));
i++;
}
pthread_join(tid[0], 0);
pthread_join(tid[1], 0);
pthread_exit(0);
pthread_mutex_destroy(&lock1);
pthread_mutex_destroy(&lock2);
return 0;
}
| 1
|
#include <pthread.h>
const size_t NUMTHREADS = 20;
int done = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* ThreadEntry( void* id )
{
const int myid = (long)id;
int i;
const int workloops = 5;
for( i=0; i<workloops; i++ )
{
printf( "[thread %d] working (%d/%d)\\n", myid, i, workloops );
sleep(1);
}
pthread_mutex_lock( &mutex );
done++;
printf( "[thread %d] done is now %d. Signalling cond.\\n", myid, done );
pthread_cond_signal( &cond );
pthread_mutex_unlock( & mutex );
return 0;
}
int main( int argc, char** argv )
{
printf( "[thread main] starting\\n" );
int t;
pthread_t threads[NUMTHREADS];
for( t=0; t<NUMTHREADS; t++ )
{
pthread_create( &threads[t], 0, ThreadEntry, (void*)(long)t );
}
pthread_mutex_lock( &mutex );
while( done < NUMTHREADS )
{
printf( "[thread main] done is %d which is < %d so waiting on cond\\n", done, (int)NUMTHREADS );
pthread_cond_wait( & cond, & mutex );
printf( "[thread main] wake - cond was signalled.\\n" );
}
printf( "[thread main] done == %d so everyone is done\\n", (int)NUMTHREADS );
pthread_mutex_unlock( & mutex );
return 0;
}
| 0
|
#include <pthread.h>
static char buffer[10];
static unsigned int first;
static unsigned int next;
static int buffer_size;
_Bool send, receive;
int value;
pthread_mutex_t m;
void initLog(int max)
{
buffer_size = max;
first = next = 0;
}
int removeLogElement(void)
{
assert(first>=0);
if (next > 0 && first < buffer_size)
{
first++;
return buffer[first-1];
}
else
{
return -1;
}
}
int insertLogElement(int b)
{
if (next < buffer_size && buffer_size > 0)
{
buffer[next] = b;
next = (next+1)%buffer_size;
assert(next<buffer_size);
}
else
{
return -1;
}
return b;
}
void *t1(void *arg)
{
int i;
for(i=0; i<7; i++)
{
pthread_mutex_lock(&m);
if (send)
{
assert(i==insertLogElement(i));
value=i;
send=0;
receive=1;
}
pthread_mutex_unlock(&m);
}
}
void *t2(void *arg)
{
int i;
for(i=0; i<7; i++)
{
pthread_mutex_lock(&m);
if (receive)
{
assert(removeLogElement()==value);
receive=0;
send=1;
}
pthread_mutex_unlock(&m);
}
}
int main(void) {
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
initLog(10);
send=1;
receive=0;
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 1
|
#include <pthread.h>
void preprocess_rgb(uint8_t * in, uint8_t * out, int width, int height);
void preprocess_ir(uint8_t * in, uint8_t * out, int width, int height);
void * preprocessor(void * args)
{
struct thread_arg * ta = (struct thread_arg *)args;
struct channel * input = ta->input, * output = ta->output;
struct timeval tv;
uint8_t * ibuf_rgb, * obuf_rgb, * ibuf_ir, * obuf_ir;
int full, buf_index;
if(SETUP_STREAMS & SETUP_STREAM_RGB) {
ibuf_rgb = malloc(SETUP_IMAGE_SIZE_RAW_RGB);
obuf_rgb = malloc(SETUP_IMAGE_SIZE_RGB);
}
if(SETUP_STREAMS & SETUP_STREAM_IR) {
ibuf_ir = malloc(SETUP_IMAGE_SIZE_RAW_IR);
obuf_ir = malloc(SETUP_IMAGE_SIZE_IR);
}
while(1) {
tv.tv_sec = 0;
tv.tv_usec = SETUP_POLL_DELAY;
select(0, 0, 0, 0, &tv);
if(!sem_trywait(&input->full)) {
pthread_mutex_lock(&input->lock);
sem_getvalue(&input->full, &full);
buf_index = (unsigned int)((input->serial - full) % SETUP_BUFFER_LENGTH_G2P);
if(SETUP_STREAMS & SETUP_STREAM_RGB) {
memcpy(ibuf_rgb, input->rgb[buf_index].data, SETUP_IMAGE_SIZE_RAW_RGB);
}
if(SETUP_STREAMS & SETUP_STREAM_IR) {
memcpy(ibuf_ir, input->ir[buf_index].data, SETUP_IMAGE_SIZE_RAW_IR);
}
sem_post(&input->empty);
pthread_mutex_unlock(&input->lock);
if(SETUP_STREAMS & SETUP_STREAM_RGB) {
preprocess_rgb(ibuf_rgb, obuf_rgb, SETUP_IMAGE_WIDTH_RGB, SETUP_IMAGE_HEIGHT_RGB);
}
if(SETUP_STREAMS & SETUP_STREAM_IR) {
preprocess_ir(ibuf_ir, obuf_ir, SETUP_IMAGE_WIDTH_IR, SETUP_IMAGE_HEIGHT_IR);
}
if(sem_trywait(&output->empty)) {
} else {
pthread_mutex_lock(&output->lock);
output->serial++;
if(SETUP_STREAMS & SETUP_STREAM_RGB) {
output->rgb[output->serial % SETUP_BUFFER_LENGTH_P2C].size = SETUP_IMAGE_SIZE_RGB;
memcpy(output->rgb[output->serial % SETUP_BUFFER_LENGTH_P2C].data, obuf_rgb, SETUP_IMAGE_SIZE_RGB);
}
if(SETUP_STREAMS & SETUP_STREAM_IR) {
output->ir[output->serial % SETUP_BUFFER_LENGTH_P2C].size = SETUP_IMAGE_SIZE_IR;
memcpy(output->ir[output->serial % SETUP_BUFFER_LENGTH_P2C].data, obuf_ir, SETUP_IMAGE_SIZE_IR);
}
sem_post(&output->full);
pthread_mutex_unlock(&output->lock);
}
}
}
return 0;
}
void preprocess_rgb(uint8_t * in, uint8_t * out, int width, int height)
{
int x,y;
uint8_t *dst = out;
uint8_t *prevLine;
uint8_t *curLine;
uint8_t *nextLine;
uint32_t hVals;
uint32_t vSums;
uint8_t hSum;
uint8_t yOdd;
curLine = in;
nextLine = curLine + width;
for (y = 0; y < height; ++y) {
if ((y > 0) && (y < height-1))
prevLine = curLine - width;
else if (y == 0)
prevLine = nextLine;
else
nextLine = prevLine;
hVals = (*(curLine++) << 8);
hVals |= (*curLine << 16);
vSums = ((*(prevLine++) + *(nextLine++)) << 7) & 0xFF00;
vSums |= ((*prevLine + *nextLine) << 15) & 0xFF0000;
yOdd = y & 1;
for (x = 0; x < width-1; ++x) {
hVals |= *(curLine++);
vSums |= (*(prevLine++) + *(nextLine++)) >> 1;
hSum = ((uint8_t)(hVals >> 16) + (uint8_t)(hVals)) >> 1;
if (yOdd == 0) {
if ((x & 1) == 0) {
*(dst++) = hSum;
*(dst++) = hVals >> 8;
*(dst++) = vSums >> 8;
} else {
*(dst++) = hVals >> 8;
*(dst++) = (hSum + (uint8_t)(vSums >> 8)) >> 1;
*(dst++) = ((uint8_t)(vSums >> 16) + (uint8_t)(vSums)) >> 1;
}
} else {
if ((x & 1) == 0) {
*(dst++) = ((uint8_t)(vSums >> 16) + (uint8_t)(vSums)) >> 1;
*(dst++) = (hSum + (uint8_t)(vSums >> 8)) >> 1;
*(dst++) = hVals >> 8;
} else {
*(dst++) = vSums >> 8;
*(dst++) = hVals >> 8;
*(dst++) = hSum;
}
}
hVals <<= 8;
vSums <<= 8;
}
hVals |= (uint8_t)(hVals >> 16);
vSums |= (uint8_t)(vSums >> 16);
hSum = (uint8_t)(hVals);
if (yOdd == 0) {
if ((x & 1) == 0) {
*(dst++) = hSum;
*(dst++) = hVals >> 8;
*(dst++) = vSums >> 8;
} else {
*(dst++) = hVals >> 8;
*(dst++) = (hSum + (uint8_t)(vSums >> 8)) >> 1;
*(dst++) = vSums;
}
} else {
if ((x & 1) == 0) {
*(dst++) = vSums;
*(dst++) = (hSum + (uint8_t)(vSums >> 8)) >> 1;
*(dst++) = hVals >> 8;
} else {
*(dst++) = vSums >> 8;
*(dst++) = hVals >> 8;
*(dst++) = hSum;
}
}
}
}
void preprocess_ir(uint8_t * in, uint8_t * out, int width, int height)
{
int vw = 10, n = width * height;
uint32_t buffer = 0;
int bitsIn = 0;
while (n--) {
while (bitsIn < vw) {
buffer = (buffer << 8) | *(in++);
bitsIn += 8;
}
bitsIn -= vw;
*(out++) = buffer >> (bitsIn + vw - 8);
}
}
| 0
|
#include <pthread.h>
int food = 5;
int monitor = 1;
int state[5];
pthread_mutex_t monitor_mutex;
pthread_cond_t resource_ready;
pthread_t philo[5];
void *philosopher (void *num);
void get_chopsticks (int, int, int);
void test (int);
void put_chopsticks (int, int, int);
int main (int argc, char **argv)
{
if (argc == 2)
food = atoi (argv[1]);
int i;
pthread_mutex_init (&monitor_mutex, 0);
pthread_cond_init (&resource_ready, 0);
for (i = 0; i < 5; i++)
pthread_create (&philo[i], 0, philosopher, (void *)i);
for (i = 0; i < 5; i++)
pthread_join (philo[i], 0);
return 0;
}
void *philosopher (void *num)
{
int id;
int i, left_chopstick, right_chopstick, f;
id = (int)num;
state[id] = 0;
printf ("Philosopher %d is thinking.\\n", id);
right_chopstick = id;
left_chopstick = (id + 1)%5;
while (food > 0)
{
get_chopsticks (id, left_chopstick, right_chopstick);
sleep(1);
}
return (0);
}
void get_chopsticks (int phil, int c1, int c2)
{
pthread_mutex_lock (&monitor_mutex);
state[phil] = monitor;
test(phil);
if (state[phil] != 2)
{
pthread_cond_wait (&resource_ready, &monitor_mutex);
printf ("Philosopher %d is now eating\\n", phil);
food--;
if (food == 0)
{
printf ("There is no more food on the table. Program exit\\n");
pthread_mutex_destroy(&monitor_mutex);
pthread_cond_destroy(&resource_ready);
exit(1);
}
printf ("There are/is %d food(s) left\\n", food);
put_chopsticks (phil, c1, c2);
sleep(1);
}
pthread_mutex_unlock (&monitor_mutex);
}
void test (int phil)
{
if ((state[(phil+4)%5] != 2)&& (state[phil] == 1))
{
state[phil] = 2;
pthread_cond_signal (&resource_ready);
}
}
void put_chopsticks (int phil, int c1, int c2)
{
state[phil] = 0;
test ((phil+4)%5);
test ((phil+1)%5);
}
| 1
|
#include <pthread.h>
pthread_mutex_t updatelock;
pthread_cond_t finished;
int numWorkers;
int numArrived = 0;
int final_sum;
int final_max, final_maxi, final_maxj;
int final_min, final_mini, final_minj;
int final_num_workers;
double start_time, end_time;
int size, stripSize;
int matrix[10000][10000];
void *Worker(void *);
void set_values(int, int, int, int, int, int);
void set_max(int, int, int);
void set_min(int, int, int);
void update_values(int sum, int max, int maxi, int maxj, int min, int mini, int minj) {
pthread_mutex_lock(&updatelock);
int id = rand()%1000;
final_sum += sum;
final_num_workers++;
set_values(max, maxi, maxj, min, mini, minj);
if (final_num_workers == numWorkers)
pthread_cond_broadcast(&finished);
pthread_mutex_unlock(&updatelock);
}
void set_values(int max, int maxi, int maxj, int min, int mini, int minj) {
if (max > final_max)
set_max(max, maxi, maxj);
if (min < final_min)
set_min(min, mini, minj);
}
void set_max(int max, int maxi, int maxj) {
final_max = max;
final_maxi = maxi;
final_maxj = maxj;
}
void set_min(int min, int mini, int minj) {
final_min = min;
final_mini = mini;
final_minj = minj;
}
double read_timer() {
static bool initialized = 0;
static struct timeval start;
struct timeval end;
if( !initialized )
{
gettimeofday( &start, 0 );
initialized = 1;
}
gettimeofday( &end, 0 );
return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec);
}
void print_result() {
printf("The total is %d\\n", final_sum);
printf("The max is %d at %d,%d\\n", final_max, final_maxi, final_maxj);
printf("The min is %d at %d,%d\\n", final_min, final_mini, final_minj);
printf("The execution time is %g sec\\n", end_time - start_time);
}
int main(int argc, char *argv[]) {
int i, j;
long l;
pthread_attr_t attr;
pthread_t workerid[10];
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
pthread_mutex_init(&updatelock, 0);
pthread_cond_init(&finished, 0);
final_num_workers = 0;
final_min = 1000;
size = (argc > 1)? atoi(argv[1]) : 10000;
numWorkers = (argc > 2)? atoi(argv[2]) : 10;
if (size > 10000) size = 10000;
if (numWorkers > 10) numWorkers = 10;
stripSize = size/numWorkers;
srand ( time(0) );
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
matrix[i][j] = rand()%99;
}
}
start_time = read_timer();
for (l = 0; l < numWorkers; l++)
pthread_create(&workerid[l], &attr, Worker, (void *) l);
pthread_cond_wait(&finished, &updatelock);
end_time = read_timer();
print_result();
pthread_exit(0);
}
void *Worker(void *arg) {
long myid = (long) arg;
int total, i, j, first, last, max, maxi, maxj, min, mini, minj;
first = myid*stripSize;
last = (myid == numWorkers - 1) ? (size - 1) : (first + stripSize - 1);
total = 0;
max = -1000;
maxi = 0;
maxj = 0;
min = 1000;
mini = 0;
minj = 0;
for (i = first; i <= last; i++) {
for (j = 0; j < size; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
maxi = i;
maxj = j;
}
if (matrix[i][j] < min) {
min = matrix[i][j];
mini = i;
minj = j;
}
total += matrix[i][j];
}
}
update_values(total, max, maxi, maxj, min, mini, minj);
}
| 0
|
#include <pthread.h>
pthread_cond_t my_cond;
pthread_mutex_t my_mutex;
void*
my_thread_routine(void *arg)
{
int my_id = (int)arg;
pthread_mutex_lock(&my_mutex);
pthread_cond_wait(&my_cond, &my_mutex);
pthread_mutex_unlock(&my_mutex);
while(1)
{
pthread_testcancel();
printf("%d\\n", my_id);
}
pthread_exit(0);
}
volatile int main_can_run;
void
sig_alrm_h(int sno)
{
main_can_run = 0;
}
int
main(int argc, char *argv[])
{
int no_threads, my_sleep_time;
int i;
pthread_t *my_threads;
int init_main_loop = 999999;
if(argc < 3)
{
printf("wakeup_test <no_threads> <time>\\n");
return 2;
}
no_threads = strtoul(argv[1], 0, 10);
my_sleep_time = strtoul(argv[2], 0, 10);
my_threads = malloc(sizeof(pthread_t)*no_threads);
for(i = 0; i <no_threads; i++)
{
if(pthread_create(my_threads + i, 0, my_thread_routine, (void *)i+1))
{
perror("pthread_create:");
}
}
signal(SIGALRM, sig_alrm_h);
nice(-5);
printf("Going to wake up all the threads\\n");
sleep(1);
while(init_main_loop--);
alarm(my_sleep_time);
struct timespec ts1, ts2;
clock_gettime(CLOCK_MONOTONIC, &ts1);
pthread_cond_broadcast(&my_cond);
clock_gettime(CLOCK_MONOTONIC, &ts2);
main_can_run = 1;
while(main_can_run)
{
printf("0\\n");
}
printf("Marking END\\n");
for(i = 0; i < no_threads; i++)
{
pthread_cancel(my_threads[i]);
}
for(i = 0; i < no_threads; i++)
{
pthread_join(my_threads[i], 0);
}
printf("Time for broadcast = %lu\\n", ((ts2.tv_sec*1000000000 + ts2.tv_nsec) - (ts1.tv_sec*1000000000 + ts2.tv_nsec))/1000000);
return 0;
}
| 1
|
#include <pthread.h>
int lock_count;
task_t lock_task = 0;
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
pthread_spinlock_t spinlock;
pthread_mutex_t mlock;
void test_spin() {
pthread_spin_lock(&spinlock);
pthread_spin_unlock(&spinlock);
}
void test_mutex() {
pthread_mutex_lock(&mlock);
pthread_mutex_unlock(&mlock);
}
void test_rdlock() {
pthread_rwlock_rdlock(&rwlock);
pthread_rwlock_unlock(&rwlock);
}
void *func(void *arg) {
int i;
for (i=0; i<lock_count; i++) {
lock_task();
}
return 0;
}
int main(int argc, char ** argv)
{
int i, opt;
int lock_worker_num = 1000000;
struct timeval start;
struct timeval end;
struct timeval diff;
double time_total;
lock_task = test_rdlock;
lock_count = 1000000;
while ((opt = getopt(argc, argv, "w:c:t:")) != -1) {
switch(opt) {
case 'w':
lock_worker_num = atoi(optarg);
if (lock_worker_num > 128) {
fprintf(stderr, "Too many workers %d\\n", lock_worker_num);
exit(2);
}
break;
case 'c':
lock_count = atoi(optarg);
break;
case 't':
if (strcmp(optarg, "rdlock") == 0) {
lock_task = test_rdlock;
} else if (strcmp(optarg, "mutex") == 0){
lock_task = test_mutex;
} else if (strcmp(optarg, "spin") == 0){
lock_task = test_spin;
} else {
fprintf(stderr,
"Unknown arg %s for option %c\\n"
"Usage: %s {-w number_of_worker} {-c lock_count} {-t rdlock|mutex|spin}\\n",
optarg, opt, argv[0]);
exit(1);
}
break;
default:
fprintf(stderr,
"Unknown option %c\\n"
"Usage: %s {-w number_of_worker} {-c lock_count} {-t rdlock|mutex|spin}\\n",
opt, argv[0]);
exit(1);
break;
}
}
pthread_mutex_init(&mlock, 0);
pthread_spin_init(&spinlock, PTHREAD_PROCESS_PRIVATE);
pthread_t workers[128];
gettimeofday(&start, 0);
for (i=0; i<lock_worker_num; i++) {
pthread_create(&workers[i], 0, func, (void *) 0);
}
for (i=0; i<lock_worker_num; i++) {
pthread_join(workers[i], 0);
}
gettimeofday(&end, 0);
timersub(&end, &start, &diff);
time_total = diff.tv_sec + diff.tv_usec / 1000000.0;
printf("%.2lf\\n", (lock_worker_num * lock_count) / time_total / 1000000.0f);
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
void *Tackle(void *Dummy) {
extern pthread_mutex_t Mutex;
printf("Waiting for the snap\\n");
pthread_mutex_lock(&Mutex);
pthread_mutex_unlock(&Mutex);
printf("Tackle!!\\n");
return(0);
}
int main(int argc,char *argv[]) {
extern pthread_mutex_t Mutex;
int Index;
pthread_t NewThread;
pthread_mutex_init(&Mutex,0);
pthread_mutex_lock(&Mutex);
for (Index=0;Index<atoi(argv[1]);Index++) {
if (pthread_create(&NewThread,0,Tackle,0) != 0) {
perror("Creating thread");
exit(1);
}
if (pthread_detach(NewThread) != 0) {
perror("Detaching thread");
exit(1);
}
}
fgetc(stdin);
pthread_mutex_unlock(&Mutex);
printf("Exiting the main program, leaving the threads running\\n");
pthread_exit(0);
}
pthread_mutex_t Mutex;
| 1
|
#include <pthread.h>
pthread_mutex_t garfo[5];
int pratadas;
void* filosofo(void *arg) {
int i;
i=*((int*)arg);
while(1) {
printf("Filosofo %d pensando!!!\\n",i);
sleep(rand()%3);
pthread_mutex_lock(&garfo[i]);
pthread_mutex_lock(&garfo[(i+(5 -1))%5]);
printf("Filosofo %d comendo com garfos %d e %d!!!\\n",i,i,(i+(5 -1))%5);
pratadas++;
printf("Ja foram %d pratadas de macarrão.\\n\\n",pratadas);
sleep(rand()%3);
pthread_mutex_unlock(&garfo[i]);
pthread_mutex_unlock(&garfo[(i+(5 -1))%5]);
}
pthread_exit(0);
}
int main(int argc, char **argv) {
pthread_t filosofos[5];
int codigo_de_erro, i, id[5];
pratadas=0;
for(i=0;i<5;i++) {
pthread_mutex_init(&garfo[i], 0);
id[i]=i;
}
for(i=0;i<5;i++) {
codigo_de_erro = pthread_create(&filosofos[i], 0, filosofo, (void*)&id[i]);
if(codigo_de_erro != 0) {
printf("Erro na criação de thread filha, Codigo de erro %d\\n", codigo_de_erro);
exit(1);
}
}
for(i=0;i<5;i++) {
pthread_join(filosofos[i], 0);
}
return 0;
}
| 0
|
#include <pthread.h>
static int *volatile global_ptr;
static pthread_mutex_t mux = PTHREAD_MUTEX_INITIALIZER;
static void *
thr_main(void *ign)
{
while (1) {
int *p;
pthread_mutex_lock(&mux);
STOP_ANALYSIS();
p = global_ptr;
if (p) {
p = global_ptr;
*p = 5;
}
STOP_ANALYSIS();
pthread_mutex_unlock(&mux);
read_cntr++;
STOP_ANALYSIS();
}
return 0;
}
int
main()
{
pthread_t thr;
int forever = 0;
pthread_create(&thr, 0, thr_main, 0);
time_t start_time = time(0);
if (getenv("SOS22_RUN_FOREVER"))
forever = 1;
int t;
while (forever || time(0) < start_time + 10) {
STOP_ANALYSIS();
global_ptr = &t;
STOP_ANALYSIS();
usleep(1000000);
pthread_mutex_lock(&mux);
STOP_ANALYSIS();
global_ptr = 0;
STOP_ANALYSIS();
pthread_mutex_unlock(&mux);
write_cntr++;
}
printf("Survived, %d read events and %d write events\\n", read_cntr, write_cntr);
return 0;
}
| 1
|
#include <pthread.h>
void* deposit(void* data);
struct account
{
char name[20];
int balance;
};
struct account yac={"Gokhan",100};
pthread_mutex_t lock;
int main(int argc, char const *argv[])
{
int i,n;
n=6;
pthread_t tid[n];
int deposit_amount[n];
deposit_amount[0]=1000;
deposit_amount[1]=2500;
deposit_amount[2]=2000;
deposit_amount[3]=1500;
deposit_amount[4]=4000;
deposit_amount[5]=7500;
for (int i = 0; i < n; ++i)
pthread_create(&tid[i],0,&deposit,(void*)&deposit_amount[i]);
for (int i = 0; i < n; ++i)
pthread_join(tid[i],0);
printf("---------RESULT\\n Account Owner:%s,balance%d",yac.name,yac.balance);
return 0;
}
int ReturnValue(int temp1)
{
int temp2;
for(temp2=0;temp2<1000000;temp2++);
return temp1;
}
void* deposit(void* data)
{
int amount=*((int*)data);
pthread_mutex_lock(&lock);
printf("Account Owner:%s,Current Balance:%d \\n",yac.name,yac.balance);
printf("deposit işlemi gerçekleştiriliyor....%d\\n",amount);
yac.balance +=ReturnValue(amount);
printf("Account Owner:%s,Updated Balance:%d \\n\\n",yac.name,yac.balance );
pthread_mutex_unlock(&lock);
return(void*)0;
}
| 0
|
#include <pthread.h>
static pthread_key_t key;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static void thread_init(void) {
pthread_key_create(&key, free);
}
int putenv_r(char *env) {
int err, envlen, ret = -1;
char *envbuf;
sigset_t mask, oldmask;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0)
err_exit(err, "SIG_BLOCK error");
pthread_once(&init_done, thread_init);
pthread_mutex_lock(&lock);
envbuf = pthread_getspecific(key);
if(envbuf == 0) {
envbuf = malloc(ARG_MAX);
if(envbuf == 0) {
pthread_mutex_unlock(&lock);
return ret;
}
pthread_setspecific(key, envbuf);
}
envlen = strlen(env);
strncpy(envbuf, env, envlen + 1);
ret = putenv(envbuf);
pthread_mutex_unlock(&lock);
if((err = pthread_sigmask(SIG_SETMASK, &oldmask, 0)) != 0)
err_exit(err, "SIG_SETMASK error");
return ret;
}
int main(void) {
char buf[128];
return 0;
}
| 1
|
#include <pthread.h>
char buffer[100][100];
pthread_t ctid[10];
pthread_t ptid[5];
FILE *fpprod,*fpcons;
pthread_mutex_t mutex;
sem_t full,empty;
int counter,flag;
void *prod(void *arg);
void *cons(void *arg);
void initialize();
void insert_item();
void delete_item();
char switchBuffer();
void strrev(char str[]);
void add_in_buffer(char str[]);
int main()
{
initialize();
int i,rv;
for (i = 0;i < 5;i++)
{
rv = pthread_create(&ptid[i],0,prod,0);
if (rv)
{
printf("ERROR; return code from pthread_create() is %d\\n", rv);
exit(-1);
}
}
for (i = 0;i < 10;i++)
{
rv = pthread_create(&ctid[i],0,cons,0);
if (rv)
{
printf("ERROR; return code from pthread_create() is %d\\n", rv);
exit(-1);
}
}
sleep(2);
fclose(fpprod);
fclose(fpcons);
}
void initialize()
{
fpprod = fopen("input.txt","r");
fpcons = fopen("output.txt","w");
pthread_mutex_init(&mutex,0);
sem_init(&empty,0,100);
sem_init(&full,0,0);
counter = 0;
flag =0;
}
void *prod(void *arg)
{
while(1)
{
sem_wait(&empty);
pthread_mutex_lock(&mutex);
insert_item();
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void *cons(void *arg)
{
while(1)
{
sem_wait(&full);
pthread_mutex_lock(&mutex);
delete_item();
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
void insert_item()
{
if(feof(fpprod))
return;
int i;
char ch,result[100];
ch = fgetc(fpprod);
i=0;
while(ch!='\\n'&&ch!=EOF)
{
result[i++]=ch;
ch = fgetc(fpprod);
}
result[i++]='\\0';
strrev(result);
add_in_buffer(result);
counter++;
return;
}
void delete_item()
{
int i;
char str[100];
if (counter>0)
{
for (i = 0;i<100;i++)
{
str[i]=buffer[0][i];
}
switchBuffer();
fputs(str,fpcons);
fputc('\\n',fpcons);
}
}
char switchBuffer()
{
int i,j;
for (i =0 ;i<counter;i++)
{
for(j=0;j<100;j++)
{
buffer[i][j]=buffer[i+1][j];
}
}
counter--;
}
void strrev(char str[])
{
char temp;
int len = strlen(str);
int i;
for (i=0;i<len/2;i++)
{
temp = str[len-i-1];
str[len -i -1]=str[i];
str[i]= temp;
}
}
void add_in_buffer(char str[])
{
int i;
for (i=0;i<100;i++)
{
buffer[counter][i]=str[i];
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
void *thread_worker(void *);
void critical_section(int thread_num, int i);
int main(int argc , char * argv[]) {
int rtn, i;
pthread_t pthread_id = 0;
rtn = pthread_create(&pthread_id, 0, thread_worker, 0);
if(rtn == -1) {
printf("pthread_create ERROR!\\n");
return -1;
}
for(i = 0; i < 10000; ++i) {
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2);
critical_section(1, i);
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
}
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
pause();
return 0;
}
void *thread_worker(void *p) {
int i;
for(i = 0 ; i < 10000; i++) {
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2);
critical_section(2, i);
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
}
}
void critical_section(int thread_num, int i) {
printf("Thread %d: %d\\n",thread_num, i);
}
| 1
|
#include <pthread.h>
int count = 0;
Turn turn = None;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
void *even (void *args)
{
while(1)
{
pthread_mutex_lock(&lock);
while(turn != Even)
pthread_cond_wait(&condition, &lock);
printf("even %d\\n", count++);
turn = Odd;
pthread_cond_broadcast(&condition);
pthread_mutex_unlock(&lock);
}
}
void *odd (void *args)
{
while(1)
{
pthread_mutex_lock(&lock);
while(turn != Odd)
pthread_cond_wait(&condition, &lock);
printf("odd %d\\n", count++);
turn = Even;
pthread_cond_broadcast(&condition);
pthread_mutex_unlock(&lock);
}
}
int main ()
{
char buf[32];
pthread_t t1,t2;
pthread_create(&t2, 0, odd, 0);
pthread_create(&t1, 0, even, 0);
sleep(1);
pthread_mutex_lock(&lock);
printf("Start\\n");
sleep(1);
turn = Even;
pthread_cond_broadcast(&condition);
pthread_mutex_unlock(&lock);
printf("Enter \\"end\\" to end...\\n");
while(strcmp(gets(buf), "end") != 0);
return 0;
}
| 0
|
#include <pthread.h>
double *a = (double *) malloc (1000000 * sizeof(double));
double *warehouse = a;
pthread_mutex_t mutexsum = PTHREAD_MUTEX_INITIALIZER;
pthread_barrier_t barr;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
double sum =0.0;
static struct timeval start_time;
static void start_timer()
{
gettimeofday(&start_time, 0);
}
static double end_timer()
{
struct timeval end_time;
gettimeofday(&end_time, 0);
return (end_time.tv_sec-start_time.tv_sec)*1000 + (end_time.tv_usec-start_time.tv_usec)/1000.0;
}
void * producers(void* thread_id)
{
long ID = (long) thread_id;
int chunk = 1000000/2;
srand(86456);
double maxr = (double)32767;
double temp = rand();
for(int i = (ID*chunk); i <= chunk*(ID+1); i++)
{
*(warehouse+i) = temp/maxr;
}
}
void* consumers(void * thread_ID)
{
long ID = (long)thread_ID;
int chunk = 1000000/2;
for(int i = (ID*chunk); i < chunk*(ID+1); i++)
{
pthread_mutex_lock (&mutexsum);
sum += *(warehouse+i);
pthread_mutex_unlock (&mutexsum);
}
}
int main()
{
void *status;
int rc;
int t =0;
if(pthread_barrier_init(&barr, 0, 2))
{
printf("Could not create a barrier\\n");
return -1;
}
start_timer();
pthread_t * thread = (pthread_t *)malloc(sizeof(pthread_t)*2);
for(t =0; t<2; t++)
{
rc = pthread_create(&thread[t], 0, producers, (void *)t);
}
for (int i = 0; i < 2; i++)
{
pthread_join(thread[i], &status);
}
for(t =0; t<2; t++)
{
rc = pthread_create(&thread[t], 0, consumers, (void *)t);
}
for (int i = 0; i < 2; i++)
{
pthread_join(thread[i], &status);
}
printf("With %d thread and %.4lf milliseconds, the sum is %.4lf.\\n", 2, end_timer(), sum);
return 0;
}
| 1
|
#include <pthread.h>
int TOTAL = 0;
pthread_mutex_t lock;
void * Count(void * a)
{
pthread_mutex_lock(&lock);
int i, tmp;
for(i = 0; i < 1000000; i++)
{
tmp = TOTAL;
tmp = tmp+1;
TOTAL = tmp;
}
pthread_mutex_unlock(&lock);
}
int main(int argc, char * argv[])
{
pthread_t tid1, tid2;
if(pthread_mutex_init(&lock, 0) != 0)
{
printf("\\n ERROR creating mutex");
exit(1);
}
if(pthread_create(&tid1, 0, Count, 0))
{
printf("\\n ERROR creating thread 1");
exit(1);
}
if(pthread_create(&tid2, 0, Count, 0))
{
printf("\\n ERROR creating thread 2");
exit(1);
}
if(pthread_join(tid1, 0))
{
printf("\\n ERROR joining thread");
exit(1);
}
if(pthread_join(tid2, 0))
{
printf("\\n ERROR joining thread");
exit(1);
}
pthread_mutex_destroy(&lock);
if (TOTAL < 2 * 1000000)
printf("\\n BOOM! TOTAL is [%d], should be %d\\n\\n", TOTAL, 2*1000000);
else
printf("\\n OK! TOTAL is [%d]\\n\\n", TOTAL);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
void *record_fun()
{
int cmd;
while(1)
{
pthread_mutex_lock(&mutex_record);
pthread_cond_wait(&cond_record,&mutex_record);
cmd = msg.cmd;
pthread_mutex_unlock(&mutex_record);
switch(cmd)
{
case RECORD_ON:
system("killall mjpg_streamer");
usleep(500);
system("ffmpeg -f video4linux2 -s 320*240 -r 10 -i /dev/video0 /motion/photo/videoR.avi &");
break;
case RECORD_OFF:
system("killall ffmpeg");
usleep(1000000);
system("mjpg_streamer -i \\"/mjpg/input_uvc.so -y\\" -o \\"/mjpg/output_http.so -w /www\\" &");
break;
case RECORD_DEL:
system("rm -rf /var/www/motion/photo/*.jpg");
break;
case RECORD_RESET:
system("killall mjpg_streamer");
system("killall ffmpeg");
usleep(1000000);
system("mjpg_streamer -i \\"/mjpg/input_uvc.so -y\\" -o \\"/mjpg/output_http.so -w /www\\" &");
break;
default:
break;
}
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
void * smoker1(void * arg);
void * smoker2(void * arg);
void * smoker3(void * arg);
void * putMaterials(void * arg);
void smoke(int i);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int * buffer;
int main(){
srand(time(0));
pthread_t * tids = (pthread_t*)malloc(3*sizeof(pthread_t));
int i;
buffer = (int *) malloc(2*sizeof(int));
*buffer = 0;
*(buffer + 1) = 0;
pthread_t * agent;
pthread_create(agent,0,putMaterials,(void*)0);
pthread_create(tids,0,smoker1,(void*)1);
pthread_create((tids+1),0,smoker2,(void*)2);
pthread_create((tids+2),0,smoker3,(void*)3);
pthread_join(*(tids),0);
pthread_join(*(tids+1),0);
pthread_join(*(tids+2),0);
pthread_join(*agent,0);
free(tids);
return 0;
}
void * putMaterials(void * arg){
int * materials = (int *) malloc(3 * sizeof(int));
int number;
while(1){
while(*buffer == 0 && *(buffer+1) == 0)
sleep(3);
pthread_mutex_lock(&mutex);
*buffer = rand() % 3;
number = rand() % 3;
while(number == *buffer)
number=rand() % 3;
*(buffer + 1) = number;
pthread_mutex_unlock(&mutex);
}
free(materials);
pthread_exit(0);
}
void * smoker1(void * arg){
while(1){
while(!pthread_mutex_trylock(&mutex)){
if(*buffer == 2 && *(buffer+1) == 3 || *buffer == 3 && *(buffer+1) == 2){
*buffer = 0;
*(buffer+1) == 0;
int i = (int) arg;
printf("Smoker No. %d is taking materials.\\n",i);
printf("Smoker No. %d is smoking.\\n",i);
sleep(3);
pthread_mutex_unlock(&mutex);
}
}
}
pthread_exit(0);
}
void * smoker2(void * arg){
while(1){
while(!pthread_mutex_trylock(&mutex)){
if(*buffer == 1 && *(buffer+1) == 2 || *buffer == 2 && *(buffer+1) == 1){
*buffer = 0;
*(buffer+1) == 0;
int i = (int) arg;
printf("Smoker No. %d is taking materials.\\n",i);
printf("Smoker No. %d is smoking.\\n",i);
sleep(3);
pthread_mutex_unlock(&mutex);
}
}
}
pthread_exit(0);
}
void * smoker3(void * arg){
while(1){
while(!pthread_mutex_trylock(&mutex)){
if(*buffer == 1 && *(buffer+1) == 3 || *buffer == 3 && *(buffer+1) == 1){
*buffer = 0;
*(buffer+1) == 0;
int i = (int) arg;
printf("Smoker No. %d is taking materials.\\n",i);
printf("Smoker No. %d is smoking.\\n",i);
sleep(3);
pthread_mutex_unlock(&mutex);
}
}
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock;
int value;
}SharedInt;
sem_t sem;
SharedInt* sip;
void *funcWCritSec(int* v2) {
pthread_mutex_lock(&(sip->lock));
sip->value = sip->value + *v2;
if(sip->value < 3) {
sip->value = sip->value + *v2;
pthread_mutex_unlock(&(sip->lock));
sem_post(&sem);
return 0;
}
sip->value = sip->value - *v2;
pthread_mutex_unlock(&(sip->lock));
sem_post(&sem);
}
int main() {
sem_init(&sem, 0, 0);
SharedInt si;
sip = &si;
sip->value = 0;
int v2 = 1;
pthread_mutex_init(&(sip->lock), 0);
pthread_t thread1;
pthread_t thread2;
pthread_create (&thread1,0,funcWCritSec,&v2);
pthread_create (&thread2,0,funcWCritSec,&v2);
sem_wait(&sem);
sem_wait(&sem);
pthread_mutex_destroy(&(sip->lock));
sem_destroy(&sem);
printf("%d\\n", sip->value);
return sip->value-2;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_t tid[4];
int s_lohan=100, s_kepiting=100;
void cek_game_status(){
if (s_lohan <=0 || s_kepiting <=0 || s_lohan>100 || s_kepiting >100){
printf ("game ended\\n");
exit(0);
}
}
void *makan_lohan(void *arg){pthread_mutex_lock(&lock);
s_lohan+=10;
printf("Lohan status is now %d\\n", s_lohan);
pthread_mutex_unlock(&lock);
cek_game_status();
}
void *makan_kepiting(void *arg){
pthread_mutex_lock(&lock);
s_kepiting+=10;
printf("Kepiting status is now %d\\n", s_kepiting);
pthread_mutex_unlock(&lock);
cek_game_status();
}
void *lohan_berkurang(void *arg){
while(1){
printf("Lohan status is now %d\\n", s_lohan);
cek_game_status();
sleep(10);
pthread_mutex_lock(&lock);
s_lohan-=15;
pthread_mutex_unlock(&lock);
}
}
void *kepiting_berkurang(void *arg){
while (1){
printf("Kepiting status is now %d\\n", s_kepiting);
cek_game_status();
sleep(20);
pthread_mutex_lock(&lock);
s_kepiting-=10;
pthread_mutex_unlock(&lock);
}
}
int main (){
char command[50];
int pil;
printf ("1. Feed lohan\\n2. Feed kepiting\\n3. Exit\\n");
pthread_create(&(tid[0]), 0, lohan_berkurang, 0);
pthread_create(&(tid[1]), 0, kepiting_berkurang, 0);
while (1){
scanf ("%d",&pil);
switch (pil){
case 1:
pthread_create(&(tid[2]), 0, makan_lohan, 0);
break;
case 2:
pthread_create(&(tid[3]), 0, makan_kepiting, 0);
break;
case 3:
exit (0);
}
}
}
| 0
|
#include <pthread.h>
FILE **fp1, **fp2;
int flag[MAX_FILE_NUMBER];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *convert(void *arg)
{
int i, idx, ifhave;
int *tmp = (int *)arg;
while (1)
{
ifhave = 0;
pthread_mutex_lock(&mutex);
for (i = 0; i < tmp[0]; i++)
{
if (flag[i] == 0)
{
ifhave = 1;
flag[i] = 1;
idx = i;
break;
}
}
pthread_mutex_unlock(&mutex);
if (!ifhave)
{
printf("%u: finished\\n", (unsigned int)pthread_self());
break;
}
printf("tid: %u idx: %d\\n", (unsigned int)pthread_self(), idx);
int c = 1;
while (c != EOF)
{
c = fgetc(fp1[idx]);
if (c != EOF)
fputc(toupper(c), fp2[idx]);
}
}
pthread_exit(0);
}
int main(int argc, char **argv)
{
char dest_fname[FILENAME_LENGTH];
int i, num[1];
pthread_t tid[N_THREADS];
fp1 = (FILE **)malloc((argc - 1) * sizeof(FILE *));
fp2 = (FILE **)malloc((argc - 1) * sizeof(FILE *));
for (i = 0; i < argc - 1; i++)
{
fp1[i] = fopen(argv[i + 1], "r");
strcpy(dest_fname, argv[i + 1]);
strcat(dest_fname, ".UPPER.txt");
printf("%s\\n", dest_fname);
fp2[i] = fopen(dest_fname, "w");
if ((fp1[i] == 0) || (fp2[i] == 0))
{
perror("fopen");
exit(1);
}
flag[i] = 0;
}
num[0] = argc - 1;
for (i = 0; i < N_THREADS; i++)
{
pthread_create(&tid[i], 0, convert, (void *)num);
}
printf("execute\\n");
for (i = 0; i < N_THREADS; i++)
{
if (pthread_join(tid[i], 0) != 0)
{
perror("join");
exit(1);
}
}
printf("execute\\n");
for (i = 0; i < argc - 1; i++)
{
fclose(fp1[i]);
fclose(fp2[i]);
}
printf("execute\\n");
free(fp1);
free(fp2);
return 0;
}
| 1
|
#include <pthread.h>
int iter = 0, buffer[256];
pthread_mutex_t sum_mutex;
void* do_work(void *tid)
{
int *mytid = (int *) tid;
*mytid += 1;
int finish = 0;
while (1)
{
pthread_mutex_lock (&sum_mutex);
if (iter >= 256) finish = 1;
else
{
buffer[iter] = *mytid;
printf ("Escribi %d en la posicion %d del buffer\\n", *mytid, iter++);
}
pthread_mutex_unlock (&sum_mutex);
if (finish == 1) break;
sleep(*mytid);
}
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int i, start, tids[4];
pthread_t threads[4];
pthread_attr_t attr;
pthread_mutex_init(&sum_mutex, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (i=0; i<4; i++) {
tids[i] = i;
pthread_create(&threads[i], &attr, do_work, (void *) &tids[i]);
}
for (i=0; i<4; i++) {
pthread_join(threads[i], 0);
}
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&sum_mutex);
pthread_exit (0);
}
| 0
|
#include <pthread.h>
int balance = 1000000;
pthread_mutex_t mutex;
void *withdraw(void * n)
{
int temp = (int)n;
printf("\\nWithdraw Called :: %d Debit",temp);
pthread_mutex_lock(&mutex);
balance = balance - temp;
pthread_mutex_unlock(&mutex);
printf("\\nBalance = %d ",balance);
}
void *deposit(void * n)
{
int temp = (int)n;
printf("\\nDeposit Called :: %d Credit",temp);
balance = balance + temp;
printf("\\nBalance = %d ",balance);
}
int main()
{
printf("You have %d Cr. in your bank account\\n",balance);
if(pthread_mutex_init(&mutex,0))
perror("pthread_mutex_init failed");
int n = 600000;
int m = 500000;
pthread_t t_ID[2];
pthread_create(&t_ID[0], 0, withdraw, (void *)n);
pthread_create(&t_ID[1], 0, deposit, (void *)m);
pthread_join(t_ID[0],0);
pthread_join(t_ID[1],0);
printf("\\n");
}
| 1
|
#include <pthread.h>
volatile long double result = 0.0;
pthread_mutex_t resultLock;
long double intervals;
int numThreads;
double a[700][700];
double b[700][700];
double c[700][700];
struct thread_info {
pthread_t thread_id;
int thread_num;
int perThread;
int threadStart;
int i, j;
};
void *matmul(void *arg){
int i,j,k;
double mult = 0;
int perThread, threadStart;
struct thread_info *tinfo = arg;
perThread = tinfo->perThread;
threadStart = tinfo->threadStart;
i = tinfo->i;
j = tinfo->j;
for (k = tinfo->threadStart; k < tinfo->perThread + tinfo->threadStart; k++){
mult += a[i][k]*b[k][j];
}
pthread_mutex_lock(&resultLock);
result += mult;
pthread_mutex_unlock(&resultLock);
return 0;
}
int main()
{
pthread_t *threads;
void *retval;
int *threadID;
int p;
int i,j,k;
int numThreads = 1;
struct thread_info *tinfo;
threads = malloc(numThreads*sizeof(pthread_t));
threadID = malloc(numThreads*sizeof(int));
tinfo = calloc(numThreads, sizeof(struct thread_info));
pthread_mutex_init(&resultLock, 0);
for(p=0; p<1; p++)
{
for(i=0; i<700; i++){
for(j=0; j<700; j++){
a[i][j] = (double)(i+j);
b[i][j] = (double)(i-j);
}
}
printf("starting multiply \\n");
for(i=0; i<700; i++){
for(j=0; j<700; j++){
c[i][j] = 0.0;
result = c[i][j];
for(k=0; k<numThreads; k++){
tinfo[k].thread_num = k;
tinfo[k].perThread = 700 / numThreads;
tinfo[k].threadStart = tinfo[k].perThread*k;
tinfo[k].i = i;
tinfo[k].j = j;
pthread_create(&threads[k], 0, matmul, &tinfo[k]);
}
for (k = 0; k < numThreads; k++) {
pthread_join(threads[k], &retval);
}
c[i][j] = result;
}
}
printf("a result %g \\n", c[7][8]);
}
return 0;
}
| 0
|
#include <pthread.h>
void *find_words(void*);
int map_reduce(int number_threads, char *string, struct list *list);
int main(void) {
char *string;
int cur_time, i, j;
struct list *list;
struct stat *buf;
buf = (struct stat *) malloc(sizeof(struct stat));
stat("./Don_Quixote.txt", buf);
int fd = open("./Don_Quixote.txt", O_RDONLY);
string = (char *)malloc(sizeof(char) * buf->st_size);
read(fd, string, buf->st_size);
list = (struct list *)malloc(sizeof(struct list));
for(j = 2; j < 4; ++j) {
list_init(list);
cur_time = clock();
map_reduce(j, string, list);
cur_time = clock() - cur_time;
printf("%d\\n\\n", cur_time);
for(i = 0; i < list->current_length; ++i)
free(list->head[i]);
list_destroy(list);
}
free(string);
free(list);
exit(0);
}
int is_separator(char *simbol, char *separators) {
while(*separators != 0) {
if(*simbol == *separators)
return 1;
++separators;
}
return 0;
}
void *find_words(void *arg) {
struct list *list;
char *begin, *end;
char *new_begin, *new_str;
int i, is_unique;
void **pointer;
pointer = (void **)arg;
list = (struct list *)(pointer[0]);
begin = (char *)(pointer[1]);
end = (char *)(pointer[2]);
while(begin != end) {
while(begin <= end && is_separator(begin, " ,.?!"))
++begin;
if(begin > end)
return 0;
new_begin = begin;
while(new_begin <= end && !is_separator(new_begin, " ,.?!"))
++new_begin;
--new_begin;
pthread_mutex_lock(list->mutex);
is_unique = 0;
for(i = 0; i < list->current_length; ++i) {
if(strncmp(list->head[i], begin, new_begin - begin + 1) == 0) {
is_unique = 1;
break;
}
}
if(is_unique == 0) {
new_str = (char *)malloc(sizeof(char) * (new_begin - begin + 2));
memcpy(new_str, begin, new_begin - begin + 1);
new_str[new_begin - begin + 1] = '\\0';
list_add(list, new_str);
}
pthread_mutex_unlock(list->mutex);
usleep(1000);
begin = new_begin + 1;
}
pthread_exit(0);
}
int map_reduce(int number_threads, char *string, struct list *list) {
int length, delta_length, i, begin_offset, end_offset, cur_pthread;
void ***arg;
pthread_t *pthreads;
pthreads = (pthread_t *)malloc(sizeof(pthread_t)*number_threads);
arg = (void ***)malloc(sizeof(void *) * number_threads);
length = strlen(string);
delta_length = length / number_threads;
begin_offset = 0;
cur_pthread = 0;
for(i = 0; i < number_threads; ++i) {
if(i == number_threads - 1)
end_offset = length;
else {
end_offset = delta_length * (i + 1);
while(end_offset >= begin_offset && !is_separator(string + end_offset, " ,.?!"))
--end_offset;
}
if(end_offset >= begin_offset) {
arg[cur_pthread] = (void **)malloc(sizeof(void *) * 3);
arg[cur_pthread][0] = list;
arg[cur_pthread][1] = string + begin_offset;
arg[cur_pthread][2] = string + end_offset - 1;
pthread_create((pthreads + cur_pthread), 0, find_words, (void*)(arg[cur_pthread]));
++cur_pthread;
}
begin_offset = end_offset;
}
for(i = 0; i < cur_pthread; ++i) {
pthread_join(pthreads[i], 0);
free(arg[i]);
}
free(pthreads);
free(arg);
return 0;
}
static pthread_cond_t c = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
static void *th_waiters(void *arg)
{
pthread_mutex_lock(&m);
while (! isend) {
pthread_cond_wait(&c, &m);
count++;
}
pthread_mutex_unlock(&m);
return arg;
}
static void *th_broadcast(void *arg)
{
while (! isend)
pthread_cond_broadcast(&c);
return arg;
}
static void test_exec(void)
{
int i;
pthread_t *t;
count = 0;
t = malloc(sizeof(*t) * nproc);
for (i = 0; i < nproc-1; i++)
pthread_create(&t[i], 0, th_waiters, 0);
pthread_create(&t[i], 0, th_broadcast, 0);
for (i = 0; i < nproc; i++)
pthread_join(t[i], 0);
free(t);
}
static void test_print_results(int sig)
{
isend = 1;
print_results();
pthread_cond_broadcast(&c);
}
| 1
|
#include <pthread.h>
int nblect=0;
sem_t mutex;
sem_t BD;
sem_t SAS;
pthread_mutex_t mutex2;
pthread_cond_t fprod;
pthread_cond_t fconso;
int Nmess=2;
int Pconso=0;
int Pprod=0;
int tampon[2];
void debut_lire (){
printf("Demande de lecture\\n");
sem_wait(&SAS);
sem_wait(&mutex);
nblect++;
if(nblect==1){
sem_wait(&BD);
printf("Blocage de la base de donnée pour les redacteurs\\n");
}
sem_post(&mutex);
sem_post(&SAS);
printf("Debut de la lecture (je suis le %d ième à lire)\\n",nblect);
}
void fin_lire (){
sem_wait(&mutex);
printf("Fin de lecture (il reste %d lecteurs en train de lire)\\n",nblect-1);
nblect--;
if(nblect==0){
printf("Deblocage de la base de donnée pour les rédacteurs\\n");
sem_post(&BD);
}
sem_post(&mutex);
}
void debut_ecrire () {
printf("Demande d'ecriture\\n");
sem_wait(&SAS);
sem_wait(&BD);
sem_post(&SAS);
printf("Debut de l'ecriture\\n");
}
void fin_ecrire (){
printf("Fin de l'ecriture\\n");
sem_post(&BD);
}
void deposer(int message){
pthread_mutex_lock(&mutex2);
while(Nmess==0){
pthread_cond_wait(&fprod,&mutex2);
}
printf(" Ecriture du message : %d dans le tampon %d\\n", message,Pprod);
tampon[Pprod]=message;
Nmess--;
Pprod=(Pprod+1)%2;
pthread_cond_signal(&fconso);
pthread_mutex_unlock(&mutex2);
}
void retirer() {
pthread_mutex_lock(&mutex2);
while(Nmess==2) {
pthread_cond_wait(&fconso,&mutex2);
}
Nmess++;
int message=tampon[Pconso];
printf(" Message : %d lue dans le tampon %d\\n",message,Pconso);
Pconso=(Pconso+1)%2;
pthread_cond_signal(&fprod);
pthread_mutex_unlock(&mutex2);
}
void *thread1(void *a)
{
int i= (int) a;
for(i=0;i <10; i++)
{
deposer(i);
usleep(100 * drand48());
debut_lire();
fin_lire();
}
}
void *thread2(void *a)
{
int i= (int) a;
for(i=0;i <10; i++)
{
retirer();
usleep(100 * drand48());
debut_ecrire();
fin_ecrire();
}
}
void *thread3(void *a)
{
int i= (int) a;
for(i=0;i <10; i++)
{
deposer(i);
usleep(100 * drand48());
debut_ecrire();
fin_ecrire();
}
}
void *thread4(void *a)
{
int i= (int) a;
for(i=0;i <10; i++)
{
retirer();
usleep(100 * drand48());
debut_lire();
fin_lire();
}
}
main() {
void * status;
pthread_t thread1_pid,thread2_pid,thread3_pid,thread4_pid,thread5_pid,thread6_pid,thread7_pid,thread8_pid;
sem_init(&mutex,0,1);
sem_init(&BD,0,1);
sem_init(&SAS,0,1);
pthread_create(&thread1_pid,0,thread1,0);
pthread_create(&thread2_pid,0,thread2,0);
pthread_create(&thread3_pid,0,thread3,0);
pthread_create(&thread4_pid,0,thread4,0);
pthread_create(&thread5_pid,0,thread1,0);
pthread_create(&thread6_pid,0,thread2,0);
pthread_create(&thread7_pid,0,thread3,0);
pthread_create(&thread8_pid,0,thread4,0);
pthread_join(thread1_pid,&status);
pthread_join(thread2_pid,&status);
pthread_join(thread3_pid,&status);
pthread_join(thread4_pid,&status);
pthread_join(thread5_pid,&status);
pthread_join(thread6_pid,&status);
pthread_join(thread7_pid,&status);
pthread_join(thread8_pid,&status);
}
| 0
|
#include <pthread.h>
pthread_mutex_t pLogFileWrite_Mutex = PTHREAD_MUTEX_INITIALIZER ;
static int WriteLogFileInHex (const char* ,const char* );
static int WriteLogFile_Ex (const char*,const char* ) ;
int WriteLogFile (const char*,int) ;
int WriteLogFileInHex_Ex (const char* ,int ) ;
int WriteLogFile (const char* szStrMsg , int iType)
{
if (!strlen(szStrMsg))
return -1 ;
time_t t ;
struct tm* tm = 0 ;
t = time (0) ;
tm = localtime (&t) ;
char szBuffer [MAXCONTLEN] ;
memset (szBuffer, '\\0',sizeof(szBuffer)) ;
int iRet =-1 ;
switch (iType){
case __SYS_TYPE_LOGFILE_RAW__ :{
if (tm){
strftime (szBuffer, sizeof(szBuffer),"%Y%m%d.raw",tm);
}
} break;
case __SYS_TYPE_LOGFILE_ERR__ :{
if (tm){
strftime (szBuffer, sizeof(szBuffer),"%Y%m%d.err",tm);
}
} break;
case __SYS_TYPE_LOGFILE_SQL__ :{
if (tm){
strftime (szBuffer, sizeof(szBuffer),"%Y%m%d.sql",tm);
}
} break;
default : break ;
}
if (strlen(szBuffer))
return WriteLogFile_Ex ((const char*)szBuffer,szStrMsg) ;
else
return iRet ;
}
int WriteLogFileInHex_Ex (const char* szStrMsg,int iType)
{
if (!strlen(szStrMsg))
return -1 ;
time_t t ;
struct tm* tm = 0 ;
t = time (0) ;
tm = localtime (&t);
char tmp [MAXCONTLEN] ;
memset (tmp , '\\0',sizeof(tmp));
switch (iType){
case __SYS_TYPE_LOGFILE_RAW__ : {
if (tm)
strftime (tmp,sizeof(tmp),"%Y%m%d.raw",tm) ;
} break;
case __SYS_TYPE_LOGFILE_ERR__ :{
if (tm)
strftime (tmp,sizeof(tmp),"%Y%m%d.err",tm);
} break ;
case __SYS_TYPE_LOGFILE_SQL__ : {
if (tm)
strftime (tmp,sizeof(tmp),"%Y%m%d.sql",tm) ;
} break ;
}
return WriteLogFileInHex (szStrMsg, (const char*)tmp) ;
}
static int WriteLogFileInHex (const char* szLogMsg,const char* szFileName){
pthread_mutex_lock (&pLogFileWrite_Mutex);
if (!strlen (szFileName)||!strlen (szLogMsg)) {
printf ("You have passed an invalid msg,pls check your system...\\n") ;
return -1 ;
}
char szBuffer[1024] ;
memset (szBuffer,'\\0',sizeof(szBuffer)) ;
char szTmp [10] ;
memset (szTmp,'\\0',sizeof(szTmp)) ;
int iShow = 0;
int iWrite = 0 ;
read_config_file ("./sysconfig.cfg","MSGSWITCH",szTmp) ;
if (!strlen(szTmp))
iShow =0 ;
else
iShow = atoi (szTmp) ;
memset (szTmp,'\\0',sizeof(szTmp));
read_config_file("./sysconfig.cfg","LOGWRITE",szTmp);
if (!strlen(szTmp))
iWrite = 0 ;
else
iWrite = atoi (szTmp);
time_t t ;
struct tm* tm = 0 ;
t = time (0);
tm= localtime(&t) ;
char tmptmp [MAXCONTLEN] ;
memset (tmptmp,'\\0',sizeof(tmptmp));
if (tm)
strftime (tmptmp,sizeof(tmptmp),"\\n[%Y-%m-%d %H:%M:%s]\\n",tm);
else{
pthread_mutex_unlock (&pLogFileWrite_Mutex) ;
return - 1 ;
}
FILE* fd = 0 ;
if ((fd= fopen (szFileName,"a+"))==0){
fclose(fd) ;
pthread_mutex_unlock (&pLogFileWrite_Mutex);
return -1 ;
}
if (iWrite) {
fseek (fd,0L,2);
fwrite (tmptmp,sizeof(char), strlen(tmptmp) ,fd) ;
fseek (fd,0L,2) ;
}
int iLen = strlen (szLogMsg) ;
int x =0 ;
int y = 0 ;
char tmp [16] ;
memset (tmp,'\\0',sizeof(tmp)) ;
int ipos =0 ;
for (x= 0 ; x < iLen ; ++x) {
tmp [x%16] = szLogMsg[x] ;
if ((x+1)%16==0) {
for (y=0 ; y< 16 ; ++y ){
sprintf (szBuffer+ipos,"0x%02X ",tmp[y]&0xFF);
ipos +=5 ;
}
for (y=0 ; y < 16; ++y ){
sprintf (szBuffer+ipos,"%c",isprint (tmp[y])?tmp[y]:'.');
ipos ++ ;
}
strcat(szBuffer,"\\n");
ipos +=1 ;
}
}
if (iShow)
printf ("%s\\n" ,szBuffer) ;
if (iWrite){
fwrite (szBuffer,sizeof(char), strlen(szBuffer) ,fd) ;
fseek (fd,0L,2);
}
fclose(fd);
pthread_mutex_unlock (&pLogFileWrite_Mutex) ;
return 0 ;
}
static int WriteLogFile_Ex (const char* szFileName,const char* szLogMsg )
{
pthread_mutex_lock (&pLogFileWrite_Mutex) ;
if (!strlen (szFileName)||!strlen(szLogMsg)){
pthread_mutex_unlock(&pLogFileWrite_Mutex) ;
return -1 ;
}
time_t t ;
struct tm* tm = 0;
t = time (0);
tm = localtime(&t);
char tmp [MAXCONTLEN] ;
memset (tmp,0x00,sizeof(tmp));
if (tm)
strftime (tmp,sizeof(tmp),"[%Y-%m-%d %H:%M:%S] ",tm);
else {
pthread_mutex_unlock(&pLogFileWrite_Mutex) ;
return -1 ;
}
int iShow =0 ;
int iWrite = 0 ;
char szBuff [10] ;
memset (szBuff,'\\0',sizeof(szBuff)) ;
read_config_file ("./sysconfig.cfg","MSGSWITCH",szBuff) ;
if (!strlen (szBuff))
iShow =0 ;
else
iShow = atoi (szBuff) ;
memset (szBuff,'\\0',sizeof(szBuff)) ;
read_config_file ("./sysconfig.cfg","LOGWRITE",szBuff) ;
if (!strlen(szBuff))
iWrite = 0 ;
else
iWrite = atoi (szBuff);
FILE* fd = 0 ;
if ((fd= fopen (szFileName,"a+"))==0){
fclose(fd) ;
pthread_mutex_unlock (&pLogFileWrite_Mutex);
return -1 ;
}
if (iShow)
printf ("%s",tmp);
if (iWrite) {
fseek (fd,0L,2);
fwrite (tmp,sizeof(char), strlen(tmp)+0 ,fd) ;
}
if (iShow)
printf ("%s\\n",szLogMsg);
if (iWrite){
fseek (fd,0L,2) ;
fwrite (szLogMsg,sizeof(char), strlen(szLogMsg)+0 ,fd);
fseek (fd,0L,2) ;
fwrite ("\\n\\r",sizeof(char),2,fd) ;
}
fclose(fd);
pthread_mutex_unlock (&pLogFileWrite_Mutex) ;
return 0 ;
}
| 1
|
#include <pthread.h>
unsigned char onebyte[128];
} BigMEMBlock;
int numblocks = 1024*1024*1024/128 ;
int numworkers = 1;
int runtime = 600;
int prepare = 5;
size_t MEMBLOCKSIZE = sizeof(BigMEMBlock);
BigMEMBlock *mempool;
pthread_t *tid;
pthread_mutex_t filelock;
FILE* logfd;
pthread_t timer_td;
int shouldend = 0;
int background = 0;
int record = 0;
long setmem() {
int idx = rand() % numblocks;
struct timespec begin, end;
long timediff;
BigMEMBlock *source = mempool+idx;
BigMEMBlock tmp;
clock_gettime(CLOCK_MONOTONIC, &begin);
memcpy(&tmp, source, sizeof(MEMBLOCKSIZE));
clock_gettime(CLOCK_MONOTONIC, &end);
timediff = (end.tv_sec - begin.tv_sec) * 1000000000 + (end.tv_nsec - begin.tv_nsec);
return timediff;
}
void flushlog(long *timerecords, int size) {
int i = 0;
if (background) {
return;
}
pthread_mutex_lock(&filelock);
for (i = 0; i < size; i++) {
fprintf(logfd, "%ld\\n", timerecords[i]);
}
pthread_mutex_unlock(&filelock);
}
void *dowork() {
long timerecords[10000], timediff;
int timeidx = 0;
printf("Child Pid: %d\\n", syscall(SYS_gettid));
while(!shouldend) {
timediff = setmem();
if (record && !background && timeidx < 10000) {
timerecords[timeidx] = timediff;
timeidx ++;
}
if (record && !background && timeidx == 10000) {
flushlog(timerecords, 10000);
timeidx = 0;
}
}
if (record && !background && timeidx != 0) {
flushlog(timerecords, timeidx);
}
return 0;
}
void *timerend() {
int i;
for (i = 0; background || i < prepare; i++) {
if (!background) {
printf("Prepare: %d/%d \\r", i, prepare);
fflush(stdout);
}
sleep(1);
}
record = 1;
for (i = 0; background || i < runtime; i++) {
if (!background) {
printf("Progress: %d/%d \\r", i, runtime);
}
fflush(stdout);
sleep(1);
}
shouldend = 1;
return 0;
}
int main(int argc, char** argv) {
int i;
srand((unsigned) time(0));
mempool = (BigMEMBlock *)malloc(numblocks*sizeof(BigMEMBlock));
for (i = 0; i < numblocks; i ++) {
memset(&mempool[i], rand()%256, sizeof(BigMEMBlock));
}
tid = malloc(numworkers * sizeof(pthread_t));
printf("Main Pid: %d\\n", syscall(SYS_gettid));
if (argc > 1) {
background = 1;
runtime += 5;
}
if (!background) {
logfd = fopen("memaccess.log", "w");
}
pthread_mutex_init(&filelock, 0);
for(i = 0; i < numworkers; i ++) {
pthread_create(&tid[i], 0, dowork, 0);
}
pthread_create(&timer_td, 0, timerend, 0);
pthread_join(timer_td, 0);
for (i = 0; i < numworkers; i++) {
pthread_join(tid[i], 0);
}
pthread_mutex_destroy(&filelock);
if (!background) {
fclose(logfd);
}
free(mempool);
free(tid);
}
| 0
|
#include <pthread.h>
struct student{
int id;
int age;
int name;
}stu;
int i;
pthread_mutex_t mutex;
void *thread_func1(void *arg){
while(1){
pthread_mutex_lock(&mutex);
stu.id = i;
stu.age = i;
stu.name = i;
i++;
if(stu.id != stu.age || stu.id != stu.name || stu.age != stu.name){
printf("%d, %d, %d\\n", stu.id, stu.age, stu.name);
break;
}
pthread_mutex_unlock(&mutex);
}
return (void *)0;
}
void *thread_func2(void *arg){
while(1){
pthread_mutex_lock(&mutex);
stu.id = i;
stu.age = i;
stu.name = i;
i++;
if(stu.id != stu.age || stu.id != stu.name || stu.age != stu.name){
printf("%d, %d, %d\\n", stu.id, stu.age, stu.name);
break;
}
pthread_mutex_unlock(&mutex);
}
return (void *)0;
}
int main(void){
pthread_t tid1, tid2;
int err;
err = pthread_mutex_init(&mutex, 0);
if(err != 0){
printf("init mutex failed\\n");
return -1;
}
err = pthread_create(&tid1, 0, thread_func1, 0);
if(err != 0){
printf("create new thread failed\\n");
return;
}
err = pthread_create(&tid2, 0, thread_func2, 0);
if(err != 0){
printf("create new thread failed\\n");
return;
}
pthread_join(tid1, 0);
pthread_join(tid2, 0);
return 0;
}
| 1
|
#include <pthread.h>
static int (*pthread_mutex_lock_orig) (pthread_mutex_t *m) = 0;
static int (*pthread_mutex_unlock_orig)(pthread_mutex_t *m) = 0;
static int enable_lock_tracking = 0;
int pthread_mutex_lock(pthread_mutex_t *m)
{
int res;
if (!pthread_mutex_lock_orig)
pthread_mutex_lock_orig = checked_dlsym(RTLD_NEXT, "pthread_mutex_lock");
res = pthread_mutex_lock_orig(m);
if (enable_lock_tracking) {
printf("thread: %d - pthread_mutex_lock(%p)\\n", gettid(), m);
fflush(stdout);
}
return res;
}
int pthread_mutex_unlock(pthread_mutex_t *m)
{
int res;
if (!pthread_mutex_unlock_orig)
pthread_mutex_unlock_orig = checked_dlsym(RTLD_NEXT, "pthread_mutex_unlock");
if (enable_lock_tracking) {
printf("thread: %d - pthread_mutex_unlock(%p)\\n", gettid(), m);
fflush(stdout);
}
res = pthread_mutex_unlock_orig(m);
return res;
}
void toggle_lock_tracking()
{
enable_lock_tracking = !enable_lock_tracking;
}
| 0
|
#include <pthread.h>
struct word_record{
char *str;
int count;
};
struct thread_data{
FILE *fp;
int start;
int blockSize;
char filepath[1024];
};
pthread_mutex_t critical_mutex;
int i=0;
struct word_record * Rec;
void* count_frequency(void* data){
int index=0,k=0;
struct thread_data* td=data;
char *buffer = malloc(td->blockSize);
memset(buffer,'\\0',sizeof(buffer));
FILE *lfp=fopen(td->filepath,"r");
fseek(lfp, td->start,0);
for(k=0;k<td->blockSize;k++)
*(buffer+k)=fgetc(lfp);
fclose(lfp);
pthread_mutex_lock(&critical_mutex);
while ((Rec+i)->str != 0)
{
index=data_index(Rec,(Rec+i)->str,i);
if(index >=0){
(Rec+index)->count++;
}
else{
i++;
}
}
free(buffer);
pthread_mutex_unlock(&critical_mutex);
}
int main(int argc, char **argv){
int nthreads=5, x, id, blockSize,len;
FILE *fp;
pthread_t *threads;
struct thread_data data[nthreads];
char filepath[1024] = {'\\0',};
printf("enter file path \\n");
scanf("%s",filepath);
fp=fopen(filepath,"r");
printf("Enter the number of threads: ");
scanf("%d",&nthreads);
threads = malloc(nthreads*sizeof(pthread_t));
fseek(fp, 0, 2);
len = ftell(fp);
printf("len= %d\\n",len);
fclose(fp);
Rec =(struct word_record *)calloc((len/1000),(sizeof(struct word_record)));
blockSize=(len)/nthreads;
printf("size= %d\\n",blockSize);
for(id = 0; id < nthreads; id++){
strcpy(data[id].filepath, filepath);
data[id].fp=fp;
data[id].start = id*blockSize;
data[id].blockSize=blockSize;
}
for(id = 0; id < nthreads; id++)
pthread_create(&threads[id], 0, &count_frequency,&data[id]);
for(id = 0; id < nthreads; id++)
pthread_join(threads[id],0);
fclose(fp);
return 0;
int k=0;
for(k=0;k<=i;k++){
printf("%s : %d", (Rec+k)->str , ((Rec+k)->count));
}
}
int data_index(struct word_record *Rec,char *word,int max){
int j;
for(j=0; j<max;i++){
if(strcmp((Rec+j)->str,word)==0){
return j;
}
}
return -1;
}
void sort(struct word_record *Rec){
int max= i;
char *con;
int m, n;
for( m=0;m<max;m++){
for( n=0;n<m;n++){
if(strcmp((Rec+m)->str,(Rec+n)->str)>1){
con=(Rec+n)->str;
(Rec+n)->str=(Rec+m)->str;
(Rec+m)->str=con;
}
}
}
}
| 1
|
#include <pthread.h>
pthread_t t_master;
pthread_t t_slave[4];
int master_cnt;
int slave_cnt[4];
int loop;
int done;
pthread_cond_t c = PTHREAD_COND_INITIALIZER;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
void* master_thread_code(void* arg) {
while(loop) {
pthread_mutex_lock(&m);
done=0;
pthread_cond_broadcast(&c);
pthread_mutex_unlock(&m);
pthread_mutex_lock(&m);
while(done != ((1<<4)-1)) pthread_cond_wait(&c,&m);
pthread_mutex_unlock(&m);
master_cnt++;
};
pthread_exit(0);
return 0;
};
void* slave_thread_code(void* arg) {
int idx = (int)arg;
int flag = 1<<idx;
while(loop) {
pthread_mutex_lock(&m);
while(done&flag) pthread_cond_wait(&c,&m);
pthread_mutex_unlock(&m);
pthread_mutex_lock(&m);
done|=flag;
pthread_cond_broadcast(&c);
pthread_mutex_unlock(&m);
slave_cnt[idx]++;
};
pthread_exit(0);
return 0;
};
int main(int argc, char* argv[]) {
int i;
master_cnt=0;
for(i=0;i<4;i++) slave_cnt[i]=0;
loop=1;
for(i=0;i<4;i++) pthread_create(&t_slave[i],0,slave_thread_code,(void*)i);
pthread_create(&t_master,0,master_thread_code,0);
for(i=0;i<1;i++) sleep(1);
loop=0;
printf("master thread runs: %i\\n",master_cnt/1);
for(i=0;i<4;i++) printf("slave thread %i runs: %i\\n",i,slave_cnt[i]/1);
printf("done ... terminate with kill command or CRTL+C\\n");
pthread_join(t_master,0);
for(i=0;i<4;i++) pthread_join(t_slave[i],0);
return 0;
};
| 0
|
#include <pthread.h>
static long TOTAL;
int counter = 0;
pthread_mutex_t lock;
int next_counter(void)
{
pthread_mutex_lock( &lock );
int temp = ++counter;
pthread_mutex_unlock( &lock );
return temp;
}
int is_prime( long x )
{
long i;
for( i = 2; i < x/2; ++i )
{
if( 0 == x % i )
return 0;
}
return 1;
}
void *prime_print(void *t)
{
int i = 0;
long j = 0L;
long tid = (long) t ;
double result = 0.0;
printf( "Thread %ld starting...\\n", tid );
while( j < TOTAL )
{
j = next_counter();
++i;
if( 1 == is_prime( j ) )
{
printf( "Prime: %ld\\n", j );
}
}
printf( "Thread %ld done.\\n", tid );
pthread_exit( (void*) i );
}
int main (int argc, char *argv[])
{
pthread_t thread[5];
int rc;
long t;
void* status;
TOTAL = pow( 10, 5 );
rc = pthread_mutex_init( &lock, 0 );
if( rc )
{
printf("ERROR in pthread_mutex_init(): "
"%s\\n", strerror(rc));
exit(-1);
}
for( t = 0; t < 5; ++t )
{
printf("Main: creating thread %ld\\n", t);
rc = pthread_create( &thread[t],
0,
prime_print,
(void*) t);
if (rc) {
printf("ERROR in pthread_create():"
" %s\\n", strerror(rc));
exit( -1 );
}
}
for( t = 0; t < 5; ++t )
{
rc = pthread_join(thread[t], &status);
if (rc)
{
printf("ERROR in pthread_join():"
" %s\\n", strerror(rc));
exit( -1 );
}
printf("Main: completed join with thread %ld "
"having a status of %ld\\n",t,(long)status);
}
printf("Main: program completed. Exiting."
" Counter = %d\\n",counter);
pthread_mutex_destroy(&lock);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mEnqueue = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mDequeue = PTHREAD_MUTEX_INITIALIZER;
int val;
struct element* next;
} element;
element* head;
element* tail;
int size;
} queue;
void init_queue(queue *q) {
element *e = (element*)malloc(sizeof(element));
e->next = 0;
e->val=0;
q->head = e;
q->tail = e;
q->size = 0;
}
void enqueue(queue *q, int inputValue){
pthread_mutex_lock(&mEnqueue);
element *new = (element*)malloc(sizeof(element));
new->val = inputValue;
new->next = 0;
q->tail->next = new;
q->tail = new;
q->size = q->size+1;
pthread_mutex_unlock(&mEnqueue);
}
int dequeue(queue *q, int* extractedVal) {
pthread_mutex_lock(&mDequeue);
if(q->head->next == 0){
pthread_mutex_unlock(&mDequeue);
return 1;
}
element *oldDummy = q->head;
element *newDummy = q->head->next;
q->head = newDummy;
*extractedVal = newDummy->val;
free(oldDummy);
q->size = q->size-1;
pthread_mutex_unlock(&mDequeue);
return 0;
}
void *endequeue(void* inq) {
queue *q = (queue*)inq;
int val;
srand(time(0));
int r;
int maxsize=0;
int size = 1000000/4;
printf("X/N: %d\\n",size);
for(int i = 0;i<size;i++){
r = rand()%2;
if(r) {
enqueue(q,1);
if(q->size>maxsize) maxsize = q->size;
}else{
if(dequeue(q,&val)){
}
}
}
printf("m: %d\\n",maxsize);
pthread_exit(0);
}
int main(int argc, char **argv){
pthread_mutex_init(&mDequeue,0);
pthread_mutex_init(&mEnqueue,0);
pthread_t threads[4];
queue *q = (queue *)malloc(sizeof(queue));
init_queue(q);
for(int i = 0; i<100;i++){
enqueue(q,i);
}
for(int i=0;i<4;i++){
pthread_create(&threads[i],0,endequeue,(void *) q);
}
for(int i=0;i<4;i++){
pthread_join(threads[i],0);
}
pthread_mutex_destroy(&mDequeue);
pthread_mutex_destroy(&mEnqueue);
return 0;
}
| 0
|
#include <pthread.h>
bool *is_prime;
pthread_mutex_t is_prime_mutex = PTHREAD_MUTEX_INITIALIZER;
int next = 0;
pthread_mutex_t next_mutex = PTHREAD_MUTEX_INITIALIZER;
int max_number;
void print_usage(void);
void *find_primes(void *id);
int get_next_index(void);
void record_not_prime(int n);
void record_prime(int p);
void init_is_prime(int size);
void free_is_prime(void);
int main(int argc, char* argv[]) {
pthread_t threads[1000];
if (argc < 2) {
fprintf(stderr, "Error: incorrect number of arguments.\\n");
print_usage();
}
max_number = atoi(argv[1]);
int num_threads = argc == 3 ? atoi(argv[2]): 2;
int rc;
init_is_prime(max_number + 1);
for (int i = 0; i < num_threads; ++i) {
rc = pthread_create(&threads[i], 0, find_primes, (void *)i);
}
for (int i = 0; i < num_threads; ++i) {
rc = pthread_join(threads[i], 0);
}
printf("Primes: ");
bool first = 1;
for (int i = 0; i < max_number + 1; ++i) {
if (is_prime[i]) {
if (!first) printf(", ");
printf("%d", i);
first = 0;
}
}
free_is_prime();
pthread_exit(0);
}
void init_is_prime(int size) {
is_prime = (bool *) malloc(sizeof(bool) * (size));
is_prime[0] = is_prime[1] = 0;
for (int i = 2; i < size; ++i) is_prime[i] = 1;
}
void free_is_prime(void) {
free(is_prime);
}
pthread_mutex_t output_mutex = PTHREAD_MUTEX_INITIALIZER;
void output(char *s, int id) {
pthread_mutex_lock(&output_mutex);
printf(s, id);
pthread_mutex_unlock(&output_mutex);
}
void *find_primes(void *id) {
int n = get_next_index();
while (n < max_number) {
if (is_prime[n]) {
int i;
for (i = n - 1; i > 1; --i) {
if (n % i == 0) {
record_not_prime(n);
break;
}
}
if (i == 1)
record_prime(n);
}
n = get_next_index();
}
pthread_exit(0);
}
int get_next_index() {
pthread_mutex_lock(&next_mutex);
int n = next;
next++;
pthread_mutex_unlock(&next_mutex);
return n;
}
void record_not_prime(int n) {
pthread_mutex_lock(&is_prime_mutex);
is_prime[n] = 0;
pthread_mutex_unlock(&is_prime_mutex);
}
void record_prime(int p) {
pthread_mutex_lock(&is_prime_mutex);
for (int i = p * 2; i < max_number + 1; i += p) {
is_prime[i] = 0;
}
pthread_mutex_unlock(&is_prime_mutex);
}
void print_usage() {
fprintf(stderr, "Usage: priem [max-number-to-test] [number-of-threads; default is 2]");
}
| 1
|
#include <pthread.h>
int available[3]={10,12,14};
int maximum[5][3]={{4,5,2},{5,7,3},{6,3,8},{5,9,7},{10,5,4}};
int allocation[5][3]={{1,1,0},{2,0,1},{0,0,2},{0,0,0},{0,0,0}};
int need[5][3]={{3,4,2},{3,7,2},{6,3,6},{5,9,7},{10,5,4}};
pthread_mutex_t mutex;
pthread_cond_t cond_var;
void release(int id)
{
available[0]+=maximum[id][0];
available[1]+=maximum[id][1];
available[2]+=maximum[id][2];
}
void request(int id,int input[3])
{
int i;
if(input[0]>need[id][0]||input[1]>need[id][1]||input[2]>need[id][2])
printf("what you input is over the need for %d!\\n",id+1);
else if(input[0]>available[0]||input[1]>available[1]||input[2]>available[2])
printf("what you need is over the available!\\n");
else if(need[id][0]>available[0]&&((available[0]-input[0])<need[(id+1)%5][0]||(available[0]-input[0])<need[(id+2)%5][0]||(available[0]-input[0])<need[(id+3)%5][0]||(available[0]-input[0])<need[(id+4)%5][0])&&need[id][1]>available[1]&&((available[1]-input[1])<need[(id+1)%5][1]||(available[1]-input[1])<need[(id+2)%5][1]||(available[1]-input[1])<need[(id+3)%5][1]||(available[1]-input[1])<need[(id+4)%5][1])&&need[id][2]>available[2]&&((available[2]-input[2])<need[(id+1)%5][2]||(available[2]-input[2])<need[(id+2)%5][2]||(available[2]-input[2])<need[(id+3)%5][2]||(available[2]-input[2])<need[(id+4)%5][2]))
{
printf("this input will make the system come into a dead_lock!\\n");
}
else
{
for(i=0;i<3;i++)
{
need[id][i]=need[id][i]-input[i];
allocation[id][i]+=input[i];
available[i]-=input[i];
}
if(need[id][0]==0&&need[id][1]==0&&need[id][2]==0)
{
release(id);
need[id][0]=need[id][1]=need[id][2]=-1;
}
}
}
void run(int id)
{
int i=0;
int input[3];
printf("available is %d %d %d\\n",available[0],available[1],available[2]);
printf(" maximum allocation need\\n");
for(i=0;i<5;i++)
{
printf("%d:%2d %2d %2d ",i+1,maximum[i][0],maximum[i][1],maximum[i][2]);
printf(" %2d %2d %2d ",allocation[i][0],allocation[i][1],allocation[i][2]);
printf(" %2d %2d %2d \\n",need[i][0],need[i][1],need[i][2]);
}
pthread_mutex_lock(&mutex);
{
printf("please input %d's need(3 resources):",id+1);
scanf("%d %d %d",&input[0],&input[1],&input[2]);
request(id,input);
}
pthread_mutex_unlock(&mutex);
sleep(rand()%3);
}
void inite(void *args)
{
srand((int)time(0));
int id=rand()%5;
while(1)
{
int id=rand()%5;
run(id);
}
return;
}
void main()
{
int rc;
pthread_t thread;
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond_var,0);
rc=pthread_create(&thread,0,inite,(void *)(1));
if(rc)
{
printf("ERROR;RETURN CODE IS %d\\n",rc);
return ;
}
pthread_join(thread,0);
return ;
}
| 0
|
#include <pthread.h>
{
double *a;
double *b;
double sum;
int veclen;
} DOTDATA;
DOTDATA dotstr;
pthread_t callThd[8];
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);
printf("Thread %ld adding partial sum of %f to global sum of %f\\n", (long)arg, mysum, dotstr.sum);
dotstr.sum += mysum;
pthread_mutex_unlock (&mutexsum);
pthread_exit((void*) 0);
}
int main (int argc, char *argv[])
{
long i;
double *a, *b;
void *status;
pthread_attr_t attr;
a = (double*) malloc (8*100*sizeof(double));
b = (double*) malloc (8*100*sizeof(double));
for (i=0; i<100*8; i++) {
a[i]=1;
b[i]=a[i];
}
dotstr.veclen = 100;
dotstr.a = a;
dotstr.b = b;
dotstr.sum=0;
pthread_mutex_init(&mutexsum, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i=0;i<8;i++) {
pthread_create( &callThd[i], &attr, dotprod, (void *)i);
}
pthread_attr_destroy(&attr);
for(i=0;i<8;i++) {
pthread_join( callThd[i], &status);
}
printf ("Done. Threaded version: sum = %f \\n", dotstr.sum);
free (a);
free (b);
pthread_mutex_destroy(&mutexsum);
pthread_exit(0);
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
unsigned int __VERIFIER_nondet_uint();
static int top=0;
static unsigned int arr[(800)];
pthread_mutex_t m;
_Bool flag=(0);
void error(void)
{
ERROR:
__VERIFIER_error(); return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
(top==0) ? (1) : (0);
}
int push(unsigned int *stack, int x)
{
if (top==(800))
{
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<(800); i++)
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint()%(800);
if ((push(arr,tmp)==(-1)))
error();
pthread_mutex_unlock(&m);
}
}
void *t2(void *arg)
{
int i;
for(
i=0; i<(800); i++)
{
pthread_mutex_lock(&m);
if (top>0)
{
if ((pop(arr)==(-2)))
error();
}
pthread_mutex_unlock(&m);
}
}
int main(void)
{
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t *fork_lft, *fork_rgt;
const char *name;
pthread_t thread;
int fail;
} Philosopher;
int running = 1;
void *PhilPhunction(void *p) {
Philosopher *phil = (Philosopher*)p;
int failed;
int tries_left;
pthread_mutex_t *fork_lft, *fork_rgt, *fork_tmp;
while (running) {
printf("%s is thinking\\n", phil->name);
sleep( 1+ rand()%8);
fork_lft = phil->fork_lft;
fork_rgt = phil->fork_rgt;
printf("%s is hungry\\n", phil->name);
tries_left = 2;
do {
failed = pthread_mutex_lock( fork_lft);
failed = (tries_left>0)? pthread_mutex_trylock( fork_rgt )
: pthread_mutex_lock(fork_rgt);
if (failed) {
pthread_mutex_unlock( fork_lft);
fork_tmp = fork_lft;
fork_lft = fork_rgt;
fork_rgt = fork_tmp;
tries_left -= 1;
}
} while(failed && running);
if (!failed) {
printf("%s is eating\\n", phil->name);
sleep( 1+ rand() % 8);
pthread_mutex_unlock( fork_rgt);
pthread_mutex_unlock( fork_lft);
}
}
return 0;
}
int main()
{
const char *nameList[] = { "Kant", "Aristotle", "Raymond", "Platon", "Confucius" };
pthread_mutex_t forks[5];
Philosopher philosophers[5];
Philosopher *phil;
int i;
int failed;
for (i=0;i<5; i++) {
failed = pthread_mutex_init(&forks[i], 0);
if (failed) {
printf("Failed to initialize mutexes.");
exit(1);
}
}
for (i=0;i<5; i++) {
phil = &philosophers[i];
phil->name = nameList[i];
phil->fork_lft = &forks[i];
phil->fork_rgt = &forks[(i+1)%5];
phil->fail = pthread_create( &phil->thread, 0, PhilPhunction, phil);
}
sleep(40);
running = 0;
for(i=0; i<5; i++) {
phil = &philosophers[i];
if ( !phil->fail && pthread_join( phil->thread, 0) ) {
printf("error joining thread for %s", phil->name);
exit(1);
}
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex;
sem_t students_sem;
sem_t ta_sem;
int waiting_students;
int seed;
void *Ta(void *param){
int totalHelpers = 8;
while(totalHelpers){
struct timeval now;
struct timespec timeout;
gettimeofday(&now);
timeout.tv_sec = now.tv_sec + rand_r(&seed)%3;
timeout.tv_nsec = now.tv_usec * 1000;
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
int programTime = rand_r(&seed);
int sleepTime = programTime%3 +1;
int sval = 0;
sem_getvalue(&students_sem, &sval);
totalHelpers--;
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void *Student(void *param){
int restHelp = 2;
int id = *( (int *) param);
while(restHelp){
int programTime = rand_r(&seed);
int sleepTime = programTime%3 +1;
sleep(sleepTime);
int *seats = (int*)malloc(sizeof(int));
if(!sem_trywait(&students_sem)){
int sval = 0;
sem_getvalue(&students_sem, &sval);
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
sem_wait(&ta_sem);
pthread_mutex_lock(&mutex);
sem_post(&students_sem);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
sleep(3);
restHelp--;
sem_post(&ta_sem);
}
else {
sleep(2);
continue;
}
}
pthread_exit(0);
}
int main(){
seed = rand();
printf("CS149 SleepingTA from Jingyuan Chen\\n");
pthread_mutex_init((&mutex),0);
pthread_attr_t attr;
sem_init(&students_sem, 0, 2);
sem_init(&ta_sem, 0, 1);
pthread_t *studentPool = (pthread_t *)malloc(sizeof(pthread_t)*4);
pthread_t ta;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&ta, &attr, Ta, 0);
int i=0;
int *ids = (int *)malloc(sizeof(int)*4);
for(;i<4;i++){
*(ids+i) = i+1;
pthread_create((studentPool+i), &attr, Student, (void*) (ids+i));
}
void *rv;
for(i=0;i<4;i++){
pthread_join(*(studentPool+i),&rv);
}
pthread_join(ta,&rv);
return 0;
}
| 0
|
#include <pthread.h>
int main()
{
char *shm = "myshm";
char *shm1 = "myshm1";
int shm_id, shm_id1;
char *buf;
pid_t pid;
pthread_mutex_t *mutex;
pthread_mutexattr_t mutexattr;
shm_id1 = shm_open(shm1, O_RDWR|O_CREAT, 0644);
ftruncate(shm_id1, 100);
mutex =(pthread_mutex_t *)mmap(0, 100, PROT_READ|PROT_WRITE, MAP_SHARED, shm_id1, 0);
pthread_mutexattr_init(&mutexattr);
pthread_mutex_init(mutex, &mutexattr);
shm_id = shm_open(shm, O_RDWR|O_CREAT, 0644);
ftruncate(shm_id, 100);
buf =(char *)mmap(0, 100, PROT_READ|PROT_WRITE, MAP_SHARED, shm_id, 0);
pid = fork();
if(pid==0)
{
sleep(1);
printf("I'm child proccess\\n");
pthread_mutex_lock(mutex);
memcpy(buf, "hello", 6);
printf("child buf is : %s\\n", buf);
pthread_mutex_unlock(mutex);
}
else if(pid>0)
{
printf("I'm parent proccess\\n");
pthread_mutex_lock(mutex);
memcpy(buf, "world", 6);
sleep(3);
printf("parent buf is : %s\\n", buf);
pthread_mutex_unlock(mutex);
}
pthread_mutexattr_destroy(&mutexattr);
pthread_mutex_destroy(mutex);
munmap(buf, 100);
shm_unlink(shm);
munmap(mutex, 100);
shm_unlink(shm1);
}
| 1
|
#include <pthread.h>
int cmr_msg_queue_create(unsigned int count, unsigned int *queue_handle)
{
struct cmr_msg_cxt *msg_cxt;
CMR_LOGV("count 0x%x, queue_handle 0x%x", count, (unsigned int)queue_handle);
if (0 == count) {
return -CMR_MSG_PARAM_ERR;
}
msg_cxt = (struct cmr_msg_cxt*)malloc(sizeof(struct cmr_msg_cxt));
if (0 == msg_cxt) {
return -CMR_MSG_NO_MEM;
}
bzero(msg_cxt, sizeof(*msg_cxt));
msg_cxt->msg_head = (struct cmr_msg*)malloc((unsigned int)(count * sizeof(struct cmr_msg)));
if (0 == msg_cxt->msg_head) {
return -CMR_MSG_NO_MEM;
}
msg_cxt->msg_magic = CMR_MSG_MAGIC_CODE;
msg_cxt->msg_count = count;
msg_cxt->msg_read = msg_cxt->msg_head;
msg_cxt->msg_write = msg_cxt->msg_head;
pthread_mutex_init(&msg_cxt->mutex, 0);
sem_init(&msg_cxt->msg_sem, 0, 0);
*queue_handle = (unsigned int)msg_cxt;
return CMR_MSG_SUCCESS;
}
int cmr_msg_get(unsigned int queue_handle, struct cmr_msg *message)
{
struct cmr_msg_cxt *msg_cxt = (struct cmr_msg_cxt*)queue_handle;
if (0 == queue_handle || 0 == message) {
return -CMR_MSG_PARAM_ERR;
}
do { if (((struct cmr_msg_cxt*)queue_handle)->msg_magic != CMR_MSG_MAGIC_CODE) { return CMR_MSG_INVALID_HANDLE; } } while(0);
sem_wait(&msg_cxt->msg_sem);
pthread_mutex_lock(&msg_cxt->mutex);
if (msg_cxt->msg_read != msg_cxt->msg_write) {
*message = *msg_cxt->msg_read++;
if (msg_cxt->msg_read > msg_cxt->msg_head + msg_cxt->msg_count - 1) {
msg_cxt->msg_read = msg_cxt->msg_head;
}
}
pthread_mutex_unlock(&msg_cxt->mutex);
CMR_LOGV("queue_handle 0x%x, msg type 0x%x", queue_handle, message->msg_type);
return CMR_MSG_SUCCESS;
}
int cmr_msg_post(unsigned int queue_handle, struct cmr_msg *message)
{
struct cmr_msg_cxt *msg_cxt = (struct cmr_msg_cxt*)queue_handle;
struct cmr_msg *ori_node = msg_cxt->msg_write;
CMR_LOGV("queue_handle 0x%x, msg type 0x%x ", queue_handle, message->msg_type);
if (0 == queue_handle || 0 == message) {
return -CMR_MSG_PARAM_ERR;
}
do { if (((struct cmr_msg_cxt*)queue_handle)->msg_magic != CMR_MSG_MAGIC_CODE) { return CMR_MSG_INVALID_HANDLE; } } while(0);
pthread_mutex_lock(&msg_cxt->mutex);
*msg_cxt->msg_write++ = *message;
if (msg_cxt->msg_write > msg_cxt->msg_head + msg_cxt->msg_count - 1) {
msg_cxt->msg_write = msg_cxt->msg_head;
}
if (msg_cxt->msg_write == msg_cxt->msg_read) {
msg_cxt->msg_write = ori_node;
}
pthread_mutex_unlock(&msg_cxt->mutex);
sem_post(&msg_cxt->msg_sem);
return CMR_MSG_SUCCESS;
}
int cmr_msg_queue_destroy(unsigned int queue_handle)
{
struct cmr_msg_cxt *msg_cxt = (struct cmr_msg_cxt*)queue_handle;
CMR_LOGV("queue_handle 0x%x", queue_handle);
if (0 == queue_handle) {
return -CMR_MSG_PARAM_ERR;
}
do { if (((struct cmr_msg_cxt*)queue_handle)->msg_magic != CMR_MSG_MAGIC_CODE) { return CMR_MSG_INVALID_HANDLE; } } while(0);
if (msg_cxt->msg_head) {
free(msg_cxt->msg_head);
msg_cxt->msg_head = 0;
}
sem_destroy(&msg_cxt->msg_sem);
pthread_mutex_destroy(&msg_cxt->mutex);
bzero(msg_cxt, sizeof(*msg_cxt));
free(msg_cxt);
return CMR_MSG_SUCCESS;
}
| 0
|
#include <pthread.h>
struct LinkedList
{
int data;
struct LinkedList *next;
struct LinkedList *prev;
};
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
struct LinkedList *head;
{
char A[100];
} Info;
{
Info info;
struct Element_ *next;
} Element;
struct LinkedList *
LinkedList_new (int x)
{
struct LinkedList *newNode =
(struct LinkedList *) malloc (sizeof (struct LinkedList));
newNode->data = x;
newNode->prev = 0;
newNode->next = 0;
return newNode;
}
void *
LinkedList_addToEnd (char x)
{
struct LinkedList *temp = head;
struct LinkedList *newNode = LinkedList_new (x);
if (head == 0)
{
head = newNode;
return;
}
while (temp->next != 0)
temp = temp->next;
temp->next = newNode;
newNode->prev = temp;
}
void *
Forward ()
{
struct LinkedList *temp = head;
pthread_mutex_lock (&lock);
sleep (2);
printf ("Forward: ");
while (temp != 0)
{
printf ("%c ", temp->data);
temp = temp->next;
}
printf ("\\n");
pthread_mutex_unlock (&lock);
}
void *
Reverse ()
{
struct LinkedList *temp = head;
pthread_mutex_lock (&lock);
sleep (2);
if (temp == 0)
return;
while (temp->next != 0)
{
temp = temp->next;
}
printf ("Reverse: ");
while (temp != 0)
{
printf ("%c ", temp->data);
temp = temp->prev;
}
printf ("\\n");
pthread_mutex_unlock (&lock);
}
void
print_comparisons (Element * elm)
{
assert (elm);
Element *cur = elm;
Element *next = cur->next;
pthread_mutex_lock (&lock);
sleep (2);
for (; next; cur = next, next = next->next)
{
if (strcmp (cur->info.A, next->info.A) == 0)
printf ("ptrs found are same\\n");
else
printf ("ptrs found are different\\n");
pthread_mutex_unlock (&lock);
}
}
void main ()
{
pthread_t t1, t2, t3;
int res;
head = 0;
pthread_create (&t1, PTHREAD_CREATE_JOINABLE, LinkedList_addToEnd, 0);
pthread_join (t1, head);
pthread_create (&t2, PTHREAD_CREATE_JOINABLE, Forward, 0);
pthread_join (t2, head);
pthread_create (&t3, PTHREAD_CREATE_JOINABLE, Reverse, 0);
pthread_join (t3, head);
Info a;a.A[0] = 'A';LinkedList_addToEnd ('A');a.A[1] = '\\0';
Element na;na.info = a;
Forward ();
Reverse ();
Info b;b.A[0] = 'B';LinkedList_addToEnd ('B');b.A[1] = '\\0';
Element nb;nb.info = b;
Forward ();
Reverse ();
Info c;c.A[0] = 'B';LinkedList_addToEnd ('B');c.A[1] = '\\0';
Element nc;nc.info = c;
Forward ();
Reverse ();
Info d;d.A[0] = 'D';LinkedList_addToEnd ('D');d.A[1] = '\\0';
Element nd;nd.info = d;
Forward ();
Reverse ();
na.next = &nb;
nb.next = &nc;
nc.next = &nd;
nd.next = 0;
print_comparisons (&na);
return 0;
}
| 1
|
#include <pthread.h>
void *producer(void *);
void *consumer(void *);
pthread_mutex_t mut;
pthread_cond_t producer_cv;
pthread_cond_t consumer_cv;
int supply = 0;
int num_cons_remaining = 100;
int main(int argc, char * argv[])
{
pthread_t prod_tid;
pthread_t cons_tid[100];
int thread_index[100];
int i;
pthread_mutex_init(&mut, 0);
pthread_cond_init(&producer_cv, 0);
pthread_cond_init(&consumer_cv, 0);
pthread_create(&prod_tid, 0, producer, 0);
for (i = 0; i < 100; i++)
{
thread_index[i] = i;
pthread_create(&cons_tid[i], 0,
consumer, (void *)&thread_index[i]);
}
pthread_join(prod_tid, 0);
for (i = 0; i < 100; i++)
pthread_join(cons_tid[i], 0);
printf("All threads complete\\n");
return 0;
}
void *producer(void *arg)
{
int producer_done = 0;
pthread_mutex_lock(&mut);
while (!producer_done)
{
supply = supply + 10;
printf("Supply is %i\\n", supply);
fflush(stdin);
pthread_cond_wait(&producer_cv, &mut);
pthread_cond_broadcast(&consumer_cv);
if(num_cons_remaining == 0){
producer_done = 1;
printf("Supply is %i Number of consumbers left %i\\nProducer has left for the day.\\n",supply, num_cons_remaining);
fflush(stdin);
}
}
pthread_mutex_unlock(&mut);
return 0;
}
void *consumer(void *arg)
{
int cid = *((int *)arg);
pthread_mutex_lock(&mut);
while (supply == 0)
pthread_cond_wait(&consumer_cv, &mut);
printf("consumer thread id %d consumes an item\\n", cid);
fflush(stdin);
supply--;
if (supply == 0)
pthread_cond_signal(&producer_cv);
num_cons_remaining--;
pthread_mutex_unlock(&mut);
return 0;
}
| 0
|
#include <pthread.h>
int num_processes, num_resources, strategy;
int **hold, **need, **max, *avail;
unsigned long simTime = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t isDone = PTHREAD_COND_INITIALIZER;
int isSafe(){
int i,j;
int work[num_resources];
int finish[num_processes];
for(i = 0; i < num_resources; i++){
work[i] = avail[i];
}
for(i = 0; i < num_processes; i++){
finish[i] = 0;
}
for(i = 0; i < num_processes; i++){
if(finish[i] == 0){
finish[i] = 1;
for( j = 0; j < num_resources; j++){
if(need[i][j] > work[j])
finish[i] = 0;
}
if(finish[i]){
for( j = 0; j < num_resources; j++){
work[j] = work[j] + hold[i][j];
}
i = -1;
}
}
}
for(i = 0; i < num_processes; i++){
if(finish[i] == 0) return 0;
}
return 1;
}
void printResources(){
int i,j;
printf("HOLD:\\n");
for( i = 0; i < num_processes; i++){
for( j = 0; j < num_resources; j++){
printf("%d ", hold[i][j]);
}
printf("\\n");
}
printf("\\nNEED:\\n");
for( i = 0; i < num_processes; i++){
for( j = 0; j < num_resources; j++){
printf("%d ", need[i][j]);
}
printf("\\n");
}
printf("\\nMAX:\\n");
for( i = 0; i < num_processes; i++){
for( j = 0; j < num_resources; j++){
printf("%d ", max[i][j]);
}
printf("\\n");
}
printf("\\nAVAILABLE\\n");
for( j = 0; j < num_resources; j++){
printf("%d ", avail[j]);
}
printf("\\n");
if(isSafe())
printf("SAFE\\n");
else
printf("NOT SAFE\\n");
}
void* bankerProcess(void *arg){
int pid = (int *) arg;
int i;
int req[num_resources];
while(1){
pthread_mutex_lock(&mutex);
for(i = 0; i < num_resources; i++){
req[i] = rand() % need[pid][i];
}
for(i = 0; i < num_resources; i++){
printf("%d : %d %d\\n", i, req[i], need[pid][i]);
}
for(i = 0; i < num_resources; i++){
avail[i] = avail[i] - req[i];
hold[pid][i] = hold[pid][i] + req[i];
need[pid][i] = need[pid][i] - req[i];
}
if(!isSafe()){
printf("Not a safe state, Reallocating the resources\\n");
for(i = 0; i < num_resources; i++){
avail[i] = avail[i] + req[i];
hold[pid][i] = hold[pid][i] - req[i];
need[pid][i] = need[pid][i] + req[i];
}
pthread_cond_wait(&isDone, &mutex);
pthread_mutex_unlock(&mutex);
}
else{
printf("Safe state\\n");
simTime =+ need[pid][0];
pthread_mutex_unlock(&mutex);
sleep(need[pid][0]);
pthread_mutex_lock(&mutex);
int release;
for(i = 0; i < num_resources; i++){
release = rand() % hold[pid][i];
avail[i] = avail[i] + release;
hold[pid][i] = hold[pid][i] - release;
need[pid][i] = need[pid][i] + release;
}
simTime =+ release;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&isDone);
sleep(need[pid][0]);
}
}
}
int main(){
printf("Number of processes : ");
scanf("%d", &num_processes);
printf("Number of resources : ");
scanf("%d", &num_resources);
printf("Strategy type : \\n");
printf(" 1. Deadlock Avoidance\\n");
printf(" 2. Deadlock Detection\\n");
scanf("%d", &strategy);
hold = (int**)malloc(num_processes * sizeof(int*));
need = (int**)malloc(num_processes * sizeof(int*));
max = (int**)malloc(num_processes * sizeof(int*));
int i,j;
for (i = 0; i < num_processes; i++) {
hold[i] = (int*)malloc(num_resources * sizeof(int));
need[i] = (int*)malloc(num_resources * sizeof(int));
max[i] = (int*)malloc(num_resources * sizeof(int));
}
avail = (int *)malloc(num_resources * sizeof(int));
srand(1500);
for( i = 0; i < num_processes; i++){
for( j = 0; j < num_resources; j++){
avail[j] = 15 + rand() % 15;
hold[i][j] = rand() % 100;
need[i][j] = rand() % 20;
max[i][j] = hold[i][j] + need[i][j];
}
}
printResources();
pthread_t processes[num_processes];
for(i = 0; i < num_processes; i++){
int rc = pthread_create(&processes[i], 0, bankerProcess, (void *) i);
if (rc){
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
sleep(10);
printf("EXIT\\n");
exit(0);
pthread_exit(0);
return 1;
}
| 1
|
#include <pthread.h>
int threadSearch(int start,int end);
void *searching(void* arg);
int atoi(char* arg);
int numthreads = 100;
int increment = 100;
int done = 0;
int result = -1;
struct position
{
int pos;
int checked;
};
struct position pdx;
struct position * ptr=&pdx;
pthread_mutex_t lock;
pthread_cond_t cond;
int main(int argc, char *argv[]) {
int startNum = atoi(argv[1]);
int endNum = atoi(argv[2]);
printf("%d %d\\n",startNum, endNum );
numthreads = 100;
int res = threadSearch(startNum, endNum);
}
int threadSearch(int start, int end){
pthread_t tids[numthreads];
ptr->pos = start;
ptr->checked = 0;
int j;
for(j = 0;j<numthreads;j++){
pthread_create(&tids[j],0,searching,end);
}
for(j = 0;j<numthreads;j++){
pthread_join(tids[j],0);
}
if (result == -1)
printf("Number not found\\n");
else
printf("s_1 == %d\\n", result);
return result;
}
int padding_oracle(int i){
return 0;
}
void * searching(void * arg){
pthread_mutex_lock(&lock);
int ind;
if(ptr->checked==1){
ptr->pos++;
ptr->checked=0;
ind = ptr->pos;
ptr->checked = 1;
}
else{
ind = ptr->pos;
ptr->checked = 1;
}
int y = (int)arg;
pthread_mutex_unlock(&lock);
while(ind<=y && !done) {
printf("%d\\n",ind );
if (padding_oracle(ind) == 1) {
result = ind;
done = 1;
pthread_cond_broadcast(&cond);
break;
}
ind = ind+increment;
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t _lock;
void* value;
int key;
volatile struct _setos_node* next;
} setos_node;
setos_node* head;
int setos_init(void)
{
head = (setos_node*) malloc(sizeof(setos_node));
head->next = 0;
head->key = INT_MIN;
if (pthread_mutex_init(&_lock, 0) != 0)
{
printf("mutex init failed\\n");
return -1;
}
return 1;
}
int setos_free(void)
{
free(head);
pthread_mutex_destroy(&_lock);
}
int setos_add(int key, void* value)
{
int rc = pthread_mutex_lock(&_lock);
if (rc != 0)
{
perror("cannot acquire lock\\n");
}
volatile setos_node* node = head;
volatile setos_node* prev;
while ((node != 0) && (node->key < key)) {
prev = node;
node = node->next;
}
if ((node != 0) && (node->key == key))
{
pthread_mutex_unlock(&_lock);
return 0;
}
setos_node* new_node = (setos_node*) malloc(sizeof(setos_node));
new_node->key = key;
new_node->value = value;
new_node->next = node;
prev->next = new_node;
pthread_mutex_unlock(&_lock);
return 1;
}
int setos_remove(int key, void** value)
{
int rc = pthread_mutex_lock(&_lock);
if (rc != 0)
{
perror("cannot acquire lock\\n");
}
volatile setos_node* node = head->next;
volatile setos_node* prev = head;
while (node != 0) {
if (node->key == key) {
if (value != 0)
*value = node->value;
prev->next = node->next;
pthread_mutex_unlock(&_lock);
return 1;
}
prev = node;
node = node->next;
}
pthread_mutex_unlock(&_lock);
return 0;
}
int setos_contains(int key)
{
int rc = pthread_mutex_lock(&_lock);
if (rc != 0)
{
perror("cannot acquire lock\\n");
}
volatile setos_node* node = head->next;
while (node != 0) {
if (node->key == key)
{
pthread_mutex_unlock(&_lock);
return 1;
}
node = node->next;
}
pthread_mutex_unlock(&_lock);
return 0;
}
int main(void)
{
printf ("coarse\\n" );
int x = 1;
if (setos_init()==-1)
{
return -1;
}
setos_add(1, &x);
setos_add(2, &x);
setos_add(3, &x);
assert(setos_contains(2));
assert(!setos_contains(4));
assert(!setos_remove(4,0));
assert(setos_remove(2,0));
assert(!setos_contains(2));
setos_free();
printf ("done\\n" );
return 0;
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
unsigned int __VERIFIER_nondet_uint();
static int top=0;
static unsigned int arr[(400)];
pthread_mutex_t m;
_Bool flag=(0);
void error(void)
{ ERROR:
__VERIFIER_error(); return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
(top==0) ? (1) : (0);
}
int push(unsigned int *stack, int x)
{
if (top==(400))
{
printf("stack overflow\\n");
return (-1);
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (get_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();
flag=(1);
pthread_mutex_unlock(&m);
}
}
void *t2(void *arg)
{
int i;
for(
i=0; i<(400); i++)
{
pthread_mutex_lock(&m);
if (flag)
{
if (!(pop(arr)!=(-2)))
error();
}
pthread_mutex_unlock(&m);
}
}
int main(void)
{
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 0
|
#include <pthread.h>
void *threadfunc(void *arg);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int main(void)
{
int ret;
pthread_t new;
struct timespec ts;
struct timeval tv;
printf("condition variable test 6: bogus timedwaits\\n");
ret = pthread_mutex_lock(&mutex);
if (ret)
err(1, "pthread_mutex_lock(1)");
printf("unthreaded test (past)\\n");
gettimeofday(&tv, 0);
tv.tv_sec -= 2;
TIMEVAL_TO_TIMESPEC(&tv, &ts);
ret = pthread_cond_timedwait(&cond, &mutex, &ts);
if (ret != ETIMEDOUT) {
printf("FAIL: pthread_cond_timedwait() (unthreaded)"
" in the past returned %d\\n", ret);
exit(1);
}
printf("unthreaded test (zero time)\\n");
tv.tv_sec = 0;
tv.tv_usec = 0;
TIMEVAL_TO_TIMESPEC(&tv, &ts);
ret = pthread_cond_timedwait(&cond, &mutex, &ts);
if (ret != ETIMEDOUT) {
printf("FAIL: pthread_cond_timedwait() (unthreaded)"
" with zero time returned %d\\n", ret);
exit(1);
}
ret = pthread_create(&new, 0, threadfunc, 0);
if (ret != 0)
err(1, "pthread_create");
ret = pthread_join(new, 0);
if (ret != 0)
err(1, "pthread_join");
printf("threaded test\\n");
gettimeofday(&tv, 0);
tv.tv_sec -= 2;
TIMEVAL_TO_TIMESPEC(&tv, &ts);
ret = pthread_cond_timedwait(&cond, &mutex, &ts);
if (ret != ETIMEDOUT) {
printf("FAIL: pthread_cond_timedwait() (threaded)"
" in the past returned %d\\n", ret);
exit(1);
}
printf("threaded test (zero time)\\n");
tv.tv_sec = 0;
tv.tv_usec = 0;
TIMEVAL_TO_TIMESPEC(&tv, &ts);
ret = pthread_cond_timedwait(&cond, &mutex, &ts);
if (ret != ETIMEDOUT) {
printf("FAIL: pthread_cond_timedwait() (threaded)"
" with zero time returned %d\\n", ret);
exit(1);
}
pthread_mutex_unlock(&mutex);
return 0;
}
void *
threadfunc(void *arg)
{
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t corda = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t ida = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t volta = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t turno = PTHREAD_MUTEX_INITIALIZER;
int a_b = 0, b_a = 0;
void* atravessa_corda_AB(void* arg) {
int id = *((int *) arg);
time_t t;
printf("***Macaco %d criado em A.***\\n", id);
srand((unsigned) time(&t));
while(1) {
pthread_mutex_lock(&turno);
pthread_mutex_lock(&ida);
a_b++;
if(a_b == 1) {
pthread_mutex_lock(&corda);
}
pthread_mutex_unlock(&ida);
pthread_mutex_unlock(&turno);
printf("Macaco %d atravessando A_B.\\n", id);
sleep(rand() % 5);
printf("Macaco %d terminou a travessia A_B\\n", id); fflush(stdout);
pthread_mutex_lock(&ida);
a_b--;
if(a_b==0) {
pthread_mutex_unlock(&corda);
}
pthread_mutex_unlock(&ida);
sleep(rand() % 10);
}
}
void* atravessa_corda_BA(void* arg) {
int id = *((int *) arg);
time_t t;
printf("***Macaco %d criado em B.***\\n", id);
srand((unsigned) time(&t));
while(1) {
pthread_mutex_lock(&turno);
pthread_mutex_lock(&volta);
b_a++;
if(b_a == 1) {
pthread_mutex_lock(&corda);
}
pthread_mutex_unlock(&volta);
pthread_mutex_unlock(&turno);
printf("Macaco %d atravessando B_A.\\n", id);
sleep(rand() % 5);
printf("Macaco %d terminou a travessia B_A\\n", id); fflush(stdout);
pthread_mutex_lock(&volta);
b_a--;
if(b_a==0) {
pthread_mutex_unlock(&corda);
}
pthread_mutex_unlock(&volta);
sleep(rand() % 10);
}
}
int main() {
pthread_t a[12];
time_t t;
int* id;
int i;
srand((unsigned) time(&t));
for(i = 0; i < 12; i++) {
id = (int*) calloc (1, sizeof(int));
*id = i;
if(rand() % 2) {
pthread_create(&a[i], 0, atravessa_corda_AB, (void *) (id));
}
else {
pthread_create(&a[i], 0, atravessa_corda_BA, (void *) (id));
}
}
pthread_join(a[0],0);
return 0;
}
| 0
|
#include <pthread.h>
struct pp_thread_info {
int *msgcount;
char *msg;
int modval;
pthread_mutex_t *mutex;
};
void *
pp_thread(void *arg)
{
struct pp_thread_info *infop;
int c;
infop = arg;
while (1) {
pthread_mutex_lock(infop->mutex);
if (*infop->msgcount >= 100)
break;
if (*infop->msgcount % 2 == infop->modval) {
printf("%s\\n", infop->msg);
c = *infop->msgcount;
sched_yield();
c = c + 1;
*infop->msgcount = c;
}
pthread_mutex_unlock(infop->mutex);
sched_yield();
}
pthread_mutex_unlock(infop->mutex);
return (0);
}
int
main(void)
{
pthread_t ping_id1, pong_id1;
pthread_t ping_id2, pong_id2;
pthread_mutex_t mutex;
struct pp_thread_info ping, pong;
int msgcount;
msgcount = 0;
if (pthread_mutex_init(&mutex, 0) != 0) {
fprintf(stderr, "Mutex init failed: %s\\n", strerror(errno));
exit(1);
}
ping.msgcount = &msgcount;
ping.msg = "ping";
ping.modval = 0;
ping.mutex = &mutex;
pong.msgcount = &msgcount;
pong.msg = "pong";
pong.modval = 1;
pong.mutex = &mutex;
if ((pthread_create(&ping_id1, 0, &pp_thread, &ping) != 0) ||
(pthread_create(&pong_id1, 0, &pp_thread, &pong) != 0) ||
(pthread_create(&ping_id2, 0, &pp_thread, &ping) != 0) ||
(pthread_create(&pong_id2, 0, &pp_thread, &pong) != 0)) {
fprintf(stderr, "pingpong: pthread_create failed %s\\n", strerror(errno));
exit(1);
}
pthread_join(ping_id1, 0);
pthread_join(pong_id1, 0);
pthread_join(ping_id2, 0);
pthread_join(pong_id2, 0);
pthread_mutex_destroy(&mutex);
printf("Main thread exiting\\n");
}
| 1
|
#include <pthread.h>
inline uint64_t check(uint64_t ans, uint64_t guess){
cv_t cv_a, cv_g;
uint64_t i, j, result = 0;
cv_a.n = ans; cv_g.n = guess;
for (i = 0; i < 4; i++) {
if (cv_a.c[i] == cv_g.c[i]) {
result += 0x10;
} else {
for (j = 0; j < 4; j++) {
if ((i != j) && (cv_a.c[i] == cv_g.c[j])) {
result += 1;
}
}
}
}
return result;
}
inline uint64_t guess(){
uint64_t ans = candidates[rand() % CANDIDATES_COUNT], cbuf[CANDIDATES_COUNT], *c = candidates, cl = CANDIDATES_COUNT, times = 0, ci, g, i, res;
while (times < 12) {
g = c[rand() % cl];
res = check(ans, g);
if (res == 0x40) {
return times + 1;
}
times++;
ci = 0;
for (i = 0; i < cl; i++) {
if (res == check(c[i], g)) {
cbuf[ci] = c[i];
ci++;
}
}
c = cbuf; cl = ci;
if (cl == 0) {
return 0;
}
}
return times;
}
pthread_t tid;
uint64_t stat[12 + 1];
int running;
} thread_data_t;
static int running = 1;
static pthread_mutex_t report_mutex = PTHREAD_MUTEX_INITIALIZER;
static uint64_t mstat[12 + 1];
static char *filename;
static int proc_cnt;
static thread_data_t *thread_data;
void action_quit(int sig){
int i;
for (i = 0; i < proc_cnt; i++){
thread_data[i].running = 0;
}
running = 0;
}
void action_record(int sig){
int i;
for (i = 0; i < proc_cnt; i++){
thread_data[i].running = 0;
}
}
int read_file(char *filename, uint64_t *stat){
FILE *fp; int i;
char num[100] = "\\0";
fp = fopen(filename, "r");
if (0 == fp) {
return 0;
}
for (i = 0; i < 12 + 1; i++) {
stat[i] = strtoull(fgets(num, 100, fp), 0, 0);
}
fclose(fp);
return 1;
}
int write_file(char *filename, uint64_t *stat){
FILE *fp; int i;
fp = fopen(filename, "w");
if (0 == fp) {
return 0;
}
for (i = 0; i < 12 + 1; i++) {
fprintf(fp, "%lu\\n", stat[i]);
}
fclose(fp);
return 1;
}
void report_stat(uint64_t *stat) {
int i;
pthread_mutex_lock(&report_mutex);
for (i = 0; i < 12 + 1; i++) {
mstat[i] += stat[i];
stat[i] = 0;
}
write_file(filename, mstat);
pthread_mutex_unlock(&report_mutex);
}
void* thread_main(void *data){
while (running) {
while (((thread_data_t*)data)->running) {
(((thread_data_t*)data)->stat)[guess()]++;
}
report_stat(((thread_data_t*)data)->stat);
if (running) {
((thread_data_t*)data)->running = 1;
}
}
return ((void*)0);
}
int main(int argc, char *argv[]) {
int i, j;
if (argc < 2) {
fprintf(stderr, "Usage: %s FILENAME\\n", argv[0]);
return 1;
}
if (!strcmp(argv[1], "stat")) {
filename = argv[2];
read_file(filename, mstat);
for (i = 1; i <= 12; i++) {
printf("%d,%llu\\n", i, mstat[i]);
}
printf("Failed,%llu\\n", mstat[0]);
return 0;
} else if (!strcmp(argv[1], "statb")) {
filename = argv[2];
read_file(filename, mstat);
printf("100 DATA 11,2\\r\\n");
for (i = 1; i <= 11; i++) {
printf("%d DATA \\"%2d\\",%llu\\r\\n", 100+i, i, mstat[i]);
}
return 0;
}
filename = argv[1];
read_file(filename, mstat);
proc_cnt = get_nprocs();
srand(time(0));
signal(SIGINT, action_quit);
signal(SIGQUIT, action_quit);
signal(SIGUSR1, action_record);
thread_data = malloc(sizeof(thread_data_t) * proc_cnt);
for (i = 0; i < proc_cnt; i++) {
for (j = 0; j < 12 + 1; j++) {
thread_data[i].stat[j] = 0;
}
thread_data[i].running = 1;
pthread_create(&(thread_data[i].tid), 0, thread_main, &(thread_data[i]));
}
for (i = 0; i < proc_cnt; i++) {
pthread_join(thread_data[i].tid, 0);
}
free(thread_data);
signal(SIGUSR1, SIG_DFL);
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
return 0;
}
| 0
|
#include <pthread.h>
char *ID;
int N;
int procs;
volatile float A[5000][5000], B[5000], X[5000];
void gauss();
unsigned int time_seed() {
struct timeval t;
struct timezone tzdummy;
gettimeofday(&t, &tzdummy);
return (unsigned int)(t.tv_usec);
}
void parameters(int argc, char **argv) {
int submit = 0;
int seed = 0;
char uid[L_cuserid + 2];
if ( argc == 1 && !strcmp(argv[1], "submit") ) {
submit = 1;
N = 4;
procs = 2;
printf("\\nSubmission run for \\"%s\\".\\n", cuserid(uid));
strcpy(uid,ID);
srand(4|2[uid]&3);
}
else {
if (argc == 3) {
seed = atoi(argv[3]);
srand(seed);
printf("Random seed = %i\\n", seed);
}
else {
printf("Usage: %s <matrix_dimension> <num_procs> [random seed]\\n",
argv[0]);
printf(" %s submit\\n", argv[0]);
exit(0);
}
}
if (!submit) {
N = atoi(argv[1]);
if (N < 1 || N > 5000) {
printf("N = %i is out of range.\\n", N);
exit(0);
}
procs = atoi(argv[2]);
if (procs < 1) {
printf("Warning: Invalid number of processors = %i. Using 1.\\n", procs);
procs = 1;
}
}
printf("\\nMatrix dimension N = %i.\\n", N);
printf("Number of processors = %i.\\n", procs);
}
void initialize_inputs() {
int row, col;
printf("\\nInitializing...\\n");
for (col = 0; col < N; col++) {
for (row = 0; row < N; row++) {
A[row][col] = (float)rand() / 32768.0;
}
B[col] = (float)rand() / 32768.0;
X[col] = 0.0;
}
}
void print_inputs() {
int row, col;
if (N < 10) {
printf("\\nA =\\n\\t");
for (row = 0; row < N; row++) {
for (col = 0; col < N; col++) {
printf("%5.2f%s", A[row][col], (col < N-1) ? ", " : ";\\n\\t");
}
}
printf("\\nB = [");
for (col = 0; col < N; col++) {
printf("%5.2f%s", B[col], (col < N-1) ? "; " : "]\\n");
}
}
}
void print_X() {
int row;
if (N < 10) {
printf("\\nX = [");
for (row = 0; row < N; row++) {
printf("%5.2f%s", X[row], (row < N-1) ? "; " : "]\\n");
}
}
}
int main(int argc, char **argv) {
struct timeval etstart, etstop;
struct timezone tzdummy;
clock_t etstart2, etstop2;
unsigned long long usecstart, usecstop;
struct tms cputstart, cputstop;
ID = argv[argc-1];
argc--;
parameters(argc, argv);
initialize_inputs();
print_inputs();
printf("\\nStarting clock.\\n");
gettimeofday(&etstart, &tzdummy);
etstart2 = times(&cputstart);
gauss();
gettimeofday(&etstop, &tzdummy);
etstop2 = times(&cputstop);
printf("Stopped clock.\\n");
usecstart = (unsigned long long)etstart.tv_sec * 1000000 + etstart.tv_usec;
usecstop = (unsigned long long)etstop.tv_sec * 1000000 + etstop.tv_usec;
print_X();
printf("\\nElapsed time = %g ms.\\n",
(float)(usecstop - usecstart)/(float)1000);
}
int colIndex;
pthread_mutex_t index_lock;
void *solve(void * threadNorm) {
int norm = *((int *)threadNorm);
int row = 0;
float multiplier;
int col;
while(row < N) {
pthread_mutex_lock(&index_lock);
row = norm + colIndex + 1;
colIndex += 1;
pthread_mutex_unlock(&index_lock);
if(row >= N){
pthread_exit(0);
}
multiplier = A[row][norm]/A[norm][norm];
for(col = norm; col < N; col++) {
A[row][col] -= A[norm][col] * multiplier;
}
B[row] -= B[norm] * multiplier;
}
}
void gauss() {
int norm, row, col;
float multiplier;
colIndex = 0;
pthread_mutex_init(&index_lock, 0);
pthread_t thread[procs];
for(norm = 0; norm < N - 1; norm++){
int i, j;
colIndex = 0;
for(i = 0; i < (procs); i++) {
pthread_create(&thread[i], 0, solve, (void *)&norm);
}
for(j = 0; j < (procs); j++) {
pthread_join(thread[j], 0);
}
}
pthread_mutex_destroy(&index_lock);
for(row = N - 1; row >= 0; row--) {
X[row] = B[row];
for (col = N-1; col > row; col--) {
X[row] -= A[row][col] * X[col];
}
X[row] /= A[row][row];
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t shared_array_mutex = PTHREAD_MUTEX_INITIALIZER;
char shared_array[ 256 ] = {0};
char shared_array_changed = 0;
int fileLong = 0;
void * filler_thread( void * arg )
{
FILE *f;
char line[256];
f = fopen((char*) arg, "r");
int i;
for( i = 0; i < fileLong; i++ )
{
fgets(line, sizeof(line), f);
for(;;)
{
pthread_mutex_lock( &shared_array_mutex );
if( shared_array_changed == 0 )
break;
pthread_mutex_unlock( &shared_array_mutex );
}
strcpy( shared_array, line );
shared_array_changed = 1;
pthread_mutex_unlock( &shared_array_mutex );
}
pthread_exit( 0 );
}
void * printer_thread( void * arg )
{
int i;
for( i = 0; i < fileLong; i++ )
{
for(;;)
{
pthread_mutex_lock( &shared_array_mutex );
if( shared_array_changed == 1 )
break;
pthread_mutex_unlock( &shared_array_mutex );
}
if (strstr(shared_array, (char*) arg))
puts( shared_array );
shared_array_changed = 0;
pthread_mutex_unlock( &shared_array_mutex );
}
pthread_exit( 0 );
}
int main( int argc, char **argv )
{
char fpath[50], str[50];
if (argc < 3)
{
printf("Please input like: ./a.out text.txt substring\\n");
return 1;
}
strncpy(fpath, argv[1], 50 -1);
if (strlen(argv[1]) >= 50)
fpath[50 -1] = '\\0';
strncpy(str, argv[2], 50 -1);
if (strlen(argv[2]) >= 50)
str[50 -1] = '\\0';
FILE *fNumOfStrings;
char line[256];
fNumOfStrings = fopen(fpath, "r");
while(fgets(line, sizeof(line), fNumOfStrings) != 0)
fileLong++;
fclose(fNumOfStrings);
pthread_t th_filler, th_printer;
pthread_create( &th_printer, 0, printer_thread, str );
pthread_create( &th_filler, 0, filler_thread, fpath );
pthread_join( th_printer, 0 );
pthread_join( th_filler, 0 );
printf( "done.\\n" );
return 0;
}
| 0
|
#include <pthread.h>
void delay()
{
int i = 0;
for ( i=0; i<1000000; i++) ;
}
{
int x;
int y;
pthread_mutex_t mutex;
} DATA;
DATA data;
void init_data()
{
data.x = 0;
data.y = 0;
pthread_mutex_init(&data.mutex, 0);
printf("init_data\\n");
}
pthread_once_t one = PTHREAD_ONCE_INIT;
void* foo( void* args)
{
int i = 0;
pthread_once(&one, init_data);
for (i=0; i<20; i++)
{
pthread_mutex_lock(&data.mutex);
data.x = 100; delay();
data.x = data.x+1; delay();
printf("%s : %d\\n", (char*)args, data.x); delay();
pthread_mutex_unlock(&data.mutex);
}
printf("%s finish \\n", (char*)args);
return 0;
}
int main()
{
pthread_t t1, t2;
pthread_create( &t1, 0, foo, "A");
pthread_create( &t2, 0, foo, "\\tB");
void *r1, *r2;
pthread_join( t1, &r1);
pthread_join( t2, &r2);
}
| 1
|
#include <pthread.h>
int threadsNum;
char *fileName;
int recordsNum;
char *searched;
int file;
int signr;
pthread_t *threads;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *threadFunction(void *);
void signalHandler(int signal) {
printf("PID: %d TID: %ld received signal no %d\\n", getpid(), pthread_self(), signal);
return;
}
int main(int argc, char *argv[]) {
fileName = (char *)malloc(MAXFILENAME * sizeof(char));
searched = (char *) malloc(MAXSEARCH * sizeof(char));
if (argc != 6) {
printf("Wrong arguments! Threads number, file name, number of records, searched word required and signal number\\n");
return 1;
}
threadsNum = atoi(argv[1]);
fileName = argv[2];
recordsNum = atoi(argv[3]);
searched = argv[4];
signr = atoi(argv[5]);
if ((file = open(fileName, O_RDONLY)) == -1) {
printf("Error while open a file\\n");
return 2;
}
threads = (pthread_t *)malloc(threadsNum * sizeof(pthread_t));
for (int i = 0; i < threadsNum; i++) {
if (pthread_create(&threads[i], 0, threadFunction, 0) != 0) {
printf("pthread_create(): %d: %s\\n", errno, strerror(errno));
exit(-1);
}
}
pthread_kill(threads[0], signr);
for (int i = 0; i < threadsNum; i++) {
pthread_join(threads[i], 0);
}
free(threads);
close(file);
return 0;
}
void * threadFunction(void *unused) {
signal(SIGUSR1, signalHandler);
signal(SIGTERM, signalHandler);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
sleep(1);
char **readRecords = calloc(recordsNum, sizeof(char *));
for (int i = 0; i < recordsNum; i++) {
readRecords[i] = calloc(1024, sizeof(char));
}
char *num = (char *) malloc(MAXIDDIGITS * sizeof(char));
pthread_mutex_lock(&mutex);
for (int i = 0; i < recordsNum; i++) {
if (read(file, readRecords[i], BUFFERSIZE) == -1) {
printf("read(): %d: %s\\n", errno, strerror(errno));
exit(-1);
}
}
pthread_mutex_unlock(&mutex);
for (int i = 0; i < recordsNum; i++) {
if (strstr(readRecords[i], searched) != 0) {
strncpy(num, readRecords[i], MAXIDDIGITS);
printf("Thread with TID=%ld: found word in record number %d\\n", pthread_self(), atoi(num));
for (int j = 0; j < threadsNum; j++) {
if (threads[j] != pthread_self()) {
pthread_cancel(threads[j]);
}
}
break;
}
}
return 0;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.