text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int **matrice = 0;
int digprinc=0;
int digsec=0;
int rigcent=0;
int colcent=0;
int n=0;
int i =0;
int j=0;
int max=0;
int array[4];
void *funzione(void *param){
while(i<n){
pthread_mutex_lock(&mutex);
digprinc+=matrice[i][i];
digsec+=matrice[i][n-i-1];
rigcent+=matrice[n/2][i];
colcent+=matrice[i][n/2];
i++;
pthread_mutex_unlock(&mutex);
}
array[0]=digprinc;
array[1]=digsec;
array[2]=rigcent;
array[3]=colcent;
while (j<4){
pthread_mutex_lock(&mutex);
if (array[j] > max)
{
max = array[j];
}
j++;
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void stampa(int **m,int n){
int i,j=0;
for (i=0;i<n;i++){
for(j=0;j<n;j++){
printf("%d \\t",m[i][j]);
}
printf("\\n");
}
}
int main (int argc, char *argv[]){
pthread_t threads[4];
int i,j=0;
n=atoi(argv[1]);
if (n%2 == 0){
perror("N deve essere dispari");
exit(1);
}
matrice = (int**)malloc(sizeof(int*)*n);
for (i=0;i<n;i++){
matrice[i]=(int*)malloc(sizeof(int)*n);
for (j=0;j<n;j++){
matrice[i][j]=1+rand()%5;
}
}
stampa(matrice,n);
printf("\\n");
for (i =0 ; i< 4; i++){
pthread_create(&threads[i],0,funzione,0);
}
for (i =0 ; i< 4; i++){
pthread_join(threads[i],0);
}
printf("la diagonale principale è:%d\\n la diag secondaria è:%d\\n, la riga centrale è:%d\\n la colonna centrale è :%d",digprinc,digsec,rigcent,colcent);
printf("il max è :%d\\n",max );
return 0;
}
| 1
|
#include <pthread.h>
extern char **envrion;
pthread_mutex_t env_mutex;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
static void thread_init(void)
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&env_mutex, &attr);
pthread_mutexattr_destroy(&attr);
}
int getenv_r(const char *name, char *buf, int buflen)
{
int i;
int len;
int olen;
pthread_once(&init_done, thread_init);
len = strlen(name);
pthread_mutex_lock(&env_mutex);
for (i = 0; envrion[i] != 0; ++i) {
if ((0 == strncmp(name, envrion[i], len)) && ('=' == envrion[i][len])) {
olen = strlen(&envrion[i][len+1]);
if (olen >= buflen) {
pthread_mutex_unlock(&env_mutex);
return (ENOENT);
}
strcpy(buf, &envrion[i][len+1]);
pthread_mutex_unlock(&env_mutex);
return (0);
}
}
pthread_mutex_unlock(&env_mutex);
return (ENOENT);
}
| 0
|
#include <pthread.h>
int semid;
char operazione;
int riga;
int colonna;
int **matA,**matB,**matC;
int *somma;
int dimensione;
}msg;
pthread_mutex_t mutex;
void * threadFiglio (void * args){
msg* data=(msg * )args;
int riga=data->riga;
int colonna = data->colonna;
char operazione = data->operazione;
int **matriceC=data->matC;
int **matriceA=data->matA;
int **matriceB=data->matB;
int dimensione=data->dimensione;
printf("riga=> %i\\t colonna =>%i\\t operazione==>%c\\t\\n",riga,colonna,data->operazione);
int i=0;
switch(operazione){
case 'm':{
for(i=0;i < dimensione ;i++){
matriceC[riga][colonna]+=(matriceA[riga][i]*matriceB[i][colonna]);
printf("matc==>%i,\\triga=>%i,\\t colonna->%i\\n",matriceC[riga][colonna],riga,colonna );
}
break;
}
case 's':{
int temp=0;
for (i=0;i<dimensione;i++){
temp+=matriceC[i][0];
}
pthread_mutex_lock(&mutex);
sleep(1);
*data->somma+=temp;
pthread_mutex_unlock(&mutex);
break;
}
}
free(data);
return 0;
}
int main(int argc, char *argv[]){
int fd_matriceA;
int fd_matriceB;
int fd_matriceC;
int i=0,j=0;
char *token;
char bufferA[4096];
char bufferB[4096];
char bufferC[4096];
const int dim=atoi(argv[4]);
int matriceA[dim][dim];
int matriceB[dim][dim];
int matriceC[dim][dim];
if(argc < 5){
printf(" Numero di argomenti insufficienti o non corretti\\n" );
exit(1);
}
if(!(fd_matriceA=open(argv[1],O_RDONLY))){
printf("Errore on Open matrice A\\n");
}
if(!(fd_matriceB=open(argv[2],O_RDONLY))){
printf("Errore on Open matrice A\\n");
}
if(!(fd_matriceC=open(argv[3],O_RDONLY))){
printf("Errore on Open matrice A\\n");
}
if(!read(fd_matriceA,bufferA,4096))
printf("file A non letto correttamente\\n");
if(!read(fd_matriceB,bufferB,4096))
printf("file B non letto correttamente\\n");
if(!read(fd_matriceC,bufferC,4096)){
printf("file C non letto correttamente\\n");
}
token=strtok(bufferA,";\\n");
i =0, j=0;
while(token != 0){
matriceA[i][j]=atoi(token);
j++;
if (i==dim){
i++;
j=0;
}
token=strtok(0,";\\n");
}
token=strtok(bufferB,";\\n");
i =0, j=0;
while(token != 0){
matriceB[i][j]=atoi(token);
j++;
if (i==dim){
i++;
j=0;
}
token=strtok(0,";\\n");
}
int **ptrA= (int**)malloc(dim*sizeof(int * ));
int **ptrB= (int**)malloc(dim*sizeof(int * ));
int **ptrC= (int**)malloc(dim*sizeof(int * ));
int * sum =(int *) malloc(sizeof(int));
for(i=0;i<dim;i++){
ptrA[i]=(int *)malloc(sizeof(int));
ptrB[i]=(int *)malloc(sizeof(int));
ptrC[i]=(int *)malloc(sizeof(int));
}
for(i=0;i<dim;i++){
for(j=0;j<dim;j++){
ptrA[i][j]=matriceA[i][j];
ptrB[i][j]=matriceB[i][j];
}
}
pthread_mutex_init(&mutex,0);
pthread_t singola[dim][dim];
msg *toParent;
for(i=0;i<dim;i++){
for(j=0;j<dim;j++){
toParent=(msg *) malloc(sizeof(msg));
toParent->matA=ptrA;
toParent->matB=ptrB;
toParent->matC=ptrC;
toParent->dimensione=dim;
toParent->operazione='m';
toParent->riga=i;
toParent->colonna=j;
if(pthread_create(&singola[i][j],0,&threadFiglio,(void *)toParent)<0){
printf("C'è stato un errore nella creazione del thread");
exit(0);
}
}
}
for(i=0;i<dim;i++){
toParent=(msg *) malloc(sizeof(msg));
toParent->matA=ptrA;
toParent->matB=ptrB;
toParent->matC=ptrC;
toParent->dimensione=dim;
toParent->operazione='s';
toParent->riga=i;
toParent->colonna=0;
toParent->somma=sum;
if(pthread_create(&singola[i][0],0,&threadFiglio,(void *)toParent)<0){
printf("C'è stato un errore nella creazione del thread");
exit(0);
}
}
for ( i = 0; i < dim; i++) {
for(j=0;j<dim;j++){
pthread_join(singola[i][j],0);
}
}
for ( i = 0; i < dim; i++) {
for(j=0;j<dim;j++){
printf("%i \\t",ptrC[i][j] );
if(j==dim-1){
printf("\\n" );
}
}
}
printf("somma vale ==> %i\\n",*sum );
for(i=0;i<dim;i++){
free(ptrA[i]);
free(ptrB[i]);
free(ptrC[i]);
}
pthread_mutex_destroy(&mutex);
printf("padre ha finito tutto\\n" );
}
| 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>
int fd = -1;
int open_port(char* serial_path, int speed) {
fd = open(serial_path, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
status->pipe_error = PIPE_COULD_NOT_OPEN_ERROR;
return -1;
}
fcntl(fd, F_SETFL, FNDELAY);
struct termios options;
tcgetattr(fd, &options);
if (speed > 0) {
cfsetispeed(&options, speed);
cfsetospeed(&options, speed);
}
options.c_cflag |= (CLOCAL | CREAD);
tcsetattr(fd, TCSANOW, &options);
status->pipe_error = 0;
return fd;
}
int wait_on_data(int fd, uint64_t millisec) {
struct pollfd fds;
int retval;
fds.fd = fd;
fds.events = POLLIN | POLLRDNORM | POLLPRI;
retval = poll(&fds, 1, millisec);
if (retval == -1) {
}
return retval;
}
void imprint_current_time(char* s) {
time_t t = time(0);
struct tm tm = *localtime(&t);
sprintf(s, "%d/%d/%d UTC %02d:%02d:%02d:%03d", tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, (int)(millis() % 1000));
}
size_t parse(char* buffer, size_t buff_len) {
size_t i, j;
char* line = malloc(sizeof(char)*M);
for (i = 0, j = 0; i < buff_len; i++) {
if (buffer[i] == '\\n') {
memcpy(line, buffer+j, i-j);
line[i-j] = 0;
if (i-j > 0) {
double curr_time = ((double)micros())/1000000.0;
if (use_mysql) {
}
if (use_server) {
tail_str_list_server = add_str_node(tail_str_list_server, line, curr_time);
atomicAdd32(&str_list_size_server, 1);
}
if (use_log) {
tail_str_list_log = add_str_node(tail_str_list_log, line, curr_time);
atomicAdd32(&str_list_size_log, 1);
}
pthread_mutex_lock(&status_lock);
strncpy(status->values.text, line, sizeof(status->values.text));
status->values.text[sizeof(status->values.text)-1] = 0;
status->values.time = curr_time;
pthread_mutex_unlock(&status_lock);
}
j = i + 1;
}
}
free(line);
return j;
}
void* obtain_data(void* arg) {
fd = open_port(serial_path, serial_speed);
char line[M];
char buffer[N<<2];
size_t buff_len = 0;
line[0] = 0;
uint64_t bytes_written = 0;
while (running) {
char socket_neg = 0;
if (fd == -1) socket_neg = 1;
else socket_neg = 0;
if (socket_neg) {
close(fd);
status->pipe_error = PIPE_CLOSED_ERROR;
fd = open_port(serial_path, serial_speed);
delay(100);
} else {
wait_on_data(fd, 1000);
int read_bytes = read(fd, line, M-1);
if (read_bytes > 0) {
memcpy(buffer+buff_len, line, read_bytes);
buff_len += read_bytes;
if (buff_len > N<<2)
buff_len = N<<2;
buffer[buff_len] = 0;
int j = parse(buffer, buff_len);
memmove(buffer, buffer+j, buff_len - j);
buff_len = buff_len - j;
buffer[buff_len] = 0;
bytes_written += j;
line[read_bytes] = 0;
} else if (read_bytes == 0) {
} else {
}
}
}
return 0;
}
| 1
|
#include <pthread.h>
char *buf[10];
pthread_mutex_t lock;
int stock;
pthread_cond_t condlock;
int count;
void * produce(void * arg){
while(1){
pthread_mutex_lock(&lock);
while(stock >= 10)
pthread_cond_wait(&condlock, &lock);
sprintf(buf[stock],"consumer %d\\n", count++);
stock++;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&condlock);
}
return (void*)0;
}
void* consumer(void * arg){
while(1){
pthread_mutex_lock(&lock);
while(stock<=0)
pthread_cond_wait(&condlock, &lock);
printf("%s",buf[stock]);
stock--;
pthread_cond_signal(&condlock);
pthread_mutex_unlock(&lock);
}
return (void*) 0;
}
int main(){
for(int i=0; i<10; ++i)
buf[i] = (char*) malloc(sizeof(char) * 4096);
pthread_mutex_init(&lock, 0);
pthread_cond_init(&condlock, 0);
pthread_t tid[8];
for(int i=0; i<8/2; i++)
pthread_create(tid+i, 0, consumer,0);
for(int i=8/2; i<8; i++)
pthread_create(tid+i, 0, produce,0);
sleep(2);
return 0;
}
| 0
|
#include <pthread.h>
struct foo {
int f_count;
pthread_mutex_t f_lock;
struct foo *f_next;
int f_id;
};
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
void fh_init() {
int i;
pthread_mutex_lock(&hashlock);
for(i = 0; i < 29; ++i)
fh[i] = 0;
pthread_mutex_unlock(&hashlock);
}
struct foo *foo_alloc(int id) {
struct foo *fp;
int idx;
if((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 0;
if(pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return 0;
}
idx = (((unsigned long)fp) % 29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
fp->f_id = id;
pthread_mutex_unlock(&fp->f_lock);
printf("object id %d at hash index %d\\n", id, idx);
}
return fp;
}
void foo_hold(struct foo *fp) {
pthread_t tid = pthread_self();
if(fp == 0) {
err_msg("get NULL fp in foo_hold\\n");
return;
}
pthread_mutex_lock(&fp->f_lock);
++fp->f_count;
printf("foo_hold: thread %ld gets lock, object id %d, f_count %d\\n",
tid, fp->f_id, fp->f_count);
pthread_mutex_unlock(&fp->f_lock);
}
struct foo *foo_find(struct foo *ifp, int id) {
struct foo *fp;
int idx;
idx = (((unsigned long)ifp) % 29);
pthread_mutex_lock(&hashlock);
for(fp = fh[idx]; fp != 0; fp = fp->f_next) {
if(fp->f_id == id) {
foo_hold(fp);
break;
}
}
pthread_mutex_unlock(&hashlock);
return fp;
}
int foo_rele(struct foo *fp) {
struct foo *tfp;
int idx;
pthread_t tid = pthread_self();
pthread_mutex_lock(&fp->f_lock);
if(fp->f_count == 1) {
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_lock(&hashlock);
pthread_mutex_lock(&fp->f_lock);
if(fp->f_count != 1) {
fp->f_count--;
printf("foo_rele: thread %ld gets lock, object id %d, f_count %d\\n",
tid, fp->f_id, fp->f_count);
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
return 0;
}
idx = (((unsigned long)fp) % 29);
tfp = fh[idx];
if(tfp == fp) {
fh[idx] = fp->f_next;
} else {
while(tfp->f_next != fp)
tfp = tfp->f_next;
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
printf("foo_rele: thread %ld free object id %d\\n",
tid, fp->f_id);
free(fp);
return 1;
} else {
fp->f_count--;
printf("foo_rele: thread %ld gets lock, object id %d, f_count %d\\n",
tid, fp->f_id, fp->f_count);
pthread_mutex_unlock(&fp->f_lock);
}
return 0;
}
pthread_t thdarr[1000];
void *thr_fn(void *arg) {
int id, i;
pthread_t tid = pthread_self();
struct foo *fp = 0;
id = tid % 100;
for(i = 0; i < 29; ++i) {
if(fh[i] != 0) {
fp = foo_find(fh[i], id);
if(fp != 0){
printf("thread %ld finds object id %d at hash idx %d\\n",
tid, id, i);
break;
}
}
}
if(fp != 0) {
sleep(1);
foo_rele(fp);
} else {
printf("thread %ld can't find id %d\\n", tid, id);
}
printf("thread %ld returns\\n", tid);
return (void *)0;
}
int main(void) {
struct foo *fp;
int i, err, thrjoin;
pthread_t tid;
fh_init();
for (i = 0; i < 100; ++i) {
if ((fp = foo_alloc(i)) == 0)
err_sys("foo_alloc error");
}
for (i = 0; i < 1000; ++i) {
err = pthread_create(&tid, 0, thr_fn, 0);
if (err != 0)
err_quit("can't create thread: %s\\n", strerror(err));
thdarr[i] = tid;
printf("new thread %ld\\n", tid);
}
while(1) {
thrjoin = 0;
for(i = 0; i < 1000; ++i) {
if(thdarr[i] != 0) {
pthread_join(thdarr[i], 0);
thdarr[i] = 0;
thrjoin = 1;
}
}
if(thrjoin == 0)
return 0;
sleep(1);
}
}
| 1
|
#include <pthread.h>
int totalNumOfPassengers = 10;
int numOfPassengersOnBus = 0;
int maxPassenger = 5;
int isBusArrived = 0;
void* bus(void* ptr);
void* passenger(void* ptr);
pthread_cond_t condFull, condArrived, condEmpty, condAvailable;
pthread_mutex_t lock;
int main(int argc, char* argv[])
{
srand(time(0));
pthread_cond_init(&condFull, 0);
pthread_cond_init(&condArrived, 0);
pthread_cond_init(&condEmpty, 0);
pthread_cond_init(&condAvailable, 0);
pthread_mutex_init(&lock, 0);
pthread_t tBus;
pthread_t* tPassengers = malloc(sizeof(pthread_t)*totalNumOfPassengers);
const char* busMsg = "Bus";
pthread_create(&tBus, 0, bus, (void*)busMsg );
for(int i=0; i<totalNumOfPassengers; i++)
{
pthread_create(&tPassengers[i], 0, passenger, 0 );
}
sleep(1);
pthread_join(tBus, 0);
for(int i=0; i<totalNumOfPassengers; i++)
{
pthread_join(tPassengers[i], 0);
}
return 0;
}
void* bus(void* ptr)
{
char* tName = (char*) ptr;
while(1)
{
pthread_mutex_lock(&lock);
if(isBusArrived == 0)
{
isBusArrived = 1;
printf("%s arrived with %d passengers!\\n", tName, numOfPassengersOnBus);
pthread_cond_broadcast(&condArrived);
}
while(numOfPassengersOnBus>0)
{
printf("%s waits to empty all %d passengers...\\n", tName, numOfPassengersOnBus);
pthread_cond_wait(&condEmpty, &lock);
}
printf("%s unloaded all passengers. Now loading new passengers.\\n", tName);
while(numOfPassengersOnBus<maxPassenger)
pthread_cond_wait(&condFull, &lock);
printf("%s loaded max %d passengers. Depart...\\n", tName, maxPassenger);
isBusArrived = 0;
pthread_mutex_unlock(&lock);
sleep(rand()%2);
}
return 0;
}
void* passenger(void* ptr)
{
static int globalId = 0;
int isOnBus = 0;
char msg[12];
sprintf(msg, "Passenger%d", globalId);
globalId++;
while(1)
{
pthread_mutex_lock(&lock);
while(isBusArrived==0)
{
printf("%s waits the bus to arrive...\\n", msg);
pthread_cond_wait(&condArrived, &lock);
}
if(numOfPassengersOnBus==0)
{
pthread_cond_broadcast(&condEmpty);
printf("%s notified that the bus is empty!\\n", msg);
}
if(isOnBus==0)
{
while(numOfPassengersOnBus==maxPassenger)
{
printf("%s waits the bus to have space...\\n", msg);
pthread_cond_wait(&condAvailable, &lock);
}
numOfPassengersOnBus++;
printf("%s got into the bus. Total passengers now = %d.\\n", msg, numOfPassengersOnBus);
isOnBus=1;
}
else
{
while(isBusArrived==0)
{
printf("%s is on the bus and wait to his destination...\\n", msg);
pthread_cond_wait(&condArrived, &lock);
}
numOfPassengersOnBus--;
printf("%s got off the bus. Total passengers now = %d.\\n", msg, numOfPassengersOnBus);
isOnBus = 0;
pthread_cond_broadcast(&condAvailable);
}
if(numOfPassengersOnBus==maxPassenger)
{
pthread_cond_broadcast(&condFull);
printf("%s notified that the bus is full!\\n", msg);
}
pthread_mutex_unlock(&lock);
sleep(rand()%maxPassenger);
}
return 0;
}
| 0
|
#include <pthread.h>
{
int meals[5];
pthread_mutex_t mutex;
} meal_data;
meal_data shared;
{
FILE *outputFile;
pthread_t philosophers[5];
void* status;
int error;
} dinner_table;
dinner_table thisTable;
void philosopher(int i);
void think();
void eat(int i);
void take_fork(int i);
void put_fork(int i);
void philosopher(int i)
{
fprintf(thisTable.outputFile, "Philosopher number %d enters the room\\n", i);
while((shared.meals[i] < 5))
{
think();
pthread_mutex_lock(&shared.mutex);
take_fork((i + 5 - 1) % 5);
take_fork((i+1) % 5);
eat(i);
put_fork((i + 5 - 1) % 5);
put_fork((i+1) % 5);
pthread_mutex_unlock(&shared.mutex);
}
}
void think()
{
pthread_yield_np();
}
void eat(int i)
{
}
void take_fork(int i)
{
fprintf(thisTable.outputFile, "pick up fork %d\\n", i);
}
void put_fork(int i)
{
fprintf(thisTable.outputFile, "put down fork %d\\n", i);
}
static void* initPhilosopher(void *i)
{
philosopher((int)(uintptr_t) i);
return 0;
}
int main(int argc, const char * argv[])
{
thisTable.outputFile = fopen("butler.output", "w");
pthread_mutex_init(&shared.mutex, 0);
int i;
for (i = 0; i < 5; i++)
{
thisTable.error = pthread_create(&thisTable.philosophers[i], 0, initPhilosopher, (void *)(intptr_t) i);
}
for (i = 0; i < 5; i++)
{
thisTable.error = pthread_join(thisTable.philosophers[i], &thisTable.status);
fprintf(thisTable.outputFile, "Philosopher %d left the room\\n", i);
}
pthread_mutex_destroy(&shared.mutex);
fprintf(thisTable.outputFile, "The end.\\n");
thisTable.outputFile = fopen("states.output", "w");
return 0;
}
| 1
|
#include <pthread.h>
struct block_filter * create_block_filter(int block_size, int block_num) {
struct block_filter * filter = 0;
struct block * blocks = 0;
u_char *data = 0;
int i;
filter = malloc(sizeof(struct block_filter));
if (filter == 0)
goto OK;
blocks = malloc(block_num * sizeof(struct block));
if (blocks == 0)
goto Fail1;
data = malloc(block_size * block_num);
if (data == 0)
goto Fail2;
memset(filter, 0, sizeof(struct block_filter));
memset(blocks, 0, block_num * sizeof(struct block));
filter->block_data=data;
filter->block_size = block_size;
filter->block_num = block_num;
filter->blosk_list = blocks;
filter->full_list = 0;
filter->empty_list = 0;
pthread_cond_init(&(filter->cond_full), 0);
pthread_mutex_init(&(filter->mutex_full), 0);
pthread_cond_init(&(filter->cond_empt), 0);
pthread_mutex_init(&(filter->mutex_empt), 0);
for (i = 0; i < block_num; i++) {
blocks[i].filter=filter;
blocks[i].block_no = i;
blocks[i].block_size = block_size;
blocks[i].data = data + i * block_size;
if (filter->empty_list == 0) {
blocks[i].next = blocks + i;
blocks[i].prev = blocks + i;
filter->empty_list = blocks + i;
} else {
blocks[i].next = filter->empty_list;
blocks[i].prev = filter->empty_list->prev;
filter->empty_list->prev->next = blocks + i;
filter->empty_list->prev = blocks + i;
}
}
goto OK;
Fail2: free(blocks);
Fail1: free(filter);
filter = 0;
OK: return filter;
}
struct block *get_block(struct block_filter* filter, int timeout,
enum block_status status) {
struct block** pblock_head = 0;
struct block *pblock = 0;
pthread_cond_t * cond = 0;
pthread_mutex_t *mutex = 0;
struct timespec abstime;
struct timeval now;
if (status == BLOCK_EMPTY) {
pblock_head = &(filter->empty_list);
mutex = &(filter->mutex_empt);
cond = &(filter->cond_empt);
} else {
pblock_head = &(filter->full_list);
mutex = &(filter->mutex_full);
cond = &(filter->cond_full);
}
pthread_mutex_lock(mutex);
pblock = *pblock_head;
if (pblock != 0) {
if (pblock->next == pblock) {
*pblock_head = 0;
} else {
pblock->prev->next = pblock->next;
pblock->next->prev = pblock->prev;
*pblock_head = pblock->next;
}
} else {
if (timeout < 0) {
pthread_cond_wait(cond, mutex);
} else if (timeout > 0) {
gettimeofday(&now, 0);
long nsec = now.tv_usec * 1000 + (timeout % 1000) * 1000000;
abstime.tv_nsec = nsec % 1000000000;
abstime.tv_sec = now.tv_sec + nsec / 1000000000 + timeout / 1000;
pthread_cond_timedwait(cond, mutex, &abstime);
}
pblock = *pblock_head;
if (pblock != 0) {
if (pblock->next == pblock) {
*pblock_head = 0;
} else {
pblock->prev->next = pblock->next;
pblock->next->prev = pblock->prev;
*pblock_head = pblock->next;
}
}
}
pthread_mutex_unlock(mutex);
return pblock;
}
void put_block(struct block *pblock,enum block_status status) {
struct block** pblock_head = 0;
pthread_cond_t * cond = 0;
pthread_mutex_t *mutex = 0;
struct block_filter* filter=pblock->filter;
if (status == BLOCK_EMPTY) {
pblock_head = &(filter->empty_list);
mutex = &(filter->mutex_empt);
cond = &(filter->cond_empt);
} else {
pblock_head = &(filter->full_list);
mutex = &(filter->mutex_full);
cond = &(filter->cond_full);
}
pthread_mutex_lock(mutex);
if (*pblock_head == 0) {
pblock->next = pblock;
pblock->prev = pblock;
*pblock_head = pblock;
} else {
pblock->next = *pblock_head;
pblock->prev = (*pblock_head)->prev;
(*pblock_head)->prev->next = pblock;
(*pblock_head)->prev = pblock;
}
pthread_cond_signal(cond);
pthread_mutex_unlock(mutex);
}
| 0
|
#include <pthread.h>
struct passed_args{
long pid;
};
pthread_mutex_t count_mutex;
pthread_mutex_t mutex;
pthread_mutex_t print_mutex;
long int accessers = 0;
void *accesser(void *passed_arg);
int main(int argc, char **argv)
{
if (argc != 2) {
printf(
"USAGE: p1 accessers\\n"
);
exit(1);
}
int num_thread = atoi(argv[1]);
pthread_t threads[num_thread];
struct passed_args a[num_thread];
if (pthread_mutex_init(&count_mutex, 0) != 0) {
printf("ERROR: Count init failed\\n");
exit(1);
}
if (pthread_mutex_init(&mutex, 0) != 0) {
printf("ERROR: Mutex init failed\\n");
exit(1);
}
if (pthread_mutex_init(&print_mutex, 0) != 0) {
printf("ERROR: Print Mutex Init failed\\n");
exit(1);
}
for (long i = 0; i < num_thread; ++i) {
a[i].pid = i;
pthread_create(&(threads[i]),
0,
accesser,
(void *)&a[i]);
}
while(1 == 1) {
sleep(10);
}
for (long i = 0; i < num_thread; ++i) {
pthread_join(threads[i], 0);
}
return 0;
}
void *accesser(void *passed_arg)
{
struct passed_args *a = (struct passed_args*) passed_arg;
while (1 == 1) {
pthread_mutex_lock(&count_mutex);
accessers += 1;
if (accessers > 3) {
pthread_mutex_lock(&mutex);
pthread_mutex_lock(&print_mutex);
printf("Accesser %ld waiting\\n",
a->pid);
pthread_mutex_unlock(&print_mutex);
}
pthread_mutex_unlock(&count_mutex);
pthread_mutex_lock(&print_mutex);
printf("Accesser %ld accessing resource\\n",
a->pid);
pthread_mutex_unlock(&print_mutex);
sleep(1);
pthread_mutex_lock(&count_mutex);
accessers -= 1;
if (accessers <= 3) {
pthread_mutex_unlock(&mutex);
}
pthread_mutex_unlock(&count_mutex);
}
return 0;
}
| 1
|
#include <pthread.h>
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo {
int f_count;
pthread_mutex_t f_lock;
int f_id;
struct foo *f_next;
};
struct foo *foo_alloc(int id) {
struct foo *fp;
int idx;
if ((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 1;
fp->f_id = id;
if (pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return 0;
}
idx = (((unsigned long) id) % 29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
}
return fp;
}
void foo_hold(struct foo *fp) {
pthread_mutex_lock(&hashlock);
fp->f_count++;
pthread_mutex_unlock(&hashlock);
}
struct foo *foo_find(int id) {
struct foo *fp;
pthread_mutex_lock(&hashlock);
for (fp = fh[(((unsigned long) id) % 29)]; fp != 0; fp = fp->f_next) {
if (fp->f_id == id) {
fp->f_count++;
break;
}
}
pthread_mutex_unlock(&hashlock);
return fp;
}
void foo_rele(struct foo *fp) {
struct foo *tfp;
int idx;
pthread_mutex_lock(&hashlock);
if (--fp->f_count == 0) {
idx = (((unsigned long) fp->f_id) % 29);
tfp = fh[idx];
if (tfp == fp) {
fh[idx] = fp->f_next;
} else {
while (tfp->f_next != fp) {
tfp = tfp->f_next;
}
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
} else {
pthread_mutex_unlock(&hashlock);
}
}
| 0
|
#include <pthread.h>
unsigned int global;
static pthread_mutex_t mutex;
void *increment_global(void *threadid)
{
printf("Valeur initiale : %d\\n", global);
pthread_mutex_lock(&mutex);
while (global < 1e8) {
global++;
}
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main (int argc, char *argv[])
{
pthread_t threads[2];
int i,
rc;
void *ret;
global = 0;
pthread_mutex_init (&mutex, 0);
for(i=0; i < 2; i++){
printf("Dans main : creation thread %d\\n", i);
rc = pthread_create(&threads[i], 0, increment_global, (void *)i);
if (rc){
printf("Erreur creation thread : %d\\n", rc);
exit(2);
}
}
for (i = 0; i < 2; ++i) {
(void)pthread_join (threads[i], &ret);
}
printf("global : %d\\n", global);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
struct job {
struct job* next;
int value;
};
struct job* job_queue;
pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER;
void process_job(struct job* job)
{
printf("now thread: %d finish the job: %d\\n", (int)pthread_self(), job->value);
}
void* thread_function (void* arg)
{
while (1) {
struct job* next_job;
pthread_mutex_lock (&job_queue_mutex);
if (job_queue == 0)
next_job = 0;
else {
next_job = job_queue;
job_queue = job_queue->next;
}
pthread_mutex_unlock (&job_queue_mutex);
if (next_job == 0)
break;
process_job (next_job);
free (next_job);
}
return 0;
}
int main()
{
int job_size = 1000;
int thread_num = 5;
int i;
struct job* jobs_pre = (struct job*) malloc(sizeof(struct job));
jobs_pre->value = 0;
jobs_pre->next = 0;
job_queue = jobs_pre;
for (i = 1; i < job_size; i++)
{
struct job* jobs = (struct job*)malloc(sizeof(struct job));
jobs->value = i;
jobs_pre->next = jobs;
jobs_pre = jobs;
jobs->next = 0;
}
pthread_t thread_id[thread_num];
for (i = 0; i < thread_num; i++)
pthread_create(&thread_id[i], 0, &thread_function, 0);
for (i = 0; i < thread_num; i++)
pthread_join(thread_id[i], 0);
return 0;
}
| 0
|
#include <pthread.h>
void initSwitchBuffer(struct switch_buffer ** buffer, unsigned int size);
void freeSwitchBuffer(struct switch_buffer ** buffer);
int switchBufferQueue(struct switch_buffer * buffer, struct switch_if * receiverIf, const u_char * packetData, const int packetLength);
const struct switch_buffer_item * switchBufferDequeue(struct switch_buffer * buffer);
void initSwitchBuffer(struct switch_buffer ** buffer, unsigned int size) {
debug_print("%s\\n", "START");
if (buffer != 0 && *buffer != 0)
debug_print("%s\\n", "Buffer already initialized -> freeing");
freeSwitchBuffer(buffer);
if (size > SWITCH_BUFFER_MAX_SIZE)
size = SWITCH_BUFFER_MAX_SIZE;
(*buffer) = (struct switch_buffer *) malloc(sizeof(struct switch_buffer));
if (*buffer == 0) {
debug_print("%s\\n", "Error initializing buffer");
return;
}
(*buffer)->size = size;
(*buffer)->start = 0;
(*buffer)->end = 0;
pthread_mutex_init(&(*buffer)->mutex, 0);
(*buffer)->items = (struct switch_buffer_item *) malloc(sizeof(struct switch_buffer_item) * (*buffer)->size);
if ((*buffer)->items == 0) {
debug_print("%s\\n", "Error initializing buffer items");
free((void *) *buffer);
*buffer = 0;
return;
}
for (int i = 0; i < (*buffer)->size; i++) {
(*buffer)->items[i].packetData = (u_char *) malloc(sizeof(u_char) * SWITCH_BUFFER_PACKET_DATA_SIZE);
if ((*buffer)->items[i].packetData == 0) {
debug_print("%s\\n", "Error initializing buffer packet data");
freeSwitchBuffer(buffer);
return;
}
}
debug_print("%s\\n", "END");
}
void freeSwitchBuffer(struct switch_buffer ** buffer) {
debug_print("%s\\n","START");
if (buffer == 0 || *buffer == 0)
return;
pthread_mutex_destroy(&(*buffer)->mutex);
for (int i = 0; i < (*buffer)->size; i++) {
if ((*buffer)->items[i].packetData != 0)
free((void *) (*buffer)->items[i].packetData);
}
free((void *) (*buffer)->items);
free((void *) *buffer);
*buffer = 0;
debug_print("%s\\n","END");
}
int switchBufferQueue(struct switch_buffer * buffer, struct switch_if * receiverIf,const u_char * packetData, const int packetLength) {
if (buffer == 0) {
debug_print("%s\\n", "Cannot queue to unitialized buffer");
return 0;
}
pthread_mutex_lock(&buffer->mutex);
if (buffer->start == (buffer->end + 1) % buffer->size) {
pthread_mutex_unlock(&buffer->mutex);
return 0;
}
buffer->items[buffer->end].receiverIf = receiverIf;
buffer->items[buffer->end].size = packetLength;
memcpy(buffer->items[buffer->end].packetData, packetData,sizeof(char) * packetLength);
buffer->end = (buffer->end + 1) % buffer->size;
pthread_mutex_unlock(&buffer->mutex);
return 1;
}
const struct switch_buffer_item * switchBufferDequeue(struct switch_buffer * buffer) {
if (buffer == 0) {
debug_print("%s\\n", "Cannot dequeue to unitialized buffer");
return 0;
}
pthread_mutex_lock(&buffer->mutex);
struct switch_buffer_item * retItem = 0;
if (buffer->start == buffer->end) {
pthread_mutex_unlock(&buffer->mutex);
return 0;
}
retItem = &buffer->items[buffer->start];
buffer->start = (buffer->start + 1) % buffer->size;
pthread_mutex_unlock(&buffer->mutex);
return retItem;
}
| 1
|
#include <pthread.h>
struct args {
int n;
int s;
int* threadid;
};
double* A=0;
double* B=0;
double* C = 0;
void Get_dims(int* n_p);
void *Mat_Mat_mult(void *arguments);
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int main(void) {
double* A = 0;
double* B = 0;
double c = 0.0;
int n, i, j;
clock_t start, end;
double cpu_time_used;
pthread_t threads[2];
Get_dims(&n);
A = malloc(n*n*sizeof(double));
B = malloc(n*n*sizeof(double));
C = malloc(n*n*sizeof(double));
if (A == 0 || B == 0 || C == 0) {
fprintf(stderr, "Can't allocate storage\\n");
exit(-1);
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
A[i*n+j] = 2.0;
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
B[i*n+j] = 3.0;
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
C[i*n+j] = 0.0;
}
}
struct args *mult_args;
mult_args->n = n;
mult_args->s = 250;
mult_args->threadid = 0;
start = clock();
int t,rc;
for(t=0;t<2;t++){
mult_args->threadid =&t;
rc = pthread_create(&threads[t], 0, Mat_Mat_mult, &mult_args);
if (rc){
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("The Loop Runtime is %f ", cpu_time_used);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
c += C[i*n+j];
}
}
c = c / (n*n);
printf("The average of the matrix is %f ", c);
free(A);
free(B);
free(C);
return 0;
}
void Get_dims(int* n_p ) {
printf("Enter the dimension of the matrix\\n");
scanf("%d", n_p);
if (*n_p <= 0) {
fprintf(stderr, "n must be positive\\n");
exit(-1);
}
}
void *Mat_Mat_mult(void *arguments) {
int i, j, k, it, jt, kt,my_beg, my_fin, my_n, s, n, h,my_tid ;
long tid;
double* my_A = 0;
double* my_B = 0;
double* my_C = 0;
struct args *my_args;
my_args = (struct args *) arguments;
tid = (long) my_args->threadid;
my_tid=(int) tid;
n = (int) my_args -> n;
my_n = n/2;
s = (int) my_args -> s;
my_beg=tid*(n/2);
my_fin= (tid+1)*(n/2);
my_A = malloc(n*n/2*sizeof(double));
my_B = malloc(n*n/2*sizeof(double));
my_C = malloc(n*n/2*sizeof(double));
h= 0;
if(h<my_n){
for (i = my_beg; i < my_fin; i++) {
for (j = 0; j < my_n; j++) {
my_A[n*h+j] = A[i*n+j];
my_B[n*h+j] = B[i*n+j];
my_C[n*h+j] = C[i*n+j];
}
h++;
}
}
for (it = 0; it < my_n; it+=s) {
for (kt = 0; kt < my_n; kt+=s) {
for (jt = 0; jt < my_n; jt+=s) {
for (i = it; i < (((it+374) < (n/2)) ? (it+374) : (n/2)); i++) {
for (k = kt; k < (((kt+s-1) < (n)) ? (kt+s-1) : (n)); k++) {
for (j = jt; j < (((jt+s-1) < (n)) ? (jt+s-1) : (n)); j++) {
C[i*n+j] += my_A[i*n+k]*my_B[j*n+k];
}
}
}
}
}
}
pthread_mutex_lock(&mutex1);
h=0;
for(i=my_beg; i<my_fin; i++){
for (j=0; j<n; j++){
C[i*n+j] += my_C[n*h+j];
}
h++;
}
printf("Thread %i has finished its section.", my_tid);
pthread_mutex_unlock(&mutex1);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
sem_t full, empty;
buffer_type buffer[5];
int counter;
pthread_t thread_id;
pthread_attr_t attr;
void *producer_thread(void *param);
void *consumer_thread(void *param);
void initializi() {
pthread_mutex_init(&mutex, 0);
sem_init(&full, 0, 0);
sem_init(&empty, 0, 5);
pthread_attr_init(&attr);
counter = 0;
}
void *producer_thread(void *param) {
buffer_type item;
while(1) {
int rNum = rand() / 100000000;
sleep(rNum);
item = rand();
sem_wait(&empty);
pthread_mutex_lock(&mutex);
if(produce_item(item)) {
fprintf(stderr, " Producer report error condition\\n");
}
else {
printf("Producer working %d\\n", item);
}
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void *consumer_thread(void *param) {
buffer_type item;
while(1) {
int rNum = rand() / 100000000;
sleep(rNum);
sem_wait(&full);
pthread_mutex_lock(&mutex);
if(consume_item(&item)) {
fprintf(stderr, "Consumer report error condition\\n");
}
else {
printf("Consumer working %d\\n", item);
}
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
int produce_item(buffer_type item) {
if(counter < 5) {
buffer[counter] = item;
counter++;
return 0;
}
else {
return -1;
}
}
int consume_item(buffer_type *item) {
if(counter > 0) {
*item = buffer[(counter-1)];
counter--;
return 0;
}
else {
return -1;
}
}
int main(int argc, char *argv[]) {
if(argc != 4) {
fprintf(stderr, "./a.out <total sleep time> <no of produce thread> <no of consumer threads>");
}
int totalsleep = atoi(argv[1]),nConsumer = atoi(argv[3]),nProducer = atoi(argv[2]);
initializi();
int i;
for(i = 0; i < nConsumer; i++) {
pthread_create(&thread_id,&attr,consumer_thread,0);
}
for( i = 0; i < nProducer; i++) {
pthread_create(&thread_id,&attr,producer_thread,0);
}
sleep(totalsleep);
printf("finished sleep time of main \\t%d\\t seconds \\n",totalsleep);
exit(0);
}
| 1
|
#include <pthread.h>
struct list_node_s
{
int data;
struct list_node_s* next;
pthread_mutex_t mutex;
};
double timeval_diff(struct timeval *a, struct timeval *b)
{
return
(double)(a->tv_sec + (double)a->tv_usec/1000000) -
(double)(b->tv_sec + (double)b->tv_usec/1000000);
}
int thread_count;
struct list_node_s** head_pp;
pthread_mutex_t mutex;
pthread_mutex_t mutex2;
pthread_rwlock_t rwlock;
pthread_mutex_t head_p_mutex;
long thread;
long operaciones=100000;
double member=80;
double insert=10;
double del=10;
struct timeval t_ini, t_fin;
double secs;
int MemberP(int value)
{
struct list_node_s* temp_p;
pthread_mutex_lock(&head_p_mutex);
temp_p=*head_pp;
while(temp_p != 0 && temp_p->data<value)
{
if (temp_p->next != 0)
pthread_mutex_lock(&(temp_p->next->mutex));
if (temp_p == *head_pp)
pthread_mutex_unlock(&head_p_mutex);
pthread_mutex_unlock(&(temp_p->mutex));
temp_p=temp_p->next;
}
if (temp_p == 0 || temp_p->data >value)
{
if (temp_p == *head_pp)
pthread_mutex_unlock(&head_p_mutex);
if (temp_p != 0)
pthread_mutex_unlock(&(temp_p->mutex));
return 0;
}
else
{
if (temp_p == *head_pp)
pthread_mutex_unlock(&head_p_mutex);
pthread_mutex_unlock(&(temp_p->mutex));
return 1;
}
}
int Member(int value)
{
struct list_node_s* curr_p=*head_pp;
while(curr_p!=0 && curr_p->data < value)
curr_p=curr_p->next;
if(curr_p == 0 || curr_p->data >value)
return 0;
else
return 1;
}
int Insert(int value)
{
struct list_node_s* curr_p= *head_pp;
struct list_node_s* pred_p= 0;
struct list_node_s* temp_p;
while(curr_p != 0 && curr_p->data<value)
{
pred_p=curr_p;
curr_p=curr_p->next;
}
if(curr_p == 0 || curr_p->data > value)
{
temp_p=malloc(sizeof(struct list_node_s));
temp_p->data=value;
temp_p->next=curr_p;
if (pred_p == 0)
*head_pp=temp_p;
else
pred_p->next=temp_p;
return 1;
}
else
return 0;
}
int Delete(int value)
{
struct list_node_s* curr_p=*head_pp;
struct list_node_s* pred_p= 0;
while(curr_p != 0 && curr_p->data < value)
{
pred_p=curr_p;
curr_p=curr_p->next;
}
if(curr_p != 0 && curr_p->data == value)
{
if(pred_p == 0)
{
*head_pp=curr_p->next;
free(curr_p);
}
else
{
pred_p->next=curr_p->next;
free(curr_p);
}
return 1;
}
else
return 0;
}
void* Mutex(void* r)
{ long ops=(long) r;
for(int j=0;j<ops*member/100;j++)
{
pthread_mutex_lock(&mutex);
Member(rand()%10000);
pthread_mutex_unlock(&mutex);
}
for(int j=0;j<ops*insert/100;j++)
{
pthread_mutex_lock(&mutex);
Insert(rand()%10000);
pthread_mutex_unlock(&mutex);
}
for(int j=0;j<ops*del/100;j++)
{
pthread_mutex_lock(&mutex);
Delete(rand()%10000);
pthread_mutex_unlock(&mutex);
}
}
void* MutexNode(void* r)
{ long ops=(long) r;
printf("Operaciones %li \\n",ops);
for(int j=0;j<ops*member/100;j++)
MemberP(rand()%10000);
for(int j=0;j<ops*insert/100;j++)
Insert(rand()%10000);
for(int j=0;j<ops*del/100;j++)
Delete(rand()%10000);
}
void* RW(void* r)
{ long ops=(long) r;
for(int j=0;j<ops*member/100;j++)
{
pthread_rwlock_rdlock(&rwlock);
Member(rand()%10000);
pthread_rwlock_unlock(&rwlock);
}
for(int j=0;j<ops*insert/100;j++)
{
pthread_rwlock_wrlock(&rwlock);
Insert(rand()%10000);
pthread_rwlock_unlock(&rwlock);
}
for(int j=0;j<ops*del/100;j++)
{
pthread_rwlock_wrlock(&rwlock);
Delete(rand()%10000);
pthread_rwlock_unlock(&rwlock);
}
}
int main(int argc,char* argv[])
{
pthread_t* thread_handles;
struct list_node_s* head;
head=malloc(sizeof(struct list_node_s));
head->data=0;
head->next=0;
head_pp=&head;
thread_count=strtol(argv[1],0,10);
thread_handles=malloc (thread_count*sizeof(pthread_t));
for(int i =0; i<1000;++i)
Insert(i);
long op=operaciones/thread_count;
gettimeofday(&t_ini, 0);
for(thread=0;thread<thread_count;thread++)
{
pthread_create(&thread_handles[thread],0,Mutex,(void *)op);
}
for(thread=0;thread<thread_count;thread++)
pthread_join(thread_handles[thread],0);
gettimeofday(&t_fin, 0);
secs = timeval_diff(&t_fin, &t_ini);
printf("%.16g Mutex segundos\\n", secs );
free(thread_handles);
gettimeofday(&t_ini, 0);
for(thread=0;thread<thread_count;thread++)
{
pthread_create(&thread_handles[thread],0,MutexNode,(void *)op);
}
for(thread=0;thread<thread_count;thread++)
pthread_join(thread_handles[thread],0);
gettimeofday(&t_fin, 0);
secs = timeval_diff(&t_fin, &t_ini);
printf("%.16g MutexNODE segundos\\n", secs );
free(thread_handles);
return 0;
}
| 0
|
#include <pthread.h>
char getch(void);
struct RingBuffer
{
unsigned int tail;
unsigned int head;
unsigned char data[(16)];
};
char ringBufGetChar (struct RingBuffer *apBuffer)
{
int index;
index = apBuffer->head;
apBuffer->head = (apBuffer->head + 1) % (16);
return apBuffer->data[index];
}
void ringBufPutChar (struct RingBuffer *apBuffer, const char c)
{
apBuffer->data[apBuffer->tail] = c;
apBuffer->tail = (apBuffer->tail + 1) % (16);
}
static struct RingBuffer ring;
static sem_t semEmpty;
static sem_t semFull;
static sem_t semFinishSignal;
static pthread_mutex_t bufferAccess;
void* producer (void *param)
{
char c;
while (1)
{
if (sem_trywait(&semFinishSignal) == 0)
{
break;
}
if (sem_trywait(&semEmpty) == 0)
{
c = getch();
if (c == 'q' || c == 'Q')
{
sem_post(&semFinishSignal);
sem_post(&semFinishSignal);
}
pthread_mutex_lock(&bufferAccess);
ringBufPutChar(&ring, c);
pthread_mutex_unlock(&bufferAccess);
sem_post(&semFull);
}
}
return 0;
}
void* consumer (void *param)
{
char c;
printf("Znakovi preuzeti iz kruznog bafera:\\n");
while (1)
{
if (sem_trywait(&semFinishSignal) == 0)
{
break;
}
if (sem_trywait(&semFull) == 0)
{
pthread_mutex_lock(&bufferAccess);
c = ringBufGetChar(&ring);
pthread_mutex_unlock(&bufferAccess);
printf("%c", c);
fflush(stdout);
usleep((400000));
sem_post(&semEmpty);
}
}
return 0;
}
int main (void)
{
pthread_t hProducer;
pthread_t hConsumer;
sem_init(&semEmpty, 0, (16));
sem_init(&semFull, 0, 0);
sem_init(&semFinishSignal, 0, 0);
pthread_mutex_init(&bufferAccess, 0);
pthread_create(&hProducer, 0, producer, 0);
pthread_create(&hConsumer, 0, consumer, 0);
pthread_join(hConsumer, 0);
pthread_join(hProducer, 0);
sem_destroy(&semEmpty);
sem_destroy(&semFull);
sem_destroy(&semFinishSignal);
pthread_mutex_destroy(&bufferAccess);
printf("\\n");
return 0;
}
| 1
|
#include <pthread.h>
int bloqueadas = 0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void barreira(){
pthread_mutex_lock(&mutex);
if (bloqueadas == (5 -1)) {
pthread_cond_broadcast(&cond);
bloqueadas = 0;
} else {
bloqueadas++;
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
}
void* A (void* arg){
int tid = *(int*)arg, i;
int cont = 0, boba1, boba2;
for (i=0; i < 5; i++) {
cont++;
printf("Thread %d: cont=%d, passo=%d\\n", tid, cont, i);
barreira();
boba1=100; boba2=-100; while (boba2 < boba1) boba2++;
}
pthread_exit(0);
}
int main(int argc, char*argv[]) {
pthread_t *threads;
int t;
int *tid;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
threads = (pthread_t *) malloc(sizeof(pthread_t) * 5);
if(threads==0) {
printf("--ERRO: malloc()\\n"); exit(1);
}
for(t=0;t<5;t++){
tid = malloc(sizeof(int));
if(tid == 0){
printf("--ERRO: malloc()\\n"); exit(1);
}
*tid = t;
if(pthread_create(&threads[t],0,A,(void*)tid)){
printf("--ERRO: pthread_create()\\n"); exit(1);
}
}
for(t=0;t<5;t++){
if(pthread_join(threads[t],0)){
printf("--ERRO: pthread_join()\\n"); exit(1);
}
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
free(threads);
return 0;
}
| 0
|
#include <pthread.h>
void helloSender(void *param)
{
struct shared_mem *mem = (struct shared_mem*) param;
int len;
char *msg = formHelloPacket(mem->local_id, &len);
for(;;){
DBG("helloSender: saying hello!");
sendToNeighbours(0, msg, len, mem);
sleep(HELLO_TIMER);
}
}
void ddrSender(void *param)
{
struct shared_mem *mem = (struct shared_mem*) param;
int len;
char *msg = formDDRequestPacket(mem->local_id, &len);
for(;;){
sleep(DDR_TIMER);
DBG("helloSender: saying hello!");
sendToNeighbours(0, msg, len, mem);
}
}
void deathChecker(void *param)
{
struct shared_mem *mem = ((struct shared_mem*) param);
struct real_connection *conns = mem->p_connections;
time_t end;
double time_since_last_seen;
int i;
for(;;){
DBG("deathChecker: Let's check all the nodes!");
end = time(0);
for(i=MIN_ID; i<MAX_NODES; i++){
if(i==mem->local_id) continue;
pthread_mutex_lock(&(mem->mutexes->connection_mutex));
if(conns[i].online==ONLINE){
time_since_last_seen = difftime(end, conns[i].last_seen);
pthread_mutex_unlock(&(mem->mutexes->connection_mutex));
if(time_since_last_seen > DEATH_TIMER){
DBG("deathChecker: node %d is dead!", i);
pthread_mutex_lock(&(mem->mutexes->connection_mutex));
conns[i].online = OFFLINE;
pthread_mutex_unlock(&(mem->mutexes->connection_mutex));
reactToStateChange(i, OFFLINE, mem);
}
DBG("deathChecker: node %d is OK!", i);
}else{
pthread_mutex_unlock(&(mem->mutexes->connection_mutex));
}
}
sleep(DEATH_TIMER);
}
}
void reactToStateChange(int id, int new_state, struct shared_mem *mem)
{
pthread_mutex_lock(&(mem->mutexes->status_mutex));
if(mem->p_status_table[id]==new_state) {
pthread_mutex_unlock(&(mem->mutexes->status_mutex));
return;
}else {
pthread_mutex_unlock(&(mem->mutexes->status_mutex));
}
if(new_state == ONLINE){
fprintf(stderr,"NODE %d WENT ONLINE!\\n", id);
}else{
fprintf(stderr,"NODE %d WENT OFFLINE!\\n", id);
}
pthread_mutex_lock(&(mem->mutexes->status_mutex));
mem->p_status_table[id] = new_state;
pthread_mutex_unlock(&(mem->mutexes->status_mutex));
createRoutingTable (mem);
sendNSU(id, new_state, mem);
if(new_state == OFFLINE){
int i;
pthread_mutex_lock(&(mem->mutexes->routing_mutex));
pthread_mutex_lock(&(mem->mutexes->status_mutex));
for(i=0; i<mem->p_routing_table->size; i++){
if(i!=mem->local_id && mem->p_routing_table->table[i].next_hop_id == -1){
mem->p_status_table[i] = OFFLINE;
}
}
pthread_mutex_unlock(&(mem->mutexes->status_mutex));
pthread_mutex_unlock(&(mem->mutexes->routing_mutex));
}
if(new_state == ONLINE && isNeighbour(mem->local_id, id, *(mem->p_topology))){
sleep(1);
int len;
char *packet = formDDRequestPacket(mem->local_id, &len);
sendToNeighbour(id, packet, len, mem);
}
resendUndeliveredMessages(id, mem);
}
void sendNSU(int id, int new_state, struct shared_mem *mem)
{
int len;
char *packet = formNSUPacket(id, new_state, &len);
sendToNeighbours(id, packet, len, mem);
}
void sendToNeighbours(int not_to, char *packet, int len, struct shared_mem *p_mem)
{
int id;
pthread_mutex_lock(&(p_mem->mutexes->connection_mutex));
struct real_connection *conns = p_mem->p_connections;
for(id=0; id<MAX_NODES; id++){
if(id != not_to && conns[id].id!=-1){
pthread_mutex_unlock(&(p_mem->mutexes->connection_mutex));
sendToNeighbour(id, packet, len, p_mem);
pthread_mutex_lock(&(p_mem->mutexes->connection_mutex));
}
}
pthread_mutex_unlock(&(p_mem->mutexes->connection_mutex));
}
int sendToId(int dest_id, char *packet, int len, struct shared_mem *p_mem, int retry)
{
pthread_mutex_lock(&(p_mem->mutexes->routing_mutex));
if(dest_id > p_mem->p_routing_table->size){
ERROR("cannot reach node %d -- ID too big!", dest_id);
pthread_mutex_unlock(&(p_mem->mutexes->routing_mutex));
return -1;
}else{
pthread_mutex_unlock(&(p_mem->mutexes->routing_mutex));
}
if(dest_id == p_mem->local_id){
ERROR("why would you send anything to yourself!?!");
return -1;
}
pthread_mutex_lock(&(p_mem->mutexes->routing_mutex));
DBG("trying to reach id %d\\n", dest_id);
int next_id = p_mem->p_routing_table->table[idToIndex(dest_id)].next_hop_id;
if(next_id==-1){
fprintf(stderr,"cannot reach node %d. %s\\n", dest_id, retry==RETRY?"Will try it later":"");
pthread_mutex_unlock(&(p_mem->mutexes->routing_mutex));
if(retry==RETRY){
addWaitingMessage(dest_id, len, packet, p_mem);;
}
return -1;
}else{
pthread_mutex_unlock(&(p_mem->mutexes->routing_mutex));
}
sendToNeighbour(next_id, packet, len, p_mem);
return 0;
}
| 1
|
#include <pthread.h>
static unsigned short timeout=10;
struct did_cache_entry {
char dirname[AFP_MAX_PATH];
unsigned int did;
struct timeval time;
struct did_cache_entry * next;
} ;
int free_entire_did_cache(struct afp_volume * volume)
{
struct did_cache_entry * d, * p, *p2;
pthread_mutex_lock(&volume->did_cache_mutex);
p=volume->did_cache_base;
for (d=volume->did_cache_base;d;d=p)
{
p2=p;
p=d->next;
free(p2);
}
pthread_mutex_unlock(&volume->did_cache_mutex);
return 0;
}
int remove_did_entry(struct afp_volume * volume, const char * name)
{
struct did_cache_entry * d, * p=0;
pthread_mutex_lock(&volume->did_cache_mutex);
for (d=volume->did_cache_base;d;d=d->next)
{
if (strcmp(d->dirname,name)==0) {
if (p)
p->next=d->next;
else
volume->did_cache_base=d->next;
volume->did_cache_stats.force_removed++;
free(d);
break;
} else
p=d;
}
pthread_mutex_unlock(&volume->did_cache_mutex);
return 0;
}
static int add_did_cache_entry(struct afp_volume * volume,
unsigned int new_did, char * path)
{
struct did_cache_entry * new, *old_base;
if ((new=malloc(sizeof(* new)))==0) return -1;
memset(new,0,sizeof(*new));
new->did=new_did;
memcpy(new->dirname,path,AFP_MAX_PATH);
gettimeofday(&new->time,0);
pthread_mutex_lock(&volume->did_cache_mutex);
old_base=volume->did_cache_base;
volume->did_cache_base=new;
new->next=old_base;
pthread_mutex_unlock(&volume->did_cache_mutex);
return 0;
}
unsigned char is_dir(struct afp_volume * volume,
unsigned int parentdid, const char * path)
{
int ret;
unsigned int filebitmap=0;
unsigned int dirbitmap=0;
struct afp_file_info fi;
ret =afp_getfiledirparms(volume,parentdid,
filebitmap,dirbitmap,path,&fi);
if (ret) return 0;
return fi.isdir;
}
static unsigned int find_dirid_by_fullname(struct afp_volume * volume,
char * path)
{
struct did_cache_entry * p, *prev=volume->did_cache_base;
struct timeval time;
unsigned int found_did=0;
unsigned char breakearly=0;
gettimeofday(&time,0);
pthread_mutex_lock(&volume->did_cache_mutex);
for (p=volume->did_cache_base;p;p=p->next) {
if (time.tv_sec > (p->time.tv_sec+timeout)) {
volume->did_cache_stats.expired++;
if (prev==volume->did_cache_base) {
if (strcmp(p->dirname,path)==0) breakearly=1;
volume->did_cache_base=p->next;
free(p);
if (breakearly) goto out;
p=volume->did_cache_base;
if (!p) goto out;
prev=volume->did_cache_base;
continue;
} else {
prev->next=p->next;
free(p);
p=prev;
}
}
if (strcmp(p->dirname,path)==0) {
found_did=p->did;
volume->did_cache_stats.hits++;
goto out;
}
prev=p;
}
out:
pthread_mutex_unlock(&volume->did_cache_mutex);
return found_did;
}
int get_dirid(struct afp_volume * volume, const char * path,
char * basename, unsigned int * dirid)
{
char * p, *p2;
int ret;
struct afp_file_info fi;
unsigned int filebitmap,dirbitmap;
unsigned int newdid;
unsigned int parent_did;
char copy[AFP_MAX_PATH];
if (((p=strrchr(path,'/')))==0) return -1;
if (basename) {
memset(basename,0,AFP_MAX_PATH);
memcpy(basename,p+1,strlen(path)-(p-path)-1);
}
if (p-path==0) {
*dirid=AFP_ROOT_DID;
goto out;
}
memcpy(copy,path,p-path+1);
if (copy[p-path]=='/') copy[p-path]='\\0';
if ((newdid=find_dirid_by_fullname(volume,copy))) {
*dirid=newdid;
goto out;
}
while ((p=strrchr(copy,'/'))) {
if (p==copy) {
parent_did=AFP_ROOT_DID;
break;
}
*p='\\0';
if ((parent_did=find_dirid_by_fullname(volume,copy))) {
break;
}
}
filebitmap=kFPNodeIDBit ;
dirbitmap=kFPNodeIDBit ;
p=path+(p-copy);
p2=p;
while ((p=strchr(p+1,'/'))) {
memset(copy,0,AFP_MAX_PATH);
memcpy(copy,p2,p-p2);
volume->did_cache_stats.misses++;
ret =afp_getfiledirparms(volume,parent_did,
filebitmap,dirbitmap,copy,&fi);
if (fi.isdir) {
memset(copy,0,AFP_MAX_PATH);
memcpy(copy,path,p-path);
add_did_cache_entry(volume, fi.fileid,copy);
} else {
break;
}
parent_did=fi.fileid;
p2=p;
}
*dirid=parent_did;
out:
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t id_mutex = PTHREAD_MUTEX_INITIALIZER;
static uint32_t next_id = 1;
static int wish_init_heartbeat_packet_impl( struct wish_state* state, struct wish_heartbeat_packet* h ) {
memset( h, 0, sizeof(struct wish_heartbeat_packet) );
struct sysinfo sys;
int rc = sysinfo( &sys );
if( rc < 0 ) {
return -errno;
}
wish_state_rlock( state );
struct statfs fs;
rc = statfs( state->conf.files_root, &fs );
wish_state_unlock( state );
if( rc < 0 ) {
return -errno;
}
rc = gettimeofday( &h->sendtime, 0 );
if( rc < 0 ) {
return -errno;
}
h->loads[0] = sys.loads[0];
h->loads[1] = sys.loads[1];
h->loads[2] = sys.loads[2];
h->ram_total = sys.totalram;
h->ram_free = sys.freeram + sys.bufferram;
h->disk_total = fs.f_blocks * fs.f_bsize;
h->disk_free = fs.f_bavail * fs.f_bsize;
return 0;
}
int wish_init_heartbeat_packet( struct wish_state* state, struct wish_heartbeat_packet* h ) {
int rc = wish_init_heartbeat_packet_impl( state, h );
if( rc != 0 )
return rc;
pthread_mutex_lock( &id_mutex );
h->id = next_id;
next_id++;
pthread_mutex_unlock( &id_mutex );
return 0;
}
int wish_init_heartbeat_packet_ack( struct wish_state* state, struct wish_heartbeat_packet* ack, struct wish_heartbeat_packet* original ) {
int rc = wish_init_heartbeat_packet_impl( state, ack );
if( rc != 0 )
return rc;
ack->id = original->id;
return 0;
}
int wish_init_nget_packet( struct wish_state* state, struct wish_nget_packet* npkt, uint64_t rank, uint32_t props ) {
npkt->rank = rank;
npkt->props = props;
return 0;
}
int wish_pack_heartbeat_packet( struct wish_state* state, struct wish_packet* wp, struct wish_heartbeat_packet* h ) {
wish_init_header( state, &wp->hdr, PACKET_TYPE_HEARTBEAT );
uint8_t* packet_buf = (uint8_t*)calloc( sizeof(struct wish_heartbeat_packet), 1 );
off_t offset = 0;
wish_pack_uint( packet_buf, &offset, h->id );
wish_pack_ulong( packet_buf, &offset, h->loads[0] );
wish_pack_ulong( packet_buf, &offset, h->loads[1] );
wish_pack_ulong( packet_buf, &offset, h->loads[2] );
wish_pack_ulong( packet_buf, &offset, h->ram_total );
wish_pack_ulong( packet_buf, &offset, h->ram_free );
wish_pack_ulong( packet_buf, &offset, h->disk_total );
wish_pack_ulong( packet_buf, &offset, h->disk_free );
wish_init_packet_nocopy( wp, &wp->hdr, packet_buf, sizeof(struct wish_heartbeat_packet) );
return 0;
}
int wish_pack_nget_packet( struct wish_state* state, struct wish_packet* wp, struct wish_nget_packet* pkt ) {
wish_init_header( state, &wp->hdr, PACKET_TYPE_NGET );
uint8_t* packet_buf = (uint8_t*)calloc( sizeof(struct wish_nget_packet), 1 );
off_t offset = 0;
wish_pack_ulong( packet_buf, &offset, pkt->rank );
wish_pack_uint( packet_buf, &offset, pkt->props );
wish_init_packet_nocopy( wp, &wp->hdr, packet_buf, sizeof(struct wish_nget_packet) );
return 0;
}
int wish_unpack_heartbeat_packet( struct wish_state* state, struct wish_packet* wp, struct wish_heartbeat_packet* h ) {
off_t offset = 0;
h->id = wish_unpack_uint( wp->payload, &offset );
h->loads[0] = wish_unpack_ulong( wp->payload, &offset );
h->loads[1] = wish_unpack_ulong( wp->payload, &offset );
h->loads[2] = wish_unpack_ulong( wp->payload, &offset );
h->ram_total = wish_unpack_ulong( wp->payload, &offset );
h->ram_free = wish_unpack_ulong( wp->payload, &offset );
h->disk_total = wish_unpack_ulong( wp->payload, &offset );
h->disk_free = wish_unpack_ulong( wp->payload, &offset );
return 0;
}
int wish_unpack_nget_packet( struct wish_state* state, struct wish_packet* wp, struct wish_nget_packet* pkt ) {
off_t offset = 0;
pkt->rank = wish_unpack_ulong( wp->payload, &offset );
pkt->props = wish_unpack_uint( wp->payload, &offset );
return 0;
}
| 1
|
#include <pthread.h>
pthread_t tid[R_THREADS];
pthread_mutex_t mutex;
sem_t sem;
char filebuffer[FB_SIZE][13];
int stop = 0;
int ri = 0;
int wi = 0;
void closeFile(int fp, char *filename){
if(flock(fp, LOCK_UN) == -1)
printf("[Reader] Failed to unlock file %s. (%s)\\n", filename, strerror(errno));
close(fp);
}
void checkFile(char *filename){
char aux[11];
int fp, i, n;
aux[10] = '\\0';
fp = open(filename, O_RDONLY);
if(fp == -1){
printf("[Reader] File %s not found!\\n", filename);
return;
}
if(flock(fp, LOCK_SH) == -1){
printf("[Reader] Failed to lock file %s. (%s)\\n", filename, strerror(errno));
close(fp);
return;
}
if(read(fp, aux, 10) == 0){
printf("[Reader] %s -> Incorrect. File is empty!\\n", filename);
closeFile(fp, filename);
return;
}
for(i = 0; i <= 9; i++){
if(strcmp(aux, _string[i]) == 0)
break;
else if(i == 9){
printf("[Reader] %s -> Incorrect. Error in line 1: %s\\n", filename, aux);
closeFile(fp, filename);
return;
}
}
for(n = 1; read(fp, aux, 10) != 0; n++){
if(strcmp(aux, _string[i]) != 0){
printf("[Reader] %s -> Incorrect. Line %d is different: %s\\n", filename, n+1, aux);
closeFile(fp, filename);
return;
}
}
if(n != 1024){
printf("[Reader] %s -> Incorrect. Number of Lines: %d\\n", filename, n);
closeFile(fp, filename);
return;
}
printf("[Reader] %s -> Correct.\\n", filename);
closeFile(fp, filename);
}
void *reader(){
char filename[13];
while(1){
sem_wait(&sem);
if(stop) break;
pthread_mutex_lock(&mutex);
strcpy(filename, filebuffer[ri]);
ri = (ri + 1) % FB_SIZE;
pthread_mutex_unlock(&mutex);
checkFile(filename);
}
pthread_exit(0);
return 0;
}
int main(){
char buffer[B_SIZE];
int n, size;
char *aux, *str;
if(pthread_mutex_init(&mutex, 0) == -1) {
printf("[Reader] Failed to initialize mutex.\\n");
return -2;
}
if(sem_init(&sem, 0, 0) == -1) {
printf("[Reader] Failed to initialize semaphore.\\n");
return -3;
}
printf("[Reader] Started.\\n");
for(n = 0; n < R_THREADS; n++){
if(pthread_create(&(tid[n]), 0, &reader, 0) != 0){
printf("[Reader] Failed to create thread.\\n");
return -1;
}
}
printf("[Reader] Threads created.\\n");
while(!stop){
if((size = read(STDIN_FILENO, buffer, B_SIZE)) > 0) {
buffer[size-1] = '\\0';
if(strcmp(buffer, "sair") == 0){
stop = 1;
for(n = 0; n < R_THREADS; n++)
sem_post(&sem);
}
str = buffer;
while(!stop) {
aux = strtok(str, " ");
if(aux == 0) break;
str = 0;
if(strlen(aux) > 12)
aux[12] = '\\0';
strcpy(filebuffer[wi], aux);
wi = (wi + 1) % FB_SIZE;
sem_post(&sem);
}
}
}
for(n = 0; n < R_THREADS; n++){
if(pthread_join(tid[n], 0) != 0){
printf("[Reader] Failed to join threads.\\n");
return -1;
}
}
printf("[Reader] Threads terminated.\\n");
if(pthread_mutex_destroy(&mutex) == -1)
printf("[Reader] Failed to destroy mutex.\\n");
if(sem_destroy(&sem) == -1)
printf("[Reader] Failed to destroy semaphore.\\n");
printf("[Reader] Done.\\n");
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t *mutex;
int main()
{
char *ptr;
int i;
pid_t pid;
pthread_mutexattr_t attr;
mutex = mmap(0, sizeof(pthread_mutex_t), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON, -1, 0);
pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(mutex, &attr);
ptr = mmap(0, 100, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON, -1, 0);
pid = fork();
if(pid == 0) {
printf("Process 1 lock...\\n");
pthread_mutex_lock(mutex);
printf("Process 1 lock ok\\n");
for(i=0; i<5; i++) {
sprintf(ptr, "hello, i=%d", i);
sleep(1);
}
printf("Process 1 unlock\\n");
pthread_mutex_unlock(mutex);
}
else {
pid = fork();
if(pid == 0) {
printf("Process 2 lock...\\n");
pthread_mutex_lock(mutex);
printf("Process 2 lock ok\\n");
for(i=5; i>=0; i--) {
ptr[5] = i+0x30;
printf("(child)ptr=%s\\n", ptr);
sleep(1);
}
pthread_mutex_unlock(mutex);
printf("Process 2 unlock ok\\n");
}
else {
for(i=0; i<=10; i++) {
printf("(parent)ptr=%s\\n", ptr);
sleep(1);
}
}
}
munmap(ptr, 100);
return 0;
}
| 1
|
#include <pthread.h>
void *customerMaker();
void *barberShop();
void *waitingRoom();
void checkQueue();
pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t wait_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t sleep_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t barberSleep_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t barberWorking_cond = PTHREAD_COND_INITIALIZER;
int returnTime=5,current=0, sleeping=0, iseed;
int main(int argc, char *argv[])
{
iseed=time(0);
srand(iseed);
pthread_t barber,customerM,timer_thread;
pthread_attr_t barberAttr, timerAttr;
pthread_attr_t customerMAttr;
pthread_attr_init(&timerAttr);
pthread_attr_init(&barberAttr);
pthread_attr_init(&customerMAttr);
printf("\\n");
pthread_create(&customerM,&customerMAttr,customerMaker,0);
pthread_create(&barber,&barberAttr,barberShop,0);
pthread_join(barber,0);
pthread_join(customerM,0);
return 0;
}
void *customerMaker()
{
int i=0;
printf("*Customer Maker Created*\\n\\n");
fflush(stdout);
pthread_t customer[6 +1];
pthread_attr_t customerAttr[6 +1];
while(i<(6 +1))
{
i++;
pthread_attr_init(&customerAttr[i]);
while(rand()%2!=1)
{
sleep(1);
}
pthread_create(&customer[i],&customerAttr[i],waitingRoom,0);
}
pthread_exit(0);
}
void *waitingRoom()
{
pthread_mutex_lock(&queue_mutex);
checkQueue();
sleep(returnTime);
waitingRoom();
}
void *barberShop()
{
int loop=0;
printf("The barber has opened the store.\\n");
fflush(stdout);
while(loop==0)
{
if(current==0)
{
printf("\\tThe shop is empty, barber is sleeping.\\n");
fflush(stdout);
pthread_mutex_lock(&sleep_mutex);
sleeping=1;
pthread_cond_wait(&barberSleep_cond,&sleep_mutex);
sleeping=0;
pthread_mutex_unlock(&sleep_mutex);
printf("\\t\\t\\t\\tBarber wakes up.\\n");
fflush(stdout);
}
else
{
printf("\\t\\t\\tBarber begins cutting hair.\\n");
fflush(stdout);
sleep((rand()%20)/5);
current--;
printf("\\t\\t\\t\\tHair cut complete, customer leaving store.\\n");
pthread_cond_signal(&barberWorking_cond);
}
}
pthread_exit(0);
}
void checkQueue()
{
current++;
printf("\\tCustomer has arrived in the waiting room.\\t\\t\\t\\t\\t\\t\\t%d Customers in store.\\n",current);
fflush(stdout);
printf("\\t\\tCustomer checking chairs.\\n");
fflush(stdout);
if(current<6)
{
if(sleeping==1)
{
printf("\\t\\t\\tBarber is sleeping, customer wakes him.\\n");
fflush(stdout);
pthread_cond_signal(&barberSleep_cond);
}
printf("\\t\\tCustomer takes a seat.\\n");
fflush(stdout);
pthread_mutex_unlock(&queue_mutex);
pthread_mutex_lock(&wait_mutex);
pthread_cond_wait(&barberWorking_cond,&wait_mutex);
pthread_mutex_unlock(&wait_mutex);
return;
}
if(current>=6)
{
printf("\\t\\tAll chairs full, leaving store.\\n");
fflush(stdout);
current--;
pthread_mutex_unlock(&queue_mutex);
return;
}
}
| 0
|
#include <pthread.h>
void *Producer();
void *Consumer();
int BufferIndex=0;
char *BUFFER;
pthread_cond_t Buffer_Not_Full=PTHREAD_COND_INITIALIZER;
pthread_cond_t Buffer_Not_Empty=PTHREAD_COND_INITIALIZER;
pthread_mutex_t mVar=PTHREAD_MUTEX_INITIALIZER;
int main()
{
pthread_t ptid,ctid;
BUFFER=(char *) malloc(sizeof(char) * 10);
pthread_create(&ptid,0,Producer,0);
pthread_create(&ctid,0,Consumer,0);
pthread_join(ptid,0);
pthread_join(ctid,0);
return 0;
}
void *Producer()
{
for(;;)
{
pthread_mutex_lock(&mVar);
if(BufferIndex==10)
{
pthread_cond_wait(&Buffer_Not_Full,&mVar);
}
BUFFER[BufferIndex++]='@';
printf("Produce : %d \\n",BufferIndex);
pthread_mutex_unlock(&mVar);
pthread_cond_signal(&Buffer_Not_Empty);
}
}
void *Consumer()
{
for(;;)
{
pthread_mutex_lock(&mVar);
if(BufferIndex==-1)
{
pthread_cond_wait(&Buffer_Not_Empty,&mVar);
}
printf("Consume : %d \\n",BufferIndex--);
pthread_mutex_unlock(&mVar);
pthread_cond_signal(&Buffer_Not_Full);
}
}
| 1
|
#include <pthread.h>
struct playclock *nemoplay_clock_create(void)
{
struct playclock *clock;
clock = (struct playclock *)malloc(sizeof(struct playclock));
if (clock == 0)
return 0;
memset(clock, 0, sizeof(struct playclock));
if (pthread_mutex_init(&clock->lock, 0) != 0)
goto err1;
clock->speed = 1.0f;
clock->ptime = 0.0f;
clock->ltime = av_gettime_relative() / 1000000.0f;
clock->dtime = -clock->ltime;
return clock;
err1:
free(clock);
return 0;
}
void nemoplay_clock_destroy(struct playclock *clock)
{
pthread_mutex_destroy(&clock->lock);
free(clock);
}
void nemoplay_clock_set_speed(struct playclock *clock, double speed)
{
pthread_mutex_lock(&clock->lock);
clock->speed = speed;
pthread_mutex_unlock(&clock->lock);
}
void nemoplay_clock_set(struct playclock *clock, double ptime)
{
double ctime = av_gettime_relative() / 1000000.0f;
pthread_mutex_lock(&clock->lock);
clock->ptime = ptime;
clock->ltime = ctime;
clock->dtime = ptime - ctime;
pthread_mutex_unlock(&clock->lock);
}
double nemoplay_clock_get(struct playclock *clock)
{
double ctime = av_gettime_relative() / 1000000.0f;
double rtime;
pthread_mutex_lock(&clock->lock);
if (clock->state == NEMOPLAY_CLOCK_NORMAL_STATE)
rtime = clock->dtime + ctime - (ctime - clock->ltime) * (1.0f - clock->speed);
else
rtime = clock->dtime + clock->ltime;
pthread_mutex_unlock(&clock->lock);
return rtime;
}
void nemoplay_clock_set_state(struct playclock *clock, int state)
{
pthread_mutex_lock(&clock->lock);
clock->state = state;
if (state == NEMOPLAY_CLOCK_NORMAL_STATE) {
double ctime = av_gettime_relative() / 1000000.0f;
clock->dtime += (clock->ltime - ctime);
clock->ltime = ctime;
}
pthread_mutex_unlock(&clock->lock);
}
| 0
|
#include <pthread.h>
extern char **environ;
pthread_mutex_t env_mutex;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
static void
thread_init(void)
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&env_mutex, &attr);
pthread_mutexattr_destroy(&attr);
}
int
getenv_r(const char *name, char *buf, int buflen)
{
int i, len, olen;
pthread_once(&init_done, thread_init);
len = strlen(name);
pthread_mutex_lock(&env_mutex);
for (i = 0; environ[i] != 0; i++) {
if ((strncmp(name, environ[i], len) == 0) &&
(environ[i][len] == '=')) {
olen = strlen(&environ[i][len+1]);
if (olen >= buflen) {
pthread_mutex_unlock(&env_mutex);
return(ENOSPC);
}
strcpy(buf, &environ[i][len+1]);
pthread_mutex_unlock(&env_mutex);
return(0);
}
}
pthread_mutex_unlock(&env_mutex);
return(ENOENT);
}
| 1
|
#include <pthread.h>
int cntA;
int cntB;
int cntC;
pthread_mutex_t mutaA;
pthread_mutex_t mutaB;
pthread_mutex_t mutaC;
pthread_t threads[10];
int array[100*10];
void *init(void *arg) {
int idx = (*(int *) arg);
int offset = idx * 100;
int i;
for (i = 0; i < 100; i++) {
array[i+offset] = rand() % 3;
}
pthread_exit(0);
}
void *func(void *arg) {
int idx = (*(int *) arg);
int i;
int offset = idx * 100;
for (i = 0; i < 100; i++) {
if (array[i+offset] == 0) {
pthread_mutex_lock(&mutaA);
cntA++;
pthread_mutex_unlock(&mutaA);
} else if (array[i+offset] == 1) {
pthread_mutex_lock(&mutaB);
cntB++;
pthread_mutex_unlock(&mutaB);
} else {
pthread_mutex_lock(&mutaC);
cntC++;
pthread_mutex_unlock(&mutaC);
}
}
pthread_exit(0);
}
int main() {
srand(time(0));
int i;
int rc = 0;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_mutex_init(&mutaA, 0);
pthread_mutex_init(&mutaB, 0);
pthread_mutex_init(&mutaC, 0);
cntA = 0;
cntB = 0;
cntC = 0;
for (i = 0; i < 10; i++) {
rc = pthread_create(&threads[i], &attr, init, &i);
if (rc) {
printf("pthread_create failes, error code %d\\n", rc);
exit(0);
}
}
for (i = 0; i < 10; i++) {
rc = pthread_join(threads[i], 0);
if (rc) {
printf("pthread_join fails, error code %d\\n", rc);
exit(0);
}
}
for (i = 0; i < 10; i++) {
rc = pthread_create(&threads[i], &attr, func, &i);
if (rc) {
printf("pthread_create fails, error code %d\\n", rc);
exit(0);
}
}
for (i = 0; i < 10; i++) {
rc = pthread_join(threads[i], 0);
if (rc) {
printf("pthread_join fails, error code %d\\n", rc);
exit(0);
}
}
printf("cntA = %d, cntB = %d, cntC = %d, total = %d\\n", cntA, cntB, cntC, cntA + cntB + cntC);
return 0;
}
| 0
|
#include <pthread.h>
int pthread_library_is_available = 0;
int pthread_detection_done = 0;
int (*pthread_key_create_fnptr)(pthread_key_t *key,
void (*destructor)(void*)) = 0;
void *(*pthread_getspecific_fnptr)(pthread_key_t key) = 0;
int (*pthread_setspecific_fnptr)(pthread_key_t key,
const void *value) = 0;
int (*pthread_once_fnptr)(pthread_once_t *, void (*)(void)) = 0;
pthread_t (*pthread_self_fnptr)(void) = 0;
int (*pthread_mutex_lock_fnptr)(pthread_mutex_t *mutex) = 0;
int (*pthread_mutex_unlock_fnptr)(pthread_mutex_t *mutex) = 0;
void check_pthread_library(void)
{
if (pthread_detection_done == 0) {
pthread_key_create_fnptr = dlsym(RTLD_DEFAULT,
"pthread_key_create");
pthread_getspecific_fnptr = dlsym(RTLD_DEFAULT,
"pthread_getspecific");
pthread_setspecific_fnptr = dlsym(RTLD_DEFAULT,
"pthread_setspecific");
pthread_once_fnptr = dlsym(RTLD_DEFAULT,
"pthread_once");
pthread_mutex_lock_fnptr = dlsym(RTLD_DEFAULT,
"pthread_mutex_lock");
pthread_mutex_unlock_fnptr = dlsym(RTLD_DEFAULT,
"pthread_mutex_unlock");
pthread_self_fnptr = dlsym(RTLD_DEFAULT,
"pthread_self");
if (pthread_key_create_fnptr &&
pthread_getspecific_fnptr &&
pthread_setspecific_fnptr &&
pthread_once_fnptr) {
SB_LOG(SB_LOGLEVEL_DEBUG,
"pthread library FOUND");
pthread_detection_done = 1;
pthread_library_is_available = 1;
} else if (!pthread_key_create_fnptr &&
!pthread_getspecific_fnptr &&
!pthread_setspecific_fnptr &&
!pthread_once_fnptr) {
SB_LOG(SB_LOGLEVEL_DEBUG,
"pthread library not found");
pthread_detection_done = -1;
pthread_library_is_available = 0;
} else {
SB_LOG(SB_LOGLEVEL_ERROR,
"pthread library is only partially available"
" - operation may become unstable");
pthread_detection_done = -2;
pthread_library_is_available = 0;
}
} else {
SB_LOG(SB_LOGLEVEL_NOISE,
"pthread detection already done (%d)",
pthread_detection_done);
}
}
| 1
|
#include <pthread.h>
int vector_size;
double start_time, end_time;
pthread_mutex_t mutex_size = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_vector = PTHREAD_MUTEX_INITIALIZER;
void set_start_time(){
double usec;
struct timeval current_time;
gettimeofday(¤t_time,0);
usec=current_time.tv_usec;
start_time=current_time.tv_sec+(usec/1000000);
}
void set_end_time(){
double usec;
struct timeval current_time;
gettimeofday(¤t_time,0);
usec=current_time.tv_usec;
end_time=current_time.tv_sec+(usec/1000000);
}
void set_random_values(int *vector){
int counter;
struct timeval current_time;
gettimeofday(¤t_time,0);
srandom(current_time.tv_usec);
for(counter=0;counter<vector_size;counter++) vector[counter]=(random())%201;
}
int sum_vector(int *vector){
int counter;
int result=0;
for(counter=0;counter<vector_size;counter++)
result=result+vector[counter];
return result;
}
void *threaded_sum_vector(void *vec){
int *vector,private_size;
vector=(int*) vec;
while(vector_size>0){
pthread_mutex_lock(&mutex_size);
vector_size--;
private_size=vector_size;
pthread_mutex_unlock(&mutex_size);
pthread_mutex_lock(&mutex_vector);
if (private_size>0)
vector[0]=vector[0]+vector[private_size];
pthread_mutex_unlock(&mutex_vector);
}
}
int main(int argc, char *argv[]){
if (argc!=3){
printf("Número incorreto de parâmetros\\n");
printf("Uso: ./<nome do programa> <tam. do vetor> <qtd. de threads>\\n");
return 0;
}
int thread_quantity, sum, thread_index, *the_vector;
double time_main, time_thread;
pthread_t *thread_vector;
sscanf(argv[1],"%d",&vector_size);
sscanf(argv[2],"%d",&thread_quantity);
printf("vector size: %d, number of threads: %d\\n",vector_size,thread_quantity);
thread_vector=(pthread_t*)malloc(sizeof(pthread_t)*thread_quantity);
the_vector=(int*)malloc(sizeof(int)*vector_size);
set_random_values(the_vector);
set_start_time();
sum=sum_vector(the_vector);
set_end_time();
time_main=end_time-start_time;
set_start_time();
for(thread_index=0;thread_index<thread_quantity;thread_index++)
pthread_create(thread_vector+thread_index,0,threaded_sum_vector,(void*)the_vector);
for(thread_index=0;thread_index<thread_quantity;thread_index++)
pthread_join(thread_vector[thread_index],0);
set_end_time();
time_thread=end_time-start_time;
printf("sum value: %d, time at main: %f seconds\\n",sum,time_main);
printf("sum value: %d, time with threads: %f seconds\\n",the_vector[0],time_thread);
free(the_vector);
free(thread_vector);
return 0;
}
| 0
|
#include <pthread.h>
int buffer;
int number;
sem_t empty,full;
void* consumer(void*);
void* producer(void*);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main(int argc, char *argv[]) {
if(argv[1] != 0) {
buffer = atoi(argv[1]);
number = 0;
}
else {
printf("Enter buffer size as an argument when launching program\\n");
return(0);
}
sem_init(&empty, 0, 1);
sem_init(&full, 0, 0);
pthread_t first, secnd;
pthread_create(&first, 0, consumer, 0);
pthread_create(&secnd, 0, producer, 0);
pthread_join(first, 0);
pthread_join(secnd, 0);
printf("All done!\\n");
}
void* producer(void *x) {
while(1) {
sem_wait(&empty);
pthread_mutex_lock(&mutex);
number++;
printf("Producer: %d\\n", number);
pthread_mutex_unlock(&mutex);
sem_post(&full);
if(number >= buffer) {
printf("Producer done\\n");
break;
}
sleep(1);
}
}
void* consumer(void *x) {
while(1) {
sem_wait(&full);
pthread_mutex_lock(&mutex);
printf("Consumer: %d\\n", number);
pthread_mutex_unlock(&mutex);
sem_post(&empty);
if(number >= buffer) {
printf("Consumer done\\n");
break;
}
}
}
| 1
|
#include <pthread.h>
uint64_t nb;
FILE * file;
char str[60];
pthread_t thread0;
pthread_t thread1;
pthread_mutex_t lock;
void* thread_prime_factors(void * u);
void print_prime_factors(uint64_t n);
void* thread_prime_factors(void * u)
{
pthread_mutex_lock(&lock);
while ( fgets(str, 60, file)!=0 )
{
nb=atol(str);
pthread_mutex_unlock(&lock);
print_prime_factors(nb);
pthread_mutex_lock(&lock);
}
pthread_mutex_unlock(&lock);
return 0;
}
void print_prime_factors(uint64_t n)
{
printf("%ju : ", n );
uint64_t i;
for( i=2; n!=1 ; i++ )
{
while (n%i==0)
{
n=n/i;
printf("%ju ", i);
}
}
printf("\\n");
return;
}
int main(void)
{
printf("En déplaçant la boucle de lecture dans chacun des threads :\\n");
file = fopen ("fileQuestion4pasEfficace.txt","r");
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("\\n mutex init failed\\n");
return 1;
}
pthread_create(&thread0, 0, thread_prime_factors, 0);
pthread_create(&thread1, 0, thread_prime_factors, 0);
pthread_join(thread0, 0);
pthread_join(thread1, 0);
pthread_mutex_destroy(&lock);
return 0;
}
| 0
|
#include <pthread.h>
int main()
{
int philosopherIds[__NR_OF_PHILOSOPHERS];
pthread_t philosophersThreads[__NR_OF_PHILOSOPHERS];
initializeMutex();
preparePhilosopers(philosopherIds,philosophersThreads);
finalize(philosophersThreads);
return 0;
}
void initializeMutex()
{
int i,result;
if ((result = pthread_mutex_init(&m, 0)) != 0)
{
perror("mutex");
exit(1);
}
for(i = 0; i < __NR_OF_PHILOSOPHERS; i++)
{
if ((result = pthread_mutex_init(&s[i], 0)) != 0)
{
perror("mutex");
exit(2);
}
pthread_mutex_lock(&s[i]);
state[i]=THINKING;
}
}
void preparePhilosopers(int *philosopherIds, pthread_t *philosophersThreads)
{
int i;
for(i=0; i<__NR_OF_PHILOSOPHERS; ++i)
{
philosopherIds[i] = i;
if(pthread_create(&philosophersThreads[i], 0, philosopher, (void *)&philosopherIds[i])!=0)
{
fprintf(stderr,"\\nERROR: pthread_create() failed. Cannot create philosopher!\\n");
exit(3);
}
}
}
void *philosopher(void *philosopherID)
{
int mealCnt = 0;
printf("Philospoher NR. %d \\tjoined the table\\n", *(int*)philosopherID);
for(; mealCnt < __NR_OF_MEALS; mealCnt++)
{
think((int*)philosopherID);
eat((int*)philosopherID,&mealCnt);
}
printf("Philospoher NR. %d \\tFinished all of meals\\n", *(int*)philosopherID);
}
void think(const int* philosopherID)
{
printf("Philospoher NR. %d \\tThink\\n", *philosopherID);
sleep(__THINK_TIME);
}
void eat(const int* philosopherID,const int* mealNr)
{
grabForks(philosopherID);
sleep(__EATING_TIME);
putAwayForks(philosopherID);
}
void grabForks(const int* philosopherID)
{
pthread_mutex_lock(&m);
state[*philosopherID]=HUNGRY;
test(philosopherID);
pthread_mutex_unlock(&m);
pthread_mutex_lock(&s[*philosopherID]);
}
void putAwayForks( const int* philosopherID )
{
int left = LEFT;
int right = RIGHT;
pthread_mutex_lock(&m);
state[*philosopherID]=THINKING;
test(&left);
test(&right);
pthread_mutex_unlock(&m);
}
void test(const int* philosopherID)
{
if( state[*philosopherID] == HUNGRY
&& state[LEFT] != EATING
&& state[RIGHT] != EATING )
{
state[*philosopherID] = EATING;
pthread_mutex_unlock(&s[*philosopherID]);
}
}
void finalize(const pthread_t *philosophersThreads)
{
int i;
for(i=0; i<__NR_OF_PHILOSOPHERS; ++i)
{
pthread_join(philosophersThreads[i],0);
}
pthread_mutex_destroy(&m);
for(i=0; i<__NR_OF_PHILOSOPHERS; ++i)
{
pthread_mutex_destroy(&s[i]);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t head_p_mutex = PTHREAD_MUTEX_INITIALIZER;
struct list_node_s{
int data;
struct list_node_s* next;
pthread_mutex_t mutex;
};
int Member(int value, struct list_node_s* head_p){
struct list_node_s* temp_p;
pthread_mutex_lock(&head_p_mutex);
temp_p = head_p;
while(temp_p != 0 && temp_p->data < value){
if(temp_p->next != 0) pthread_mutex_lock(&(temp_p->next->mutex));
if(temp_p == head_p) pthread_mutex_unlock(&head_p_mutex);
pthread_mutex_unlock(&(temp_p->mutex));
temp_p = temp_p->next;
}
if(temp_p == 0 || temp_p->data > value){
if(temp_p == head_p) pthread_mutex_unlock(&head_p_mutex);
if(temp_p != 0) pthread_mutex_unlock(&(temp_p->mutex));
return 0;
}
else {
if(temp_p == head_p) pthread_mutex_unlock(&head_p_mutex);
pthread_mutex_unlock(&(temp_p->mutex));
return 1;
}
}
int Insert(int value, struct list_node_s** head_p){
pthread_mutex_lock(&head_p_mutex);
int flag = 0;
struct list_node_s* curr_p = *head_p;
struct list_node_s* pred_p = 0;
struct list_node_s* temp_p;
while(curr_p != 0 && curr_p->data < value){
if(curr_p->next != 0) pthread_mutex_lock(&(curr_p->next->mutex));
if(curr_p == *head_p) pthread_mutex_unlock(&head_p_mutex);
pthread_mutex_unlock(&curr_p->mutex);
pred_p = curr_p;
curr_p = curr_p->next;
}
if(curr_p == 0 || curr_p->data > value){
temp_p = malloc(sizeof(struct list_node_s));
temp_p->data = value;
temp_p->next = curr_p;
if(curr_p == *head_p) flag = 1;
if(pred_p == 0)
*head_p = temp_p;
else pred_p->next = temp_p;
if(curr_p != 0) pthread_mutex_unlock(&curr_p->mutex);
if(flag==1) pthread_mutex_unlock(&head_p_mutex);
return 1;
}
pthread_mutex_unlock(&curr_p->mutex);
if(curr_p == *head_p) pthread_mutex_unlock(&head_p_mutex);
else return 0;
}
int Delete(int value, struct list_node_s** head_p){
pthread_mutex_lock(&head_p_mutex);
struct list_node_s* curr_p = *head_p;
struct list_node_s* pred_p = 0;
while(curr_p != 0 && curr_p->data < value){
if(curr_p->next != 0) pthread_mutex_lock(&(curr_p->next->mutex));
if(curr_p == *head_p) pthread_mutex_unlock(&head_p_mutex);
pthread_mutex_unlock(&curr_p->mutex);
pred_p = curr_p;
curr_p = curr_p->next;
}
if(curr_p != 0 && curr_p->data == value){
if(pred_p == 0){
*head_p = curr_p->next;
pthread_mutex_unlock(&curr_p->mutex);
pthread_mutex_unlock(&head_p_mutex);
free(curr_p);
}
else{
pred_p->next = curr_p->next;
pthread_mutex_unlock(&curr_p->mutex);
free(curr_p);
}
return 1;
}
else{
if(curr_p != 0) pthread_mutex_unlock(&curr_p->mutex);
if(curr_p == *head_p) pthread_mutex_unlock(&head_p_mutex);
return 0;
}
}
struct list_node_s* list = 0;
void N_Insert(double ops){
double i;
for(i = 0; i < ops; i++) {
Insert(1000,&list);
}
return;
}
void N_Member(double ops){
double i;
for(i = 0; i < ops; i++) {
Member(1000,list);
}
return;
}
void N_Delete(double ops){
double i;
for(i = 0; i < ops; i++) {
Delete(1000,&list);
}
return;
}
double members, inserts, deletes;
void* N_All(void* rank){
long my_rank = (long) rank;
N_Member(members);
N_Insert(inserts);
N_Delete(deletes);
return 0;
}
int main(int argc, char* argv[]){
long thread;
double thread_count,i, elapsed;
pthread_t *thread_handles;
struct list_node_s* list = 0;
struct timespec begin,end;
thread_count = strtol(argv[1],0,10);
thread_handles = malloc(thread_count* sizeof(pthread_t));
scanf("%lf %lf %lf", &members, &inserts, &deletes);
members = (members * 1000.0)/thread_count;
inserts = (inserts * 1000.0)/thread_count;
deletes = (deletes * 1000.0)/thread_count;
for(i = 0; i < 1000; i++){
Insert(i,&list);
}
clock_gettime(CLOCK_MONOTONIC, &begin);
for(thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], 0, N_All, (void*) thread);
for(thread = 0; thread < thread_count; thread++) pthread_join(thread_handles[thread], 0);
clock_gettime(CLOCK_MONOTONIC, &end);
elapsed = end.tv_sec - begin.tv_sec;
elapsed += (end.tv_nsec - begin.tv_nsec) / 1000000000.0;
printf("%lf\\n", elapsed);
return 0;
}
| 0
|
#include <pthread.h>
static volatile int pid = -1;
static int prog_length;
static pthread_mutex_t pid_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t zombie_lock = PTHREAD_MUTEX_INITIALIZER;
static int get_current_pid(void)
{
int __pid;
pthread_mutex_lock(&pid_lock);
__pid = pid;
pthread_mutex_unlock(&pid_lock);
return __pid;
}
static void * sniffer(void *dummy)
{
int cache_pid = -1, fd = -1;
char str[50], buf[2000], sample[2000];
pthread_mutex_lock(&zombie_lock);
pthread_mutex_unlock(&zombie_lock);
for (;;)
{
int length_cmp;
if (get_current_pid() != cache_pid)
{
pthread_mutex_lock(&zombie_lock);
cache_pid = pid;
snprintf(str, 50, "/proc/%d/stat", cache_pid);
if (fd > 0)
close(fd);
fd = open(str, O_RDONLY|O_NONBLOCK);
if (fd > 0)
{
int length;
length = read(fd, &buf, 2000);
if (length > 0)
{
length_cmp = length;
memcpy(sample, buf, length);
sample[length-1] = 0;
}
}
pthread_mutex_unlock(&zombie_lock);
}
if (fd > 0)
{
int length;
lseek(fd, 0, 0);
length = read(fd, &buf, 200);
buf[length-1] = 0;
if (length >= length_cmp && memcmp(buf, sample,
length_cmp))
printf("length %d, pid %d\\n"
"original data: %s\\n"
"modifyed data: %s\\n",
length, cache_pid, sample, buf);
}
}
}
static int is_zombie(int __pid)
{
char str[50], state;
FILE * status;
snprintf(str, 50, "/proc/%d/status", __pid);
status = fopen(str, "r");
if (!status)
{
perror("open");
exit(2);
}
fscanf(status, "%*s\\t%*s\\nState:\\t%c", &state);
fclose(status);
if (state != 'Z')
return 0;
return 1;
}
int main(int argc, char *argv[])
{
int dummy;
pthread_t task_struct_sniffer;
pthread_mutex_lock(&zombie_lock);
if (pthread_create(&task_struct_sniffer, 0, sniffer, 0))
{
perror("pthread_create");
exit(1);
}
for (;;)
{
int __pid = fork();
if (!__pid)
_exit(0);
while (!is_zombie(__pid));
pthread_mutex_lock(&pid_lock);
pid = __pid;
pthread_mutex_unlock(&pid_lock);
pthread_mutex_unlock(&zombie_lock);
usleep(1);
wait(&dummy);
pthread_mutex_lock(&zombie_lock);
}
pthread_mutex_unlock(&zombie_lock);
}
| 1
|
#include <pthread.h>
struct node *head = 0;
struct node *create_node(int value) {
struct node *newnode = malloc(sizeof(struct node));
pthread_mutex_init(&newnode->lock, 0);
newnode->value = value;
newnode->next = 0;
return newnode;
}
void insert(struct list *L, int value){
struct node *newnode = create_node(value);
pthread_mutex_lock(&L->lock);
struct node *cur = L->head;
if(L->head == 0 || L->head->value > value) {
newnode->next = L->head;
L->head = newnode;
pthread_mutex_unlock(&L->lock);
return;
}
pthread_mutex_lock(&L->head->lock);
pthread_mutex_unlock(&L->lock);
while(cur->next != 0 && cur->next->value <= value) {
struct node *temp = cur;
pthread_mutex_lock(&cur->next->lock);
cur = cur->next;
pthread_mutex_unlock(&temp->lock);
}
if(cur->next != 0) {
pthread_mutex_lock(&cur->next->lock);
}
newnode->next = cur->next;
cur->next = newnode;
pthread_mutex_unlock(&cur->lock);
if(cur->next->next != 0) {
pthread_mutex_unlock(&cur->next->next->lock);
}
return;
}
int length(struct list *L) {
struct node *cur = L->head;
int count = 0;
while(cur != 0) {
count++;
cur = cur->next;
}
return count;
}
void print_list(struct list *L) {
struct node *cur = L->head;
while(cur != 0) {
printf("%d -> ", cur->value);
cur = cur->next;
}
printf("\\n");
}
| 0
|
#include <pthread.h>
int on_train;
int start_trip;
pthread_mutex_t pass_mtx;
pthread_mutex_t wait_mtx;
struct list *nxt;
}waitL;
waitL *root_train=0;
waitL *end_train=0;
pthread_mutex_t mtx_train = PTHREAD_MUTEX_INITIALIZER;
waitL *root_passengers=0;
waitL *end_passengers=0;
pthread_mutex_t mtx_passengers = PTHREAD_MUTEX_INITIALIZER;
void *Train ( void *arg ) {
while ( 1 ) {
pthread_mutex_lock ( &mtx_train );
while ( start_trip == 0 ) {
waitL *curr;
curr = (waitL *)malloc(sizeof(waitL));
curr->nxt = 0;
pthread_mutex_init ( &curr->wait_mtx, 0 );
pthread_mutex_lock ( &curr->wait_mtx );
if ( end_train == 0 ) {
end_train = curr;
root_train = end_train;
}else {
end_train->nxt = curr;
end_train = curr;
}
pthread_mutex_unlock ( &mtx_train );
pthread_mutex_lock ( &curr->wait_mtx );
pthread_mutex_destroy ( &curr->wait_mtx );
free(curr);
pthread_mutex_lock ( &mtx_train );
}
start_trip = 0;
printf("Starting...!!!\\n");
printf("On Trip\\n");
sleep(6);
printf("The trip is finished...\\n");
if ( root_passengers != 0 ) {
waitL *temp;
temp = (waitL *)malloc(sizeof(waitL));
temp = root_passengers;
root_passengers = root_passengers->nxt;
if ( root_passengers == 0 ) {
end_passengers = root_passengers;
}
pthread_mutex_unlock( &temp->wait_mtx );
}
pthread_mutex_unlock ( &mtx_train );
}
pthread_exit ( 0 );
}
void *Passengers ( void *arg ) {
pthread_mutex_lock ( &pass_mtx );
pthread_mutex_lock ( &mtx_passengers );
if ( on_train < 15 - 1 ) {
on_train++;
pthread_mutex_unlock ( &pass_mtx );
waitL *curr;
curr = (waitL *)malloc(sizeof(waitL));
curr->nxt = 0;
pthread_mutex_init ( &curr->wait_mtx,0 );
pthread_mutex_lock ( &curr->wait_mtx );
if ( end_passengers == 0 ) {
end_passengers = curr;
root_passengers = end_passengers;
}else {
end_passengers->nxt = curr;
end_passengers = curr;
}
pthread_mutex_unlock ( &mtx_passengers );
pthread_mutex_lock ( &curr->wait_mtx );
pthread_mutex_destroy ( &curr->wait_mtx );
free(curr);
printf("malakas\\n");
pthread_mutex_lock ( &mtx_passengers );
}else if ( on_train == 15 - 1 ) {
on_train++;
start_trip = 1;
printf("On train: %d\\n", on_train);
if ( root_train != 0 ) {
waitL *temp;
temp = (waitL *)malloc(sizeof(waitL));
temp = root_train;
root_train = root_train->nxt;
if ( root_train == 0 ) {
end_train = root_train;
}
pthread_mutex_unlock( &temp->wait_mtx );
}
waitL *curr;
curr = (waitL *)malloc(sizeof(waitL));
curr->nxt = 0;
pthread_mutex_init ( &curr->wait_mtx,0 );
pthread_mutex_lock ( &curr->wait_mtx );
if ( end_passengers == 0 ) {
end_passengers = curr;
root_passengers = end_passengers;
}else {
end_passengers->nxt = curr;
end_passengers = curr;
}
pthread_mutex_unlock ( &mtx_passengers );
pthread_mutex_lock ( &curr->wait_mtx );
pthread_mutex_destroy ( &curr->wait_mtx );
free(curr);
pthread_mutex_lock ( &mtx_passengers );
}
printf("%p\\n", root_passengers);
printf("Yeahhhhh..It's awesomeeee.....\\n");
on_train--;
if ( on_train > 0 ) {
if ( root_passengers != 0 ) {
waitL *temp;
temp = (waitL *)malloc(sizeof(waitL));
temp = root_passengers;
root_passengers = root_passengers->nxt;
if ( root_passengers == 0 ) {
end_passengers = root_passengers;
}
printf("Yeah %d, %p, %p\\n", on_train,temp, root_passengers);
pthread_mutex_unlock( &temp->wait_mtx );
}
}else {
pthread_mutex_unlock ( &pass_mtx );
}
pthread_mutex_unlock ( &mtx_passengers );
pthread_exit ( 0 );
}
int init () {
pthread_t thread;
on_train = 0;
start_trip = 0;
if ( pthread_mutex_init ( &pass_mtx, 0 ) != 0 ) {
printf("\\n create_mutex init failed\\n");
return 1;
}
pthread_create ( &thread, 0, Train, 0 );
return (0);
}
int main ( int argc, char *argv[] ) {
int check_init,NumOfPassengers;
pthread_t thread;
check_init = init();
if ( check_init == 1 ) {
printf("Error in init.\\n");
return 1;
}
while ( 1 ) {
printf("Enter the number of the passengers\\n");
scanf(" %d", &NumOfPassengers );
while ( NumOfPassengers > 0 ) {
pthread_create ( &thread, 0, Passengers, 0 );
NumOfPassengers--;
}
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t condition_c, condition_p;
int buffer = 0;
void* producer(void *ptr) {
for (int i = 1; i <= 10; i++) {
pthread_mutex_lock(&mutex);
while (buffer != 0) {
pthread_cond_wait(&condition_p, &mutex);
}
buffer = i;
printf("produced %d\\n", buffer);
pthread_cond_signal(&condition_c);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void* consumer(void *ptr) {
for (int i = 1; i <= 10; i++) {
pthread_mutex_lock(&mutex);
while (buffer == 0) {
pthread_cond_wait(&condition_c, &mutex);
}
printf("consumed %d\\n", buffer);
buffer = 0;
pthread_cond_signal(&condition_p);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main(int argc, char **argv) {
pthread_t producer_t, consumer_t;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&condition_c, 0);
pthread_cond_init(&condition_p, 0);
pthread_create(&consumer_t, 0, consumer, 0);
pthread_create(&producer_t, 0, producer, 0);
pthread_join(consumer_t, 0);
pthread_join(producer_t, 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&condition_c);
pthread_cond_destroy(&condition_p);
}
| 0
|
#include <pthread.h>
int g = 0;
pthread_mutex_t l;
void *foo(void *arg) {
long x = (long)arg;
if (x == 1 || g > 10) {
pthread_mutex_lock(&l);
}
g = 10;
RC_ACCESS(1, RC_ALIAS | RC_MHP | RC_RACE);
RC_ACCESS(1, RC_ALIAS | RC_MHP | RC_RACE);
if (x == 1 && g > 10) {
g = 5;
RC_ACCESS(2, RC_ALIAS | RC_MHP | RC_PROTECTED);
RC_ACCESS(2, RC_ALIAS | RC_MHP | RC_PROTECTED);
}
pthread_mutex_unlock(&l);
if (x == 1 && g > 10) {
pthread_mutex_lock(&l);
}
g = 10;
RC_ACCESS(3, RC_ALIAS | RC_MHP | RC_RACE);
RC_ACCESS(3, RC_ALIAS | RC_MHP | RC_RACE);
if (x == 1 || g > 10) {
g = 5;
RC_ACCESS(4, RC_ALIAS | RC_MHP | RC_RACE);
RC_ACCESS(4, RC_ALIAS | RC_MHP | RC_RACE);
}
pthread_mutex_unlock(&l);
return 0;
}
int main(int argc, char *argv[]) {
pthread_t thread[10];
int ret;
long t = 1;
for (int i = 0; i < 10; ++i) {
ret = pthread_create(&thread[i], 0, foo, (void *)t);
if (ret){
exit(-1);
}
}
return 0;
}
| 1
|
#include <pthread.h>
int count = 0;
int readcount = 0;
int writecount = 0;
pthread_mutex_t mutex1;
pthread_mutex_t mutex2;
pthread_mutex_t mutex3;
pthread_mutex_t w;
pthread_mutex_t r;
void *reader_thread(void *p) {
long id = (long) p;
int i = 10;
while (i --> 0) {
pthread_mutex_lock(&mutex3);
pthread_mutex_lock(&r);
pthread_mutex_lock(&mutex1);
if (++readcount == 1)
pthread_mutex_lock(&w);
pthread_mutex_unlock(&mutex1);
pthread_mutex_unlock(&r);
pthread_mutex_unlock(&mutex3);
usleep(50);
printf("Read: thread %ld, counter = %d.\\n", id, count);
pthread_mutex_lock(&mutex1);
if (--readcount == 0)
pthread_mutex_unlock(&w);
pthread_mutex_unlock(&mutex1);
}
}
void *writer_thread(void *p) {
long id = (long)p;
int i = 10;
while (i --> 0) {
pthread_mutex_lock(&mutex2);
if (++writecount == 1)
pthread_mutex_lock(&r);
pthread_mutex_unlock(&mutex2);
pthread_mutex_lock(&w);
usleep(100);
count++;
printf("Wrote: thread %ld, counter = %d.\\n", id, count);
pthread_mutex_unlock(&w);
pthread_mutex_lock(&mutex2);
if (--writecount == 0)
pthread_mutex_unlock(&r);
pthread_mutex_unlock(&mutex2);
}
}
int main(int argc, char *argv[]) {
long int i;
int num = 5;
pthread_t *reader, *writer;
pthread_mutex_init(&mutex1, 0);
pthread_mutex_init(&mutex2, 0);
pthread_mutex_init(&mutex3, 0);
pthread_mutex_init(&w, 0);
pthread_mutex_init(&r, 0);
reader = malloc(2*num*sizeof(pthread_t));
writer = reader + num;
for (i = 0; i < num; i++) {
pthread_create(&reader[i], 0, reader_thread, (void *)i);
pthread_create(&writer[i], 0, writer_thread, (void *)(i+num));
}
for (i = 0; i < num; i++) {
pthread_join(reader[i], 0);
pthread_join(writer[i], 0);
}
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
pthread_mutex_destroy(&mutex3);
pthread_mutex_destroy(&w);
pthread_mutex_destroy(&r);
argc = argc;
argv = argv;
return 0;
}
| 0
|
#include <pthread.h>
struct glob{
int a;
int b;
}obj;
pthread_mutex_t mutex;
void *writer(void *arg){
printf("writer-thread has created: %lu\\n",pthread_self());
pthread_mutex_lock(&mutex);
obj.a = 10;
pthread_exit(0);
sleep(1);
obj.b = 20;
pthread_mutex_unlock(&mutex);
return 0;
}
void *reader1(void *arg){
printf("reader1 has created: %lu\\n",pthread_self());
pthread_mutex_lock(&mutex);
pause();
printf("rd1 : member1: %d\\n",obj.a);
printf("rd1 : member2: %d\\n",obj.b);
pthread_mutex_unlock(&mutex);
return 0;
}
void *reader2(void *arg){
printf("reader2 has created: %lu\\n",pthread_self());
pthread_mutex_lock(&mutex);
pause();
printf("rd2 : member1: %d\\n",obj.a);
printf("rd2 : member2: %d\\n",obj.b);
pthread_mutex_unlock(&mutex);
return 0;
}
void *reader3(void *arg){
printf("reader3 has created: %lu\\n",pthread_self());
pthread_mutex_lock(&mutex);
printf("rd3 : member1: %d\\n",obj.a);
printf("rd3 : member2: %d\\n",obj.b);
pthread_mutex_lock(&mutex);
return 0;
}
main(){
pthread_mutex_init(&mutex,0);
pthread_t tid1,tid2,tid3,tid4;
pthread_create(&tid1,0,writer,0);
sleep(1);
pthread_create(&tid2,0,reader1,0);
pthread_create(&tid3,0,reader2,0);
pthread_create(&tid4,0,reader3,0);
pause();
}
| 1
|
#include <pthread.h>
struct person_info {
int sex;
char name[32 +1];
int age;
};
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *write_thread_routine(void * arg)
{
int i;
char buf[1024];
struct person_info *pInfo = (struct person_info *)arg;
printf("I'm sub thread,my thread ID is:0x%x\\n", (int)pthread_self());
if(!pInfo) {
pthread_exit(0);
}
while (1) {
fprintf (stderr, "writer: please input string:");
bzero (buf, 1024);
if (fgets (buf, 1024 - 1, stdin) == 0) {
perror ("fgets");
continue;
}
int len = strlen(buf);
if(len > 32) {
len = 32;
}
pthread_mutex_lock(&mutex);
pInfo->sex = 1;
pInfo->age = 18;
bzero(pInfo->name, 32 +1);
strncpy(pInfo->name, buf, len);
pthread_mutex_unlock(&mutex);
if ( !strncasecmp (buf, "quit", strlen ("quit"))) {
break;
}
}
pthread_exit((void *)pInfo);
}
void read_thread_routine(void *arg)
{
struct person_info *pInfo = (struct person_info *)arg;
printf("I'm read thread!\\n");
if(!pInfo) {
pthread_exit(0);
}
while(1) {
pthread_mutex_lock(&mutex);
if ( !strncasecmp (pInfo->name, "quit", strlen ("quit"))) {
pthread_mutex_unlock(&mutex);
break;
}
printf("read: sex = %d, age=%d, name=%s\\n", pInfo->sex, pInfo->age, pInfo->name);
pthread_mutex_unlock(&mutex);
usleep(200000);
}
pthread_exit(0);
}
int main(void)
{
pthread_t tid_w, tid_r;
char *msg = "Hello, 1510";
struct person_info *pInfo = 0;
printf("thread demo!\\n");
pInfo = (struct person_info *)malloc(sizeof(struct person_info));
if(!pInfo) {
exit(1);
}
pthread_mutex_init(&mutex, 0);
pthread_create(&tid_w, 0, write_thread_routine, (void *)pInfo);
pthread_create(&tid_r, 0, (void *)read_thread_routine, (void *)pInfo);
pthread_join(tid_w, 0);
pthread_join(tid_r, 0);
pthread_mutex_destroy(&mutex);
if(pInfo) free(pInfo);
sleep(5);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t lockAmp;
pthread_mutex_t lockDolar;
pthread_mutex_t lockBirlesim;
pthread_mutex_t lockMakine;
int amp = 0;
int dolar = 0;
int sayac = 1;
void makina();
void makinaAmp();
void makinaDolar();
void makinaBirlestir();
int main(int argc, char **argv){
pthread_t mAmp, mDolar, mBirlestir;
void *retval;
if(pthread_mutex_init(&lockAmp,0) != 0) {
printf("mutex hatası\\n");
return 1;
}
if(pthread_mutex_init(&lockDolar,0) != 0) {
printf("mutex hatası\\n");
return 1;
}
if(pthread_mutex_init(&lockMakine,0) != 0) {
printf("mutex hatası\\n");
return 1;
}
if(pthread_mutex_init(&lockBirlesim,0) != 0) {
printf("mutex hatası\\n");
return 1;
}
pthread_create(&mAmp, 0, makinaAmp, 0);
pthread_create(&mDolar, 0, makinaDolar, 0);
pthread_create(&mBirlestir, 0, makinaBirlestir, 0);
pthread_join(mAmp, &retval);
pthread_join(mDolar, &retval);
pthread_join(mBirlestir, &retval);
return 0;
}
void makina(){
pthread_mutex_lock(&lockMakine);
}
void makinaAmp(){
while (1) {
makina();
sleep(3);
amp = 1;
pthread_mutex_unlock(&lockMakine);
pthread_mutex_unlock(&lockBirlesim);
printf("&\\n");
pthread_mutex_lock(&lockAmp);
}
}
void makinaDolar(){
while (1) {
makina();
sleep(5);
dolar = 1;
pthread_mutex_unlock(&lockMakine);
pthread_mutex_unlock(&lockBirlesim);
printf("$\\n");
pthread_mutex_lock(&lockDolar);
}
}
void makinaBirlestir(){
char ilk,iki;
while(1){
if (amp == 1 || dolar == 1) {
if (dolar == 1) {
ilk = '$';
iki = '&';
pthread_mutex_lock(&lockBirlesim);
}
else if (amp == 1) {
ilk = '&';
iki = '$';
pthread_mutex_lock(&lockBirlesim);
}
}
if (amp == 1 && dolar == 1) {
sleep(4);
printf("%d_%c%c\\n", sayac,ilk,iki);
pthread_mutex_unlock(&lockAmp);
pthread_mutex_unlock(&lockDolar);
amp = 0;
dolar = 0;
sayac++;
}
}
}
| 1
|
#include <pthread.h>
void * whattodo( void * arg );
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main()
{
int i, rc;
int * t;
pthread_t tid[ 8 ];
for ( i = 0 ; i < 8 ; i++ )
{
t = (int *)malloc( sizeof( int ) );
*t = 3 + ( rand() % 11 );
printf( "MAIN: Next thread will nap for %d seconds.\\n", *t );
rc = pthread_create( &tid[i], 0, whattodo, t );
if ( rc != 0 ) {
perror( "Could not create the thread" );
}
}
for ( i = 0 ; i < 8 ; i++ ) {
pthread_join( tid[i], 0 );
}
printf( "MAIN: All threads accounted for.\\n" );
return 0;
}
void critical_section( int nap_time )
{
printf( "THREAD %u: Entering my critical section.\\n", (unsigned int)pthread_self() );
printf( "THREAD %u: Napping for %d seconds.\\n", (unsigned int)pthread_self(), nap_time );
sleep( nap_time );
printf( "THREAD %u: Leaving my critical section.\\n", (unsigned int)pthread_self() );
}
void * whattodo( void * arg )
{
int t = *(int *)arg;
printf( "THREAD %u: I'm want to nap for %d seconds.\\n", (unsigned int)pthread_self(), t );
pthread_mutex_lock( &mutex );
critical_section( t );
pthread_mutex_unlock( &mutex );
printf( "THREAD %u: I'm awake now.\\n", (unsigned int)pthread_self() );
return 0;
}
| 0
|
#include <pthread.h>
const int MAX_THREADS = 1024;
long thread_count;
long long n;
double sum;
pthread_mutex_t mutex;
void* Thread_sum(void* rank);
int main(int argc, char* argv[])
{
long thread;
pthread_t* thread_handles;
thread_count = strtol(argv[1],0,10);
n = strtoll(argv[2],0,10);
thread_handles = (pthread_t*) malloc (thread_count*sizeof(pthread_t));
pthread_mutex_init(&mutex, 0);
sum = 0.0;
for (thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread], 0,Thread_sum, (void*)thread);
for (thread = 0; thread < thread_count; thread++)
pthread_join(thread_handles[thread], 0);
sum = 4.0*sum;
printf("the sum is : %.15f\\n",sum);
pthread_mutex_destroy(&mutex);
free(thread_handles);
return 0;
}
void* Thread_sum(void* rank)
{
long my_rank = (long) rank;
double factor;
long long i;
long long my_n = n/thread_count;
long long my_first_i = my_n*my_rank;
long long my_last_i = my_first_i + my_n;
double my_sum = 0.0;
if (my_first_i % 2 == 0)
factor = 1.0;
else
factor = -1.0;
for (i = my_first_i; i < my_last_i; i++, factor = -factor) {
my_sum += factor/(2*i+1);
}
pthread_mutex_lock(&mutex);
sum += my_sum;
pthread_mutex_unlock(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t barrier;
pthread_mutex_t min_mutex, max_mutex;
pthread_cond_t go;
int numWorkers;
int numArrived = 0;
void Barrier() {
pthread_mutex_lock(&barrier);
numArrived++;
if (numArrived == numWorkers) {
numArrived = 0;
pthread_cond_broadcast(&go);
} else
pthread_cond_wait(&go, &barrier);
pthread_mutex_unlock(&barrier);
}
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);
}
int x, y;
int value;
} Pos;
double start_time, end_time;
int size, stripSize;
long sums[10];
Pos min, max;
int matrix[10000][10000];
void *Worker(void *);
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(&barrier, 0);
pthread_mutex_init(&max_mutex, 0);
pthread_mutex_init(&min_mutex, 0);
pthread_cond_init(&go, 0);
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(7);
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
matrix[i][j] = rand()%99;
}
}
min.value = matrix[0][0];
min.x = min.y = 0;
max.value = matrix[0][0];
max.x = max.y = 0;
start_time = read_timer();
for (l = 0; l < numWorkers; l++)
pthread_create(&workerid[l], &attr, Worker, (void *) l);
pthread_exit(0);
}
void *Worker(void *arg) {
long myid = (long) arg;
long total;
int i, j, first, last;
first = myid*stripSize;
last = (myid == numWorkers - 1) ? (size - 1) : (first + stripSize - 1);
total = 0;
for (i = first; i <= last; i++)
for (j = 0; j < size; j++) {
total += matrix[i][j];
if (min.value > matrix[i][j]) {
pthread_mutex_lock(&min_mutex);
if (min.value > matrix[i][j]) {
min.value = matrix[i][j];
min.x = j;
min.y = i;
}
pthread_mutex_unlock(&min_mutex);
} else if (max.value < matrix[i][j]) {
pthread_mutex_lock(&max_mutex);
if (max.value < matrix[i][j]) {
max.value = matrix[i][j];
max.x = j;
max.y = i;
}
pthread_mutex_unlock(&max_mutex);
}
}
sums[myid] = total;
Barrier();
if (myid == 0) {
total = 0;
for (i = 0; i < numWorkers; i++) {
total += sums[i];
}
end_time = read_timer();
printf("The total is %ld, min is %d at [%d,%d], max is %d at [%d,%d]\\n", total,
min.value, min.y, min.x, max.value, max.y, max.x);
printf("The execution time is %g sec\\n", end_time - start_time);
}
}
| 0
|
#include <pthread.h>
struct msg{
struct msg *next;
int num;
};
struct msg *head;
pthread_cond_t g_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
void* threadFunc_Consumer(void* args){
struct msg *mp;
while(1){
pthread_mutex_lock(&g_mutex);
while(!head)
pthread_cond_wait(&g_cond,&g_mutex);
mp = head;
head = head->next;
printf("consumer:%d\\n",mp->num);
pthread_mutex_unlock(&g_mutex);
free(mp);
sleep( rand() % 5 );
}
return (void*)0;
}
void* threadFunc_Producer(void* args ){
struct msg *mp;
while(1){
mp = malloc(sizeof(struct msg));
mp->num = rand()% 1000 + 1;
printf("Producer:%d\\n",mp->num);
pthread_mutex_lock(&g_mutex);
mp->next = head;
head = mp;
pthread_mutex_unlock(&g_mutex);
pthread_cond_signal(&g_cond);
sleep(rand()%5);
}
return (void*)0;
}
int main()
{
pthread_t pid,cid;
srand(time(0));
pthread_create(&pid,0,threadFunc_Producer,0);
pthread_create(&cid,0,threadFunc_Consumer,0);
pthread_join(pid,0);
pthread_join(cid,0);
return 0;
}
| 1
|
#include <pthread.h>
enum
{
NOT_RESERVED = 0,
RESERVED_DATA = 1,
RESERVED_FREE = 2,
};
static int g_buffer_size;
static int g_start_idx;
static int g_data_size;
static int g_reserve_type;
static int g_reserve_size;
char *g_data_buffer = 0;
pthread_mutex_t g_buf_mutex;
int init_buffer(int buf_size)
{
if(g_data_buffer != 0)
{
free(g_data_buffer);
g_data_buffer = 0;
}
g_data_buffer = (char *)malloc(buf_size+(16*1024*1024));
memset(g_data_buffer, 0x0, buf_size);
g_buffer_size = buf_size;
g_start_idx = 0;
g_data_size = 0;
g_reserve_type = NOT_RESERVED;
pthread_mutex_init(&g_buf_mutex, 0);
return 0;
}
int destroy_buffer()
{
if(g_data_buffer != 0)
{
free(g_data_buffer);
g_data_buffer = 0;
}
pthread_mutex_destroy(&g_buf_mutex);
return 0;
}
int clear_buffer()
{
if(g_data_buffer == 0)
{
return -1;
}
pthread_mutex_lock(&g_buf_mutex);
g_start_idx = 0;
g_data_size = 0;
memset(g_data_buffer, 0x0, g_buffer_size);
pthread_mutex_unlock(&g_buf_mutex);
return 0;
}
char *get_free_buffer(int get_size)
{
pthread_mutex_lock(&g_buf_mutex);
if(g_buffer_size-g_data_size < get_size)
{
pthread_mutex_unlock(&g_buf_mutex);
return 0;
}
int free_idx = (g_start_idx + g_data_size) % g_buffer_size;
if(free_idx + get_size > g_buffer_size)
{
g_reserve_type = RESERVED_FREE;
g_reserve_size = free_idx + get_size - g_buffer_size;
}
char *ptr = g_data_buffer + free_idx;
pthread_mutex_unlock(&g_buf_mutex);
return ptr;
}
int use_free_buffer(int used_size)
{
pthread_mutex_lock(&g_buf_mutex);
g_data_size += used_size;
if(g_reserve_type == RESERVED_FREE)
{
memcpy(g_data_buffer, g_data_buffer+g_buffer_size, g_reserve_size);
g_reserve_type = NOT_RESERVED;
}
pthread_mutex_unlock(&g_buf_mutex);
return 0;
}
char *get_buffer(int get_size)
{
pthread_mutex_lock(&g_buf_mutex);
if(g_data_size < get_size)
{
pthread_mutex_unlock(&g_buf_mutex);
return 0;
}
if(g_start_idx + get_size > g_buffer_size)
{
g_reserve_type = RESERVED_DATA;
g_reserve_size = g_start_idx + get_size - g_buffer_size;
memcpy(g_data_buffer+g_buffer_size, g_data_buffer, g_reserve_size);
}
char *ptr = g_data_buffer + g_start_idx;
pthread_mutex_unlock(&g_buf_mutex);
return ptr;
}
int release_buffer(int used_size)
{
pthread_mutex_lock(&g_buf_mutex);
memset(g_data_buffer+g_start_idx, 0x0, used_size);
g_start_idx += used_size;
g_start_idx %= g_buffer_size;
g_data_size -= used_size;
if(g_data_size < 0)
{
g_data_size = 0;
}
if(g_reserve_type == RESERVED_DATA)
{
g_reserve_type = NOT_RESERVED;
}
pthread_mutex_unlock(&g_buf_mutex);
return 0;
}
int get_data_size()
{
return g_data_size;
}
| 0
|
#include <pthread.h>
void *sum(void *p);
unsigned long int sumtotal = 0;
unsigned long int n;
int numthreads;
pthread_mutex_t mutex;
int main(int argc, char **argv) {
pthread_t tid[8];
int i, myid[8];
struct timeval start, end;
gettimeofday(&start, 0);
scanf("%lu %d", &n, &numthreads);
for (i = 0; i < numthreads; i++) {
myid[i] = i;
pthread_create(&tid[i], 0, sum, &myid[i]);
}
for (i = 0; i < numthreads; i++) {
pthread_join(tid[i], 0);
}
pthread_mutex_destroy(&mutex);
gettimeofday(&end, 0);
long spent = (end.tv_sec * 1000000 + end.tv_usec)
- (start.tv_sec * 1000000 + start.tv_usec);
printf("%lu\\n%ld\\n", sumtotal, spent);
return 0;
}
void *sum(void *p) {
int myid = *((int *) p);
unsigned long int start = (myid * (unsigned long int) n) / numthreads;
unsigned long int end = ((myid + 1) * (unsigned long int) n) / numthreads;
unsigned long int i;
unsigned long int local_sum = 0.0;
for (i = start; i < end; i++) {
local_sum += 2;
}
pthread_mutex_lock(&mutex);
sumtotal += local_sum;
pthread_mutex_unlock(&mutex);
return 0 ;
}
| 1
|
#include <pthread.h>
int ssock;
pthread_mutex_t smutex = PTHREAD_MUTEX_INITIALIZER;
void* comth(void* arg)
{
int ix;
int csock;
char buf[64];
int len;
ix = *((int*)arg);
free(arg);
while(1)
{
pthread_mutex_lock(&smutex);
csock = accept(ssock, 0, 0);
pthread_mutex_unlock(&smutex);
sleep(3);
len = sprintf(buf, "%d. szal: %d\\n", ix, rand()%10 );
send(csock, buf, len, 0);
close(csock);
}
return 0;
}
int main()
{
struct sockaddr_in6 addr;
pthread_t th[3];
int i;
int reuse;
int* pix;
if((ssock = socket(PF_INET6, SOCK_STREAM, 0)) < 0)
{
perror("socket");
return 1;
}
reuse = 1;
setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
memset(&addr, 0, sizeof(addr));
addr.sin6_family = AF_INET6;
addr.sin6_addr = in6addr_any;
addr.sin6_port = htons(2233);
if(bind(ssock, (struct sockaddr*)&addr, sizeof(addr)) < 0)
{
perror("bind");
return 1;
}
if(listen(ssock, 5) < 0)
{
perror("listen");
return 1;
}
srand(time(0));
for(i = 0; i < 3; i++)
{
pix = malloc(sizeof(int));
*pix = i;
pthread_create(&th[i], 0, comth, pix);
}
while(1) sleep(1);
return 0;
}
| 0
|
#include <pthread.h>
int semsetid = -1;
pthread_mutex_t mutex;
union semun
{
int val;
struct semid_ds *buf;
unsigned short *array;
struct seminfo *__buf;
};
void getChopsticks(int num)
{
int left = num;
int right = (num + 1) % 5;
struct sembuf sem[2] = {{left, -1, 0},
{right, -1, 0}};
semop(semsetid, sem, 2);
}
void putChopsticks(int num)
{
int left = num;
int right = (num + 1) % 5;
struct sembuf sem[2] = {{left, 1, 0},
{right, 1, 0}};
semop(semsetid, sem, 2);
}
void *eatThink(void *arg)
{
int num = (int)arg;
while (1)
{
printf("%dtn pilosopher is thinking...\\n", num);
sleep(1);
getChopsticks(num);
printf("\\t\\t\\t%dth get chopsticks to eat\\n", num);
sleep(1);
pthread_mutex_lock(&mutex);
putChopsticks(num);
printf("%dth put down chopsticks to think\\n", num);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main(int argc, char const *argv[])
{
int ret = -1;
int i = 0;
union semun sem;
semsetid = semget(0x1024, 5, IPC_CREAT | 0777);
if(semsetid == -1){
perror("semget");
return -1;
}
sem.val = 1;
for(i = 0; i < 5; i++){
semctl(semsetid, i, SETVAL, sem);
}
pthread_t pilosopher[5];
for(i = 0; i < 5; i++){
ret = pthread_create(&pilosopher[i], 0, eatThink, (void *)i);
if (ret == -1)
{
perror("pthread");
return -1;
}
}
while (1)
{
pause();
}
return 0;
}
| 1
|
#include <pthread.h>
{
char buff[100];
char fin;
int hilos;
int espera;
sem_t semaforo_es;
sem_t semaforo_mayus;
}
datos_compartidos;
int aleatorio (void);
void * es (void *);
void * mayus (void *);
int main (int argc, char * argv[])
{
int i, e;
pthread_t tids[200];
datos_compartidos dc;
dc.fin = 0;
if (argc > 1)
{
if (sscanf(argv[1],"%d",&dc.hilos) != 1 ||
dc.hilos < 1 || dc.hilos > 200)
{
printf ("Parámetro \\"nº_de_hilos\\" incorrecto.\\n");
dc.fin = 1;
}
}
else
dc.hilos = 2;
if (argc > 2)
{
if (sscanf(argv[2],"%d",&dc.espera) != 1 ||
dc.espera < 0 || dc.espera > 1000000)
{
printf ("Parámetro \\"microsegundos\\" incorrecto.\\n");
dc.fin = 1;
}
}
else
dc.espera = 20;
if (dc.fin)
{
printf ("Uso:\\n\\t%s [ nº_de_hilos "
"[ microsegundos ] ]\\n", argv[0]);
printf ("Máx. nº_de_hilos: %d\\n", 200);
printf ("Máx. microsegundos: %d\\n", 1000000);
return -2;
}
srand ((unsigned)getpid() ^ (unsigned)time(0));
if (sem_init (&dc.semaforo_es, 0, 0) ||
sem_init (&dc.semaforo_mayus, 0, 0))
{
perror ("sem_init");
return -1;
}
for (i=0; i<dc.hilos; i++)
if ((e=pthread_create (&tids[i], 0, mayus, &dc)) != 0)
{
fprintf (stderr, "Error %d al "
"crear el hilo nº %d\\n", e, i+1);
return -1;
}
es (&dc);
for (i=0; i<dc.hilos; i++)
if ((e=pthread_join (tids[i], 0)) != 0)
{
fprintf (stderr, "Error %d esperando "
"al hilo nº %d\\n", e, i+1);
return -2;
}
sem_destroy (&dc.semaforo_es);
sem_destroy (&dc.semaforo_mayus);
return 0;
}
void * es (void * pv)
{
datos_compartidos * dc = (datos_compartidos *) pv;
int i;
printf ("Escriba líneas de texto (Ctrl+D para terminar):\\n");
for (;;)
{
if (!fgets (dc->buff, 100, stdin))
dc->fin = 1;
for (i=0; i<dc->hilos; i++)
sem_post (&dc->semaforo_mayus);
if (dc->fin)
return 0;
for (i=0; i<dc->hilos; i++)
sem_wait (&dc->semaforo_es);
fputs (dc->buff, stdout);
}
}
void * mayus (void * pv)
{
datos_compartidos * dc = (datos_compartidos *) pv;
int i;
char c;
static pthread_mutex_t quietoparao = PTHREAD_MUTEX_INITIALIZER;
for (;;)
{
sem_wait (&dc->semaforo_mayus);
if (dc->fin)
return 0;
pthread_mutex_lock (&quietoparao);
for (i=0; dc->buff[i]; i++)
if (aleatorio() > 32767/2)
{
c = dc->buff[i];
if (c >= 'a' && c <= 'z')
{
if (dc->espera)
usleep (dc->espera);
dc->buff[i] -= ('a' - 'A');
}
}
pthread_mutex_unlock (&quietoparao);
sem_post (&dc->semaforo_es);
}
}
int aleatorio (void)
{
int i;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock (&mutex);
i = rand ();
pthread_mutex_unlock (&mutex);
return i;
}
| 0
|
#include <pthread.h>
int flag = 0;
struct Usuario{
char telefone[4];
char enderecoIP[4];
char porta[4];
int status;
struct Usuario *prox;
};
usuario *LISTA;
pthread_t thread_servidor;
pthread_mutex_t mutex;
void *Servidor(void *args);
void insereFim(usuario *LISTA, char tel[], char ip[], char port[]);
int vazia(usuario *LISTA);
void exibe(usuario *LISTA);
main(argc, argv)
int argc;
char **argv;
{
unsigned short port;
char sendbuf[12];
struct sockaddr_in client;
struct sockaddr_in server;
int s;
int ns;
int namelen;
int tc;
int teste = 2;
if (argc != 2)
{
fprintf(stderr, "Use: %s porta\\n", argv[0]);
exit(1);
}
port = (unsigned short) atoi(argv[1]);
if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{
perror("Socket()");
exit(2);
}
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr.s_addr = INADDR_ANY;
if (bind(s, (struct sockaddr *)&server, sizeof(server)) < 0)
{
perror("Bind()");
exit(3);
}
if (listen(s, 1) != 0)
{
perror("Listen()");
exit(4);
}
LISTA = (usuario *) malloc(sizeof(usuario));
LISTA->prox = 0;
pthread_mutex_init(&mutex, 0);
while(1)
{
namelen = sizeof(client);
if((ns = accept(s, (struct sockaddr *)&client, &namelen)) == -1)
{
perror("Accept()");
exit(5);
}
tc = pthread_create(&thread_servidor, 0, Servidor, (void *) &ns);
if(tc)
{
printf("ERRO: impossivel criar um thread cliente\\n");
exit(-1);
}
pthread_detach(thread_servidor);
}
close(s);
printf("Servidor terminou com sucesso.\\n");
exit(0);
}
void *Servidor(void *args)
{
char telefone[4];
char enderecoIP[4];
char porta[4];
char recvbuf[4 + 4 + 4 + 4];
int ns;
ns = *(int*)args;
if(recv(ns, recvbuf, sizeof(recvbuf), 0) == -1)
{
perror("Recv()");
exit(6);
}
pthread_mutex_lock(&mutex);
sscanf(recvbuf,"%s %s %s", telefone, enderecoIP, porta);
printf("Mensagem recebida do cliente: %s %s %s\\n", telefone, enderecoIP, porta);
insereFim(LISTA, telefone, enderecoIP, porta);
exibe(LISTA);
pthread_mutex_unlock(&mutex);
close(ns);
pthread_exit(0);
}
void insereFim(usuario *LISTA, char tel[], char ip[], char port[])
{
usuario *novo=(usuario *) malloc(sizeof(usuario));
if(!novo){
printf("Sem memoria disponivel!\\n");
exit(1);
}
strcpy(novo->telefone, tel);
strcpy(novo->enderecoIP, ip);
strcpy(novo->porta, port);
novo->status = 1;
novo->prox = 0;
if(vazia(LISTA))
LISTA->prox=novo;
else{
usuario *tmp = LISTA->prox;
while(tmp->prox != 0)
tmp = tmp->prox;
tmp->prox = novo;
}
}
int vazia(usuario *LISTA)
{
if(LISTA->prox == 0)
return 1;
else
return 0;
}
void exibe(usuario *LISTA)
{
if(vazia(LISTA)){
printf("Lista vazia!\\n\\n");
return ;
}
usuario *tmp;
tmp = LISTA->prox;
while( tmp != 0){
printf("%s\\n", tmp->telefone);
tmp = tmp->prox;
}
printf("\\n\\n");
}
| 1
|
#include <pthread.h>
BTN_PRESS = 0,
BTN_RELEASE
} BTN_STATE_E;
static BTN_STATE_E current_btn_state = BTN_RELEASE;
static short worker_stop = 0;
static useconds_t worker_delay = 200000;
static pthread_mutex_t btn_state_lock;
void sigint_handler (int s) {
debug("Caught signal %d\\n", s);
worker_stop = 1;
}
void gpio_event_cb (int n, siginfo_t *info, void *unused) {
debug("Button %s\\n", (info->si_int == 0) ? "Pressed" : "Released");
pthread_mutex_lock(&btn_state_lock);
current_btn_state = (BTN_STATE_E) info->si_int;
pthread_mutex_unlock(&btn_state_lock);
}
int send_pid_to_kmod () {
int fd;
if ((fd = open ("/sys/class/gpio-trigger/pid", O_WRONLY) ) == -1) {
debug("Cannot open output file\\n");
return -1;
}
int pid_len = sizeof(pid_t);
char *pid_str = (char *) malloc (pid_len * sizeof (char));
check_mem(pid_str);
memset(pid_str, 0, pid_len);
sprintf(pid_str, "%d", getpid());
int bytes_write = write (fd, pid_str, strlen(pid_str));
close(fd);
free(pid_str);
return (bytes_write == -1) ? -1 : 1;
}
long long get_system_time () {
struct timeb t;
ftime(&t);
return 1000 * t.time + t.millitm;
}
long long get_timeuse (long long start, long long end) {
return end - start;
}
void * work_func (void *argu) {
char cmd[128] = {0};
system("touch /tmp/gpio.log");
long long start = 0, end = 0, timeuse = 0;
static BTN_STATE_E prev_btn_state = BTN_RELEASE;
while (worker_stop == 0) {
debug("prev_btn_state : %d\\tcurrent_btn_state : %d", (int) prev_btn_state, (int) current_btn_state);
pthread_mutex_lock(&btn_state_lock);
if (prev_btn_state != current_btn_state) {
switch (current_btn_state) {
case BTN_PRESS:
{
start = get_system_time();
debug("start time : %lld", start);
break;
}
case BTN_RELEASE:
{
end = get_system_time();
debug("end time : %lld", end);
break;
}
default:
debug("Unknown Button State");
break;
}
}
prev_btn_state = current_btn_state;
pthread_mutex_unlock(&btn_state_lock);
if (start != 0 && end != 0) {
timeuse = get_timeuse (start, end);
debug("\\x1B[32mTimeuse : %lld \\033[0m", timeuse);
if (timeuse >= 5 * 1000) {
}
sprintf(cmd, "echo %d >> /tmp/gpio.log", timeuse);
system(cmd);
memset(cmd, 0, 128);
start = end = timeuse = 0;
}
usleep(worker_delay);
}
return 0;
}
int main (int argc, char **argv) {
pthread_t work_thread;
if ( send_pid_to_kmod() == -1 ) {
debug("send_pid_to_kmod failed");
exit(1);
}
debug("send_pid_to_kmod Success");
pthread_mutex_init(&btn_state_lock, 0);
struct sigaction sig;
sig.sa_sigaction = gpio_event_cb;
sig.sa_flags = SA_SIGINFO;
sigaction(40, &sig, 0);
memset(&sig, 0, sizeof(sig));
sig.sa_handler = sigint_handler;
sigemptyset(&sig.sa_mask);
sig.sa_flags = 0;
sigaction(SIGINT, &sig, 0);
debug("Event Register Success");
pthread_create(&work_thread, 0, &work_func, 0);
pthread_join(work_thread, 0);
pthread_mutex_destroy(&btn_state_lock);
debug("Process Return");
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t consoleMutex;
pthread_mutex_t debugMutex;
struct threadArgs {
int threadId;
char searchString[15];
int startIndex;
int endIndex;
char searchArray[100000][15];
};
void *threadWork(void *args) {
struct threadArgs * newArgs;
newArgs = (struct threadArgs *)args;
bool found = 0;
int position = -1;
int i;
for ( i = newArgs->startIndex ; (i < newArgs->endIndex) && !found ; i++ ) {
if ( strcmp(newArgs->searchArray[i], newArgs->searchString) == 0) {
found = 1;
position = i;
}
}
pthread_mutex_lock(&consoleMutex);
if ( found )
printf("thread %d,\\t found yes,\\t slice %d,\\t position %d\\n", newArgs->threadId, newArgs->threadId, position + 4);
else
printf("thread %d,\\t found no,\\t slice %d,\\t position %d\\n", newArgs->threadId, newArgs->threadId, position);
pthread_mutex_unlock(&consoleMutex);
pthread_exit(0);
}
int main () {
FILE *fp;
char valueArray[100000][15];
char searchString[15];
int NT = 0;
int NS = 0;
int sectionSize = 0;
int startIndex, endIndex;
char line[15];
int counter = 0;
int i, j;
for ( i = 0 ; i < 100000 ; i++)
for ( j = 0 ; j < 15 ; j++ )
valueArray[i][j] = 0;
fp = fopen("fartico_aniketsh_input_partA.txt", "r");
while (fgets(line, 15, fp)) {
switch (counter) {
case 0 :
NT = atoi(line);
break;
case 1 :
NS = atoi(line);
break;
case 2 :
strncpy(searchString, line, sizeof(line));
break;
default :
strncpy(valueArray[counter - 3], line, sizeof(line));
}
counter++;
}
fclose(fp);
pthread_t threads[NT];
sectionSize = 100000 / NS;
startIndex = 0;
endIndex = sectionSize - 1;
int status;
struct threadArgs args[NT];
for ( i = 0 ; i < NS ; i++ ) {
memcpy(args[i].searchArray, valueArray, (100000 * 15) * sizeof(char));
strcpy(args[i].searchString, searchString);
args[i].threadId = i + 1;
args[i].startIndex = startIndex;
args[i].endIndex = endIndex;
status = pthread_create(&threads[i], 0, threadWork, (void*)&args[i]);
startIndex = startIndex + sectionSize;
endIndex = endIndex + sectionSize;
}
for ( i = 0 ; i < NT ; i++)
pthread_join(threads[i], 0);
return 0;
}
| 1
|
#include <pthread.h>
struct list_head {
struct list_head *next ;
struct list_head *prev ;
};
struct s {
int datum ;
struct list_head list ;
};
struct cache {
struct list_head slot[10] ;
pthread_mutex_t slots_mutex[10] ;
};
struct cache c ;
static inline void INIT_LIST_HEAD(struct list_head *list) {
list->next = list;
list->prev = list;
}
struct s *new(int x) {
struct s *p = malloc(sizeof(struct s));
p->datum = x;
INIT_LIST_HEAD(&p->list);
return p;
}
static inline void list_add(struct list_head *new, struct list_head *head) {
struct list_head *next = head->next;
next->prev = new;
new->next = next;
new->prev = head;
head->next = new;
}
void *f(void *arg) {
struct s *pos ;
int j;
struct list_head const *p ;
struct list_head const *q ;
while (j < 10) {
pthread_mutex_lock(&c.slots_mutex[j]);
p = c.slot[j].next;
pos = (struct s *)((char *)p - (size_t)(& ((struct s *)0)->list));
while (& pos->list != & c.slot[j]) {
pos->datum++;
q = pos->list.next;
pos = (struct s *)((char *)q - (size_t)(& ((struct s *)0)->list));
}
pthread_mutex_unlock(&c.slots_mutex[j]);
j ++;
}
return 0;
}
int main() {
pthread_t t1, t2;
for (int i = 0; i < 10; i++) {
INIT_LIST_HEAD(&c.slot[i]);
pthread_mutex_init(&c.slots_mutex[i], 0);
for (int j = 0; j < 30; j++) list_add(&new(j*i)->list, &c.slot[i]);
}
pthread_create(&t1, 0, f, 0);
pthread_create(&t2, 0, f, 0);
return 0;
}
| 0
|
#include <pthread.h>
int tid;
} data;
int x;
int y;
} int2;
double x;
double y;
} double2;
float **mat;
double x = -DBL_MAX, dt=0.001;
int nColumns=2048, nLines=2048, i = 0, size;
pthread_mutex_t mutex;
pthread_cond_t condM;
pthread_cond_t condE;
int2 coordinatesConversion( double x,double y, int nColumns,int nLines){
int2 ret;
int2 retError;
retError.x=-1;
retError.y=-1;
ret.x=round(((2.0+x)/3.5) *((double)(nColumns-1)));
ret.y=round(((1.5+y)/3.5) *((double)(nLines-1)));
if(ret.x<0 || ret.x>=nColumns) return retError;
if(ret.y<0 || ret.y>=nLines) return retError;
return ret;
}
int printMatrixToFilePGM(float **mat,int tamx, int nLines, char *srcFile){
FILE *arq=fopen(srcFile,"w");
int cont, cont2;
float min,max;
min=mat[0][0];
max=mat[0][0];
for(cont=0;cont<nLines;cont++){
for(cont2=0;cont2<tamx;cont2++){
if(min>mat[cont][cont2]) min=mat[cont][cont2];
if(max<mat[cont][cont2]) max=mat[cont][cont2];
}
}
max=max*0.35;
float delta=max-min;
fprintf(arq,"P2 \\n");
fprintf(arq,"%d\\n%d \\n",tamx,nLines);
fprintf(arq,"255\\n");
for(cont=0;cont<nLines;cont++){
for(cont2=0;cont2<tamx;cont2++){
int valpixel=((mat[cont][cont2]-min)/delta)*255.0f;
if(valpixel>255) valpixel=255;
fprintf(arq,"%d \\n", valpixel);
}
}
fclose(arq);
}
float** mallocFloatMatrix(int tamx, int nLines, float defaultValueOfTheElementsAtMatrix){
float **errorCodeReturn=0x0;
float **mat;
int i,j;
int condErrorMalloc=0;
mat=malloc(sizeof(float *)*nLines);
if(mat==0x0) return errorCodeReturn;
for(i=0;i<tamx;i++)
mat[i]=malloc(sizeof(float )*tamx);
for(i=0;i<tamx;i++){
if(mat[i]==0x0){
condErrorMalloc=1;
break;
}
}
if(condErrorMalloc==0){
return mat;
}
for(i=0;i<nLines;i++){
for(j=0;j<tamx;j++)
mat[i][j]=defaultValueOfTheElementsAtMatrix;
}
for(i=0;i<tamx;i++)
if(mat[i]!=0x0) free(mat[i]);
free(mat);
return errorCodeReturn;
}
void freeFloatMatrix(float **mat,int tamx, int nLines){
int i;
for(i=0;i<nLines;i++){
if(mat[i]!=0x0) free(mat[i]);
}
free(mat);
}
int iteration(double x,double y, int nColumns,int nLines, int ite,int2 *iterationPath){
int cont;
int condInvalidPointer=1;
double2 z;
z.x=0.0;
z.y=0.0;
double2 c;
c.x=x;
c.y=y;
double2 zt;
for(cont=0;cont<ite;cont++){
zt.x=((z.x*z.x)-(z.y*z.y))+c.x;
zt.y=(2.0*(z.x*z.y))+c.y;
z=zt;
if(((z.x*z.x)+(z.y*z.y))>4.0){
if(cont>100)
condInvalidPointer=0;
break;
}
iterationPath[cont]=coordinatesConversion(z.x,z.y,nColumns,nLines);
}
if(condInvalidPointer)
return 0;
return cont;
}
void *mestre(void *param){
for(i=0;i<size;i++){
pthread_mutex_lock(&mutex);
x=-2.0+((double)i*dt);
pthread_cond_signal(&condE);
pthread_cond_wait(&condM, &mutex);
pthread_mutex_unlock(&mutex);
}
}
void *escravo(void *param){
data *dados = (data *)param;
int k, ite=600,progress=0;
while (1) {
if (i >= size) {
printf("%d saiu. \\n", dados->tid);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
while (x == -DBL_MAX) {
pthread_cond_signal(&condM);
pthread_cond_wait(&condE, &mutex);
}
double x1 = x;
x = -DBL_MAX;
pthread_cond_signal(&condM);
pthread_mutex_unlock(&mutex);
double y;
for(y=-2.0;y<2.0;y=y+dt){
int2* iterationPath=(int2 *)malloc(sizeof(int2)*ite);
if(iterationPath==0x0) return 0x0;
int completedIterations = iteration(x1,y,nColumns,nLines,ite, iterationPath);
for(k=0;k<completedIterations;k++){
if(iterationPath[k].x!=-1 && iterationPath[k].y!=-1)
mat[iterationPath[k].x][iterationPath[k].y]=mat[iterationPath[k].x][iterationPath[k].y]+1.0f;
}
free(iterationPath);
}
progress++;
if(progress%100 ==0)
printf("[%d] %lf \\n",dados->tid,x1);
}
}
int main(void){
pthread_t mestre_t;
pthread_t threads[4];
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&condM, 0);
pthread_cond_init(&condE, 0);
size = round(4.0/dt);
mat=mallocFloatMatrix(nColumns,nLines,0.0f);
if(mat==0x0) return 0;
int t;
pthread_create(&mestre_t, 0, mestre, 0);
data *dados = (data *)malloc(4 * sizeof(data));
for (t=0; t<4; t++){
dados[t].tid = t;
pthread_create(&threads[t], 0, escravo, &dados[t]);
}
for (t=0; t<4; t++)
pthread_join(threads[t], 0);
printMatrixToFilePGM(mat,nColumns,nLines,"saida3.pgm");
freeFloatMatrix(mat,nColumns,nLines);
return 0;
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int *spaces;
int capacity;
int occupied;
int nextin;
int nextout;
int car_in;
int car_out;
pthread_mutex_t lock;
pthread_cond_t num_space;
pthread_cond_t num_car;
pthread_barrier_t barrier;
} parking_lot_t;
static void * parking_handler(void *parking_lot);
static void * picking_handler(void *parking_lot);
static void * monitor(void *parking_lot);
static void initialize(parking_lot_t *cp, int size);
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s capacity\\n", argv[0]);
exit(1);
}
parking_lot_t parking_lot;
initialize(&parking_lot, atoi(argv[1]));
pthread_t car_parker1, car_parker2, car_parker3;
pthread_t car_picker1, car_picker2, car_picker3;
pthread_t parking_monitor;
pthread_create(&car_parker1, 0, parking_handler,(void*)&parking_lot);
pthread_create(&car_picker1, 0, picking_handler, (void*)&parking_lot);
pthread_create(&car_parker2, 0, parking_handler, (void*)&parking_lot);
pthread_create(&car_picker2, 0, picking_handler, (void*)&parking_lot);
pthread_create(&car_parker3, 0, parking_handler, (void*)&parking_lot);
pthread_create(&car_picker3, 0, picking_handler, (void*)&parking_lot);
pthread_create(&parking_monitor, 0, monitor,(void*)&parking_lot);
pthread_join(car_parker1, 0);
pthread_join(car_picker1, 0);
pthread_join(car_parker2, 0);
pthread_join(car_picker2, 0);
pthread_join(car_parker3, 0);
pthread_join(car_picker3, 0);
pthread_join(parking_monitor, 0);
exit(0);
}
static void initialize(parking_lot_t *parking_lot, int size){
parking_lot->capacity = size;
parking_lot->occupied = parking_lot->nextin = parking_lot->nextout = 0;
parking_lot->car_in = parking_lot->car_out = 0;
parking_lot->spaces = (int*)calloc(size, sizeof(*(parking_lot->spaces)));
pthread_barrier_init(&(parking_lot->barrier), 0, 6);
if(parking_lot->spaces == 0){
printf("No enough memory\\n");
exit(1);
}
srand((unsigned int)(getpid()));
pthread_mutex_init(&(parking_lot->lock), 0);
pthread_cond_init(&(parking_lot->num_space), 0);
pthread_cond_init(&(parking_lot->num_car), 0);
}
static void* parking_handler(void* in_parking_lot){
parking_lot_t *parking_lot = (parking_lot_t*)in_parking_lot;
unsigned int seed;
pthread_barrier_wait(&(parking_lot->barrier));
while(1){
usleep(rand_r(&seed) % 1000000);
pthread_mutex_lock(&(parking_lot->lock));
while(parking_lot->occupied == parking_lot->capacity){
pthread_cond_wait(&(parking_lot->num_space), &(parking_lot->lock));
}
parking_lot->spaces[parking_lot->nextin] = rand_r(&seed) % 10;
parking_lot->occupied++;
parking_lot->nextin++;
parking_lot->nextin%= parking_lot->capacity;
parking_lot->car_in++;
pthread_cond_signal(&(parking_lot->num_car));
}
return ((void*) 0);
}
static void * picking_handler(void* in_parking_lot){
parking_lot_t *parking_lot = (parking_lot_t*)in_parking_lot;
pthread_barrier_wait(&(parking_lot->barrier));
unsigned int seed;
while(1){
usleep(rand_r(&seed) & 1000000);
pthread_mutex_lock(&(parking_lot->lock));
while(parking_lot->occupied == 0){
pthread_cond_wait(&(parking_lot->num_car), &(parking_lot->lock));
}
parking_lot->spaces[parking_lot->nextout] = 0;
parking_lot->occupied--;
parking_lot->nextout++;
parking_lot->nextout%= parking_lot->capacity;
parking_lot->car_out++;
pthread_cond_signal(&(parking_lot->num_space));
}
return ((void*) 0);
}
static void *monitor(void *in_parking_lot){
parking_lot_t *parking_lot = (parking_lot_t*)in_parking_lot;
while(1){
sleep(2);
pthread_mutex_lock(&(parking_lot->lock));
printf("car_in: %d\\t", parking_lot->car_in);
printf("car_out+occupied: %d\\n", parking_lot->car_out + parking_lot->occupied);
pthread_mutex_unlock((&parking_lot->lock));
}
return ((void*)0);
}
| 0
|
#include <pthread.h>
unsigned int count;
unsigned int data[12];
int in;
int out;
pthread_mutex_t mutex;
pthread_cond_t empty;
pthread_cond_t full;
} buffer_t;
static buffer_t shared_buffer = {
.count = 0,
.in = 0,
.out = 0,
.mutex = PTHREAD_MUTEX_INITIALIZER,
.empty = PTHREAD_COND_INITIALIZER,
.full = PTHREAD_COND_INITIALIZER
};
static const char *progname = "bounded";
static int
next()
{
static unsigned int cnt = 0;
return ++cnt;
}
static void
check(unsigned int num)
{
static unsigned int cnt = 0;
assert(num == ++cnt);
}
static void*
producer(void *data)
{
buffer_t *buffer = (buffer_t *) data;
while (1) {
pthread_mutex_lock(&buffer->mutex);
while (buffer->count == 12) {
pthread_cond_wait(&buffer->empty, &buffer->mutex);
}
buffer->data[buffer->in] = next();
buffer->in = (buffer->in + 1) % 12;
buffer->count++;
pthread_cond_signal(&buffer->full);
pthread_mutex_unlock(&buffer->mutex);
}
return 0;
}
static void*
consumer(void *data)
{
buffer_t *buffer = (buffer_t *) data;
while (1) {
pthread_mutex_lock(&buffer->mutex);
while (buffer->count == 0) {
pthread_cond_wait(&buffer->full, &buffer->mutex);
}
check(buffer->data[buffer->out]);
buffer->out = (buffer->out + 1) % 12;
buffer->count--;
pthread_cond_signal(&buffer->empty);
pthread_mutex_unlock(&buffer->mutex);
}
return 0;
}
static int
run(int nc, int np)
{
int err, n = nc + np;
pthread_t thread[n];
for (int i = 0; i < n; i++) {
err = pthread_create(&thread[i], 0,
i < nc ? consumer : producer, &shared_buffer);
if (err) {
fprintf(stderr, "%s: %s: unable to create thread %d: %d\\n",
progname, __func__, i, err);
return 1;
}
}
for (int i = 0; i < n; i++) {
if (thread[i]) (void) pthread_join(thread[i], 0);
}
return 0;
}
int
main(int argc, char *argv[])
{
int c, nc = 1, np = 1;
while ((c = getopt(argc, argv, "c:p:h")) >= 0) {
switch (c) {
case 'c':
if ((nc = atoi(optarg)) <= 0) {
fprintf(stderr, "number of consumers must be > 0\\n");
exit(1);
}
break;
case 'p':
if ((np = atoi(optarg)) <= 0) {
fprintf(stderr, "number of producers must be > 0\\n");
exit(1);
}
break;
case 'h':
printf("Usage: %s [-c consumers] [-p producers] [-h]\\n", progname);
exit(0);
}
}
return run(nc, np);
}
| 1
|
#include <pthread.h>
char bwc_buffer[BUFFER_LENGTH];
char bwss_buffer[BUFFER_LENGTH];
pthread_t bwss_thread;
pthread_t bwc_thread;
char *bwss_port = "2000";
char *bwc_port = "2001";
int bwc_socket;
int bwss_socket;
int cnt,ready,ready2;
pthread_mutex_t mutex;
pthread_cond_t cond,cond2;
void* connect_client(void *pcl);
void *bwc_connect(void * ptr);
void *bwss_connect(void *ptr);
int DreadUDP(int cl, char *buf, int l) {
int cnt, pos;
int size = l;
fprintf(stderr, "DreadUDP: %d bytes\\n", size);
pos = 0;
while(size > 0) {
cnt = read(cl, buf+pos, size);
if(cnt <= 0) return cnt;
size -= cnt;
pos += cnt;
}
return pos;
}
void DwriteUDP(int cl, char *buf, int l) {
if(l >= 0) {
printf("entre a DwriteUDP\\n");
if(write(cl, buf, l) != l) {
perror("falló write en el socket");
exit(1);
}
}
fprintf(stderr, "DwriteUDP: %d bytes \\n", l);
}
int main(int argc, char **argv) {
char *bwss_server;
if(argc == 1) {
bwss_server = "localhost";
} else if (argc == 2) {
bwss_server = argv[1];
} else {
fprintf(stderr, "Use: bwcs client_port bwss_server server_port\\n");
return 1;
}
ready = 1;
ready2 = 0;
cnt = 0;
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond,0);
pthread_cond_init(&cond2,0);
pthread_create(&bwc_thread, 0, bwc_connect, (void *)bwc_port);
pthread_create(&bwss_thread, 0, bwss_connect, (void *)bwss_server);
pthread_join(bwss_thread, 0);
pthread_join(bwc_thread, 0);
}
void *bwss_connect(void *ptr) {
int bytes;
if((bwss_socket = j_socket_udp_connect((char *)ptr, bwss_port)) < 0) {
printf("udp connect failed\\n");
exit(1);
}
for(bytes=0;; bytes+=cnt) {
pthread_mutex_lock(&mutex);
while(!ready2){
pthread_cond_wait(&cond2,&mutex);
}
if(cnt <= 0) break;
DwriteUDP(bwss_socket, bwc_buffer, cnt);
ready = 1;
ready2 = 0;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
DwriteUDP(bwss_socket, bwc_buffer, 0);
pthread_mutex_unlock(&mutex);
for(bytes=0;; bytes+=cnt) {
pthread_mutex_lock(&mutex);
cnt = DreadUDP(bwss_socket, bwss_buffer, BUFFER_LENGTH);
ready2 = 0;
ready = 1;
pthread_cond_broadcast(&cond2);
if(cnt <= 0) break;
while(!ready2){
pthread_cond_wait(&cond,&mutex);
}
pthread_mutex_unlock(&mutex);
}
pthread_mutex_unlock(&mutex);
Dclose(bwss_socket);
fprintf(stderr, "%s\\n", "close socket\\n");
return 0;
}
void *bwc_connect(void* ptr) {
Dbind(connect_client, (char *)ptr);
return 0;
}
void* connect_client(void *pcl){
int bytes;
bwc_socket = *((int *)pcl);
free(pcl);
for(bytes=0;; bytes+=cnt) {
pthread_mutex_lock(&mutex);
cnt = Dread(bwc_socket, bwc_buffer, BUFFER_LENGTH);
ready2 = 1;
ready = 0;
pthread_cond_broadcast(&cond2);
if(cnt <= 0) break;
while(!ready){
pthread_cond_wait(&cond,&mutex);
}
pthread_mutex_unlock(&mutex);
}
pthread_mutex_unlock(&mutex);
for(bytes=0;; bytes+=cnt) {
pthread_mutex_lock(&mutex);
while(!ready){
pthread_cond_wait(&cond2,&mutex);
}
if(cnt <= 0) break;
Dwrite(bwc_socket, bwss_buffer, cnt);
ready = 0;
ready2 = 1;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
Dwrite(bwc_socket, bwss_buffer, 0);
pthread_mutex_unlock(&mutex);
Dclose(bwc_socket);
return 0;
}
| 0
|
#include <pthread.h>
unsigned char startsWith(const char* str, const char* cmp)
{
while(1) {
char strC;
char cmpC = *cmp;
if(cmpC == '\\0') return 1;
strC = *str;
if(strC == '\\0' || strC != cmpC) return 0;
str++;cmp++;
}
}
char* skipWhitespace(char* s)
{
while(1) {
char c = *s;
if(c == '\\0') return s;
if(c != ' ' && c != '\\t' && c != '\\n') return s;
s++;
}
}
const char** globalEnvp;
pthread_mutex_t childProcessesMutex;
pthread_cond_t childProcessesCond;
unsigned char debug;
unsigned char globalExit;
void signalManagerThread()
{
pthread_mutex_lock( &childProcessesMutex );
pthread_cond_signal( &childProcessesCond );
pthread_mutex_unlock( &childProcessesMutex );
}
void manager()
{
pid_t managerPid = getpid();
int status;
printf("[manager %d] start\\n", managerPid);
while(1) {
if(globalExit) break;
pthread_mutex_lock( &childProcessesMutex );
if(debug) printf("[manager %d] [debug] waiting for child processes...\\n", managerPid);
pthread_cond_wait( &childProcessesCond, &childProcessesMutex );
pthread_mutex_unlock( &childProcessesMutex );
while(1) {
if(debug) printf("[manager %d] [debug] waitpid\\n", managerPid);
pid_t pid = waitpid(WAIT_ANY, &status, 0);
if(debug) printf("[manager %d] [debug] waitpid returned %d\\n", managerPid, pid);
if(pid == -1) {
if(errno == ECHILD) {
break;
}
printf("[manager %d] waitpid failed (errno %d)\\n", managerPid, errno);
return;
}
if (WIFEXITED(status)) {
printf("[manager %d] pid %d exited with code %d\\n",
managerPid, pid, WEXITSTATUS(status));
} else {
printf("[manager %d] pid %d changed somehow\\n", managerPid, pid);
}
}
}
printf("[manager %d] finish\\n", managerPid);
}
void* uiThread(void* ptr)
{
pid_t uiPid = getpid();
printf("[ui %d] start\\n", uiPid);
char buffer[100];
while(fgets(buffer, sizeof(buffer), stdin) != 0) {
size_t stringLength = strlen(buffer);
while(stringLength > 0) {
stringLength--;
if(buffer[stringLength] == '\\n' || buffer[stringLength] == '\\r') {
buffer[stringLength] = '\\0';
} else {
stringLength++;
break;
}
}
if(startsWith(buffer, "exec")) {
char* args = skipWhitespace(buffer + (sizeof("exec") - 1));
if(*args == '\\0') {
printf("[ui %d] the 'exec' command requires arguments\\n", uiPid);
} else {
printf("[ui %d] the 'exec' command is not implemented\\n", uiPid);
}
} else if(startsWith(buffer, "system")) {
char* args = skipWhitespace(buffer + (sizeof("system") - 1));
if(*args == '\\0') {
printf("[ui %d] the 'system' command requires arguments\\n", uiPid);
} else {
pid_t pid = fork();
if(pid == 0) {
system(args);
return;
}
if(pid == -1) {
printf("[ui %d] fork failed\\n", uiPid);
} else {
printf("[ui %d] created child process %d\\n", uiPid, pid);
signalManagerThread();
}
}
} else {
printf("[ui %d] unknown command '%s'\\n", uiPid, buffer);
}
}
printf("[ui %d] finish\\n", uiPid);
globalExit = 1;
signalManagerThread();
return 0;
}
int main(int argc, const char* argv[], const char* envp[])
{
debug = 0;
globalExit = 0;
globalEnvp = envp;
pthread_t uiThreadInfo;
int status;
status = pthread_create(&uiThreadInfo, 0, uiThread, (void*)0);
if(status) {
printf("[main] error: pthread_create returned %d\\n", status);
return 1;
}
manager();
return 0;
}
| 1
|
#include <pthread.h>
FILE *fs;
FILE *ft;
long NumThreads;
int ThreadParam[64];
pthread_t ThreadHandle[64];
pthread_attr_t ThreadAttr;
pthread_mutex_t lock;
unsigned long long Primes[8192];
int PrimesIndex[8192];
unsigned long long array[8192];
int size;
void* (*MTFindPrimesFunc) (void *arg);
void *MTFindPrimes(void* threadID){
int i = 0, j;
int NumberOfPrimes = 0;
int isprime = 0;
int tid = *((int *) threadID);
int ts;
int te;
if (size % NumThreads != 0){
ts = tid * (size/NumThreads + 1);
if (tid == (NumThreads - 1)){
te = size - 1;
}
else {
te = ts + size/NumThreads;
}
}
else {
ts = tid * size/NumThreads;
te = ts + size/NumThreads;
}
for (i = ts; i <= te; i++){
isprime = 1;
if (array[i] % 2 == 0){
isprime = 0;
}
else {
for (j = 3; j<(unsigned long long)(sqrt(array[i]) + 1); j = j + 2){
if (array[i] % j == 0){
isprime = 0;
break;
}
}
}
if (isprime == 1){
pthread_mutex_lock(&lock);
Primes[NumberOfPrimes + ts] = array[i];
PrimesIndex[NumberOfPrimes + ts] = i;
NumberOfPrimes++;
pthread_mutex_unlock(&lock);
}
}
pthread_exit(0);
}
int main(int argc, char** argv){
int ThreadErr, i = 0, j = 0, isprime, NumberOfPrimes;
double timer;
clock_t start,stop;
start = clock();
switch(argc){
case 3 : NumThreads = 4;
printf("CASE = 3");
break;
case 4 : NumThreads = atoi(argv[3]);
printf("CASE = 4");
break;
default : printf("\\n\\nUsage: ./primeP infile.txt outfile.txt numThreads");
printf("\\n\\nExample: ./primeP numbers.txt primes.txt 4\\n\\n");
return 0;
}
if (NumThreads > 64 || NumThreads < 1){
printf("The number of threads is : %l", NumThreads);
printf("The number of threads requested is not valid. It can support anywhere from 1 to %u threads.\\n", 64);
exit(1);
}
else{
fs = fopen (argv[1], "r");
if (fs == 0){
printf("Cannot open file fs!\\n");
return 0;
}
while (fscanf(fs,"%llu", &array[i]) > 0){
i++;
size++;
if (fscanf(fs,"%llu", &array[i]) > 0){;
i++;
size++;
}
else{
break;
}
}
printf("size = %d", size);
fclose(fs);
ft = fopen (argv[2],"w");
if (ft == 0){
printf("Cannot open file ft!\\n");
return 0;
}
if (size % NumThreads != 0){
printf("Cannot divide task evently among threads. Each thread will receive %d . The last thread will receive less. \\n", size/NumThreads + 1);
}
if (NumThreads >= 1){
pthread_mutex_init(&lock, 0);
if (NumThreads == 1){
printf("Executing the serial version\\n");
}
else{
printf("Executing the multithreaded version with %li threads.\\n", NumThreads);
}
pthread_attr_init(&ThreadAttr);
pthread_attr_setdetachstate(&ThreadAttr, PTHREAD_CREATE_JOINABLE);
for(i=0; i<NumThreads; i++){
ThreadParam[i] = i;
ThreadErr = pthread_create(&ThreadHandle[i], &ThreadAttr, MTFindPrimes, (void *)&ThreadParam[i]);
if(ThreadErr != 0){
printf("\\nThread Creation Error %d. Exiting abruptly... \\n",ThreadErr);
exit(1);
}
}
for(i=0; i<NumThreads; i++){
pthread_join(ThreadHandle[i], 0);
}
printf("FINISHED EXECUTION\\n");
pthread_attr_destroy(&ThreadAttr);
pthread_mutex_destroy(&lock);
}
}
stop = clock();
timer = ((double)(stop - start))/((double) CLOCKS_PER_SEC);
printf("\\n timer = %f\\n", timer);
if (NumThreads >= 1){
NumberOfPrimes = 0;
for (i = 0; i < size; i++){
if (Primes[i] != 0){
fprintf(ft,"%d: %llu\\n",PrimesIndex[i] + 1, Primes[i]);
NumberOfPrimes++;
}
}
printf("NumberOfPrimes = %d\\n", NumberOfPrimes);
}
fclose(ft);
return (0);
}
| 0
|
#include <pthread.h>
enum Colour
{
blue = 0,
red = 1,
yellow = 2,
Invalid = 3
};
const char* ColourName[] = {"blue", "red", "yellow"};
const int STACK_SIZE = 32*1024;
const BOOL TRUE = 1;
const BOOL FALSE = 0;
int CreatureID = 0;
enum Colour doCompliment(enum Colour c1, enum Colour c2)
{
switch (c1)
{
case blue:
switch (c2)
{
case blue:
return blue;
case red:
return yellow;
case yellow:
return red;
default:
goto errlb;
}
case red:
switch (c2)
{
case blue:
return yellow;
case red:
return red;
case yellow:
return blue;
default:
goto errlb;
}
case yellow:
switch (c2)
{
case blue:
return red;
case red:
return blue;
case yellow:
return yellow;
default:
goto errlb;
}
default:
break;
}
errlb:
printf("Invalid colour\\n");
exit( 1 );
}
char* formatNumber(int n, char* outbuf)
{
int ochar = 0, ichar = 0;
int i;
char tmp[64];
const char* NUMBERS[] =
{
"zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine"
};
ichar = sprintf(tmp, "%d", n);
for (i = 0; i < ichar; i++)
ochar += sprintf( outbuf + ochar, " %s", NUMBERS[ tmp[i] - '0' ] );
return outbuf;
}
struct MeetingPlace
{
pthread_mutex_t mutex;
int meetingsLeft;
struct Creature* firstCreature;
};
struct Creature
{
pthread_t ht;
pthread_attr_t stack_att;
struct MeetingPlace* place;
int count;
int sameCount;
enum Colour colour;
int id;
BOOL two_met;
BOOL sameid;
};
void MeetingPlace_Init(struct MeetingPlace* m, int meetings )
{
pthread_mutex_init( &m->mutex, 0 );
m->meetingsLeft = meetings;
m->firstCreature = 0;
}
BOOL Meet( struct Creature* cr)
{
BOOL retval = TRUE;
struct MeetingPlace* mp = cr->place;
pthread_mutex_lock( &(mp->mutex) );
if ( mp->meetingsLeft > 0 )
{
if ( mp->firstCreature == 0 )
{
cr->two_met = FALSE;
mp->firstCreature = cr;
}
else
{
struct Creature* first;
enum Colour newColour;
first = mp->firstCreature;
newColour = doCompliment( cr->colour, first->colour );
cr->sameid = cr->id == first->id;
cr->colour = newColour;
cr->two_met = TRUE;
first->sameid = cr->sameid;
first->colour = newColour;
first->two_met = TRUE;
mp->firstCreature = 0;
mp->meetingsLeft--;
}
}
else
retval = FALSE;
pthread_mutex_unlock( &(mp->mutex) );
return retval;
}
void* CreatureThreadRun(void* param)
{
struct Creature* cr = (struct Creature*)param;
while (TRUE)
{
if ( Meet(cr) )
{
while (cr->two_met == FALSE)
sched_yield();
if (cr->sameid)
cr->sameCount++;
cr->count++;
}
else
break;
}
return 0;
}
void Creature_Init( struct Creature *cr, struct MeetingPlace* place, enum Colour colour )
{
cr->place = place;
cr->count = cr->sameCount = 0;
cr->id = ++CreatureID;
cr->colour = colour;
cr->two_met = FALSE;
pthread_attr_init( &cr->stack_att );
pthread_attr_setstacksize( &cr->stack_att, STACK_SIZE );
pthread_create( &cr->ht, &cr->stack_att, &CreatureThreadRun, (void*)(cr) );
}
char* Creature_getResult(struct Creature* cr, char* str)
{
char numstr[256];
formatNumber(cr->sameCount, numstr);
sprintf( str, "%u%s", cr->count, numstr );
return str;
}
void runGame( int n_meeting, int ncolor, const enum Colour* colours )
{
int i;
int total = 0;
char str[256];
struct MeetingPlace place;
struct Creature *creatures = (struct Creature*) calloc( ncolor, sizeof(struct Creature) );
MeetingPlace_Init( &place, n_meeting );
for (i = 0; i < ncolor; i++)
{
printf( "%s ", ColourName[ colours[i] ] );
Creature_Init( &(creatures[i]), &place, colours[i] );
}
printf("\\n");
for (i = 0; i < ncolor; i++)
pthread_join( creatures[i].ht, 0 );
for (i = 0; i < ncolor; i++)
{
printf( "%s\\n", Creature_getResult(&(creatures[i]), str) );
total += creatures[i].count;
}
printf( "%s\\n\\n", formatNumber(total, str) );
pthread_mutex_destroy( &place.mutex );
free( creatures );
}
void printColours( enum Colour c1, enum Colour c2 )
{
printf( "%s + %s -> %s\\n",
ColourName[c1],
ColourName[c2],
ColourName[doCompliment(c1, c2)] );
}
void printColoursTable(void)
{
printColours(blue, blue);
printColours(blue, red);
printColours(blue, yellow);
printColours(red, blue);
printColours(red, red);
printColours(red, yellow);
printColours(yellow, blue);
printColours(yellow, red);
printColours(yellow, yellow);
}
int main(int argc, char** argv)
{
int n = (argc == 2) ? atoi(argv[1]) : 600;
printColoursTable();
printf("\\n");
const enum Colour r1[] = { blue, red, yellow };
const enum Colour r2[] = { blue, red, yellow,
red, yellow, blue,
red, yellow, red, blue };
runGame( n, sizeof(r1) / sizeof(r1[0]), r1 );
runGame( n, sizeof(r2) / sizeof(r2[0]), r2 );
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t cm_debug_file_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t cm_notice_file_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t cm_warn_file_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t cm_error_file_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t cm_output_file_mutex = PTHREAD_MUTEX_INITIALIZER;
void cm_request_mutex(pthread_mutex_t* p_mutex) {
if (OPEN_LOCK ) {
pthread_mutex_lock(p_mutex);
}
}
void cm_release_mutex(pthread_mutex_t* p_mutex) {
if (OPEN_LOCK) {
pthread_mutex_unlock(p_mutex);
}
}
void CM_DEBUG(int switch_id, const char* buffer) {
FILE * fp;
if (!OPEN_DEBUG) {
return;
}
cm_request_mutex(&cm_debug_file_mutex);
char fname[100];
get_switch_output_file(switch_id, DEBUG_ID, fname, 100);
fp = fopen(fname, "a+");
if (fp == 0) {
printf("open file failed");
cm_release_mutex(&cm_debug_file_mutex);
return;
}
fputs(buffer, fp);
fputc('\\n', fp);
fflush(fp);
fclose(fp);
cm_release_mutex(&cm_debug_file_mutex);
}
void CM_NOTICE(int switch_id, const char* buffer) {
FILE * fp;
if (!OPEN_NOTICE) {
return;
}
cm_request_mutex(&cm_notice_file_mutex);
char fname[100];
get_switch_output_file(switch_id, NOTICE_ID, fname, 100);
fp = fopen(fname, "a+");
if (fp == 0) {
printf("open file failed");
cm_release_mutex(&cm_notice_file_mutex);
return;
}
fputs(buffer, fp);
fputc('\\n', fp);
fflush(fp);
fclose(fp);
cm_release_mutex(&cm_notice_file_mutex);
}
void CM_WARNING(int switch_id, const char* buffer) {
FILE * fp;
if (!OPEN_WARNING) {
return;
}
cm_request_mutex(&cm_warn_file_mutex);
char fname[100];
get_switch_output_file(switch_id, WARNING_ID, fname, 100);
fp = fopen(fname, "a+");
if (fp == 0) {
printf("open file failed");
cm_release_mutex(&cm_warn_file_mutex);
return;
}
fputs(buffer, fp);
fputc('\\n', fp);
fflush(fp);
fclose(fp);
cm_release_mutex(&cm_warn_file_mutex);
}
void CM_ERROR(int switch_id, const char* buffer) {
FILE * fp;
if (!OPEN_ERROR) {
return;
}
cm_request_mutex(&cm_error_file_mutex);
char fname[100];
get_switch_output_file(switch_id, ERROR_ID, fname, 100);
fp = fopen(fname, "a+");
if (fp == 0) {
printf("open file failed");
cm_release_mutex(&cm_error_file_mutex);
return;
}
fputs(buffer, fp);
fputc('\\n', fp);
fflush(fp);
fclose(fp);
cm_release_mutex(&cm_error_file_mutex);
}
void CM_OUTPUT(int switch_id, const char* buffer) {
FILE * fp;
if (!OPEN_OUTPUT) {
return;
}
cm_request_mutex(&cm_output_file_mutex);
char fname[100];
get_switch_output_file(switch_id, OUTPUT_ID, fname, 100);
fp = fopen(fname, "a+");
if (fp == 0) {
printf("open file failed");
cm_release_mutex(&cm_output_file_mutex);
return;
}
fputs(buffer, fp);
fputc('\\n', fp);
fflush(fp);
fclose(fp);
cm_release_mutex(&cm_output_file_mutex);
}
void get_switch_output_file(int switch_id, int level, char* fname, int fname_len) {
if (level == DEBUG_ID) {
snprintf(fname, fname_len, "%ss%d.debug", CM_RECEIVER_TARGET_FLOW_FNAME_PREFIX, switch_id+1);
} else if (level == ERROR_ID) {
snprintf(fname, fname_len, "%ss%d.error", CM_RECEIVER_TARGET_FLOW_FNAME_PREFIX, switch_id+1);
} else if (level == WARNING_ID) {
snprintf(fname, fname_len, "%ss%d.warning", CM_RECEIVER_TARGET_FLOW_FNAME_PREFIX, switch_id+1);
} else if (level == NOTICE_ID) {
snprintf(fname, fname_len, "%ss%d.notice", CM_RECEIVER_TARGET_FLOW_FNAME_PREFIX, switch_id+1);
} else if (level == OUTPUT_ID) {
snprintf(fname, fname_len, "%ss%d.result", CM_RECEIVER_TARGET_FLOW_FNAME_PREFIX, switch_id+1);
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int pepsi = 0;
int counter = 0;
void * produce(){
while(pepsi < 50 && counter == 0){
pthread_mutex_lock(&mutex1);
counter++;
pthread_mutex_unlock(&mutex1);
printf("Producer has produced 1\\n");
pepsi++;
}
pthread_exit(0);
return 0;
}
void * consume(){
while(pepsi < 50 && counter > 0){
pthread_mutex_lock(&mutex1);
counter--;
pthread_mutex_unlock(&mutex1);
printf("Consumer has consume 1\\n");
}
return 0;
}
int main(){
pthread_t producer, consumers[10];
pthread_create(&producer, 0, produce, 0);
for(int i = 0; i < 10; i++){
pthread_create(&consumers[i], 0, consume, 0);
sleep(2);
}
pthread_join(producer, 0);
for(int i = 0; i < 10; i++)
pthread_join(consumers[i], 0);
return 0;
}
| 1
|
#include <pthread.h>
void parse_url(char *url, struct request *req)
{
char *s;
int i, j, k;
int temp;
i = j = k = 0;
s = url;
printf("%s\\n", s);
if ((strncmp(url, "ftp://", 6)) == 0) {
fprintf(stderr, "Error: Currently Aget doesn't support FTP requests...\\n");
exit(1);
} else
if ((strncmp(url, "http://", 7)) != 0) {
fprintf(stderr, "Error: URL should be of the form http://...\\n");
exit(1);
}
if (req->port == 0) {
req->port = 80;
req->proto = PROTO_HTTP;
}
pthread_mutex_lock(&assertM);
temp = assert1;
assert1++;
pthread_mutex_unlock(&assertM);
s = url + 7;
for (i = 0; *s != '/'; i++, s++) {
if (i > MAXHOSTSIZ) {
fprintf(stderr, "Error: Cannot get hostname from URL...\\n");
exit(1);
}
if (*s == ':') {
while(*s != '/') {
req->username[j++] = *--s;
i--;
}
req->username[--j] = '\\0';
revstr(req->username);
while(1) {
if (*s == ':') {
while(*s != '@') {
if (k > MAXBUFSIZ) {
fprintf(stderr, "Error: Cannot get password from URL...\\n");
exit(1);
}
req->password[k++] = *++s;
}
break;
}
s++;
}
req->password[--k] = '\\0';
}
req->host[i] = *s;
}
req->host[i] = '\\0';
for (i = 0; *s != '\\0'; i++, s++) {
if (i > MAXURLSIZ) {
fprintf(stderr, "Error: Cannot get remote file name from URL...\\n");
exit(1);
}
req->url[i] = *s;
}
req->url[i] = '\\0';
--s;
for (i = 0; *s != '/'; i++, s--) {
if (i > MAXBUFSIZ) {
fprintf(stderr, "Error: Cannot get local file name from URL...\\n");
exit(1);
}
req->file[i] = *s;
}
req->file[i] = '\\0';
revstr(req->file);
}
int numofthreads(int size)
{
if (size == 0)
return 0;
else if (size < 1024 * 2)
return 1;
else if ((size >= 1024 * 2) && (size < 1024 * 4))
return 2;
else if ((size >= 1024 * 4) && (size < 1024 * 8))
return 3;
else if ((size >= 1024 * 8) && (size < 1024 * 16))
return 4;
else if ((size >= 1024 * 16) && (size < 1024 * 32))
return 5;
else if ((size >= 1024 * 32) && (size < 1024 * 64))
return 6;
else if ((size >= 1024 * 64) && (size < 1024 * 128))
return 7;
else if ((size >= 1024 * 128) && (size < 1024 * 256))
return 8;
else if ((size >= 1024 * 256) && (size < 1024 * 512))
return 9;
else
return 10;
}
int calc_offset(long long total, int part, int nthreads)
{
return (part * (total / nthreads));
}
void usage()
{
fprintf(stderr, "usage: aget [options] url\\n");
fprintf(stderr, "\\toptions:\\n");
fprintf(stderr, "\\t\\t-p port number\\n");
fprintf(stderr, "\\t\\t-l local file name\\n");
fprintf(stderr, "\\t\\t-n suggested number of threads\\n");
fprintf(stderr, "\\t\\t-f force using suggested number of threads\\n");
fprintf(stderr, "\\t\\t-h this screen\\n");
fprintf(stderr, "\\t\\t-v version info\\n");
fprintf(stderr, "\\n");
fprintf(stderr, "http//www.enderunix.org/aget/\\n");
}
void revstr(char *str)
{
char *p, *s;
int i;
int size;
if ((size = strlen(str)) == 0)
return;
printf("size : %d\\n", size);
p = (char *)calloc(size+1, sizeof(char));
s = p;
for (i = size; i > 0; i--, s++) {
*s = *(str + i - 1);
printf("%c\\n", *s);
}
*s = '\\0';
memset(str, 0, size);
strncpy(str, p, size);
free(p);
}
void Log(char *fmt, ...)
{
va_list ap;
char *lfmt;
lfmt = (char *)calloc(7 + strlen(fmt), sizeof(char));
sprintf(lfmt, "<LOG> %s", fmt);
fflush(stdout);
__builtin_va_start((ap));
vfprintf(stderr, lfmt, ap);
;
if (fmt[0] != '\\0' && fmt[strlen(fmt) - 1] == ':')
fprintf(stderr, " %s", strerror(errno));
fprintf(stderr, "\\n");
free(lfmt);
}
void updateProgressBar(float cur, float tot)
{
float rat;
int ndot, i;
static float prev = -1;
rat = cur/tot;
ndot = (int)(rat * 100);
if ((ndot < prev + 5) && (ndot != 100))
return;
for (i = 0; i < ndot; i += 2)
putchar('.');
for (i = ndot - 1; i < 100; i += 2)
putchar(' ');
printf("[%d%% completed]\\n", ndot);
prev = ndot;
}
void handleHttpRetcode(char *rbuf)
{
if ((strstr(rbuf, "HTTP/1.1 416")) != 0) {
Log("Server returned HTTP/1.1 416 - Requested Range Not Satisfiable\\n");
exit(1);
} else
if ((strstr(rbuf, "HTTP/1.1 403")) != 0) {
Log("<Server returned HTTP/1.1 403 - Permission Denied\\n");
exit(1);
} else
if ((strstr(rbuf, "HTTP/1.1 404")) != 0) {
Log("<Server returned HTTP/1.1 404 - File Not Found\\n");
exit(1);
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t m;
pthread_cond_t cond_reset=PTHREAD_COND_INITIALIZER;
int x=0;
void * writer(void* arg){
int numWriter = *(int*) arg;
while(1){
pthread_mutex_lock(&m);
printf(" incr%d: before x=%d\\n",numWriter,x);
x+=1;
printf(" after x=%d\\n",x);
pthread_mutex_unlock(&m);
sleep(rand()%3);
pthread_cond_signal(&cond_reset);
}
}
void * controleur(void* arg){
while(1){
pthread_mutex_lock(&m);
while(x<5)
pthread_cond_wait(&cond_reset,&m);
printf(" reset: before x=%d\\n",x);
x=0;
printf(" after x=%d\\n",x);
pthread_mutex_unlock(&m);
}
}
int main(void){
pthread_t writ[5];
pthread_t control[2];
int i,numWriter;
for(i=0;i<2;i++)
pthread_create(&control[i],0,controleur,0);
for(i=0;i<5;i++){
numWriter = i+1;
pthread_create(&writ[i],0,writer,(void*) &numWriter);
}
while(1){
sleep(10);
}
}
| 1
|
#include <pthread.h>
int count = 1;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
void *threadStep (void *a) {
while (count < 1000000) {
pthread_mutex_lock (&m);
count++;
pthread_mutex_unlock (&m);
}
}
void *threadPrgs (void *a) {
int p, i;
while (count < 1000000) {
pthread_mutex_lock (&m);
p = count / 1000000;
for (i = 0; i < 10; i++)
printf ("%c", i <= p?'x':' ');
pthread_mutex_unlock (&m);
printf (" . ");
}
}
int main () {
pthread_t tid1, tid2;
pthread_mutex_init (&m, 0);
if (pthread_create (&tid1, 0, threadStep, 0)) {
printf ("\\nDeu bosta na thread 1, filhão\\n");
return 1;
}
if (pthread_create (&tid2, 0, threadPrgs, 0)) {
printf ("\\nA thread 2 cagou, fera\\n");
return 1;
}
if (pthread_join (tid1, 0)) {
printf ("\\nFera, deu merda no join com a 1\\n");
return 1;
}
if (pthread_join (tid2, 0)) {
printf ("\\nBah, fodeu tudo aqui no join da 2\\n");
return 1;
}
pthread_mutex_destroy (&m);
pthread_exit (0);
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t randLock;
static unsigned int randSeed;
void randInit() {
randSeed = (unsigned int) time(0);
pthread_mutex_init(&randLock, 0);
}
int nextRand() {
pthread_mutex_lock(&randLock);
int val = rand_r(&randSeed);
pthread_mutex_unlock(&randLock);
return val;
}
void assertTrue(int value, char* errorString) {
if(!value) {
fprintf(stderr, "%s\\n", errorString);
exit(-1);
}
}
int safeConvert(char* str, char* errorString) {
if(str[0] == '0' && str[1] == '\\0') {
return 0;
}
int num = atoi(str);
assertTrue(num, errorString);
return num;
}
| 1
|
#include <pthread.h>
unsigned long fh;
uint64_t readpos;
uint32_t refcount;
struct _fhentry *next;
} fhentry;
static unsigned long nextfh=1;
static fhentry *fhhead=0;
static uint8_t opbuff[0x1000000];
static uint64_t writepos=0;
static uint8_t waiting=0;
static pthread_mutex_t opbufflock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t nodata = PTHREAD_COND_INITIALIZER;
static time_t convts=0;
static struct tm convtm;
static pthread_mutex_t timelock = PTHREAD_MUTEX_INITIALIZER;
static inline void oplog_put(uint8_t *buff,uint32_t leng) {
uint32_t bpos;
if (leng>0x1000000) {
buff+=leng-0x1000000;
leng=0x1000000;
}
pthread_mutex_lock(&opbufflock);
bpos = writepos%0x1000000;
writepos+=leng;
if (bpos+leng>0x1000000) {
memcpy(opbuff+bpos,buff,0x1000000 -bpos);
buff+=0x1000000 -bpos;
leng-=0x1000000 -bpos;
bpos = 0;
}
memcpy(opbuff+bpos,buff,leng);
if (waiting) {
pthread_cond_broadcast(&nodata);
waiting=0;
}
pthread_mutex_unlock(&opbufflock);
}
void oplog_printf(const struct fuse_ctx *ctx,const char *format,...) {
va_list ap;
static char buff[1000];
uint32_t leng;
struct timeval tv;
struct tm ltime;
pthread_mutex_lock(&timelock);
gettimeofday(&tv,0);
if (convts/900!=tv.tv_sec/900) {
convts=tv.tv_sec/900;
convts*=900;
localtime_r(&convts,&convtm);
}
ltime = convtm;
leng = tv.tv_sec - convts;
ltime.tm_sec += leng%60;
ltime.tm_min += leng/60;
pthread_mutex_unlock(&timelock);
leng = snprintf(buff,1000,"%02u.%02u %02u:%02u:%02u.%06u: uid:%u gid:%u pid:%u cmd:",ltime.tm_mon+1,ltime.tm_mday,ltime.tm_hour,ltime.tm_min,ltime.tm_sec,(unsigned)tv.tv_usec,ctx->uid,ctx->gid,ctx->pid);
if (leng<1000) {
__builtin_va_start((ap));
leng += vsnprintf(buff+leng,1000 -leng,format,ap);
;
}
if (leng>=1000) {
leng=1000 -1;
}
buff[leng++]='\\n';
oplog_put((uint8_t*)buff,leng);
}
unsigned long oplog_newhandle(int hflag) {
fhentry *fhptr;
uint32_t bpos;
pthread_mutex_lock(&opbufflock);
fhptr = malloc(sizeof(fhentry));
fhptr->fh = nextfh++;
fhptr->refcount = 1;
if (hflag) {
if (writepos<0xF00000) {
fhptr->readpos = 0;
} else {
fhptr->readpos = writepos - 0xF00000;
bpos = fhptr->readpos%0x1000000;
while (fhptr->readpos < writepos) {
if (opbuff[bpos]=='\\n') {
break;
}
bpos++;
bpos%=0x1000000;
fhptr->readpos++;
}
if (fhptr->readpos<writepos) {
fhptr->readpos++;
}
}
} else {
fhptr->readpos = writepos;
}
fhptr->next = fhhead;
fhhead = fhptr;
pthread_mutex_unlock(&opbufflock);
return fhptr->fh;
}
void oplog_releasehandle(unsigned long fh) {
fhentry **fhpptr,*fhptr;
pthread_mutex_lock(&opbufflock);
fhpptr = &fhhead;
while ((fhptr = *fhpptr)) {
if (fhptr->fh==fh) {
fhptr->refcount--;
if (fhptr->refcount==0) {
*fhpptr = fhptr->next;
free(fhptr);
} else {
fhpptr = &(fhptr->next);
}
} else {
fhpptr = &(fhptr->next);
}
}
pthread_mutex_unlock(&opbufflock);
}
void oplog_getdata(unsigned long fh,uint8_t **buff,uint32_t *leng,uint32_t maxleng) {
fhentry *fhptr;
uint32_t bpos;
struct timeval tv;
struct timespec ts;
pthread_mutex_lock(&opbufflock);
for (fhptr=fhhead ; fhptr && fhptr->fh != fh ; fhptr=fhptr->next ) {
}
if (fhptr==0) {
*buff = 0;
*leng = 0;
return;
}
fhptr->refcount++;
while (fhptr->readpos>=writepos) {
gettimeofday(&tv,0);
ts.tv_sec = tv.tv_sec+1;
ts.tv_nsec = tv.tv_usec*1000;
waiting=1;
if (pthread_cond_timedwait(&nodata,&opbufflock,&ts)==ETIMEDOUT) {
*leng = 2;
return;
}
}
bpos = fhptr->readpos%0x1000000;
*leng = (writepos-(fhptr->readpos));
*buff = opbuff+bpos;
if ((*leng)>(0x1000000 -bpos)) {
(*leng) = (0x1000000 -bpos);
}
if ((*leng)>maxleng) {
(*leng) = maxleng;
}
fhptr->readpos+=(*leng);
}
void oplog_releasedata(unsigned long fh) {
fhentry **fhpptr,*fhptr;
fhpptr = &fhhead;
while ((fhptr = *fhpptr)) {
if (fhptr->fh==fh) {
fhptr->refcount--;
if (fhptr->refcount==0) {
*fhpptr = fhptr->next;
free(fhptr);
} else {
fhpptr = &(fhptr->next);
}
} else {
fhpptr = &(fhptr->next);
}
}
pthread_mutex_unlock(&opbufflock);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex_pi;
double pi;
struct thread_data_st
{
int st_my_rank;
int st_n;
double st_my_pi;
};
struct thread_data_st thread_data_st_array[8];
void *calc_pi_routine(void *routine_data)
{
int n, my_rank, i;
double x, h, sum;
struct thread_data_st *r_data;
r_data = (struct thread_data_st *) routine_data;
n = r_data->st_n;
my_rank = r_data->st_my_rank;
h = 1.0 / (double)n;
sum = 0.0;
for (i = my_rank + 1; i <= n; i += 8)
{
x = h * ((double)i - 0.5);
sum += 4.0 / (1.0 + x * x);
}
r_data->st_my_pi = h * sum;
pthread_mutex_lock(&mutex_pi);
pi += r_data->st_my_pi;
pthread_mutex_unlock(&mutex_pi);
}
int main(int argc, char **argv)
{
int i, j, n;
pthread_t threads[8];
printf("Enter the number of intervals: \\n");
scanf("%d", &n);
for(i = 0; i < 8; i++)
{
thread_data_st_array[i].st_my_rank = i;
thread_data_st_array[i].st_n = n;
pthread_create(&threads[i], 0, calc_pi_routine, (void *)&thread_data_st_array[i]);
}
for (j=0; j < 8; j++)
{
pthread_join(threads[j], 0);
}
printf("PI is approximately %20.16f\\n", pi);
}
| 1
|
#include <pthread.h>
void memory_data_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);
mdr = mem_data;
pthread_barrier_wait(&update_registers);
}
}
| 0
|
#include <pthread.h>
struct msg {
struct msg *next;
int num;
};
struct msg *head;
pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void *consumer(void *p)
{
struct msg *mp;
for (;;) {
pthread_mutex_lock(&lock);
while (head == 0)
pthread_cond_wait(&has_product, &lock);
mp = head;
head = mp->next;
pthread_mutex_unlock(&lock);
printf("Consume %d\\n", mp->num);
free(mp);
sleep(rand() % 5);
}
}
void *producer(void *p)
{
struct msg *mp;
for (;;) {
mp = malloc(sizeof(struct msg));
mp->num = rand() % 1000 + 1;
printf("Produce %d\\n", mp->num);
pthread_mutex_lock(&lock);
mp->next = head;
head = mp;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&has_product);
sleep(rand() % 5);
}
}
int main(int argc, char *argv[])
{
pthread_t pid, cid;
srand(time(0));
pthread_create(&pid, 0, producer, 0);
pthread_create(&cid, 0, consumer, 0);
pthread_join(pid, 0);
pthread_join(cid, 0);
return 0;
}
| 1
|
#include <pthread.h>
struct spmc_moal_t {
pthread_mutex_t moal;
void **data;
uintptr_t len;
uintptr_t max;
};
struct spmc_moal_t *spmc_moal_init(uintptr_t max) {
struct spmc_moal_t *q = (struct spmc_moal_t*)malloc(sizeof(struct spmc_moal_t));
if (q == 0) {
return 0;
}
pthread_mutex_init(&q->moal, 0);
q->data = (void**) malloc(sizeof(void*) * max);
q->len = 0;
q->max = max;
return q;
}
void spmc_moal_destroy(struct spmc_moal_t *q) {
pthread_mutex_destroy(&q->moal);
free(q->data);
}
void *spmc_moal_dequeue(struct spmc_moal_t *q) {
pthread_mutex_lock(&q->moal);
if (q->len == 0) {
pthread_mutex_unlock(&q->moal);
return 0;
}
void *item = q->data[q->len - 1];
q->len -= 1;
pthread_mutex_unlock(&q->moal);
return item;
}
bool spmc_moal_enqueue(struct spmc_moal_t *q, void *item) {
pthread_mutex_lock(&q->moal);
if (q->len == q->max) {
pthread_mutex_unlock(&q->moal);
return 0;
}
q->data[q->len] = item;
q->len += 1;
pthread_mutex_unlock(&q->moal);
return 1;
}
| 0
|
#include <pthread.h>
struct jc_type_file_seq_cwlv {
struct jc_type_file_comm_hash *comm_hash;
};
static struct jc_type_file_seq_cwlv global_cwlv;
static int
jc_type_file_seq_cwlv_init(
struct jc_comm *jcc
)
{
return global_cwlv.comm_hash->init(global_cwlv.comm_hash, jcc);
}
static int
jc_type_file_seq_cwlv_execute(
struct jc_comm *jcc
)
{
return global_cwlv.comm_hash->execute(global_cwlv.comm_hash, jcc);
}
static int
jc_type_file_seq_cwlv_copy(
unsigned int data_num
)
{
return global_cwlv.comm_hash->copy(global_cwlv.comm_hash, data_num);
}
static int
jc_type_file_seq_cwlv_comm_init(
struct jc_type_file_comm_node *fsn
)
{
return JC_OK;
}
static char*
jc_type_file_seq_cwlv_comm_execute(
char separate,
struct jc_type_file_comm_node *fsn,
struct jc_type_file_comm_var_node *svar
)
{
if (svar->last_val)
free(svar->last_val);
pthread_mutex_lock(&svar->mutex);
svar->last_val = jc_file_val_get(fsn->col_num, 0,
separate, svar->cur_ptr,
&svar->cur_ptr);
pthread_mutex_unlock(&svar->mutex);
if (!svar->last_val)
fprintf(stderr, "no more data in line %d, col %d",
fsn->col_num, svar->line_num);
return svar->last_val;
}
static int
jc_type_file_seq_cwlv_comm_copy(
struct jc_type_file_comm_node *fsn,
struct jc_type_file_comm_var_node *svar
)
{
return JC_OK;
}
static int
jc_type_file_seq_cwlv_comm_destroy(
struct jc_type_file_comm_node *fsn
)
{
return JC_OK;
}
static int
jc_type_file_seq_cwlv_comm_var_destroy(
struct jc_type_file_comm_var_node *svar
)
{
return JC_OK;
}
int
json_config_type_file_seq_cwlv_init()
{
struct jc_type_file_manage_oper oper;
struct jc_type_file_comm_hash_oper comm_oper;
memset(&comm_oper, 0, sizeof(comm_oper));
comm_oper.comm_hash_copy = jc_type_file_seq_cwlv_comm_copy;
comm_oper.comm_hash_init = jc_type_file_seq_cwlv_comm_init;
comm_oper.comm_hash_execute = jc_type_file_seq_cwlv_comm_execute;
comm_oper.comm_node_destroy = jc_type_file_seq_cwlv_comm_destroy;
comm_oper.comm_var_node_destroy = jc_type_file_seq_cwlv_comm_var_destroy;
global_cwlv.comm_hash = jc_type_file_comm_create(
0,
0,
&comm_oper);
if (!global_cwlv.comm_hash)
return JC_ERR;
memset(&oper, 0, sizeof(oper));
oper.manage_execute = jc_type_file_seq_cwlv_execute;
oper.manage_init = jc_type_file_seq_cwlv_init;
oper.manage_copy = jc_type_file_seq_cwlv_copy;
return jc_type_file_seq_module_add("sequence_continue_with_last_value",&oper);
}
int
json_config_type_file_seq_cwlv_uninit()
{
if (global_cwlv.comm_hash)
jc_type_file_comm_destroy(global_cwlv.comm_hash);
return JC_OK;
}
| 1
|
#include <pthread.h>
struct WaitGroup {
int count;
pthread_cond_t cnd;
pthread_mutex_t mtx;
};
int Wait(struct WaitGroup * wp) {
if(0 == wp) {
return EINVAL;
}
pthread_mutex_lock(&wp -> mtx);
while(wp -> count > 0) {
pthread_cond_wait(&wp -> cnd, &wp -> mtx);
}
pthread_mutex_unlock(&wp -> mtx);
return 0;
}
int Add(struct WaitGroup * wp, int n) {
if(0 == wp) {
return EINVAL;
}
pthread_mutex_lock(&wp -> mtx);
wp -> count += n;
pthread_mutex_unlock(&wp -> mtx);
pthread_cond_broadcast(&wp -> cnd);
return 0;
}
int Done(struct WaitGroup * wp) {
return Add(wp, -1);
}
void * start_thread(void *arg) {
if(0 == arg) {
xdebug("arg is NULL");
return 0;
}
xdebug("aha~");
struct WaitGroup * wp = (struct WaitGroup*)arg;
sleep(pthread_self() % 3);
xdebug("aha done ~");
Done(wp);
return 0;
}
int main(int argc, char * argv[]) {
struct WaitGroup wp = {0, PTHREAD_COND_INITIALIZER, PTHREAD_MUTEX_INITIALIZER};
int n = 5;
int i = 0;
for(i = 0; i < n; i++) {
pthread_t pt;
if(0 != pthread_create(&pt, 0, start_thread, &wp)) {
xdebug("create thread faild");
} else {
Add(&wp, 1);
}
}
Wait(&wp);
xdebug("main over");
return 0;
}
| 0
|
#include <pthread.h>
double max;
double min;
double average;
double total;
double num;
double input_start[5];
double* input_end = input_start;
int quit;
pthread_mutex_t lock1;
void calculate(double f){
if (f > max){
max = f;
}
if (f < min){
min = f;
}
total = f + total;
num++;
}
void store_input(double f){
for (int i = 3; i >= 0; i--){
input_start[i + 1] = input_start[i];
}
input_start[0] = f;
}
void* func1(void* p){
char input[256];
scanf("%s", input);
double f;
if (strcmp(input, "0")!= 0) {
if (strcmp(input, "q") == 0){
pthread_mutex_lock(&lock1);
quit = 0;
pthread_mutex_unlock(&lock1);
pthread_exit(0);
}
f = atof(input);
if (f != 0) {
pthread_mutex_lock(&lock1);
max = f;
min = f;
total = f + total;
num++;
store_input(f);
pthread_mutex_unlock(&lock1);
}
}
else{
pthread_mutex_lock(&lock1);
calculate(0);
store_input(0);
pthread_mutex_unlock(&lock1);
}
do{
scanf("%s", input);
double f;
if (strcmp(input, "0")!= 0) {
if (strcmp(input, "q") == 0){
pthread_mutex_lock(&lock1);
quit = 0;
pthread_mutex_unlock(&lock1);
pthread_exit(0);
}
f = atof(input);
if (f != 0) {
pthread_mutex_lock(&lock1);
calculate(f);
store_input(f);
pthread_mutex_unlock(&lock1);
}
}
else{
pthread_mutex_lock(&lock1);
calculate(0);
store_input(0);
pthread_mutex_unlock(&lock1);
}
} while(1);
return p;
}
int main(){
quit = 1;
total = 0;
num = 0;
pthread_t t1;
pthread_mutex_init(&lock1, 0);
pthread_create(&t1, 0, &func1, 0);
do {
pthread_mutex_lock(&lock1);
if (quit == 0) {
pthread_mutex_unlock(&lock1);
break;
}
pthread_mutex_unlock(&lock1);
sleep(10);
pthread_mutex_lock(&lock1);
if (num != 0) {
average = total / num;
pthread_mutex_unlock(&lock1);
}
else {
average = 0;
pthread_mutex_unlock(&lock1);
}
printf("\\nmax = %f\\nmin = %f\\naverage = %f\\n", max, min, average);
for (int j = 0; j < 5; j++){
printf("%f\\n", input_start[j]);
}
printf("\\n");
} while(1);
pthread_join(t1, 0);
return 1;
}
| 1
|
#include <pthread.h>
char family_type[20];
char name[20];
int enter_time;
int exit_time;
};
static sem_t mysem;
static pthread_mutex_t capuletlock;
static pthread_mutex_t montaguelock;
static int num_capulets=0;
static int num_montagues=0;
void *gang_member(void *args)
{
struct person *myargs;
myargs=(struct person *)args;
if(myargs->enter_time==0)
{
printf("%s %s arrives at time %i \\n", myargs->family_type, myargs->name, myargs->enter_time);
}
else
{
sleep(myargs->enter_time);
printf("%s %s arrives at time %i \\n", myargs->family_type, myargs->name, myargs->enter_time);
}
if(strcmp(myargs->family_type,"Capulet")==0 )
{
pthread_mutex_lock(&capuletlock);
num_capulets += 1;
printf("%s %s enters the plaza.\\n", myargs->family_type, myargs->name);
if(num_capulets==1)
{
sem_wait(&mysem);
}
pthread_mutex_unlock(&capuletlock);
sleep(myargs->exit_time);
pthread_mutex_lock(&capuletlock);
num_capulets -= 1;
if(num_capulets==0)
{
sem_post(&mysem);
}
printf("%s %s leaves the plaza. \\n",myargs->family_type, myargs->name);
pthread_mutex_unlock(&capuletlock);
}
if (strcmp(myargs->family_type,"Montague")==0)
{
pthread_mutex_lock(&montaguelock);
num_montagues+= 1;
if(num_montagues==1)
{
sem_wait(&mysem);
}
printf("%s %s enters the plaza.\\n", myargs->family_type, myargs->name);
pthread_mutex_unlock(&montaguelock);
sleep(myargs->exit_time);
pthread_mutex_lock(&montaguelock);
num_montagues-= 1;
if(num_montagues==0)
{
sem_post(&mysem);
}
printf("%s %s leaves the plaza.\\n", myargs->family_type, myargs->name);
pthread_mutex_unlock(&montaguelock);
}
}
int main()
{
int i;
int pid=1;
struct person parray[3];
pthread_t tid[3];
int number_people=0;
sem_init(&mysem, 0, 1);
pthread_mutex_init(&capuletlock, 0);
pthread_mutex_init(&montaguelock, 0);
printf("reading from file now...\\n");
while(fscanf(stdin,"%s %s %d %d",parray[i].family_type, parray[i].name,
&parray[i].enter_time, &parray[i].exit_time ) != EOF )
{
number_people++;
i++;
}
for(i=0;i<number_people;i++)
{
pid = pthread_create(&tid[i], 0, &gang_member,(void*) &parray[i]);
if(pid!=0)
{
perror("Cannot create the thread! \\n");
}
}
for (i = 0; i < number_people; i++)
{
pthread_join(tid[i], 0);
}
sem_destroy(&mysem);
return 0;
}
| 0
|
#include <pthread.h>
struct data
{
int *fullarr;
int fullsize;
int partsize;
};
int min = (10000 + 1);
pthread_mutex_t mutex;
struct data dataitem;
void *findmin(int *arg)
{
int i, j, start, end, len, mymin;
int *array;
i = arg;
len = dataitem.partsize;
start = i*len;
end = start + len;
array = dataitem.fullarr;
mymin = array[start];
for(j=start+1;j<end;j++)
{
if(array[j]<mymin)
{
mymin = array[j];
}
}
pthread_mutex_lock (&mutex);
if(min>mymin){
min = mymin;
}
pthread_mutex_unlock (&mutex);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
pthread_t *threads;
int i, j, numthreads, partialsize, min_nopthread;
int *arr;
pthread_attr_t attr;
void *status;
double time_start, time_end, diff;
struct timeval tv;
struct timezone tz;
if(argc!=3)
{
printf("Enter number of threads and size of array as arguments.\\n");
exit(1);
}
numthreads = atoi(argv[1]);
if(numthreads>8)
{
printf("Maximum number of threads is 8.\\n");
exit(1);
}
if(atoi(argv[2])%numthreads!=0)
{
printf("Number of threads should be factor of %d.\\n",atoi(argv[2]));
exit(1);
}
threads = (pthread_t *)malloc(numthreads*sizeof(pthread_t));
pthread_mutex_init(&mutex, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
arr = (int *)malloc(atoi(argv[2])*sizeof(int));
srand(time(0));
for(i=0;i<atoi(argv[2]);i++)
arr[i] = rand()%10000 + 1;
partialsize = atoi(argv[2])/numthreads;
dataitem.fullsize = atoi(argv[2]);
dataitem.fullarr = arr;
dataitem.partsize = partialsize;
gettimeofday(&tv, &tz);
time_start = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
for(i=0;i<numthreads;i++)
{
pthread_create(&threads[i], &attr, findmin, (void *)i);
}
pthread_attr_destroy(&attr);
for(i=0; i<numthreads; i++)
{
pthread_join(threads[i], &status);
}
gettimeofday(&tv, &tz);
time_end = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
printf ("Min = %d\\n", min);
printf("Time in Seconds (T) : %lf\\n", time_end - time_start);
min_nopthread = (10000 + 1);
gettimeofday(&tv, &tz);
time_start = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
for(i=0;i<atoi(argv[2]);i++)
{
if(min_nopthread>arr[i])
min_nopthread = arr[i];
}
gettimeofday(&tv, &tz);
time_end = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
printf("Min_nopthread = %d\\n",min_nopthread);
printf("Time in Seconds (T) : %lf\\n", time_end - time_start);
free(arr);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&mutex);
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
int s=0;
sem_t full,empty;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int q[5];
void *prod(void *count)
{
int* c = (int*)count;
long int i;
int j;
for(i=0;i<10;i++)
{
sem_wait(&full);
sem_getvalue(&full,&s);
printf("full= %d\\n", s);
pthread_mutex_lock(&mutex);
q[*c]=1;
(*c)++;
for(j=0;j<5;j++)
{
printf("%d ", q[j]);
}
printf("Producer, c = %d \\n" , *c);
sem_post(&empty);
pthread_mutex_unlock(&mutex);
}
return 0;
}
void *cons(void *count)
{
int* c = (int*)count;
long int i;
int j;
int k;
for(i=0;i<10;i++)
{
sem_wait(&empty);
sem_getvalue(&empty,&s);
printf("empty= %d\\n", s);
pthread_mutex_lock(&mutex);
(*c)--;
q[*c]=0;
for(j=0;j<5;j++)
{
printf("%d ", q[j]);
}
printf("Consumer, c = %d \\n" , *c);
sem_post(&full);
pthread_mutex_unlock(&mutex);
}
return 0;
}
int main()
{
int count = 0;
pthread_t producer;
pthread_t consumer;
sem_init(&full,0,5);
sem_init(&empty,0,0);
sem_getvalue(&full,&s);
printf("full= %d\\n", s);
pthread_create(&producer, 0, prod, &count);
pthread_create(&consumer, 0, cons, &count);
pthread_join(producer, 0);
pthread_join(consumer, 0);
printf("Value of count is = %d\\n", count);
for(int j=0;j<5;j++)
{
printf("%d ", q[j]);
}
exit(0);
}
| 0
|
#include <pthread.h>
struct skynetCore_t{
pthread_mutex_t protector;
pid_t pid;
};
int set_priority(int priority)
{
int policy;
struct sched_param param;
if (priority < 1 || priority > 63) return -1;
pthread_getschedparam(pthread_self(), &policy, ¶m);
param.sched_priority = priority;
return pthread_setschedparam(pthread_self(), policy, ¶m);
}
int get_priority()
{
int policy;
struct sched_param param;
pthread_getschedparam(pthread_self(), &policy, ¶m);
return param.sched_curpriority;
}
void nagger(void *arg){
set_priority(*(int*)arg);
int skynetDesc = shm_open("/skynetcore", O_RDWR, S_IRWXU);
struct skynetCore_t* skynetCore = mmap(0, sizeof(struct skynetCore_t), PROT_READ|PROT_WRITE, MAP_SHARED, skynetDesc, 0);
pthread_mutex_lock(&skynetCore->protector);
int corePid = skynetCore->pid;
pthread_mutex_unlock(&skynetCore->protector);
int message = *(int*)arg;
int skynetChannelId = ConnectAttach(0, corePid, 1, 0, 0);
MsgSend(skynetChannelId, &message, sizeof(int), &message, sizeof(int));
printf("I sent %i and got %i back!\\n", *(int*)arg, message);
ConnectDetach(skynetChannelId);
}
int main(int argc, char *argv[]) {
set_priority(6);
int i;
pthread_t naggers[4];
int ids[4] = { 1, 2, 4, 5 };
for (i = 0; i < 4; i++)
{
pthread_create(&naggers[i], 0, nagger, &ids[i]);
}
for (i = 0; i < 4; i++)
{
pthread_join(naggers[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
int ** bigMatrix[200];
int value;
pthread_mutex_t lock;
} counter_t;
counter_t *prCount;
counter_t *coCount;
int producerTotal = 0;
int consumerTotal = 0;
int buffer[200];
int fill_ptr = 0;
int use_ptr = 0;
int count = 0;
int producerSum = 0;
int consumerSum = 0;
int loops = 6555;
pthread_cond_t empty = PTHREAD_COND_INITIALIZER;
pthread_cond_t fill = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int CounterGet(counter_t *c) {
pthread_mutex_lock(&c->lock);
int rc = c->value;
pthread_mutex_unlock(&c->lock);
return rc;
}
void CounterInit(counter_t *c) {
c->value = 0;
pthread_mutex_init(&c->lock, 0);
}
void CounterIncrement(counter_t *c) {
pthread_mutex_lock(&c->lock);
c->value++;
pthread_mutex_unlock(&c->lock);
}
void CounterDecrement(counter_t *c) {
pthread_mutex_lock(&c->lock);
c->value--;
pthread_mutex_unlock(&c->lock);
}
int ** AllocMatrix(int r, int c)
{
int ** a;
int i;
a = (int**) malloc(sizeof(int *) * r);
assert(a != 0);
for (i = 0; i < r; i++)
{
a[i] = (int *) malloc(c * sizeof(int));
assert(a[i] != 0);
}
return a;
}
void FreeMatrix(int ** a, int r, int c)
{
int i;
for (i=0; i<r; i++)
{
free(a[i]);
}
free(a);
}
void GenMatrix(int ** matrix, const int height, const int width)
{
int i, j;
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
{
int * mm = matrix[i];
mm[j] = rand() % 10;
}
}
}
int SumMatrix(int ** matrix, const int height, const int width)
{
int sum = 0;
int i, j;
for (i=0; i<height; i++)
for (j=0; j<width; j++)
{
sum += matrix[i][j];
}
return sum;
}
int put() {
int **mat = AllocMatrix(5, 5);
GenMatrix(mat, 5, 5);
int sum = SumMatrix(mat ,5 , 5);
bigMatrix[fill_ptr] = mat;
fill_ptr = (fill_ptr + 1) % 200;
count++;
return sum;
}
int get() {
int sum = SumMatrix(bigMatrix[use_ptr], 5, 5);
FreeMatrix(bigMatrix[use_ptr], 5, 5);
use_ptr = (use_ptr + 1) % 200;
count--;
return sum;
}
void *producer(void *arg) {
int producerSum = 0;
while(CounterGet(prCount) < 6555) {
pthread_mutex_lock(&mutex);
while (count == 200) {
if(CounterGet(prCount) == 6555) {
break;
}
pthread_cond_wait(&empty, &mutex);
}
if (CounterGet(prCount) < 6555) {
producerSum += put();
CounterIncrement(prCount);
}
pthread_cond_signal(&fill);
pthread_mutex_unlock(&mutex);
}
return producerSum;
}
void *consumer(void *arg) {
int consumerSum = 0;
while(CounterGet(coCount) < 6555) {
pthread_mutex_lock(&mutex);
while (count == 0) {
if(CounterGet(coCount) == 6555) {
break;
}
pthread_cond_wait(&fill, &mutex);
}
if (CounterGet(coCount) < 6555) {
int tmp = get();
consumerSum += tmp;
CounterIncrement(coCount);
}
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
}
return consumerSum;
}
int main() {
int producerSumGlobal = 0;
int consumerSumGlobal = 0;
int prReturn[6];
int coReturn[6];
int i = 0;
pthread_t prThread[6];
pthread_t coThread[6];
prCount = malloc(sizeof(counter_t));
coCount = malloc(sizeof(counter_t));
CounterInit(prCount);
CounterInit(coCount);
srand(time(0));
for(i = 0; i < 6; i++) {
pthread_create(&prThread[i], 0, producer, 0);
pthread_create(&coThread[i], 0, consumer, 0);
}
for(i = 0; i < 6; i++) {
pthread_join(prThread[i], &prReturn[i]);
pthread_join(coThread[i], &coReturn[i]);
}
for (i = 0; i < 6; i++) {
producerSumGlobal += prReturn[i];
consumerSumGlobal += coReturn[i];
}
printf("producer: %d\\nconsumer: %d\\n", producerSumGlobal,
consumerSumGlobal);
free(prCount);
free(coCount);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t oskit_uvm_mutex;
pthread_key_t oskit_uvm_per_thread_key;
static void thread_create_hook(pthread_t tid);
static void thread_destroy_hook(pthread_t tid);
static void per_thread_destructor(void *arg);
static void thread_csw_hook(void);
extern void
oskit_uvm_thread_init()
{
int rc;
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&oskit_uvm_mutex, &attr);
pthread_mutexattr_destroy(&attr);
rc = pthread_key_create(&oskit_uvm_per_thread_key, per_thread_destructor);
assert(rc == 0);
oskit_pthread_aftercsw_hook_set(thread_csw_hook);
oskit_pthread_create_hook_set(thread_create_hook);
oskit_pthread_destroy_hook_set(thread_destroy_hook);
thread_create_hook(pthread_self());
}
extern void
oskit_uvm_lock()
{
if (!threads_initialized) {
return;
}
assert(curproc);
pthread_mutex_lock(&oskit_uvm_mutex);
curproc->p_pid = (int)pthread_self();
assert(cpl == 0);
}
extern void
oskit_uvm_unlock()
{
if (!threads_initialized) {
return;
}
pthread_mutex_unlock(&oskit_uvm_mutex);
}
static struct oskit_uvm_per_thread *pt_head;
static struct oskit_uvm_per_thread *pt_exited;
static void
thread_create_hook(pthread_t tid)
{
struct oskit_uvm_per_thread *pt;
UVM_LOCK;
if (pt_head) {
pt = pt_head;
pt_head = pt_head->pt_next;
UVM_UNLOCK;
} else {
UVM_UNLOCK;
pt = malloc(sizeof(*pt), M_TEMP, M_WAITOK);
assert(pt);
bzero(pt, sizeof(*pt));
}
pt->pt_tid = tid;
oskit_pthread_setspecific(tid, oskit_uvm_per_thread_key, (void*)pt);
}
static void
per_thread_destructor(void *arg)
{
struct oskit_uvm_per_thread *pt = (struct oskit_uvm_per_thread*)arg;
assert(pt->pt_tid == pthread_self());
UVM_LOCK;
pt->pt_next = pt_exited;
pt_exited = pt;
UVM_UNLOCK;
pthread_setspecific(oskit_uvm_per_thread_key, 0);
}
static void
thread_destroy_hook(pthread_t tid)
{
struct oskit_uvm_per_thread **pt;
struct oskit_uvm_per_thread *tmp;
int found = 0;
UVM_LOCK;
for (pt = &pt_exited ; *pt ; pt = &((*pt)->pt_next)) {
if ((*pt)->pt_tid == tid) {
tmp = (*pt)->pt_next;
(*pt)->pt_next = pt_head;
pt_head = *pt;
*pt = tmp;
found = 1;
break;
}
}
assert(found);
UVM_UNLOCK;
}
static void (*uvm_csw_hook)();
static void
thread_csw_hook()
{
oskit_uvm_activate_locked(oskit_uvm_vmspace_get());
if (uvm_csw_hook) {
(*uvm_csw_hook)();
}
}
extern void
oskit_uvm_csw_hook_set(void (*hook)(void))
{
uvm_csw_hook = hook;
}
| 1
|
#include <pthread.h>
void init(int n, double (**A)[n], double **b, double **x0, double **x1)
{
*A = malloc(n * n * sizeof(double));
*b = malloc(n * sizeof(double));
*x0 = malloc(n * sizeof(double));
*x1 = malloc(n * sizeof(double));
unsigned short xi[3] = {4, 153, 17};
int i,j;
for (i = 0; i < n; i++) {
(*A)[i][i] = 0.0;
(*x0)[i] = 0.0;
(*x1)[i] = 0.0;
for (j = 0; j < n; j++) {
if (i != j)
{
(*A)[i][j] = erand48(xi);
(*A)[i][i] += 2.0 * (*A)[i][j];
}
}
(*b)[i] = 0.0;
for (j = 0; j < n; j++) {
(*b)[i] += (*A)[i][j] * j;
}
}
}
void print_vector(int n, double v[n])
{
for(int i = 0; i < n; i++)
printf("%lf ", v[i]);
printf("\\n");
}
void print_matrix(int n, double M[n][n])
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
printf("%lf ", M[i][j]);
}
printf("\\n");
}
}
struct pthread_args
{
int id;
int tnum;
int n;
int *iter;
double *stop;
double *A;
double *b;
double *x0;
double *x1;
pthread_mutex_t *mutex;
pthread_barrier_t *barrier;
};
void * pthread_jacobi(void *args)
{
struct pthread_args *a = (struct pthread_args*)args;
int id = a->id, n = a->n, iter = 0, tnum = a->tnum;
double l_stop, *stop = a->stop, *tmp,
(*A)[n] = a->A, *b = a->b, *x0 = a->x0, *x1 = a->x1;
do
{
l_stop = 0.0;
for (int i = id*(n/tnum); i < (id+1)*(n/tnum); i++)
{
x1[i] = 0.0;
for (int j = 0; j < n; j++)
{
if(i != j)
x1[i] += A[i][j] * x0[j];
}
x1[i] = (b[i] - x1[i]) / A[i][i];
l_stop += pow(x1[i] - x0[i], 2.0);
}
tmp = x1; x1 = x0; x0 = tmp;
iter++;
pthread_barrier_wait(a->barrier);
if(id == 0) *stop = 0.0;
pthread_barrier_wait(a->barrier);
pthread_mutex_lock(a->mutex);
*stop += l_stop;
pthread_mutex_unlock(a->mutex);
pthread_barrier_wait(a->barrier);
} while((sqrt(*stop) > 0.00001) && (iter < 1000000));
if(id == 0) *(a->iter) = iter;
return 0;
}
void main(int argc, char **argv)
{
int n = 14, iter = 0, tnum = 2;
if(argc > 2)
{ n = atoi(argv[1]); tnum = atoi(argv[1]); }
double stop, (*A)[n], *b, *x0, *x1;
pthread_mutex_t mutex;
pthread_barrier_t barrier;
pthread_barrier_init(&barrier, 0, tnum);
pthread_mutex_init(&mutex, 0);
init(n, &A, &b, &x0, &x1);
printf("Matrix A:\\n");
print_matrix(n, A);
printf("\\nVector b:\\n");
print_vector(n, b);
printf("\\nInitial Guess of Vector x:\\n");
print_vector(n, x1);
pthread_t *thread; struct pthread_args *thread_arg;
thread = malloc((unsigned long)tnum * sizeof(*thread));
thread_arg = malloc((unsigned long)tnum * sizeof(*thread_arg));
for (int i = 0; i < tnum; i++)
{
thread_arg[i] =
(struct pthread_args){ i, tnum, n, &iter, &stop, A, b, x0, x1, &mutex, &barrier};
pthread_create(thread + i, 0, &pthread_jacobi, thread_arg + i);
}
for (int i = 0; i < tnum; i++)
{
pthread_join(thread[i], 0 );
}
printf("\\nSolution Vector x after %d Iterations:\\n", iter);
print_vector(n, x1);
}
| 0
|
#include <pthread.h>
struct foo {
int f_count;
pthread_mutex_t f_lock;
struct foo *f_next;
int f_id;
};
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo *
foo_alloc(void)
{
struct foo *fp;
int idx;
if ((fp = malloc(sizeof(struct foo))) == 0)
return 0;
fp->f_count = 1;
if (pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return 0;
}
pthread_mutex_lock(&hashlock);
idx = (((unsigned long) fp) % 29);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
return(fp);
}
void
foo_hold(struct foo *fp)
{
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
struct foo *
foo_find(int id)
{
struct foo *fp;
int idx;
pthread_mutex_lock(&hashlock);
for (idx=0; idx<29; idx++) {
for (fp = fh[idx]; fp != 0; fp = fp->f_next) {
if (fp->f_id == id) {
fp->f_count++;
pthread_mutex_unlock(&hashlock);
return(fp);
}
}
}
pthread_mutex_unlock(&hashlock);
return(0);
}
void
foo_rele(struct foo *fp)
{
struct foo *temp;
int idx;
pthread_mutex_lock(&hashlock);
if (fp->f_count == 1) {
fp->f_count--;
idx = (((unsigned long) fp) % 29);
temp = fh[idx];
if (temp == fp) {
fh[idx] = fp->f_next;
} else {
while (temp->f_next != fp)
temp = temp->f_next;
temp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
} else {
fp->f_count--;
pthread_mutex_unlock(&hashlock);
}
}
int
main(void)
{
struct foo *fp, *temp;
fp = foo_alloc();
printf("fp->f_count = %d\\n", fp->f_count);
fp->f_id = 1337;
temp = foo_find(1337);
printf("fp->f_count = %d\\n", fp->f_count);
foo_rele(fp);
printf("fp->f_count = %d\\n", fp->f_count);
foo_rele(fp);
exit(0);
}
| 1
|
#include <pthread.h>
int *numbers;
size_t length;
} thread_arg_t;
static int Sum = 0;
static pthread_mutex_t Sum_Mutext = PTHREAD_MUTEX_INITIALIZER;
static void *thread_start(void *arg) {
thread_arg_t *thread_args = (thread_arg_t *) arg;
int *numbers = thread_args->numbers;
size_t length = thread_args->length;
for (size_t i = 0; i < length; ++i) {
pthread_mutex_lock(&Sum_Mutext);
Sum += numbers[i];
pthread_mutex_unlock(&Sum_Mutext);
}
return 0;
}
int main(int argc, char **argv) {
int firstSequence[] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
int secondSequence[] = {
10, 20, 30, 40, 50, 60, 70, 80, 90, 100
};
pthread_t threads[2];
thread_arg_t thread_args[2];
thread_args[0].numbers =
firstSequence;
thread_args[0].length =
sizeof(firstSequence) /
sizeof(firstSequence[0]);
thread_args[1].numbers =
secondSequence;
thread_args[1].length =
sizeof(secondSequence) /
sizeof(secondSequence[0]);
for (size_t i = 0; i < 2; ++i) {
if (0 != pthread_create(
&threads[i],
0,
thread_start,
(void *) &thread_args[i]
)) {
fputs("Failed to create a thread.\\n", stderr);
}
}
for (size_t i = 0; i < 2; ++i) {
if (0 != pthread_join(threads[i], 0)) {
fputs("Failed to wait for the thread to finish.\\n", stderr);
}
}
printf("The total sum of two arrays is %d.\\n", Sum);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
void prepare(void) {
printf("preparing locks...\\n");
pthread_mutex_lock(&lock1);
pthread_mutex_lock(&lock2);
}
void parent(void) {
printf("parent unlocking locks...\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void child(void) {
printf("child unlocking locks...\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void *thr_fn(void *arg) {
printf("thread %ld started...\\n", pthread_self());
pause();
return (void *)0;
}
int main(void) {
int err;
pthread_t tid;
pid_t pid;
if((err = pthread_atfork(prepare, parent, child)) != 0)
err_exit(err, "can't install fork handlers");
err = pthread_create(&tid, 0, thr_fn, 0);
if(err != 0)
err_exit(err, "can't create thread");
sleep(2);
printf("parent about to fork...\\n");
if((pid = fork()) < 0)
err_quit("for failed");
else if(pid == 0)
printf("child returned from fork\\n");
else
printf("parent returned from fork\\n");
return 0;
}
| 1
|
#include <pthread.h>
clock_t startm, stopm;
int PORT = 8181;
int putConsole(const char* msg);
void* doNewThread(void* Iterations);
pthread_mutex_t console;
int main(int argc, char **argv) {
if ( (startm = clock()) == -1) { printf("Error calling clock"); exit(1); };
pthread_t* thrArr;
int i,paramThreads = 1, paramIterations = 1;
while ((i = getopt (argc, argv, "n:m:p:")) != -1)
switch (i){
case 'p':
PORT = atoi(optarg);
break;
case 'n':
paramThreads = atoi(optarg);
break;
case 'm':
paramIterations = atoi(optarg);
break;
case '?':
if (optopt == 'n' || optopt == 'm' )
fprintf (stderr, "Option -%c requires an argument.\\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\\n", optopt);
else
fprintf (stderr,"Unknown option character `\\\\x%x'.\\n", optopt);
return 1;
default:
abort ();
}
pthread_mutex_init (&console, 0);
thrArr = (pthread_t*) calloc (paramThreads, sizeof(pthread_t));
assert(thrArr != 0);
for(i=0; i<paramThreads; i++) {
if (pthread_create(&thrArr[i], 0, doNewThread,(void*) ¶mIterations)) {
fprintf(stderr, "error creating a new thread \\n");
exit(1);
}
}
for(i=0; i<paramThreads; i++)
pthread_join(thrArr[i], 0);
free(thrArr);
if ( (stopm = clock()) == -1) { printf("Error calling clock"); exit(1); };
printf("%6.3f seconds used by the processor.\\n", ((double)stopm-startm)/CLOCKS_PER_SEC);;
return 0;
}
void* doNewThread(void* Iterations) {
int i, sockfd, nIterations = *((int*)Iterations);
char buffer[8196];
struct sockaddr_in serv_addr;
while (nIterations--) {
if ((sockfd = socket(AF_INET, SOCK_STREAM,0)) <0)
putConsole("socket() failed");
else {
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
serv_addr.sin_port = htons(PORT);
if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) <0)
putConsole("connect() failed");
else {
write(sockfd, "GET /index.html \\r\\n", 18);
while( (i=read(sockfd,buffer,8196)) > 0) {
buffer[i] = 0;
putConsole(buffer);
}
close(sockfd);
}
}
}
return 0;
}
int putConsole(const char* mesg) {
pthread_mutex_lock(&console);
printf("%s\\n", mesg);
pthread_mutex_unlock(&console);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t buffer_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t num_in_mutex = PTHREAD_MUTEX_INITIALIZER;
double x;
double y;
} points;
points points_buf[32];
int read;
int write;
int done;
int num_elms;
}fifo_buf;
void init_fifo_buf(fifo_buf * buffer){
buffer->read = 0;
buffer->write = 0;
buffer->done = 0;
buffer->num_elms = 0;
}
void add_points(points * current_points, fifo_buf * buffer){
while(1){
pthread_mutex_lock(&buffer_mutex);
if(buffer->read == buffer->write && buffer->num_elms != 0){
pthread_mutex_unlock(&buffer_mutex);
continue;
}
break;
}
buffer->points_buf[buffer->write].x = current_points->x;
buffer->points_buf[buffer->write].y = current_points->y;
buffer->write = (buffer->write + 1) % 32;
buffer->num_elms += 1;
pthread_mutex_unlock(&buffer_mutex);
return;
}
void read_points(points * current_points,fifo_buf * buffer){
while(1){
pthread_mutex_lock(&buffer_mutex);
if(buffer->write == buffer->read && buffer->num_elms == 0){
pthread_mutex_unlock(&buffer_mutex);
continue;
}
break;
}
current_points->x = buffer->points_buf[buffer->read].x;
current_points->y = buffer->points_buf[buffer->read].y;
buffer->read = (buffer->read + 1) % 32;
buffer->num_elms -= 1;
pthread_mutex_unlock(&buffer_mutex);
return;
}
double pi_approx(int num_points){
srand (time(0));
fifo_buf shared_buf;
init_fifo_buf(&shared_buf);
int num_in = 0;
int i;
{
{
{
for(i = 0; i < num_points; i++){
points new_points;
new_points.x = (double)rand() / (double)32767;
new_points.y = (double)rand() / (double)32767;
add_points(&new_points, &shared_buf);
}
shared_buf.done = 1;
}
{
while(shared_buf.done == 0 || shared_buf.num_elms > 0){
points current_points;
read_points(¤t_points, &shared_buf);
double r = sqrt( pow((current_points.x - 0.5),2) +
pow((current_points.y - 0.5),2));
if(r <= 0.5){
pthread_mutex_lock(&num_in_mutex);
num_in++;
pthread_mutex_unlock(&num_in_mutex);
}
}
}
}
}
return((double)4*num_in/num_points);
}
int main(int argc, char **argv){
if(argc < 2){
printf("usage: hw2c NUM_POINTS\\n");
return(1);
}
int num_points = atoi(argv[1]);
printf("%.*e\\n",pi_approx(num_points));
return(0);
}
| 1
|
#include <pthread.h>
void *producer (void *args);
void *consumer (void *args);
int a_mem[0xffff];
int b_mem[0xffff];
pthread_mutex_t *a_mutex;
pthread_mutex_t *b_mutex;
int a_is_processing;
int b_is_processing;
int a_is_empty;
int b_is_empty;
pthread_cond_t *a_is_ready, *a_isnt_processing;
pthread_cond_t *b_is_ready, *b_isnt_processing;
} queue;
queue *queueInit (void);
void queueDelete (queue *q);
void queueAdd (queue *q, int in);
void queueDel (queue *q, int *out);
int main ()
{
queue *fifo;
pthread_t pro, con;
fifo = queueInit ();
if (fifo == 0) {
fprintf (stderr, "main: Queue Init failed.\\n");
exit (1);
}
pthread_create (&pro, 0, producer, fifo);
pthread_create (&con, 0, consumer, fifo);
pthread_join (pro, 0);
pthread_join (con, 0);
queueDelete (fifo);
return 0;
}
void *producer (void *q)
{
queue *fifo;
int i;
fifo = (queue *)q;
int fd = 0;
void *map_base = 0, *virt_addr = 0;
struct timeval tpstart,tpend;
float timeuse;
const uint32_t ALT_H2F_BASE = 0xC0000000;
const uint32_t ALT_H2F_OCM_OFFSET = 0x00000000;
off_t target = ALT_H2F_BASE;
unsigned long read_result;
int idx = 0;
if((fd = open("/dev/mem", O_RDWR | O_SYNC)) == -1)
do { fprintf(stderr, "Error at line %d, file %s (%d) [%s]\\n", 103, "pc_ocm.c", errno, strerror(errno)); exit(1); } while(0);
printf("/dev/mem opened.\\n"); fflush(stdout);
map_base = mmap(0, 0x44000, PROT_READ | PROT_WRITE, MAP_SHARED, fd, target & ~(0x44000 - 1));
printf("Memory mapped at address %p.\\n", map_base); fflush(stdout);
virt_addr = map_base + (target & (0x44000 - 1));
for (i = 0; i < 20; i++) {
pthread_mutex_lock (fifo->a_mutex);
while (fifo->a_is_processing) {
printf ("producer: memory A is processing.\\n");
pthread_cond_wait (fifo->a_isnt_processing, fifo->a_mutex);
}
fifo->a_is_empty = 0;
printf("producer: copying a\\n");
for( idx = 0 ; idx < 0xffff; idx ++ ) {
void* access_addr = virt_addr + ALT_H2F_OCM_OFFSET + idx*4;
read_result = *((uint32_t*) access_addr);
fifo->a_mem[idx] = read_result;
}
printf("producer: copying a (end)\\n");
pthread_mutex_unlock (fifo->a_mutex);
pthread_cond_signal (fifo->a_is_ready);
pthread_mutex_lock (fifo->b_mutex);
while (fifo->b_is_processing) {
printf ("producer: memory B is processing.\\n");
pthread_cond_wait (fifo->b_isnt_processing, fifo->b_mutex);
}
fifo->b_is_empty = 0;
printf("producer: copying b\\n");
for( idx = 0 ; idx < 0xffff; idx ++ ) {
void* access_addr = virt_addr + ALT_H2F_OCM_OFFSET + idx*4;
read_result = *((uint32_t*) access_addr);
fifo->b_mem[idx] = read_result;
}
printf("producer: copying b (end)\\n");
pthread_mutex_unlock (fifo->b_mutex);
pthread_cond_signal (fifo->b_is_ready);
}
if(munmap(map_base, 0x44000) == -1) do { fprintf(stderr, "Error at line %d, file %s (%d) [%s]\\n", 148, "pc_ocm.c", errno, strerror(errno)); exit(1); } while(0);
close(fd);
return (0);
}
void *consumer (void *q)
{
queue *fifo;
int i, d;
fifo = (queue *)q;
for (i = 0; i < 20; i++) {
pthread_mutex_lock (fifo->a_mutex);
while (fifo->a_is_empty) {
printf ("consumer: memory A is empty, wait producer.\\n");
pthread_cond_wait (fifo->a_is_ready, fifo->a_mutex);
}
fifo->a_is_processing = 1;
printf("image process A\\n");
usleep(10);
fifo->a_is_processing = 0;
fifo->a_is_empty = 1;
pthread_mutex_unlock (fifo->a_mutex);
pthread_cond_signal (fifo->a_isnt_processing);
pthread_mutex_lock (fifo->b_mutex);
while (fifo->b_is_empty) {
printf ("consumer: memory B is empty, wait producer.\\n");
pthread_cond_wait (fifo->b_is_ready, fifo->b_mutex);
}
fifo->b_is_processing = 1;
printf("image process B\\n");
usleep(10);
fifo->b_is_processing = 0;
fifo->b_is_empty = 1;
pthread_mutex_unlock (fifo->b_mutex);
pthread_cond_signal (fifo->b_isnt_processing);
}
return (0);
}
queue *queueInit (void)
{
queue *q;
q = (queue *)malloc (sizeof (queue));
if (q == 0) return (0);
q->a_is_processing = 0;
q->b_is_processing = 0;
q->a_is_empty = 1;
q->b_is_empty = 1;
q->a_mutex= (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t));
pthread_mutex_init (q->a_mutex, 0);
q->b_mutex= (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t));
pthread_mutex_init (q->b_mutex, 0);
q->a_is_ready= (pthread_cond_t *) malloc (sizeof (pthread_cond_t));
pthread_cond_init (q->a_is_ready, 0);
q->b_is_ready= (pthread_cond_t *) malloc (sizeof (pthread_cond_t));
pthread_cond_init (q->b_is_ready, 0);
q->a_isnt_processing= (pthread_cond_t *) malloc (sizeof (pthread_cond_t));
pthread_cond_init (q->a_isnt_processing, 0);
q->b_isnt_processing= (pthread_cond_t *) malloc (sizeof (pthread_cond_t));
pthread_cond_init (q->b_isnt_processing, 0);
return (q);
}
void queueDelete (queue *q)
{
pthread_mutex_destroy (q->a_mutex);
free (q->a_mutex);
pthread_mutex_destroy (q->b_mutex);
free (q->b_mutex);
pthread_cond_destroy (q->a_is_ready);
free (q->a_is_ready);
pthread_cond_destroy (q->b_is_ready);
free (q->b_is_ready);
pthread_cond_destroy (q->a_isnt_processing);
free (q->a_isnt_processing);
pthread_cond_destroy (q->b_isnt_processing);
free (q->b_isnt_processing);
free (q);
}
| 0
|
#include <pthread.h>
static pthread_key_t key;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;
extern char **environ;
static void
thread_init(void)
{
pthread_key_create(&key, free);
}
char *
getenv(const char *name)
{
int i, len;
char *envbuf;
pthread_once(&init_done, thread_init);
pthread_mutex_lock(&env_mutex);
envbuf = (char *)pthread_getspecific(key);
if (envbuf == 0)
{
envbuf = malloc(4096);
if (envbuf == 0)
{
pthread_mutex_unlock(&env_mutex);
return(0);
}
pthread_setspecific(key, envbuf);
}
len = strlen(name);
for (i = 0; environ[i] != 0; i++)
{
if ((strncmp(name, environ[i], len) == 0) &&
(environ[i][len] == '='))
{
strncpy(envbuf, &environ[i][len+1], 4096 -1);
pthread_mutex_unlock(&env_mutex);
return(envbuf);
}
}
pthread_mutex_unlock(&env_mutex);
return(0);
}
| 1
|
#include <pthread.h>
int * T;
sem_t * sem;
pthread_mutex_t * lock;
pthread_cond_t * cond;
void wtc_proc_init(int * initial_matrix, int n, int number_of_processes) {
sem_t * temp_sem;
int process_number;
pthread_condattr_t cond_attr;
pthread_mutexattr_t lock_attr;
T = share_memory(sizeof(int) * n * n);
sem = share_memory(sizeof(int));
temp_sem = sem_open("/semaphore", O_CREAT, 0644, 0);
memcpy(&sem, &temp_sem, sizeof(int));
memcpy(T, initial_matrix, sizeof(int) * n * n);
lock = share_memory(sizeof(pthread_mutex_t));
cond = share_memory(sizeof(pthread_cond_t));
pthread_mutexattr_init(&lock_attr);
pthread_mutexattr_setpshared(&lock_attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(lock, &lock_attr);
pthread_condattr_init(&cond_attr);
pthread_condattr_setpshared(&cond_attr, PTHREAD_PROCESS_SHARED);
pthread_cond_init(cond, &cond_attr);
for (process_number = 0; process_number < number_of_processes; process_number++) {
wtc_proc_create(process_number, number_of_processes, n);
}
}
int * wtc_proc(int n, int number_of_processes) {
int i, k;
for (k = 0; k < n; k++) {
for (i=0; i < number_of_processes; i++){
sem_wait(sem);
}
pthread_mutex_lock(lock);
pthread_cond_broadcast(cond);
pthread_mutex_unlock(lock);
}
for (i = 0; i < number_of_processes; i++) {
sem_wait(sem);
}
return T;
}
void wtc_proc_create(int process_number, int number_of_processes, int n) {
int pid, i, j, k;
pid = fork();
switch (pid) {
case -1:
perror("fork"); exit(1);
break;
case 0:
for (k = 0; k < n; k++) {
for (i = process_number; i < n; i += number_of_processes) {
for (j = 0 ; j < n; j++) {
T[j + i*n] = T[j + i*n] | (T[j + k*n] & T[k + i*n]);
}
}
pthread_mutex_lock(lock);
sem_post(sem);
pthread_cond_wait(cond, lock);
pthread_mutex_unlock(lock);
}
sem_post(sem);
exit(0);
break;
}
}
void wtc_proc_cleanup() {
shmdt(T);
shmdt(sem);
shmdt(lock);
shmdt(cond);
if (sem_close(sem) == -1) {
perror("sem_close"); exit(1);
}
if (sem_unlink("/semaphore") == -1) {
perror("sem_unlink"); exit(1);
}
}
| 0
|
#include <pthread.h>
void* task(void* arg);
int var = 0;
int max = INT_MIN;
int min = 32767;
pthread_mutex_t lock;
int main(int argc, char* argv[])
{
pthread_mutex_init(&lock, 0);
pthread_t threads[6];
int threadArgs[6];
int i;
for (i = 0; i < 6; ++i) {
threadArgs[i] = i;
printf("Main: Creating thread %d\\n", i);
int ok = pthread_create(&threads[i], 0, task, (void*)&threadArgs[i]);
if (ok != 0) {
printf("Main: Could not create thread\\n", i);
exit(1);
}
}
for (i = 0; i < 6; ++i) {
int ok = pthread_join(threads[i], 0);
if (ok != 0) {
printf("Main: Could not JOIN thread %d\\n", i);
exit(1);
}
printf("Main: Thread %d complete\\n", i);
}
printf("After all, var = %d\\n", var);
printf(" min = %d\\n", min);
printf(" max = %d\\n", max);
printf("Main: Completed\\n");
return 0;
}
void* task(void* arg)
{
int myId;
myId = *((int*)arg);
printf(" Thread %d: Started\\n", myId);
int incDec = 1;
if (myId % 2 == 1) {
incDec = -1;
}
int i;
for (i = 0; i < 10000; ++i) {
pthread_mutex_lock(&lock);
var = var + incDec;
if (var > max) {
max = var;
}
if (var < min) {
min = var;
}
pthread_mutex_unlock(&lock);
}
printf(" Thread %d: var = %d\\n", myId, var);
printf(" Thread %d: Ending\\n", myId);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
uint8_t savedNonce[32];
volatile bool nonceFound;
void saveNonce(uint8_t *val) {
pthread_mutex_lock(&mutex);
if (nonceFound) return;
memcpy(savedNonce, val, 32);
nonceFound=1;
pthread_mutex_unlock(&mutex);
}
struct ThreadData {
int thread_num;
uint8_t data[32];
uint8_t threshold[32];
};
void getHash(uint8_t *in, uint8_t *out) {
struct sha3_ctx ctx;
sha3_init(&ctx, 256);
sha3_update(&ctx, in, 64);
sha3_finalize(&ctx, out);
}
int compare256(uint8_t first[32], uint8_t second[32]) {
int i;
for(i = 0; i < 32; i++) {
if (first[i] < second[i]) return -1;
else if (first[i] > second[i]) return 1;
}
return 0;
}
void increment256(uint8_t val[32]) {
int i;
for(i=31; i >= 0; i--) {
val[i]++;
if (val[i] != 0) return;
}
}
void print256(uint8_t val[32]) {
int i;
for(i = 0; i < 32; i++)
printf("%02x", val[i]);
printf("\\n");
}
void *calculateHashes(void *x) {
uint8_t dataAndNonce[64] = {0};
uint8_t out[32];
struct ThreadData *threadData = (struct ThreadData *) x;
memcpy(dataAndNonce, threadData->data, 32);
uint64_t i;
*(dataAndNonce + 32) = threadData->thread_num;
while(1){
if (nonceFound) return 0;
increment256(dataAndNonce+32);
getHash(dataAndNonce, out);
if (compare256(out, threadData->threshold) == -1) {
printf("data: ");
print256(dataAndNonce);
printf("nonce: ");
print256(dataAndNonce+32);
printf("out: ");
print256(out);
printf("done\\n");
saveNonce(dataAndNonce+32);
return 0;
}
}
printf("shouldn't be here\\n");
exit(1);
}
int findNonce(uint8_t data[32], uint8_t threshold[32], uint8_t *out) {
pthread_t inc_x_thread[8];
struct ThreadData threadData[8];
printf("data: ");
print256(data);
printf("threshold: ");
print256(threshold);
int thread_num;
int i;
nonceFound=0;
for(thread_num = 0; thread_num < 8 -1; thread_num++) {
memcpy(threadData[thread_num].threshold, threshold, 32);
memcpy(threadData[thread_num].data, data, 32);
threadData[thread_num].thread_num = thread_num;
if(pthread_create(&inc_x_thread[thread_num], 0, calculateHashes, (threadData+thread_num))) {
fprintf(stderr, "Error creating thread\\n");
return 1;
}
}
for(thread_num = 0; thread_num < 8 -1; thread_num++) {
if(pthread_join(inc_x_thread[thread_num], 0)) {
fprintf(stderr, "Error joining thread\\n");
return 2;
}
}
assert(nonceFound);
printf("savedNonce: ");
print256(savedNonce);
memcpy(out, savedNonce, 32);
return 0;
}
| 0
|
#include <pthread.h>
int buffer[100];
int nextp, nextc;
int count=0;
int procheck = 0;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
void printfunction(void * ptr)
{
int count = *(int *) ptr;
if (count==0)
{
printf("All items produced are consumed by the consumer \\n");
}
else
{
for (int i=0; i<=count; i=i+1)
{
printf("%d, \\t",buffer[i]);
}
printf("\\n");
}
}
void *producer(void *ptr)
{
int item, flag=0;
int in = *(int *) ptr;
do
{
pthread_mutex_lock(&mutex);
item = (rand()%7)%10;
flag=flag+1;
nextp=item;
buffer[in]=nextp;
in=((in+1)%100);
count = count + 1;
pthread_mutex_unlock(&mutex);
}
while (flag<=1000);
procheck = 1;
pthread_exit(0);
}
void *consumer(void *ptr)
{
int item, flag=1000;
int out = *(int *) ptr;
do
{
pthread_mutex_lock(&mutex);
while (count >0)
{
nextc = buffer[out];
out=(out+1)%100;
printf("\\t\\tCount = %d in consumer at Iteration = %d\\n", count, flag);
count = count-1;
flag=flag-1;
}
if (count <= 0 && procheck == 0)
{
printf("consumer made to wait...faster than producer.\\n");
}
pthread_mutex_unlock(&mutex);
}
while (procheck==0 || flag>=0);
pthread_exit(0);
}
int main(void)
{
int in=0, out=0;
pthread_t pro, con;
int rc1;
int rc2;
rc1 = pthread_create(&pro, 0, producer, &count);
rc2 = pthread_create(&con, 0, consumer, &count);
if (rc1)
{
printf("ERROR; return code from pthread_create() is %d\\n", rc1);
exit(-1);
}
if (rc2)
{
printf("ERROR; return code from pthread_create() is %d\\n", rc2);
exit(-1);
}
pthread_join(pro, 0);
pthread_join(con, 0);
printfunction(&count);
}
| 1
|
#include <pthread.h>
int NUM_BINS;
pthread_mutex_t lock;
long long rand_per_thread;
struct bin{
int lower;
int upper;
long long value;
} ;
struct bin *my_bin;
void *histogram(void *threadid)
{
long tid;
tid = (long)threadid;
int i,j;
int x;
srand(time(0));
for(i=0;i<rand_per_thread;i++)
{
x=rand()%(100);
for (j=0;j<NUM_BINS;j++)
{
if(x >=my_bin[j].lower && x< my_bin[j].upper)
{
pthread_mutex_lock(&lock);
my_bin[j].value=my_bin[j].value+1;
pthread_mutex_unlock(&lock);
break;
}
}
}
pthread_exit(0);
}
int main(int argc, char *argv[])
{
pthread_t *threads;
pthread_attr_t attr;
long long NUM_THREADS;
int rc;
long t;
void *status;
int i;
int bin_width;
long long test;
long long NUM_RAND;
NUM_RAND=atoll(argv[1]);
NUM_BINS=atoi(argv[2]);
NUM_THREADS=atoll(argv[3]);
threads=malloc(NUM_THREADS*sizeof(pthread_t));
my_bin=malloc(NUM_BINS*sizeof(struct bin));
if (my_bin == 0)
printf("Problem with Malloc\\n");
bin_width=100/NUM_BINS;
rand_per_thread=NUM_RAND/NUM_THREADS;
printf("Conditions: Number of randoms: %lld, Number of bins: %d, Number of threads: %lld, Range: %d, Bin Width: %d, Rand per thread: %lld\\n", NUM_RAND,NUM_BINS,NUM_THREADS,100,bin_width, rand_per_thread);
for (i=0;i<NUM_BINS;i++)
{
my_bin[i].lower=i*bin_width;
my_bin[i].upper=(i+1)*bin_width;
my_bin[i].value=0;
}
clock_t tic,toc;
if (threads == 0)
{
printf("Problem with malloc...\\n");
return 1;
}
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("\\n mutex init failed\\n");
return 1;
}
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
tic=clock();
for(t=0;t<NUM_THREADS;t++)
{
rc = pthread_create(&threads[t], &attr, histogram, (void *)t);
if (rc)
{
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
pthread_attr_destroy(&attr);
for(t=0; t<NUM_THREADS; t++)
{
pthread_join(threads[t], &status);
}
toc=clock();
test=0;
for (i=0;i<NUM_BINS;i++)
{
printf("bin (%d,%d) = %lld\\n",my_bin[i].lower,my_bin[i].upper,my_bin[i].value);
test=test+my_bin[i].value;
}
printf("Total random number processed = %lld \\n",test);
printf("Time = %lf \\n",(double)(toc-tic)/(double)CLOCKS_PER_SEC);
pthread_mutex_destroy(&lock);
pthread_exit(0);
free (threads);
free (my_bin);
}
| 0
|
#include <pthread.h>
struct timerfd_context {
int fd;
pthread_t worker;
timer_t timer;
int flags;
struct timerfd_context *next;
};
static struct timerfd_context *timerfd_contexts;
pthread_mutex_t timerfd_context_mtx = PTHREAD_MUTEX_INITIALIZER;
struct timerfd_context *
get_timerfd_context(int fd, bool create_new)
{
for (struct timerfd_context *ctx = timerfd_contexts; ctx;
ctx = ctx->next) {
if (fd == ctx->fd) {
return ctx;
}
}
if (create_new) {
struct timerfd_context *new_ctx =
calloc(1, sizeof(struct timerfd_context));
if (!new_ctx) {
return 0;
}
new_ctx->fd = -1;
new_ctx->next = timerfd_contexts;
timerfd_contexts = new_ctx;
return new_ctx;
}
return 0;
}
static void *
worker_function(void *arg)
{
struct timerfd_context *ctx = arg;
siginfo_t info;
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGRTMIN);
sigaddset(&set, SIGRTMIN + 1);
(void)pthread_sigmask(SIG_BLOCK, &set, 0);
struct kevent kev;
EV_SET(&kev, 0, EVFILT_USER, 0, NOTE_TRIGGER, 0,
(void *)(intptr_t)pthread_getthreadid_np());
(void)kevent(ctx->fd, &kev, 1, 0, 0, 0);
for (;;) {
if (sigwaitinfo(&set, &info) != SIGRTMIN) {
break;
}
EV_SET(&kev, 0, EVFILT_USER, 0, NOTE_TRIGGER, 0,
(void *)(intptr_t)timer_getoverrun(ctx->timer));
(void)kevent(ctx->fd, &kev, 1, 0, 0, 0);
}
return 0;
}
static int
timerfd_create_impl(int clockid, int flags)
{
if (clockid != CLOCK_MONOTONIC && clockid != CLOCK_REALTIME) {
return EINVAL;
}
if (flags & ~(TFD_CLOEXEC | TFD_NONBLOCK)) {
return EINVAL;
}
struct timerfd_context *ctx = get_timerfd_context(-1, 1);
if (!ctx) {
errno = ENOMEM;
return -1;
}
ctx->fd = kqueue();
if (ctx->fd == -1) {
return -1;
}
ctx->flags = flags;
struct kevent kev;
EV_SET(&kev, 0, EVFILT_USER, EV_ADD | EV_CLEAR, 0, 0, 0);
if (kevent(ctx->fd, &kev, 1, 0, 0, 0) == -1) {
close(ctx->fd);
ctx->fd = -1;
return -1;
}
if (pthread_create(&ctx->worker, 0, worker_function, ctx) == -1) {
close(ctx->fd);
ctx->fd = -1;
return -1;
}
int ret = kevent(ctx->fd, 0, 0, &kev, 1, 0);
if (ret == -1) {
pthread_kill(ctx->worker, SIGRTMIN + 1);
pthread_join(ctx->worker, 0);
close(ctx->fd);
ctx->fd = -1;
return -1;
}
int tid = (int)(intptr_t)kev.udata;
struct sigevent sigev = {.sigev_notify = SIGEV_THREAD_ID,
.sigev_signo = SIGRTMIN,
.sigev_notify_thread_id = tid};
if (timer_create(clockid, &sigev, &ctx->timer) == -1) {
pthread_kill(ctx->worker, SIGRTMIN + 1);
pthread_join(ctx->worker, 0);
close(ctx->fd);
ctx->fd = -1;
return -1;
}
return ctx->fd;
}
int
timerfd_create(int clockid, int flags)
{
pthread_mutex_lock(&timerfd_context_mtx);
int ret = timerfd_create_impl(clockid, flags);
pthread_mutex_unlock(&timerfd_context_mtx);
return ret;
}
static int
timerfd_settime_impl(
int fd, int flags, const struct itimerspec *new, struct itimerspec *old)
{
struct timerfd_context *ctx = get_timerfd_context(fd, 0);
if (!ctx) {
errno = EINVAL;
return -1;
}
if (flags & ~(TFD_TIMER_ABSTIME)) {
errno = EINVAL;
return -1;
}
return timer_settime(ctx->timer,
(flags & TFD_TIMER_ABSTIME) ? TIMER_ABSTIME : 0, new, old);
}
int
timerfd_settime(
int fd, int flags, const struct itimerspec *new, struct itimerspec *old)
{
pthread_mutex_lock(&timerfd_context_mtx);
int ret = timerfd_settime_impl(fd, flags, new, old);
pthread_mutex_unlock(&timerfd_context_mtx);
return ret;
}
ssize_t
timerfd_read(struct timerfd_context *ctx, void *buf, size_t nbytes)
{
int fd = ctx->fd;
int flags = ctx->flags;
pthread_mutex_unlock(&timerfd_context_mtx);
if (nbytes < sizeof(uint64_t)) {
errno = EINVAL;
return -1;
}
struct timespec timeout = {0, 0};
struct kevent kev;
int ret = kevent(
fd, 0, 0, &kev, 1, (flags & TFD_NONBLOCK) ? &timeout : 0);
if (ret == -1) {
return -1;
} else if (ret == 0) {
errno = EAGAIN;
return -1;
}
uint64_t nr_expired = 1 + (uint64_t)kev.udata;
memcpy(buf, &nr_expired, sizeof(uint64_t));
return sizeof(uint64_t);
}
int
timerfd_close(struct timerfd_context *ctx)
{
timer_delete(ctx->timer);
pthread_kill(ctx->worker, SIGRTMIN + 1);
pthread_join(ctx->worker, 0);
int ret = close(ctx->fd);
ctx->fd = -1;
return ret;
}
| 1
|
#include <pthread.h>
int i = 0;
pthread_mutex_t i_mutex;
void* thread1_func(){
for(int j = 0; j < 100000; ++j){
while( pthread_mutex_lock(&i_mutex) );
i++;
pthread_mutex_unlock(&i_mutex);
}
return 0;
}
void* thread2_func(){
for(int j = 0; j < 1000000; ++j){
while( pthread_mutex_lock(&i_mutex) );
i--;
pthread_mutex_unlock(&i_mutex);
}
return 0;
}
int main(){
pthread_t thread1;
pthread_create(&thread1, 0, thread1_func, 0);
pthread_t thread2;
pthread_create(&thread2, 0, thread2_func, 0);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
printf("num: %d\\n", i);
return 0;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.