text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
extern int __setlogin(const char* name);
extern pthread_mutex_t __logname_mutex;
extern char *__logname;
int setlogin(const char* name)
{
pthread_mutex_lock(&__logname_mutex);
int res = __setlogin(name);
if (res == 0 && __logname != 0) {
__logname[0] = 0;
}
pthread_mutex_unlock(&__logname_mutex);
return res;
}
| 1
|
#include <pthread.h>
extern char server_ip[];
extern int server_port;
extern struct tabella_memoria *memory;
extern struct lista *lista_blocchi;
struct tabella_memoria *popolaMemoria(char *file) {
printf("* Lettura dati dal file %s, inizializzazione memoria... ",file);
fflush(stdout);
FILE *fp;
struct tabella_memoria *l = 0;
l = malloc(sizeof(struct tabella_memoria));
struct tabella_memoria *lis = l;
if((fp=fopen(file,"r")) == 0) {
sys_err("! errore apertura file\\n");
}
while(1) {
int blocco = 0;
int porta = 0;
char server[22];
memset(server,'\\0',sizeof(server));
if(fscanf(fp,"%d",&blocco) != 1) break;
if(fscanf(fp,"%s",server) != 1) sys_err("! errore lettura server");
if(fscanf(fp,"%d",&porta) != 1) sys_err("! errore lettura porta");
if(strcmp(server,server_ip) != 0) continue;
if(porta != server_port) continue;
l = lis;
lis = (struct tabella_memoria *)malloc(sizeof(struct tabella_memoria));
lis->ID_blocco = blocco;
lis->controllo_rw = 0;
pthread_mutex_init(&lis->mutex_blocco,0);
pthread_cond_init(&lis->condition_blocco,0);
lis->indirizzo_locale = malloc(DIMBLOCK);
lis->list = l;
}
fflush(0);
fclose(fp);
printf("fatto\\n");
return lis;
}
void *restituisciMemoriaLocale(int ID) {
void *memoria = 0;
struct tabella_memoria *l = memory;
while(l != 0)
{
if(l->ID_blocco == ID) {
memoria = l->indirizzo_locale;
}
l = l->list;
}
return memoria;
}
int restituisciControllorw(int ID) {
struct tabella_memoria *l = memory;
while(l != 0)
{
if(l->ID_blocco == ID)
{
return l->controllo_rw;
}
l = l->list;
}
return -1;
}
void lock_blocco(int ID)
{
struct tabella_memoria *l = memory;
while( l!= 0)
{
if(l->ID_blocco == ID)
{
pthread_mutex_lock(&l->mutex_blocco);
break;
}
l = l->list;
}
}
void wait_blocco(int ID)
{
struct tabella_memoria *l = memory;
while(l!= 0)
{
if(l->ID_blocco == ID)
{
pthread_cond_wait(&l->condition_blocco,&l->mutex_blocco);
break;
}
l=l->list;
}
}
void unlock_blocco(int ID)
{
struct tabella_memoria *l = memory;
while( l!= 0)
{
if(l->ID_blocco == ID)
{
pthread_mutex_unlock(&l->mutex_blocco);
break;
}
l = l->list;
}
}
void stampaTabellaMemoria() {
struct tabella_memoria *l;
l = memory;
while( l != 0)
{
printf("* ID: %d -> %x (controllo_rw: %d)\\n",
l->ID_blocco,
l->indirizzo_locale,
l->controllo_rw);
l= l->list;
}
}
void stampaTabellaInterna()
{
struct lista *l = lista_blocchi;
printf("------------ TABELLA INTERNA INIZIO ----------------\\n");
if (l == 0) printf("* Lista blocchi vuota\\n");
while(l != 0)
{
printf("* ID_blocco: %d\\n",l->tab_interna.ID_blocco);
printf("* ID_client: %d\\n",l->tab_interna.ID_client);
printf("* controllo_rw: %d\\n",l->tab_interna.controllo_rw);
printf("* socket_client: %d\\n",l->tab_interna.socket_client);
printf("* indirizzo locale: %x\\n",(void *)l->tab_interna.indirizzo_locale);
printf("* Stringa locale: %s\\n",(void *)l->tab_interna.indirizzo_locale);
l= l->list;
}
printf("------------ TABELLA INTERNA FINE ----------------\\n");
}
void liberaMemoria() {
struct tabella_memoria *l = memory;
while( l!= 0)
{
struct tabella_memoria *tmp = l;
free(l->indirizzo_locale);
l=l->list;
free(tmp);
}
}
void stampaHeader(struct protocol_header *p_h) {
printf("* tipo operazione: %d\\n",p_h->tipo_operazione);
printf("* cod_risultato: %d\\n",p_h->cod_risultato);
printf("* ID_client: %d\\n",p_h->ID_client);
printf("* dim_dato: %d\\n",p_h->dim_dato);
printf("* ID_blocco: %d\\n",p_h->ID_blocco);
}
int controllaOperazione(struct protocol_header *p_h) {
printf("* Il client %d ha richiesto un ",p_h->ID_client);
switch(p_h->tipo_operazione)
{
case 1:
printf("map\\n");
break;
case 2:
printf("unmap\\n");
break;
case 3:
printf("update\\n");
break;
case 4:
printf("write\\n");
break;
case 5:
printf("update\\n");
break;
default:
sys_err("!! operazione non riconosciuta");
}
return p_h->tipo_operazione;
}
void incrementaRW(int ID)
{
struct tabella_memoria *l = memory;
while( l != 0)
{
if(l->ID_blocco == ID)
{
l->controllo_rw = (l->controllo_rw)+1;
pthread_cond_broadcast(&l->condition_blocco);
}
l = l->list;
}
}
void aggiornaRW(int ID_c,int ID_b)
{
struct lista *l = lista_blocchi;
while (l != 0)
{
if(l->tab_interna.ID_blocco == ID_b && l->tab_interna.ID_client == ID_c)
{
l->tab_interna.controllo_rw = restituisciControllorw(l->tab_interna.ID_blocco);
}
l=l->list;
}
}
int verificaRW(int ID_c,int ID_b)
{
struct lista *l = lista_blocchi;
int cod = 1;
while(l != 0)
{
if((l->tab_interna.ID_blocco == ID_b) && (l->tab_interna.ID_client == ID_c))
{
if( l->tab_interna.controllo_rw == restituisciControllorw(ID_b))
{
cod = 0;
break;
}
}
l=l->list;
}
return cod;
}
void sys_err(char *s) {
perror(s);
exit(-1);
}
void sys_warn(char *s) {
perror(s);
}
void user_err(char *s) {
printf("%s\\n",s);
exit(-1);
}
void debug(char *s) {
printf(">> %s\\n",s);
}
| 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>
static struct mod_object *modules;
static pthread_mutex_t mtx_mod;
void
mod_init(void)
{
pthread_mutex_init(&mtx_mod, 0);
}
int
mod_load(char *mod)
{
struct mod_object *mhand, *mlist;
void (*module_init)(struct mod_object *);
int (**func_mod_load)(char *);
int (**func_mod_unload)(const char *);
int (**func_irc_cmd)(int, const char *, const char *);
int (**func_mod_register_irc)(struct mod_object *,
int (*)(const char *, const char *,
const char *, const char *));
if((mhand = calloc(1, sizeof(*mhand))) == 0)
goto not_enough_mem;
if((mhand->dl_handler = dlopen(mod, RTLD_LAZY|RTLD_LOCAL)) == 0)
goto dlopen_error;
else
{
char *file = basename(mod);
if(file == 0)
return(-1);
mhand->filename = strdup(file);
}
pthread_mutex_lock(&mtx_mod);
if(modules == 0)
modules = mhand;
else
{
for(mlist = modules; mlist->next != 0; mlist = mlist->next)
{
if(mlist == mhand)
{
vout(3, VOUT_FLOW_INBOUND, "Modules", "Module already loaded.");
goto dlopen_error;
}
}
mlist->next = mhand;
}
pthread_mutex_unlock(&mtx_mod);
if((func_mod_load = dlsym(mhand->dl_handler, "mod_load")) != 0)
*func_mod_load = &mod_load;
if((func_mod_unload = dlsym(mhand->dl_handler, "mod_unload")) != 0)
*func_mod_unload = &mod_unload;
if((func_mod_register_irc = dlsym(mhand->dl_handler, "mod_register_irc")) != 0)
*func_mod_register_irc = &mod_register_irc;
if((func_irc_cmd = dlsym(mhand->dl_handler, "irc_cmd")) != 0)
*func_irc_cmd = &irc_cmd;
if((*(void **)(&module_init) = dlsym(mhand->dl_handler, "module_init")) != 0)
(*module_init)(mhand);
return(0);
dlopen_error:
free(mhand);
not_enough_mem:
return(-1);
}
int
mod_unload(const char *mod)
{
struct mod_object *mlist;
if(modules == 0 || mod == 0)
return(-1);
pthread_mutex_lock(&mtx_mod);
for(mlist = modules;
mlist->next != 0 && mlist->next->filename == mod;
mlist = mlist->next);
if(mlist == 0)
return(-1);
if(modules == mlist)
modules = 0;
{
struct mod_object *temp = mlist->next;
if(mlist->next != 0)
{
mlist->next = mlist->next->next;
mlist = temp;
}
}
if(dlclose(mlist->dl_handler) != 0)
return(-1);
pthread_mutex_unlock(&mtx_mod);
if(mlist != 0)
{
if(mlist->filename != 0)
free(mlist->filename);
free(mlist);
}
return(0);
}
int
mod_irc_callback(const char *from, const char *to, const char *command, const char *mesg)
{
int eat = MOD_EAT_NONE;
struct mod_object *mlist = modules;
if(mlist == 0)
return(eat);
pthread_mutex_lock(&mtx_mod);
do
{
if(mlist->irc_callback == 0)
continue;
if((eat = (*mlist->irc_callback)(from, to, command, mesg)) != MOD_EAT_NONE)
break;
}
while((mlist = mlist->next) != 0);
pthread_mutex_unlock(&mtx_mod);
return(eat);
}
int
mod_register_irc(struct mod_object *mh,
int (*callback)(const char *from, const char *to,
const char *command, const char *mesg))
{
if(mh == 0 || callback == 0)
return(-1);
pthread_mutex_lock(&mtx_mod);
mh->irc_callback = callback;
pthread_mutex_unlock(&mtx_mod);
return(0);
}
| 0
|
#include <pthread.h>
int pthread_barrier_init(pthread_barrier_t *barrier,
const pthread_barrierattr_t *attr, unsigned int count)
{
if (unlikely(!barrier) || unlikely(count == 0)) {
errno = EINVAL;
return -1;
}
if (attr && (*attr != PTHREAD_PROCESS_PRIVATE)) {
errno = EINVAL;
return -1;
}
if (pthread_mutex_init(&barrier->mutex, 0) != 0)
return -1;
if (pthread_cond_init(&barrier->cond, 0) != 0) {
pthread_mutex_destroy(&barrier->mutex);
return -1;
}
barrier->tripCount = count;
barrier->count = 0;
return 0;
}
int pthread_barrier_destroy(pthread_barrier_t *barrier)
{
if (unlikely(!barrier)) {
errno = EINVAL;
return -1;
}
if (pthread_cond_destroy(&barrier->cond) != 0)
return -1;
if (pthread_mutex_destroy(&barrier->mutex) != 0)
return -1;
return 0;
}
int pthread_barrier_wait(pthread_barrier_t *barrier)
{
if (unlikely(!barrier)) {
errno = EINVAL;
return -1;
}
if (pthread_mutex_lock(&barrier->mutex) !=0)
return -1;
++(barrier->count);
if (barrier->count >= barrier->tripCount) {
barrier->count = 0;
pthread_cond_broadcast(&barrier->cond);
} else {
pthread_cond_wait(&barrier->cond, &(barrier->mutex));
}
pthread_mutex_unlock(&barrier->mutex);
return 0;
}
| 1
|
#include <pthread.h>
float** main_plate;
float** main_prev_plate;
char** main_locked_cells;
pthread_barrier_t barrier_first;
pthread_barrier_t barrier_second;
pthread_mutex_t critical_begin_end;
pthread_mutex_t runnable;
int nthreads;
int begin;
int end;
} arg_plate_t;
double when() {
struct timeval tp;
gettimeofday(&tp, 0);
return ((double)tp.tv_sec + (double)tp.tv_usec * 1e-6);
}
float** createPlate() {
float** plate = (float**)malloc(16384 * sizeof(float*));
int k;
for (k = 0; k < 16384; k++) {
plate[k] = (float*)malloc(16384 * sizeof(float));
}
return plate;
}
char** createCharPlate() {
char** plate = (char**)malloc(16384 * sizeof(char*));
int k;
for (k = 0; k < 16384; k++) {
plate[k] = (char*)malloc(16384 * sizeof(char));
}
return plate;
}
void copy(float** main, float** result) {
int i,j;
for (i = 0; i < 16384; i++) {
for (j = 0; j < 16384; j++) {
result[i][j] = main[i][j];
}
}
}
void initPlate(float** plate, float** prev_plate) {
int i, j;
for (i = 0; i < 16384; i++) {
for (j = 0; j < 16384; j++) {
if (i == 0 || j == 0 || j == 16384 -1) {
plate[i][j] = 0;
prev_plate[i][j] = 0;
main_locked_cells[i][j] = '1';
}
else if (i == 16384 -1) {
plate[i][j] = 100;
prev_plate[i][j] = 100;
main_locked_cells[i][j] = '1';
}
else if (i == 400 && j >= 0 && j <= 330) {
plate[i][j] = 100;
prev_plate[i][j] = 100;
main_locked_cells[i][j] = '1';
}
else if (i == 200 && j == 500) {
plate[i][j] = 100;
prev_plate[i][j] = 100;
main_locked_cells[i][j] = '1';
}
else {
plate[i][j] = 50;
prev_plate[i][j] = 50;
main_locked_cells[i][j] = '0';
}
}
}
for (i = 0; i < 16384; i++) {
if ((i % 20) == 0) {
for (j = 0; j < 16384; j++) {
plate[i][j] = 100;
prev_plate[i][j] = 100;
main_locked_cells[i][j] = '1';
}
}
}
for (j = 0; j < 16384; j++) {
if ((j % 20) == 0) {
for (i = 0; i < 16384; i++) {
plate[i][j] = 0;
prev_plate[i][j] = 0;
main_locked_cells[i][j] = '1';
}
}
}
}
void cleanupFloat(float** plate) {
int i, j;
for (i = 0; i < 16384; i++) {
free(plate[i]);
}
free(plate);
}
void cleanupChar(char** plate) {
int i, j;
for (i = 0; i < 16384; i++) {
free(plate[i]);
}
free(plate);
}
void* update_plate(void* plate_arguments) {
for(;;) {
pthread_barrier_wait(&barrier_first);
arg_plate_t* plate_args = (arg_plate_t*)plate_arguments;
pthread_mutex_lock(&runnable);
int begin = plate_args->begin;
int end = plate_args->end;
pthread_mutex_unlock(&runnable);
int i, j;
for (i = begin; i < end; i++) {
for (j = 0; j < 16384; j++) {
if (main_locked_cells[i][j] == '0') {
main_plate[i][j] = (main_prev_plate[i+1][j] + main_prev_plate[i][j+1] + main_prev_plate[i-1][j]
+ main_prev_plate[i][j-1] + 4 * main_prev_plate[i][j]) * 0.125;
}
}
}
pthread_barrier_wait(&barrier_second);
}
}
char steady(float** current_plate) {
int count = 0;
int i, j;
float main_diff = 0;
for (i = 0; i < 16384; i++) {
for (j = 0; j < 16384; j++) {
if (main_locked_cells[i][j] == '0') {
if (current_plate[i][j] > 50)
count++;
float diff = fabs(current_plate[i][j] - (current_plate[i+1][j] + current_plate[i-1][j]
+ current_plate[i][j+1] + current_plate[i][j-1]) * 0.25);
if (diff > main_diff)
main_diff = diff;
}
}
}
if (main_diff > 0.1)
return (1);
else
return (0);
}
void allocateWorkload(int nthreads, int* begin_end) {
int step = 16384 / nthreads;
int i;
int begin = 0;
for (i = 0; i < nthreads*2; i++) {
begin_end[i] = begin;
begin = begin+step;
i += 1;
begin_end[i] = begin;
}
}
int startUpdate(pthread_t* threads, int nthreads) {
printf("Updating plate to steady state\\n");
int iterations = 0;
int* begin_end = (int*)malloc((nthreads*2) * sizeof(int));
allocateWorkload(nthreads, begin_end);
int i;
int j;
pthread_t worker[nthreads];
arg_plate_t* plate_args;
for (i = 0; i < nthreads; i++) {
pthread_mutex_lock(&critical_begin_end);
plate_args = (arg_plate_t*)malloc(sizeof(arg_plate_t));
j = i * 2;
plate_args->begin = begin_end[j];
plate_args->end = begin_end[j+1];
pthread_create(&worker[i], 0, &update_plate, (void*)plate_args);
pthread_mutex_unlock(&critical_begin_end);
}
do {
iterations++;
printf("Iteration: %d\\n", iterations);
pthread_barrier_wait(&barrier_first);
pthread_barrier_wait(&barrier_second);
copy(main_plate, main_prev_plate);
} while(steady(main_plate));
return iterations;
}
int main(int argc, char* argv[]) {
double start = when();
printf("Starting time: %f\\n", start);
int nthreads = atoi(argv[1]);
pthread_t threads[nthreads];
main_plate = createPlate();
main_prev_plate = createPlate();
main_locked_cells = createCharPlate();
initPlate(main_plate, main_prev_plate);
pthread_barrier_init(&barrier_first,0,nthreads+1);
pthread_barrier_init(&barrier_second,0,nthreads+1);
pthread_mutex_init(&critical_begin_end,0);
pthread_mutex_init(&runnable,0);
int iterations = startUpdate(threads, nthreads);
double end = when();
printf("\\nEnding time: %f\\n", end);
printf("Total execution time: %f\\n", end - start);
printf("Number of iterations: %d\\n\\n", iterations);
pthread_barrier_destroy(&barrier_first);
pthread_barrier_destroy(&barrier_second);
pthread_mutex_destroy(&critical_begin_end);
pthread_mutex_destroy(&runnable);
printf("Cleanup\\n");
cleanupFloat(main_plate);
cleanupFloat(main_prev_plate);
cleanupChar(main_locked_cells);
return 0;
}
| 0
|
#include <pthread.h>
void *filosofo (void *id);
void pegaGarfo (int, int, char *);
void devolveGarfo (int, int, char *);
void pensar(int);
void comer(int);
int comidaNaMesa ();
int numero_filosofos;
pthread_mutex_t *garfo;
pthread_t *filo;
pthread_mutex_t comidaBloqueada;
int sleep_seconds = 0;
int tempoComendo;
int tempoPensando;
int filosofoAleatorio;
int main (int argn, char **argv)
{
int i;
printf("Informe o numero de filosofos:\\n");
scanf("%d", &numero_filosofos);
filosofoAleatorio = rand() % numero_filosofos;
garfo = (pthread_mutex_t *) malloc(numero_filosofos*sizeof(pthread_mutex_t));
filo = (pthread_t *) malloc(numero_filosofos*sizeof(pthread_t));
printf("Informe o tempo gasto do filosofo pensando:\\n");
scanf("%d", &tempoPensando);
printf("Informe o tempo gasto do filosofo comendo:\\n");
scanf("%d", &tempoComendo);
printf("---------------------------------------------:\\n");
if (argn == 2)
sleep_seconds = atoi (argv[1]);
pthread_mutex_init (&comidaBloqueada, 0);
for (i = 0; i < numero_filosofos; i++)
pthread_mutex_init (&garfo[i], 0);
for (i = 0; i < numero_filosofos; i++)
pthread_create (&filo[i], 0, filosofo, (void *)i);
for (i = 0; i < numero_filosofos; i++)
pthread_join (filo[i], 0);
return 0;
}
void *filosofo (void *num)
{
int id;
int i, garfoEsquerdo, garfoDireito, f;
id = (int)num;
garfoDireito = id;
garfoEsquerdo = id + 1;
pensar(id);
if (garfoEsquerdo == numero_filosofos)
garfoEsquerdo = 0;
while (f = comidaNaMesa()) {
if (filosofoAleatorio == id)
pegaGarfo (id, garfoEsquerdo, "esquerda");
else
pegaGarfo (id, garfoDireito, "direita ");
devolveGarfo(id, garfoDireito, "direita");
pegaGarfo (id, garfoDireito, "direita");
if (filosofoAleatorio != id) {
devolveGarfo(id, garfoDireito, "direita");
pegaGarfo(id, garfoEsquerdo, "esquerda");
} else {
comer(id);
devolveGarfo(id, garfoDireito, "direita");
devolveGarfo(id, garfoEsquerdo, "esquerda");
filosofoAleatorio = rand() % numero_filosofos;
pensar(id);
}
pegaGarfo(id, garfoDireito, "direita");
comer(id);
devolveGarfo(id, garfoDireito, "direita");
devolveGarfo(id, garfoEsquerdo, "esquerda");
pensar(id);
}
printf ("Filosofo %d acabou de comer.\\n", id);
return (0);
}
int
comidaNaMesa ()
{
static int comida = 50;
int meuPrato;
pthread_mutex_lock (&comidaBloqueada);
if (comida > 0) {
comida--;
}
meuPrato = comida;
pthread_mutex_unlock (&comidaBloqueada);
return comida;
}
void
pegaGarfo (int filo,
int g,
char *lado)
{
pthread_mutex_lock (&garfo[g]);
printf ("Filosfo %d FAMINTO: pega o garfo %d da %s\\n", filo, g, lado);
}
void
devolveGarfo (int filo, int g, char *lado)
{
pthread_mutex_unlock(&garfo[g]);
printf("Filosfo %d devolve o garfo %d da %s\\n", filo, g, lado);
}
void pensar(int id) {
printf("Filosofo %d esta PENSANDO\\n",id);
sleep(tempoPensando);
}
void comer(int id) {
printf ("Filosfo %d: COMENDO.\\n", id);
sleep(tempoComendo);
}
| 1
|
#include <pthread.h>
void *pool_manager(void *attr);
int WORKERS = 10;
pthread_mutex_t m;
pthread_cond_t cond;
int S[100];
int TOP = -1;
void push(int data){
if(TOP==99) return;
S[++TOP] = data;
}
int pop(){
if(TOP==-1) return -1;
return S[TOP--];
}
void init_pool(){
int i;
for(i=0;i<WORKERS;i++){
pthread_t th;
pthread_create(&th, 0, pool_manager, 0);
}
}
void *pool_manager(void *attr){
int curr = (int)pthread_self();
printf("Current th = %d\\n", curr);
while(1){
pthread_mutex_lock(&m);
if(TOP==-1){
pthread_cond_wait(&cond, &m);
}
int request = pop();
printf("%d = ThreadID %d\\n", request, curr);
pthread_mutex_unlock(&m);
}
}
int main(int argc, char *argv[]){
init_pool();
sleep(10);
int i;
for(i=1;i <=50; i++){
push(i);
pthread_cond_broadcast(&cond);
}
while(1);
return 0;
}
| 0
|
#include <pthread.h>
extern pthread_mutex_t mtx;
extern int level;
void* bus_led()
{
int wdata ,rdata,temp ;
int fd;
int num;
fd = open("/dev/cnled", O_RDWR);
if(fd < 0) {
perror("driver (//dev//cnled) open errir.\\n");
exit(0);
}
while(level!=6) {
pthread_mutex_lock(&mtx);
if(level == 0)
continue;
wdata = 0;
write(fd, &wdata, 4);
for(num = 1; num <= level*2; num++) {
read(fd,&rdata,4);
temp = 1;
temp <<=(num-1);
wdata = rdata | temp;
}
write(fd,&wdata,4);
pthread_mutex_unlock(&mtx);
usleep(100000);
}
close(fd);
return ;
}
| 1
|
#include <pthread.h>
void *ticketsell1(void *);
void *ticketsell2(void *);
int tickets = 20;
pthread_mutex_t mutex;
int main() {
pthread_t id1,id2;
pthread_mutex_init(&mutex,0);
int error;
error = pthread_create(&id1,0,ticketsell1,0);
if(error != 0){
printf("pthread is not created!\\n");
return -1;
}
error = pthread_create(&id2,0,ticketsell2,0);
if (error != 0) {
printf("pthread is not created!\\n");
return -1;
}
pthread_join(id1,0);
pthread_join(id2,0);
return 0;
}
void *ticketsell1(void *arg) {
while (1) {
pthread_mutex_lock(&mutex);
if (tickets > 0) {
usleep(1000);
printf("ticketse1 sells tickets:%d\\n", tickets--);
pthread_mutex_unlock(&mutex);
} else{
pthread_mutex_unlock(&mutex);
break;
}
}
return (void *)0;
}
void *ticketsell2(void *arg) {
while (1) {
pthread_mutex_lock(&mutex);
if (tickets > 0) {
usleep(2000);
printf("ticketse2 sells tickets:%d\\n", tickets--);
pthread_mutex_unlock(&mutex);
} else{
pthread_mutex_unlock(&mutex);
break;
}
}
return (void *)0;
}
| 0
|
#include <pthread.h>
int arr[10];
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static pthread_barrier_t barrier;
static int avail = 0;
static void *producer(void *arg)
{
sleep(1);
printf("\\n%s: Started producing..\\n", __func__);
int cnt = *((int *)arg);
int i, j, ret;
for (j = 0; j < cnt; j++) {
pthread_mutex_lock(&mtx);
for (i = 0; i < 9; i++)
arr[i] = 'A' + j;
pthread_mutex_unlock(&mtx);
printf("\\n%s: Data has produced\\n", __func__);
printf("%s: Broadcasted the signal to consumers.\\n\\n",
__func__);
avail += 2;
ret = pthread_cond_broadcast(&cond);
if (ret != 0)
perror("pthread_cond_signal");
pthread_barrier_wait(&barrier);
}
return 0;
}
static void *consumer1(void *arg)
{
int i, j, ret;
printf("\\n%s: Trying to consume..\\n", __func__);
for (j = 0; j < *(int *)arg; j++) {
pthread_mutex_lock(&mtx);
while (avail == 0) {
ret = pthread_cond_wait(&cond, &mtx);
if ((errno=ret) != 0)
perror("pthread_cond_wait");
}
printf("%s: Signal recieved.\\n", __func__);
printf("Data read: ");
for (i = 0; i < 9; i++)
printf("%c ", arr[i]);
printf("\\n");
avail--;
pthread_mutex_unlock(&mtx);
pthread_barrier_wait(&barrier);
}
}
static void *consumer2(void *arg)
{
printf("\\n%s: Trying to consume..\\n", __func__);
int i, j, ret;
for (j = 0; j < *(int *)arg; j++) {
pthread_mutex_lock(&mtx);
while (avail == 0) {
ret = pthread_cond_wait(&cond, &mtx);
if ((errno=ret) != 0)
perror("pthread_cond_wait");
}
printf("%s: Signal recieved.\\n", __func__);
printf("Data read: ");
for (i = 0; i < 9; i++)
printf("%c ", arr[i]);
printf("\\n");
avail--;
pthread_mutex_unlock(&mtx);
pthread_barrier_wait(&barrier);
}
}
int main()
{
pthread_t tid;
int ret, j, totRequired = 26;
pthread_barrier_init(&barrier, 0, 3);
ret = pthread_create(&tid, 0, producer, &totRequired);
if (ret != 0) {
errno = ret;
perror("pthread_create");
}
ret = pthread_create(&tid, 0, consumer1, &totRequired);
if (ret != 0) {
errno = ret;
perror("pthread_create");
}
ret = pthread_create(&tid, 0, consumer2, &totRequired);
if (ret != 0) {
errno = ret;
perror("pthread_create");
}
pthread_exit(0);
exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
void* imprimir(void*);
int j=0;
int main(void) {
pthread_mutex_init(&mutex,0);
pthread_t hilo[30];
int i;
for (i=0;i<30;i++) {
pthread_create(&hilo[i],0,&imprimir,&i);
}
for (i=0;i<30;i++) {
pthread_join(hilo[i],0);
}
pthread_mutex_destroy(&mutex);
return 0;
}
void* imprimir(void* b) {
int *a = b;
int i;
for (i=0;i<10000;i++) {
if (0) {
pthread_mutex_lock(&mutex);
j++;
pthread_mutex_unlock(&mutex);
} else {
j++;
}
printf("Hilo %i: j=%i\\n",*a,j);
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_t workerid[3];
pthread_mutex_t lock;
pthread_cond_t read;
pthread_cond_t writeStd;
pthread_cond_t writeFile;
char * line[100];
void * readInput(void *arg);
void * writeOutput(void *arg);
void * writeToFile(void *arg);
int main(int argc, char *argv[]){
char* filename = argv[1];
pthread_create(&workerid[0], 0, readInput, (void *) 0);
pthread_create(&workerid[1], 0, writeOutput, (void *) 1);
pthread_create(&workerid[2], 0, writeToFile, (void *) filename);
for (int i = 0; i < 3; i++) {
pthread_join(workerid[i], 0);
}
}
void * readInput(void *arg){
char input[100];
int ch;
do{
int i=0;
while(EOF!=(ch=fgetc(stdin)) && ch !='\\n' && i<100){
input[i++]=ch;
}
input[i]='\\0';
if(*input){
pthread_mutex_lock(&lock);
*line = input;
pthread_cond_signal(&read);
pthread_mutex_unlock(&lock);
}
}while(ch != EOF);
}
void * writeOutput(void *arg){
while(1){
pthread_mutex_lock(&lock);
pthread_cond_wait(&read, &lock);
printf("%s\\n", *line);
pthread_cond_signal(&writeStd);
pthread_mutex_unlock(&lock);
}
}
void * writeToFile(void *arg){
char* filename = (char*) arg;
FILE *file = fopen(filename,"a+");
if(!file) {
fprintf(stderr,"Error opening file...exiting\\n");
exit(1);
}
while(1){
pthread_mutex_lock(&lock);
pthread_cond_wait(&writeStd, &lock);
fprintf(file, "%s\\n", *line);
pthread_cond_signal(&writeFile);
pthread_mutex_unlock(&lock);
fflush(file);
}
fclose(file);
}
| 1
|
#include <pthread.h>
int numThreads;
double a, b, h;
int n, local_n;
pthread_mutex_t mutex;
double total;
double funcion(double x) {
double funcionEvaluar;
funcionEvaluar = x*x;
return funcionEvaluar;
}
double trapezoidalFun(double local_a, double local_b, int local_n, double h) {
double integral; double x; int i;
integral = (funcion(local_a) + funcion(local_b))/2.0;
x = local_a;
for (i = 1; i <= local_n-1; i++) {
x = local_a + i*h;
integral += funcion(x);
}
integral = integral*h;
return integral;
}
void *Thread_work(void* rank) {
double local_a; double local_b;
double my_int; long my_rank = (long) rank;
local_a = a + my_rank*local_n*h;
local_b = local_a + local_n*h;
my_int = trapezoidalFun(local_a, local_b, local_n, h);
pthread_mutex_lock(&mutex);
total += my_int;
pthread_mutex_unlock(&mutex);
return 0;
}
int main(int argc, char** argv) {
long i;
pthread_t* arrThreads;
total = 0.0;
numThreads = strtol(argv[1], 0, 10);
printf("Ingrese inicio, fin, numPedazos: \\n");
scanf("%lf %lf %d", &a, &b, &n);
h = (b-a)/n;
local_n = n/numThreads;
arrThreads = malloc (numThreads*sizeof(pthread_t));
pthread_mutex_init(&mutex, 0);
for (i = 0; i < numThreads; i++) pthread_create(&arrThreads[i], 0, Thread_work, (void*) i);
for (i = 0; i < numThreads; i++) pthread_join(arrThreads[i], 0);
printf("Con %d pedazos ",n); printf(" desde %f hasta %f es: %19.15e\\n",a, b, total);
pthread_mutex_destroy(&mutex);
free(arrThreads);
return 0;
}
| 0
|
#include <pthread.h>
int NumProcs;
int **grid[2];
int timesteps, xdim, ydim;
pthread_mutex_t SyncLock;
pthread_cond_t SyncCV;
int SyncCount;
pthread_mutex_t ThreadLock;
void Barrier()
{
int ret;
pthread_mutex_lock(&SyncLock);
SyncCount++;
if(SyncCount == NumProcs) {
ret = pthread_cond_broadcast(&SyncCV);
SyncCount = 0;
assert(ret == 0);
} else {
ret = pthread_cond_wait(&SyncCV, &SyncLock);
assert(ret == 0);
}
pthread_mutex_unlock(&SyncLock);
}
void* pthreadKernel(void* arg) {
int threadId = (long) arg;
int timeStepIndex, xIndex, yIndex;
for (timeStepIndex = 0; timeStepIndex < timesteps; ++timeStepIndex) {
for (xIndex = 1 + threadId * ((xdim-1) / NumProcs); xIndex < 1 + (threadId + 1) * ((xdim-1) / NumProcs); ++xIndex) {
for (yIndex = 1; yIndex < ydim-1; ++yIndex) {
grid[1][xIndex][yIndex] =
(
grid[0][xIndex ][yIndex ] +
grid[0][xIndex ][yIndex - 1] +
grid[0][xIndex ][yIndex + 1] +
grid[0][xIndex - 1][yIndex ] +
grid[0][xIndex + 1][yIndex ]
) / 5;
}
}
Barrier();
if (threadId == 0) {
int** temp = grid[0];
grid[0] = grid[1];
grid[1] = temp;
}
Barrier();
}
}
int pthread_ocean (int myNumProcs, int **myGrid[2], int myXdim, int myYdim, int myTimesteps) {
NumProcs = myNumProcs;
grid[0] = myGrid[0];
grid[1] = myGrid[1];
xdim = myXdim;
ydim = myYdim;
timesteps = myTimesteps;
pthread_attr_t attr;
int ret;
long threadIndex;
pthread_t* threads = (pthread_t*) malloc(sizeof(pthread_t) * NumProcs);
if (threads == 0) {
printf("Could not malloc pthread_t\\n");
return 1;
}
ret = pthread_cond_init(&SyncCV, 0);
assert(ret == 0);
ret = pthread_mutex_init(&SyncLock, 0);
assert(ret == 0);
SyncCount = 0;
for (threadIndex = 0; threadIndex < NumProcs; ++threadIndex) {
if (pthread_create(&threads[threadIndex], 0, pthreadKernel, (void*) threadIndex)) {
printf("Could not create thread %d\\n", threadIndex);
return 1;
}
}
for (threadIndex = 0; threadIndex < NumProcs; ++threadIndex) {
if (pthread_join(threads[threadIndex], 0)) {
printf("Could not join thread\\n");
return -1;
}
}
myGrid[0] = grid[0];
myGrid[1] = grid[1];
return 0;
}
| 1
|
#include <pthread.h>
int i, k;
pthread_mutex_t msg_mutex = PTHREAD_MUTEX_INITIALIZER;
int log_count = 0;
void
send_response (pthread_t tid)
{
unsigned int k = (int) tid;
int j;
unsigned int flight_number = k % 10000;
if (k % 5 == 1)
{
printf
("FLIGHT NO. %u \\n\\t PERMISSION DENIED... Please Go to MUMBAI ! \\n\\n\\n",
flight_number);
}
else if (k % 5 == 2)
{
printf
("FLIGHT NO. %u \\n \\t\\t PERMISSION DENIED... Please Go to DELHI ! \\n\\n\\n",
flight_number);
}
else if (k % 5 == 3)
{
printf
("FLIGHT NO. %u \\n \\t PERMISSION DENIED... Please Go to HYDERABAD ! \\n\\n\\n",
flight_number);
}
else if (k % 5 == 4)
{
printf
("FLIGHT NO. %u \\n \\t\\t PERMISSION DENIED... Please Go to KOLKATA !\\n\\n\\n",
flight_number);
}
else
{
r:
if (runway == 0 && count != 0)
{
pthread_mutex_lock (&msg_mutex);
runway = 1;
printf ("FLIGHT NO.%u \\n PLEASE LAND !\\n\\n\\n", pending[0]);
logg[log_count] = pending[0];
log_count++;
for (i = 0; i < (count - 1); i++)
pending[i] = pending[i + 1];
count--;
printf ("\\n\\ncount = %d\\n", count);
if (count != 0)
{
for (i = 0; i < count; i++)
printf ("\\n\\nFLIGHT NO. %u PLEASE WAIT !! \\n\\n", pending[i]);
}
sleep (2);
runway = 0;
pthread_mutex_unlock (&msg_mutex);
}
else if (runway == 1)
{
printf
("FLIGHT NO. %u\\nrunway is busy ... wait for a while..\\n\\n\\n",
flight_number);
pending[count] = flight_number;
count++;
sleep (2);
runway = 0;
goto r;
}
else
{
pthread_mutex_lock (&msg_mutex);
runway = 1;
printf ("FLIGHT NO. %u \\tPLEASE LAND ....... \\n", flight_number);
logg[log_count] = flight_number;
log_count++;
sleep (2);
runway = 0;
pthread_mutex_unlock (&msg_mutex);
}
}
}
| 0
|
#include <pthread.h>
int threadNumber;
int lBound;
int uBound;
} bounds;
void *prime(void *number);
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
int main(int argc, char **argv)
{
int rc1;
pthread_t *currThread;
bounds * cliBounds;
int currentNumber;
if(argc != 4)
{
printf("There are not enough args on the cli\\n");
return -1;
}
int lowerBound = atoi(argv[1]);
int upperBound = atoi(argv[2]);
int numThreads = atoi(argv[3]);
int difference = (upperBound-lowerBound)+1;
int range = (difference/numThreads)-1;
int balance = difference%numThreads;
if(lowerBound >= upperBound)
{
printf("The upper bound should be greater than the lower bound.\\n");
return -1;
}
if(numThreads < 1)
{
printf("The number of threads must be greater than or equal to one.\\n");
return -1;
}
printf("lower: %d\\n", lowerBound);
printf("upper: %d\\n", upperBound);
printf("threads: %d\\n", numThreads);
printf("numbers to check: %d\\n", difference);
printf("distribute: %d\\n", range);
printf("mod: %d\\n", (difference%numThreads));
numThreads++;
cliBounds = (bounds*) malloc((sizeof(bounds)*numThreads));
pthread_t threads[numThreads];
currentNumber=lowerBound;
int i=0;
for(i; i < numThreads-1; i++)
{
currThread = &threads[i];
cliBounds[i].threadNumber = i;
cliBounds[i].lBound = currentNumber;
cliBounds[i].uBound = currentNumber+range;
currentNumber+=range;
if (currentNumber > upperBound)
{
currentNumber = upperBound;
cliBounds[i].uBound = currentNumber;
}
if(balance != 0)
{
cliBounds[i].uBound++;
balance--;
currentNumber++;
}
currentNumber++;
}
i=0;
for(i; i < numThreads-1; i++)
{
if( (rc1=pthread_create( currThread, 0, &prime, &cliBounds[i])) )
{
printf("Thread creation failed: %d\\n", rc1);
}
pthread_join( *currThread, 0);
}
exit(0);
}
void *prime(void *number)
{
bounds *bob = (bounds*)number;
int lower=(*bob).lBound;
int upper=(*bob).uBound;
int amount = (upper-lower)+1;
int boolPrime[amount];
counter++;
printf("==== Thread %d ====\\n", (*bob).threadNumber);
printf("lower Number: %d\\n",lower);
printf("upper Number: %d\\n",upper);
printf("number of numbers: %d\\n",amount);
int x=lower;
int y;
for(x; x <= upper; x++)
{
y=2;
pthread_mutex_lock( &mutex1 );
while(y < x)
{
if(x%y ==0)
break;
else
y++;
}
pthread_mutex_unlock( &mutex1 );
if(y == x)
{
boolPrime[x] = 1;
printf("%d is prime\\n", x);
}
else
{
boolPrime[x] = 0;
printf("%d is NOT prime\\n", x);
}
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
enum Statu{ Main=0,Son=1,ThreadNum };
enum Statu Running=Son;
const int loop_times=50;
void* son_thread(void * arg){
pthread_mutex_lock(&mutex);
for(int ci=0;ci<loop_times;){
if(Running==Son){
for(int cj=0;cj<10;++cj);
printf("%d\\n: 子线程循环 10 次",ci);
Running=Main;
++ci;
}
pthread_cond_signal(&cond);
pthread_cond_wait(&cond,&mutex);
}
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
pthread_exit(0);
}
void* main_thread(void * arg){
pthread_mutex_lock(&mutex);
for(int ci=0;ci<loop_times;){
if(Running==Main){
for(int cj=0;cj<100;++cj);
printf("%d\\n: 主线程运行 100 次",ci);
Running=Son;
++ci;
}
pthread_cond_signal(&cond);
pthread_cond_wait(&cond,&mutex);
}
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
pthread_exit(0);
}
int main(int argc,char *argv[]){
pthread_cond_init(&cond,0);
pthread_mutex_init(&mutex,0);
pthread_t threads[ThreadNum];
pthread_create(&threads[Main],0,main_thread,0);
pthread_create(&threads[Son],0,son_thread,0);
pthread_join(threads[Main],0);
pthread_join(threads[Son],0);
return 0;
}
| 0
|
#include <pthread.h>
size_t start;
size_t end;
uint16_t * data;
int * hist;
pthread_mutex_t lock;
} Worker;
void increment_bucket(Worker * t_work, int bucket) {
pthread_mutex_lock(&t_work->lock);
t_work->hist[bucket]++;
pthread_mutex_unlock(&t_work->lock);
}
void * fill_buckets(void * t_arg) {
Worker * t_work = t_arg;
for (size_t t = t_work->start; t < t_work->end; t++) {
uint16_t val = t_work->data[t];
int bucket = (val - 1) / 4000;
if (bucket < 0) {
bucket = 0;
} else if (bucket >= (40000/4000)) {
bucket = (40000/4000) - 1;
}
increment_bucket(t_work, bucket);
}
pthread_exit(0);
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "Usage: ./parhist <filename>\\n");
exit(1);
}
const char *filename = argv[1];
size_t file_size = get_file_size(filename);
struct mmap_region region;
map_file_region(filename, file_size, ®ion);
uint16_t *arr = region.addr;
size_t num_elements = file_size/sizeof(uint16_t);
int histogram[(40000/4000)] = { 0 };
size_t chunk_size = num_elements / 2;
size_t leftover = num_elements % 2;
Worker * thread_work = malloc(sizeof(Worker));
pthread_mutex_init(&thread_work->lock, 0);
pthread_t threads[2];
Worker workers[2];
for (size_t i = 0; i < 2; i++) {
workers[i] = * thread_work;
workers[i].start = i * chunk_size;
workers[i].end = workers[i].start + chunk_size;
workers[i].data = arr;
workers[i].hist = histogram;
if (i == 2 - 1) {
workers[i].end += leftover;
}
pthread_create(&threads[i], 0, fill_buckets, &workers[i]);
}
for (int j = 0; j < 2; j++) {
pthread_join(threads[j], 0);
}
for (int i = 0; i < (40000/4000); i++) {
printf("%5i..%5i: %i\\n", i*4000 +1, (i+1)*4000, histogram[i]);
}
unmap_file_region(®ion);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t my_mutex;
static int tab[5];
void *read_tab_process (void * arg)
{
int i;
pthread_mutex_lock (&my_mutex);
for (i = 0 ; i != 5 ; i++)
printf ("read_process, tab[%d] vaut %d\\n", i, tab[i]);
pthread_mutex_unlock (&my_mutex);
pthread_exit (0);
}
void *write_tab_process (void * arg)
{
int i;
pthread_mutex_lock (&my_mutex);
for (i = 0 ; i != 5 ; i++) {
tab[i] = 2 * i;
printf ("write_process, tab[%d] vaut %d\\n", i, tab[i]);
sleep (1);
}
pthread_mutex_unlock (&my_mutex);
pthread_exit (0);
}
int main (int ac, char **av)
{
pthread_t th1, th2;
void *ret;
pthread_mutex_init (&my_mutex, 0);
if (pthread_create (&th1, 0, write_tab_process, 0) < 0) {
fprintf (stderr, "pthread_create error for thread 1\\n");
exit (1);
}
(void)pthread_join (th1, &ret);
if (pthread_create (&th2, 0, read_tab_process, 0) < 0) {
fprintf (stderr, "pthread_create error for thread 2\\n");
exit (1);
}
(void)pthread_join (th2, &ret);
return 0;
}
| 0
|
#include <pthread.h>
void* thread1( void* pParam );
void* thread2( void* pParam );
int count1 = 0;
int count2 = 0;
pthread_mutex_t mutex;
pthread_t Thread_create( void* (*start_routine)( void* ) )
{
pthread_t tid;
pthread_create( &tid, 0, start_routine, 0 );
return tid;
}
void Thread_waitUntilExit( pthread_t tid )
{
pthread_join( tid, 0 );
}
int main( void )
{
pthread_t tid1, tid2;
pthread_mutex_init( &mutex, 0 );
tid1 = Thread_create( thread1 );
tid2 = Thread_create( thread2 );
Thread_waitUntilExit( tid1 );
Thread_waitUntilExit( tid2 );
pthread_mutex_destroy( &mutex );
return 0;
}
void* thread1( void* pParam )
{
int i;
while( 1 )
{
printf( "Here is thread1.\\n" );
pthread_mutex_lock( &mutex );
printf( "count1:" );
for( i = 0; i < 10; i++ )
{
printf( "%d:", count1 );
count1++;
}
printf( "\\n" );
sleep( 1 );
pthread_mutex_unlock( &mutex );
printf( "count2:" );
for( i = 0; i < 10; i++ )
{
printf( "%d:", count2 );
count2++;
}
printf( "\\n" );
sleep( 1 );
}
}
void* thread2( void* pParam )
{
int i;
while( 1 )
{
printf( "Here is thread2.\\n" );
pthread_mutex_lock( &mutex );
count1 = 0;
sleep( 1 );
pthread_mutex_unlock( &mutex );
count2 = 0;
sleep( 1 );
}
}
| 1
|
#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);
}
void parent(void)
{
printf("parent unlocking locks...\\n");
pthread_mutex_unlock(&lock1);
}
void child(void)
{
printf("child unlocking locks...\\n");
pthread_mutex_unlock(&lock1);
}
void prepare1(void)
{
printf("preparing locks... 1\\n");
pthread_mutex_lock(&lock2);
}
void parent1(void)
{
printf("parent unlocking locks...1\\n");
pthread_mutex_unlock(&lock2);
}
void child1(void)
{
printf("child unlocking locks...1\\n");
pthread_mutex_unlock(&lock2);
}
void *thr_fn(void* arg)
{
printf("thread started...\\n");
pause();
return 0;
}
int main(void)
{
int err;
pid_t pid;
pthread_t tid;
if((err=pthread_atfork(prepare,parent,child))!=0)
err_exit(err,"can't install fork handlers");
if((err=pthread_atfork(prepare1,parent1,child1))!=0)
err_exit(err,"can't install fork handlers");
err=pthread_create(&tid,0,thr_fn,0);
if(err!=0)
err_exit(err,"can't create thread");
sleep(2);
printf("parent about to fork...\\n");
if((pid=fork())<0)
err_quit("fork failed");
else if(pid==0)
printf("child returned from fork\\n");
else
printf("parent returned from fork\\n");
return 0;
}
| 0
|
#include <pthread.h>
void try_reconnect(struct asd_pool* pool, int sockfd) {
int fdi;
for(fdi = 0; fdi < pool->num_connections; fdi++) {
if(pool->connections[fdi].fd == sockfd) {
close(pool->connections[fdi].fd);
pool->connections[fdi].fd = connect_to_server(pool->host.hostname, pool->host.port);
sockfd = pool->connections[fdi].fd;
log("[ERROR][POOL] Socket died, attempted a reconnect with FD %d", sockfd);
struct obj_header head;
head.op = OP_NONE;
int status = send(sockfd, &head, sizeof(head), MSG_NOSIGNAL);
if(status < 0) {
log("[ERROR][POOL] Host is DEAD, result of send(NOOP) is %d", status);
close(pool->connections[fdi].fd);
pthread_mutex_unlock(&pool->connections[fdi].mutex);
pool->connections[fdi].fd = -1;
pool->alive = 0;
pool->invalidate = 1;
}
return;
}
}
}
struct asd_pool* create_pool(struct asd_host host, int num_connections) {
struct asd_pool* pool = malloc(sizeof(struct asd_pool));
log("[INIT][POOL] Created a Connection Pool %p", pool);
pool->num_connections = num_connections;
pool->connections = malloc(sizeof(struct asd_connection) * num_connections);
pool->host = host;
pool->alive = 1;
pool->invalidate = 0;
int i;
for(i = 0; i < num_connections; i++) {
pool->connections[i].available = 1;
int fd = connect_to_server(host);
pool->connections[i].fd = fd;
pthread_mutex_init(&pool->connections[i].mutex, 0);
log("[INIT][POOL] Pool connection has file descriptor %d", pool->connections[i].fd);
}
pthread_mutex_init(&pool->mutex, 0);
return pool;
};
int get_connection_b(struct asd_pool* pool) {
char nbuf[1];
if(pool->alive == 0) {
log("[INFO][POOL] Connection pool is not responsive. Attempting Reconnect.");
int i;
for(i = 0; i < pool->num_connections; i++) {
pool->connections[i].available = 1;
int fd = connect_to_server(pool->host);
struct obj_header head;
head.op = OP_NONE;
int status = send(fd, &head, sizeof(head), MSG_NOSIGNAL);
if(status >= 0) {
log("[INFO][POOL] Host is ALIVE, open FD = %d, result of send(NOOP) is %d", fd, status);
recv(fd, nbuf, sizeof(char), 0);
pool->connections[i].fd = fd;
pool->alive = 1;
pool->invalidate = 0;
}
}
}
if(pool->alive == 0)
return -1;
log("[INFO][POOL] Scanning %d Connections in Pool %p", pool->num_connections, pool);
int i, fd = -1;
while(fd < 0) {
for(i = 0; i < pool->num_connections; i++) {
log("[INFO][POOL] Trying lock on Connection %d", i);
int trylock = pthread_mutex_trylock(&pool->connections[i].mutex);
if(trylock == 0) {
fd = pool->connections[i].fd;
break;
}
}
}
return fd;
};
int release_connection(struct asd_pool* pool, int fd) {
log("[INFO][POOL] Release a Pool FD %d", fd);
pthread_mutex_lock(&pool->mutex);
int i;
for(i = 0; i < pool->num_connections; i++) {
if(pool->connections[i].fd == fd) {
pool->connections[i].available = 1;
pthread_mutex_unlock(&pool->connections[i].mutex);
break;
}
}
pthread_mutex_unlock(&pool->mutex);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond34;
volatile int t34 = 0;
void *T1 (void * tid) {
printf("tudo bem?\\n");
pthread_mutex_lock(&mutex);
t34++;
if(t34 == 2) { pthread_cond_broadcast(&cond34); }
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void *T2 (void * tid) {
printf("hola!\\n");
pthread_mutex_lock(&mutex);
t34++;
if(t34 == 2) { pthread_cond_broadcast(&cond34); }
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void *T3 (void * tid) {
pthread_mutex_lock(&mutex);
if (t34 != 2) { pthread_cond_wait(&cond34, &mutex); }
pthread_mutex_unlock(&mutex);
printf("ate mais tarde.\\n");
pthread_exit(0);
}
void *T4 (void * tid) {
pthread_mutex_lock(&mutex);
if (t34 != 2) { pthread_cond_wait(&cond34, &mutex); }
pthread_mutex_unlock(&mutex);
printf("tchau!\\n");
pthread_exit(0);
}
int main(int argc, char const *argv[]) {
void *T[4];
pthread_t threads[4];
int i;
for (i = 0; i < 4; ++i) {
if ( (T[i] = malloc(sizeof(void))) == 0 ) {
printf("--ERRO: malloc()\\n"); exit(-1);
}
}
T[0] = T1, T[1] = T2, T[2] = T3, T[3] = T4;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond34, 0);
for (i = 0; i < 4; ++i) {
if ( pthread_create(&threads[i], 0, T[i], 0) ) {
printf("--ERRO: pthread_create()\\n"); exit(-1);
}
}
for (i = 0; i < 4; ++i) {
if ( pthread_join(threads[i], 0) ) {
printf("--ERRO: pthread_join()\\n"); exit(-1);
}
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond34);
return 0;
}
| 0
|
#include <pthread.h>
long globalCntr;
long allUpdates;
int doSomeMath(int inVal){
double d = atan2((double) inVal,0.1);
d=log(d);
int q=(int)ceil(d);
return 1;
}
int floatOperations(struct evaluatorStat *gg){
float f1 = .4444;
float f2 = .621678;
for(int i = 0; i<gg->NrOfWork ; i++){
f1=f1*f2;
}
gg->stop=clock();
}
int dummyfunc(void *empty) {
empty=malloc(1);
printf("scheduler set ? !\\n");
return empty;
}
int synchFuncer(struct evaluatorStat *gg) {
for (int i = 0; i < gg->NrOfWork; ++i)
{
int calc=doSomeMath(55);
pthread_mutex_lock(gg->lock);
globalCntr=globalCntr+1;
pthread_mutex_unlock(gg->lock);
allUpdates++;
}
gg->stop=clock();
}
void printdiff(struct evaluatorStat *gg) {
printf("time taken for thread %d : %d\\n",gg->id, gg->stop-gg->start );
}
void calculateAvg(struct evaluatorStat *gg[],int length){
int avg=0;
for(int i = 0;i<length;i++){
avg+=gg[i]->stop - gg[i]->start;
}
printf("AVG : %d",avg /length);
}
int main ( int argc , char *argv[] ) {
int op=0;
globalCntr=0;
allUpdates=0;
char *testtype="synch";
ttype t = SYNCH;
schedulerType sched = SCHED_FIFO;
int noOfTimes=100;
struct sched_param *sp = malloc(sizeof(struct sched_param));
sp->sched_priority=99;
const struct sched_param *ss= sp;
while((op = getopt(argc,argv,"S:n:slfe")) != -1) {
switch(op) {
case 'n':
noOfTimes=atoi(optarg);
printf("n %s\\n", optarg);
break;
case 's':
t=SYNCH;
break;
case 'l':
t=LOAD;
break;
case 'f':
t=FLOATOPS;
break;
case 'e':
t=EMPTYLOOP;
break;
case 'S':
sched = SCHED_RR;
int sSet=sched_setscheduler(0,SCHED_FIFO, ss);
printf("Set Scheduler %d\\n",sSet);
if(sSet<0)
;
break;
default:
printf("DEFAULT %s\\n", optarg);
break;
}
}
int results[noOfTimes] ;
pthread_mutex_t newLock ;
if(pthread_mutex_init(&newLock,0)<0) {
fprintf(stderr, "Lock not initiated\\n");
}
struct evaluatorStat *ct[noOfTimes];
for(int i =0;i<noOfTimes;i++){
ct[i]= malloc(sizeof(struct evaluatorStat)*noOfTimes);
}
for(int i=0;i<noOfTimes;i++) {
ct[i]->id=i;
ct[i]->clock=20;
ct[i]->NrOfWork=noOfTimes;
ct[i]->lock = &newLock;
ct[i]->funcPtr=&synchFuncer;
switch(t) {
case SYNCH:
ct[i]->funcPtr=&synchFuncer;
break;
case LOAD:
ct[i]->funcPtr=&synchFuncer;
break;
case FLOATOPS:
ct[i]->funcPtr=&floatOperations;
break;
case EMPTYLOOP:
ct[i]->funcPtr=&synchFuncer;
break;
}
}
pthread_t theThreads[noOfTimes];
for (int i = 0; i < noOfTimes; ++i)
{
ct[i]->start=clock();
int q= pthread_create(&theThreads[i],0,ct[i]->funcPtr,ct[i]);
int bu= sched_setscheduler(q,SCHED_FIFO,ss);
printf("pthread created %d sched %d\\n",q, bu );
}
for (int i = 0; i < noOfTimes; ++i)
{
int q = pthread_join(theThreads[i],0);
}
for(int i=0;i<noOfTimes;i++) {
printdiff(ct[i]);
}
calculateAvg(ct,noOfTimes);
fprintf(stdout, "nr of updates for globalCntr: %d, and globalCntr itself: %d\\n",allUpdates,globalCntr );
return 0;
}
| 1
|
#include <pthread.h>
longArchFix sum, numbersPerProcess;
pthread_mutex_t sum_mutex;
static void usage(char *prog_name, char *msg)
{
if (msg != 0)
fputs(msg, stderr);
fprintf(stderr, "Usage: %s [options]\\n", prog_name);
fprintf(stderr, "Options are:\\n");
fprintf(stderr, "\\t%s", "--im <numeric> Set intervcal maximum\\n");;
fprintf(stderr, "\\t%s", "--tmin <numeric> Set the minimum number of threads\\n");;
fprintf(stderr, "\\t%s", "--tmax <numeric> Set the maximum number of threads\\n");;
fprintf(stderr, "\\t%s", "--showlicense List license message\\n");;
fprintf(stderr, "\\t%s", "--hidelicense Don't list license message\\n");;
fprintf(stderr, "Defaults: %s --im 100000 --tmin 1 --tmax 8 --showlicense\\n", prog_name);
exit(1);
}
int isPrime(longArchFix num) {
if (num<3) {
return 0;
}
longArchFix i;
for(i=2;i<num;i++)
{
if(num%i==0)
return 0;
}
return 1;
}
longArchFix primeCountInterval(longArchFix from, longArchFix to) {
longArchFix primecount = 0;
longArchFix i=0;
for(i=from; i<=to; i++) {
if (isPrime(i)>0) {
primecount++;
}
}
return primecount;
}
void *primeCountPrint(void *arg) {
longArchFix i = (longArchFix)arg;
longArchFix pc = primeCountInterval(numbersPerProcess*i,numbersPerProcess*(i+1));
pthread_mutex_lock(&sum_mutex);
sum += pc;
pthread_mutex_unlock(&sum_mutex);
pthread_exit(0);
}
void calculateThreaded(longArchFix threadcount, longArchFix until) {
sum = 0;
numbersPerProcess = ceill((float)until/(float)threadcount);
longArchFix i;
pthread_t* threads;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
int rc;
threads = (pthread_t*)malloc(sizeof(pthread_t)*(threadcount));
struct timeval tv1, tv2;
gettimeofday(&tv1, 0);
for (i=0; i<threadcount; i++) {
rc = pthread_create(&threads[i], &attr, primeCountPrint, (void*)i);
if (rc!=0) {
printf("Couldn't create thread!\\n");
exit(-1);
}
}
void *status;
pthread_attr_destroy(&attr);
for(i=0; i<threadcount; i++) {
pthread_join(threads[i], &status);
}
gettimeofday(&tv2, 0);
double time_spent = (double) (tv2.tv_usec - tv1.tv_usec)/1000000 +(double) (tv2.tv_sec - tv1.tv_sec);
printf("%fs - %ld threads [%ld,%ld] = %ld primes found\\n", time_spent, threadcount, 0L, numbersPerProcess*threadcount,sum+1);
free(threads);
}
int main(int argc, char *argv[])
{
longArchFix until = 100000;
int threadstart = 1;
int threadcount = 8;
static int listlicense = 1;
static struct option long_options[] = {
{"showlicense", no_argument, &listlicense, 1},
{"hidelicense", no_argument, &listlicense, 0},
{"im", required_argument, 0, 'i'},
{"tmin", required_argument, 0, 'c'},
{"tmax", required_argument, 0, 'f'}
};
int opt;
int option_index = 0;
while ((opt = getopt_long(argc, argv, "i:c:f:",long_options, &option_index))!=-1) {
switch (opt) {
case 0: break;
case 'i':
until = atol(optarg);
if (until<2) {
usage(argv[0], "\\nInvalid --im value!\\n\\n");
}
break;
case 'c':
threadstart = atol(optarg);
if (threadstart<1) {
usage(argv[0], "\\nInvalid --tmin value!\\n\\n");
}
break;
case 'f':
threadcount = atol(optarg);
if (threadcount<1) {
usage(argv[0], "\\nInvalid --tmax value!\\n\\n");
}
break;
default: usage(argv[0], 0);
}
}
if (threadcount<threadstart) {
usage(argv[0], "\\nInvalid --tmax value!\\n--tmax should be greater or equal then --tmin\\n\\n");
}
printf("PrimeBenchc %s\\n", "v0.3");
if (listlicense) {
printf("All primebenchc code is Copyright 2013 by Nyiro Zoltan-Csaba.\\n\\nThis program is free software; you can redistribute it and/or modify\\nit under the terms of the GNU General Public License as published by\\nthe Free Software Foundation; either version 2 of the License, or (at\\nyour option) any later version.\\n\\nThis program is distributed in the hope that it will be useful, but\\nWITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\\nor FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\\nfor more details.\\n\\n");
printf("You should have received a copy of the GNU General Public License\\nalong with this program as the file LICENSE.txt; if not, please see\\nhttp://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.\\n\\n\\n");
}
printf("The calculations are made up to %d thread(s).\\n", threadcount);
int i;
for (i=threadstart; i<=threadcount; i++) {
sum = 0;
calculateThreaded(i,until);
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t fork_mutex[3];
pthread_mutex_t eat_mutex;
main()
{
int i;
pthread_t diner_thread[3];
int dn[3];
void *diner();
pthread_mutex_init(&eat_mutex, 0);
for (i=0;i<3;i++)
pthread_mutex_init(&fork_mutex[i], 0);
for (i=0;i<3;i++){
dn[i] = i;
pthread_create(&diner_thread[i],0,diner,&dn[i]);
}
for (i=0;i<3;i++)
pthread_join(diner_thread[i],0);
pthread_exit(0);
}
void *diner(int *i)
{
int v;
int eating = 0;
printf("I'm diner %d\\n",*i);
v = *i;
while (eating < 5) {
printf("%d is thinking\\n", v);
sleep( v/2);
printf("%d is hungry\\n", v);
pthread_mutex_lock(&eat_mutex);
pthread_mutex_lock(&fork_mutex[v]);
pthread_mutex_lock(&fork_mutex[(v+1)%3]);
pthread_mutex_unlock(&eat_mutex);
printf("%d is eating\\n", v);
eating++;
sleep(1);
printf("%d is done eating\\n", v);
pthread_mutex_unlock(&fork_mutex[v]);
pthread_mutex_unlock(&fork_mutex[(v+1)%3]);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
long countin = 0;
long thread_iteration_number = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* worker(){
long i;
long countin_t = 0;
unsigned int globalSeed = rand();
for (i = 0; i < thread_iteration_number; i++){
double x = rand_r(&globalSeed) / ((double)32767 + 1) * 2.0 - 1.0;
double y = rand_r(&globalSeed) / ((double)32767 + 1) * 2.0 - 1.0;
if (((x*x) + (y*y)) < 1){
countin_t++;
}
}
pthread_mutex_lock(&mutex);
countin = countin + countin_t;
pthread_mutex_unlock(&mutex);
}
int main(int argc, const char *argv[]){
if (argc != 3){
fprintf(stderr, "Kullanim: ./name <iterasyon sayisi> <thread sayisi>\\n");
exit(1);
}
long total_iteration_number = atol(argv[1]);
int thread_number = atoi(argv[2]);
thread_iteration_number = total_iteration_number/thread_number;
pthread_t *threads = malloc(thread_number * sizeof(pthread_t));
pthread_attr_t attr;
pthread_attr_init(&attr);
int i;
for (i = 0; i < thread_number; i++) {
pthread_create(&threads[i], &attr, worker, (void *) 0);
}
for (i = 0; i < thread_number; i++) {
pthread_join(threads[i], 0);
}
pthread_mutex_destroy(&mutex);
free(threads);
double pi = (4*(double)countin) / ((double)thread_number*(double)thread_iteration_number);
printf("pi: %f\\n", pi);
return 0;
}
| 0
|
#include <pthread.h>
static int buffer[8];
static int n = 0;
static pthread_mutex_t lock;
static pthread_mutex_t mutex1;
static pthread_mutex_t mutex2;
pthread_cond_t filaCheia = PTHREAD_COND_INITIALIZER;
pthread_cond_t filaVazia = PTHREAD_COND_INITIALIZER;
void produtor(void)
{
int i = 0;
while(i < 12)
{
if(n == 8)
{
pthread_cond_wait(&filaCheia, &mutex1);
}
pthread_mutex_lock(&lock);
buffer[n] = i;
printf("%d produzido\\n", buffer[n]);
n++;
pthread_cond_signal (&filaVazia);
pthread_mutex_unlock(&lock);
i++;
sleep(1);
}
printf("fim da produção\\n");
return;
}
void consumidor(void* id)
{
int i = 0, t;
printf("consumidor %d começou\\n", (int) id);
while(i < 4)
{
if(n == 0)
{
pthread_cond_wait(&filaVazia, &mutex2);
}
pthread_mutex_lock(&lock);
printf("%d[%d] consumido.\\n", buffer[0], (int)id);
for(t = 0; t < n -1; t++)
{
buffer[t] = buffer[t+1];
}
n--;
pthread_cond_signal (&filaCheia);
pthread_mutex_unlock(&lock);
i++;
sleep(2);
}
printf("fim do consumo\\n");
return;
}
int main(void)
{
int i;
pthread_t threads[1 + 3];
for(i = 0; i < 1; i++)
{
pthread_create(&threads[i], 0, produtor, 0);
}
for(; i < 3 + 1; i++)
{
pthread_create(&threads[i], 0, consumidor, (void*) i);
}
for(i = 0; i < 1 + 3; i++)
{
pthread_join(threads[i],0);
}
printf("final\\n");
return 0;
}
| 1
|
#include <pthread.h>
void *producer ();
void *consumer ();
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int *pipeClean;
int num_pairs, num_transfers;
struct thread_data {
char pipeName[20];
int pairNum;
};
int main(int argc, char **argv) {
int i, t1, t2, num_threads;
char namebuf[20], numbuf[10], c;
static pthread_t *threads;
struct thread_data *thread_args;
void *ret;
num_pairs = num_transfers = 0;
while (1) {
c = getopt(argc, argv, "p:t:");
if (c == -1) {
break;
}
switch (c) {
case 'p':
num_pairs = atoi(optarg);
break;
case 't':
num_transfers = atoi(optarg);
break;
default:
printf("Unknown option %c. Valid options are:\\n"
"-p <number of pairs of named pipes to create>\\n"
"-t <number of transfers to make for each thread pair>\\n",
optopt);
exit(1);
}
}
if (!num_pairs || !num_transfers) {
printf("You must specify how many pipes and transfers on each pipe are to be made.\\n"
"namepipe -p [NUM_PIPES] -t [NUM_TRANSFERS]\\n");
}
num_threads = 2 * num_pairs;
threads = malloc(sizeof(pthread_t) * num_threads);
if (!threads){
fprintf(stderr, "can't initialise threads\\n");
exit(1);
}
pipeClean = malloc(sizeof(int) * num_pairs);
if (!pipeClean) {
fprintf(stderr, "can't initialize pipeClean\\n");
exit(1);
}
for (i=0; i<num_pairs; i++) {
t2 = (i*2)+1;
t1 = t2-1;
thread_args = malloc(sizeof(struct thread_data));
sprintf(numbuf, "%d", i);
strcat(strcpy(namebuf, "name.out."), numbuf);
strcpy(thread_args->pipeName, namebuf);
thread_args->pairNum = i;
if (mkfifo(namebuf,0666) < 0) {
fprintf(stderr, "creation of named pipe %s failed. Exiting...\\n", namebuf);
exit(1);
}
pipeClean[i] = 1;
if (pthread_create(&threads[t1],0,producer,(void *) thread_args)){
fprintf(stderr, "failed creating writing thread");
exit(1);
}
if (pthread_create(&threads[t2],0,consumer,(void *) thread_args)){
fprintf(stderr, "failed creating reading thread");
exit(1);
}
}
for (i=0; i<num_threads; i++) {
pthread_join(threads[i], &ret);
}
if (num_threads)
system("rm -f name.out.*");
return 0;
}
void *producer(void *thread_args) {
int fd,i,size;
struct thread_data *data = (struct thread_data *) thread_args;
if ((fd=open(data->pipeName,O_RDWR)) < 0){
fprintf(stderr, "opening named pipe for writing failed");
exit(1);
}
printf("producer for pipename %s will now write %d \\"%s\\" messages to the pipe\\n", data->pipeName, num_transfers, "I am iron man");
for (i=0;i<num_transfers;){
pthread_mutex_lock(&mutex);
if (pipeClean[data->pairNum]) {
if ((size=write(fd,"I am iron man",strlen("I am iron man"))) < 0){
fprintf(stderr, "writing to the named pipe failed");
exit(1);
}
pipeClean[data->pairNum] = 0;
i++;
}
pthread_mutex_unlock(&mutex);
}
printf("producer for pair %d is done\\n", data->pairNum);
close(fd);
return 0;
}
void *consumer(void *thread_args) {
int fd,i,size;
struct thread_data *data = (struct thread_data *) thread_args;
char buf[strlen("I am iron man")];
if ((fd=open(data->pipeName,O_RDWR)) < 0) {
fprintf(stderr, "opening named pipe for reading failed");
exit(1);
}
printf("consumer for pipename %s starting\\n", data->pipeName);
for(i=0;i<num_transfers;) {
pthread_mutex_lock(&mutex);
if (!pipeClean[data->pairNum]) {
if ((size=read(fd,buf,strlen("I am iron man"))) < 0) {
fprintf(stderr, "reading from the named pipe failed");
exit(1);
}
pipeClean[data->pairNum] = 1;
i++;
}
pthread_mutex_unlock(&mutex);
}
printf("consumer for pair %d is done\\n", data->pairNum);
close(fd);
free(data);
return 0;
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error() ;
int element[(20)];
int head;
int tail;
int amount;
} QType;
pthread_mutex_t m;
int __VERIFIER_nondet_int();
int stored_elements[(20)];
_Bool enqueue_flag, dequeue_flag;
QType queue;
int init(QType *q)
{
q->head=0;
q->tail=0;
q->amount=0;
}
int empty(QType * q)
{
if (q->head == q->tail)
{
printf("queue is empty\\n");
return (-1);
}
else
return 0;
}
int full(QType * q)
{
if (q->amount == (20))
{
printf("queue is full\\n");
return (-2);
}
else
return 0;
}
int enqueue(QType *q, int x)
{
q->element[q->tail] = x;
q->amount++;
if (q->tail == (20))
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == (20))
{
q->head = 1;
}
else
q->head++;
return x;
}
void *t1(void *arg)
{
int value, i;
pthread_mutex_lock(&m);
if (enqueue_flag)
{
for(
i=0; i<(20); i++)
{
value = __VERIFIER_nondet_int();
enqueue(&queue,value);
stored_elements[i]=value;
}
enqueue_flag=(0);
dequeue_flag=(1);
}
pthread_mutex_unlock(&m);
return 0;
}
void *t2(void *arg)
{
int i;
pthread_mutex_lock(&m);
if (dequeue_flag)
{
for(
i=0; i<(20); i++)
{
if (empty(&queue)!=(-1))
if (!dequeue(&queue)==stored_elements[i]) {
ERROR:
__VERIFIER_error();
}
}
dequeue_flag=(0);
enqueue_flag=(1);
}
pthread_mutex_unlock(&m);
return 0;
}
int main(void)
{
pthread_t id1, id2;
enqueue_flag=(1);
dequeue_flag=(0);
init(&queue);
if (!empty(&queue)==(-1)) {
ERROR:
__VERIFIER_error();
}
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, &queue);
pthread_create(&id2, 0, t2, &queue);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int source = 0;
void *t1_handler(void *arg)
{
int i;
int ret;
printf("1\\n");
for(i = 0; i < 1000000; i++){
pthread_mutex_lock(&mutex1);
source++;
again:
ret = pthread_mutex_trylock(&mutex);
if(ret != 0){
printf("fail to lock mutex %d\\n", ret);
pthread_mutex_unlock(&mutex1);
sleep(1);
pthread_mutex_lock(&mutex1);
goto again;
}
(*(int *)arg)++;
pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&mutex1);
}
}
void *t2_handler(void *arg)
{
int i;
printf("2\\n");
for(i = 0; i < 1000000; i++){
pthread_mutex_lock(&mutex);
(*(int *)arg)++;
pthread_mutex_lock(&mutex1);
source++;
pthread_mutex_unlock(&mutex1);
pthread_mutex_unlock(&mutex);
}
}
void *t3_handler(void *arg)
{
int i;
printf("3\\n");
for(i = 0; i < 1000000; i++){
pthread_mutex_lock(&mutex);
(*(int *)arg)++;
pthread_mutex_lock(&mutex1);
source++;
pthread_mutex_unlock(&mutex1);
pthread_mutex_unlock(&mutex);
}
}
int main(void)
{
pthread_t t1, t2, t3;
int no = 0;
pthread_create(&t1, 0, t1_handler, &no);
pthread_create(&t2, 0, t2_handler, &no);
pthread_create(&t3, 0, t3_handler, &no);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_join(t3, 0);
printf("no = %d\\n", no);
printf("source = %d\\n", source);
return 0;
}
| 0
|
#include <pthread.h>
void *constructor_refresh_thread(void *e)
{
(void)e;
while (1)
{
sgt_constructor()->select = !sgt_constructor()->select;
pthread_mutex_lock(&sgt_constructor()->mutex_preview);
constructor_calcul();
pthread_mutex_unlock(&sgt_constructor()->mutex_preview);
usleep(100000);
}
return (0);
}
| 1
|
#include <pthread.h>
int works_count = 0;
pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t job_queue_count;
void task(const int* value){
printf(" [work] | now working on %d.\\n", *value);
}
struct job {
struct job* next;
void (*func)(const int*);
};
struct job* job_queue;
void process_job(struct job* jb, const int* value){
printf(" [prep] | preparing to work.\\n");
jb->func(value);
}
void initialize_job_queue() {
job_queue = 0;
sem_init(&job_queue_count, 0, 0);
}
void* thread_function(void* arg) {
while (1) {
struct job* next_job;
sem_wait(&job_queue_count);
pthread_mutex_lock(&job_queue_mutex);
next_job = job_queue;
job_queue = job_queue->next;
pthread_mutex_unlock(&job_queue_mutex);
process_job(next_job, &works_count);
works_count++;
free(next_job);
}
return 0;
}
void enqueue_job() {
struct job* new_job;
new_job = (struct job*)malloc(sizeof(struct job));
pthread_mutex_lock(&job_queue_mutex);
new_job->next = job_queue;
job_queue = new_job;
job_queue->func = &task;
sem_post(&job_queue_count);
pthread_mutex_unlock(&job_queue_mutex);
}
void main(int argc, char* argv[]){
int tasks = 0;
int rnd_value = 0;
pthread_t thread;
pthread_create(&thread, 0, &thread_function, 0);
while(1){
srand(time(0) + rnd_value);
rnd_value = rand()%2;
if( rnd_value == 0){
enqueue_job();
sem_getvalue(&job_queue_count, &tasks);
printf(" [main] | new task was added. Tasks now : %d.\\n", tasks);
}
usleep(1000);
}
pthread_join(thread, 0);
return;
}
| 0
|
#include <pthread.h>
struct msg {
struct msg *m_next;
};
struct msg *workq;
pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;
void process_msg(void)
{
struct msg *mp;
for (;;) {
pthread_mutex_lock(&qlock);
while (workq == 0)
pthread_cond_wait(&qready, &qlock);
mp = workq;
workq = mp->m_next;
pthread_mutex_unlock(&qlock);
}
}
void enqueue_msg(struct msg *mp)
{
pthread_mutex_lock(&qlock);
mp->m_next = workq;
workq = mp;
pthread_mutex_unlock(&qlock);
pthread_cond_signal(&qready);
}
| 1
|
#include <pthread.h>
void *philosopher (void *id);
void grab_chopstick (int,
int,
char *);
void down_chopsticks (int,
int);
int food_on_table ();
pthread_mutex_t chopstick[5];
pthread_t philo[5];
pthread_mutex_t food_lock;
int sleep_seconds = 0;
int main (int argn,char **argv)
{
int i;
if (argn == 2)
sleep_seconds = atoi (argv[1]);
pthread_mutex_init (&food_lock, 0);
for (i = 0; i < 5; i++)
pthread_mutex_init (&chopstick[i], 0);
for (i = 0; i < 5; i++)
pthread_create (&philo[i], 0, philosopher, (void*) i);
for (i = 0; i < 5; i++)
pthread_join (philo[i], 0);
return 0;
}
void *philosopher (void *num)
{
int id;
int i, left_chopstick, right_chopstick, f;
id = (int)num;
printf ("Philosopher %d is done thinking and now ready to eat.\\n", id);
right_chopstick = id;
left_chopstick = id + 1;
if (left_chopstick == 5)
left_chopstick = 0;
while (f = food_on_table ()) {
if (id == 1)
sleep (sleep_seconds);
grab_chopstick (id, right_chopstick, "right ");
grab_chopstick (id, left_chopstick, "left");
printf ("Philosopher %d: eating.\\n", id);
usleep (5000 * (50 - f + 1));
down_chopsticks (left_chopstick, right_chopstick);
}
printf ("Philosopher %d is done eating.\\n", id);
return (0);
}
int
food_on_table ()
{
static int food = 50;
int myfood;
pthread_mutex_lock (&food_lock);
if (food > 0) {
food--;
}
myfood = food;
pthread_mutex_unlock (&food_lock);
return myfood;
}
void
grab_chopstick (int phil,
int c,
char *hand)
{
pthread_mutex_lock (&chopstick[c]);
printf ("Philosopher %d: got %s chopstick %d\\n", phil, hand, c);
}
void
down_chopsticks (int c1,
int c2)
{
pthread_mutex_unlock (&chopstick[c1]);
pthread_mutex_unlock (&chopstick[c2]);
}
| 0
|
#include <pthread.h>
static time_t time_orig;
static time_t time_interval;
static int bool_black = 0;
static pthread_mutex_t mutex_screen = PTHREAD_MUTEX_INITIALIZER;
static char screen_light_buf[4];
static int screen_set_time(time_t time)
{
return_val_if_fail(time > 0, -1);
miui_debug("set time %ld\\n", time);
time_orig = time;
return 0;
}
int screen_set_black(int black)
{
pthread_mutex_lock(&mutex_screen);
int fd = open(acfg()->brightness_path, O_WRONLY);
if (fd <= 0)
{
miui_error("open %s failed!\\n", acfg()->brightness_path);
}
else
{
bool_black = black;
if (bool_black)
{
if (write(fd,"0", 1) <= 0)
{
miui_error("%s write error %s", acfg()->brightness_path, strerror(errno));
}
}
else
{
miui_debug("screen_light_buf is %s\\n", screen_light_buf);
if (write(fd,screen_light_buf,strlen(screen_light_buf)) <= 0)
{
miui_error("%s write error %s", acfg()->brightness_path, strerror(errno));
}
}
close(fd);
}
pthread_mutex_unlock(&mutex_screen);
return 0;
}
int screen_is_black()
{
return bool_black;
}
int screen_set_light(int light)
{
return_val_if_fail(light > 10, -1);
return_val_if_fail(light <= 255, -1);
return_val_if_fail(0 <= snprintf(screen_light_buf,sizeof(screen_light_buf), "%d", light), -1);
return 0;
}
int screen_set_interval(int interval)
{
return_val_if_fail(interval > 0, -1);
time_interval = interval;
return 0;
}
static void *screen_black_thread(void *cookie)
{
while(1)
{
if (difftime(time((time_t *)0), time_orig) > time_interval)
{
if (0 == bool_black)
screen_set_black(1);
}
else if (0 != bool_black)
{
screen_set_black(0);
}
sleep(1);
}
return 0;
}
static pthread_t screen_thread_t;
static int screen_init()
{
time_interval = 120;
screen_set_light(60);
screen_set_time(time((time_t*)0));
screen_set_black(0);
pthread_create(&screen_thread_t, 0, screen_black_thread, 0);
pthread_detach(screen_thread_t);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
void prepare (void)
{
printf ("prepareing locks...\\n");
pthread_mutex_lock (&lock1);
pthread_mutex_lock (&lock2);
}
void parent (void)
{
printf ("parent unlocking locks...\\n");
pthread_mutex_unlock (&lock1);
pthread_mutex_unlock (&lock2);
}
void child (void)
{
printf ("child unlocking locks...\\n");
pthread_mutex_unlock (&lock1);
pthread_mutex_unlock (&lock2);
}
void *thr_fn (void *arg)
{
printf ("thread started...\\n");
pause ();
return (0);
}
int main (void)
{
int err;
pid_t pid;
pthread_t tid;
if ((err = pthread_atfork (prepare, parent, child)) != 0) {
err_exit (err, "cna't install fork handlers");
}
err = pthread_create (&tid, 0, thr_fn, 0);
if (err != 0) {
err_exit (err, "can't create thread");
}
sleep (2);
printf ("parent about to fork...\\n");
if ((pid = fork ()) < 0) {
err_quit ("fork failed\\n");
} else if (pid == 0) {
printf ("child returned from fork\\n");
} else {
printf ("parent return from fork\\n");
}
exit (0);
}
| 0
|
#include <pthread.h>
int ProcCurr[3][3];
int temp[3][3];
int Available[10];
int Max[3][3] = { {10,10,10},{10,10,10},{10,10,10} };
int Allocation[3][3] = { {1,2,3},{3,2,1},{1,1,1} };
int Need[3][3];
int counti = 0;
int countj = 0;
int threadsi = 3;
int threadsj = 3;
void *inc_count(void *r);
void *watch_count(void *r);
pthread_mutex_t mutex;
pthread_cond_t count_threshold_cv;
main(int argc, char *argv[])
{
pthread_t ProcCurr[3][3];
pthread_attr_t attr;
int retcode, i, j;
long r1 = 1,r2 = 2,r3 = 3;
if(pthread_mutex_init(&mutex, 0) < 0){
perror("Pthread_mutex_init error.");
exit(1);
}
else
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_create(&ProcCurr[0][0], &attr, watch_count, (void *)r1);
pthread_create(&ProcCurr[1][0], &attr, inc_count, (void *)r2);
pthread_create(&ProcCurr[2][0], &attr, inc_count, (void *)r3);
for(i=0; i<=threadsi; i++){
for(j=0; j<=threadsj; j++){
pthread_join(ProcCurr[i][j],0);
}
}
printf("Main: waited on %d, %d threads. Done.\\n", threadsi, threadsj);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit(0);
}
void *inc_count(void *r)
{
int i, j, n, m;
long my_id = (long)r;
for(i=0; i<10; i++){
for(j=0; j<10; j++){
Need[n][m] = Max[n][m] - Allocation[i][j];
printf("Allocation = %d, Need = %d\\n", Allocation[i][j], Need[n][m]);
}
pthread_mutex_lock(&mutex);
if(counti == 10 && countj == 10){
pthread_cond_signal(&count_threshold_cv);
printf("inc_count: thread %ld, Need = %d. Threshold reached.\\n",my_id, Need[n][m]);
}
printf("inc_count: thread %ld, Need = %d. Unlocking mutex.\\n", my_id, Need[n][m]);
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_exit(0);
watch_count(r);
}
void *watch_count(void *r)
{
long my_id = (long)r;
int n, m;
printf("Start watch_count: thread %ld\\n", my_id);
while(counti < 10 && countj <10)
{ pthread_mutex_lock(&mutex);
pthread_cond_wait(&count_threshold_cv, &mutex);
printf("watch_count: thread %ld, available = %d. Conditional Signal Received.\\n", my_id, Available[m]);
countj++;
printf("watch_count: thread %ld, Need now = %d.\\n", my_id, Need[counti][countj]);
}
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
struct range {
int begin;
int end;
};
int *array = 0;
int N = 0;
pthread_mutex_t queue_mutex;
pthread_cond_t queue_cond;
int completed = 0;
pthread_mutex_t completed_mutex;
bool is_completed() {
pthread_mutex_lock(&completed_mutex);
bool res = (completed == N);
pthread_mutex_unlock(&completed_mutex);
return res;
}
void report_completed(int num) {
pthread_mutex_lock(&completed_mutex);
completed += num;
pthread_mutex_unlock(&completed_mutex);
}
void swap(int a, int b)
{
if (a == b) return;
int tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}
void bubble_sort(int low, int high)
{
if (low > high) return;
int i, j;
for (i = low; i <= high; i++)
for (j = i+1; j <= high; j++)
if (array[i] > array[j])
swap(i, j);
report_completed(high-low+1);
}
int partition(int low, int high)
{
int pivot = array[low], middle = low, i;
swap(low, high);
for(i=low; i<high; i++) {
if(array[i] < pivot) {
swap(i, middle);
middle++;
}
}
swap(high, middle);
report_completed(1);
return(middle);
}
void submit(int low, int high) {
struct range *r = (struct range*) malloc(sizeof(struct range));
r->begin = low;
r->end = high;
pthread_mutex_lock(&queue_mutex);
enqueue(r);
pthread_cond_signal(&queue_cond);
;
pthread_mutex_unlock(&queue_mutex);
}
void quicksort(int low, int high)
{
if (high - low < 10) {
bubble_sort(low, high);
return;
}
int middle = partition(low, high);
submit(low, middle-1);
quicksort(middle+1, high);
}
void worker(long rank) {
struct range *r = 0;
while (!is_completed()) {
;
pthread_mutex_lock(&queue_mutex);
while (empty() && !is_completed()) {
;
pthread_cond_wait(&queue_cond, &queue_mutex);
}
r = dequeue();
pthread_mutex_unlock(&queue_mutex);
if (r != 0) {
;
quicksort(r->begin, r->end);
free(r);
}
}
pthread_cond_signal(&queue_cond);
;
}
void* child_proc(void *ip)
{
worker((long)ip);
return 0;
}
int main(int argc, char **argv)
{
int i, j;
int num_threads;
char ans;
pthread_t *thread_id = 0;
if((argc != 2) && (argc != 3))
{
printf("Usage: qsort_queue N [num_threads]\\n");
exit(0);
}
N = atoi(argv[1]);
if(N < 2)
{
printf("N must be greater than 2\\n");
exit(0);
}
if(argc == 2)
{
num_threads = 1;
}
else
{
num_threads = atoi(argv[2]);
if(num_threads < 1)
{
printf("num_threads must be greater than 1\\n");
exit(0);
}
}
printf("Quicksort with %d threads (queue version), array_size = %d\\n", num_threads, N);
pthread_mutex_init(&queue_mutex, 0);
pthread_cond_init(&queue_cond, 0);
pthread_mutex_init(&completed_mutex, 0);
if(num_threads > 1) {
thread_id = (pthread_t*)malloc((num_threads-1)*sizeof(pthread_t));
if (thread_id == 0) {
printf("Lack of memory when creating threads\\n");
goto QUIT_POINT;
}
for(i=1;i<num_threads;i++)
{
pthread_create(&thread_id[i-1],0,child_proc,(void*)i);
;
}
}
array = (int *) malloc(sizeof(int) * N);
if (array == 0) {
printf("Lack of memory when allocating data buffer\\n");
goto QUIT_POINT;
}
for (i=0; i<N; i++)
array[i] = i+1;
srand(time(0));
for (i=0; i<N; i++) {
j = (rand()*1./32767)*(N-1);
swap(i, j);
}
submit(0, N-1);
worker (0);
if(num_threads > 1) {
for(i=1;i<num_threads;i++)
{
pthread_join(thread_id[i-1],0);
}
}
QUIT_POINT:
if (thread_id != 0) {
free(thread_id);
thread_id = 0;
}
if (array != 0) {
free(array);
array = 0;
}
return 0;
}
| 0
|
#include <pthread.h>
long int sum;
pthread_mutex_t m;
void *runner(void * param);
main(int argc, char *argv[])
{
int num_threads, i;
pthread_t tid[10];
pthread_attr_t attr;
if (argc != 2) {
fprintf(stderr, "usage: a.out <integer value>\\n");
exit(-1);
}
if (atoi(argv[1]) <= 0) {
fprintf(stderr,"%d must be > 0\\n", atoi(argv[1]));
exit(-2);
}
if (atoi(argv[1]) > 10) {
fprintf(stderr,"%d must be <= %d\\n", atoi(argv[1]), 10);
exit(-3);
}
num_threads = atoi(argv[1]);
printf("The number of threads is %d\\n", num_threads);
pthread_attr_init(&attr);
for (i=0; i<num_threads; i++) {
pthread_create(&(tid[i]), &attr, runner, (void *) i);
printf("Creating thread number %d, tid=%lu \\n", i, tid[i]);
}
for (i=0; i<num_threads; i++) {
pthread_join(tid[i],0);
}
printf("\\nsum = %ld\\n", sum);
}
void *runner(void * param)
{
pthread_mutex_lock(&m);
int i;
int threadnumber = (int) param;
for (i=1; i<=10; i++){
sum += i;
printf("Thread number [%d] i= (%d) sum=(%ld)\\n ", threadnumber, i,sum);
}
pthread_mutex_unlock(&m);
}
| 1
|
#include <pthread.h>
struct bbq_node
{
struct bbq_node *next;
int value;
};
struct bbq_node *head=0;
struct bbq_node *tail=0;
struct bbq_node *p_ptr=0;
struct bbq_node *c_ptr=0;
unsigned int N, P, C, X, Dequeue, Ptime, con_time;
sem_t emptyCount;
sem_t fullCount;
int bbq_counter = 0;
int buffer_count=0;
pthread_mutex_t sharedLock;
void init_bbq(unsigned int N)
{
int i;
struct bbq_node *tmp;
struct bbq_node *node= (struct bbq_node *)malloc(sizeof(struct bbq_node));
head= node;
tmp=head;
head->next= 0;
for (i=1 ; i< N; i++)
{
node= (struct bbq_node *)malloc(sizeof(struct bbq_node));
tmp->next= node;
tmp= node;
}
tmp->next= head;
}
void producer(int start, int end) {
int i, semValue;
for (i=0; i< X; i++)
{
sem_wait(&emptyCount);
pthread_mutex_lock(&sharedLock);
bbq_counter++;
p_ptr->value= bbq_counter;
p_ptr= p_ptr->next;
buffer_count++;
semValue= buffer_count;
fprintf(stderr, "[PRODUCER] Buffer count increased to %d Value: %d\\n", semValue, bbq_counter);
pthread_mutex_unlock(&sharedLock);
sem_post(&fullCount);
sleep(Ptime);
}
}
void consumer()
{
int i, qValue, semValue;
for (i=0; i < Dequeue; i++)
{
sem_wait(&fullCount);
pthread_mutex_lock(&sharedLock);
qValue= c_ptr->value;
c_ptr= c_ptr->next;
buffer_count--;
semValue= buffer_count;
fprintf(stderr, "[CONSUMER] Buffer count decreased to %d Value: %d\\n", semValue, qValue);
pthread_mutex_unlock(&sharedLock);
sem_post(&emptyCount);
sleep(con_time);
}
}
int main(int argc, char *argv[]) {
time_t start_time, end_time;
struct tm *ptr;
int i, retvalue;
int debuga=0;
pthread_mutex_init(&sharedLock, 0);
if (argc< 7)
{
perror("Requires following arguments: N, P, C, X, Ptime, Ctime \\n");
exit(-1);
}
N = atoi(argv[1]);
P = atoi(argv[2]);
C = atoi(argv[3]);
X = atoi(argv[4]);
Ptime = atoi(argv[5]);
con_time = atoi(argv[6]);
Dequeue = P * X / C;
init_bbq(N);
p_ptr= head;
c_ptr= head;
sem_init(&emptyCount, 0, N);
sem_init(&fullCount, 0, 0);
sem_getvalue(&emptyCount, &debuga);
fprintf(stderr,"counter %d", debuga);
pthread_t producer_TID[P], consumer_TID[C];
start_time = time(0);
ptr=localtime(&start_time);
printf("Start: ");
printf(asctime(ptr));
printf("\\n\\n\\n");
for (i = 0; i < P; i++)
{
pthread_create(&producer_TID[i], 0, (void *) producer, 0);
}
for (i = 0; i < C; i++)
pthread_create(&consumer_TID[i], 0, (void *) consumer, 0);
for (i = 0; i < P; i++) {
pthread_join(producer_TID[i], 0);
}
for (i = 0; i < C; i++) {
pthread_join(consumer_TID[i], 0);
}
end_time = time(0);
printf("====================\\n");
printf("End time: %s", ctime(&end_time));
printf("Duration: %ld seconds\\n", end_time - start_time);
pthread_mutex_destroy(&sharedLock);
sem_destroy(&emptyCount);
sem_destroy(&fullCount);
return 0;
}
| 0
|
#include <pthread.h>
void *vestiario();
void *piscina();
void *limpeza();
int num_nadadores;
int contBanho = 0;
int segundoBanho = 0;
pthread_mutex_t mutex1;
pthread_mutex_t mutex2;
sem_t chuveiros;
sem_t raias;
bool raia1 = 1;
bool raia2 = 1;
bool raia3 = 1;
bool raia4 = 1;
bool raia5 = 1;
bool limpar = 0;
void *vestiario(void *arg) {
int banho = *(int *)arg;
sem_wait(&chuveiros);
if (banho == 1) {
printf("Primeiro banho\\n\\n");
usleep(8 * 100000);
pthread_mutex_lock(&mutex1);
contBanho++;
pthread_mutex_unlock(&mutex1);
if (contBanho != 5)
sem_post(&chuveiros);
else
limpar = 1;
pthread_exit(piscina());
}
if (banho == 2) {
printf("Segundo banho\\n\\n");
usleep(10 * 100000);
pthread_mutex_lock(&mutex2);
segundoBanho++;
contBanho++;
pthread_mutex_unlock(&mutex2);
if (contBanho != 5)
sem_post(&chuveiros);
else
limpar = 1;
pthread_exit(0);
}
printf("tchau\\n\\n");
}
void *piscina() {
sem_wait(&raias);
int banho = 2;
if (raia1) {
raia1 = 0;
printf("Nadador utilizando a raia 1\\n\\n");
usleep(10 * 5 * 100000);
raia1 = 1;
sem_post(&raias);
pthread_exit(vestiario((void*)&banho));
}
if (raia2) {
raia2 = 0;
printf("Nadador utilizando a raia 2\\n\\n");
usleep(10 * 5 * 100000);
raia2 = 1;
sem_post(&raias);
pthread_exit(vestiario((void*)&banho));
}
if (raia3) {
raia3 = 0;
printf("Nadador utilizando a raia 3\\n\\n");
usleep(10 * 5 * 100000);
raia3 = 1;
sem_post(&raias);
pthread_exit(vestiario((void*)&banho));
}
if (raia4) {
raia4= 0;
printf("Nadador utilizando a raia 4\\n\\n");
usleep(10 * 5 * 100000);
raia4 = 1;
sem_post(&raias);
pthread_exit(vestiario((void*)&banho));
}
if (raia5) {
raia5 = 0;
printf("Nadador utilizando a raia 5\\n\\n");
usleep(10 * 5 * 100000);
raia5 = 1;
sem_post(&raias);
pthread_exit(vestiario((void*)&banho));
}
}
void *limpeza() {
while (!limpar) {
usleep(1000);
if (segundoBanho == num_nadadores) {
printf("Simulação terminada.\\n\\n");
pthread_exit(0);
}
}
printf("Limpando banheiro\\n\\n");
contBanho = 0;
usleep(15 * 100000);
sem_post(&chuveiros);
limpar = 0;
limpeza();
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Use: %s [numero de nadadores]\\n", argv[0]);
return 0;
}
num_nadadores = atoi(argv[1]);
sem_init(&chuveiros, 0, 3);
sem_init(&raias, 0, 5);
pthread_mutex_init(&mutex1, 0);
pthread_mutex_init(&mutex2, 0);
pthread_t zelador;
pthread_create(&zelador, 0, limpeza, 0);
int i;
int banho = 1;
pthread_t nadadores[num_nadadores];
for (i = 0; i < num_nadadores; i++)
pthread_create(&nadadores[i], 0, vestiario, (void*)&banho);
for (i = 0; i < num_nadadores; i++)
pthread_join(nadadores[i], 0);
pthread_join(zelador, 0);
sem_destroy(&chuveiros);
sem_destroy(&raias);
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
return 0;
}
| 1
|
#include <pthread.h>
{
pthread_cond_t biglietteria_libera;
pthread_cond_t partenza_gruppo;
pthread_cond_t finito_servire_utente;
pthread_cond_t gruppo_libero;
pthread_mutex_t mut;
int n_in_gruppo;
int n_in_coda_biglietteria;
int n_gruppi_partiti;
bool biglietteria_occupata;
}monitor;
monitor m;
void init()
{
printf("-----init\\n");
pthread_mutex_init(&m.mut,0);
pthread_cond_init(&m.biglietteria_libera,0);
pthread_cond_init(&m.partenza_gruppo,0);
pthread_cond_init(&m.finito_servire_utente,0);
pthread_cond_init(&m.gruppo_libero,0);
m.n_in_gruppo=0;
printf("m.n_in_gruppo= %d\\n",m.n_in_gruppo);
m.n_in_coda_biglietteria=0;
printf("m.utenti_in_coda_biglietteria= %d\\n",m.n_in_coda_biglietteria);
m.biglietteria_occupata=1;
m.n_gruppi_partiti=0;
printf("m.n_gruppi_partiti= %d\\n",m.n_gruppi_partiti);
}
void user(void* arg)
{
int id = (int)arg;
pthread_mutex_lock(&m.mut);
while(
m.biglietteria_occupata
) {
printf("\\tuser [%d]aspetta in fila\\n",id);
m.n_in_coda_biglietteria++;
pthread_cond_wait(&m.biglietteria_libera,&m.mut);
printf("\\tuser [%d]suo turno in biglietteria\\n",id);
m.n_in_coda_biglietteria--;
}
printf("\\tuser [%d] arriva allo sportello della biglietteria\\n",id);
m.biglietteria_occupata=1;
sleep(2);
printf("\\tuser [%d] finito procedura alla biglietteria\\n",id);
m.n_in_gruppo++;
printf("\\tuser [%d] passo la gestione alla biglietteria entro nel gruppo:%d\\n",id,m.n_in_gruppo);
pthread_cond_signal(&m.finito_servire_utente);
printf("\\tuser [%d] aspetto la partenza del gruppo\\n",id);
pthread_cond_wait(&m.partenza_gruppo,&m.mut);
printf("\\t\\tuser [%d] partito con il gruppo\\n",id);
sleep(2);
printf("\\t\\tuser [%d] terminato visita con il gruppo\\n",id);
m.n_in_gruppo--;
pthread_cond_signal(&m.gruppo_libero);
pthread_mutex_unlock(&m.mut);
pthread_exit(id);
}
void* biglietteria()
{
pthread_mutex_lock(&m.mut);
while(m.n_gruppi_partiti!=2) {
printf("----- gestione del gruppo %d -----\\n",m.n_gruppi_partiti);
printf("biglietteria apre\\n");
m.biglietteria_occupata=0;
pthread_cond_signal(&m.biglietteria_libera);
while(
m.n_in_gruppo!=2
) {
printf("biglietteria aspetta il prossimo utente, gruppo: %d\\n",m.n_in_gruppo);
m.biglietteria_occupata=0;
pthread_cond_signal(&m.biglietteria_libera);
pthread_cond_wait(&m.finito_servire_utente,&m.mut);
}
printf("biglietteria| gruppo pieno,chiudo biglietteria e faccio partire la visita\\n");
m.biglietteria_occupata=1;
pthread_cond_broadcast(&m.partenza_gruppo);
while(m.n_in_gruppo!=0) {
printf("biglietteria| aspetta che il gruppo si svuoti, n_in_gruppo: %d\\n",m.n_in_gruppo);
pthread_cond_wait(&m.gruppo_libero,&m.mut);
}
m.n_gruppi_partiti++;
m.biglietteria_occupata=0;
pthread_cond_signal(&m.biglietteria_libera);
}
pthread_mutex_unlock(&m.mut);
printf("biglietteria termina esecuzione\\n");
pthread_exit(0);
}
int main(int argc, char *argv[])
{
pthread_t bigl;
pthread_t th[4];
int retval[4],ret_bigl;
int i;
init();
printf("creazione barriera_monitor\\n");
pthread_create(&bigl,0,biglietteria,0);
printf("creazione users\\n");
for (int i = 0; i < 4; ++i)
{
pthread_create(&th[i],0,user, (void *)i);
}
for (int i = 0; i < 4; ++i)
{
pthread_join(th[i],&retval[i]);
printf("terminato son [%d]\\n",retval[i]);
}
printf("aspetto biglietteria \\n");
pthread_join(bigl,0);
printf("%d\\n",i);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
void *traveler_arrive( void *p )
{
char *name = (char *)p;
printf( "Traveler %s needs a taxi now.\\n",name );
pthread_mutex_lock( &mutex );
pthread_cond_wait( &cond,&mutex );
pthread_mutex_unlock( &mutex );
printf( "%s has gotten a taxi now\\n",name );
pthread_exit( 0 );
}
void *taxi_arrive( void *p )
{
char *name = (char *)p;
printf( "taxi %s has arrived\\n",name );
pthread_cond_signal( &cond );
pthread_exit( 0 );
}
int main()
{
char *name;
pthread_t tid;
pthread_mutex_init( &mutex,0 );
pthread_cond_init( &cond,0 );
name = "Jack";
pthread_create( &tid,0,(void *)taxi_arrive,name );
sleep(1);
name = "Susan";
pthread_create( &tid,0,(void *)traveler_arrive,name );
sleep(1);
name = "Mike";
pthread_create( &tid,0,(void *)taxi_arrive,name );
sleep(1);
exit(0);
}
| 1
|
#include <pthread.h>
int isp_app_msg_queue_create(unsigned int count, unsigned int *queue_handle)
{
struct isp_app_msg_cxt *msg_cxt;
if (0 == count) {
return -ISP_APP_MSG_PARAM_ERR;
}
msg_cxt = (struct isp_app_msg_cxt*)malloc(sizeof(struct isp_app_msg_cxt));
if (0 == msg_cxt) {
return -ISP_APP_MSG_NO_MEM;
}
bzero(msg_cxt, sizeof(*msg_cxt));
msg_cxt->msg_head = (struct isp_app_msg*)malloc((unsigned int)(count * sizeof(struct isp_app_msg)));
if (0 == msg_cxt->msg_head) {
free(msg_cxt);
return -ISP_APP_MSG_NO_MEM;
}
msg_cxt->msg_magic = ISP_APP_MSG_MAGIC_CODE;
msg_cxt->msg_count = count;
msg_cxt->msg_read = msg_cxt->msg_head;
msg_cxt->msg_write = msg_cxt->msg_head;
pthread_mutex_init(&msg_cxt->mutex, 0);
sem_init(&msg_cxt->msg_sem, 0, 0);
*queue_handle = (unsigned int)msg_cxt;
return ISP_APP_MSG_SUCCESS;
}
int isp_app_msg_get(unsigned int queue_handle, struct isp_app_msg *message)
{
struct isp_app_msg_cxt *msg_cxt = (struct isp_app_msg_cxt*)queue_handle;
if (0 == queue_handle || 0 == message) {
return -ISP_APP_MSG_PARAM_ERR;
}
do { if (((struct isp_app_msg_cxt*)queue_handle)->msg_magic != ISP_APP_MSG_MAGIC_CODE) { return ISP_APP_MSG_INVALID_HANDLE; } } while(0);
sem_wait(&msg_cxt->msg_sem);
pthread_mutex_lock(&msg_cxt->mutex);
if (msg_cxt->msg_read != msg_cxt->msg_write) {
*message = *msg_cxt->msg_read++;
if (msg_cxt->msg_read > msg_cxt->msg_head + msg_cxt->msg_count - 1) {
msg_cxt->msg_read = msg_cxt->msg_head;
}
}
pthread_mutex_unlock(&msg_cxt->mutex);
return ISP_APP_MSG_SUCCESS;
}
int isp_app_msg_post(unsigned int queue_handle, struct isp_app_msg *message)
{
struct isp_app_msg_cxt* msg_cxt = (struct isp_app_msg_cxt*)queue_handle;
struct isp_app_msg* ori_node = msg_cxt->msg_write;
if (0 == queue_handle || 0 == message) {
return -ISP_APP_MSG_PARAM_ERR;
}
do { if (((struct isp_app_msg_cxt*)queue_handle)->msg_magic != ISP_APP_MSG_MAGIC_CODE) { return ISP_APP_MSG_INVALID_HANDLE; } } while(0);
pthread_mutex_lock(&msg_cxt->mutex);
*msg_cxt->msg_write++ = *message;
if (msg_cxt->msg_write > msg_cxt->msg_head + msg_cxt->msg_count - 1) {
msg_cxt->msg_write = msg_cxt->msg_head;
}
if (msg_cxt->msg_write == msg_cxt->msg_read) {
msg_cxt->msg_write = ori_node;
}
pthread_mutex_unlock(&msg_cxt->mutex);
sem_post(&msg_cxt->msg_sem);
return ISP_APP_MSG_SUCCESS;
}
int isp_app_msg_peak(uint32_t queue_handle, struct isp_app_msg *message)
{
struct isp_app_msg_cxt *msg_cxt = (struct isp_app_msg_cxt*)queue_handle;
uint32_t msg_cnt = 0;
int rtn = 0;
if (0 == queue_handle || 0 == message) {
return -ISP_APP_MSG_PARAM_ERR;
}
do { if (((struct isp_app_msg_cxt*)queue_handle)->msg_magic != ISP_APP_MSG_MAGIC_CODE) { return ISP_APP_MSG_INVALID_HANDLE; } } while(0);
rtn = sem_trywait(&msg_cxt->msg_sem);
if (rtn) {
return -ISP_APP_MSG_NO_OTHER_MSG;
}
pthread_mutex_lock(&msg_cxt->mutex);
if (msg_cxt->msg_read != msg_cxt->msg_write) {
*message = *msg_cxt->msg_read++;
if (msg_cxt->msg_read > msg_cxt->msg_head + msg_cxt->msg_count - 1) {
msg_cxt->msg_read = msg_cxt->msg_head;
}
} else {
return -ISP_APP_MSG_NO_OTHER_MSG;
}
pthread_mutex_unlock(&msg_cxt->mutex);
return ISP_APP_MSG_SUCCESS;
}
int isp_app_msg_queue_destroy(unsigned int queue_handle)
{
struct isp_app_msg_cxt *msg_cxt = (struct isp_app_msg_cxt*)queue_handle;
if (0 == queue_handle) {
return -ISP_APP_MSG_PARAM_ERR;
}
do { if (((struct isp_app_msg_cxt*)queue_handle)->msg_magic != ISP_APP_MSG_MAGIC_CODE) { return ISP_APP_MSG_INVALID_HANDLE; } } while(0);
if (msg_cxt->msg_head) {
free(msg_cxt->msg_head);
msg_cxt->msg_head = 0;
}
sem_destroy(&msg_cxt->msg_sem);
pthread_mutex_destroy(&msg_cxt->mutex);
bzero(msg_cxt, sizeof(*msg_cxt));
free(msg_cxt);
return ISP_APP_MSG_SUCCESS;
}
| 0
|
#include <pthread.h>
struct msg {
struct msg *m_next;
char *data;
};
struct msg *workq;
pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;
void
process_msg(int thread)
{
struct msg *mp;
for (;;) {
pthread_mutex_lock(&qlock);
while (workq == 0)
pthread_cond_wait(&qready, &qlock);
mp = workq;
workq = mp->m_next;
pthread_mutex_unlock(&qlock);
printf("thread %u message:%s \\n",thread,mp->data);
free(mp);
}
}
void
enqueue_msg(struct msg *mp)
{
pthread_mutex_lock(&qlock);
mp->m_next = workq;
workq = mp;
pthread_mutex_unlock(&qlock);
pthread_cond_signal(&qready);
}
pthread_t ntid[2];
struct foo {
int f_count;
pthread_mutex_t f_lock;
};
struct foo * foo_alloc(void)
{
struct foo *fp;
if ((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 1;
if (pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return(0);
}
}
return(fp);
}
void
foo_hold(struct foo *fp)
{
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
void
foo_rele(struct foo *fp)
{
pthread_mutex_lock(&fp->f_lock);
if (--fp->f_count == 0) {
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
} else {
pthread_mutex_unlock(&fp->f_lock);
}
}
void
printids(const char *s)
{
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid %u tid %u (0x%x)\\n", s, (unsigned int)pid,
(unsigned int)tid, (unsigned int)tid);
}
void
cleanup(void *arg)
{
printf("cleanup: %s\\n", (char *)arg);
}
void * thr_func1(void *arg)
{
struct foo* fp=(struct foo*)arg;
pthread_cleanup_push(cleanup,"thread 1 cleanup");
printids("new thread: ");
pthread_cleanup_pop(0);
process_msg(1);
return((void *)2);
}
void * thr_func2(void *arg)
{
struct foo* fp=(struct foo*)arg;
pthread_cleanup_push(cleanup,"thread 2 cleanup");
printids("new thread: ");
pthread_cleanup_pop(0);
process_msg(2);
pthread_exit((void *)1);
}
int
main(void)
{
int err;
void * ret;
struct foo *fp=foo_alloc();
char message[][5]={"1111", "2222", "3333", "4444", "5555", "6666", "7777", "8888", "9999", "000" };
int loop=0;
err = pthread_create(&ntid[0], 0, thr_func1, fp);
if (err != 0){
exit(0);
}
err = pthread_create(&ntid[1], 0, thr_func2, fp);
if (err != 0){
exit(0);
}
sleep(1);
for(loop ; loop<10 ; loop++ ){
struct msg * f=malloc(sizeof(struct msg));
f->data=message[loop];
enqueue_msg(f);
}
sleep(1);
err = pthread_join(ntid[0], &ret);
printf("thread 1 exit code %u\\n",(int)ret);
err = pthread_join(ntid[1], &ret);
printf("thread 2 exit code %u\\n",(int)ret);
printids("main thread:");
exit(0);
}
extern int makethread(void *(*)(void *), void *);
struct to_info {
void (*to_fn)(void *);
void *to_arg;
struct timespec to_wait;
};
void *timeout_helper(void *arg)
{
struct to_info *tip;
tip = (struct to_info *)arg;
nanosleep(&tip->to_wait, 0);
(*tip->to_fn)(tip->to_arg);
return 0;
}
void timeout(const struct timespec *when, void (*func)(void *), void *arg)
{
struct timespec now;
struct timeval tv;
struct to_info *tip;
int err;
gettimeofday(&tv, 0);
now.tv_sec = tv.tv_sec;
now.tv_nsec = tv.tv_usec * 1000;
if ((when->tv_sec > now.tv_sec) || (when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) {
tip = malloc(sizeof(struct to_info));
if (tip != 0) {
tip->to_fn = func;
tip->to_arg = arg;
tip->to_wait.tv_sec = when->tv_sec - now.tv_sec;
if (when->tv_nsec >= now.tv_nsec) {
tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec;
} else {
tip->to_wait.tv_sec--;
tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec * when->tv_nsec;
}
err = makethread(timeout_helper, (void *)tip);
if (err == 0)
return;
}
}
(*func) (arg);
}
pthread_mutexattr_t attr;
pthread_mutex_t mutex;
void retry(void *arg)
{
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
}
int main(void)
{
int err, condition, arg;
struct timespec when;
if ((err = pthread_mutexattr_init(&attr)) != 0)
err_exit(err, "pthread_mutexattr_init failed");
if ((err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) != 0)
err_exit(err, "can't set recursive type");
if ((err = pthread_mutex_init(&mutex, &attr)) != 0)
err_exit(err, "can't create recursive mutex");
pthread_mutex_lock(&mutex);
if (condition) {
timeout(&when, retry, (void *)arg);
}
pthread_mutex_unlock(&mutex);
exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t gSharedValueLock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gReadCondition = PTHREAD_COND_INITIALIZER;
pthread_cond_t gWriteCondition = PTHREAD_COND_INITIALIZER;
unsigned int gSharedValue = 0;
int gReaderCount = 0;
int gWaitingReaderCount = 0;
void *reader(void *arg){
int threadId = *((int*)arg);
for (int i = 0; i < READ_TIMES; ++i){
usleep(1000 * (rand() % (READERS_COUNT + WRITERS_COUNT)));
pthread_mutex_lock(&gSharedValueLock);
++gWaitingReaderCount;
while (gReaderCount == -1) {
pthread_cond_wait(&gReadCondition, &gSharedValueLock);
}
--gWaitingReaderCount;
int readCount = ++gReaderCount;
pthread_mutex_unlock(&gSharedValueLock);
printf("%u\\t\\tReader ID %d\\tReaders: %d\\tWaitingReaders: %d\\n", gSharedValue, threadId, readCount, gWaitingReaderCount);
pthread_mutex_lock(&gSharedValueLock);{
--gReaderCount;
if (gReaderCount == 0) {
pthread_cond_signal(&gWriteCondition);
}
}
pthread_mutex_unlock(&gSharedValueLock);
}
pthread_exit((void*)threadId);
}
void *writer(void *arg){
int threadId = *((int*)arg);
for (int i = 0; i < WRITE_TIMES; ++i){
usleep(1000 * (rand() % (WRITERS_COUNT + READERS_COUNT)));
pthread_mutex_lock(&gSharedValueLock);
while (gReaderCount != 0) {
pthread_cond_wait(&gWriteCondition, &gSharedValueLock);
}
gReaderCount = -1;
pthread_mutex_unlock(&gSharedValueLock);
usleep(1000 * (rand() % (WRITERS_COUNT + READERS_COUNT)));
printf("%u <<<<\\tWriter ID %d\\tReaders: %d\\tWaitingReaders: %d\\n", ++gSharedValue, threadId, gReaderCount < 0 ? 0 : gReaderCount, gWaitingReaderCount);
pthread_mutex_lock(&gSharedValueLock); {
++gReaderCount;
if (gWaitingReaderCount > 0) {
pthread_cond_broadcast(&gReadCondition);
} else {
pthread_cond_signal(&gWriteCondition);
}
}
pthread_mutex_unlock(&gSharedValueLock);
}
pthread_exit((void*)threadId);
}
| 0
|
#include <pthread.h>
static int num = 0;
static pthread_mutex_t mut_num = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond_num = PTHREAD_COND_INITIALIZER;
static void *thr_primer(void *p);
int main()
{
int i,j,mark;
int err;
pthread_t tid[4];
for(i = 0; i < 4 ; i++)
{
err = pthread_create(tid+i,0,thr_primer,(void *)i);
if(err)
{
fprintf(stderr,"pthread_create():%s\\n",strerror(err));
exit(1);
}
}
for(i = 30000000 ; i <= 30000200 ; i++)
{
pthread_mutex_lock(&mut_num);
while(num != 0)
{
pthread_cond_wait(&cond_num,&mut_num);
}
num = i;
pthread_cond_signal(&cond_num);
pthread_mutex_unlock(&mut_num);
}
pthread_mutex_lock(&mut_num);
while(num != 0)
{
pthread_cond_wait(&cond_num,&mut_num);
}
num = -1;
pthread_cond_broadcast(&cond_num);
pthread_mutex_unlock(&mut_num);
for(i = 0; i < 4 ; i++)
pthread_join(tid[i],0);
pthread_mutex_destroy(&mut_num);
pthread_cond_destroy(&cond_num);
exit(0);
}
static void *thr_primer(void *p)
{
int i,j,mark;
while(1)
{
pthread_mutex_lock(&mut_num);
while(num == 0)
{
pthread_cond_wait(&cond_num,&mut_num);
}
if(num == -1)
{
pthread_mutex_unlock(&mut_num);
break;
}
i = num;
num = 0;
pthread_cond_broadcast(&cond_num);
pthread_mutex_unlock(&mut_num);
mark = 1;
for(j = 2; j < i/2 ; j++)
{
if(i % j == 0)
{
mark = 0;
break;
}
}
if(mark)
printf("[%d]%d is a primer.\\n",(int)p,i);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int counter = 0;
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t threshold_condv = PTHREAD_COND_INITIALIZER;
void *inc_counter(void *thread_id)
{
long th_id = (long) thread_id;
for (int ii = 0; ii < 10; ii++) {
pthread_mutex_lock(&counter_mutex);
counter++;
fprintf(stderr, "Counter thread %ld, count = %d\\n", th_id, counter);
if (counter == 12) {
pthread_cond_signal(&threshold_condv);
fprintf(stderr, "Counter thread %ld, threshold reached\\n", th_id);
}
pthread_mutex_unlock(&counter_mutex);
sleep(1);
}
return 0;
}
void *watch_counter(void *arg )
{
fprintf(stderr, "Starting watcher thread\\n");
pthread_mutex_lock(&counter_mutex);
if (counter < 12) {
pthread_cond_wait(&threshold_condv, &counter_mutex);
fprintf(stderr, "Watcher thread, condition signal received\\n");
counter += 125;
fprintf(stderr, "Watcher thread, count now = %d.\\n", counter);
}
pthread_mutex_unlock(&counter_mutex);
return 0;
}
int main(void)
{
pthread_t thread_ids[3];
if (pthread_create(&thread_ids[0], 0, &watch_counter, 0) != 0) {
perror("pthread_create 0");
exit(1);
}
if (pthread_create(&thread_ids[1], 0, &inc_counter, (long *) 1) != 0) {
perror("pthread_create 1");
exit(1);
}
if (pthread_create(&thread_ids[2], 0, &inc_counter, (long *) 2) != 0) {
perror("pthread_create 2");
exit(1);
}
for (int ii = 0; ii < 3; ii ++) {
if (pthread_join(thread_ids[ii], 0) != 0) {
perror("pthread_join");
exit(1);
}
}
exit(0);
}
| 0
|
#include <pthread.h>
static char const *short_usage =
("Usage: egytian_cotton [-fhv] [-n num_threads] [-s bytes]\\n");
static char const *flags_usage =
(" -f expect thread creation to fail for given\\n"
" thread creation parameters\\n"
" -h longer help\\n"
" -v increase verbosity\\n"
" -n number of additional threads to create\\n"
" -s stack size for each new thread\\n");
static char const *long_winded_explanation[] = {
"This is a test to exercise the thread library when used",
"in a high thread-count situation. The exit status (and",
"SUCCESS/FAIL output) will indicate success when all requested",
"threads were created without error and the -f flag is not",
"specified. This is typicaly used to make sure that a large",
"number of threads can be created -- as long as the stack size",
"requested is moderate, so we don't run out of memory",
"Conversely, the -f flag is used to ensure that the thread",
"library returns the appropriate error rather than faulting,",
"when a larger-than-supported number of threads is requested,",
"or if the total amount of stack memory exceeds available",
"memory / address space",
0,
};
int gVerbosity = 0;
int gExpectThreadCreationFailure = 0;
size_t kNewlineMask = 0x3f;
size_t kCountMask = 0xff;
pthread_mutex_t gBarrierMu = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gBarrierCv = PTHREAD_COND_INITIALIZER;
int gThreadWait = 1;
void *thread_start(void *state) {
int tid = (int) (uintptr_t) state;
pthread_mutex_lock(&gBarrierMu);
while (gThreadWait) {
if (gVerbosity > 1) {
printf("Thread %d: waiting\\n", tid);
}
pthread_cond_wait(&gBarrierCv, &gBarrierMu);
}
pthread_mutex_unlock(&gBarrierMu);
return 0;
}
int main(int ac,
char **av) {
int opt;
size_t num_threads = ((size_t) 4095);
size_t stack_size = ((size_t) 1024);
char const **line;
int rv = 0;
pthread_t thr_state;
pthread_attr_t attr;
size_t tid;
while (EOF != (opt = getopt(ac, av, "fhn:s:v"))) {
switch (opt) {
case 'f':
gExpectThreadCreationFailure = 1;
break;
case 'n':
num_threads = strtoul(optarg, (char **) 0, 0);
break;
case 's':
stack_size = strtoul(optarg, (char **) 0, 0);
break;
case 'v':
++gVerbosity;
break;
case 'h':
fprintf(stderr, "%s%s\\n", short_usage, flags_usage);
for (line = long_winded_explanation; 0 != *line; ++line) {
fprintf(stderr, " %s\\n", *line);
}
return 0;
default:
fprintf(stderr, "%s\\n", short_usage);
return 1;
}
}
if (gVerbosity > 1) {
printf("Creating %""zd"" threads with 0x%""zx"" byte stacks\\n",
num_threads,
stack_size);
printf("According to the command line parameters,"
" this is%s expected to work.\\n",
gExpectThreadCreationFailure ? " not" : "");
}
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, stack_size);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
for (tid = 0; tid < num_threads; ++tid) {
if (gVerbosity > 0) {
printf("Creating thread %""zd""\\n", tid); fflush(stdout);
}
if (0 != (rv = pthread_create(&thr_state,
&attr,
thread_start,
(void *) tid))) {
printf("Thread creation failed at thread %""zd"", error %d (%s)\\n",
tid, rv, strerror(rv));
if (gExpectThreadCreationFailure) {
if (EAGAIN == rv) {
printf("This is expected.\\n");
rv = 0;
goto cleanup_exit;
}
}
break;
}
putchar('.');
if (kCountMask == (tid & kCountMask)) {
printf("%""zd", tid);
}
if (kNewlineMask == (tid & kNewlineMask)) {
putchar('\\n');
}
}
if (0 == rv && gExpectThreadCreationFailure) {
printf("Expected thread creation failure.\\n");
rv = 1;
}
cleanup_exit:
pthread_mutex_lock(&gBarrierMu);
gThreadWait = 0;
pthread_cond_broadcast(&gBarrierCv);
pthread_mutex_unlock(&gBarrierMu);
if (0 == rv) {
printf("PASSED\\n");
} else {
printf("FAILED\\n");
}
return rv;
}
| 1
|
#include <pthread.h>
int buffer[5];
int count = 0;
int front = -1;
int rear = 0;
pthread_mutex_t lock;
pthread_cond_t nonFull;
pthread_cond_t nonEmpty;
void *producerWork(void *);
void *consumerWork(void *);
void bufferAdd(int);
int bufferRemove();
int main(int argc, char * argv[]) {
pthread_mutex_init(&lock, 0);
pthread_cond_init(&nonFull, 0);
pthread_cond_init(&nonEmpty, 0);
pthread_t threadHandle[64];
pthread_attr_t attr[64];
int i,numberOfThreads;
if (argc != 2) {
printf("usage: %s <integer number of producter and consumer threads>\\n",
argv[0]);
exit(1);
}
sscanf(argv[1], "%d", &numberOfThreads);
srand(5);
for (i=0; i < numberOfThreads; i++) {
pthread_attr_init(&attr[i]);
pthread_attr_setscope(&attr[i], PTHREAD_SCOPE_SYSTEM);
if (i % 2 == 0) {
pthread_create(&threadHandle[i], &attr[i], producerWork, &i);
} else {
pthread_create(&threadHandle[i], &attr[i], consumerWork, &i);
}
}
for (i=0; i < numberOfThreads; i++) {
pthread_join(threadHandle[i], (void **) 0);
}
printf("After join in main!\\n");
}
void *producerWork(void * args) {
int threadId;
int counter = 0;
unsigned int sleepAmt;
threadId = *((int *) args);
while (counter < 100) {
sleepAmt = rand() % 10;
sleep(sleepAmt);
printf("Producer try to add when count = %d\\n", count);
bufferAdd(threadId);
printf("Producer added\\n");
counter++;
}
}
void *consumerWork(void * args) {
int threadId;
int counter = 0;
unsigned int sleepAmt;
threadId = *((int *) args);
while (counter < 100) {
sleepAmt = rand() % 5;
sleep(sleepAmt);
printf("Consumer trying to remove when count = %d\\n", count);
bufferRemove(threadId);
printf("Consumer removed\\n");
counter++;
}
}
void bufferAdd(int item) {
pthread_mutex_lock(&lock);
while(count == 5) {
while(pthread_cond_wait(&nonFull, &lock) != 0);
}
if (count == 0) {
front = 0;
rear = 0;
} else {
rear = (rear + 1) % 5;
}
buffer[rear] = item;
count++;
pthread_cond_signal(&nonEmpty);
pthread_mutex_unlock(&lock);
}
int bufferRemove() {
int returnValue;
pthread_mutex_lock(&lock);
while(count == 0) {
while(pthread_cond_wait(&nonEmpty, &lock) != 0);
}
returnValue = buffer[front];
front = (front + 1) % 5;
count--;
pthread_cond_signal(&nonFull);
pthread_mutex_unlock(&lock);
return returnValue;
}
| 0
|
#include <pthread.h>
static uint64_t global_int;
static pthread_mutex_t lock;
void bounds_error()
{
printf("Argument out of bounds:\\n"
"t must be between %lu and %lu,\\n"
"n must be between %lu and %lu.\\n",
1l, 16l, 1l, 1000000000l);
exit(1);
}
void *add_to_global(void *argument)
{
int i, n;
uint64_t local_int = 0;
n = *((int *) argument);
for (i = 1; i <= n; ++i) {
local_int += i;
}
pthread_mutex_lock(&lock);
global_int += local_int;
pthread_mutex_unlock(&lock);
return 0;
}
int main(int argc, char *argv[])
{
int t, n, i, rc;
pthread_t threads[16l];
if (argc != 3) {
printf("You must specify exactly two arguments.\\n");
} else {
t = strtol(argv[1], 0, 0);
n = strtol(argv[2], 0, 0);
if (1l > t || t > 16l)
bounds_error();
if (1l > n || t > 1000000000l)
bounds_error();
global_int = 0;
if (pthread_mutex_init(&lock, 0) != 0) {
printf("Mutex init failed\\n");
exit(1);
}
for (i=0; i<t; ++i) {
rc = pthread_create(&threads[i], 0, add_to_global, (void *)&n);
if (rc != 0) {
printf("Failed to create thread %d\\n", i);
exit(1);
}
}
for (i=0; i<t; ++i) {
rc = pthread_join(threads[i], 0);
if (rc != 0) {
printf("Failed to join thread %d\\n", i);
exit(1);
}
}
pthread_mutex_destroy(&lock);
printf("%llu\\n", global_int);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_t tid[4];
pthread_mutex_t mutex;
int *array;
int length = 1000000000;
int count = 0;
int double_count = 0;
int t = 4;
int max_threads = 0;
struct padded_int{
int value;
char padding[60];
}private_count[4];
void *count3s_thread(void *arg)
{
clock_t startTime = clock();
int length_per_thread = length/max_threads;
int id = (int)arg;
int start = id * length_per_thread;
printf("\\tThread [%d] starts [%d] length [%d]\\n", id, start, length_per_thread);
for (int i = start; i < start + length_per_thread; i++)
{
if (array[i] == 3)
{
private_count[id].value++;
}
}
pthread_mutex_lock(&mutex);
count = count + private_count[id].value;
pthread_mutex_unlock(&mutex);
clock_t endTime = clock();
printf("time couting in %f!\\n", (float)(endTime - startTime) / CLOCKS_PER_SEC);
}
void initialize_vector()
{
array = (int*) malloc(sizeof(int) * 1000000000);
if (array == 0)
{
printf("Allocation memory failed!\\n");
exit(-1);
}
for (int i = 0; i < 1000000000; i++)
{
array[i] = rand() % 20;
if (array[i] == 3)
{
double_count++;
}
}
}
int main(int argc, char *argv[])
{
int i = 0;
int err;
clock_t t1, t2;
if (argc == 2)
{
max_threads = atoi(argv[1]);
if (max_threads > 4)
{
max_threads = 4;
}
}
else
{
max_threads = 4;
}
printf("[3s-05] Using %d threads\\n", max_threads);
srand(time(0));
printf("*** 3s-05 ***\\n");
printf("Initializing vector... ");
fflush(stdout);
initialize_vector();
printf("Vector initialized!\\n");
fflush(stdout);
t1 = clock();
pthread_mutex_init(&mutex, 0);
while (i < max_threads)
{
private_count[i].value = 0;
err = pthread_create(&tid[i], 0, &count3s_thread, (void*)i);
if (err != 0)
{
printf("[3s-05] Can't create a thread: [%d]\\n", i);
}
else
{
printf("[3s-05] Thread created!\\n");
}
i++;
}
for (i =0; i < max_threads; i++)
{
void *status;
int rc;
rc = pthread_join(tid[i], &status);
if (rc)
{
printf("ERROR; retrun code from pthread_join() is %d\\n", rc);
exit(-1);
}
else
{
printf("Thread [%d] exited with status [%ld]\\n", i, (long)status);
}
}
printf("[3s-05] Count by threads %d\\n", count);
printf("[3s-05] Double check %d\\n", double_count);
pthread_mutex_destroy(&mutex);
t2 = clock();
printf("time couting in %f!\\n", (float)(t2 - t1) / CLOCKS_PER_SEC);
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo {
int f_count;
pthread_mutex_t f_lock;
int f_id;
struct foo *f_next;
};
struct foo * foo_alloc(int id) {
struct foo *fp;
int idx;
if ((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 1;
fp->f_id = id;
if (pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return(0);
}
idx = (((unsigned long)id)%29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
}
return(fp);
}
void foo_hold(struct foo *fp) {
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
struct foo * foo_find(int id) {
struct foo *fp;
pthread_mutex_lock(&hashlock);
for (fp = fh[(((unsigned long)id)%29)]; fp != 0; fp = fp->f_next) {
if (fp->f_id == id) {
foo_hold(fp);
break;
}
}
pthread_mutex_unlock(&hashlock);
return(fp);
}
void foo_rele(struct foo *fp) {
struct foo *tfp;
int idx;
pthread_mutex_lock(&fp->f_lock);
if (fp->f_count == 1) {
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_lock(&hashlock);
pthread_mutex_lock(&fp->f_lock);
if (fp->f_count != 1) {
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
return;
}
idx = (((unsigned long)fp->f_id)%29);
tfp = fh[idx];
if (tfp == fp) {
fh[idx] = fp->f_next;
} else {
while (tfp->f_next != fp)
tfp = tfp->f_next;
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
} else {
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
}
}
void id_entry(int x) {
int i;
for(i = 0 ; i < 20 ; i++) {
foo_alloc(x + i);
}
pthread_exit((void *)2);
}
void print_all_foo_entry() {
int i;
for(i = 0 ; i < 29 ; i++) {
struct foo * tmp;
if(fh[i] != 0)
printf("fh[%2d]: ", i);
for(tmp = fh[i] ; tmp != 0 ; tmp = tmp->f_next ) {
printf("%d", tmp->f_id);
if(tmp->f_next != 0) {
printf(" -> ");
}
}
if(fh[i] != 0)
printf("\\n");
}
}
int main() {
int error;
pthread_t tid1, tid2, tid3;
void *tret;
error = pthread_create(&tid1, 0, id_entry, 0);
if (error)
do { errno = error; perror("can’t create thread 1"); exit(1); } while (0);
error = pthread_create(&tid2, 0, id_entry, 29);
if (error)
do { errno = error; perror("can’t create thread 2"); exit(1); } while (0);
error = pthread_create(&tid3, 0, id_entry, 35);
if (error)
do { errno = error; perror("can’t create thread 2"); exit(1); } while (0);
error = pthread_join(tid1, &tret);
if (error)
do { errno = error; perror("can’t join with thread 1"); exit(1); } while (0);
printf("thread 1: exit code %ld\\n", (long)tret);
error = pthread_join(tid2, &tret);
if (error)
do { errno = error; perror("can’t join with thread 2"); exit(1); } while (0);
printf("thread 2: exit code %ld\\n", (long)tret);
error = pthread_join(tid3, &tret);
if (error)
do { errno = error; perror("can’t join with thread 3"); exit(1); } while (0);
printf("thread 3: exit code %ld\\n", (long)tret);
print_all_foo_entry();
exit(0);
}
| 1
|
#include <pthread.h>
{
int thread_done ;
int rs232Ctrl ;
} Thdata;
void print_signal_status(int) ;
int getch() ;
pthread_mutex_t mutex_rs232_receiver = PTHREAD_MUTEX_INITIALIZER ;
int getch(void)
{
int c=0;
struct termios org_opts, new_opts;
int res=0;
res=tcgetattr(STDIN_FILENO, &org_opts);
assert(res==0);
memcpy(&new_opts, &org_opts, sizeof(new_opts));
new_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL);
tcsetattr(STDIN_FILENO, TCSANOW, &new_opts);
c=getchar();
res=tcsetattr(STDIN_FILENO, TCSANOW, &org_opts);
assert(res==0);
return(c);
}
void print_signal_status(int status)
{
printf("CAR : ") ;
if( status & TIOCM_CAR )
printf("1\\n") ;
else
printf("0\\n") ;
printf("SR : ") ;
if( status & TIOCM_SR )
printf("1\\n") ;
else
printf("0\\n") ;
printf("ST : ") ;
if( status & TIOCM_ST )
printf("1\\n") ;
else
printf("0\\n") ;
printf("DTR : ") ;
if( status & TIOCM_DTR )
printf("1\\n") ;
else
printf("0\\n") ;
printf("DSR : ") ;
if( status & TIOCM_DSR )
printf("1\\n") ;
else
printf("0\\n") ;
printf("RTS : ") ;
if( status & TIOCM_RTS )
printf("1\\n") ;
else
printf("0\\n") ;
printf("CTS : ") ;
if( status & TIOCM_CTS )
printf("1\\n") ;
else
printf("0\\n") ;
printf("RNG : ") ;
if( status & TIOCM_RNG )
printf("1\\n") ;
else
printf("0\\n") ;
}
void rs232Receiver(void *ptr)
{
Thdata *thdata = (Thdata*)(ptr) ;
char buf[8] ;
int len ;
memset( buf , 0 , 8 ) ;
for(;;)
{
pthread_mutex_lock(&mutex_rs232_receiver) ;
if( thdata->thread_done )
{
pthread_mutex_unlock(&mutex_rs232_receiver) ;
break ;
}
pthread_mutex_unlock(&mutex_rs232_receiver) ;
len = read( thdata->rs232Ctrl , buf , 7 ) ;
if( len > 0 )
{
buf[len] = '\\0' ;
printf("%d byte received from rs232 : %s\\n",len,buf) ;
}
usleep(10000) ;
}
}
void readUART(int ctrl)
{
unsigned char buf[512] ;
unsigned char c ;
int len_buf ;
int len_c ;
int i ;
memset( buf , 0 , 512 ) ;
len_buf = 0 ;
for(;;)
{
len_c = read( ctrl , &c , 1 ) ;
if( len_c > 0)
{
if( c == 0x7e )
{
if( len_buf > 1 )
{
printf( "received %d byte from UART \\n",len_buf) ;
for( i=0 ; i< len_buf ; ++i)
{
printf("%02x",buf[i]) ;
}
printf("7e\\n") ;
}
len_buf = 0 ;
buf[len_buf++] = 0x7e ;
}
else
{
if( len_buf >=512 )
{
printf("the length is larger than 512\\n") ;
break ;
}
buf[ len_buf++ ] = c ;
}
}
}
}
int main(int argc, const char* argv[])
{
int status ;
int rs232Ctrl ;
int uartCtrl ;
struct termios rs232Options ;
struct termios uartOptions ;
pthread_t rs232_receiver_thread ;
Thdata thdata ;
int k1,k2,k3 ;
uartCtrl = open( "/dev/tts/2" , O_RDWR | O_NOCTTY ) ;
if( uartCtrl < 0 )
{
perror("could not open /dev/tts/2\\n") ;
return -1 ;
}
tcgetattr( uartCtrl , &uartOptions) ;
cfsetispeed(&uartOptions, B57600);
cfsetospeed(&uartOptions, B57600);
uartOptions.c_cc[VMIN] = 1 ;
uartOptions.c_cflag |= ( CLOCAL | CREAD | CS8 );
uartOptions.c_iflag = IGNBRK | IGNPAR ;
tcflush( uartCtrl , TCIFLUSH);
tcsetattr( uartCtrl , TCSANOW, &uartOptions);
readUART( uartCtrl ) ;
close(uartCtrl) ;
return 0 ;
}
| 0
|
#include <pthread.h>
void psm_init(struct positrack_shared_memory* psm)
{
int i;
psm->numframes=POSITRACKSHARENUMFRAMES;
for(i = 0 ; i < psm->numframes; i++)
{
psm->id[i]=0;
psm->frame_no[i]=0;
psm->ts[i].tv_sec=0;
psm->ts[i].tv_nsec=0;
psm->x[i]=-1;
psm->y[i]=-1;
psm->hd[i]=-1;
}
if(psm->is_mutex_allocated==0)
{
pthread_mutexattr_init(&psm->attrmutex);
pthread_mutexattr_setpshared(&psm->attrmutex, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&psm->pmutex, &psm->attrmutex);
psm->is_mutex_allocated=1;
}
}
void psm_free(struct positrack_shared_memory* psm)
{
if(psm->is_mutex_allocated==1)
{
pthread_mutex_destroy(&psm->pmutex);
pthread_mutexattr_destroy(&psm->attrmutex);
}
}
void psm_add_frame(struct positrack_shared_memory* psm, unsigned long int frame_no, struct timespec fts, double x, double y, double hd)
{
int i;
pthread_mutex_lock(&psm->pmutex);
for(i =psm->numframes-1; i > 0; i--)
{
psm->id[i]=psm->id[i-1];
psm->frame_no[i]=psm->frame_no[i-1];
psm->ts[i]=psm->ts[i-1];
psm->x[i]=psm->x[i-1];
psm->y[i]=psm->y[i-1];
psm->hd[i]=psm->hd[i-1];
}
psm->id[0]=psm->id[0]+1;
psm->frame_no[0]=frame_no;
psm->ts[0]=fts;
psm->x[0]=x;
psm->y[0]=y;
psm->hd[0]=hd;
pthread_mutex_unlock(&psm->pmutex);
}
int control_shared_memory_interface_init(struct control_shared_memory_interface* csmi)
{
shm_unlink(POSITRACKCONTROLSHARE);
csmi->size=sizeof(struct positrack_control_shared_memory);
csmi->des=shm_open(POSITRACKCONTROLSHARE, O_CREAT | O_RDWR | O_TRUNC,0600);
if(csmi->des ==-1)
{
fprintf(stderr, "problem with shm_open\\n");
return -1;
}
if (ftruncate(csmi->des,csmi->size) == -1)
{
fprintf(stderr, "problem with ftruncate\\n");
return -1;
}
csmi->pcsm = (struct positrack_control_shared_memory*) mmap(0, csmi->size, PROT_READ | PROT_WRITE, MAP_SHARED, csmi->des, 0);
if (csmi->pcsm == MAP_FAILED)
{
fprintf(stderr, "csmi->pcsm mapping failed\\n");
return -1;
}
if(csmi->pcsm->is_mutex_allocated==0)
{
pthread_mutexattr_init(&csmi->pcsm->attrmutex);
pthread_mutexattr_setpshared(&csmi->pcsm->attrmutex, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&csmi->pcsm->pmutex, &csmi->pcsm->attrmutex);
csmi->pcsm->is_mutex_allocated=1;
}
csmi->pcsm->start_tracking=0;
csmi->pcsm->stop_tracking=0;
csmi->timer = g_timeout_add(500, sharedMemoryTimerCallback, 0);
return 0;
}
int control_shared_memory_interface_free(struct control_shared_memory_interface* csmi)
{
g_source_remove(csmi->timer);
if(csmi->pcsm->is_mutex_allocated==1)
{
pthread_mutex_destroy(&csmi->pcsm->pmutex);
pthread_mutexattr_destroy(&csmi->pcsm->attrmutex);
}
if(munmap(csmi->pcsm, csmi->size) == -1)
{
fprintf(stderr, "csmi->pcsm munmapping failed\\n");
return -1;
}
shm_unlink(POSITRACKCONTROLSHARE);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t saldo_mutex;
unsigned int saldo;
void *PrintHello(void *threadid)
{
long tid;
unsigned misaldo;
tid = (long)threadid;
pthread_mutex_lock(&saldo_mutex);
misaldo=saldo;
misaldo+=1;
if(tid%2==0)sleep(1);
saldo=misaldo;
pthread_mutex_unlock(&saldo_mutex);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int num_threads=atoi(argv[1]);
pthread_t threads[num_threads];
int rc;
long t;
pthread_mutex_init(&saldo_mutex,0);
for(t=0;t<num_threads;t++){
rc = pthread_create(&threads[t], 0, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
for(t=0;t<num_threads;t++){
pthread_join(threads[t], 0);
}
printf("saldo %u \\n",saldo);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int count = 0;
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *inc_count(void *idp)
{
int j,i;
double result=0.0;
long my_id = (long)idp;
for (i=0; i < 10; i++) {
pthread_mutex_lock(&count_mutex);
count++;
if (count == 12) {
pthread_cond_signal(&count_threshold_cv);
printf("inc_count(): thread %ld, count = %d Threshold reached.\\n", my_id, count);
}
printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count);
pthread_mutex_unlock(&count_mutex);
sleep(1);
}
pthread_exit(0);
}
void *watch_count(void *idp)
{
long my_id = (long)idp;
printf("Starting watch_count(): thread %ld\\n", my_id);
pthread_mutex_lock(&count_mutex);
while (count<12) {
printf("***Before cond_wait: thread %ld\\n", my_id);
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("***Thread %ld Condition signal received.\\n", my_id);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int i, rc;
pthread_t threads[6];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[2], &attr, watch_count, (void *)2);
pthread_create(&threads[3], &attr, watch_count, (void *)3);
pthread_create(&threads[4], &attr, watch_count, (void *)4);
pthread_create(&threads[5], &attr, watch_count, (void *)5);
pthread_create(&threads[0], &attr, inc_count, (void *)0);
pthread_create(&threads[1], &attr, inc_count, (void *)1);
for (i = 0; i < 6; i++) {
pthread_join(threads[i], 0);
rc = pthread_create(&threads[t], 0, watch_count, (void *)i);
if (rc){
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
printf ("Main(): Waited on %d threads. Done.\\n", 6);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit (0);
}
| 1
|
#include <pthread.h>
uint64_t i;
uint64_t j;
} walkargs;
uint64_t max = 100;
int numthreads=0;
int maxthreads=4;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_t *tid;
unsigned char *grid;
void *walkovergrid(void *args){
uint64_t i = ((walkargs*)args)->i;
uint64_t j = ((walkargs*)args)->j;
for (j;j<max;j+=i) {
( grid[(j)/8] &= ~(1<<((j)%8)) );
}
pthread_mutex_lock(&mutex);
numthreads--;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main(int argc, char* argv[]){
uint64_t i, j;
uint64_t ti=0;
walkargs *threadargs;
if ( argc > 1 ) {
max = strtoull(argv[1], 0, 0);
}
grid = malloc(max/8);
memset(grid,0xaa,max/8);
memset(grid,0b10101100,1);
threadargs = malloc(sqrt(max) * sizeof(walkargs));
tid = malloc(sqrt(max) * sizeof(pthread_t));
for (i=3; i<(uint64_t)sqrt(max); i++) {
if ( ( grid[(i)/8] & (1<<((i)%8)) ) ) {
j = (uint64_t)pow(i,2);
( grid[(j)/8] &= ~(1<<((j)%8)) );
threadargs[ti].i=i;
threadargs[ti].j=j;
pthread_create(&tid[ti], 0, walkovergrid, (void *)&threadargs[ti]);
numthreads++;
ti++;
pthread_mutex_lock(&mutex);
while ( numthreads >= maxthreads ) {
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
}
}
free(grid);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_t thr1, thr2, thr3;
pthread_attr_t attr1, attr2, attr3;
void * fonction_2(void * unused)
{
int i, j;
fprintf(stderr, " T2 demarre\\n");
fprintf(stderr, " T2 travaille...\\n");
for (i = 0; i < 100000; i ++)
for (j = 0; j < 10000; j ++)
;
fprintf(stderr, " T2 se termine\\n");
return 0;
}
void * fonction_3(void * unused)
{
int i, j;
fprintf(stderr, " T3 demarre\\n");
fprintf(stderr, " T3 demande le mutex\\n");
pthread_mutex_lock(& mutex);
fprintf(stderr, " T3 tient le mutex\\n");
fprintf(stderr, " T3 travaille...\\n");
for (i = 0; i < 100000; i ++)
for (j = 0; j < 10000; j ++)
;
fprintf(stderr, " T3 lache le mutex\\n");
pthread_mutex_unlock(& mutex);
fprintf(stderr, " T3 se termine\\n");
return 0;
}
void * fonction_1(void *unused)
{
fprintf(stderr, "T1 demarre\\n");
fprintf(stderr, "T1 demande le mutex\\n");
pthread_mutex_lock(& mutex);
fprintf(stderr, "T1 tient le mutex\\n");
fprintf(stderr, "reveil de T3\\n");
pthread_create(& thr3, &attr3, fonction_3, 0);
fprintf(stderr, "reveil de T2\\n");
pthread_create(& thr2, &attr2, fonction_2, 0);
fprintf(stderr, "T1 lache le mutex\\n");
pthread_mutex_unlock(& mutex);
fprintf(stderr, "T1 se termine\\n");
return 0;
}
int main(int argc, char * argv [])
{
struct sched_param param;
pthread_mutexattr_t attr;
pthread_mutexattr_init(& attr);
pthread_mutexattr_setprotocol (& attr, PTHREAD_PRIO_INHERIT);
pthread_mutex_init(& mutex, &attr);
pthread_attr_init(& attr1);
pthread_attr_init(& attr2);
pthread_attr_init(& attr3);
pthread_attr_setschedpolicy(& attr1, SCHED_FIFO);
pthread_attr_setschedpolicy(& attr2, SCHED_FIFO);
pthread_attr_setschedpolicy(& attr3, SCHED_FIFO);
param.sched_priority = 10;
pthread_attr_setschedparam(& attr1, & param);
param.sched_priority = 20;
pthread_attr_setschedparam(& attr2, & param);
param.sched_priority = 30;
pthread_attr_setschedparam(& attr3, & param);
pthread_attr_setinheritsched(& attr1, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setinheritsched(& attr2, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setinheritsched(& attr3, PTHREAD_EXPLICIT_SCHED);
if ((errno = pthread_create(& thr1, & attr1, fonction_1, 0)) != 0) {
perror("pthread_create");
exit(1);
}
pthread_join(thr1, 0);
return 0;
}
| 1
|
#include <pthread.h>
struct info_sclad {
int sclad[5];
int *cl_need;
int count_cl;
int *index;
};
pthread_mutex_t lock1;
pthread_mutex_t lock2;
pthread_mutex_t lock3;
pthread_mutex_t lock4;
pthread_mutex_t lock5;
pthread_mutex_t cl;
void zag_sig(int signo)
{
printf("end work\\n");
exit(0);
}
void *add_to_sclad(void *arg)
{
struct info_sclad *copy_sclad = 0;
int i;
copy_sclad = (struct info_sclad *)arg;
while(1) {
i = rand()%5;
if (i == 0)
pthread_mutex_lock(&lock1);
else if(i == 1)
pthread_mutex_lock(&lock2);
else if(i == 2)
pthread_mutex_lock(&lock3);
else if(i == 3)
pthread_mutex_lock(&lock4);
else if(i == 4)
pthread_mutex_lock(&lock5);
copy_sclad->sclad[i] = 50;
printf("add_to_sclad i = %d sclad = %d\\n", i, copy_sclad->sclad[i]);
if (i == 0)
pthread_mutex_unlock(&lock1);
else if(i == 1)
pthread_mutex_unlock(&lock2);
else if(i == 2)
pthread_mutex_unlock(&lock3);
else if(i == 3)
pthread_mutex_unlock(&lock4);
else if(i == 4)
pthread_mutex_unlock(&lock5);
sleep(5);
}
arg = (void *)copy_sclad;
}
struct info_sclad *initstruct(struct info_sclad *sclad, int count_cl)
{
int iter = 0;
sclad = malloc(sizeof(struct info_sclad));
sclad->cl_need = malloc(sizeof(int) * count_cl);
sclad->count_cl = count_cl;
sclad->index = malloc(sizeof(int) * count_cl);
for(iter = 0; iter < sclad->count_cl; iter++) {
sclad->cl_need[iter] = rand()%150;
printf("add_to_cl i = %d cl = %d\\n", iter, sclad->cl_need[iter]);
}
for(iter = 0; iter < sclad->count_cl; iter++) {
sclad->index[iter] = iter;
}
return sclad;
}
int colvo_pusto = 0;
int now_cl = 0;
void *client(void *arg)
{
struct info_sclad *copy_sclad = 0;
int i = 0, j = 0, iter = 0, end = 1;
copy_sclad = (struct info_sclad *)arg;
pthread_mutex_lock(&cl);
i = copy_sclad->index[now_cl];
now_cl++;
pthread_mutex_unlock(&cl);
while (1) {
if(copy_sclad->cl_need[i] > 0){
j = rand() % 5;
if (j == 0)
pthread_mutex_lock(&lock1);
else if(j == 1)
pthread_mutex_lock(&lock2);
else if(j == 2)
pthread_mutex_lock(&lock3);
else if(j == 3)
pthread_mutex_lock(&lock4);
else if(j == 4)
pthread_mutex_lock(&lock5);
printf("client to sclad sclad = %d, j%d\\n", copy_sclad->sclad[j], j);
if(copy_sclad->sclad[j] > 0){
printf("client do i = %d cl = %d j = %d\\n", i, copy_sclad->cl_need[i], j);
if(copy_sclad->cl_need[i] >= copy_sclad->sclad[j]) {
copy_sclad->cl_need[i] -= copy_sclad->sclad[j];
copy_sclad->sclad[j] = 0;
}
else {
copy_sclad->cl_need[i] = 0;
copy_sclad->sclad[j] -= copy_sclad->cl_need[i];
}
printf("cl posle i = %d cl = %d j = %d\\n", i, copy_sclad->cl_need[i], j);
}
}
if (j == 0)
pthread_mutex_unlock(&lock1);
else if(j == 1)
pthread_mutex_unlock(&lock2);
else if(j == 2)
pthread_mutex_unlock(&lock3);
else if(j == 3)
pthread_mutex_unlock(&lock4);
else if(j == 4)
pthread_mutex_unlock(&lock5);
if(copy_sclad->cl_need[i] == 0){
colvo_pusto++;
pthread_exit(0);
}
sleep(3);
}
arg = (void *)copy_sclad;
}
int main(int argc, char *argv[])
{
struct info_sclad *sclad = 0;
int i = 0, count_cl = 0;
pthread_mutex_init(&lock1, 0);
pthread_mutex_init(&lock2, 0);
pthread_mutex_init(&lock3, 0);
pthread_mutex_init(&lock4, 0);
pthread_mutex_init(&lock5, 0);
pthread_mutex_init(&cl, 0);
pthread_t pog;
assert(argc>1);
count_cl = atoi(argv[1]);
signal(SIGALRM, zag_sig);
pthread_t cl_init[count_cl];
sclad = initstruct(sclad, count_cl);
pthread_create(&pog, 0, add_to_sclad, (void *)sclad);
i = 0;
while(i < count_cl ){
pthread_create(&cl_init[i], 0, client, (void *)sclad);
i++;
}
for(i = 0; i<count_cl; i++)
pthread_join(cl_init[i], 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cnd = PTHREAD_COND_INITIALIZER;
struct global_data{
char task;
const int count;
};
void * task_a(void * ctx)
{
struct global_data *d = ctx;
int i;
printf("started task_a\\n");
for(i=0; i < d->count; ++i){
pthread_mutex_lock(&mtx);
while(d->task != 'a') pthread_cond_wait(&cnd, &mtx);
printf("task_a: %d\\n",i);
d->task = 'b';
pthread_cond_signal(&cnd);
pthread_mutex_unlock(&mtx);
}
return 0;
}
void * task_b(void * ctx)
{
struct global_data *d = ctx;
int i;
printf("started task_b\\n");
for(i=0; i < d->count; ++i){
pthread_mutex_lock(&mtx);
while(d->task != 'b') pthread_cond_wait(&cnd, &mtx);
printf("task_b: %d\\n",i);
d->task = 'a';
pthread_cond_signal(&cnd);
pthread_mutex_unlock(&mtx);
}
return 0;
}
int main()
{
struct global_data data = {0,10};
pthread_t thread_a;
pthread_t thread_b;
if(pthread_create(&thread_a, 0, task_a, &data)){
printf("Failed to create thread_a\\n");
exit(1);
}
if(pthread_create(&thread_b, 0, task_b, &data)){
printf("Failed to create thread_b\\n");
exit(2);
}
sleep(1);
pthread_mutex_lock(&mtx);
printf("setting task to a\\n");
data.task = 'a';
pthread_cond_signal(&cnd);
pthread_mutex_unlock(&mtx);
pthread_join(thread_a, 0);
pthread_join(thread_b, 0);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_key_t key;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;
extern char **environ;
static void
thread_init(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);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_t threads[8];
uint8_t Image[(1024*4)][(1024*4)];
int id;
double Re1, Im1, Re2, Im2;
double threshold;
int xo, yo;
int width, height;
int maxiters;
} Job;
Job jobs[(((1024*4))/256 * ((1024*4))/256)];
int free_job_idx = 0;
int processed;
void* thread_result;
} processed_t;
void* thread(void* sec) {
Job *job;
double dRe, dIm;
double Cre, Cim, Xre, Xim, Tre, Tim;
int x, y, i;
processed_t result;
result.processed = 0;
while (1) {
pthread_mutex_lock(&mutex);
if (free_job_idx == (((1024*4))/256 * ((1024*4))/256)) {
pthread_mutex_unlock(&mutex);
break;
}
else {
job = &jobs[free_job_idx];
free_job_idx += 1;
}
pthread_mutex_unlock(&mutex);
result.processed += 1;
dRe = (job->Re2 - job->Re1)/job->width;
dIm = (job->Im2 - job->Im1)/job->height;
Cim = job->Im1;
for (y=0; y < job->height; y++) {
Cre = job->Re1;
for (x=0; x < job->width; x++) {
Xre = 0.0;
Xim = 0.0;
for (i=0; i < job->maxiters; i++) {
Tre = Xre*Xre - Xim*Xim + Cre;
Tim = 2*Xre*Xim + Cim;
if (Tre*Tre + Tim*Tim > job->threshold)
break;
Xre = Tre;
Xim = Tim;
}
Image[job->yo + y][job->xo + x] = (job->maxiters - i);
Cre += dRe;
}
Cim += dIm;
}
}
return result.thread_result;
}
uint32_t get_time(void) {
struct timeval T;
gettimeofday(&T, 0);
return (T.tv_sec * 1000000) + T.tv_usec;
}
int main() {
memset(Image, 127, sizeof(Image));
int x, y, i;
FILE* f;
double Re_min = -2.0;
double Re_max = 0.5;
double Im_min = -1.0;
double Im_max = 1.0;
double ti1, ti2, tr1, tr2;
uint32_t time1, time2;
i = 0;
for (y=0; y < (1024*4); y += 256) {
ti1 = ((double)y)/(1024*4);
ti2 = ((double)y + 256)/(1024*4);
for (x=0; x < (1024*4); x += 256) {
tr1 = ((double)x)/(1024*4);
tr2 = ((double)x + 256)/(1024*4);
jobs[i].Re1 = Re_min + tr1 * (Re_max - Re_min);
jobs[i].Im1 = Im_min + ti1 * (Im_max - Im_min);
jobs[i].Re2 = Re_min + tr2 * (Re_max - Re_min);
jobs[i].Im2 = Im_min + ti2 * (Im_max - Im_min);
jobs[i].xo = x;
jobs[i].yo = y;
jobs[i].width = 256;
jobs[i].height = 256;
jobs[i].maxiters = 255;
jobs[i].threshold = 20.0;
i += 1;
}
}
pthread_mutex_init(&mutex, 0);
printf("image dimensions %d x %d\\n", (1024*4), (1024*4));
printf("image splitted into %d pieces size %d x %d\\n",
(((1024*4))/256 * ((1024*4))/256), 256, 256);
printf("%d thread(s) will be run\\n", 8);
time1 = get_time();
for (i=0; i < 8; i++) {
threads[i] = 0;
pthread_create(&threads[i], 0, thread, 0);
}
for (i=0; i < 8; i++)
pthread_join(threads[i], 0);
time2 = get_time();
printf("all threads finished after %0.3fs, saving image\\n", (time2-time1)/1000000.0);
f = fopen("mandelbrot.pgm", "wb");
if (f != 0) {
fprintf(f, "P5\\n%d %d 255\\n", (int)(1024*4), (int)(1024*4));
fwrite(Image, sizeof(Image), 1, f);
fclose(f);
return 0;
}
else {
puts("ERROR: Can't open file for writing!");
return 1;
}
}
| 1
|
#include <pthread.h>
void *playAudioThread(void *arg) {
int status;
appLog(LOG_DEBUG, "inside playAudioThread..........");
char *filename = arg;
char *FilePath;
FilePath = malloc(FILE_PATH_LEN_MAX);
if (!FilePath) {
appLog(LOG_DEBUG, "allocated memory failed, thread %d exited",
(int)pthread_self());
pthread_exit(0);
}
memset(FilePath, 0, FILE_PATH_LEN_MAX);
appLog(LOG_DEBUG, "File to play: %s", filename);
strcat(FilePath, (char *) DEFAULT_PATH);
strcat(FilePath, filename);
appLog(LOG_DEBUG, "File Path: %s", FilePath);
appLog(LOG_DEBUG, "deallocating memory");
free(arg);
free(FilePath);
appLog(LOG_DEBUG, "exit playAudioThread..........");
pthread_exit(0);
}
int stopAudio() {
pthread_mutex_lock(&g_audio_status_mutex);
g_audio_flag = AUDIO_STOP;
pthread_mutex_unlock(&g_audio_status_mutex);
return ACP_SUCCESS;
}
int pauseAudio() {
pthread_mutex_lock(&g_audio_status_mutex);
g_audio_flag = AUDIO_PAUSE;
pthread_mutex_unlock(&g_audio_status_mutex);
return ACP_SUCCESS;
}
| 0
|
#include <pthread.h>
pthread_cond_t is_waiting[10];
pthread_cond_t is_haircutting = PTHREAD_COND_INITIALIZER;
pthread_mutex_t semaphore = PTHREAD_MUTEX_INITIALIZER;
pthread_t t1, t2[10];
int args[10];
int next = 0;
int last = 0;
int waiting_customers_qty;
int seats[8];
int customer_status[10];
void *customer(void *arg){
int CID = *(int*)arg;
for(;;){
sleep(random() % 3);
pthread_mutex_lock(&semaphore);
printf("Entra cliente %d\\n", CID);
if(waiting_customers_qty == 10)
printf("Barberia llena. cliente %d se retira\\n", CID);
else{
waiting_customers_qty += 1;
seats[last] = CID;
if(++last >= 10)
last = 0;
customer_status[CID] = 1;
printf("Cliente %d ocupa el asiento %d\\n", CID, last);
pthread_cond_signal(&is_haircutting);
while(customer_status[CID])
pthread_cond_wait(&is_waiting[CID], &semaphore);
printf("Cliente %d se retira\\n", CID);
}
pthread_mutex_unlock(&semaphore);
}
return 0;
}
void *barber(void *arg){
for(;;) {
sleep(random() % 3);
pthread_mutex_lock(&semaphore);
while(waiting_customers_qty == 0)
pthread_cond_wait(&is_haircutting, &semaphore);
printf("Barbero comienza a atender\\n");
int id = seats[next];
printf("El barbero corta pelo a cliente %d\\n", id);
customer_status[id] = 0;
waiting_customers_qty -= 1;
if (++next >= 8)
next = 0;
pthread_cond_signal(&is_waiting[id]);
pthread_mutex_unlock(&semaphore);
}
return 0;
}
int main(){
int i;
pthread_create(&t1, 0, barber, 0);
for(i = 0; i < 10; i++){
args[i] = i;
pthread_cond_init(&is_waiting[i], 0);
pthread_create(&t2[i], 0, customer, (void*)&args[i]);
}
pthread_join(t1, 0);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER;
void output_init()
{
return;
}
void output( char * string, ... )
{
va_list ap;
char *ts="[??:??:??]";
struct tm * now;
time_t nw;
pthread_mutex_lock(&m_trace);
nw = time(0);
now = localtime(&nw);
if (now == 0)
printf(ts);
else
printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec);
__builtin_va_start((ap));
vprintf(string, ap);
;
pthread_mutex_unlock(&m_trace);
}
void output_fini()
{
return;
}
| 0
|
#include <pthread.h>
static pthread_t thread;
static pthread_cond_t cond;
static pthread_mutex_t mutex;
static int flag = 1;
void * thr_fn(void * arg)
{
struct timeval now;
struct timespec outtime;
pthread_mutex_lock(&mutex);
while (flag)
{
printf("*****\\n");
gettimeofday(&now, 0);
outtime.tv_sec = now.tv_sec + 5;
outtime.tv_nsec = now.tv_usec * 1000;
pthread_cond_timedwait(&cond, &mutex, &outtime);
}
pthread_mutex_unlock(&mutex);
printf("cond thread exit\\n");
}
int main(void)
{
char c ;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
if (0 != pthread_create(&thread, 0, thr_fn, 0))
{
printf("error when create pthread,%d\\n", errno);
return 1;
}
while ((c = getchar()) != 'q');
printf("Now terminate the thread!\\n");
pthread_mutex_lock(&mutex);
flag = 0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
printf("Wait for thread to exit\\n");
pthread_join(thread, 0);
printf("Bye\\n");
return 0;
}
| 1
|
#include <pthread.h>
struct User_list* list_init()
{
struct User_list* list = malloc( sizeof( struct User_list ) );
list->head = 0;
pthread_mutex_init( &( list->mutex ), 0 );
return list;
}
void list_free( struct User_list* list )
{
if( list == 0 )
{
return;
}
pthread_mutex_destroy( &list->mutex );
struct User_node* node = list->head;
struct User_node* tmp = 0;
while( node != 0 )
{
tmp = node;
node = node->next;
node_free( tmp );
}
free( list );
list = 0;
}
void list_append_node( struct User_list* list, struct User_node* unode )
{
assert( list );
assert( unode );
unode->next = list->head;
list->head = unode;
}
bool list_user_exists( struct User_list* list, char const* nick )
{
assert( list );
assert( nick );
struct User_node* unode = list->head;
while( unode != 0 )
{
if( strcmp( unode->nick, nick ) == 0 )
return 1;
else
unode = unode->next;
}
return 0;
}
void list_send_foreach( struct User_list* list, char const* nick, char const* message )
{
assert( list );
assert( nick );
assert( message );
time_t rawtime;
struct tm * timeinfo;
char buffer [ 8 ] = {'\\0'};
time( &rawtime );
timeinfo = localtime( &rawtime );
strftime( buffer, 8, " %H:%M ", timeinfo );
int const full_message_len = 19 + strlen( nick ) + strlen( message ) + 1;
char* full_message = malloc( full_message_len );
memset( full_message, '\\0', full_message_len );
strcpy( full_message, "[" );
strcat( full_message, nick );
strcat( full_message, buffer );
strcat( full_message, "]: " );
strcat( full_message, message );
strcat( full_message, ">>>> " );
struct User_node* unode = list->head;
while( unode != 0 )
{
puts( "broadcasting" );
if( strcmp( unode->nick, nick ) == 0 )
{
unode = unode->next;
continue;
}
node_send_data( unode, full_message, full_message_len );
unode = unode->next;
}
free( full_message );
}
void list_del_user( struct User_list* list, char const* nick )
{
struct User_node* prev = 0;
struct User_node* node = list->head;
while( node != 0 )
{
if( strcmp( node->nick, nick ) == 0 )
{
pthread_mutex_lock( &list->mutex );
if( prev == 0 )
{
list->head = node->next;
}
else
{
prev->next = node->next;
}
node_free( node );
pthread_mutex_unlock( &list->mutex );
break;
}
prev = node;
node = node->next;
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t chop_mutex[5];
void *doit(void *vptr)
{
int *i,a,b;
i = vptr;
while(1)
{
pthread_mutex_lock(&chop_mutex[(*i + 4) % 5]);
printf("Philosopher %c fetches chopstick %d\\n", *i + 'A',(*i + 4) % 5);
if (!pthread_mutex_trylock(&chop_mutex[*i]))
{
printf("Philosopher %c fetches chopstick %d\\n", *i + 'A',*i);
sleep(rand() % 10);
printf("Philosopher %c releases chopsticks %d %d\\n", *i + 'A',*i, (*i + 4) % 5);
pthread_mutex_unlock(&chop_mutex[(*i + 4) % 5]);
pthread_mutex_unlock(&chop_mutex[*i]);
return 0;
}
else
{
pthread_mutex_unlock(&chop_mutex[(*i + 4) % 5]);
sleep(rand() % 10);
}
}
}
int main(void)
{
int i = 0;
pthread_t tid[5];
srand(time(0));
int count[5];
for (i = 0; i < 5; i++)
pthread_mutex_init(&chop_mutex[i], 0);
for (i = 0; i < 5; i++)
{
count[i] = i;
pthread_create(&tid[i], 0, &doit, (void *)&count[i]);
}
for (i = 0; i < 5; i++)
pthread_join(tid[i], 0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_t thread[2];
pthread_mutex_t mut;
int share_resource = 0, i;
void *thread1()
{
printf("thread1 : I'm thread 1\\n");
for (i = 0; i < 5; i++) {
printf("thread1 : share_resource = %d\\n", share_resource);
pthread_mutex_lock(&mut);
share_resource++;
pthread_mutex_unlock(&mut);
sleep(2);
}
printf("thread1 :主函数在等我完成任务吗?\\n");
pthread_exit(0);
}
void *thread2()
{
printf("thread2 : I'm thread 2\\n");
for (i = 0; i < 5; i++) {
printf("thread2 : share_resource = %d\\n", share_resource);
pthread_mutex_lock(&mut);
share_resource++;
pthread_mutex_unlock(&mut);
sleep(3);
}
printf("thread2 :主函数在等我完成任务吗?\\n");
pthread_exit(0);
}
void thread_create(void)
{
int temp;
memset(&thread, 0, sizeof(thread));
if ((temp = pthread_create(&thread[0], 0, thread1, 0)) != 0)
printf("线程1创建失败!\\n");
else
printf("线程1被创建.\\n");
if ((temp = pthread_create(&thread[1], 0, thread2, 0)) != 0)
printf("线程2创建失败!\\n");
else
printf("线程2被创建.\\n");
}
void thread_wait(void)
{
if (thread[0] != 0) {
pthread_join(thread[0], 0);
printf("线程1已经结束\\n");
}
if (thread[1] != 0) {
pthread_join(thread[1], 0);
printf("线程2已经结束\\n");
}
}
int main()
{
pthread_mutex_init(&mut, 0);
printf("我是主函数,我正在创建线程\\n");
thread_create();
printf("我是主函数,我正在等待线程完成任务\\n");
thread_wait();
printf("我是主进程,我在等\\n");
return 0;
}
| 0
|
#include <pthread.h>
struct thread_data
{
int thread_id;
int offset;
int end_point;
};
pthread_mutex_t lock;
pthread_cond_t ok_to_proceed;
int threads_completed;
} barrier_t;
int N, NUM_THREADS, currentPrime = 2, *primes;
barrier_t barrier;
FILE *file;
pthread_mutex_t print_mutex = PTHREAD_MUTEX_INITIALIZER;
void barrier_init(barrier_t* b){
pthread_mutex_init(&(b->lock), 0);
pthread_cond_init(&(b->ok_to_proceed), 0);
b->threads_completed = 0;
}
void getNextPrime(){
int i = currentPrime;
for ( i = i+1; i < N; i++) {
if(primes[i]==0){
currentPrime = i;
return;
}
}
}
void* syncPoint(barrier_t *b){
pthread_mutex_lock(&b->lock);
b->threads_completed++;
if(b->threads_completed<NUM_THREADS){
pthread_cond_wait(&b->ok_to_proceed, &b->lock);
}
else if(b->threads_completed==NUM_THREADS){
b->threads_completed = 0;
getNextPrime();
pthread_cond_broadcast(&b->ok_to_proceed);
}
pthread_mutex_unlock(&b->lock);
return 0;
}
void *getPrimes(void *threadarg)
{
struct thread_data *my_data = (struct thread_data*)threadarg;
int startAt = my_data->offset;
int stopAt = my_data->end_point;
while (currentPrime < sqrt(N)) {
for (int x = startAt ; x <= stopAt; x++) {
if(x%currentPrime == 0 && primes[x]== 0 && currentPrime!=x){
primes[x] = -1;
}
}
if(NUM_THREADS>1){
syncPoint(&barrier);
}else{
currentPrime++;
}
}
pthread_exit(0);
}
int main(int argc, char *argv[])
{
if(argc<3){
printf("Argument parse error**.\\n\\tmain <number> <threads>\\n");
return -1;
}
if(atoi(argv[2])<1){
printf("Invalid number of threads\\n");
return -1;
}
N = atoi(argv[1]);
if(N<2){
printf("N MUST be > 2\\n");
return -1;
}
NUM_THREADS = atoi(argv[2]);
struct thread_data thread_data_array[NUM_THREADS];
primes = malloc(sizeof(int) * N);
barrier_init(&barrier);
for (int i = 0 ; i < N; i++)
primes[i]=0;
pthread_t threads[NUM_THREADS];
int rc;
for(int t = 0;t < NUM_THREADS;t++) {
thread_data_array[t].thread_id = t;
if(t==0)
thread_data_array[t].offset = 2;
else
thread_data_array[t].offset = t*N/NUM_THREADS+1;
thread_data_array[t].end_point = (t+1)*N/NUM_THREADS;
rc = pthread_create(&threads[t],0,getPrimes,(void*) &thread_data_array[t]);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], 0);
}
file = fopen("primes.txt", "w");
int count_primes=0;
printf("prime numbers between %d and %d\\n\\n",2,N);
fprintf(file, "prime numbers between %d and %d\\n\\n",2,N);
for (int i = 2 ; i <= N; i++) {
if(primes[i] == 0){
fprintf(file, "%d ",i);
printf("%d ",i);
count_primes++;
}
}
printf("\\n\\n%d prime number(s) found\\n\\n",count_primes);
fprintf(file,"\\n\\n%d prime number(s) found\\n\\n",count_primes);
fclose(file);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
struct atm_log {
uintptr_t i;
uintptr_t thd_id;
uintptr_t c;
void *p;
uintptr_t o;
uintptr_t n;
const char *file;
uintptr_t line;
};
static struct atm_log log_entries[1 << 14];
static uint32_t log_i;
static pthread_mutex_t log_mu;
static pthread_key_t key;
static pthread_once_t once = PTHREAD_ONCE_INIT;
static void do_once (void) {
pthread_mutex_init (&log_mu, 0);
pthread_key_create (&key, 0);
}
static int thread_id;
void nsync_atm_log_ (int c, void *p, uint32_t o, uint32_t n, const char *file, int line) {
if (0) {
struct atm_log *e;
uint32_t i;
int *pthd_id;
int thd_id;
pthread_once (&once, &do_once);
pthd_id = (int *) pthread_getspecific (key);
pthread_mutex_lock (&log_mu);
i = log_i++;
if (pthd_id == 0) {
thd_id = thread_id++;
pthd_id = (int *) malloc (sizeof (*pthd_id));
pthread_setspecific (key, pthd_id);
*pthd_id = thd_id;
} else {
thd_id = *pthd_id;
}
pthread_mutex_unlock (&log_mu);
e = &log_entries[i & ((1 << 14) - 1)];
e->i = i;
e->thd_id = thd_id;
e->c = c;
e->p = p;
e->o = o;
e->n = n;
e->file = file;
e->line = line;
}
}
void nsync_atm_log_print_ (void) {
if (0) {
uint32_t i;
pthread_once (&once, &do_once);
pthread_mutex_lock (&log_mu);
for (i = 0; i != (1 << 14); i++) {
struct atm_log *e = &log_entries[i];
if (e->file != 0) {
fprintf (stderr, "%6lx %3d %c p %16p o %8x n %8x %10s:%d\\n",
(unsigned long) e->i,
(int) e->thd_id,
e->c <= ' '? '?' : (char)e->c,
e->p,
(uint32_t) e->o,
(uint32_t) e->n,
e->file,
(int) e->line);
}
}
pthread_mutex_unlock (&log_mu);
}
}
| 0
|
#include <pthread.h>
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo {
int f_count;
pthread_mutex_t f_lock;
struct foo *f_next;
int f_id;
};
struct foo *foo_alloc()
{
struct foo *fp;
int idx;
if((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 1;
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);
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;
idx = 29(fp);
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_lock(&hashlock);
return (fp);
}
void foo_rele(struct foo *fp)
{
struct foo *tfp;
int idx;
pthread_mutex_lock(&fp->f_lock);
if(fp->f_count == 1) {
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_lock(&hashlock);
pthread_mutex_lock(&fp->f_lock);
if(fp->f_count != 1) {
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
return;
}
idx = (((unsigned long)fp) % 29);
tfp = fh[idx];
if(tfp == fp) {
fh[idx] = fp->f_next;
}
else {
while(tfp->f_next != fp) {
tfp = tfp->f_next;
}
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
}
else {
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
}
}
| 1
|
#include <pthread.h>
int nthreads;
pthread_mutex_t chopstick[50];
FILE *fp = fopen("status.txt", "a");
void thinking(){
int rnd = (random() % 499) + 1;
usleep(rnd);
}
void eating(int threadIndex){
int rnd = (random() % 499) + 1;
fprintf(fp, "Philosopher %d is eating\\n", threadIndex);
usleep(rnd);
}
void pickUpChopsticks(int threadIndex){
int right;
int left = threadIndex;
if(threadIndex == 0){
right = nthreads - 1;
}else{
right = threadIndex - 1;
}
pthread_mutex_lock(&chopstick[left]);
pthread_mutex_lock(&chopstick[right]);
}
void putDownChopsticks(int threadIndex){
int right;
int left = threadIndex;
if(threadIndex == 0){
right = nthreads - 1;
}else{
right = threadIndex - 1;
}
pthread_mutex_unlock(&chopstick[left]);
pthread_mutex_unlock(&chopstick[right]);
}
void *PhilosopherThread(void *threadID){
long tid;
tid = (long)threadID;
thinking();
pickUpChopsticks(tid);
eating(tid);
putDownChopsticks(tid);
pthread_exit(0);
}
void createPhilosophers(int nthreads){
pthread_t threads[nthreads];
int rc;
long i;
void *status;
for(i = 0; i < nthreads; i++){
rc = pthread_create(&threads[i], 0, PhilosopherThread, (void *)i);
if(rc){
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
for(i = 0; i < nthreads; i++){
rc = pthread_join(threads[i], &status);
if(rc){
printf("ERROR; return code from pthread_join() is %d\\n", rc);
exit(-1);
}
}
pthread_exit(0);
}
int main(int argc, char ** argv ){
nthreads = atoi(argv[1]);
srandom(time(0));
for(int i = 0; i < nthreads; i++){
pthread_mutex_init(&chopstick[i], 0);
}
createPhilosophers(nthreads);
fclose(fp);
for(int j = 0; j < nthreads; j++){
pthread_mutex_destroy(&chopstick[j]);
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int flag =0 ;
void * pthread_a(void *arga){
fprintf(stderr,"flag a %ld\\n",flag);
pthread_mutex_lock(&mutex);
flag = 1;
fprintf(stderr,"flag a %ld\\n",flag);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
fprintf(stderr , "a finish !\\n");
sleep(1);
sleep(1);
sleep(1);
sleep(1);
sleep(1);
pthread_exit(0);
}
void * pthread_b(void *argb){
pthread_mutex_lock(&mutex);
fprintf(stderr,"flag b %ld\\n",flag);
while(flag != 1)
pthread_cond_wait(&cond,&mutex);
flag = 2;
fprintf(stderr,"flag b %ld\\n",flag);
pthread_mutex_unlock(&mutex);
fprintf(stderr , "b finish !\\n!");
pthread_exit(0);
}
int arg[2]={0};
int main(void)
{
pthread_t tid[2];
int ret;
ret = pthread_create(&tid[0], 0,pthread_a, 0);
if (ret != 0 )
fprintf(stderr , "create a error\\n");
ret = pthread_create(&tid[1], 0,pthread_b, 0);
if (ret != 0 )
fprintf(stderr , "create b error\\n");
pthread_join(tid[0],0);
pthread_join(tid[1],0);
sleep(1);
fprintf(stderr , "main exit ! \\n");
return 0;
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error();
static int iTThreads = 2;
static int iRThreads = 1;
static int data1Value = 0;
static int data2Value = 0;
pthread_mutex_t *data1Lock;
pthread_mutex_t *data2Lock;
void lock(pthread_mutex_t *);
void unlock(pthread_mutex_t *);
void *funcA(void *param) {
pthread_mutex_lock(data1Lock);
data1Value = 1;
pthread_mutex_unlock(data1Lock);
pthread_mutex_lock(data2Lock);
data2Value = data1Value + 1;
pthread_mutex_unlock(data2Lock);
return 0;
}
void *funcB(void *param) {
int t1 = -1;
int t2 = -1;
pthread_mutex_lock(data1Lock);
if (data1Value == 0) {
pthread_mutex_unlock(data1Lock);
return 0;
}
t1 = data1Value;
pthread_mutex_unlock(data1Lock);
pthread_mutex_lock(data2Lock);
t2 = data2Value;
pthread_mutex_unlock(data2Lock);
if (t2 != (t1 + 1)) {
fprintf(stderr, "Bug found!\\n");
ERROR: __VERIFIER_error();
;
}
return 0;
}
int main(int argc, char *argv[]) {
int i,err;
if (argc != 1) {
if (argc != 3) {
fprintf(stderr, "./twostage <param1> <param2>\\n");
exit(-1);
} else {
sscanf(argv[1], "%d", &iTThreads);
sscanf(argv[2], "%d", &iRThreads);
}
}
data1Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
data2Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
if (0 != (err = pthread_mutex_init(data1Lock, 0))) {
fprintf(stderr, "pthread_mutex_init error: %d\\n", err);
exit(-1);
}
if (0 != (err = pthread_mutex_init(data2Lock, 0))) {
fprintf(stderr, "pthread_mutex_init error: %d\\n", err);
exit(-1);
}
pthread_t tPool[iTThreads];
pthread_t rPool[iRThreads];
for (i = 0; i < iTThreads; i++) {
if (0 != (err = pthread_create(&tPool[i], 0, &funcA, 0))) {
fprintf(stderr, "Error [%d] found creating 2stage thread.\\n", err);
exit(-1);
}
}
for (i = 0; i < iRThreads; i++) {
if (0 != (err = pthread_create(&rPool[i], 0, &funcB, 0))) {
fprintf(stderr, "Error [%d] found creating read thread.\\n", err);
exit(-1);
}
}
for (i = 0; i < iTThreads; i++) {
if (0 != (err = pthread_join(tPool[i], 0))) {
fprintf(stderr, "pthread join error: %d\\n", err);
exit(-1);
}
}
for (i = 0; i < iRThreads; i++) {
if (0 != (err = pthread_join(rPool[i], 0))) {
fprintf(stderr, "pthread join error: %d\\n", err);
exit(-1);
}
}
return 0;
}
void lock(pthread_mutex_t *lock) {
int err;
if (0 != (err = pthread_mutex_lock(lock))) {
fprintf(stderr, "Got error %d from pthread_mutex_lock.\\n", err);
exit(-1);
}
}
void unlock(pthread_mutex_t *lock) {
int err;
if (0 != (err = pthread_mutex_unlock(lock))) {
fprintf(stderr, "Got error %d from pthread_mutex_unlock.\\n", err);
exit(-1);
}
}
| 0
|
#include <pthread.h>
void init_matrix (int *matrix, int fils, int cols) {
int i, j;
for (i = 0; i < fils; i++) {
for (j = 0; j < cols; j++) {
matrix[i * cols + j] = 1;
}
}
}
int *matrix1;
int *matrix2;
int *matrixR;
int matrix1_fils;
int matrix1_cols;
int matrix2_fils;
int matrix2_cols;
pthread_t *thread_list;
pthread_mutex_t mutex;
int pending_jobs = 0;
struct job {
int i, j;
struct job *next;
};
struct job *job_list = 0;
struct job *last_job = 0;
void add_job(int i, int j){
struct job *job = malloc(sizeof(struct job));
job->i = i;
job->j = j;
job->next = 0;
if(pending_jobs == 0){
job_list = job;
last_job = job;
}
else{
last_job->next = job;
last_job = job;
}
pending_jobs++;
}
struct job* get_job(){
struct job *job = 0;
if(pending_jobs > 0){
job = job_list;
job_list = job->next;
if(job_list == 0){
last_job = 0;
}
pending_jobs--;
}
return job;
}
void do_job(struct job *job) {
int k, acum;
acum = 0;
for (k = 0; k < matrix1_cols; k++) {
acum += matrix1[job->i * matrix1_cols + k] * matrix2[k * matrix2_cols + job->j];
}
matrixR[job->i * matrix2_cols + job->j] = acum;
}
void* dispatch_job () {
struct job *job;
while(1) {
pthread_mutex_lock(&mutex);
job = get_job();
pthread_mutex_unlock(&mutex);
if (job) {
do_job(job);
free(job);
}
else {
pthread_exit(0);
}
}
}
int main (int argc, char **argv) {
if (argc > 3) {
printf("\\n%s %s %s %s\\n", argv[0], argv[1], argv[2], argv[3]);
matrix1_fils = strtol(argv[1], (char **) 0, 10);
matrix1_cols = strtol(argv[2], (char **) 0, 10);
matrix2_fils = matrix1_cols;
matrix2_cols = strtol(argv[3], (char **) 0, 10);
int i,j;
matrix1 = (int *) calloc(matrix1_fils * matrix1_cols, sizeof(int));
matrix2 = (int *) calloc(matrix2_fils * matrix2_cols, sizeof(int));
matrixR = (int *) malloc(matrix1_fils * matrix2_cols * sizeof(int));
init_matrix(matrix1, matrix1_fils, matrix1_cols);
init_matrix(matrix2, matrix2_fils, matrix2_cols);
for (i = 0; i < matrix1_fils; i++) {
for (j = 0; j < matrix2_cols; j++) {
add_job(i,j);
}
}
thread_list = malloc(sizeof(int) * 3);
pthread_mutex_init(&mutex, 0);
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS);
for (i = 0; i < 3; i++) {
pthread_create(&thread_list[i], &attr, dispatch_job, 0);
}
for (i = 0; i < 3; i++) {
pthread_join(thread_list[i], 0);
}
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&mutex);
free(thread_list);
free(matrix1);
free(matrix2);
free(matrixR);
return 0;
}
fprintf(stderr, "Uso: %s filas_matriz1 columnas_matriz1 columnas_matriz2\\n", argv[0]);
return -1;
}
| 1
|
#include <pthread.h>
pthread_mutex_t value_lock = PTHREAD_MUTEX_INITIALIZER;
int value = 0;
void* thread_func1(void *arg)
{
pthread_mutex_lock(&value_lock);
int count = 1;
while (count++ <= 5) {
value += 1;
printf("thread 1: value = %d\\n", value);
}
pthread_mutex_unlock(&value_lock);
pthread_exit((void*)1);
}
void* thread_func2(void *arg)
{
pthread_mutex_lock(&value_lock);
int count = 1;
while (count++ <= 5) {
value += 10;
printf("thread 2: value = %d\\n", value);
}
pthread_mutex_unlock(&value_lock);
pthread_exit((void*)2);
}
void* thread_func3(void *arg)
{
pthread_mutex_lock(&value_lock);
int count = 1;
while (count++ <= 5) {
value += 100;
printf("thread 3: value = %d\\n", value);
}
pthread_mutex_unlock(&value_lock);
pthread_exit((void*)3);
}
void* thread_func4(void *arg)
{
pthread_mutex_lock(&value_lock);
int count = 1;
while (count++ <= 5) {
value += 1000;
printf("thread 4: value = %d\\n", value);
}
pthread_mutex_unlock(&value_lock);
pthread_exit((void*)4);
}
void* thread_func5(void *arg)
{
pthread_mutex_lock(&value_lock);
int count = 1;
while (count++ <= 5) {
value += 10000;
printf("thread 5: value = %d\\n", value);
}
pthread_mutex_unlock(&value_lock);
pthread_exit((void*)5);
}
int main(void)
{
int err;
pthread_t tid1, tid2, tid3, tid4, tid5;
err = pthread_create(&tid1, 0, thread_func1, 0);
if (0 != err) {
printf("can't create thread 1: %s\\n", strerror(err));
abort();
}
err = pthread_create(&tid2, 0, thread_func2, 0);
if (0 != err) {
printf("can't create thread 2: %s\\n", strerror(err));
abort();
}
err = pthread_create(&tid3, 0, thread_func3, 0);
if (0 != err) {
printf("can't create thread 3: %s\\n", strerror(err));
abort();
}
err = pthread_create(&tid4, 0, thread_func4, 0);
if (0 != err) {
printf("can't create thread 4: %s\\n", strerror(err));
abort();
}
err = pthread_create(&tid5, 0, thread_func5, 0);
if (0 != err) {
printf("can't create thread : %s\\n", strerror(err));
abort();
}
sleep(1);
printf("main thread end\\n");
exit(0);
}
| 0
|
#include <pthread.h>
int SendMsgToUser(struct IRCAllUsers *allusers, const char *nick,
const char *msg) {
int ret = 0;
struct IRCUser *ptr;
struct Client *thr_info;
int written, len;
len = strlen(msg);
pthread_mutex_lock(&allusers->lock);
ptr = GetUserPtr(allusers, nick);
if (ptr == 0) {
ret = -1;
} else {
thr_info = ptr->thr_info;
pthread_mutex_lock(&thr_info->send_lock);
written = write(thr_info->sockfd, msg, len);
pthread_mutex_unlock(&thr_info->send_lock);
}
pthread_mutex_unlock(&allusers->lock);
if (written != len) {
ret = -1;
}
return ret;
}
int SendMsgToChannel(struct IRCAllChannels *channels,
struct IRCAllUsers *allusers, const char *channame,
const char *nick, const char *msg) {
int ret = 0;
int i;
struct IRCChannel *chan_ptr;
struct Client *thr_info;
char *str;
int written, len;
len = strlen(msg);
pthread_mutex_lock(&channels->lock);
pthread_mutex_lock(&allusers->lock);
chan_ptr = GetChannelPtr(channels, channame);
if (chan_ptr == 0) {
ret = -1;
} else {
for (i = 0; i < IRC_CHANUSERS_MAX; i++) {
if (chan_ptr->users[i] != 0) {
str = chan_ptr->users[i]->nick;
if (strncmp(str, nick, IRC_NICK_MAX_LENGTH) != 0) {
thr_info = chan_ptr->users[i]->thr_info;
pthread_mutex_lock(&thr_info->send_lock);
written = write(thr_info->sockfd, msg, len);
pthread_mutex_unlock(&thr_info->send_lock);
}
}
}
}
pthread_mutex_unlock(&allusers->lock);
pthread_mutex_unlock(&channels->lock);
if (written != len) {
ret = -1;
}
return ret;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int n;
} data;
void print_char_by_char(char *s, int n) {
int i = 0;
while (s[i] != '\\0') {
printf("%c", s[i]);
fflush(stdout);
i++;
struct timespec tim, tim2;
tim.tv_sec = 0;
tim.tv_nsec = 500000000L;
nanosleep(&tim , &tim2);
}
printf("%d \\n", n);
sleep(1);
}
void *mytask(void *p_data) {
char *message = "Thread_n ";
data *info = p_data;
pthread_mutex_lock(&mutex);
print_char_by_char(message, info->n);
pthread_mutex_unlock(&mutex);
return 0;
}
int main(void) {
printf("main start\\n");
int i;
pthread_t threads[5];
data infos[5];
for (i = 0; i < 5; i++) {
infos[i].n = i;
pthread_create(&threads[i], 0, mytask, &infos[i]);
}
for (i = 0; i < 5; i++) {
pthread_join(threads[i], 0);
}
printf("main end\\n");
}
| 0
|
#include <pthread.h>
char q[5][1024];
char data[1024];
int first = 0;
int last = 0;
int count = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t empty = PTHREAD_MUTEX_INITIALIZER;
void insertQ(char x[], int *first) {
pthread_mutex_lock(&mutex);
strcpy(q[*first], x);
*first++;
count++;
pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&empty);
}
void dequeue( int *last) {
char getdata[1024];
while (count == 0) pthread_mutex_lock(&empty);
pthread_mutex_lock(&mutex);
strcpy(getdata,q[*last]);
*last++;
printf("count in dqueue = %d \\n",count) ;
count--;
pthread_mutex_unlock(&mutex);
printf ("string dequeued from queue is : %s \\n" , getdata);
conv(strlen(getdata));
}
void * prod(void *arg) {
int input;
while(1){
printf("********Enter the string to insert in queue******* \\n");
scanf ("%s", data);
insertQ(data, &first);
sleep(1);
}
}
void * con(void *arg) {
while(1)
{
dequeue(&last);
}
}
void printstr(char x[])
{
printf ("string dequeued from queue is %s \\n" , x);
printf("number of words in string %zd \\n", strlen(x));
}
void main()
{
pthread_t threadp1;
pthread_t threadc1;
int zero = 0; int one = 1;
pthread_create(&threadp1, 0, prod, &zero);
pthread_create(&threadc1, 0, con, 0);
pthread_exit(0);
}
void conv(int number)
{
printf("string length in digits: %d \\n", number);
printf("string length in digits: ");
int x = number;
int len =0;
do
{
x=x/10;
len++;
}while (x!=0);
char *num ;
int unit=0;
int tens=0;
int hun=0;
unit = number%10;
tens = ((number/10)%10);
hun = (number/100)%10;
if (len == 0) {
fprintf(stderr, "empty string\\n");
return;
}
if (len > 3) {
fprintf(stderr, "Length more than 4 is not supported\\n");
return;
}
char *single_digits[] = { "zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"};
char *two_digits[] = {"", "ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
char *tens_multiple[] = {"", "", "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety"};
char *tens_power[] = {"hundred"};
if (len == 1) {
printf("%s\\n", single_digits[unit-0]);
return;
}
if (tens ==1){
printf("%s \\n", two_digits[unit+1]);
return;
}
if (hun==0)
{
if (unit !=0){
printf("%s ", tens_multiple[tens]);
printf("%s\\n", single_digits[unit-0]);
}
else
printf("%s \\n", tens_multiple[tens]);
}
else
{ if (unit != 0 && tens !=0 )
{
printf("%s ", single_digits[hun]);
printf("%s " , tens_power[0]);
printf("%s ", tens_multiple[tens]);
printf("%s\\n", single_digits[unit-0]);
}
else if (unit == 0 && tens !=0)
{
printf("%s ", single_digits[hun]);
printf("%s " , tens_power[0]);
printf("%s \\n", tens_multiple[tens]);
}
else {
printf("%s ", single_digits[hun]);
printf("%s " , tens_power[0]);
printf("%s\\n", single_digits[unit-0]);
}
}
printf("\\n\\n");
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error();
unsigned int __VERIFIER_nondet_uint();
static int top = 0;
static unsigned int arr[5];
pthread_mutex_t m;
_Bool flag = 0;
void error(void)
{
ERROR:
__VERIFIER_error();
return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
top == 0 ? 1 : 0;
}
int push(unsigned int *stack, int x)
{
if (top == 5)
{
printf("stack overflow\\n");
return -1;
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (top == 0)
{
printf("stack underflow\\n");
return -2;
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for (i = 0; i < 5; i++)
{
__CPROVER_assume(((5 - i) >= 0) && (i >= 0));
{
__CPROVER_assume(((5 - i) >= 0) && (i >= 0));
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint() % 5;
if (push(arr, tmp) == (-1))
error();
pthread_mutex_unlock(&m);
}
}
}
}
void *t2(void *arg)
{
int i;
for (i = 0; i < 5; i++)
{
__CPROVER_assume(((5 - i) >= 0) && (i >= 0));
{
pthread_mutex_lock(&m);
if (top > 0)
{
if (pop(arr) == (-2))
error();
}
pthread_mutex_unlock(&m);
}
}
}
int main(void)
{
pthread_t id1;
pthread_t 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 n = 1, okX = 0, okZ = 0;
pthread_cond_t fimX = PTHREAD_COND_INITIALIZER, fimZ = PTHREAD_COND_INITIALIZER;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
void X(void *argp)
{
pthread_mutex_lock(&m);
n = n*16;
pthread_cond_signal(&fimX);
okX = 1;
pthread_mutex_unlock(&m);
pthread_exit(0);
}
void Y(void *argp)
{
pthread_mutex_lock(&m);
while (!okZ)
pthread_cond_wait(&fimZ, &m);
n = n/7;
pthread_mutex_unlock(&m);
pthread_exit(0);
}
void Z(void *argp)
{
pthread_mutex_lock(&m);
while (!okX)
pthread_cond_wait(&fimX, &m);
n = n+40;
pthread_cond_signal(&fimZ);
okZ = 1;
pthread_mutex_unlock(&m);
pthread_exit(0);
}
int main(void)
{
pthread_t t1, t2, t3;
int rc;
rc = pthread_create(&t1, 0, (void *) X, 0); assert(rc == 0);
rc = pthread_create(&t2, 0, (void *) Y, 0); assert(rc == 0);
rc = pthread_create(&t3, 0, (void *) Z, 0); assert(rc == 0);
rc = pthread_join(t1, 0); assert(rc == 0);
rc = pthread_join(t2, 0); assert(rc == 0);
rc = pthread_join(t3, 0); assert(rc == 0);
printf("n=%d\\n", n);
return 0;
}
| 1
|
#include <pthread.h>
struct vring_handle {
unsigned char *buffer;
size_t buffer_size;
size_t max_rw_size;
size_t buffer_len;
size_t read_pos;
size_t write_pos;
pthread_mutex_t mutex;
};
int vring_open(struct vring_handle **handle, size_t buffer_size,
size_t max_rw_size)
{
struct vring_handle *h;
if(buffer_size == 0 || max_rw_size == 0)
return -1;
*handle = malloc(sizeof(struct vring_handle));
if(*handle == 0)
return -1;
h = *handle;
h->buffer_size = buffer_size;
h->max_rw_size = max_rw_size;
h->buffer_len = 0;
h->read_pos = 0;
h->write_pos = 0;
h->buffer = malloc(h->buffer_size+h->max_rw_size);
if(h->buffer == 0)
return -1;
pthread_mutex_init(&h->mutex, 0);
return 0;
}
size_t vring_get_length(struct vring_handle *h)
{
size_t len;
pthread_mutex_lock(&h->mutex);
len = h->buffer_len;
pthread_mutex_unlock(&h->mutex);
return len;
}
ssize_t vring_read(struct vring_handle *h, unsigned char **buffer,
size_t len, size_t pos)
{
if(len > h->max_rw_size || len == 0)
len = h->max_rw_size;
pthread_mutex_lock(&h->mutex);
if(len > h->buffer_len - pos)
len = h->buffer_len - pos;
*buffer = h->buffer + h->read_pos + pos;
if(*buffer >= h->buffer + h->buffer_size)
*buffer -= h->buffer_size;
pthread_mutex_unlock(&h->mutex);
return len;
}
ssize_t vring_read_forward(struct vring_handle *h, size_t len)
{
pthread_mutex_lock(&h->mutex);
if(len > h->buffer_len)
len = h->buffer_len;
if(len == 0)
{
pthread_mutex_unlock(&h->mutex);
return 0;
}
h->read_pos += len;
if(h->read_pos >= h->buffer_size)
h->read_pos -= h->buffer_size;
h->buffer_len -= len;
pthread_mutex_unlock(&h->mutex);
return len;
}
ssize_t vring_write(struct vring_handle *h, unsigned char **buffer)
{
ssize_t len = h->max_rw_size;
pthread_mutex_lock(&h->mutex);
if(len > h->buffer_size - h->buffer_len)
len = h->buffer_size - h->buffer_len;
pthread_mutex_unlock(&h->mutex);
*buffer = h->buffer + h->write_pos;
return len;
}
ssize_t vring_write_forward(struct vring_handle *h, size_t len)
{
size_t size = 0;
size_t rem = 0;
pthread_mutex_lock(&h->mutex);
if(len > h->buffer_size - h->buffer_len)
len = h->buffer_size - h->buffer_len;
pthread_mutex_unlock(&h->mutex);
if(len == 0)
return 0;
if(h->write_pos + len > h->buffer_size)
{
size = len - (h->buffer_size - h->write_pos);
memcpy(h->buffer, h->buffer + h->buffer_size, size);
}
else if(h->write_pos < h->max_rw_size)
{
rem = h->buffer_size + h->write_pos;
size = h->max_rw_size - h->write_pos;
if(len < size)
size = len;
memcpy(h->buffer + rem, h->buffer + h->write_pos, size);
}
pthread_mutex_lock(&h->mutex);
h->write_pos += len;
if(h->write_pos >= h->buffer_size)
h->write_pos -= h->buffer_size;
h->buffer_len += len;
pthread_mutex_unlock(&h->mutex);
return len;
}
void vring_close(struct vring_handle *h)
{
if(h == 0)
return;
if(h->buffer != 0)
free(h->buffer);
free(h);
}
| 0
|
#include <pthread.h>
const char *TURNOFF = "OFF";
const char *STOP = "STOP";
const char *START = "START";
const char *SCALE_F = "SCALE=F";
const char *SCALE_C = "SCALE=C";
const char *FREQ = "FREQ=";
const int REQ_PORTNO = 16000;
const int B = 4275;
int PORT_NUM=0;
volatile sig_atomic_t T=3;
volatile sig_atomic_t running_flag=1;
volatile sig_atomic_t scale_flag='F';
volatile sig_atomic_t pause_flag=0;
pthread_mutex_t LOGGING_MUTEX;
pthread_mutex_t T_MUTEX;
void read_temp(int logfd, int socketfd);
int socket_handler(char* hostname, int portno);
void hearfrom(int fd[2]);
inline void atomic_logging(int logfd, char *msg, int validity);
int main(void) {
int socketfd, logfd=0, portno=REQ_PORTNO;
logfd = Open("log2", O_CREAT|O_RDWR|O_TRUNC, 00700);
socketfd = socket_handler("lever.cs.ucla.edu", portno);
Write(socketfd, "Port request 604478702", strlen("Port request 604478702"));
Read(socketfd, &PORT_NUM, sizeof(int));
printf("%d\\n", PORT_NUM);
if(PORT_NUM <= 0)
unix_error("ERROR receiving portno",1);
close(socketfd);
socketfd = socket_handler("lever.cs.ucla.edu", PORT_NUM);
pthread_t pthread;
pthread_mutex_init(&LOGGING_MUTEX, 0);
pthread_mutex_init(&T_MUTEX, 0);
int fd[2] = {socketfd, logfd};
Pthread_create(&pthread, 0, (void *)hearfrom, fd);
read_temp(logfd, socketfd);
return 0;
}
int socket_handler(char* hostname, int portno)
{
int socketfd;
struct sockaddr_in serv_addr;
struct hostent *server;
socketfd = Socket(AF_INET, SOCK_STREAM, 0);
server = Gethostbyname("lever.cs.ucla.edu");
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
Connect(socketfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
return socketfd;
}
void read_temp(int logfd, int socketfd)
{
float t=14.1;
float temperature;
time_t rawtime;
struct tm *info;
char buffer[64];
char buf[64];
while(running_flag) {
if(pause_flag == 0) {
memset(buf,0,64);
memset(buffer,0,64);
time(&rawtime);
info = localtime(&rawtime);
strftime(buffer, 9, "%H:%M:%S", info);
if(t==100)
t-=100;
t++;
char *scale;
if(scale_flag == 'F') {
temperature = t*1.8+32;
scale = "F";
}
else {
temperature = t;
scale = "C";
}
size_t size = sprintf(buf, "604478702 TEMP=%0.1f\\n", temperature);
Write(socketfd, buf, size);
sprintf(buffer, "%s %0.1f %s\\n", buffer, temperature, scale);
printf("%s", buffer);
pthread_mutex_lock(&LOGGING_MUTEX);
Write(logfd, buffer, size);
fflush(0);
pthread_mutex_unlock(&LOGGING_MUTEX);
}
sleep(T);
}
}
void hearfrom(int fd[2])
{
char msg[64];
int sockfd = fd[0];
int logfd = fd[1];
while(Read(sockfd, msg, 64) > 0)
{
printf("%s\\n", msg);
int validity=1;
char buffer[64];
memset(buffer, 0, 64);
strncpy(buffer, msg, strlen(FREQ));
int offset = strlen(FREQ);
if(strcmp(buffer, FREQ) == 0)
{
int i=offset;
size_t len = strlen(&msg[offset]);
for(i=offset;i!=len;i++)
if(!isdigit(msg[i])) {
validity=0;
break;
}
if(validity == 1) {
int temp = atoi(&msg[offset]);
if(T!=temp)
T = temp;
}
}
else if(strcmp(msg, STOP)==0)
{
if(pause_flag == 0)
pause_flag=1;
}
else if(strcmp(msg, START)==0)
{
if(pause_flag == 1)
pause_flag=0;
}
else if(strcmp(msg, TURNOFF)==0)
{
running_flag = 0;
close(sockfd);
atomic_logging(logfd, msg, validity);
exit(0);
}
else if(strcmp(msg, SCALE_F)==0)
{
if(scale_flag != 'F')
scale_flag='F';
}
else if(strcmp(msg, SCALE_C)==0)
{
if(scale_flag != 'C')
scale_flag='C';
}
else
{
validity=0;
}
atomic_logging(logfd, msg, validity);
}
unix_error("Broken Socket", 1);
}
inline void atomic_logging(int logfd, char *msg, int validity)
{
char buf[64];
char *v = validity==1 ? "" : " |";
sprintf(buf, "%s%s\\n", msg, v);
pthread_mutex_lock(&LOGGING_MUTEX);
Write(logfd, buf, strlen(buf));
fflush(0);
pthread_mutex_unlock(&LOGGING_MUTEX);
}
| 1
|
#include <pthread.h>
extern void OPENSSL_cleanse(void *ptr, size_t len);
int secure_allocation_support = 0;
static pthread_mutex_t secure_allocation_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_key_t secure_allocation_key;
static const int secure_yes = 1;
static const int secure_no = 0;
static char *arena = 0;
static size_t arena_size = 0;
extern void *cmm_init(int size, int mem_min_unit, int overrun_bytes);
extern void *cmm_malloc(int size);
extern int cmm_free(void *lamb);
extern void *cmm_realloc(void *lamb, int size);
static int secure_allocation_enabled()
{
if (!secure_allocation_support)
{
return 0;
}
int* answer = (int*)pthread_getspecific(secure_allocation_key);
return answer == &secure_yes;
}
static void secure_allocation_enable(int status)
{
if (secure_allocation_support)
{
pthread_setspecific(secure_allocation_key,
status ? &secure_yes : &secure_no);
}
}
int start_secure_allocation()
{
int ret = secure_allocation_enabled();
if (ret == 0)
{
secure_allocation_enable(1);
}
return ret;
}
int stop_secure_allocation()
{
int ret = secure_allocation_enabled();
if (ret == 1)
{
secure_allocation_enable(0);
}
return ret;
}
void flush_secure_arena()
{
if (arena)
memset(arena, 0, arena_size);
}
int secure_malloc_init(size_t size, int mem_min_unit, int overrun_bytes)
{
int ret = 0;
arena_size = size;
pthread_mutex_lock(&secure_allocation_lock);
if (arena)
{
assert(0);
}
else if ((arena = (char *) cmm_init(arena_size, mem_min_unit, overrun_bytes)) == 0)
{
}
else if (mlock(arena, arena_size))
{
}
else if (pthread_key_create(&secure_allocation_key, 0) != 0)
{
}
else
{
secure_allocation_support = 1;
ret = 1;
}
pthread_mutex_unlock(&secure_allocation_lock);
return ret;
}
static int is_secured_ptr(void *ptr)
{
return secure_allocation_support
&& (char*)ptr >= arena && (char*)ptr < arena + arena_size;
}
void *secure_calloc(size_t nmemb, size_t size)
{
void *ret;
int tot_size = nmemb*size;
if (!secure_allocation_enabled())
return calloc(nmemb,size);
pthread_mutex_lock(&secure_allocation_lock);
ret = cmm_malloc(tot_size);
if (ret)
{
memset(ret,0,tot_size);
}
pthread_mutex_unlock(&secure_allocation_lock);
return ret;
}
void *secure_malloc(size_t size)
{
void *ret;
if (!secure_allocation_enabled())
return malloc(size);
pthread_mutex_lock(&secure_allocation_lock);
ret = cmm_malloc(size);
pthread_mutex_unlock(&secure_allocation_lock);
return ret;
}
void *secure_strdup(const char *str)
{
return strcpy(secure_malloc(strlen(str) + 1), str);
}
void secure_free(void *ptr)
{
if (secure_allocation_support && is_secured_ptr(ptr))
{
pthread_mutex_lock(&secure_allocation_lock);
cmm_free(ptr);
pthread_mutex_unlock(&secure_allocation_lock);
}
else
{
free(ptr);
}
}
void *secure_realloc(void *ptr, size_t size)
{
void *ret;
if (secure_allocation_support && is_secured_ptr(ptr))
{
pthread_mutex_lock(&secure_allocation_lock);
ret = cmm_realloc(ptr,size);
pthread_mutex_unlock(&secure_allocation_lock);
}
else
{
ret = realloc(ptr,size);
}
return ret;
}
void *secure_realloc_clean(void *ptr, int old_len, size_t size)
{
void *ret;
ret = secure_malloc(size);
if (ret)
memcpy(ret, ptr, old_len);
OPENSSL_cleanse(ptr, old_len);
secure_free(ptr);
return ret;
}
| 0
|
#include <pthread.h>
static void
lc_copyHlinks(struct fs *fs) {
struct hldata *hldata = fs->fs_hlinks, *new, **prev = &fs->fs_hlinks;
assert(fs->fs_sharedHlinks);
fs->fs_hlinks = 0;
while (hldata) {
new = lc_malloc(fs, sizeof(struct hldata), LC_MEMTYPE_HLDATA);
new->hl_ino = hldata->hl_ino;
new->hl_parent = hldata->hl_parent;
new->hl_nlink = hldata->hl_nlink;
new->hl_next = 0;
*prev = new;
prev = &new->hl_next;
hldata = hldata->hl_next;
}
fs->fs_sharedHlinks = 0;
}
void
lc_addHlink(struct fs *fs, struct inode *inode, ino_t parent) {
struct gfs *gfs = fs->fs_gfs;
struct hldata *hldata;
ino_t ino;
if (gfs->gfs_swapLayersForCommit || fs->fs_rfs->fs_restarted ||
(fs == lc_getGlobalFs(gfs))) {
return;
}
assert(!S_ISDIR(inode->i_mode));
ino = inode->i_ino;
if (parent == fs->fs_root) {
parent = LC_ROOT_INODE;
}
pthread_mutex_lock(&fs->fs_hlock);
if (fs->fs_sharedHlinks) {
lc_copyHlinks(fs);
}
if (!(inode->i_flags & LC_INODE_MLINKS)) {
inode->i_flags |= LC_INODE_MLINKS;
hldata = lc_malloc(fs, sizeof(struct hldata), LC_MEMTYPE_HLDATA);
hldata->hl_ino = ino;
hldata->hl_parent = (inode->i_parent == fs->fs_root) ?
LC_ROOT_INODE : inode->i_parent;
hldata->hl_nlink = 1;
hldata->hl_next = fs->fs_hlinks;
fs->fs_hlinks = hldata;
if (parent == hldata->hl_parent) {
hldata->hl_nlink++;
pthread_mutex_unlock(&fs->fs_hlock);
return;
}
hldata = 0;
} else {
hldata = fs->fs_hlinks;
while (hldata &&
((hldata->hl_ino != ino) || (hldata->hl_parent != parent))) {
hldata = hldata->hl_next;
}
}
if (hldata) {
assert(ino == hldata->hl_ino);
assert(parent == hldata->hl_parent);
hldata->hl_nlink++;
} else {
hldata = lc_malloc(fs, sizeof(struct hldata), LC_MEMTYPE_HLDATA);
hldata->hl_ino = ino;
hldata->hl_parent = parent;
hldata->hl_nlink = 1;
hldata->hl_next = fs->fs_hlinks;
fs->fs_hlinks = hldata;
}
pthread_mutex_unlock(&fs->fs_hlock);
}
void
lc_removeHlink(struct fs *fs, struct inode *inode, ino_t parent) {
struct hldata *hldata, **prev;
ino_t ino;
assert(!fs->fs_rfs->fs_restarted);
assert(!fs->fs_gfs->gfs_swapLayersForCommit);
assert(!S_ISDIR(inode->i_mode));
assert(inode->i_flags & LC_INODE_MLINKS);
if (fs->fs_hlinks == 0) {
return;
}
if (parent == fs->fs_root) {
parent = LC_ROOT_INODE;
}
ino = inode->i_ino;
prev = &fs->fs_hlinks;
pthread_mutex_lock(&fs->fs_hlock);
if (fs->fs_sharedHlinks) {
lc_copyHlinks(fs);
}
hldata = fs->fs_hlinks;
while (hldata &&
((hldata->hl_ino != ino) || (hldata->hl_parent != parent))) {
prev = &hldata->hl_next;
hldata = hldata->hl_next;
}
assert(ino == hldata->hl_ino);
assert(parent == hldata->hl_parent);
assert(hldata->hl_nlink > 0);
hldata->hl_nlink--;
if (hldata->hl_nlink == 0) {
*prev = hldata->hl_next;
pthread_mutex_unlock(&fs->fs_hlock);
lc_free(fs, hldata, sizeof(struct hldata), LC_MEMTYPE_HLDATA);
} else {
pthread_mutex_unlock(&fs->fs_hlock);
}
}
void
lc_freeHlinks(struct fs *fs) {
struct hldata *hldata = fs->fs_hlinks, *tmp;
fs->fs_hlinks = 0;
if (fs->fs_sharedHlinks) {
return;
}
while (hldata) {
tmp = hldata;
hldata = hldata->hl_next;
lc_free(fs, tmp, sizeof(struct hldata), LC_MEMTYPE_HLDATA);
}
}
| 1
|
#include <pthread.h>
int nthreads,
n,
prime[100000000 + 1],
nextbase;
int work[100];
pthread_mutex_t nextbaselock = PTHREAD_MUTEX_INITIALIZER;
pthread_t id[100];
void crossout(int k)
{
int i;
for (i = k; i * k <= n; i++) {
prime[i * k] = 0;
}
}
void *worker(int tn)
{
int lim, base;
lim = sqrt(n);
do {
pthread_mutex_lock(&nextbaselock);
base = nextbase += 2;
pthread_mutex_unlock(&nextbaselock);
if (base <= lim) {
work[tn]++;
if (prime[base])
crossout(base);
}
else
return;
} while (1);
}
int main(int argc, char **argv)
{
int nprimes,
totwork,
i;
void *p;
n = atoi(argv[1]);
nthreads = atoi(argv[2]);
for (i = 2; i <= n; i++)
prime[i] = 1;
crossout(2);
nextbase = 1;
for (i = 0; i < nthreads; i++) {
pthread_create(&id[i], 0, (void *) worker, (void *) i);
}
totwork = 0;
for (i = 0; i < nthreads; i++) {
pthread_join(id[i], &p);
printf("%d values of base done\\n", work[i]);
totwork += work[i];
}
printf("%d total values of base done\\n", totwork);
nprimes = 0;
for (i = 2; i <= n; i++)
if (prime[i])
nprimes++;
printf("the number of primes found was %d\\n", nprimes);
}
| 0
|
#include <pthread.h>
int n_completos = 0;
pthread_mutex_t trava;
int numeros[10];
void* worker(void *arg) {
int *N = (int*)(arg);
int M = (*N);
printf("Iniciando thread %d\\n", M);
int atuador = -1;
while (1) {
pthread_mutex_lock(&trava);
if (n_completos >= 10) break;
atuador = n_completos;
n_completos += 1;
pthread_mutex_unlock(&trava);
printf("Numero %d acessado por thread %d\\n", atuador, M);
numeros[atuador] *= 2;
for (int j=0; j<500000; j++);
}
printf("Saindo de thread %d\\n", M);
return 0;
}
int main(int argc, char **argv) {
pthread_t workers[3];
int thread_id[3];
for (int i=0; i<10; i++)
numeros[i] = i;
for (int i=0; i<3; i++) {
thread_id[i] = i;
}
for (int i=0; i<3; i++) {
pthread_create(&(workers[i]), 0, worker, (void*) (&thread_id[i]));
}
for (int i=0; i<3; i++) {
pthread_join(workers[i], 0);
}
for (int i=0; i<10; i++) {
printf("%d\\n", numeros[i]);
}
return 0;
}
| 1
|
#include <pthread.h>
int numberIndex = 0;
int numThreads = 2;
pthread_mutex_t m1,m2;
long sum = 0;
void *SumUpto(void *arg)
{
int *number = (int *)arg;
int n = *number;
int i;
long threadSum = 0;
pthread_mutex_lock(&m1);
int min = numberIndex;
if(min > n)
{
return 0;
}
numberIndex += (int)n/numThreads;
if(n - numberIndex < n%numThreads)
{
numberIndex = n;
}
int max = numberIndex;
numberIndex++;
pthread_mutex_unlock(&m1);
for(i = min; i <= max; i++)
{
threadSum += i;
}
pthread_mutex_lock(&m2);
sum += threadSum;
pthread_mutex_unlock(&m2);
}
int main(int argc, char *argv[])
{
clock_t start, end;
double runtime;
int number;
int p;
if(argc == 1)
{
number = 0;
p = 2;
}
else
{
number = atoi(argv[1]);
p = atoi(argv[2]);
}
numThreads = p;
int i;
pthread_mutex_init(&m1, 0);
pthread_mutex_init(&m2, 0);
pthread_t thread[p];
start = clock();
for(i = 0; i < p; i++)
{
pthread_create(&thread[i], 0, SumUpto, &number);
printf("Thread %d\\n",i);
}
for(i = 0; i < p; i++)
{
pthread_join(&thread[i], 0);
}
end = clock();
runtime = 1000*((double) (end - start)) / CLOCKS_PER_SEC;
printf("Sum of numbers is: %ld\\n", sum);
printf("Execution time: %f milliseconds\\n", runtime);
return 0;
}
| 0
|
#include <pthread.h>
int args[64] = {0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10, 11, 12, 13, 14, 15,
16, 17, 18, 19 ,20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63};
int N;
int P;
int A[0x00800000];
int sum;
pthread_mutex_t mut;
pthread_barrier_t barr;
void * thread_func(void *arg)
{
int thrno;
int i;
int chunksize;
int partialsum = 0;
pthread_barrier_wait(&barr);
chunksize = N / P;
thrno = *(int *)arg;
printf("Thread starting : %d\\n",thrno);
for (i=thrno * chunksize; i<((thrno+1) * chunksize); i++)
partialsum += A[i];
pthread_mutex_lock(&mut);
sum += partialsum;
pthread_mutex_unlock(&mut);
return 0;
}
int main(int argc, char **argv)
{
int i, mcmodel;
void *retval;
int t1, t2, t3, t4;
pthread_t thr[64];
if (argc != 3)
{
printf("Usage : reduct <NPROC> <NELEMENTS>\\n");
exit(0);
}
pthread_mutex_init(&mut, 0);
P = atoi(argv[1]);
N = atoi(argv[2]);
pthread_barrier_init(&barr, 0, P);
t1 = time(0);
for (i=1; i<P; i++)
pthread_create(&thr[i], 0, thread_func, &args[i]);
t2 = time(0);
thread_func(&args[0]);
t3 = time(0);
for (i=1; i<P; i++)
pthread_join(thr[i], &retval);
t4 = time(0);
printf("Time for completion : creation %d, reduction : %d, joining : %d\\n",t2-t1, t3-t2, t4 - t3);
return 0;
}
| 1
|
#include <pthread.h>
{
pthread_t *thread;
pthread_mutex_t cond_lock;
pthread_cond_t cond;
struct _queueNode *prev;
struct _queueNode *next;
} mqNode;
{
mqNode *front, *rear;
pthread_mutex_t queueLock;
} Queue;
Queue Q;
void initQ ()
{
Q.front = 0;
Q.rear = 0;
pthread_mutex_init (&Q.queueLock, 0);
}
void initNode (mqNode *node, pthread_t *thread)
{
node -> thread = thread;
pthread_mutex_init (&(node -> cond_lock), 0);
pthread_cond_init (&(node -> cond), 0);
node -> prev = 0;
node -> next = 0;
}
int isQEmpty ()
{
pthread_mutex_lock (&Q.queueLock);
int flag;
if (Q.front == 0 && Q.rear == 0)
flag = 1;
else
flag = 0;
pthread_mutex_unlock (&Q.queueLock);
return flag;
}
int addToQueue (mqNode *node)
{
if (isQEmpty ())
{
pthread_mutex_lock (&Q.queueLock);
Q.front = node;
Q.rear = Q.front;
pthread_mutex_unlock (&Q.queueLock);
return 1;
}
else
{
pthread_mutex_lock (&Q.queueLock);
Q.front -> prev = node;
node -> next = Q.front;
Q.front = node;
pthread_mutex_unlock (&Q.queueLock);
return 1;
}
return 0;
}
mqNode *removeFromQueue ()
{
int flag;
mqNode *node;
if (isQEmpty ())
return 0;
else
{
pthread_mutex_lock (&Q.queueLock);
if (Q.front == Q.rear)
{
node = Q.rear;
node -> next = 0;
node -> prev = 0;
Q.front = Q.rear = 0;
}
else
{
node = Q.rear;
Q.rear = node -> prev;
Q.rear -> next = 0;
node -> prev = 0;
}
pthread_mutex_unlock (&Q.queueLock);
}
return node;
}
struct connectorInput
{
int serverfd;
struct sockaddr_in *server_addr;
};
struct threadInput
{
int connfd;
pthread_t *thread;
mqNode *selfNode;
};
void *customerCare (void *input)
{
int connfd;
int n;
char buffer[1024];
pthread_t *thread;
mqNode *selfNode;
struct threadInput *custIp = (struct threadInput *)(input);
connfd = custIp -> connfd;
thread = custIp -> thread;
selfNode = custIp -> selfNode;
free (input);
custIp = 0;
bzero (buffer, 1024);
n = read (connfd, buffer, 1024);
if (n > 0)
{
strtok (buffer, "\\r\\n");
printf ("clientfd:%d :: %s\\n", connfd, buffer);
}
addToQueue (selfNode);
pthread_mutex_lock (&(selfNode -> cond_lock));
pthread_cond_wait (&(selfNode -> cond), &(selfNode -> cond_lock));
pthread_mutex_unlock (&(selfNode -> cond_lock));
bzero (buffer, 1024);
fflush (stdin);
fgets (buffer, 1024, stdin);
if (strlen (buffer) > 0)
strtok (buffer, "\\r\\n");
n = write (connfd, buffer, strlen (buffer));
if (n < 0)
{
printf ("ERROR: Cant write to clientfd:%d\\n", connfd);
}
return 0;
}
void *connector (void *input)
{
int serverfd, connfd;
int clientLenght, rc;
struct sockaddr_in *server_addr, client_addr;
pthread_t *thread;
struct connectorInput *connIp = (struct connectorInput *)(input);
serverfd = connIp -> serverfd;
server_addr = connIp -> server_addr;
struct threadInput *custIp;
while (1)
{
clientLenght = sizeof (client_addr);
connfd = accept (serverfd, (struct sockaddr *)(&client_addr), (&clientLenght));
printf ("Accepted a connection __ fd:%d\\n", connfd);
thread = (pthread_t *) malloc (sizeof (pthread_t));
mqNode *node = (mqNode *) malloc (sizeof (mqNode));
initNode (node, thread);
custIp = (struct threadInput *) malloc (sizeof (struct threadInput));
custIp -> connfd = connfd;
custIp -> thread = thread;
custIp -> selfNode = node;
rc = pthread_create (thread, 0, customerCare, (void *)(custIp));
if (rc < 0)
{
printf ("ERROR: Cannot create thread for connfd: %d\\n", connfd);
break;
}
}
return 0;
}
int main ()
{
int serverfd, rc;
pthread_t *thread;
struct sockaddr_in server_addr;
bzero (&server_addr, sizeof (server_addr));
serverfd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons (5555);
server_addr.sin_addr.s_addr = htonl (INADDR_ANY);
bind (serverfd, (struct sockaddr *)(&server_addr), sizeof (server_addr));
listen (serverfd, 10);
printf ("SERVER READY TO ACCEPT CONNECTIONS...\\n");
thread = (pthread_t *) malloc (sizeof (pthread_t));
struct connectorInput connIp;
connIp.serverfd = serverfd;
connIp.server_addr = &server_addr;
rc = pthread_create (thread, 0, connector, (void *)(&connIp));
if (rc < 0)
{
printf ("ERROR: Cant create connector thread\\n");
return -1;
}
while (1)
{
if (!isQEmpty ())
{
mqNode *node = removeFromQueue ();
pthread_mutex_lock (&(node -> cond_lock));
pthread_cond_signal (&(node -> cond));
pthread_mutex_unlock (&(node -> cond_lock));
free (node);
}
}
return 0;
}
| 0
|
#include <pthread.h>
int nproc, nthread, play, next;
int flag[6];
time_t start;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void threadResumeAll() {
pthread_mutex_lock(&mutex);
play = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
void threadResumeNext() {
pthread_mutex_lock(&mutex);
flag[next] = 1;
if(next > 0) next--;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
void threadSuspendAll() {
pthread_mutex_lock(&mutex);
play = 0;
pthread_mutex_unlock(&mutex);
}
void threadStatus(int id) {
pthread_mutex_lock(&mutex);
while(!play) pthread_cond_wait(&cond, &mutex);
while(!flag[id]) pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
}
void lock() {
pthread_mutex_lock(&mutex);
}
void unlock() {
pthread_mutex_unlock(&mutex);
}
void *TaskCode(void *arg) {
time_t st, end;
double elaps;
int id = *((int *) arg);
if(nthread == nproc) threadSuspendAll();
threadStatus(id);
lock(); nthread++; unlock();
printf("Rodando thread %d\\n", id);
st = clock();
while(42) {
end = clock();
elaps = ((double)end - (double)st) / CLOCKS_PER_SEC;
if(elaps >= 10.0) break;
}
printf("Terminei thread %d com %lf\\n", id, ((double)end - (double)start) / CLOCKS_PER_SEC);
nthread--;
threadResumeNext();
threadResumeAll();
return 0;
}
int main() {
pthread_t threads[6];
int thread_args[6];
int i, rc;
nproc = 4;
nthread = 0;
play = 1;
for(i = 0; i < 6; i++) {
thread_args[i] = i + 1;
flag[i + 1] = 0;
}
flag[6] = flag[5] = 1;
next = 4;
start = clock();
for(i = 0; i < 6; i++) {
rc = pthread_create(&threads[i], 0, TaskCode, (void *) &thread_args[i]);
assert(0 == rc);
}
for (i=0; i<6; ++i) {
rc = pthread_join(threads[i], 0);
assert(0==rc);
}
return 0;
}
| 1
|
#include <pthread.h>
int broj, obradjeno;
pthread_mutex_t monitor;
pthread_cond_t red_poslova, red_kontrola;
void *posao_n ( void *x )
{
int n;
n = (int) x;
pthread_mutex_lock ( &monitor );
obradjeno++;
if ( obradjeno == 10 )
pthread_cond_signal ( &red_kontrola );
while ( broj < 20 )
{
pthread_cond_wait ( &red_poslova, &monitor );
if ( broj % n == 0 )
printf ( "Aktiviram posao %d\\n", n );
obradjeno++;
if ( obradjeno == 10 )
pthread_cond_signal ( &red_kontrola );
}
pthread_mutex_unlock ( &monitor );
return 0;
}
void *kontrola ( void *x )
{
pthread_mutex_lock ( &monitor );
while ( broj < 20 )
{
while ( obradjeno < 10 && broj < 20 )
pthread_cond_wait ( &red_kontrola, &monitor );
broj++;
obradjeno = 0;
printf ( "Obrada broja %d\\n", broj );
pthread_cond_broadcast ( &red_poslova );
}
pthread_mutex_unlock ( &monitor );
return 0;
}
int main ()
{
int i;
pthread_t dretve[1 + 10];
broj = 0;
obradjeno = 0;
pthread_mutex_init ( &monitor, 0 );
pthread_cond_init ( &red_poslova, 0 );
pthread_cond_init ( &red_kontrola, 0 );
if ( pthread_create ( &dretve[0], 0, kontrola, 0 ) )
{
fprintf ( stderr, "Greska pri stvaranju dretve!\\n" );
exit (1);
}
for ( i = 1; i <= 10; i++ )
{
if ( pthread_create ( &dretve[i], 0, posao_n, (void *) i ) )
{
fprintf ( stderr, "Greska pri stvaranju dretve!\\n" );
exit (1);
}
}
for ( i = 0; i <= 10; i++ )
pthread_join ( dretve[i], 0 );
return 0;
}
| 0
|
#include <pthread.h>
struct _vector_info{
double *vector_a;
double *vector_b;
double sum;
int length;
};
struct _product{
vector_info_t *info;
int begin_index;
};
pthread_mutex_t mutex;
void dot_product(void *prod)
{
int i;
product_t *p = (product_t *)prod;
vector_info_t *v = p -> info;
int begin_index = p -> begin_index;
int end_index = begin_index + v -> length;
double total = 0;
for (i = 0; i < end_index; i++){
total += ( v->vector_a[i] * v->vector_b[i] );
}
pthread_mutex_lock(&mutex);
v -> sum += total;
pthread_mutex_unlock(&mutex);
pthread_exit( (void *) 0);
}
int main()
{
int i;
int return_number;
vector_info_t v;
double vector_a[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0,
9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0};
double vector_b[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0,
9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0};
double sum;
v.vector_a = vector_a;
v.vector_b = vector_b;
v.length = 4;
pthread_t threads[4];
void *status;
pthread_attr_t attr;
pthread_mutex_init(&mutex, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (i = 0; i < 4; i++){
product_t *p = (product_t *) malloc( sizeof(product_t) );
p -> begin_index = i*4;
p -> info = &v;
return_number = pthread_create( &threads[i], &attr, dot_product, (void *) p);
if (return_number){
perror("pthread_create");
}
}
pthread_attr_destroy(&attr);
for ( i = 0; i < 4; i++){
pthread_join(threads[i], &status);
}
pthread_mutex_destroy(&mutex);
printf("dot product sum: %lf\\n", v.sum);
return 0;
}
| 1
|
#include <pthread.h>
int account = 0;
int depositamount = 100;
int withdrawamount = 100;
pthread_mutex_t cmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condvar = PTHREAD_COND_INITIALIZER;
int deposit(int amount)
{
pthread_mutex_lock(&cmutex);
account = account+amount;
if (account >= 1000)
{
pthread_cond_signal(&condvar);
}
pthread_mutex_unlock(&cmutex);
return 0;
}
void* depositor(void *arg)
{
int lindex = 0;
while(lindex < 20) {
deposit(depositamount);
lindex++;
}
return 0;
}
int withdraw(int amount)
{
int retval = 0;
if (amount > 1000)
{
return retval;
}
pthread_mutex_lock(&cmutex);
while (account-amount < 1000)
{
pthread_cond_wait(&condvar, &cmutex);
}
account = account-amount;
retval = 1;
pthread_mutex_unlock(&cmutex);
return retval;
}
void* withdrawer(void *arg)
{
int lindex = 0;
int retval = 1;
while(lindex < 20)
{
while (retval)
{
retval = withdraw(withdrawamount);
}
lindex++;
}
return 0;
}
int main(void)
{
pthread_t tid1,tid2;
int rv1,rv2;
pthread_attr_t attr;
pthread_attr_init(&attr);
rv1 = pthread_create(&tid2,&attr,(void *)withdrawer,0);
if(rv1 != 0)
{
printf("\\n Cannot create thread");
exit(0);
}
rv1 = pthread_create(&tid1,&attr,(void *)depositor,0);
if(rv1 != 0)
{
printf("\\n Cannot create thread");
exit(0);
}
pthread_join(tid1,0);
pthread_join(tid2,0);
return(0);
}
| 0
|
#include <pthread.h>
unsigned degree;
unsigned N;
double* coeffs;
double* dots;
double* answers;
pthread_mutex_t mutex_for_answers;
unsigned num;
} JobInfo;
void* calc_func2(void* arg){
JobInfo* info = arg;
double coeff = coeffs[info->num];
unsigned mydegree = info->num;
unsigned i;
double answer = 0;
double curMult = 1;
for(i = 0; i < N; ++i){
unsigned j;
answer = coeff;
for(j = 0; j < mydegree; ++j){
answer *= dots[i];
}
pthread_mutex_lock(&mutex_for_answers);
answers[i] += answer;
pthread_mutex_unlock(&mutex_for_answers);
}
free(arg);
return 0;
}
int main(){
scanf("%u", °ree);
unsigned i = 0;
scanf("%u", &N);
coeffs = (double*) malloc((degree + 1) * sizeof(double));
dots = (double*) malloc( N * sizeof(double));
answers = (double*) malloc(N * sizeof(double));
memset(answers, 0, N * sizeof(double));
pthread_t* jobs = malloc( (degree + 1) * sizeof(pthread_t));
pthread_mutex_init(&mutex_for_answers, 0);
if( coeffs == 0 || dots == 0 || answers == 0 || jobs == 0){
perror("can't allocate");
exit(1);
}
for(i = 0; i < degree + 1; ++i){
scanf("%lf", coeffs + i);
}
for(i = 0; i < N; ++i){
scanf("%lf", dots + i);
}
for(i = 0; i != degree + 1; ++i){
JobInfo* jobinfo = malloc(sizeof(jobinfo));
jobinfo->num = i;
if(pthread_create(jobs + i, 0, &calc_func2, jobinfo) != 0){
perror("can't create thread");
exit(1);
}
}
for(i = 0; i != degree + 1; ++i){
pthread_join(jobs[i], 0);
printf("value in dot %lf is %lf\\n", dots[i], answers[i]);
}
free(coeffs);
free(dots);
free(answers);
pthread_mutex_destroy(&mutex_for_answers);
return 0;
}
| 1
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t wait = PTHREAD_COND_INITIALIZER;
void *
thr_fn(void *arg) {
int err, signo;
for (;;) {
err = sigwait(&mask, &signo);
if (err != 0)
err_exit(err, "sigwait failed");
switch(signo) {
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&wait);
return(0);
default:
printf("unexpected signal %d\\n", signo);
exit(1);
}
}
}
int
main(void) {
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) {
err_exit(err, "SIG_BLOCK error");
}
err = pthread_create(&tid, 0, thr_fn, 0);
if (err != 0) {
err_exit(err, "can not create thread");
}
pthread_mutex_lock(&lock);
while (quitflag == 0)
pthread_cond_wait(&wait, &lock);
pthread_mutex_unlock(&lock);
quitflag = 0;
if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0)
err_sys("SIG_SETMASK error");
exit(0);
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.