text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
pthread_mutex_t *mutex;
int pid;
char birth[25];
char clientString[10];
int elapsed_sec;
double elapsed_msec;
} stats_t;
int i;
stats_t *shm_ptr;
void exit_handler(int sig) {
pthread_mutex_lock(mutex);
shm_ptr[i].pid = -1;
pthread_mutex_unlock(mutex);
exit(0);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("invalid command");
exit(1);
}
if (strlen(argv[1]) > 10) {
printf("ClientString length too long");
exit(1);
}
struct sigaction act;
act.sa_handler = exit_handler;
if (sigaction(SIGINT, &act, 0) < 0) {
perror("sigaction");
return 1;
}
if (sigaction(SIGTERM, &act, 0) < 0) {
perror("sigaction");
return 1;
}
int fd_shm = shm_open("zhifeng_jcheng", O_RDWR, 0660);
if (fd_shm == -1) {
printf("shm_open failed\\n");
exit(1);
}
shm_ptr = (stats_t *) mmap(0, getpagesize(), PROT_READ | PROT_WRITE, MAP_SHARED, fd_shm, 0);
if (shm_ptr == MAP_FAILED) {
printf("mmap failed\\n");
exit(1);
}
mutex = (pthread_mutex_t *) shm_ptr;
pthread_mutex_lock(mutex);
struct timeval timeBefore, timeAfter;
int isSet = 0;
for (i = 1; i < 63 + 1; i++) {
if (shm_ptr[i].pid <= 0) {
shm_ptr[i].pid = getpid();
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
if (timeinfo == 0) {
perror("localtime failed");
pthread_mutex_unlock(mutex);
exit(1);
}
strcpy(shm_ptr[i].birth, asctime(timeinfo));
shm_ptr[i].birth[24] = '\\0';
strcpy(shm_ptr[i].clientString, argv[1]);
shm_ptr[i].clientString[9] = '\\0';
gettimeofday(&timeBefore, 0);
isSet = 1;
break;
}
}
if (isSet == 0) {
perror("Too many clients");
pthread_mutex_unlock(mutex);
exit(1);
}
pthread_mutex_unlock(mutex);
while (1) {
gettimeofday(&timeAfter, 0);
shm_ptr[i].elapsed_sec = (int) (timeAfter.tv_sec - timeBefore.tv_sec);
shm_ptr[i].elapsed_msec = (timeAfter.tv_usec - timeBefore.tv_usec)/1000.0;
sleep(1);
printf("Active clients :");
for (int j = 1; j < 63 + 1; j++) {
if (shm_ptr[j].pid > 0) {
printf(" %i", shm_ptr[j].pid);
}
}
printf("\\n");
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
int count = 0;
void *functionCount1()
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
pthread_cond_wait( &condition_var, &count_mutex );
count++;
printf("Counter value functionCount1: %d\\n",count);
pthread_mutex_unlock( &count_mutex );
if(count >= 10)
return 0;
}
}
void *functionCount2()
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
if( count < 3 || count > 6 )
{
pthread_cond_signal( &condition_var );
}
else
{
count++;
printf("Counter value functionCount2: %d\\n",count);
}
pthread_mutex_unlock( &count_mutex );
if(count >= 10)
return 0;
}
}
int main()
{
pthread_t thread1, thread2;
pthread_create( &thread1, 0, &functionCount1, 0);
pthread_create( &thread2, 0, &functionCount2, 0);
pthread_join( thread1, 0);
pthread_join( thread2, 0);
printf("Final count: %d\\n",count);
return 0;
}
| 0
|
#include <pthread.h>
struct foo {
int f_reference;
pthread_mutex_t f_lock;
int f_id;
struct foo* f_next;
};
struct foo* foo_hash[29];
pthread_mutex_t foo_hash_lock = PTHREAD_MUTEX_INITIALIZER;
struct foo* foo_alloc(int id)
{
int index = (((unsigned long)id) % 29);
struct foo* new_foo = malloc(sizeof(struct foo));
if (!new_foo)
return new_foo;
if (pthread_mutex_init(&new_foo->f_lock, 0) != 0) {
free(new_foo);
new_foo = 0;
return new_foo;
}
new_foo->f_id = id;
new_foo->f_reference = 1;
pthread_mutex_lock(&foo_hash_lock);
new_foo->f_next = foo_hash[index];
foo_hash[index] = new_foo;
pthread_mutex_unlock(&foo_hash_lock);
pthread_mutex_lock(&new_foo->f_lock);
pthread_mutex_unlock(&new_foo->f_lock);
return new_foo;
}
struct foo* foo_find_and_hold(int id)
{
int index = (((unsigned long)id) % 29);
struct foo* current_foo;
pthread_mutex_lock(&foo_hash_lock);
for (current_foo = foo_hash[index]; current_foo; current_foo = current_foo->f_next) {
if (current_foo->f_id == id) {
++(current_foo->f_reference);
break;
}
}
pthread_mutex_unlock(&foo_hash_lock);
return current_foo;
}
void foo_release(struct foo* fp)
{
pthread_mutex_lock(&foo_hash_lock);
if (--(fp->f_reference) == 0) {
int id = fp->f_id;
int index = (((unsigned long)id) % 29);
struct foo* current_foo = foo_hash[index];
if (current_foo == fp) {
foo_hash[index] = current_foo->f_next;
} else {
while (current_foo->f_next != fp)
current_foo = current_foo->f_next;
current_foo->f_next = fp->f_next;
}
pthread_mutex_unlock(&foo_hash_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
} else {
pthread_mutex_unlock(&foo_hash_lock);
}
}
int main(int argc, char* argv[]) { return 0; }
| 1
|
#include <pthread.h>
void
diskfs_nref (struct node *np)
{
int new_hardref;
pthread_spin_lock (&diskfs_node_refcnt_lock);
np->references++;
new_hardref = (np->references == 1);
pthread_spin_unlock (&diskfs_node_refcnt_lock);
if (new_hardref)
{
pthread_mutex_lock (&np->lock);
diskfs_new_hardrefs (np);
pthread_mutex_unlock (&np->lock);
}
}
| 0
|
#include <pthread.h>
static struct npc_list *dead_npcs;
static pthread_mutex_t dead_npcs_mutex = PTHREAD_MUTEX_INITIALIZER;
static struct npc_list *aggro_npcs;
static pthread_mutex_t aggro_npcs_mutex = PTHREAD_MUTEX_INITIALIZER;
static struct map_list *maps;
static void respawn_npcs();
static void npcs_attack_target();
static void move_enemies();
void* init_world()
{
db_set_all_users_offline();
maps = init_maps();
while(1)
{
usleep(500000);
respawn_npcs();
npcs_attack_target();
move_enemies();
}
return 0;
}
void add_dead_npc(struct npc_data *npc)
{
pthread_mutex_lock(&dead_npcs_mutex);
add_npc(&dead_npcs, npc);
pthread_mutex_unlock(&dead_npcs_mutex);
}
void add_aggro_npc(struct npc_data *npc)
{
pthread_mutex_lock(&aggro_npcs_mutex);
add_npc(&aggro_npcs, npc);
pthread_mutex_unlock(&aggro_npcs_mutex);
}
void deaggro_npc(struct npc_data *npc)
{
pthread_mutex_lock(&aggro_npcs_mutex);
rm_npc(&aggro_npcs, npc);
pthread_mutex_unlock(&aggro_npcs_mutex);
}
void respawn_npcs()
{
time_t currtime = time(0);
struct npc_list *curr = dead_npcs;
while(curr)
{
struct npc_data *npc = curr->npc;
struct npc_list *next = curr->next;
printf("%s", ctime(&currtime));
if(currtime >= npc->respawn_time)
{
printf("npc: %d\\n", npc->npc_id);
npc->hp = npc->max_hp;
char* npc_json = npc_to_json(npc);
char* command = 0;
if(!asprintf(&command, "npc add %s", npc_json))
{
continue;
}
tell_all_players_on_map(0, npc->map_id, command);
pthread_mutex_lock(&dead_npcs_mutex);
rm_npc(&dead_npcs, npc);
pthread_mutex_unlock(&dead_npcs_mutex);
free(npc_json);
free(command);
}
curr = next;
}
}
void npcs_attack_target()
{
struct npc_list *curr = aggro_npcs;
while(curr)
{
struct npc_data *npc = curr->npc;
npc_attack(npc);
curr = curr->next;
}
}
void move_enemies()
{
struct map_list *curr = maps;
while(curr)
{
struct map_t *map = curr->map;
struct npc_list *npcs = map->enemies;
while(npcs)
{
struct npc_data *npc = npcs->npc;
npc_move(npc);
npcs = npcs->next;
}
curr = curr->next;
}
}
| 1
|
#include <pthread.h>
int RUNNING = 0;
char buffer[BUFFER_SIZE];
int START = -1, END = 0;
long long HOLD_TIME = 2000;
bool isSetup = 0;
bool setup( int pinA, int pinB, int pinC )
{
wiringPiSetup();
pinMode( pinA, INPUT );
pullUpDnControl( pinA, PUD_UP );
pinMode( pinB, INPUT );
pullUpDnControl( pinB, PUD_UP );
pinMode( pinC, INPUT );
pullUpDnControl( pinC, PUD_UP );
bufferingEnabled = 0;
sem_init( &produced, 0, 0 );
sem_init( &consumed, 0, 0 );
pthread_mutex_init( &bufferLock, 0 );
isSetup = 1;
return 1;
}
void clearBuffer( void )
{
START = -1;
END = 0;
}
bool enableBuffering( void )
{
clearBuffer();
bufferingEnabled = 1;
}
bool disableBuffering( void )
{
clearBuffer();
bufferingEnabled = 0;
}
void setHoldTime( long long holdTime )
{
HOLD_TIME = holdTime;
}
bool startReading( void )
{
if( !isSetup )
{
fprintf( stderr, "Called startReading() without a successful setup (did you forget to call setup()?)" );
exit(-1);
}
if( !RUNNING )
{
if( pthread_create( &rotateThread, 0, ( void* ) &monitorRotation, 0 ) != 0 )
{
fprintf( stderr, "Failed to create monitor rotation thread!\\n" );
return 0;
}
if( pthread_create( &pushThread, 0, ( void* ) &monitorPushButton, 0 ) != 0 )
{
fprintf( stderr, "Failed to create monitor push button thread!\\n" );
return 0;
}
RUNNING = 1;
}
else
{
fprintf( stderr, "Call to startReading() when threads are already running!\\n" );
}
return 1;
}
void stopReading( void )
{
if( RUNNING == 0 )
{
if( pthread_cancel( rotateThread ) != 0 )
{
fprintf( stderr, "Failed to stop monitor rotation thread!\\n" );
}
if( pthread_cancel( pushThread ) != 0 )
{
fprintf( stderr, "Failed to stop monitor push button thread!\\n" );
}
RUNNING = 0;
}
else
{
fprintf( stderr, "Call to stopReading when threads are already stopped!\\n" );
}
}
char getReading( void )
{
if( !isSetup )
{
fprintf( stderr, "Called getReading() without a successful setup (did you forget to call setup()?)" );
exit(-1);
}
if( !RUNNING )
{
fprintf( stderr, "Called getReading() without a successful startReading() call. Exiting..." );
}
sem_wait(&produced);
char value = buffer[START];
START = (START+1) % BUFFER_SIZE;
return value;
}
void continueReading( void )
{
if( RUNNING )
{
sem_post(&consumed);
}
}
void add_to_buffer( char value )
{
pthread_mutex_lock(&bufferLock);
if( START == END )
{
wait(&consumed);
}
if( START == -1 )
{
START++;
}
buffer[END] = value;
END = ( END + 1 ) % BUFFER_SIZE;
sem_post( &produced );
if( !bufferingEnabled )
{
sem_wait(&consumed);
clearBuffer();
}
pthread_mutex_unlock(&bufferLock);
}
void monitorRotation( void *input )
{
while(1)
{
char reading1 = getKnobReading( 0x00 );
if( reading1 != 0x00 )
{
char reading2 = getKnobReading( reading1 );
if( reading2 == 0x03 )
{
char reading3 = getKnobReading( reading2 );
if( 2 == reading2 - reading3 && reading1 == 2 )
{
add_to_buffer( CLOCKWISE_STEP );
}
else
{
add_to_buffer( COUNTER_CLOCKWISE_STEP );
}
}
}
}
}
void monitorPushButton( void * input )
{
int timeHeldDown = 0;
while(1)
{
if( getPushButtonReading() )
{
add_to_buffer( PUSHED );
timeHeldDown = 0;
while( getPushButtonReading() )
{
timeHeldDown += 1;
if( timeHeldDown >= HOLD_TIME * 2000 )
{
add_to_buffer( PUSHED_AND_HELD );
break;
}
}
while( getPushButtonReading() )
{
}
}
usleep( 1000 * 10 );
}
}
char getKnobReading( char prev )
{
char state;
do {
int A = digitalRead( 7 );
int B = digitalRead( 0 );
state = 0x00;
if( A == 0 )
{
state |= 0x02;
}
else
{
state &= 0x01;
}
if( B == 0 )
{
state |= 0x01;
}
else
{
state &= 0x02;
}
usleep( 1000 );
} while( prev == state );
return state;
}
bool getPushButtonReading( void )
{
if( !digitalRead( 2 ) )
{
return 1;
}
return 0;
}
| 0
|
#include <pthread.h>
{
int id;
int dir;
int row;
long floatduration;
} Log;
int state = 0;
Log logs[15];
char lines[15 +2][161];
pthread_mutex_t display_lock = PTHREAD_MUTEX_INITIALIZER;
static int frog_row = 1 + 15 + 1, frog_col = (5 * 4);
char under_frog = '|';
const char frog = 'Y';
float mixing(float m)
{
return m*rand()/(32767);
}
void init_rivers (int nol, int lpl)
{
int i = 0, j;
const char passage[] = "||||||||";
const char floatingwood[] = "==== ";
while (i++ < lpl)
{
strcat (lines[1 - 1], passage);
strcat (lines[1 + 15 + 1 - 1], passage);
for (j = 1 ; j <= nol ; j++)
strcat (lines[j], floatingwood);
}
}
inline void drawline (char *line, int row)
{
move (row, 0);
printw (line);
}
void rotate_river (char *theline, int dir) {
char tmpline[161];
int len;
len = strlen (theline);
strcpy (tmpline, theline);
if (dir == 1)
{
strncpy (theline, tmpline+1, len-1);
theline[len-1] = tmpline[0];
}
else
{
strncpy (theline+1, tmpline, len-1);
theline[0] = tmpline[len-1];
}
}
void DrawFrog()
{
move(frog_row, frog_col);
printw("%c",frog);
}
void FrogWake()
{
move(frog_row, frog_col);
printw("%c",under_frog);
}
void MoveFrog(int state)
{
FrogWake();
switch(state)
{
case 3: frog_row--; break;
case 4: frog_row++; break;
case 1: frog_col--; break;
case 2: frog_col++; break;
default: break;
}
DrawFrog();
}
int LOGDIR(int dir)
{
return (dir == 1)? -1:1;
}
void MoveLog(int row,int dir)
{
rotate_river(lines[(row)-1], dir);
drawline(lines[row-1], row);
if(frog_row == row)
frog_col += LOGDIR(dir);
DrawFrog();
}
int OutOfBound(int row, int col)
{
if(row > 1 + 15 + 1 || row < 1 || col < 0 || col > (strlen(lines[0])-1))
return 1;
else
return 0;
}
void display (Type who, int d) {
pthread_mutex_lock (&display_lock);
if (who == LOG)
{
MoveLog (logs[d].row, logs[d].dir);
}
else
switch (d) {
case 3:
if (frog_row != 1) { MoveFrog (d); }
else state = 1000;
break;
case 4:
if (frog_row != 1 + 15 + 1) { MoveFrog (d); } break;
case 1:
if (frog_col != 0) { MoveFrog (d); } break;
case 2:
if (frog_col != strlen (lines[0])-1) { MoveFrog (d); } break;
default:
printf ("Error in display state=%d\\n", d); break;
}
under_frog = lines[frog_row - 1][frog_col];
if ((under_frog == ' ') || OutOfBound (frog_row, frog_col))
state = 998;
move (0,0);
refresh ();
pthread_mutex_unlock (&display_lock);
}
Log summon_log (int id, int dir, int row, long floatduration) {
Log log;
log.id = id;
log.dir = dir;
log.row = row;
log.floatduration = floatduration;
return log;
}
void *logf (void* tlog) {
Log *log;
log = (Log *)tlog;
while (state == 999)
{
display (LOG, log->id);
usleep (log->floatduration);
}
return 0;
}
int main () {
pthread_t log_thread[15];
int i;
int dir = 2;
char command;
printf("Please input the difficulty you want (1-10 lower is harder)\\n");
int x = 0;
scanf("%d",&x);
init_rivers (15, 5);
for (i = 0 ; i < 15 ; i++) {
logs[i] = summon_log (i, dir, (1 + i + 1), mixing((float)x*0.1)*1000000 );
if (dir == 1)
dir = 2;
else
dir = 1;
}
state = 999;
initscr ();
clear ();
cbreak ();
noecho ();
timeout (100);
for (i = 0 ; i < 15 ; i++)
pthread_create (&log_thread[i], 0, &logf, &logs[i]);
drawline (lines[1 + 15 + 1 - 1], 1 + 15 + 1);
drawline (lines[1 - 1], 1);
display (FROG, 4);
while (state == 999) {
command = getch ();
switch (command) {
case 'a':
display (FROG, 1);
break;
case 'd':
display (FROG, 2);
break;
case 'w':
display (FROG, 3);
break;
case 's':
display (FROG, 4);
break;
case 'q':
state = 997;
break;
default: break;
}
}
for (i = 0 ; i < 15 ; i++)
pthread_join (log_thread[0], 0);
echo ();
nocbreak ();
endwin ();
switch (state) {
case 1000:
printf ("Mr.Froggy survived from hell!\\n"); break;
case 998:
printf ("Rest in peace Mr.Froggy!\\n"); break;
case 997:
printf ("ByeBye Zzz\\n"); break;
default:
printf ("Err State = %d\\n", state);
}
exit (0);
}
| 1
|
#include <pthread.h>
int n = 0, m = 0, w = 0, c = 0;
pthread_mutex_t lock;
int work(int a, int b) {
return a * b;
}
void* PrintHello(void* threadid)
{
int i,j;
for (i = 0; i < m; ++i) {
pthread_mutex_lock(&lock);
printf("%ld", (pthread_t)threadid);
pthread_mutex_unlock(&lock);
for (j = 0; j < w; ++j) work(i, j);
}
pthread_exit((void*)0);
}
int main(int argc, char *argv[])
{
int t, status;
if (argc != 5) {
argv[0]);
exit(1);
}
n = atoi(argv[1]);
m = atoi(argv[2]);
w = atoi(argv[3]);
c = atoi(argv[4]);
int result;
pthread_t threads[n];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_setconcurrency(c);
for (t = 0; t < n; t++) {
printf("Creating thread %d\\n", t);
result = pthread_create(&threads[t], &attr, PrintHello, (void*)t);
if ( result ) {
perror("pthread_create");
exit(1);
}
}
for(t = 0; t < atoi(argv[1]); t++) {
printf("Main joining with thread %d\\n", t);
result = pthread_join(threads[t], (void*)&status);
if ( result ) {
perror("pthread_join");
exit(1);
}
printf("\\nCompleted joining with thread %d status = %d\\n", t, status);
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
int main(int argc, char** argv)
{
int err;
pthread_mutexattr_t mtxattr;
err = pthread_mutexattr_init(&mtxattr);
if(err)
err_abort(err, "pthread_mutexattr_init");
pthread_mutex_init(&mutex, &mtxattr);
pthread_mutex_lock(&mutex);
printf("main thread locked a mutex");
sleep(1);
printf("\\nmain thread about to release the mutex");
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);
err = pthread_mutexattr_destroy(&mtxattr);
if(err)
err_abort(err, "pthread_mutexattr_destroy");
printf("\\nmain thread exiting\\n");
return 0;
}
| 1
|
#include <pthread.h>
void
_pager_clean (void *arg)
{
struct pager *p = arg;
if (p->pager_state != NOTINIT)
{
pthread_mutex_lock (&p->interlock);
_pager_free_structure (p);
pthread_mutex_unlock (&p->interlock);
}
pager_clear_user_data (p->upi);
}
| 0
|
#include <pthread.h>
struct node {
int val;
struct node* next;
struct node* prev;
};
pthread_mutex_t mt;
pthread_mutexattr_t attr;
struct list {
int count;
struct node *head;
struct node *tail;
pthread_mutex_t *mutex;
};
struct list *memhead = 0;
struct node* getnode(int v) {
struct node *n = (struct node *)malloc(sizeof(struct node));
n->next = n;
n->prev = n->next;
n->val = v;
return n;
}
struct list *createlist() {
struct list *lst = (struct list *)malloc(sizeof(struct list));
lst->count = 0;
lst->head = (struct node *)malloc(sizeof(struct node));
lst->tail = (struct node *)malloc(sizeof(struct node));
lst->head->next = lst->tail;
lst->head->prev = 0;
lst->tail->next = 0;
lst->tail->prev = lst->head;
lst->mutex = &mt;
return lst;
}
void deletelist() {
free(memhead->head);
free(memhead->tail);
free(memhead);
}
void add_node_to_list(struct list *lst, struct node* n) {
pthread_mutex_lock(lst->mutex);
n->prev = lst->tail->prev;
n->next = lst->tail;
lst->tail->prev->next = n;
lst->tail->prev = n;
lst->count ++;
pthread_mutex_unlock(lst->mutex);
}
void delete_node_from_list(struct list *lst, struct node *n) {
pthread_mutex_lock(lst->mutex);
if (n->prev) n->prev->next = n->next;
if (n->next) n->next->prev = n->prev;
free(n);
lst->count--;
pthread_mutex_unlock(lst->mutex);
}
void dump() {
struct node *n = memhead->head->next;
while (n && n!= memhead->tail) {
printf("%d ", n->val);
n = n->next;
}
}
void* deamon(void *args) {
pthread_t ptid = pthread_self();
printf("%ld- started \\n", ptid);
srand((int)ptid);
int i ;
void *p[(1<<12)];
for (i = 0; i< (1<<12); i++) {
struct node *n = getnode(rand());
add_node_to_list(memhead, n);
p[i] = n;
usleep(1800);
}
for (i = (1<<12) - 1; i >= 0; i--) {
delete_node_from_list(memhead, (struct node *)p[i]);
usleep(1800);
}
}
int main() {
int n;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mt, &attr);
memhead = createlist();
pthread_t tid[10];
int i;
for (i = 0; i <10; i++) if (pthread_create(&tid[i], 0, deamon, 0) != 0) exit(-1);
for (i = 0; i < 10; i++) pthread_join(tid[i], 0);
printf("count: %d\\n", memhead->count);
int a = 1234;
int b = 10;
a = a % b;
printf("Resut: %d\\n", a);
return 0;
}
| 1
|
#include <pthread.h>
void
pbuf_debug(void)
{
}
struct pbuf *
pbuf_alloc(unsigned int len)
{
struct pbuf *p;
p = malloc(sizeof(struct pbuf));
if (p != 0) {
p->len = len;
}
return p;
}
int
pbuf_free(struct pbuf *p)
{
free(p);
return 0;
}
int
pbufq_init(struct pbufq *pbufq)
{
pthread_mutex_init(&pbufq->mtx, 0);
TAILQ_INIT(&pbufq->q);
pbufq->n = 0;
return 0;
}
int
pbufq_enqueue(struct pbufq *pbufq, struct pbuf *p)
{
pthread_mutex_lock(&pbufq->mtx);
TAILQ_INSERT_TAIL(&pbufq->q, p, list);
pbufq->n++;
pthread_mutex_unlock(&pbufq->mtx);
return 0;
}
unsigned int
pbufq_nqueued(struct pbufq *pbufq)
{
return pbufq->n;
}
struct pbuf *
pbufq_dequeue(struct pbufq *pbufq)
{
struct pbuf *p;
pthread_mutex_lock(&pbufq->mtx);
p = TAILQ_FIRST(&pbufq->q);
if (p != 0) {
TAILQ_REMOVE(&pbufq->q, p, list);
pbufq->n--;
}
pthread_mutex_unlock(&pbufq->mtx);
return p;
}
struct pbuf *
pbufq_poll(struct pbufq *pbufq)
{
return TAILQ_FIRST(&pbufq->q);
}
| 0
|
#include <pthread.h>
extern pthread_mutex_t write_log_mutex ;
void write_log(const char logtype, const char *format, ...)
{
char buf[256];
va_list arg;
memset(buf, 0, 256);
switch(logtype & 126)
{
case 2:
strcat(buf, "[--]\\t");
break;
case 4:
strcat(buf, "[WW]\\t");
break;
case 8:
strcat(buf, "[EE]\\t");
break;
default:
fprintf(stderr, "warning:wrong arg in write_log\\n");
return;
}
time_t t = time(0);
strcat(buf, asctime(localtime(&t)));
buf[strlen(buf) -1 ] = '\\t';
switch(logtype & 241)
{
case 0:
strcat(buf, "NOMARL\\t");
break;
case 128:
strcat(buf, "SYSTEM\\t");
break;
default:
fprintf(stderr, "warning:wrong arg in write_log\\n");
return;
}
__builtin_va_start((arg));
vsnprintf(strchr(buf, '\\0'), (256 - strlen(buf) -1), format, arg);
;
buf[strlen(buf) < (256 -2) ? strlen(buf) : 256 -2] = '\\n';
pthread_mutex_lock( &write_log_mutex );
FILE *fptr = fopen("server.log", "a");
if(fptr == 0)
{
fprintf(stderr, "can't open file logfle:%m\\n" );
exit(1);
}
if(fputs(buf, fptr) == EOF)
fprintf(stderr, "error write log\\n");
fclose(fptr);
pthread_mutex_unlock( &write_log_mutex );
}
void err_msg(const char *format, ...)
{
va_list arg;
__builtin_va_start((arg));
vfprintf(stderr, format, arg);
;
return;
}
void err_exit(const char *format, ...)
{
va_list arg;
__builtin_va_start((arg));
vfprintf(stderr, format, arg);
;
exit(1);
}
| 1
|
#include <pthread.h>
extern int K;
extern int VECT_SIZE;
extern int aHash[10];
extern int bHash[10];
extern int m[10];
pthread_t ids[48];
int nextLoc = -1;
pthread_mutex_t m_nextLoc;
int totalOnes = 0;
pthread_mutex_t m_totalOnes;
int numMemberships = 0;
pthread_mutex_t m_numMemberships;
int *M;
int *checked;
pthread_mutex_t *m_M;
int nVertices;
struct bloom *a;
int ceilDiv(int a, int b);
void *countOnes(void *x);
void setM();
void resetM();
int checkLocation(int value, int *M);
int setLocation(int value, int *M);
int resetLocation(int value);
void reconstruct0(int loc);
void reconstruct1(int loc);
void *reconstruct0_thread(void *x);
void *reconstruct1_thread(void *x);
int main(int argc, char *argv[]){
nVertices = atoi(argv[1]);
int nNodes = atoi(argv[2]);
K = atoi(argv[4]);
VECT_SIZE = atoi(argv[5]);
seiveInitial();
struct timespec start, finish, mid;
double elapsed, elapsed_m;
a = (struct bloom*)malloc(sizeof(struct bloom));
a->bloom_vector = (int*)malloc(sizeof(int)*(VECT_SIZE/NUM_BITS + 1));
init(a);
FILE *finput = fopen(argv[3],"r");
int i = 0;
int val;
while (i<nNodes){
val = 0;
fscanf(finput,"%d\\n",&val);
insert(val,a);
i++;
}
fclose(finput);
int size = ceilDiv(nVertices,NUM_BITS);
M = (int*)malloc(sizeof(int)*size);
checked = (int*)malloc(sizeof(int)*size);
for (i=0;i<size;i++) checked[i] = 0;
pthread_mutex_init(&m_nextLoc,0);
pthread_mutex_init(&m_totalOnes,0);
pthread_mutex_init(&m_numMemberships,0);
nextLoc = 0;
int rc;
clock_gettime(CLOCK_MONOTONIC, &start);
for (i=0;i<48;i++){
rc = pthread_create(&ids[i],0,countOnes,(void*)(i));
}
void *status;
for (i=0;i<48;i++){
pthread_join(ids[i],&status);
}
clock_gettime(CLOCK_MONOTONIC, &mid);
nextLoc = 0;
if (totalOnes < VECT_SIZE / 2){
resetM();
for (i=0;i<48;i++)
rc = pthread_create(&ids[i],0,reconstruct1_thread,(void*)(i));
for (i=0;i<48;i++)
pthread_join(ids[i],&status);
}
else{
setM();
for (i=0;i<48;i++)
rc = pthread_create(&ids[i],0,reconstruct0_thread,(void*)(i));
for (i=0;i<48;i++)
pthread_join(ids[i],&status);
}
clock_gettime(CLOCK_MONOTONIC, &finish);
elapsed_m = mid.tv_sec - start.tv_sec;
elapsed_m += (mid.tv_nsec - start.tv_nsec)/pow(10,9);
elapsed = finish.tv_sec - start.tv_sec;
elapsed += (finish.tv_nsec - start.tv_nsec)/pow(10,9);
totalOnes = 0;
for (i=0;i<size;i++) totalOnes += count_ones(M[i]);
printf("RECONSTRUCTED SET OF SIZE %d IN TIME %lf WITH MEMBERSHIPS=%d\\n",totalOnes, elapsed,numMemberships);
}
void *reconstruct0_thread(void *x){
while(1){
pthread_mutex_lock(&m_nextLoc);
int nL = nextLoc;
if (nL < ceilDiv (VECT_SIZE , NUM_BITS)){
nextLoc++;
pthread_mutex_unlock(&m_nextLoc);
reconstruct0(nL);
}
else{
pthread_mutex_unlock(&m_nextLoc);
pthread_exit(0);
}
}
}
void *reconstruct1_thread(void *x){
while(1){
pthread_mutex_lock(&m_nextLoc);
int nL = nextLoc;
if (nL < ceilDiv (VECT_SIZE , NUM_BITS)){
nextLoc++;
pthread_mutex_unlock(&m_nextLoc);
reconstruct1(nL);
}
else{
pthread_mutex_unlock(&m_nextLoc);
pthread_exit(0);
}
}
}
int ceilDiv(int a, int b){
return (a+b-1)/b;
}
void *countOnes(void *x){
while (1){
pthread_mutex_lock(&m_nextLoc);
int nL = nextLoc;
if (nL < ceilDiv (VECT_SIZE , NUM_BITS)){
nextLoc++;
pthread_mutex_unlock(&m_nextLoc);
int z = count_ones(a->bloom_vector[nL]);
if (z>0){
pthread_mutex_lock(&m_totalOnes);
totalOnes += z;
pthread_mutex_unlock(&m_totalOnes);
}
}
else{
pthread_mutex_unlock(&m_nextLoc);
pthread_exit(0);
}
}
}
void setM(){
int i;
int size = ceilDiv(nVertices,NUM_BITS);
for (i=0;i<size;i++) M[i] = M[i] | (~0);
}
void resetM(){
int i;
int size = ceilDiv(nVertices,NUM_BITS);
for (i=0;i<size;i++) M[i] = 0;
}
int checkLocation(int value, int *M){
int loc = value / NUM_BITS;
int off = value % NUM_BITS;
int retVal = 0;
if ((M[loc] & (1<<off)) != 0) retVal = 1;
return retVal;
}
int setLocation(int value, int *M){
int loc = value / NUM_BITS;
int off = value % NUM_BITS;
M[loc] = M[loc] | (1 << off);
}
int resetLocation(int value){
int loc = value / NUM_BITS;
int off = value % NUM_BITS;
M[loc] = M[loc] & (~(1 << off));
}
void reconstruct0(int loc){
int i;
for (i=loc*NUM_BITS;i<(loc+1)*NUM_BITS;i++){
int v = a->bloom_vector[loc] & (1 << (i%NUM_BITS));
if (v==0){
int h = 0;
for (h=0;h<3;h++){
int sample = 0, count = 0;
while (sample<nVertices){
if (((i-bHash[h])%aHash[h] + (count*m[h])%aHash[h])%aHash[h] == 0){
sample = ((int) (((double)i - bHash[h])/aHash[h] + ((double)count*m[h])/aHash[h]));
if (sample>0){
resetLocation(sample);
}
}
sample = ((int) (((double)i - bHash[h])/aHash[h] + ((double)count*m[h])/aHash[h]));
count++;
}
}
}
}
}
void reconstruct1(int loc){
int i;
int localCount = 0;
for (i=loc*NUM_BITS;i<(loc+1)*NUM_BITS;i++){
int v = a->bloom_vector[loc] & (1 << (i%NUM_BITS));
if (v!=0){
int h;
for (h=0;h<3;h++){
int sample = 0, count = 0;
while (sample<nVertices){
double cd = count, vd = m[h], ad = aHash[h], bd = bHash[h], s;
s = (i- bd + cd*vd)/ad;
sample = (int) s;
if (floor(s)==s){
if ((sample>0)&&(sample<nVertices)&&(!checkLocation(sample,checked))){
setLocation(sample,checked);
localCount++;
if (is_in(sample,a)){
setLocation(sample,M);
}
}
}
count++;
}
}
}
}
pthread_mutex_lock(&m_numMemberships);
numMemberships += localCount;
pthread_mutex_unlock(&m_numMemberships);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
int brightness, duration;
struct Node* next;
} Node_t;
Node_t* front;
Node_t* back;
} Queue_t;
void addToQueue(Queue_t* queue, int brightness, int duration) {
Node_t* newNode = malloc(sizeof(Node_t));
newNode->brightness = brightness;
newNode->duration = duration;
if(queue->front == 0 && queue->back == 0){
queue->front = newNode;
queue->back = newNode;
queue->front->next = queue->back;
}
else{
queue->back->next = newNode;
queue->back = newNode;
}
queue->back->next = 0;
}
void removeFromQueue(Queue_t* queue, int* pBrightness, int* pDuration) {
if(queue->front == 0 && queue->back == 0){
queue->front = 0;
queue->back = 0;
}else{
queue->front = queue->front->next;
}
}
int queueSize(Queue_t* queue) {
int counter = 1;
Node_t* currentNode = queue->front;
if(queue->front == 0 && queue->back == 0){
return 0;
}else if(queue->front == queue->back){
return 1;
}
else{
while(currentNode->next != 0){
currentNode = currentNode->next;
counter++;
}
}
return counter;
}
void printQueue(Queue_t* queue){
Node_t* currentNode = queue->front;
int counter = 0;
if(queue->front == 0 && queue->back == 0){
printf("Queue is empty\\n");
}else{
while(currentNode->next != 0){
printf("Node %d, brightness %d, duration %d\\n",
counter,
currentNode->brightness,
currentNode->duration
);
currentNode = currentNode->next;
counter++;
}
printf("Node %d, brightness %d, duration %d\\n",
counter,
currentNode->brightness,
currentNode->duration
);
}
}
void* fillQueue(void* queue){
printf("Filling thread started\\n");
int i;
for(i = 0; i < 100000; i++){
pthread_mutex_lock(&mutex);
addToQueue(queue, i, i);
pthread_mutex_unlock(&mutex);
}
printf("Filling thread finished\\n");
return 0;
free(queue);
}
int main(){
Queue_t* queue = malloc(sizeof(Queue_t));
pthread_t fillQueueThread1, fillQueueThread2;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&fillQueueThread1, &attr, fillQueue, (void*)queue);
pthread_create(&fillQueueThread2, &attr, fillQueue, (void*)queue);
pthread_join(fillQueueThread1, 0);
pthread_join(fillQueueThread1, 0);
printf("Queue size %d\\n",queueSize(queue));
return 0;
}
| 1
|
#include <pthread.h>
void funcCreateThread();
void *evenThread(void *);
void *oddThread(void *);
int evenOddThread(int);
int count;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
int main ()
{
funcCreateThread();
while(1);
return 0;
}
void funcCreateThread()
{
pthread_t pthreadId[2];
pthread_attr_t attr;
if (pthread_attr_init(&attr)){
perror("pthread_attr_init");
exit(1);
}
if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)){
perror("pthread_attr_setdetachedstate");
exit(1);
}
pthread_create(&pthreadId[0], &attr, &evenThread, (void *)&pthreadId[0]);
pthread_create(&pthreadId[1], &attr, &oddThread, (void *)&pthreadId[1]);
}
void *evenThread(void *data)
{
printf("in Even Thread\\n");
int i, result;
for (;;){
pthread_mutex_lock(&mutex);
if ( (count & 1) == 0 )
pthread_cond_wait(&condition_var, &mutex);
count ++;
printf("Number is even %d\\n", count);
pthread_cond_signal(&condition_var);
if (count >= 200){
pthread_mutex_unlock(&mutex);
return (0);
}
pthread_mutex_unlock(&mutex);
}
}
void *oddThread(void *data)
{
printf("in Odd Thread\\n");
int i, result;
for (; ;){
pthread_mutex_lock(&mutex);
if ( (count & 1) != 0 )
pthread_cond_wait(&condition_var, &mutex);
count ++;
printf("Number is odd %d\\n", count);
pthread_cond_signal(&condition_var);
if (count >= 200){
pthread_mutex_unlock(&mutex);
return (0);
}
pthread_mutex_unlock(&mutex);
}
}
int evenOddFunc(int data)
{
if ((data & 1) == 0)
return 1;
else
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t m;
void handle(void* data){
printf("thread [%s] exit........\\n",data);
pthread_mutex_unlock(&m);
}
void* runo(void*d){
int i;
for(i = 0 ;;i += 2){
pthread_mutex_lock(&m);
printf("%d\\n",i);
pthread_mutex_unlock(&m);
}
}
void* runa(void*d){
int i;
for(i = 1 ;;i += 2){
pthread_mutex_lock(&m);
pthread_cleanup_push(handle,"runa");
printf("%d\\n",i);
pthread_cleanup_pop(0);
pthread_mutex_unlock(&m);
}
}
int main(){
pthread_t to;
pthread_t ta;
pthread_mutex_init(&m,0);
pthread_create(&to,0,runo,0);
pthread_create(&ta,0,runa,0);
sleep(1);
pthread_cancel(ta);
pthread_join(to,(void**)0);
pthread_join(ta,(void**)0);
pthread_mutex_destroy(&m);
return 0;
}
| 1
|
#include <pthread.h>
int a = 0;
int threadsNum;
pthread_mutex_t mut;
int* massiv;
int mas_size;
int limit;
int next;
pthread_mutex_t mut;
void initializing(){
massiv[0] = 1;
massiv[3] = 1;
massiv[5] = 1;
massiv[7] = 1;
massiv[8] = 1;
massiv[9] = 1;
}
void get_next(){
while((next < limit)&&( massiv[next] == 1)){
next += 1;
}
if(next == mas_size){
next = -2;
}
else{
if(massiv[next] == 1){
next = -1;
}
else{
massiv[next] = 1;
}
}
}
void * f( int my_c) {
int t = 0;
pthread_mutex_lock(&mut);
int i = my_c*2 + 1;
pthread_mutex_unlock(&mut);
while( i < mas_size) {
pthread_mutex_lock(&mut);
massiv[i] = 1;
i+= my_c + 1;
pthread_mutex_unlock(&mut);
}
return 0;
}
int main(int argc, const char* argv[]) {
int i;
int count;
pthread_mutex_init(&mut, 0);
threadsNum = atoi(argv[1]);
mas_size = atoi(argv[2]);
massiv = (int*)calloc(sizeof(int), mas_size+10);
initializing();
int *k = (int*)malloc(threadsNum * sizeof(int));
int *newsimple = (int*)malloc(threadsNum * sizeof(int));
pthread_t *threads;
limit = 9;
next = 0;
while (next!= -2){
count = 0;
threads = (pthread_t *) malloc(sizeof(pthread_t) * threadsNum);
for( i = 0; i < threadsNum; ++i ) {
get_next();
if(( next != -1)&&(next != -2)){
pthread_mutex_lock(&mut);
newsimple[count] = next;
count++;
pthread_mutex_unlock(&mut);
}
else{
if(next == -1){
pthread_mutex_lock(&mut);
next = limit - 1;
limit = limit*limit;
if(limit > mas_size){
limit = mas_size;
}
pthread_mutex_unlock(&mut);
break;
}
else break;
}
}
for(i = 0; i < threadsNum; ++i ) {
k[i] = i;
}
for( i = 0; i < count; ++i ) {
printf("%d ", newsimple[i]+1);
pthread_create(threads + i, 0, f,newsimple[i]);
}
void *p;
i = 0;
while(i < count) {
pthread_join(threads[i], &p);
i++;
}
free(threads);
}
free(massiv);
free(k);
free(newsimple);
printf("There is all!\\n");
return 0;
}
| 0
|
#include <pthread.h>
int count = 0;
int thread_ids[3] = {0,1,2};
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *inc_count(void *t)
{
int i;
long my_id = (long)t;
for (i=0; i<10; i++) {
pthread_mutex_lock(&count_mutex);
count++;
if (count == 12) {
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 *t)
{
long my_id = (long)t;
printf("Starting watch_count(): thread %ld\\n", my_id);
pthread_mutex_lock(&count_mutex);
while (count<12) {
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %ld Condition signal received.\\n", my_id);
count += 125;
printf("watch_count(): thread %ld count now = %d.\\n", my_id, count);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main (int argc, char *argv[])
{
int i, rc;
long t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, watch_count, (void *)t1);
pthread_create(&threads[1], &attr, inc_count, (void *)t2);
pthread_create(&threads[2], &attr, inc_count, (void *)t3);
for (i=0; i<3; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited on %d threads. Done.\\n", 3);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
void * other(void * unused){
while(1)
kitsune_update("testkick");
}
void * testwait(void * unused){
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
while(1)
{
kitsune_update("testwait");
pthread_mutex_lock( &mutex );
printf("\\n\\n*********2: thread waiting forever....*********************\\n\\n");
fflush(stdout);
ktthreads_pthread_cond_wait( &cond, &mutex );
pthread_mutex_unlock( &mutex );
}
return 0;
}
int main(void){
pthread_t t;
pthread_t k;
int init = 0;
int limitprint = 0;
while(1){
kitsune_update("main");
if(!init){
kitsune_pthread_create(&t, 0, &testwait, 0);
kitsune_pthread_create(&k, 0, &other, 0);
init = 1;
}
limitprint++;
ktthreads_ms_sleep(100);
if(limitprint%500 == 0){
printf("2: main loop ");
fflush(stdout);
}
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_t thread[3];
pthread_mutex_t mut;
int number = 0, i, j;
void *woker(pthread_t consumer)
{
printf("threadx: I'm thread %lu\\n", consumer);
pthread_mutex_lock(&mut);
for(i = 0; i < 10; ++ i)
{
++ number;
printf("thread: number = %d\\n", number);
}
pthread_mutex_unlock(&mut);
printf("thread: 主函数在等我完成任务吗?\\n");
pthread_exit(0);
}
void thread_create(void)
{
printf("thread_createing......\\n");
memset(&thread, 0, sizeof(thread));
for(int i = 0; i < 3; ++ i)
{
if((pthread_create(&thread[i], 0, woker(thread[i]), 0)) != 0)
{
}
else
{
}
}
}
void thread_wait(void)
{
printf("thread_waiting......\\n");
for(int i = 0; i < 3; ++ i)
{
if(thread[0] != 0)
{
pthread_join(thread[i], 0);
printf("线程%lu已经结束.\\n", thread[i]);
}
}
}
int main()
{
pthread_mutex_init(&mut, 0);
printf("我是主函数,我正在创建线程。\\n");
thread_create();
printf("我是主函数,我正在等待线程完成任务。\\n");
thread_wait();
return 0;
}
| 1
|
#include <pthread.h>
int N;
int *X;
int gSum[4];
pthread_mutex_t mutex;
void InitializeArray(int **X, int *N)
{
int i;
*N = 20;
*X = (int *)malloc(sizeof(int)*(*N));
for (i = 0; i < *N; i++) {
(*X)[i] = 0;
}
return;
}
void *thread_func(void *pArg)
{
int tNum = *((int *) pArg);
int i, result;
for (i=0; i<N;i++) {
pthread_mutex_lock(&mutex);
result = X[i]+1;
sched_yield();
X[i] = result;
pthread_mutex_unlock(&mutex);
}
printf("Thread %d finished\\n", tNum);
free((int *)pArg);
return 0;
}
int main (int argc, char* argv[])
{
int j;
pthread_t tHandles[4];
int *threadnum;
InitializeArray(&X,&N);
pthread_mutex_init(&mutex,0);
for(j=0; j<N; j++)printf("X[%d]=%d\\n", j, X[j]);
for (j=0; j < 4; j++) {
threadnum = (int *)malloc(sizeof(int));
*threadnum = j;
pthread_create(&tHandles[j],0,thread_func,(void *)threadnum);
}
for (j=0; j<4;j++) {
pthread_join(tHandles[j],0);
}
pthread_mutex_destroy(&mutex);
for(j=0; j<N; j++)printf("X[%d]=%d\\n", j, X[j]);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t child_mutex = PTHREAD_MUTEX_INITIALIZER;
volatile int child_waiting = 0;
double endtime;
void usage(void)
{
rt_help();
printf("testpi-1 specific options:\\n");
}
int parse_args(int c, char *v)
{
int handled = 1;
switch (c) {
case 'h':
usage();
exit(0);
default:
handled = 0;
break;
}
return handled;
}
double d_gettimeofday(void)
{
int retval;
struct timeval tv;
retval = gettimeofday(&tv, 0);
if (retval != 0) {
perror("gettimeofday");
exit(-1);
}
return (tv.tv_sec + ((double)tv.tv_usec) / 1000000.);
}
void *childfunc(void *arg)
{
pthread_cond_t *cp = (pthread_cond_t *) arg;
while (child_waiting == 0) {
pthread_mutex_lock(&child_mutex);
child_waiting = 1;
if (pthread_cond_wait(cp, &child_mutex) != 0) {
perror("pthread_cond_wait");
exit(-1);
}
endtime = d_gettimeofday();
child_waiting = 2;
pthread_mutex_unlock(&child_mutex);
while (child_waiting == 2) {
poll(0, 0, 10);
}
}
pthread_exit(0);
}
void test_signal(int broadcast_flag, int iter)
{
pthread_attr_t attr;
pthread_t childid;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int i;
int prio;
struct sched_param schparm;
double starttime;
prio = sched_get_priority_max(SCHED_FIFO);
if (prio == -1) {
perror("sched_get_priority_max");
exit(-1);
}
schparm.sched_priority = prio;
if (sched_setscheduler(getpid(), SCHED_FIFO, &schparm) != 0) {
perror("sched_setscheduler");
exit(-1);
}
if (pthread_attr_init(&attr) != 0) {
perror("pthread_attr_init");
exit(-1);
}
if (pthread_attr_setschedpolicy(&attr, SCHED_FIFO) != 0) {
perror("pthread_attr_setschedpolicy");
exit(-1);
}
if (pthread_attr_setschedparam(&attr, &schparm) != 0) {
perror("pthread_attr_setschedparam");
exit(-1);
}
if (pthread_create(&childid, &attr, childfunc, (void *)&cond) != 0) {
perror("pthread_create");
exit(-1);
}
for (i = 0; i < iter; i++) {
pthread_mutex_lock(&child_mutex);
child_waiting = 0;
while (child_waiting == 0) {
pthread_mutex_unlock(&child_mutex);
sched_yield();
pthread_mutex_lock(&child_mutex);
}
pthread_mutex_unlock(&child_mutex);
if (broadcast_flag) {
starttime = d_gettimeofday();
if (pthread_cond_broadcast(&cond) != 0) {
perror("pthread_cond_broadcast");
exit(-1);
}
} else {
starttime = d_gettimeofday();
if (pthread_cond_signal(&cond) != 0) {
perror("pthread_cond_signal");
exit(-1);
}
}
for (;;) {
pthread_mutex_lock(&child_mutex);
if (child_waiting == 2) {
break;
}
pthread_mutex_unlock(&child_mutex);
poll(0, 0, 10);
}
printf("%s() latency: %d microseconds\\n",
(broadcast_flag
? "pthread_cond_broadcast"
: "pthread_cond_signal"),
(int)((endtime - starttime) * 1000000.));
pthread_mutex_unlock(&child_mutex);
}
pthread_mutex_lock(&child_mutex);
child_waiting = 3;
pthread_mutex_unlock(&child_mutex);
if (pthread_join(childid, 0) != 0) {
perror("pthread_join");
exit(-1);
}
}
int main(int argc, char *argv[])
{
struct sched_param sp;
long iter;
setup();
rt_init("h", parse_args, argc, argv);
sp.sched_priority = sched_get_priority_max(SCHED_FIFO);
if (sp.sched_priority == -1) {
perror("sched_get_priority_max");
exit(-1);
}
if (sched_setscheduler(0, SCHED_FIFO, &sp) != 0) {
perror("sched_setscheduler");
exit(-1);
}
if (argc == 1) {
fprintf(stderr, "Usage: %s iterations [unicast]\\n", argv[0]);
exit(-1);
}
iter = strtol(argv[1], 0, 0);
test_signal(argc == 2, iter);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_t soundid;
int stopmp3;
void *madplay_run( void *arg)
{
char buff[1024], mp3name[512], *item, *start;
int i = 0;
struct st_action_unit *unit = (struct st_action_unit *)arg;
printf("== madplay_run ==\\n");
printf("mp3 = %s\\n", unit->mp3sdata);
age:
start = (char *)unit->mp3sdata;
while((*start) && !stopmp3){
bzero(mp3name, 512);
for( item = start; *item; item++) {
if (*item == ' '){
mp3name[i++] = 0;
start = item + 1;
break;
}else
mp3name[i++] = *item;
}
sprintf(buff, "cd /music && madplay %s", mp3name);
printf("%s\\n", buff);
system(buff);
i = 0;
if (! *item) break;
}
if ( unit->sdata[0] == 1 && !stopmp3 ) goto age;
printf("==madplay end==\\n");
pthread_mutex_lock(&malloc_flag_mutex);
free(unit->mp3sdata);
free(unit);
pthread_mutex_unlock(&malloc_flag_mutex);
return 0;
}
int play_sound(struct st_action_unit *unit)
{
int res = -1;
struct st_action_unit *p;
stopmp3 = 0;
pthread_mutex_lock( &malloc_flag_mutex);
p = (struct st_action_unit *)malloc(sizeof *unit);
pthread_mutex_unlock( &malloc_flag_mutex);
if ( !p ) goto err;
p->dev_addr = unit->dev_addr;
p->sdata[0] = unit->sdata[0];
pthread_mutex_lock( &malloc_flag_mutex);
p->mp3sdata = malloc(strlen((char *)unit->mp3sdata)+1);
pthread_mutex_unlock( &malloc_flag_mutex);
if (!p->mp3sdata){
pthread_mutex_lock( &malloc_flag_mutex);
free(p);
pthread_mutex_unlock( &malloc_flag_mutex);
goto err;
}
bzero(p->mp3sdata, strlen((char *)unit->mp3sdata)+1);
strcpy((char *)p->mp3sdata, (char *)unit->mp3sdata);
res = pthread_create(&soundid, 0, (void *)madplay_run, (void *)p);
err:
printf("ret = %d\\n\\n\\n", res);
if( res < 0) {
printf(" play_sound:err\\n");
}
return res;
}
int stop_sound()
{
stopmp3 = 1;
return (system("killall madplay"));
}
int contiue_sound()
{
return pthread_kill(soundid, SIGCONT);
}
| 0
|
#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;
}
| 1
|
#include <pthread.h>
pthread_mutex_t M1= PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t M2= PTHREAD_MUTEX_INITIALIZER;
void* producer_routine(void* arg)
{
while(1)
{
if( 0 == pthread_mutex_lock(&M1))
{
if( 0 ==pthread_mutex_lock(&M2))
{
printf("\\n %s Got lock M1 and M2\\n",__func__);
}
pthread_mutex_unlock(&M2);
}
printf("\\n %s\\n",__func__);
pthread_mutex_unlock(&M1);
}
}
void* consumer_routine(void* arg)
{
while(1)
{
if(0 == pthread_mutex_lock(&M2))
{
if(0 == pthread_mutex_lock(&M1))
{
printf("\\n %s Got lock M2 and M1\\n",__func__);
}
pthread_mutex_unlock(&M1);
}
printf("\\n %s\\n",__func__);
pthread_mutex_unlock(&M2);
}
}
func_t func_arg[]={producer_routine ,consumer_routine};
int main (int argc ,char *argv[])
{
pthread_t tid[2];
int i=0;
for(i=0;i<2;++i)
if(0 != pthread_create(&tid[i],0,func_arg[i],0))
{
exit(-1);
}
for(i=0;i<2;++i)
pthread_join(&tid[i],0);
}
| 0
|
#include <pthread.h>
void *philosopher (void *id);
void grab_chopstick (int, int, char*);
void down_chopsticks (int, int);
int food_on_table ();
int get_token ();
void return_token ();
pthread_mutex_t chopstick[5];
pthread_mutex_t print;
pthread_t philo[5];
pthread_mutex_t food_lock;
pthread_mutex_t num_can_eat_lock;
int num_can_eat = 5 - 1;
int main (int argc, char **argv)
{
int i;
pthread_mutex_init (&food_lock, 0);
pthread_mutex_init (&num_can_eat_lock, 0);
for (i = 0; i < 5; i++)
pthread_mutex_init (&chopstick[i], 0);
int* mas = malloc(5);
for (i = 0; i < 5; i++)
mas[i] = i;
for (i = 0; i < 5; i++)
pthread_create (&philo[i], 0, philosopher, &mas[i]);
for (i = 0; i < 5; i++)
pthread_join (philo[i], 0);
return 0;
}
void* philosopher (void *num)
{
struct timeval Start;
struct timeval End;
long Sum_Wait_Time;
int id;
int left_chopstick, right_chopstick;
id = *(int*)num;
printf ("Philosopher %d: ready to eat.\\n", id);
right_chopstick = id;
left_chopstick = id + 1;
if (left_chopstick == 5)
left_chopstick = 0;
int f;
int sleep_time;
while (f = food_on_table ())
{
gettimeofday(&Start, 0);
srand(time(0));
sleep_time = 100000 * (rand() % 5 + 1);
usleep(sleep_time);
get_token ();
grab_chopstick (id, right_chopstick, "right ");
grab_chopstick (id, left_chopstick, "left");
printf ("Philosopher %d: eating.\\n", id);
down_chopsticks (left_chopstick, right_chopstick);
return_token ();
gettimeofday(&End, 0);
long wait_time = 1000000 * (End.tv_sec - Start.tv_sec) + (End.tv_usec - Start.tv_usec);
Sum_Wait_Time += wait_time;
printf("Philosopher %d: waited %ld ms.\\n", id, wait_time);
}
printf ("Philosopher %d: finished eating.\\n", id);
sleep(1);
printf ("Philosopher %d: summary waited %ld ms.\\n", id, Sum_Wait_Time);
return (0);
}
int food_on_table ()
{
static int food = 100;
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]);
}
int get_token ()
{
int successful = 0;
while (successful == 0)
{
pthread_mutex_lock (&num_can_eat_lock);
if (num_can_eat > 0)
{
num_can_eat--;
successful = 1;
}
else
{
successful = 0;
}
pthread_mutex_unlock (&num_can_eat_lock);
}
}
void return_token ()
{
pthread_mutex_lock (&num_can_eat_lock);
num_can_eat++;
pthread_mutex_unlock (&num_can_eat_lock);
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
void *threadCounter(void *param){
int *args = (int *)param;
int i;
for(i = 0; i < 1000000; i++){
pthread_mutex_lock(&lock);
(*args)++;
pthread_mutex_unlock(&lock);
}
}
int main(int argc, char** argv){
pthread_t t1;
pthread_t t2;
int shared = 0;
int err;
err = pthread_mutex_init(&lock, 0);
err = pthread_create(&t1, 0, threadCounter, (void *)&shared);
if(err != 0){
errno = err;
perror("pthread_create");
exit(1);
}
err = pthread_create(&t2, 0, threadCounter, (void *)&shared);
if(err != 0){
errno = err;
perror("pthread_create");
exit(1);
}
err = pthread_join(t1, 0);
if(err != 0){
errno = err;
perror("pthread_join");
exit(1);
}
err = pthread_join(t2, 0);
if(err != 0){
errno = err;
perror("pthread_join");
exit(1);
}
printf("After both threads are done executing, `shared` = %d\\n", shared);
err = pthread_mutex_destroy(&lock);
return 0;
}
| 0
|
#include <pthread.h>
static int global = 0;
pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
void *func(void *arg)
{
int local, i;
for (i=0; i<1000000; i++) {
pthread_mutex_lock(&mylock);
local = global;
local++;
global = local;
pthread_mutex_unlock(&mylock);
}
return 0;
}
int main()
{
pthread_t t1, t2;
pthread_create(&t1, 0, func, 0);
pthread_create(&t2, 0, func, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
printf("global = %d\\n", global);
}
| 1
|
#include <pthread.h>
static int Resource_Counter = 0;
static pthread_mutex_t Resource_Counter_Mutex =
PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t Got_Resources_Condition =
PTHREAD_COND_INITIALIZER;
static void *producer_start(void *arg) {
static const size_t TIMES_TO_PRODUCE = 10;
static const int ITEMS_TO_PRODUCE = 4;
static const unsigned int PAUSE_IN_SEC = 5;
for (size_t i = 0; i < TIMES_TO_PRODUCE; ++i) {
pthread_mutex_lock(&Resource_Counter_Mutex);
Resource_Counter += ITEMS_TO_PRODUCE;
pthread_cond_broadcast(&Got_Resources_Condition);
pthread_mutex_unlock(&Resource_Counter_Mutex);
sleep(PAUSE_IN_SEC);
}
return 0;
}
static void *consumer_start(void *arg) {
for (;;) {
pthread_mutex_lock(&Resource_Counter_Mutex);
while (Resource_Counter <= 0) {
pthread_cond_wait(
&Got_Resources_Condition,
&Resource_Counter_Mutex
);
}
--Resource_Counter;
pthread_mutex_unlock(&Resource_Counter_Mutex);
}
return 0;
}
int main(int argc, char **argv) {
pthread_t producer_threads[1];
pthread_t consumer_threads[4];
for (size_t i = 0; i < 1; ++i) {
if (0 != pthread_create(
&producer_threads[i],
0,
producer_start,
0
)) {
fputs("Failed to create a producer thread.\\n", stderr);
}
}
for (size_t i = 0; i < 4; ++i) {
if (0 != pthread_create(
&consumer_threads[i],
0,
consumer_start,
0
)) {
fputs("Failed to create a consumer thread.\\n", stderr);
}
}
for (size_t i = 0; i < 1; ++i) {
if (0 != pthread_join(producer_threads[i], 0)) {
fputs("Failed to wait for the thread to finish.\\n", stderr);
}
}
for (size_t i = 0; i < 4; ++i) {
if (0 != pthread_join(consumer_threads[i], 0)) {
fputs("Failed to wait for the thread to finish.\\n", stderr);
}
}
return 0;
}
| 0
|
#include <pthread.h>
int value;
int n_wait;
pthread_mutex_t lock;
pthread_cond_t cond;
}sem_t;
int sem_init(sem_t *sem, int pshared, unsigned int value);
int sem_wait(sem_t *sem);
int sem_post(sem_t *sem);
int sem_trywait(sem_t *sem);
int sem_getvalue(sem_t *sem, int *sval);
int sem_destroy(sem_t *sem);
sem_t sem;
void* produtor(void *arg);
void* consumidor(void *arg);
int produce_item();
int remove_item();
void insert_item(int item);
void consume_item(int item);
double drand48(void);
void srand48(long int seedval);
int b[10];
int cont = 0;
int prodpos = 0;
int conspos = 0;
int main(){
pthread_t p[10];
pthread_t c[10];
sem_init(&sem, 0, 10);
int i;
int* id = 0;
srand48(time(0));
for(i = 0; i < 10; i++){
id = (int*)malloc(sizeof(int));
*id = i;
pthread_create(&p[i], 0, produtor, (void*)(id));
}
for(i = 0; i < 10; i++){
id = (int*)malloc(sizeof(int));
*id = i;
pthread_create(&c[i], 0, consumidor, (void*)(id));
}
pthread_join(p[0], 0);
pthread_join(c[0], 0);
return 0;
}
void* produtor(void* arg){
int i = *((int*)arg);
int item;
while(1){
sem_wait(&sem);
item = produce_item();
b[prodpos] = item;
prodpos = (prodpos + 1)%10;
sem_post(&sem);
insert_item(item);
}
}
void* consumidor(void* arg){
int i = *((int*)arg);
int item;
while(1){
sem_wait(&sem);
item = remove_item(conspos);
conspos = (conspos + 1)%10;
sem_post(&sem);
consume_item(item);
}
}
int produce_item(){
printf("Gerando...\\n");
sleep(1);
return (int)(drand48()*1000);
}
int remove_item(int conspos){
printf("removendo..\\n");
sleep(1);
return b[conspos];
}
void insert_item(int item){
printf("Unidades produzidas: %d\\n", item);
sleep(1);
}
void consume_item(int item){
printf("Consumindo %d unidades\\n", item);
sleep(1);
}
int sem_init(sem_t *sem, int pshared, unsigned int value){
sem->value = value;
sem->n_wait = 0;
pthread_mutex_init(&sem->lock, 0);
pthread_cond_init(&sem->cond, 0);
return 0;
}
int sem_wait(sem_t *sem){
pthread_mutex_lock(&sem->lock);
if(sem->value > 0)
sem->value--;
else{
sem->n_wait++;
pthread_cond_wait(&sem->cond, &sem->lock);
}
pthread_mutex_unlock(&sem->lock);
return 0;
}
int sem_post(sem_t *sem){
pthread_mutex_lock(&sem->lock);
if (sem->n_wait){
sem->n_wait--;
pthread_cond_signal(&sem->cond);
}else
sem->value++;
pthread_mutex_unlock(&sem->lock);
return 0;
}
int sem_trywait(sem_t *sem){
int r;
pthread_mutex_lock(&sem->lock);
if(sem->value > 0){
sem->value--;
r = 0;
}else
r = 1;
pthread_mutex_unlock(&sem->lock);
return r;
}
int sem_getvalue(sem_t *sem, int *sval){
pthread_mutex_lock(&sem->lock);
*sval = sem->value;
pthread_mutex_unlock(&sem->lock);
return 0;
}
int sem_destroy(sem_t *sem){
if(sem->n_wait)
return 1;
pthread_mutex_destroy(&sem->lock);
pthread_cond_destroy(&sem->cond);
return 0;
}
| 1
|
#include <pthread.h>
struct data_t
{
char q[100][1025];
pthread_mutex_t lock;
pthread_cond_t cond;
int now;
int next;
int isfull;
int tnum;
};
char cmdlist[100][2048];
int cmdlist_len = 0;
pthread_mutex_t lock_fd;
void parse_cmd(char *args[100], char *cmd)
{
int in_q = 0;
int is_q_double;
int is_start = 1;
int args_idx = 0;
int cmd_len = strlen(cmd);
int i;
for (i = 0; i < cmd_len; ++i)
{
switch (cmd[i])
{
case ' ':
if (!in_q)
{
is_start = 1;
cmd[i] = '\\0';
}
break;
case '\\"':
case '\\'':
if (!in_q) {
is_start = 1;
is_q_double = (cmd[i] == '\\"' ? 1 : 0);
cmd[i] = '\\0';
in_q = 1;
}
else if ((cmd[i] == '"' && is_q_double)
|| (cmd[i] == '\\'' && !is_q_double))
{
is_start = 1;
cmd[i] = '\\0';
in_q = 0;
}
break;
default:
if (is_start)
{
args[args_idx++] = cmd + i;
is_start = 0;
}
break;
}
}
args[args_idx++] = 0;
}
void *t_func(void *_data)
{
struct data_t *data = (struct data_t*) _data;
int p1[2];
int i;
int rtn;
pthread_mutex_lock(&lock_fd);
if (pipe(p1) == -1)
{
fprintf(stderr, "%d: pipe error\\n", data->tnum);
exit(1);
}
if (fork() == 0)
{
char *args[100];
close(p1[1]);
dup2(p1[0], STDIN_FILENO);
close(p1[0]);
char buf[1024] = "cat";
args[0] = buf;
for (i = 1; i < cmdlist_len; ++i)
{
int p2[2];
if (pipe(p2) == -1)
{
fprintf(stderr, "%d: pipe error\\n", data->tnum);
exit(1);
}
if (fork() == 0)
{
close(p2[0]);
dup2(p2[1], STDOUT_FILENO);
close(p2[1]);
break;
}
close(p2[1]);
dup2(p2[0], STDIN_FILENO);
close(p2[0]);
}
parse_cmd(args, cmdlist[i - 1]);
execvp(args[0], args);
}
close(p1[0]);
pthread_mutex_unlock(&lock_fd);
pthread_mutex_t *lock = &data->lock;
pthread_cond_t *cond = &data->cond;
while (1)
{
char str[1025];
pthread_mutex_lock(lock);
if (!(data->isfull) && data->next == data->now)
{
pthread_cond_wait(cond, lock);
}
strcpy(str, data->q[data->now++]);
data->now %= 100;
data->isfull = 0;
pthread_mutex_unlock(lock);
if (str[0] == EOF)
{
close(p1[1]);
wait(&rtn);
return 0;
}
write(p1[1], str, sizeof(char) * strlen(str));
}
}
int main(int argc, char *argv[])
{
int num_thread = 1;
char cmd_str[1025] = "";
pthread_t *p_thread;
struct data_t *p_data;
char *now_pos = 0;
int i;
void *nptr = 0;
pthread_mutex_init(&lock_fd, 0);
for (i = 1; i < argc; ++i)
{
switch(argv[i][0])
{
case '-':
if (strlen(argv[i]) > 1)
{
switch(argv[i][1])
{
case 'c':
num_thread = atoi(argv[++i]);
break;
default:
fprintf(stderr, "invalid option: %s\\n", argv[i]);
exit(1);
break;
}
}
else
{
fprintf(stderr, "invalid argument\\n");
exit(1);
}
break;
default:
strcpy(cmd_str, argv[i]);
break;
}
}
if (num_thread < 1)
{
fprintf(stderr, "thread num(-c [NUM]) must be larger then 0\\n");
exit(1);
}
if (strlen(cmd_str) == 0)
{
fprintf(stderr, "usuage: papi -c [number of threads] command\\n");
exit(1);
}
now_pos = cmd_str;
while (1)
{
int idx = 0;
char *next_pos = strstr(now_pos, "==");
if (*now_pos == ' ')
now_pos++;
while (*now_pos != '\\0' && now_pos != next_pos)
cmdlist[cmdlist_len][idx++] = *(now_pos++);
cmdlist[cmdlist_len++][idx++] = '\\0';
if (*now_pos != '\\0')
now_pos += 2;
if (next_pos == 0)
break;
}
p_thread = (pthread_t*) malloc(sizeof(pthread_t) * num_thread);
p_data = (struct data_t*) malloc(sizeof(struct data_t) * num_thread);
for (i = 0; i < num_thread; ++i)
{
p_data[i].now = 0;
p_data[i].next = 0;
p_data[i].isfull = 0;
p_data[i].tnum = i;
pthread_mutex_init(&p_data[i].lock, 0);
pthread_cond_init(&p_data[i].cond, 0);
pthread_create(&p_thread[i], 0, t_func, (void*) &p_data[i]);
}
i = -1;
while (!feof(stdin))
{
char str[1025];
if (fgets(str, 1025, stdin) == 0)
break;
while (1)
{
i = (i + 1) % num_thread;
pthread_mutex_lock(&p_data[i].lock);
if (p_data[i].isfull)
{
pthread_mutex_unlock(&p_data[i].lock);
continue;
}
strcpy(p_data[i].q[p_data[i].next++], str);
p_data[i].next %= 100;
if (p_data[i].next == p_data[i].now)
p_data[i].isfull = 1;
pthread_cond_signal(&p_data[i].cond);
pthread_mutex_unlock(&p_data[i].lock);
break;
}
}
for (i = 0; i < num_thread; ++i)
{
char str[2];
str[0] = EOF;
str[1] = '\\0';
pthread_mutex_lock(&p_data[i].lock);
while (p_data[i].isfull)
{
pthread_mutex_unlock(&p_data[i].lock);
pthread_mutex_lock(&p_data[i].lock);
}
strcpy(p_data[i].q[p_data[i].next++], str);
p_data[i].next %= 100;
if (p_data[i].next == p_data[i].now)
p_data[i].isfull = 1;
pthread_cond_signal(&p_data[i].cond);
pthread_mutex_unlock(&p_data[i].lock);
}
for (i = 0; i < num_thread; ++i)
{
pthread_join(p_thread[i], &nptr);
}
return 0;
}
| 0
|
#include <pthread.h>
void * fonc_P0(void *num)
{
while (*stop==0){
pthread_mutex_lock (&voieGL);
if(aig2->occupee == 0 && aig2->reservee == 0){
if(aig2->TGV >0){
sem_post(aig2->semTGV);
}
else if(aig2->GL>0){
sem_post(aig2->semGL);
}
}
if((voieC->occupee+voieC->reservee)<2){
if(voieC->TGV >0){
sem_post(voieC->semTGV);
}
else if(voieC->GL>0){
sem_post(voieC->semGL);
}
}
if((voieD->occupee+voieD->reservee )< 2){
if(voieD->TGV >0){
sem_post(voieD->semTGV);
}
else if(voieD->GL>0){
sem_post(voieD->semGL);
}
}
pthread_mutex_unlock (&voieGL);
}
pthread_exit(0);
}
void * fonc_P1(void *num)
{
while(*stop==0){
pthread_mutex_lock (&marchandises);
if(aig1->occupee == 0 && aig1->reservee == 0 && aig1->M>0){
sem_post(aig1->semM);
}
if(voieA->occupee == 0 && voieA->reservee == 0 && voieA->M>0){
sem_post(voieA->semM);
}
if(voieB->occupee == 0 && voieB->reservee == 0 && voieB->M>0){
sem_post(voieB->semM);
}
pthread_mutex_unlock (&marchandises);
}
pthread_exit(0);
}
void * fonc_P2(void *num)
{
while(*stop==0){
pthread_mutex_lock (&tunGar);
if(tunnel->occupee ==0 && tunnel->reservee == 0){
if(tunnel->TGV>0){
sem_post(tunnel->semTGV);
}
else if(tunnel->GL>0){
sem_post(tunnel->semGL);
}
else if(tunnel->M>0){
sem_post(tunnel->semM);
}
}
pthread_mutex_unlock (&tunGar);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
unsigned int __VERIFIER_nondet_uint();
static int top = 0;
static unsigned int arr[800];
pthread_mutex_t m;
_Bool flag = 0;
void error(void)
{
ERROR:
__VERIFIER_error();
return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
top == 0 ? 1 : 0;
}
int push(unsigned int *stack, int x)
{
if (top == 800)
{
printf("stack overflow\\n");
return -1;
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (get_top() == 0)
{
printf("stack underflow\\n");
return -2;
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for (i = 0; i < 800; i++)
{
__CPROVER_assume(((800 - i) >= 0) && (i >= 0));
{
__CPROVER_assume(((800 - i) >= 0) && (i >= 0));
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint() % 800;
if (push(arr, tmp) == (-1))
error();
flag = 1;
pthread_mutex_unlock(&m);
}
}
}
}
void *t2(void *arg)
{
int i;
for (i = 0; i < 800; i++)
{
__CPROVER_assume(((800 - i) >= 0) && (i >= 0));
{
pthread_mutex_lock(&m);
if (flag)
{
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>
pthread_mutex_t mutex[2];
pthread_cond_t cond[2];
pthread_mutex_t mutexMain;
pthread_cond_t condMain;
double **matrixA;
double **matrixB;
double **matrixC;
int mA, nA, mB, nB;
int row;
int col;
int valid;
} Job;
Job jobs[2];
double** createMatrix(int m, int n) {
double **matrix;
int i, j;
matrix = calloc(m, sizeof(double*));
for (i = 0; i < m; i++) {
matrix[i] = calloc(n, sizeof(double));
printf("Unesite %d. vrstu matrice:\\n", i);
for (j = 0; j < n; j++)
scanf("%lf", &matrix[i][j]);
}
return matrix;
}
void printMatrix(double **matrix, int m, int n) {
int i, j;
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%4.2lf ", matrix[i][j]);
}
printf("\\n");
}
}
void* thread(void* arg) {
int index = (int)arg;
int i;
double res = 0.0;
Job myJob;
while (1) {
pthread_mutex_lock(&mutex[index]);
while(!jobs[index].valid == 1)
pthread_cond_wait(&cond[index], &mutex[index]);
if (jobs[index].valid == -1)
break;
jobs[index].valid = 0;
pthread_cond_signal(&cond[index]);
myJob = jobs[index];
for (i = 0; i < mA; i++)
res += matrixA[myJob.row][i]*matrixB[i][myJob.col];
matrixC[myJob.row][myJob.col] = res;
pthread_mutex_unlock(&mutex[index]);
}
pthread_exit(0);
return 0;
}
int main(int argc, char* argv[]) {
int i, j, rc, job_counter = 0;
pthread_t threads[2];
pthread_attr_t attribute;
printf("Unesite broj vrsta i kolona prve matrice:\\n");
scanf("%d %d", &mA, &nA);
printf("Unesite broj vrsta i kolona druge matrice:\\n");
scanf("%d %d", &mB, &nB);
if (mA != mB || mA < 1 || mB < 1) {
printf("Greska pri unosu velicine matrica!\\n");
exit(1);
}
matrixA = createMatrix(mA, nA);
printf("MATRICA A:\\n\\n");
printMatrix(matrixA, mA, nA);
printf("\\n");
matrixB = createMatrix(mB, nB);
printf("\\n\\nMATRICA B:\\n\\n");
printMatrix(matrixB, mB, nB);
printf("\\n");
matrixC = calloc(mA, sizeof(double*));
for (i = 0; i < mA; i++)
matrixC[i] = calloc(nB, sizeof(double));
for (i = 0; i < 2; i++) {
pthread_mutex_init(&mutex[i], 0);
pthread_cond_init(&cond[i], 0);
}
pthread_attr_init(&attribute);
pthread_attr_setdetachstate(&attribute, PTHREAD_CREATE_JOINABLE);
for (i = 0; i < 2; i++) {
rc = pthread_create(&threads[i], &attribute, thread, (void*)i);
if (rc) {
printf("GRESKA! Povratni kod iz pthread_create() je: %d", rc);
exit(1);
}
}
job_counter = 0;
for (i = 0; i < mA; i++) {
for (j = 0; j < nB; j++) {
pthread_mutex_lock(&mutex[job_counter]);
jobs[job_counter].row = i;
jobs[job_counter].col = j;
jobs[job_counter].valid = 1;
pthread_cond_signal(&cond[job_counter]);
pthread_cond_wait(&cond[job_counter], &mutex[job_counter]);
pthread_mutex_unlock(&mutex[job_counter]);
job_counter = (job_counter + 1) % 2;
}
}
for (i = 0; i < 2; i++) {
pthread_mutex_lock(&mutex[i]);
jobs[i].row = -1;
jobs[i].col = -1;
jobs[i].valid = -1;
pthread_cond_signal(&cond[i]);
pthread_mutex_unlock(&mutex[i]);
}
printf("\\n\\nMATRICA C:\\n\\n");
printMatrix(matrixC, mA, nB);
pthread_attr_destroy(&attribute);
for (i = 0; i < 2; i++) {
pthread_mutex_destroy(&mutex[i]);
pthread_cond_destroy(&cond[i]);
}
pthread_mutex_destroy(&mutexMain);
pthread_cond_destroy(&condMain);
for (i = 0; i < mA; i++) {
free(matrixA[i]);
free(matrixC[i]);
}
free(matrixA);
free(matrixC);
for(i = 0; i < mB; i++)
free(matrixB[i]);
free(matrixB);
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_mutex_t CS;
void XoInitCS(void)
{
pthread_mutex_init(&CS,0);
}
void XoEnterCS(void)
{
pthread_mutex_lock(&CS);
}
void XoLeaveCS(void)
{
pthread_mutex_unlock(&CS);
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
int element[(400)];
int head;
int tail;
int amount;
} QType;
pthread_mutex_t m;
int __VERIFIER_nondet_int();
int stored_elements[(400)];
_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 == (400))
{
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 == (400))
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == (400))
{
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<(400); 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<(400); 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;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t my_mutex;
int sockfd;
int gcondition=1;
void *writing_process(void *arg){
int i=0;
char buffer[256];
while(1){
bzero(buffer,256);
fprintf(stderr,"%d Please enter the message: ", i++);
fgets(buffer,255,stdin);
pthread_mutex_lock (&my_mutex);
gcondition=0;
pthread_mutex_unlock (&my_mutex);
write_on_socket(buffer, sockfd);
}
pthread_exit (0);
}
void *reading_process(void *arg){
char buffer[256];
int count=0;
int lcondition;
while(1){
lcondition=gcondition;
while(lcondition){
read_from_socket(buffer, sockfd);
count++;
pthread_mutex_trylock (&my_mutex);
lcondition=gcondition;
pthread_mutex_unlock (&my_mutex);
}
fprintf(stderr,"%d Read\\n",count);
count=0;
pthread_mutex_trylock (&my_mutex);
gcondition=1;
pthread_mutex_unlock (&my_mutex);
}
pthread_exit (0);
}
int main(int argc, char *argv[])
{
int portno;
pthread_t th1, th2;
void* ret;
if (argc < 3) {
fprintf(stderr,"usage %s hostname port\\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
pthread_mutex_init (&my_mutex, 0);
open_and_connect(&sockfd, argv[1], portno);
pthread_create( &th1, 0, reading_process, 0);
pthread_create( &th2, 0, writing_process, 0);
pthread_join(th1, &ret);
pthread_join(th2, &ret);
close(sockfd);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t sig_consumer = PTHREAD_COND_INITIALIZER;
pthread_cond_t sig_producer = PTHREAD_COND_INITIALIZER;
int buffer, waiting;
int result[100];
void calculate_result(int task_id)
{
int i, t_result = 0;
for(i = 0; i < 1000 * task_id; i++) {
t_result++;
}
result[task_id] = t_result;
}
void *consumer(void *thread_data)
{
int task;
while(1) {
pthread_mutex_lock(&mutex);
waiting++;
while(buffer == -1) {
pthread_cond_signal(&sig_producer);
pthread_cond_wait(&sig_consumer, &mutex);
}
task = buffer;
buffer = -1;
waiting--;
if(waiting > 0) {
pthread_cond_signal(&sig_producer);
}
pthread_mutex_unlock(&mutex);
if(task == -2) {
return 0;
}
calculate_result(task);
}
}
void *producer(void *thread_data)
{
stopwatch_start();
int *num_threads = (int *) thread_data;
int i, number = 0;
for(i = 0; i < 100; i++) {
pthread_mutex_lock(&mutex);
if((waiting == 0) || (buffer != -1)) {
pthread_cond_wait(&sig_producer, &mutex);
}
buffer = i;
pthread_cond_signal(&sig_consumer);
pthread_mutex_unlock(&mutex);
}
for(i = 1; i < *num_threads; i++) {
pthread_mutex_lock(&mutex);
if((waiting == 0) || (buffer != -1)) {
pthread_cond_wait(&sig_producer, &mutex);
}
buffer = -2;
pthread_cond_signal(&sig_consumer);
pthread_mutex_unlock(&mutex);
}
}
int main(int argc, char **argv)
{
int i, num_threads = 2;
if(argc > 1) {
num_threads = atoi(argv[1]);
if(num_threads < 1) {
fprintf(stderr, "num_threads must be at least 2 for this example");
}
}
num_threads++;
pthread_t *threads = (pthread_t *) malloc(num_threads * sizeof(pthread_t));;
pthread_cond_init(&sig_consumer, 0);
pthread_cond_init(&sig_producer, 0);
pthread_mutex_init(&mutex, 0);
buffer = -1;
waiting = 0;
if(pthread_create(&threads[0], 0, producer, &num_threads)) {
fprintf(stderr, "Error creating thread\\n");
return 1;
}
for(i = 1; i < num_threads; i++) {
if(pthread_create(&threads[i], 0, consumer, 0)) {
fprintf(stderr, "Error creating thread\\n");
return 1;
}
}
for(i = 0; i < num_threads; i++) {
pthread_join(threads[i], 0);
}
pthread_cond_destroy(&sig_consumer);
pthread_cond_destroy(&sig_producer);
pthread_mutex_destroy(&mutex);
printf("All threads exit\\n");
free(threads);
stopwatch_stop();
return 0;
}
| 0
|
#include <pthread.h>
lge_t lock_table[TBLENTRIES];
pthread_mutex_t initializer_lock = PTHREAD_MUTEX_INITIALIZER;
int
page_lock(void *va)
{
int i;
lge_t *lge = &lock_table[PGX(va)];
if(! *lge) {
pthread_mutex_lock(&initializer_lock);
*lge = malloc(sizeof(lue_t) * TBLENTRIES);
memset(*lge, 0, sizeof(lue_t) * TBLENTRIES);
pthread_mutex_unlock(&initializer_lock);
}
lue_t *lue = &(*lge)[PUX(va)];
if(! *lue) {
pthread_mutex_lock(&initializer_lock);
*lue = malloc(sizeof(lme_t) * TBLENTRIES);
memset(*lue, 0, sizeof(lme_t) * TBLENTRIES);
pthread_mutex_unlock(&initializer_lock);
}
lme_t *lme = &(*lue)[PMX(va)];
if(! *lme) {
pthread_mutex_lock(&initializer_lock);
*lme = malloc(sizeof(pthread_mutex_t) * TBLENTRIES);
for(i = 0; i < TBLENTRIES; i++) {
pthread_mutex_init(&(*lme)[i], 0);
}
pthread_mutex_unlock(&initializer_lock);
}
pthread_mutex_t *lock = &(*lme)[PTX(va)];
int r = pthread_mutex_lock(lock);
return r;
}
int
page_unlock(void *va)
{
lge_t *lge = &lock_table[PGX(va)];
if(! *lge) return -E_NO_ENTRY;
lue_t *lue = &(*lge)[PUX(va)];
if(! *lue) return -E_NO_ENTRY;
lme_t *lme = &(*lue)[PMX(va)];
if(! *lme) return -E_NO_ENTRY;
pthread_mutex_t *lock = &(*lme)[PTX(va)];
DEBUG_LOG("unlocking page %p", va);
return pthread_mutex_unlock(lock);
}
| 1
|
#include <pthread.h>
int is_prime(uint64_t p)
{ uint64_t premier = 0;
uint64_t i=2;
while (i<p && premier==0)
{ if (p%i==0)
{ premier=1;
}
i++;
}
return premier;
}
void print_prime_factors(uint64_t n)
{ printf("%lu:", n);
uint64_t i=2;
while (i<=n)
{ if (n%i==0)
{ printf(" %lu", i);
n=n/i;
} else
{ i++;
}
}
printf("\\r\\n");
}
void read_file(const char * fileName)
{
uint64_t number = 1;
FILE *file=fopen(fileName,"r");
if (file != 0)
{
while (fscanf(file,"%lu",&number) != EOF)
{
print_prime_factors(number);
}
} else
{
printf("Impossible d'ouvrir le fichier.");
}
fclose(file);
}
void *lancerLeTravail(void* tmp)
{
uint64_t nombre = *( ( uint64_t* ) tmp );
print_prime_factors(nombre);
pthread_exit(0);
}
void lancerLeTravailQuestion6()
{
pthread_t thread1;
FILE *file=fopen("in.txt","r");
uint64_t nombre1;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
for(;;)
{
pthread_mutex_lock(&mutex);
if(fscanf(file,"%lu",&nombre1) == EOF)
{
break;
}
pthread_create ( &thread1 , 0, &lancerLeTravail, &nombre1);
pthread_mutex_unlock (&mutex);
}
fclose(file);
pthread_mutex_destroy( &mutex );
exit(0);
}
int main ()
{
return 0;
}
| 0
|
#include <pthread.h>
int feed_conn(int fd)
{
char buffer[1024];
int retval;
if ((retval = recv(fd, buffer, 1024, 0)) <= 0)
return retval;
struct http_head request_head;
parser_head(buffer, &request_head, retval);
char head[HEAD_MAX_LEN];
if (request_head.method == GET)
{
int retval;
retval = open(request_head.URL, O_RDONLY);
if (retval < 0)
{
extern int errno;
if (errno == EACCES)
{
gen_http_head(head, 403, 0);
strcat(head, "<h1>403 Forbidden</h1>");
send(fd, head, strlen(head), 0);
}
else
{
gen_http_head(head, 404, 0);
strcat(head, "<h1>404 Not Found</h1>");
send(fd, head, strlen(head), 0);
}
return -1;
}
else
{
extern struct fd_pair *FP;
extern pthread_mutex_t fp_mutex;
pthread_mutex_lock(&fp_mutex);
FP = fd_pair_add(FP, fd, retval);
pthread_mutex_unlock(&fp_mutex);
gen_http_head(head, 200, request_head.URL);
send(fd, head, strlen(head), 0);
return 0;
}
}
else if (request_head.method == HEAD)
{
gen_http_head(head, 200, 0);
send(fd, head, strlen(head), 0);
return 1;
}
else
{
gen_http_head(head, 400, 0);
send(fd, head, strlen(head), 0);
return 1;
}
}
| 1
|
#include <pthread.h>
struct foo* fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo {
int f_count;
pthread_mutex_t f_lock;
struct foo *f_next;
int f_id;
};
struct foo* foo_alloc(void)
{
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->f_next;
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 = (((unsigned long)fp)%29);
pthread_mutex_lock(&hashlock);
for (fp = fh[idx]; fp != 0; fp = fp->f_next) {
if (fp->f_id == id) {
foo_hold(fp);
break;
}
}
pthread_mutex_unlock(&hashlock);
return fp;
}
void foo_release(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);
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t thread_lock;
sem_t thread_count;
int *arr;
struct node
{
int l;
int r;
};
void merge(int low, int high)
{
int mid = (low+high)/2;
int left = low;
int right = mid+1;
int b[high-low+1];
int i, cur = 0;
while(left <= mid && right <= high)
{
if (arr[left] > arr[right])
b[cur++] = arr[right++];
else
b[cur++] = arr[left++];
}
while(left <= mid)
b[cur++] = arr[left++];
while(right <= high)
b[cur++] = arr[right++];
for (i = 0; i < (high-low+1) ; i++)
arr[low+i] = b[i];
}
void* mergeSort(void *a)
{
pthread_t left_thread,right_thread;
struct node *temp=(struct node *)a;
struct node left;
struct node right;
if (temp->l < temp->r)
{
int m = (temp->l+temp->r)/2;
left.l=temp->l;
left.r=m;
right.l=m+1;
right.r=temp->r;
pthread_mutex_lock(&thread_lock);
sem_wait(&thread_count);
sem_wait(&thread_count);
pthread_create(&left_thread,0,mergeSort,&left);
pthread_create(&right_thread,0,mergeSort,&right);
sem_post(&thread_count);
sem_post(&thread_count);
pthread_mutex_unlock(&thread_lock);
pthread_join(left_thread,0);
pthread_join(right_thread,0);
merge(temp->l, temp->r);
}
}
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);
printf("\\n");
}
int main()
{
pthread_mutex_init(&thread_lock,0);
sem_init(&thread_count,0,4);
struct node main;
pthread_t *main_thread;
main_thread=(pthread_t *)malloc(sizeof(pthread_t));
int arr_size,i=0;
int *a;
printf("Enter size of array\\n");
scanf("%d",&arr_size);
a=(int *)malloc(sizeof(int)*arr_size);
printf("Enter elements of array\\n");
for(i=0;i<arr_size;i++)
{
scanf("%d",(a+i));
}
arr=a;
printf("Given array is \\n");
printArray(arr, arr_size);
main.l=0;
main.r=arr_size-1;
pthread_create(&main_thread,0,mergeSort,&main);
pthread_join(main_thread,0);
printf("\\nSorted array is \\n");
printArray(arr, arr_size);
return 0;
}
| 1
|
#include <pthread.h>
int max;
long nbThreads;
int attente;
pthread_cond_t sync_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t sync_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t nbT_mutex = PTHREAD_MUTEX_INITIALIZER;
void* func_ecoute(void* arg) {
pthread_mutex_lock(&nbT_mutex);
nbThreads++;
pthread_mutex_unlock(&nbT_mutex);
int i, nb;
int *param;
int *lvl = (int*) arg;
pthread_t *tid;
nb = (*lvl) + 1;
if (*lvl < max) {
printf("tid : %u L%d cree %d fils\\n", (unsigned int) pthread_self(),
*lvl, nb);
pthread_mutex_lock(&sync_mutex);
while (nb > attente) {
pthread_cond_wait(&sync_cond, &sync_mutex);
}
pthread_mutex_unlock(&sync_mutex);
param = (int*) malloc(sizeof(int));
*param = nb;
tid = calloc(nb, sizeof(pthread_t));
for (i = 0; i < nb; i++) {
pthread_create((tid + i), 0, func_ecoute, param);
}
for (i = 0; i < nb; i++)
pthread_join(tid[i], 0);
}
if (*lvl > 1)
pthread_exit((void*) 0);
return (void*) 0;
}
int main(int argc, char **argv) {
int sig = 0, i = 0;
sigset_t mask;
pthread_t tid;
if (argc != 2) {
printf("syntaxe %s nbThread \\n", argv[0]);
exit(1);
}
max = atoi(argv[1]);
nbThreads = 0;
attente = 0;
sigfillset(&mask);
if (pthread_sigmask(SIG_SETMASK, &mask, 0) != 0) {
perror("pthread_sigmask");
exit(1);
}
if (pthread_create(&tid, 0, func_ecoute, (void*) &i) != 0) {
perror("pthread_create \\n");
exit(1);
}
sigemptyset(&mask);
sigaddset(&mask,SIGINT);
int j;
for (j = 0; j < max; ++j) {
sigwait(&mask, &sig);
pthread_mutex_lock(&sync_mutex);
attente++;
pthread_cond_broadcast(&sync_cond);
pthread_mutex_unlock(&sync_mutex);
}
if (pthread_join(tid, 0) != 0) {
perror("pthread_join");
exit(1);
}
printf("fin LVL nombre totale de threads %ld \\n ",nbThreads);
return 0;
}
| 0
|
#include <pthread.h>
float choix(void* code, int nb_fichiers, float* retour_chef){
if(code == max){
return max_tab(nb_fichiers, retour_chef);
}
if(code == min){
return min_tab(nb_fichiers, retour_chef);
}
if(code == avg){
return avg_tab(nb_fichiers, retour_chef);
}
if(code == sum){
return sum_tab(nb_fichiers, retour_chef);
}
if(code == odd){
return odd_tab(nb_fichiers, retour_chef);
}
else{
printf("probleme de code\\n");
exit(1);
}
}
float processus_directeur(void* fonction, char** noms_fichiers){
int i=0, n;
float retour;
float* retour_chef;
int nb_fichiers = 0;
int proc[20] = {0};
int status;
int tab[2];
pipe(tab);
char buf[1024];
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
retour_chef = malloc(sizeof(float)*20);
while(noms_fichiers[i+2]){
nb_fichiers++;
proc[i] = fork();
if(proc[i] == 0){
retour = chef(fonction, noms_fichiers[i+2]);
pthread_mutex_lock(&m);
close(tab[0]);
sprintf(buf, "%f", retour);
write(tab[1], buf, 1024);
close(tab[1]);
pthread_mutex_unlock(&m);
exit(0);
} else {
waitpid(proc[i], &status, 0);
}
i++;
}
char ret[1024];
close(tab[1]);
i = 0;
while((n = read(tab[0], ret, 1024)) > 0) {
retour_chef[i] = atof(ret);
i++;
}
close(tab[0]);
pthread_mutex_destroy(&m);
float res_final = choix(fonction, nb_fichiers, retour_chef);
free(retour_chef);
return res_final;
}
| 1
|
#include <pthread.h>
int num_chunks = 0;
char *chunks[30000];
int tasks = 0;
int dtasks = 0;
pthread_mutex_t lock;
extern int vm_overload;
void* allocator(void* arg)
{
int i;
(void) arg;
while( 1 ) {
while( vm_overload ) {
sched_yield();
}
pthread_mutex_lock( &lock );
if( num_chunks < 30000 ) {
chunks[num_chunks] = malloc( (4096 * 16) );
if( chunks[num_chunks] ) num_chunks++;
else perror("malloc");
}
if( num_chunks > 0 ) {
for( i=0; i<100; i++ ) {
chunks[ rand() % num_chunks ][ rand() % (4096 * 16) ] += 10;
}
}
tasks++;
pthread_mutex_unlock( &lock );
sched_yield();
}
}
void* deallocator(void* arg)
{
int num;
void *chunk_to_free;
(void) arg;
while( 1 ) {
pthread_mutex_lock( &lock );
if( num_chunks > 0 ) {
num = rand() % num_chunks;
chunk_to_free = chunks[num];
num_chunks--;
chunks[num] = chunks[num_chunks];
free( chunk_to_free );
}
dtasks++;
pthread_mutex_unlock( &lock );
sched_yield();
}
}
int main(int argc, char **argv)
{
int a, d;
if( argc != 3 || (a=atoi(argv[1])) < 0 || (d=atoi(argv[2])) < 0 ) {
fprintf(stderr, "Format: memfiller NUM_ALLOCATORS NUM_DEALLOCATORS\\n");
exit(1);
}
srand(0);
pthread_mutex_init( &lock, 0 );
{
int rv;
pthread_attr_t attr;
pthread_t thread;
int i;
pthread_attr_init( &attr );
rv = pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_DETACHED );
assert (rv == 0);
for( i=0; i<d; i++ ) {
rv = pthread_create(&thread, &attr, &deallocator, 0);
assert (rv == 0);
}
for( i=0; i<a; i++ ) {
rv = pthread_create(&thread, &attr, &allocator, 0);
assert (rv == 0);
}
}
{
unsigned long long then, now=current_usecs();
while( 1 ) {
then = now;
sleep( 1 );
now = current_usecs();
if(now == then) now = then+1;
printf("%3d chunks %5.2f secs %.0f alloc/sec %.0f dealloc/sec vm_overload=%d\\n",
num_chunks, (double)(now-then)/1e6,
(double)tasks*1e6/(now-then), (double)dtasks*1e6/(now-then),
vm_overload
);
tasks = 0;
dtasks = 0;
}
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex, mutex2;
pthread_cond_t conditions[5];
int sum = 0;
void* thread(void *arg) {
int thread_id = (int)arg;
int local_num;
pthread_mutex_lock(&mutex);
pthread_cond_wait(&conditions[thread_id], &mutex);
pthread_mutex_unlock(&mutex);
printf("Zdravo, ja sam nit broj: %d\\nUnesite jedan ceo broj:\\n", thread_id);
scanf("%d", &local_num);
sum += local_num;
if(thread_id == 5 -1) {
pthread_cond_signal(&conditions[0]);
} else {
pthread_cond_signal(&conditions[thread_id+1]);
}
pthread_exit(0);
return 0;
}
int main(int argc, char *argv[]) {
int i, rc, num;
pthread_t threads[5];
pthread_attr_t attribute;
pthread_mutex_init(&mutex, 0);
pthread_mutex_init(&mutex2, 0);
for (i = 0; i < 5; i++)
pthread_cond_init(&conditions[i], 0);
pthread_attr_init(&attribute);
pthread_attr_setdetachstate(&attribute, PTHREAD_CREATE_JOINABLE);
for (i = 1; i < 5; i++) {
rc = pthread_create(&threads[i-1], &attribute, thread, (void *)i);
if (rc) {
printf("GRESKA! Povratni kod iz pthread_create() je: %d", rc);
exit(1);
}
}
printf("Zdravo, ja sam glavna nit.\\nUnesite jedan ceo broj:\\n");
scanf("%d", &num);
sum += num;
pthread_cond_signal(&conditions[1]);
pthread_mutex_lock(&mutex2);
pthread_cond_wait(&conditions[0], &mutex2);
pthread_mutex_unlock(&mutex2);
printf("Zbir svih brojeva je: %d\\n", sum);
pthread_mutex_destroy(&mutex);
for (i = 0; i < 5; i++)
pthread_cond_destroy(&conditions[i]);
pthread_attr_destroy(&attribute);
return 0;
}
| 1
|
#include <pthread.h>
int thread_flag;
pthread_cond_t thread_flag_cv;
pthread_mutex_t thread_flag_mutex;
int value;
void initialize_flag()
{
pthread_mutex_init(&thread_flag_mutex, 0);
pthread_cond_init(&thread_flag_cv, 0);
thread_flag = 0;
}
void do_work()
{
value++;
printf("+1: %d\\n", value);
sleep(1);
}
void* thread_function(void* thread_arg) {
while (1) {
pthread_mutex_lock(&thread_flag_mutex);
while(!thread_flag)
{
value--;
printf("-1: %d\\n", value);
pthread_cond_wait(&thread_flag_cv, &thread_flag_mutex);
}
pthread_mutex_unlock(&thread_flag_mutex);
do_work();
}
return 0;
}
void set_thread_flag(int flag_value) {
pthread_mutex_lock(&thread_flag_mutex);
thread_flag = flag_value;
pthread_cond_signal(&thread_flag_cv);
pthread_mutex_unlock(&thread_flag_mutex);
}
int main(int argc, char* argv[])
{
pthread_t thread;
int status;
initialize_flag();
status=pthread_create(&thread, 0, &thread_function, 0);
if(!status)
{
printf("Success\\n");
}
while(1)
{
value=value*2;
printf("x2: %d\\n", value);
thread_flag=rand()%2;
pthread_cond_broadcast(&thread_flag_cv);
sleep(1);
}
status=pthread_join(thread, 0);
if (!status)
{
printf("joined");
}
return 0;
}
| 0
|
#include <pthread.h>
int total_produced = 0;
void *produce(void *);
void *consume(void *);
int tmp[5];
int main(int argc, char* argv[]){
pthread_t thread1[5];
pthread_t thread2;
int i, j;
for (j=0; j<5; j++) {
tmp[j] = j;
if ((i=pthread_create(&thread1[j], 0, produce, (void*)&tmp[j])) != 0) {
printf("thread creation failed. %d\\n", j);
}
}
if ((i=pthread_create(&thread2, 0, consume, (void*)0)) != 0) {
printf("thread creation failed. %d\\n", i);
}
pthread_join(thread1[0], 0);
pthread_join(thread1[1], 0);
pthread_join(thread1[2], 0);
pthread_join(thread1[3], 0);
pthread_join(thread1[4], 0);
pthread_join(thread2, 0);
printf("Exiting main, total number of products %d\\n", total_produced);
return 0;
}
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
void *produce(void *arg){
int i;
int me;
me = *(int *)arg;
for(i=0;i<1000000;i++){
pthread_mutex_lock(&mutex);
total_produced++;
pthread_mutex_unlock(&mutex);
}
return 0;
}
void *consume(void *arg){
int i;
for(i=0;i<10;i++){
}
return 0;
}
| 1
|
#include <pthread.h>
buffer_item buffer[5];
void initializeBuffer();
void *producer(void *param);
void *consumer(void *param);
int insert_item(buffer_item item);
int remove_item(buffer_item *item);
void sig_handler(int);
pthread_mutex_t mutex;
int counter, first, last;
int flag = 0;
sem_t empty, full;
int main(int argc, char *argv[])
{
int i;
if(argc != 4)
{
fprintf(stderr, "USAGE:./proj4 <INT> <INT> <INT>\\n");
}
int sleeptime = atoi(argv[1]);
int numProd = atoi(argv[2]);
int numCons = atoi(argv[3]);
initializeBuffer();
pthread_t p_tid[numProd];
pthread_attr_t p_attr[numProd];
for (i = 0; i < numProd-1; i++)
{
pthread_attr_init(&p_attr[i] );
pthread_create( &p_tid[i], &p_attr[i], producer, 0 );
}
pthread_t c_tid[numCons];
pthread_attr_t c_attr[numCons];
for (i = 0; i < numCons-1; i++)
{
pthread_attr_init( &c_attr[i] );
pthread_create( &c_tid[i], &c_attr[i], consumer, 0 );
}
for (i = 0; i < numProd; i++)
pthread_join(p_tid[i], 0);
for (i = 0; i < numCons; i++)
pthread_join(c_tid[i], 0);
sleep(sleeptime);
printf("Exit the program\\n");
exit(0);
}
void initializeBuffer()
{
sem_init(&empty, 0, 5);
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex, 0);
counter = 0;
first = 0;
last = 0;
}
void *producer(void *param)
{
buffer_item item;
do
{
signal(SIGINT, sig_handler);
sleep((rand() % 10) + 1);
item = rand();
sem_wait(&empty);
pthread_mutex_lock(&mutex);
if(insert_item(item))
fprintf(stderr, "Producer Error!\\n");
else
{
printf("producer produced %d\\n", item);
}
pthread_mutex_unlock(&mutex);
sem_post(&full);
if(flag == 1)
break;
} while(1);
}
void *consumer(void *param)
{
buffer_item item;
do
{
signal(SIGINT, sig_handler);
sleep((rand() % 10) + 1);
sem_wait(&full);
pthread_mutex_lock(&mutex);
if(remove_item(&item))
fprintf(stderr, "Consumer Error!\\n");
else
printf("consumer consumed %d\\n", item);
pthread_mutex_unlock(&mutex);
sem_post(&empty);
if(flag == 1)
break;
} while(1);
}
int insert_item(buffer_item item)
{
if(counter < 5)
{
buffer[last] = item;
last = (last + 1) % 5;
counter++;
return 0;
}
else
{
printf("\\nError: The buffer is full.");
return -1;
}
}
int remove_item(buffer_item *item)
{
if(counter > 0)
{
*item = buffer[first];
first = (first + 1) % 5;
counter--;
return 0;
}
else
{
printf("Error: The buffer is empty.");
return -1;
}
}
void sig_handler(int sig)
{
if(sig == SIGINT)
{
printf("\\nReceived SIGINT.\\nKilling threads...\\n");
sleep(2);
flag = 1;
}
}
| 0
|
#include <pthread.h>
char *resurs;
pthread_mutex_t mutex;
int max;
}resurs_t;
resurs_t res;
int goodbye;
void *tr_consol (void *n) {
static int y = 0;
int ii = 0;
int one = 0;
int zero = 0;
while (!goodbye) {
pthread_mutex_lock (&res.mutex);
for (ii=0; ii<res.max; ii++) {
if (res.resurs[ii] == 1) one++;
if (res.resurs[ii] == 0) zero++;
}
printf ("Summ \\"1\\" = %d\\n", one);
printf ("Summ \\"0\\" = %d\\n", zero);
y++; zero = 0; one = 0;
if (res.max == y) y = 0;
pthread_mutex_unlock (&res.mutex);
sleep (1);
}
}
void sigfunc (int sig) {
if (sig != SIGINT ) return ;
else goodbye = 1;
}
int main () {
int shmid;
char *shm;
int SHMSZ = 0;
key_t key = 5678;
pthread_t *consol_tid;
res.max = 10;
if ( ( shmid = shmget (key, res.max, 0666) ) <0) {
printf ("Error shared memory\\n");
exit(1);
}
if (( shm = shmat(shmid, 0, 0) ) == (char*)-1) {
printf ("Error get shared memory\\n");
exit (0);
}
res.resurs = shm;
consol_tid = (pthread_t*) calloc (1 , sizeof (pthread_t));
if (consol_tid == 0){ printf ("res.mutex is wrong\\n"); return 0; }
signal (SIGINT, sigfunc);
int status = pthread_create( consol_tid, 0, tr_consol, (void*) res.resurs);
if( status != 0 ) perror( "pthread_create" ), exit( 1 );
status = pthread_join (*consol_tid, 0 );
free (consol_tid);
printf ("\\nEnd prog mon\\n");
return 0;
}
| 1
|
#include <pthread.h>
struct async_buffer {
pthread_cond_t cond;
pthread_mutex_t mtx;
void *buffer;
size_t buffer_read_index;
size_t buffer_write_index;
size_t buffer_size;
size_t buffer_room_left;
int flags;
};
struct async_buffer *
async_buffer_new(size_t s, int flags) {
struct async_buffer *b = memory_alloc(sizeof *b);
b->buffer = memory_alloc(s);
b->buffer_read_index = 0;
b->buffer_write_index = 0;
b->buffer_size = s;
b->buffer_room_left = s;
b->flags = flags;
pthread_cond_init(&b->cond, 0);
pthread_mutex_init(&b->mtx, 0);
return b;
}
void
async_buffer_delete(struct async_buffer *b) {
pthread_cond_destroy(&b->cond);
pthread_mutex_destroy(&b->mtx);
memory_free(b->buffer);
memory_free(b);
}
ssize_t
async_buffer_read(struct async_buffer *b, void *buf, size_t s) {
size_t avail;
size_t first_chunk_size;
if (s > b->buffer_size)
return -1;
pthread_mutex_lock(&b->mtx);
while (avail = b->buffer_size - b->buffer_room_left, avail < s) {
if (b->flags & ASYNC_BUFFER_READER_CAN_WAIT)
pthread_cond_wait(&b->cond, &b->mtx);
else {
pthread_mutex_unlock(&b->mtx);
return -1;
}
}
first_chunk_size = b->buffer_size - b->buffer_read_index >= s?
s : b->buffer_size - b->buffer_read_index;
memcpy(buf, b->buffer + b->buffer_read_index, first_chunk_size);
memcpy(buf + first_chunk_size, b->buffer, s - first_chunk_size);
b->buffer_room_left += s;
b->buffer_read_index = (b->buffer_read_index + s) % b->buffer_size;
pthread_mutex_unlock(&b->mtx);
if (s != 0)
pthread_cond_signal(&b->cond);
return s;
}
ssize_t
async_buffer_write(struct async_buffer *b, void *buf, size_t s) {
size_t avail;
size_t first_chunk_size;
if (s > b->buffer_size)
return -1;
pthread_mutex_lock(&b->mtx);
while (b->buffer_room_left < s) {
if (b->flags & ASYNC_BUFFER_WRITER_CAN_WAIT)
pthread_cond_wait(&b->cond, &b->mtx);
else {
pthread_mutex_unlock(&b->mtx);
return -1;
}
}
first_chunk_size = b->buffer_size - b->buffer_write_index >= s?
s : b->buffer_size - b->buffer_write_index;
memcpy(b->buffer + b->buffer_write_index, buf, first_chunk_size);
memcpy(b->buffer, buf + first_chunk_size, s - first_chunk_size);
b->buffer_room_left -= s;
b->buffer_write_index = (b->buffer_write_index + s) % b->buffer_size;
pthread_mutex_unlock(&b->mtx);
if (s != 0)
pthread_cond_signal(&b->cond);
return s;
}
void
async_buffer_empty(struct async_buffer *b) {
pthread_mutex_lock(&b->mtx);
b->buffer_read_index = 0;
b->buffer_write_index = 0;
b->buffer_room_left = b->buffer_size;
pthread_mutex_unlock(&b->mtx);
}
| 0
|
#include <pthread.h>
int sum;
int cpt=0;
int print_flag=0, fin_flag=0;
pthread_mutex_t mutex, mutex_fin;
pthread_cond_t cond_print, cond_fin;
void * thread_rand(void * i){
int random_val = (int) (10*((double)rand())/ 32767);
printf("tid: %u;\\trandom_val: %d\\n",(unsigned int)pthread_self(), random_val);
pthread_mutex_lock(&mutex);
sum += random_val;
cpt++;
if(cpt==15){
print_flag=1;
pthread_cond_signal(&cond_print);
}
pthread_mutex_unlock(&mutex);
return 0;
}
void * print_thread(void * arg){
pthread_mutex_lock(&mutex);
while(!print_flag){
pthread_cond_wait(&cond_print,&mutex);
}
printf("Somme : %d\\n",sum);
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&mutex_fin);
fin_flag=1;
pthread_cond_signal(&cond_fin);
pthread_mutex_unlock(&mutex_fin);
return 0;
}
int main(){
int i;
pthread_t t[15 +1];
pthread_mutex_init(&mutex, 0);
pthread_mutex_init(&mutex_fin, 0);
pthread_cond_init(&cond_print,0);
pthread_cond_init(&cond_fin,0);
sum = 0;
srand(time(0));
if((pthread_create(&(t[15]),0,print_thread,0) != 0) || (pthread_detach(t[15]) != 0)){
fprintf(stderr, "pthread creation or detach failed.\\n");
return 1;
}
for(i=0;i<15;i++){
if((pthread_create(&(t[i]),0,thread_rand,0) != 0) || (pthread_detach(t[i]) != 0)){
fprintf(stderr, "pthread creation or detach failed.\\n");
return 1;
}
}
pthread_mutex_lock(&mutex_fin);
while(!fin_flag){
pthread_cond_wait(&cond_fin,&mutex_fin);
}
pthread_mutex_unlock(&mutex_fin);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t thereAreOxygen, thereAreHydrogen;
pthread_t oxygen, hydrogen[2];
int numberOxygen = 0 , numberHydrogen=0;
int activeOxygen = 0 , activeHydrogen=0;
int currentOxygen = 0 , currentHydrogen=0;
void dataIn(){
int var=0;
if(numberHydrogen==1){
while (var<=0) {
printf("Queda 1 atomo de hidrogeno, ingrese atomos de hidrogeno: ", numberHydrogen );
scanf("%d",&var);
}
numberHydrogen+=var;
}
var=0;
if(numberOxygen==0 && numberHydrogen>0){
while (var<=0) {
printf("Hay %d atomo(s) de hidrogeno, ingrese atomos de oxigeno: ", numberHydrogen );
scanf("%d",&var); }
numberOxygen+=var;
}
var=0;
if(numberHydrogen==0 && numberOxygen>0){
while (var<=0) {
printf("Hay %d atomo(s) de oxigeno, ingrese atomos de hidrogeno: ", numberOxygen );
scanf("%d",&var);}
numberHydrogen+=var;
}
}
void startHydrogen(){
pthread_mutex_lock(&lock);
++activeHydrogen;
while (activeOxygen<1) {
pthread_cond_wait(&thereAreHydrogen, &lock);
}
--numberHydrogen;
pthread_mutex_unlock(&lock);
}
void startOxygen(){
pthread_mutex_lock(&lock);
++activeOxygen;
while (activeHydrogen<2) {
pthread_cond_wait(&thereAreOxygen, &lock);
}
--numberOxygen;
pthread_mutex_unlock(&lock);
}
void doneOxygen() {
pthread_mutex_lock(&lock);
printf("Signaling hydrogen in broadcast...\\n");
dataIn();
pthread_cond_broadcast(&thereAreHydrogen);
--activeOxygen;
++currentOxygen;
pthread_mutex_unlock(&lock);
}
void doneHydrogen() {
pthread_mutex_lock(&lock);
printf("Signaling oxygen ...\\n");
dataIn();
pthread_cond_signal(&thereAreOxygen);
--activeHydrogen;
++currentHydrogen;
pthread_mutex_unlock(&lock);
}
void *Oxigeno(void *id) {
long tid = (long)id;
printf("oxigeno[%ld] preparado para ser H2O \\n", tid);
startOxygen();
printf("oxigeno[%ld] convirtiendose \\n");
sleep(rand()%5);
printf("oxigeno[%ld] es H2O \\n", tid);
doneOxygen();
sleep(rand()%5);
pthread_exit(0);
}
void *Hidrogeno(void *id) {
long tid = (long)id;
printf("hidrogeno(%ld) preparado\\n", tid);
startHydrogen();
printf("hidrogeno(%ld) convirtiendose\\n", tid);
sleep(rand()%5);
printf("hidrogeno(%ld) es h2O\\n", tid);
doneHydrogen();
sleep(rand()%5);
pthread_exit(0);
}
int main(int argc, char *argv[]) {
while (numberOxygen<=0) {
printf("Ingrese atomos de oxigeno:");
scanf("%d",&numberOxygen);
}
while (numberHydrogen<=0) {
printf("Ingrese atomos de hidrogeno:");
scanf("%d",&numberHydrogen);
}
long i=0;
srand(time(0));
printf("main(): creando threads hidrogeno\\n");
for (i=0; i<2; i++) {
if (pthread_create(&hydrogen[i], 0, Hidrogeno, (void *)i)) {
printf("Error creando thread hidrogeno[%ld]\\n", i);
exit(1);
}
}
i=0;
printf("main(): creando thread Oxigeno\\n");
if (pthread_create(&oxygen, 0,Oxigeno, (void *)i)) {
printf("Error creando thread oxigeno[%ld]\\n", i);
exit(1);
}
void *status;
for (i=0; i<2; i++)
{
pthread_join(hydrogen[i],&status);
}
pthread_join(oxygen,&status);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int count = 0;
int thread_ids[3] = {0,1,2};
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
static void *inc_count(void *t)
{
int i;
long my_id = (long)t;
for (i=0; i<10; i++) {
pthread_mutex_lock(&count_mutex);
count++;
if (count == 12) {
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);
}
static void *watch_count(void *t)
{
long my_id = (long)t;
printf("Starting watch_count(): thread %ld\\n", my_id);
pthread_mutex_lock(&count_mutex);
while (count<12) {
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %ld Condition signal received.\\n", my_id);
count += 125;
printf("watch_count(): thread %ld count now = %d.\\n", my_id, count);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int alder_thread_worker()
{
int i;
long t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, watch_count, (void *)t1);
pthread_create(&threads[1], &attr, inc_count, (void *)t2);
pthread_create(&threads[2], &attr, inc_count, (void *)t3);
for (i=0; i<3; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited on %d threads. Done.\\n", 3);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
return 0;
}
| 1
|
#include <pthread.h>
static pid_t tids[128];
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
int tlocker_acquire() {
int i;
int rem = -1;
pid_t ctid = syscall(SYS_gettid);
;
pthread_mutex_lock(&mtx);
for (i = 0; i < 128; i++ ){
if (rem == -1 && tids[i] == 0) {
rem = i;
}
if (tids[i] == ctid) {
;
pthread_mutex_unlock(&mtx);
return 0;
}
}
assert(rem != -1);
if (i == 128) {
;
tids[rem] = ctid;
pthread_mutex_unlock(&mtx);
return 1;
}
pthread_mutex_unlock(&mtx);
printf("LOCK FAILED for %d\\n", ctid);
abort();
return -1;
}
void tlocker_release() {
int i;
pid_t ctid = syscall(SYS_gettid);
pthread_mutex_lock(&mtx);
for (i = 0; i < 128; i++) {
if(tids[i] == ctid) {
tids[i] = 0;
;
pthread_mutex_unlock(&mtx);
return;
}
}
pthread_mutex_unlock(&mtx);
;
assert(i == 128);
}
| 0
|
#include <pthread.h>
struct to_info {
void *(*fn)(void *);
void *to_arg;
int to_wait;
};
void *timer_helper(void *arg) {
struct to_info *tip;
tip = (struct to_info *)arg;
printf("sleep for %d secs\\n", tip -> to_wait);
sleep(tip -> to_wait);
(tip -> fn)(tip -> to_arg);
free(arg);
return (void *)0;
}
void timeout(const int when, void *(*fn)(void *), void *arg) {
struct to_info *tip;
tip = (struct to_info *)malloc(sizeof(struct to_info));
if (tip != 0) {
tip -> to_wait = when;
tip -> fn = fn;
tip -> to_arg = arg;
pthread_t tid;
int err = makethread(timer_helper, (void *)tip, &tid);
if (err != 0) {
fprintf(stderr, "makethread error: %s\\n", strerror(err));
free(tip);
exit(-1);
}
}
}
pthread_mutex_t lock;
pthread_mutexattr_t attr;
static volatile int flag = 0;
void *retry(void *arg) {
pthread_mutex_lock(&lock);
printf("Recursive lock\\n");
flag = 1;
pthread_mutex_unlock(&lock);
return (void *)0;
}
int main(void) {
int err;
err = pthread_mutexattr_init(&attr);
if (err != 0) {
fprintf(stderr, "pthread_mutexattr_init error: %s\\n", strerror(err));
exit(-1);
}
err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
if (err != 0) {
fprintf(stderr, "pthread_mutexattr_settype error: %s\\n", strerror(err));
exit(-1);
}
err = pthread_mutex_init(&lock, &attr);
if (err != 0) {
fprintf(stderr, "pthread_mutex_init error: %s\\n", strerror(err));
exit(-1);
}
pthread_mutex_lock(&lock);
timeout(4, retry, 0);
pthread_mutex_unlock(&lock);
while (!flag)
;
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int value = 0;
void* thread(void* arg) {
int id = (int)arg;
char run = 1;
while (run) {
pthread_mutex_lock(&mut);
pthread_cond_wait(&cond, &mut);
if (value < 0)
run = 0;
pthread_mutex_unlock(&mut);
}
}
int main() {
char command[256];
char c;
pthread_t id;
int i;
int n = 5;
for (i=0; i < n; i++)
if (pthread_create(&id, 0, thread, (void*)(i+1)))
perror("thread create");
while (value >= 0) {
gets(command);
if (strlen(command) == 0)
continue;
switch (command[0]) {
case 's':
case 'S':
value = strtol(command+1, 0, 0);
printf("values = %d\\n", value);
pthread_cond_signal(&cond);
break;
case 'b':
case 'B':
value = strtol(command+1, 0, 0);
printf("values = %d\\n", value);
pthread_cond_broadcast(&cond);
break;
case 'q':
case 'Q':
value = -1;
pthread_cond_broadcast(&cond);
break;
}
}
}
| 0
|
#include <pthread.h>
int c[10];
pthread_mutex_t global_mutex;
pthread_mutex_t local_mutex[10];
pthread_cond_t nains;
unsigned int num_nains = 0;
void enter_critical_local(int i, int j){
pthread_mutex_lock (&local_mutex[(i<j)?i:j]);
pthread_mutex_lock (&local_mutex[(i<j)?j:i]);
pthread_mutex_lock (&global_mutex);
num_nains++;
pthread_mutex_unlock (&global_mutex);
}
void exit_critical_local(int i, int j){
pthread_mutex_lock (&global_mutex);
num_nains--;
pthread_mutex_unlock (&global_mutex);
if (num_nains <= 0) {
pthread_cond_broadcast(&nains) ;
}
pthread_mutex_unlock (&local_mutex[i]);
pthread_mutex_unlock (&local_mutex[j]);
}
void enter_critical_global(){
pthread_mutex_lock (&global_mutex);
while ( num_nains > 0 ) {
pthread_cond_wait (&nains , &global_mutex);
}
}
void exit_critical_global(){
pthread_mutex_unlock (&global_mutex);
}
void init_mutexes() {
pthread_mutex_init (&global_mutex, 0);
int j;
for(j=0;j<10;j++) pthread_mutex_init (&local_mutex[j], 0);
pthread_cond_init(&nains, 0);
}
void destroy_mutexes() {
pthread_mutex_destroy (&global_mutex);
int j;
for(j=0;j<10;j++) pthread_mutex_destroy (&local_mutex[j]);
pthread_cond_destroy(&nains);
}
int randpos() {
return (rand() % 10);
}
void local_change(int i, int j){
c[i]++;
c[j]--;
}
void global_change() {
int i;
int fst;
fst = c[0];
for(i=0;i<10;i++) c[i] = c[i+1];
c[10 -1] = fst;
}
void *threadfun_local(void *arg) {
int tid = * (int *) arg;
printf("Debut thread local %d\\n",tid);
int n;
for(n=0;n<10000;n++){
int i = randpos();
int j = randpos();
if (i!=j) {
enter_critical_local(i,j);
local_change(i,j);
exit_critical_local(i,j);
}
}
printf("Fin thread local %d\\n",tid);
return 0;
}
void *threadfun_global(void *arg) {
int n;
int tid = * (int *) arg;
printf("Debut thread global %d\\n",tid);
for(n=0;n<1000;n++){
enter_critical_global();
global_change();
exit_critical_global();
}
printf("Fin thread global %d\\n",tid);
return 0;
}
int tid[5 +2];
int main(int argc, char **argv){
pthread_t local[5];
pthread_t global[2];
srand(time(0));
int i;
for(i=0; i<10; i++) c[i] = 0;
for(i=0; i<5 +2; i++) tid[i] = i;
init_mutexes();
for(i=0; i<5; i++)
pthread_create(&local[i],0,threadfun_local,&tid[i]);
for(i=0; i<2; i++)
pthread_create(&global[i],0,threadfun_global,&tid[i]);
for(i=0; i<5; i++) pthread_join(local[i],0);
for(i=0; i<2; i++) pthread_join(global[i],0);
destroy_mutexes();
int sum = 0;
for(i=0; i<10; i++) {
sum += c[i];
printf("c[%d] = %d\\n",i,c[i]);
}
if (sum == 0) printf("correct\\n"); else printf("incorrect\\n");
printf("Fin main.\\n");
}
| 1
|
#include <pthread.h>
static void *process_function(void *);
static void process_function_actual(int job_type);
static int process_judege(struct Job *job);
static char current_dictionary[100];
extern void save_environment_init(){
time_t nowtime;
memset(current_dictionary,0,sizeof(current_dictionary));
time(&nowtime);
sprintf(current_dictionary,"%s/%s/",configuration.save_environment_path,asctime(gmtime(&nowtime)));
int i;
i=0;
while(current_dictionary[i]){
if(current_dictionary[i]=='\\r' || current_dictionary[i]=='\\n')
current_dictionary[i]=' ';
i++;
}
syslog(project_params.syslog_level,"current save path is %s\\n",current_dictionary);
create_dirctionary(current_dictionary);
register_job(JOB_TYPE_SAVE_ENVIRONMENT,process_function,process_judege,CALL_BY_TCP_DATA_MANAGE);
}
static void *process_function(void *arg){
int job_type = JOB_TYPE_SAVE_ENVIRONMENT;
while(1){
pthread_mutex_lock(&(job_mutex_for_cond[job_type]));
pthread_cond_wait(&(job_cond[job_type]),&(job_mutex_for_cond[job_type]));
pthread_mutex_unlock(&(job_mutex_for_cond[job_type]));
process_function_actual(job_type);
}
}
static void process_function_actual(int job_type){
struct Job_Queue private_jobs;
private_jobs.front = 0;
private_jobs.rear = 0;
get_jobs(job_type,&private_jobs);
struct Job current_job;
struct tcp_stream *a_tcp;
char tcp_information_dir[100];
char server[100],client[100],promisc[100];
while(!jobqueue_isEmpty(&private_jobs)){
jobqueue_delete(&private_jobs,¤t_job);
memset(tcp_information_dir,0,sizeof(tcp_information_dir));
sprintf(tcp_information_dir,"%s/%hu_%hu_%u_%u_%d/",current_dictionary,current_job.ip_and_port.dest,
current_job.ip_and_port.source,current_job.ip_and_port.daddr,
current_job.ip_and_port.saddr,current_job.hash_index);
create_dirctionary(tcp_information_dir);
if(current_job.server_rev != 0 && current_job.server_rev->head != 0 && current_job.server_rev->head->data != 0){
memset(server,0,100*sizeof(char));
sprintf(server,"%s/log_server",tcp_information_dir);
write_data_to_file(server,current_job.server_rev->head->data, current_job.server_rev->head->length);
}
if(current_job.client_rev != 0 && current_job.client_rev->head != 0 && current_job.client_rev->head->data != 0){
memset(client,0,100*sizeof(char));
sprintf(client,"%s/log_client",tcp_information_dir);
write_data_to_file(client,current_job.client_rev->head->data, current_job.client_rev->head->length);
}
if(current_job.promisc != 0 && current_job.promisc->head != 0 && current_job.promisc->head->data != 0){
memset(promisc,0,100*sizeof(char));
sprintf(promisc,"%s/log_promisc",tcp_information_dir);
write_data_to_file(promisc,current_job.promisc->head->data, current_job.promisc->head->length);
}
if(current_job.server_rev!=0){
wireless_list_free(current_job.server_rev);
free(current_job.server_rev);
}
if(current_job.client_rev !=0){
wireless_list_free(current_job.client_rev);
free(current_job.client_rev);
}
if(current_job.promisc != 0){
wireless_list_free(current_job.promisc);
free(current_job.promisc);
}
}
}
static int process_judege(struct Job *job){
job->desport = 0;
job->data_need = 4;
return 1;
}
| 0
|
#include <pthread.h>
void *customerMaker();
void *barberShop();
void *waitingRoom();
void checkQueue();
pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t wait_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t sleep_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t barberSleep_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t barberWorking_cond = PTHREAD_COND_INITIALIZER;
int returnTime=5,current=0, sleeping=0, iseed;
int main(int argc, char *argv[])
{
iseed=time(0);
srand(iseed);
pthread_t barber,customerM,timer_thread;
pthread_attr_t barberAttr, timerAttr;
pthread_attr_t customerMAttr;
pthread_attr_init(&timerAttr);
pthread_attr_init(&barberAttr);
pthread_attr_init(&customerMAttr);
printf("\\n");
pthread_create(&customerM,&customerMAttr,customerMaker,0);
pthread_create(&barber,&barberAttr,barberShop,0);
pthread_join(barber,0);
pthread_join(customerM,0);
return 0;
}
void *customerMaker()
{
int i=0;
printf("*Customer Maker Created*\\n\\n");
fflush(stdout);
pthread_t customer[6 +1];
pthread_attr_t customerAttr[6 +1];
while(i<(6 +1))
{
i++;
pthread_attr_init(&customerAttr[i]);
while(rand()%2!=1)
{
sleep(1);
}
pthread_create(&customer[i],&customerAttr[i],waitingRoom,0);
}
pthread_exit(0);
}
void *waitingRoom()
{
pthread_mutex_lock(&queue_mutex);
checkQueue();
sleep(returnTime);
waitingRoom();
}
void *barberShop()
{
int loop=0;
printf("The barber has opened the store.\\n");
fflush(stdout);
while(loop==0)
{
if(current==0)
{
printf("\\tThe shop is empty, barber is sleeping.\\n");
fflush(stdout);
pthread_mutex_lock(&sleep_mutex);
sleeping=1;
pthread_cond_wait(&barberSleep_cond,&sleep_mutex);
sleeping=0;
pthread_mutex_unlock(&sleep_mutex);
printf("\\t\\t\\t\\tBarber wakes up.\\n");
fflush(stdout);
}
else
{
printf("\\t\\t\\tBarber begins cutting hair.\\n");
fflush(stdout);
sleep((rand()%20)/5);
current--;
printf("\\t\\t\\t\\tHair cut complete, customer leaving store.\\n");
pthread_cond_signal(&barberWorking_cond);
}
}
pthread_exit(0);
}
void checkQueue()
{
current++;
printf("\\tCustomer has arrived in the waiting room.\\t\\t\\t\\t\\t\\t\\t%d Customers in store.\\n",current);
fflush(stdout);
printf("\\t\\tCustomer checking chairs.\\n");
fflush(stdout);
if(current<6)
{
if(sleeping==1)
{
printf("\\t\\t\\tBarber is sleeping, customer wakes him.\\n");
fflush(stdout);
pthread_cond_signal(&barberSleep_cond);
}
printf("\\t\\tCustomer takes a seat.\\n");
fflush(stdout);
pthread_mutex_unlock(&queue_mutex);
pthread_mutex_lock(&wait_mutex);
pthread_cond_wait(&barberWorking_cond,&wait_mutex);
pthread_mutex_unlock(&wait_mutex);
return;
}
if(current>=6)
{
printf("\\t\\tAll chairs full, leaving store.\\n");
fflush(stdout);
current--;
pthread_mutex_unlock(&queue_mutex);
return;
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_t threads[MAX_THREADS];
struct timespec start_ts[MAX_THREADS];
struct timespec end_ts[MAX_THREADS];
int request_serviced[MAX_THREADS];
int n_threads = DEFAULT_N_THREADS;
int job_size = DEFAULT_JOB_SIZE;
int n_jobs = (DEFAULT_N_THREADS*DEFAULT_JOBS_PER_THREAD);
int block_size = DEFAULT_BLOCK_SIZE;
char target_dir[PATH_LENGTH];
char *block;
int rw = RW_UNSET;
int quiet = 0;
int next_job = 0;
int base_jobsn = DEFAULT_BASE_JOBSN;
int open_ext_flags = 0;
void *worker(void *arg)
{
long tid = (long)arg;
int job_id = -1;
char name[32];
int rval;
int err;
int file_jobsn;
while (1) {
pthread_mutex_lock(&mutex);
job_id = next_job;
if (next_job < n_jobs) {
next_job = next_job + 1;
}
pthread_mutex_unlock(&mutex);
if (job_id >= n_jobs) {
break;
}
if (request_serviced[tid] == 0) {
clock_gettime(CLOCK_REALTIME, &start_ts[tid]);
}
file_jobsn = job_id + base_jobsn;
bucket_path(name, n_jobs, file_jobsn);
rval = unlink(name);
if (0 != rval) {
err = errno;
if (err != ENOENT) {
fprintf(stderr, "ERR unlink(%s): %s\\n", name, strerror(err));
}
} else {
request_serviced[tid]++;
}
}
clock_gettime(CLOCK_REALTIME, &end_ts[tid]);
if (request_serviced[tid] == 0) {
memcpy(&start_ts[tid], &end_ts[tid], sizeof(struct timespec));
}
pthread_exit(0);
}
void process_arg(int argc, char *argv[])
{
int opt;
while ((opt = getopt(argc, argv, "n:t:s:k:q")) != -1) {
switch (opt) {
case 'n':
n_threads = atoi(optarg);
if (n_threads < 0 || n_threads > MAX_THREADS) {
printf("Too many threads.\\n");
exit(1);
}
break;
case 't':
strncpy(target_dir, optarg, PATH_LENGTH-1);
break;
case 's':
n_jobs = atoi(optarg);
break;
case 'k':
base_jobsn = atoi(optarg);
break;
case 'q':
quiet = 1;
break;
default:
printf("Usage: %s [-t target_dir] [-s num_jobs] [-k base_jobsn] [-q]uiet [-f]use_hack\\n", argv[0]);
exit(1);
break;
}
}
}
void print_config(void)
{
if (quiet != 0) return;
printf("Configuration:\\n");
printf(" number of workers: %d\\n", n_threads);
printf(" number of jobs: %d\\n", n_jobs);
printf(" base job number: %d\\n", base_jobsn);
printf(" target: %s\\n", target_dir);
}
int main(int argc, char *argv[])
{
int rc;
long t;
struct timespec start, end, diff;
int total_serviced;
memset(target_dir, 0, PATH_LENGTH);
snprintf(target_dir, PATH_LENGTH-1, DEFAULT_TARGET);
process_arg(argc, argv);
print_config();
if (chdir(target_dir)) {
perror("ERR Unable to chdir() to target_dir");
exit(1);
}
if (pthread_mutex_init(&mutex, 0)) {
perror("ERR Error setting up mutex");
exit(1);
}
next_job = 0;
memset(request_serviced, 0, sizeof(int)*n_threads);
clock_gettime(CLOCK_REALTIME, &start);
for (t = 0;t < n_threads;t ++) {
rc = pthread_create(&threads[t], 0, worker, (void *)t);
if (rc) {
perror("ERR Error creating thread");
exit(1);
}
}
for (t = 0; t < n_threads;t ++) {
pthread_join(threads[t], 0);
}
clock_gettime(CLOCK_REALTIME, &end);
pthread_mutex_destroy(&mutex);
if (0 == quiet) {
printf("Overall start: "); print_time(&start);
printf("Overall end: "); print_time(&end);
}
total_serviced = 0;
for (t = 0;t < n_threads;t ++) {
total_serviced += request_serviced[t];
if (0 == quiet) {
time_diff(&diff, &start_ts[t], &end_ts[t]);
print_time(&diff);
}
}
printf("INFO punlink S/n:%d/%d T:%s E:", total_serviced, n_jobs, target_dir);
print_time(&diff);
exit(0);
}
| 0
|
#include <pthread.h>
pthread_cond_t taxiCond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t taxiMutex = PTHREAD_MUTEX_INITIALIZER;
void *traveler_arrive(void *name){
printf("Traveler %s needs a taxi now!\\n", (char *)name);
pthread_mutex_lock(&taxiMutex);
pthread_cond_wait(&taxiCond, &taxiMutex);
pthread_mutex_unlock(&taxiMutex);
printf("Traveler %s now got a taxi!\\n", (char *)name);
pthread_exit(0);
}
void *taxi_arrive(void *name){
printf("Taxi %s arrives\\n", (char *)name);
pthread_cond_signal(&taxiCond);
pthread_exit(0);
}
int main(){
pthread_t thread;
pthread_attr_t threadAttr;
pthread_attr_init(&threadAttr);
pthread_create(&thread, &threadAttr, taxi_arrive, (void *)("Jack"));
sleep(1);
pthread_create(&thread, &threadAttr, traveler_arrive, (void *)("Susan"));
sleep(1);
pthread_create(&thread, &threadAttr, taxi_arrive, (void *)("Mike"));
sleep(1);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t condc, condp;
{
pthread_t evm[5];
int buffer[5];
}booth;
booth booths[3];
pthread_t voters[15];
int buffer = 0;
int no_booths = 3,no_voters =15, no_evms = 5,no_slots = 2;
void* polling_ready_booth(void *ptr)
{
int i;
for (i = 1; i <= no_voters; i++)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&condp, &mutex);
while (buffer != 0)
pthread_cond_wait(&condp, &mutex);
buffer = i;
pthread_cond_signal(&condc);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void* consumer(void *ptr)
{
int i;
for (i = 1; i <= no_evms; i++) {
pthread_mutex_lock(&mutex);
while (buffer == 0)
pthread_cond_wait(&condc, &mutex);
buffer = 0;
pthread_cond_signal(&condp);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main(int argc, char **argv)
{
int i,j;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&condc, 0);
pthread_cond_init(&condp, 0);
for(i=0;i<no_voters;i++)
pthread_create(&voters[i], 0, polling_ready_booth, 0);
for(i=0;i<no_booths;i++)
for(j=0;j<no_evms;j++)
pthread_create(&booths[i].evm[j], 0, consumer, 0);
for(i=0;i<no_voters;i++)
pthread_join(voters[i], 0);
for(i=0;i<no_booths;i++)
for(j=0;j<no_evms;j++)
pthread_join(booths[i].evm[j], 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
}
| 0
|
#include <pthread.h>
pthread_t cons[2];
pthread_t prod[2];
pthread_mutex_t buffer_mutex;
int buffer[1000];
int prod_pos=0, cons_pos=0;
sem_t free_positions, filled_positions;
void *produtor(void *arg) {
int n;
while(1) {
n = (int)(drand48() * 1000.0);
sem_wait(&free_positions);
pthread_mutex_lock(&buffer_mutex);
buffer[prod_pos] = n;
prod_pos = (prod_pos+1) % 1000;
pthread_mutex_unlock(&buffer_mutex);
sem_post(&filled_positions);
printf("Produzindo numero %d\\n", n);
sleep((int)(drand48() * 4.0));
}
}
void *consumidor(void *arg) {
int n;
while(1) {
sem_wait(&filled_positions);
pthread_mutex_lock(&buffer_mutex);
n = buffer[cons_pos];
cons_pos = (cons_pos+1) % 1000;
pthread_mutex_unlock(&buffer_mutex);
sem_post(&free_positions);
printf("Consumindo numero %d\\n", n);
sleep((int)(drand48() * 4.0));
}
}
int main(int argc, char **argv) {
int i;
srand48(time(0));
pthread_mutex_init(&buffer_mutex, 0);
sem_init(&free_positions, 0, 1000);
sem_init(&filled_positions, 0, 0);
for(i=0; i<2; i++) {
pthread_create(&(cons[i]), 0, consumidor, 0);
}
for(i=0; i<2; i++) {
pthread_create(&(prod[i]), 0, produtor, 0);
}
for(i=0; i<2; i++) {
pthread_join(cons[i], 0);
}
for(i=0; i<2; i++) {
pthread_join(prod[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
int kvm_run_init(int vcpufd, struct kvm_run_info *info) {
int rval = 0;
sigset_t set;
struct kvm_signal_mask *arg;
arg = malloc(sizeof(*arg) + sizeof(set));
if (arg == 0) {
return ENOMEM;
}
if (pthread_mutex_init(&info->lock, 0) < 0) {
return errno;
}
sigemptyset(&set);
arg->len = 8;
memcpy(arg->sigset, &set, sizeof(set));
rval = ioctl(vcpufd, KVM_SET_SIGNAL_MASK, arg);
free(arg);
return rval < 0 ? errno : 0;
}
int kvm_run(int vcpufd, int sig, struct kvm_run_info *info) {
int rval = 0;
sigset_t newset;
sigset_t oldset;
pthread_mutex_lock(&info->lock);
if (info->cancel) {
info->cancel = 0;
pthread_mutex_unlock(&info->lock);
return EINTR;
}
sigemptyset(&newset);
sigaddset(&newset, sig);
if (pthread_sigmask(SIG_BLOCK, &newset, &oldset) < 0) {
pthread_mutex_unlock(&info->lock);
return errno;
}
info->tid = pthread_self();
info->running = 1;
pthread_mutex_unlock(&info->lock);
rval = ioctl(vcpufd, KVM_RUN, 0);
if (rval < 0) {
rval = errno;
}
pthread_mutex_lock(&info->lock);
info->running = 0;
info->cancel = 0;
pthread_mutex_unlock(&info->lock);
if (pthread_sigmask(SIG_SETMASK, &oldset, 0) < 0) {
return rval != 0 ? rval : errno;
}
return rval;
}
int kvm_run_interrupt(int vcpufd, int sig, struct kvm_run_info *info) {
(void)vcpufd;
pthread_mutex_lock(&info->lock);
if (info->running) {
pthread_kill(info->tid, sig);
} else {
info->cancel = 1;
}
pthread_mutex_unlock(&info->lock);
}
| 0
|
#include <pthread.h>
pthread_mutex_t muteks;
pthread_t watki[2];
double global_array_of_local_sums[2];
void *suma_w( void *arg_wsk);
void *suma_w_no_mutex( void *arg_wsk);
double *tab;
double suma=0;
int main( int argc, char *argv[] ){
int i;
double t1,t2,t3;
int indeksy[2];
for(i=0;i<2;i++) indeksy[i]=i;
tab = (double *) malloc(100000000*sizeof(double));
for(i=0; i<100000000; i++ ) tab[i] = ((double) i+1) / 100000000;
pthread_mutex_init( &muteks, 0);
printf("Poczatek tworzenia watkow\\n");
t1 = czas_zegara();
for(i=0; i<2; i++ )
pthread_create( &watki[i], 0, suma_w, (void *) &indeksy[i] );
for(i=0; i<2; i++ ) pthread_join( watki[i], 0 );
t1 = czas_zegara() - t1;
printf("suma = %lf\\n", suma);
printf("Czas obliczen = %lf\\n", t1);
suma =0;
printf("Poczatek tworzenia watkow\\n");
t1 = czas_zegara();
for(i=0; i<2; i++ ) {
global_array_of_local_sums[i]=0.0;
pthread_create( &watki[i], 0, suma_w_no_mutex, (void *) &indeksy[i] );
}
for(i=0; i<2; i++ ) {
pthread_join( watki[i], 0 );
suma += global_array_of_local_sums[i];
}
t1 = czas_zegara() - t1;
printf("suma = %lf\\n", suma);
printf("Czas obliczen (no mutex) = %lf\\n", t1);
}
void *suma_w( void *arg_wsk){
int i, j, moj_id;
double moja_suma=0;
moj_id = *( (int *) arg_wsk );
j=100000000/2;
for( i=j*moj_id+1; i<=j*(moj_id+1); i++){
moja_suma += tab[i];
}
pthread_mutex_lock( &muteks );
suma += moja_suma;
pthread_mutex_unlock( &muteks );
pthread_exit( (void *)0);
}
void *suma_w_no_mutex( void *arg_wsk){
int i, j, moj_id;
moj_id = *( (int *) arg_wsk );
j=100000000/2;
for( i=j*moj_id+1; i<=j*(moj_id+1); i++){
global_array_of_local_sums[moj_id] += tab[i];
}
pthread_exit( (void *)0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *increment(void *ptr)
{
int *i = ptr;
for(int j=0;j<1000000;j++)
{
pthread_mutex_lock(&mutex);
*i=*i+1;
pthread_mutex_unlock(&mutex);
}
return 0;
}
int main(int argc, char **argv)
{
int i = 0;
pthread_t thread;
pthread_create(&thread,0,&increment,&i);
for(int j=0;j<1000000;j++)
{
pthread_mutex_lock(&mutex);
i=i+1;
pthread_mutex_unlock(&mutex);
}
pthread_join(thread,0);
printf("Value of 'i' is %d\\n",i);
return 0;
}
| 0
|
#include <pthread.h>
void *anti_syn_flood_check(void *I_do_not_use_this_var )
{
int n;
struct timeval begin;
int count;
gettimeofday(&begin,0);
for (n=count=0 ; n < e->max_tab_size ; n++)
if (e->msg_tab[n].c_syn_tv_sec && (begin.tv_sec - e->msg_tab[n].c_syn_tv_sec) > GARBAGE_RETENTION_TIME)
{
pthread_mutex_lock(&gl_lock_garbage);
memset(&(e->msg_tab[n]),0,sizeof(t_msg));
pthread_mutex_unlock(&gl_lock_garbage);
count++;
}
e->stat_tcpflood_dest_entries += count;
if (IS_VERBOSE)
send_log(LOG_DEBUG, "[0] Start anti synflood collecting at %d : check %d entry, found %d to destroy (elasped time = %ds)\\n",
begin.tv_sec,e->max_tab_size, count, e->synflood_ret_time);
if (count * 100 / e->max_tab_size >= 80)
send_log(LOG_WARNING, "[46] You reach more than 80% of the max size of your tcp connection buffer. Maybe you should restart with option -a\\n");
return I_do_not_use_this_var;
}
| 1
|
#include <pthread.h>
static int localId = 0;
static pthread_mutex_t onLineIdMutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t regAsClientMutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t regAsServerMutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t frameBufferMutex = PTHREAD_MUTEX_INITIALIZER;
struct OnlineMesstingServerQueueData *serverHead = 0;
struct OnlineMesstingServerQueueData *serverCurrent = 0;
struct OnlineMesstingClientQueueData *clientHead = 0;
struct OnlineMesstingClientQueueData *clientCurrent = 0;
struct MyFrameBufferQueueData *frameBufferHead = 0;
struct MyFrameBufferQueueData *frameBufferCurrent = 0;
static int updateIndex;
void updateFrameBuffer(int id,int index,int size,char *data)
{
struct MyFrameBufferQueueData *cursor = frameBufferHead;
LOGD("ONLINEVIDEO","wangsl,updateFrameBuffer index is %d \\n",index);
while(cursor != 0)
{
if(cursor->framebuffer->id == id)
{
char *framebuffer = cursor->framebuffer->buffer;
memcpy(framebuffer + index,data,size);
char filepath[32];
memset(filepath,0,32);
sprintf(filepath,"%d.bmp",updateIndex);
genBmpFile(framebuffer, filepath,1366, 768);
updateIndex++;
return;
}
cursor = cursor->next;
}
}
int generateOnlineId()
{
int ret = 0;
pthread_mutex_lock(&onLineIdMutex);
localId++;
ret = localId;
pthread_mutex_unlock(&onLineIdMutex);
return ret;
}
void registerFramebuffer(int id,char *frame,int width,int height)
{
struct MyFrameBuffer *fm = MY_NEW(MyFrameBuffer,"regMyFrameBuffer");
fm->id = id;
fm->buffer = frame;
fm->width = width;
fm->height = height;
struct MyFrameBufferQueueData *p = MY_NEW(MyFrameBufferQueueData,"regFBQueueData");
p->framebuffer = fm;
pthread_mutex_lock(&frameBufferMutex);
if(frameBufferHead == 0)
{
frameBufferHead = p;
frameBufferCurrent = frameBufferHead;
}
else
{
frameBufferCurrent->next = p;
frameBufferCurrent = p;
}
pthread_mutex_unlock(&frameBufferMutex);
}
void resetFrameBuffer(int id,char *buffer,int length)
{
struct MyFrameBufferQueueData *cursor = frameBufferHead;
while(cursor != 0)
{
if(cursor->framebuffer->id == id)
{
char *framebuffer = cursor->framebuffer->buffer;
cursor->framebuffer->buffer = buffer;
cursor->framebuffer->length = length;
MY_FREE(framebuffer);
return;
}
cursor = cursor->next;
}
}
void getOnLineFrameInfo(int id,struct ScreenInfo *screen)
{
struct MyFrameBufferQueueData *cursor = frameBufferHead;
while(cursor != 0)
{
if(cursor->framebuffer->id == id)
{
char *framebuffer = cursor->framebuffer->buffer;
screen->width = cursor->framebuffer->width;
screen->height = cursor->framebuffer->height;
}
cursor = cursor->next;
}
}
struct MyFrameBufferQueueData* getFrameBuffer(int id)
{
struct MyFrameBufferQueueData *cursor = frameBufferHead;
while(cursor != 0)
{
if(cursor->framebuffer->id == id)
{
return cursor;
}
cursor = cursor->next;
}
}
void registerOnlineAsClient(int id,
struct MyThread *iFrameAcceptThd,
struct MyThread *partDataAcceptThd,
struct FriendInfo *server)
{
struct OnlineMesstingClient* data = MY_NEW(OnlineMesstingClient,"rgOnlineMesstingClient");
data->id = id;
data->iFrameAcceptThd = iFrameAcceptThd;
data->partDataAcceptThd = partDataAcceptThd;
data->server = server;
struct OnlineMesstingClientQueueData *p = MY_NEW(OnlineMesstingClientQueueData,"OnLineMessClientQData");
p->client = data;
pthread_mutex_lock(®AsClientMutex);
if(serverHead == 0)
{
clientHead = p;
clientCurrent = clientHead;
}
else
{
clientCurrent->next = p;
clientCurrent = p;
}
pthread_mutex_unlock(®AsClientMutex);
}
void registerOnlineAsServer(int id,
struct MyThread *iFrameSendThd,
struct MyThread *partDataSendThd,
struct FriendInfo **participant)
{
struct OnlineMesstingServer* data = MY_NEW(OnlineMesstingServer,"reOnlineMesstingServer");
data->id = id;
data->iFrameSendThd = iFrameSendThd;
data->partDataSendThd = partDataSendThd;
data->participant = participant;
struct OnlineMesstingServerQueueData *p = MY_NEW(OnlineMesstingServerQueueData,"reOnlineMesstinQueData");
p->server = data;
pthread_mutex_lock(®AsServerMutex);
if(serverHead == 0)
{
serverHead = p;
serverCurrent = serverHead;
}
else
{
serverCurrent->next = p;
serverCurrent = p;
}
pthread_mutex_unlock(®AsServerMutex);
}
| 0
|
#include <pthread.h>extern int __VERIFIER_nondet_int(void);
extern void __VERIFIER_error() ;
int element[(800)];
int head;
int tail;
int amount;
} QType;
pthread_mutex_t m;
int __VERIFIER_nondet_int();
int stored_elements[(800)];
_Bool enqueue_flag, dequeue_flag;
QType queue;
int init(QType *q)
{
q->head=0;
q->tail=0;
q->amount=0;
}
int empty(QType * q)
{
if (q->head == q->tail)
{
printf("queue is empty\\n");
return (-1);
}
else
return 0;
}
int full(QType * q)
{
if (q->amount == (800))
{
printf("queue is full\\n");
return (-2);
}
else
return 0;
}
int enqueue(QType *q, int x)
{
q->element[q->tail] = x;
q->amount++;
if (q->tail == (800))
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == (800))
{
q->head = 1;
}
else
q->head++;
return x;
}
void *t1(void *arg)
{
int value, i;
pthread_mutex_lock(&m);
if (enqueue_flag)
{
for(i=0; i<(800); 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<(800); 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>extern void __VERIFIER_error() ;
int element[(800)];
int head;
int tail;
int amount;
} QType;
pthread_mutex_t m;
int __VERIFIER_nondet_int();
int stored_elements[(800)];
_Bool enqueue_flag, dequeue_flag;
QType queue;
int init(QType *q)
{
q->head=0;
q->tail=0;
q->amount=0;
}
int empty(QType * q)
{
if (q->head == q->tail)
{
printf("queue is empty\\n");
return (-1);
}
else
return 0;
}
int full(QType * q)
{
if (q->amount == (800))
{
printf("queue is full\\n");
return (-2);
}
else
return 0;
}
int enqueue(QType *q, int x)
{
q->element[q->tail] = x;
q->amount++;
if (q->tail == (800))
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == (800))
{
q->head = 1;
}
else
q->head++;
return x;
}
void *t1(void *arg)
{
int value, i;
pthread_mutex_lock(&m);
if (enqueue_flag)
{
for(
i=0; i<(800); 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<(800); 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;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int nreaders = 0, writing = 0;
void
acquire_read_lock()
{
pthread_mutex_lock(&mutex);
while(writing)
pthread_cond_wait(&cond, &mutex);
++nreaders;
pthread_mutex_unlock(&mutex);
}
void
release_read_lock()
{
pthread_mutex_lock(&mutex);
--nreaders;
if(nreaders == 0) pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
void
acquire_write_lock()
{
pthread_mutex_lock(&mutex);
while(writing || (nreaders > 0))
pthread_cond_wait(&cond, &mutex);
writing = 1;
pthread_mutex_unlock(&mutex);
}
void
release_write_lock()
{
pthread_mutex_lock(&mutex);
writing = 0;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
void*
reader(void *s)
{
int i;
while(1) {
acquire_read_lock();
for(i = 0; i < 5; i++) {
printf("reader id: %d, ount: %d\\n", (int)s, i);
sleep(1);
}
release_read_lock();
sched_yield();
}
}
void*
writer(void *s)
{
int i;
while(1) {
acquire_write_lock();
for(i = 0; i < 5; i++) {
printf("writer id: %d, ount: %d\\n", (int)s, i);
sleep(1);
}
release_write_lock();
sched_yield();
}
}
main()
{
pthread_t t[6];
pthread_attr_t attr;
int i = 0;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
for(i = 0; i < 3; i++)
pthread_create(&t[i], 0, reader, (void*)i);
for(; i < 6; i++)
pthread_create(&t[i], 0, writer, (void*)i);
while(1);
}
| 1
|
#include <pthread.h>
static struct root root = { PTHREAD_MUTEX_INITIALIZER, 0, 0, 0 };
static struct btff* btff = 0;
void *malloc(size_t size)
{
if(0 >= size)
return 0;
else
{
struct stack stack[STACK];
void* ptr;
pthread_mutex_lock(&root.mutex);
if(!btff)
{
posix_memalign((void**)&btff, 0, 0);
btff->root = &root;
}
stack[ROOT].available = root.available;
stack[ROOT].node = root.node;
stack[LIST].node = root.list;
ptr = btff->malloc(stack, size);
if(root.available != stack[ROOT].available)
root.available = stack[ROOT].available;
if(root.list != stack[LIST].node)
root.list = stack[LIST].node;
pthread_mutex_unlock(&root.mutex);
return ptr;
}
}
void free(void *ptr)
{
if(!ptr || ptr == btff)
return;
else
{
struct stack stack[STACK];
pthread_mutex_lock(&root.mutex);
if(!btff)
{
posix_memalign((void**)&btff, 0, 0);
btff->root = &root;
}
stack[ROOT].available = root.available;
stack[ROOT].node = root.node;
stack[LIST].node = root.list;
btff->free(stack, ptr);
if(root.available != stack[ROOT].available)
root.available = stack[ROOT].available;
if(root.list != stack[LIST].node)
root.list = stack[LIST].node;
pthread_mutex_unlock(&root.mutex);
}
}
void *realloc(void *ptr, size_t size)
{
if(!ptr && size <= 0)
return 0;
else
if(ptr == btff)
return 0;
else
{
struct stack stack[STACK];
pthread_mutex_lock(&root.mutex);
if(!btff)
{
posix_memalign((void**)&btff, 0, 0);
btff->root = &root;
}
stack[ROOT].available = root.available;
stack[ROOT].node = root.node;
stack[LIST].node = root.list;
if(ptr)
{
if(0 < size)
{
size_t old_size;
void* new_ptr;
new_ptr = btff->realloc(stack, ptr, &old_size, size);
if(new_ptr != ptr)
{
btff->memmove(new_ptr, ptr, old_size);
ptr = new_ptr;
}
}
else
{
btff->free(stack, ptr);
ptr = 0;
}
}
else
if(0 < size)
ptr = btff->malloc(stack, size);
if(root.available != stack[ROOT].available)
root.available = stack[ROOT].available;
if(root.list != stack[LIST].node)
root.list = stack[LIST].node;
pthread_mutex_unlock(&root.mutex);
return ptr;
}
}
static pid_t (*pfork)(void);
pid_t fork(void)
{
pid_t pid;
pthread_mutex_lock(&root.mutex);
pid = pfork();
pthread_mutex_unlock(&root.mutex);
return pid;
}
void _init(void)
{
pfork = dlsym(RTLD_NEXT, "fork");
}
| 0
|
#include <pthread.h>
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static int fd;
char* readline(int fd, char* buffer) {
int i = 0;
for (; read(fd, buffer+i, 1) == 1 && buffer[i] != '\\n'; i++) {}
if (i == 0)
return 0;
buffer[i] = '\\0';
return buffer;
}
void*
thr_fn(void *arg)
{
pid_t pid;
pthread_t tid;
char* buffer = malloc(sizeof(char)* 80);
pid = getpid();
tid = pthread_self();
pthread_mutex_lock(&mutex);
printf("Thread %d Locking mutex\\n", tid, buffer);
fflush(stdout);
if ((buffer = readline(fd, buffer)) != 0) {
buffer[strlen(buffer)] = '\\0';
}
printf("Thread %d read %s from file\\nUnlocking mutex\\n", tid, buffer);
fflush(stdout);
pthread_mutex_unlock(&mutex);
printf("Thread %d starting to execute %s\\n", tid, buffer);
fflush(stdout);
system(buffer);
printf("Thread %d finished\\n", tid);
fflush(stdout);
return((void *)0);
}
int
main(void)
{
int err, i = 0, j;
char* buffer = malloc(sizeof(char)*80);
fd = open("input", O_RDONLY);
printf("Main Process counting number of lines\\n");
fflush(stdout);
while((buffer = readline(fd, buffer)) != 0) {
buffer[strlen(buffer)] = '\\0';
i++;
usleep(10000);
}
lseek(fd, 0, 0);
free(buffer);
pthread_t* threadids = malloc(sizeof(pthread_t)*(--i));
printf("Main Process spawning threads\\n");
for(j=0; j<i; j++) {
err = pthread_create(threadids+j, 0, thr_fn, 0);
if (err != 0) {
perror("pthread_create error");
}
}
printf("Main Process waiting for threads to finish\\n");
i--;
while (i > 0) {
pthread_join(*(threadids+i), 0);
i--;
}
free(threadids);
sleep(1);
exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t vacio;
pthread_cond_t lleno;
int raciones = 0;
void *Cocinero(void *arg);
void *Salvaje(void *arg);
int main(int argc, char *argv[]){
pthread_t th1, th2, th3, th4, th5;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&vacio, 0);
pthread_cond_init(&lleno, 0);
pthread_create(&th1, 0, Cocinero, 0);
pthread_create(&th2, 0, Salvaje, 0);
pthread_create(&th3, 0, Salvaje, 0);
pthread_create(&th4, 0, Salvaje, 0);
pthread_create(&th5, 0, Salvaje, 0);
pthread_join(th1, 0);
pthread_join(th2, 0);
pthread_join(th3, 0);
pthread_join(th4, 0);
pthread_join(th5, 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&vacio);
pthread_cond_destroy(&lleno);
exit(0);
}
void getServingFromPot(){
raciones--;
printf("Racion consumida, quedan %d\\n", raciones);
}
void putServingsInPot(int m){
raciones = m;
printf("El cocinero ha rellenado caldero con %d raciones\\n", raciones);
}
void *Cocinero(void *arg)
{
while(1) {
pthread_mutex_lock(&mutex);
if(raciones == 0){
putServingsInPot(20);
pthread_cond_signal(&vacio);
}
else{
pthread_cond_wait(&lleno, &mutex);
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void *Salvaje(void *arg) {
while(1) {
pthread_mutex_lock(&mutex);
if (raciones == 0){
pthread_cond_signal(&lleno);
pthread_cond_wait(&vacio, &mutex);
}
getServingFromPot();
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
void segFaultMe();
void threadBody( void *ptr ) {
int lockMe = (int)ptr;
if (lockMe) pthread_mutex_lock(&mutex);
segFaultMe();
if (lockMe) pthread_mutex_unlock(&mutex);
}
void shutdownHook() {
printf("shutdownHook...\\n");
if (pthread_mutex_trylock(&mutex) != 0) {
printf("Mutex is locked. Unlocking...\\n");
pthread_mutex_unlock(&mutex);
} else {
printf("Mutex is NOT locked.\\n");
pthread_mutex_unlock(&mutex);
}
printf("shutdownHook is done.\\n");
}
void term(int signum)
{
printf("Received SIGTERM, exiting...\\n");
shutdownHook();
}
void segv(int signum)
{
printf("Received SIGSEGV, exiting...\\n");
shutdownHook();
signal(signum, SIG_DFL);
kill(getpid(), signum);
}
void segFaultMe() {
int *p = 0;
*p = 1;
}
int main(int argc, char **argv) {
printf("Start...\\n\\n");
printf("To test it locking mutex: %s 1\\n", argv[0]);
printf("To test it NOT locking mutex: %s\\n\\n", argv[0]);
atexit(shutdownHook);
struct sigaction action;
memset(&action, 0, sizeof(struct sigaction));
action.sa_handler = term;
sigaction(SIGTERM, &action, 0);
struct sigaction action2;
memset(&action2, 0, sizeof(struct sigaction));
action2.sa_handler = segv;
sigaction(SIGSEGV, &action2, 0);
int lockMe = 0;
if (argc > 1) {
lockMe = 1;
}
pthread_mutex_init(&mutex, 0);
pthread_t thread1;
pthread_create(&thread1, 0, (void *) &threadBody, (void *)lockMe);
while(1) {
}
pthread_mutex_destroy(&mutex);
printf("End.\\n");
}
| 1
|
#include <pthread.h>
pthread_mutex_t m;
int sum;
char* fn;
void* func(void* ar)
{
FILE* pt;
int number;
char cmd[100], result[100];
char* arg=(void*)ar;
sprintf(cmd, "grep -o '\\\\<%s\\\\>' %s | wc -w", arg, fn);
pt=popen(cmd, "r");
fgets(result, 20, pt);
pclose(pt);
number=atoi(result);
pthread_mutex_lock(&m);
sum=sum+number;
pthread_mutex_unlock(&m);
return 0;
}
int main(int argc, char* argv[])
{
pthread_t t[100];
int i;
fn=argv[1];
for(i=2; i<argc; i++)
pthread_create(&t[i], 0, func, argv[i]);
for (i=2; i<argc; i++)
pthread_join(t[i], 0);
printf("The sum is: %d\\n", sum);
return 0;
}
| 0
|
#include <pthread.h>
static char *page;
static int page_len;
static pthread_mutex_t _syscall_mtx;
long offset = 0;
void usage(const char *argv0)
{
fprintf(stderr, "usage:%s page_size(KB) num_page\\n", argv0);
exit(1);
}
static void recover(void)
{
printf("hello: recovered from pagefault\\n");
exit(0);
}
static void pgflt_handler(uintptr_t addr, uint64_t fec, struct dune_tf *tf)
{
printf("caught page fault!\\n");
int ret;
ptent_t *pte;
pthread_mutex_lock(&_syscall_mtx);
ret = dune_vm_lookup(pgroot, (void *) addr, CREATE_NORMAL, &pte);
assert(ret==0);
*pte = PTE_P | PTE_W | PTE_ADDR(dune_va_to_pa((void *) addr));
rdma_read_offset((void *)addr, offset);
pthread_mutex_unlock(&_syscall_mtx);
}
int main(int argc, char *argv[])
{
int i;
volatile int ret;
char* val = (char *) malloc(page_len);
FILE* server_list;
char port[100][20];
char buf[20];
if (argc != 3){
usage(argv[0]);
}
page_len = 1<<12*atoi(argv[1]);
if ( ( server_list=fopen("server_list.txt", "r") ) == 0)
{
perror("fopen failed\\n");
return -1;
}
for(i=0; fgets(buf, sizeof(buf), server_list) != 0; i++)
{
strcpy(port[i], buf);
}
int n=1;
char hostname[20];
snprintf(hostname, 10,"cp-%d", n+1);
printf("%s\\n", hostname);
rdma_init( "192.168.0.2", "47366" , 1<<12);
ret = dune_init_and_enter();
if (ret) {
printf("failed to initialize dune\\n");
return ret;
}
dune_register_pgflt_handler(pgflt_handler);
if (posix_memalign((void **)&page, 1<<12, page_len)) {
perror("init page memory failed");
return -1;
}
memcpy(val, page, page_len);
pthread_mutex_lock(&_syscall_mtx);
rdma_write_offset(page, offset);
dune_vm_unmap(pgroot, (void *)page, page_len);
pthread_mutex_unlock(&_syscall_mtx);
assert(!memcmp(val, page, page_len));
printf("page fault handled\\n");
rdma_done();
return 0;
}
| 1
|
#include <pthread.h>
struct to_info {
void (*to_fn)(void *);
void *to_arg;
struct timespec to_wait;
};
void clock_gettime(int id, struct timespec *tsp) {
struct timeval tv;
gettimeofday(&tv, 0);
tsp->tv_sec = tv.tv_sec;
tsp->tv_nsec = tv.tv_nsec * 1000;
}
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);
free(arg);
return 0;
}
void timeout(const struct timespec *when, void (*func)(void *), void *arg) {
struct timespec now;
struct to_info *tip;
int err;
clock_gettime(0, &now);
if ((when->tv_sec > now.tv_sec) ||
(when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) {
tip = malloc(sizeof(struct to_info));
if (tip != 0) {
tip->to_fn = func;
tip->to_arg = arg;
tip->to_wait.tv_sec = when->tv_sec - now.tv_sec;
if (when->tv_nsec >= now.tv_nsec) {
tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec;
} else {
tip->to_wait.tv_sec --;
tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec +
when->tv_nsec;
}
err = makethread(timeout_helper, (void *)tip);
if (err == 0) {
return;
} else {
free(tip);
}
}
}
(*func)(arg);
}
pthread_mutexattr_t attr;
pthread_mutex_t mutex;
void retry(void *arg) {
pthread_mutex_lock(&mutex);
printf("%d\\n", (int)arg);
pthread_mutex_unlock(&mutex);
}
int main(int argc, const char *argv[]) {
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);
condition = 1;
if (condition) {
clock_gettime(0, &when);
when.tv_sec += 10;
arg = 886;
timeout(&when, retry, (void *)((unsigned long)arg));
}
pthread_mutex_unlock(&mutex);
sleep(11);
exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
int buffer[2];
int buf_first=0;
int buf_last=0;
int buf_count=0;
void produce(int val)
{
pthread_mutex_lock(&mutex);
while(buf_count == 2){
pthread_cond_wait(&cond1, &mutex);
}
buffer[buf_first] = val;
buf_count++;
buf_first = (buf_first + 1) % 2;
printf("\\t producing value %d\\n",val);
pthread_cond_broadcast(&cond2);
pthread_mutex_unlock(&mutex);
}
int consume(void)
{
int val = -1;
pthread_mutex_lock(&mutex);
while(buf_count == 0){
pthread_cond_wait(&cond2, &mutex);
}
val = buffer[buf_last];
buf_count--;
buf_last = (buf_last + 1) % 2;
printf("\\t\\t consuming value %d\\n",val);
pthread_cond_broadcast(&cond1);
pthread_mutex_unlock(&mutex);
return val;
}
void* producer(void* arg)
{
int i = 0;
int new_value = 0;
for(i=0; i<20; i++){
new_value = rand()%10;
produce(new_value);
}
return 0;
}
void* consumer(void* arg)
{
int i = 0;
int value = 0;
for(i=0; i<20; i++){
value = consume();
}
return 0;
}
int main(void)
{
pthread_t tids[4];
int i=0;
struct timespec tt;
clock_gettime(CLOCK_MONOTONIC, &tt);
srand(tt.tv_sec);
for(i=0; i< 4; i++){
if(i%2 == 0){
if(pthread_create (&tids[i], 0, producer, 0) != 0){
fprintf(stderr,"Failed to create the using thread\\n");
return 1;
}
}
else{
if(pthread_create (&tids[i], 0, consumer, 0) != 0){
fprintf(stderr,"Failed to create the generating thread\\n");
return 1;
}
}
}
for (i = 0; i < 4; i++){
pthread_join (tids[i], 0) ;
}
return 0;
}
| 1
|
#include <pthread.h>
int nthreads = 40;
int *array;
int array_length = 2000;
int *state;
pthread_mutex_t *lock;
pthread_cond_t *sorted_cond;
int poll = 0;
pthread_mutex_t poll_lock;
pthread_cond_t poll_cond;
int check(int start, int end){
while(start<end){
if(array[start] < array[start+1]){
return 0;
}
start++;
}
printf("Correct!!!!\\n");
return 1;
}
pthread_mutex_t printlock;
void print_array(int start, int end){
int i;
for(i = start; i<=end; i++){
printf("%d ", array[i]);
}
puts("");
}
void bubble(int start, int end){
int left=start;
while(left<end){
int right = end;
for(;left<right;right--){
if(array[right] > array[right-1]){
int swap = array[right];
array[right] = array[right-1];
array[right-1] = swap;
}
}
left++;
}
}
void* sort(void* data){
int id = *(int*)data;
int start = id*array_length/nthreads;
int end = (id+1)*array_length/nthreads - 1;
while(1){
pthread_mutex_lock(&lock[id]);
if(state[id] == 2){
pthread_mutex_unlock(&lock[id]);
pthread_mutex_lock(&printlock);
printf("==== sort %d ====\\n", id);
print_array(start, end);
pthread_mutex_unlock(&printlock);
bubble(start, end);
pthread_mutex_lock(&printlock);
print_array(start, end);
printf("==== end %d ====\\n", id);
pthread_mutex_unlock(&printlock);
pthread_mutex_lock(&lock[id]);
pthread_mutex_lock(&poll_lock);
poll=0;
pthread_cond_broadcast(&poll_cond);
pthread_mutex_unlock(&poll_lock);
state[id] = 1;
pthread_cond_signal(&sorted_cond[id]);
}
pthread_mutex_unlock(&lock[id]);
if(id < nthreads-1){
pthread_mutex_lock(&lock[id+1]);
while(state[id+1] != 1){
pthread_mutex_lock(&printlock);
printf("==== %d waiting sorted %d ====\\n",id, id+1);
pthread_mutex_unlock(&printlock);
pthread_cond_wait(&sorted_cond[id+1], &lock[id+1]);
}
if(array[end] < array[end+1]){
int swap = array[end+1];
array[end+1] = array[end];
array[end] = swap;
state[id+1] = 2;
pthread_mutex_lock(&lock[id]);
state[id] = 2;
pthread_mutex_unlock(&lock[id]);
}
pthread_mutex_unlock(&lock[id+1]);
}
pthread_mutex_lock(&lock[id]);
if(state[id] == 1){
pthread_mutex_lock(&poll_lock);
pthread_mutex_unlock(&lock[id]);
poll++;
if(poll<nthreads){
pthread_mutex_lock(&printlock);
printf("==== %d waiting poll ====\\n", id);
pthread_mutex_unlock(&printlock);
pthread_cond_wait(&poll_cond, &poll_lock);
}
if(poll == nthreads){
pthread_cond_broadcast(&poll_cond);
pthread_mutex_unlock(&poll_lock);
return;
}
pthread_mutex_unlock(&poll_lock);
}else
pthread_mutex_unlock(&lock[id]);
}
}
void main(){
int i;
array = malloc(array_length * sizeof(int));
srand(time(0));
for(i = 0; i<array_length; i++){
array[i] = rand()%(array_length*2);
}
print_array(0, array_length-1);
lock = malloc(sizeof(pthread_mutex_t)*nthreads);
sorted_cond = malloc(sizeof(pthread_cond_t)*nthreads);
pthread_mutex_init(&printlock, 0);
pthread_mutex_init(&poll_lock, 0);
pthread_cond_init(&poll_cond, 0);
for(i = 0; i<nthreads; i++){
pthread_mutex_init(&lock[i], 0);
pthread_cond_init(&sorted_cond[i], 0);
}
state = malloc(nthreads*sizeof(int));
for(i = 0; i<nthreads;i++){
state[i] = 2;
}
pthread_t tid[nthreads];
for(i = 0; i<nthreads;i++){
int *j = malloc(sizeof(j));
*j = i;
pthread_create(&tid[i], 0, sort, j);
}
for(i = 0; i<nthreads;i++){
pthread_join(tid[i], 0);
}
print_array(0, array_length-1);
check(0,array_length-1);
}
| 0
|
#include <pthread.h>
int buf[5];
size_t len;
pthread_mutex_t mutex;
pthread_cond_t can_produce;
pthread_cond_t can_consume;
} buffer_t;
void* producer(void *arg) {
buffer_t *buffer = (buffer_t*)arg;
while(1) {
pthread_mutex_lock(&buffer->mutex);
if(buffer->len == 5) {
pthread_cond_wait(&buffer->can_produce, &buffer->mutex);
}
int t = rand();
printf("Produced: %d\\n", t);
buffer->buf[buffer->len] = t;
++buffer->len;
pthread_cond_signal(&buffer->can_consume);
pthread_mutex_unlock(&buffer->mutex);
sleep(2);
}
return 0;
}
void* consumer(void *arg) {
buffer_t *buffer = (buffer_t*)arg;
while(1) {
pthread_mutex_lock(&buffer->mutex);
if(buffer->len == 0) {
pthread_cond_wait(&buffer->can_consume, &buffer->mutex);
}
--buffer->len;
printf("Consumed: %d\\n", buffer->buf[buffer->len]);
pthread_cond_signal(&buffer->can_produce);
pthread_mutex_unlock(&buffer->mutex);
sleep(3);
}
return 0;
}
int main(int argc, char *argv[]) {
buffer_t buffer = {
.len = 0,
.mutex = PTHREAD_MUTEX_INITIALIZER,
.can_produce = PTHREAD_COND_INITIALIZER,
.can_consume = PTHREAD_COND_INITIALIZER
};
pthread_t prod, cons;
pthread_create(&prod, 0, producer, (void*)&buffer);
pthread_create(&cons, 0, consumer, (void*)&buffer);
pthread_join(prod, 0);
pthread_join(cons, 0);
return 0;
}
| 1
|
#include <pthread.h>
int intValue(char *s) {
int i = 1;
unsigned int result = s[0] - '0';
while(s[i] != 0) {
result *= 10;
result += s[i] - '0';
i++;
}
return result;
}
pthread_mutex_t l;
unsigned long long int S = 0;
int step;
void* thrd(void* arg) {
unsigned long long int sum = 0;
int i;
int to = ((int) arg) + step;
for(i = ((int) arg); i < to; i++) {
sum += i;
}
pthread_mutex_lock(&l);
S += sum;
pthread_mutex_unlock(&l);
return 0;
}
int main(int argc, char **argv) {
int from = intValue(argv[1]);
int to = intValue(argv[2]);
int N = intValue(argv[3]);
step = (to - from) / N;
N--;
pthread_mutex_init(&l, 0);
int i;
pthread_t id[N];
for (i = 0; i < N; i++) {
if(pthread_create(&id[i], 0, thrd,(void *) from)) {
printf("Too many threads are requested.\\n");
return -1;
}
from += step;
}
unsigned long long int sum = 0;
for(i = from; i <= to; i++) {
sum += i;
}
pthread_mutex_lock(&l);
S += sum;
pthread_mutex_unlock(&l);
for(i = 0; i < N; i++) {
pthread_join(id[i], (void **) 0);
}
printf("The sum: %llu\\n", S);
pthread_mutex_destroy(&l);
return 0;
}
| 0
|
#include <pthread.h>
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo {
int f_count;
pthread_mutex_t f_lock;
int f_id;
struct foo *f_next;
};
struct foo * foo_alloc(int id) {
struct foo *fp;
int idx;
if ((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 1;
fp->f_id = id;
if (pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return 0;
}
idx = (((unsigned long)id)%29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
}
return fp;
}
void foo_hold(struct foo *fp) {
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
struct foo *foo_find(int id) {
struct foo *fp;
pthread_mutex_lock(&hashlock);
for (fp = fh[(((unsigned long)id)%29)]; fp != 0; fp = fp->f_next) {
if (fp->f_id == id) {
foo_hold(fp);
break;
}
}
pthread_mutex_unlock(&hashlock);
return fp;
}
void foo_rele(struct foo *fp) {
struct foo *tfp;
int idx;
pthread_mutex_lock(&fp->f_lock);
if (fp->f_count == 1) {
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_lock(&hashlock);
pthread_mutex_lock(&fp->f_lock);
if (fp->f_count != 1) {
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
return;
}
idx = (((unsigned long)fp->f_id)%29);
tfp = fh[idx];
if (tfp == fp)
fh[idx] = fp->f_next;
else {
while (tfp->f_next != fp)
tfp = tfp->f_next;
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
} else {
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
}
}
| 1
|
#include <pthread.h>
int numero;
int priority;
}ThreadParam;
pthread_mutex_t mutex;
void *ThreadSetPriority(void *arg) {
pthread_mutex_lock(&mutex);
ThreadParam *param = (ThreadParam *)arg;
printf("Priorité actuelle: %d\\n", getpriority(PRIO_PROCESS, syscall(SYS_gettid)));
printf("Set de la priorité à %d...\\n", param->priority);
int ret = setpriority(PRIO_PROCESS, syscall(SYS_gettid), param->priority);
if(ret==0)
{
printf("Priorité changée avec succès pour: %d\\n", getpriority(PRIO_PROCESS, syscall(SYS_gettid)));
printf("setPriority() returne le code: %d\\n", ret);
printf("Valeur de errno: %d\\n", errno);
}
else
{
printf("CHANGEMENT DE PRIORITÉ ÉCHOUÉ.\\n");
printf("setPriority() returne le code: %d\\n", ret);
printf("Valeur de errno: %d\\n", errno);
}
pthread_mutex_unlock(&mutex);
}
int main(int argc, char *argv[]) {
pthread_t threads[5];
ThreadParam params[5];
for (int i=0; i < 5; i++) {
params[i].numero = i;
params[i].priority = ((2*i)-4);
pthread_create(&threads[i], 0, ThreadSetPriority, (void *)¶ms[i]);
}
for (int i=0; i < 5; i++) {
pthread_join(threads[i], 0);
}
exit(0);
}
| 0
|
#include <pthread.h>
int main(int argc, char** argv) {
if(argc != 4 && argc != 5){
printf("Bad number of args\\n");
return 1;
}
if(argc == 5 && strcmp(argv[4], "-i") != 0){
printf("%s\\n", "Wrong option on the end. Try '-i'");
return 1;
}
else{
debugFlag = 1;
}
srand((unsigned int) time(0));
signal(SIGINT, sigintHandler);
int readersNo = atoi(argv[1]);
int writersNo = atoi(argv[2]);
litterboxSize = atoi(argv[3]);
initLibrary();
fillLitterbox();
dividers = calloc((size_t) readersNo, sizeof(int));
readers = calloc((size_t) readersNo, sizeof(pthread_t));
writers = calloc((size_t) writersNo, sizeof(pthread_t));
for (size_t kot = 0; kot < readersNo; kot++) {
dividers[kot] = rand()%10 + 1;
pthread_create(&readers[i], 0, (void *(*)(void *)) & readerJob, ÷rs[kot]);
}
for (size_t kot = 0; kot < writersNo; kot++) {
pthread_create(&writers[kot], 0, (void *(*)(void *)) & writerJob, 0);
}
for (int kot = 0; kot < readersNo; kot++) {
pthread_join(readers[kot], 0);
}
for (int kot = 0; kot < writersNo; kot++) {
pthread_join(writers[kot], 0);
}
pthread_mutex_destroy(&mudegz);
pthread_cond_destroy(&lib->write);
pthread_cond_destroy(&lib->read);
return 0;
}
void sigintHandler(int signo){
clear();
printf("\\n\\n\\nEND\\n\\n\\n");
exit(0);
}
void fillLitterbox(){
litterbox = (int *)malloc(litterboxSize * sizeof(int));
for(int kot = 0; kot < litterboxSize; kot++){
litterbox[kot] = rand();
}
}
void readerJob(void *args){
int divider = *((int *)args);
while (1) {
startReading();
int divisible = 0;
for (int kot = 0; kot < litterboxSize; kot++) {
if (litterbox[kot] % divider == 0) {
divisible++;
if (debugFlag) printf("%i number at index:%i is divisible by: %i\\n", litterbox[kot], kot, divider);
}
}
printf("Divisible by %i -> %i\\n", divider, divisible);
stopReading();
usleep(10000);
}
}
void writerJob(void *args){
while (1) {
startWriting();
int modificationsNo = rand() % litterboxSize;
printf("Starting modifications\\n");
for (int kot = 0; kot < modificationsNo; kot++) {
int toChange = rand() % litterboxSize;
int temp = litterbox[toChange];
litterbox[toChange] = rand();
if (debugFlag) printf("Changing %i value from: %i to %i\\n", toChange+1, temp, litterbox[toChange]);
}
printf("End of modifications\\n");
stopWriting();
usleep(10000);
}
}
void startReading() {
pthread_mutex_lock(&mudegz);
lib->reading++;
if(lib->writing > 0) pthread_cond_wait(&lib->read, &mudegz);
pthread_mutex_unlock(&mudegz);
}
void stopReading() {
pthread_mutex_lock(&mudegz);
lib->reading--;
if(lib->reading == 0) pthread_cond_signal(&lib->write);
pthread_mutex_unlock(&mudegz);
}
void startWriting() {
pthread_mutex_lock(&mudegz);
lib->writing++;
if(lib->reading != 0 || m->writing != 0) pthread_cond_wait(&lib->write, &mudegz);
pthread_mutex_unlock(&mudegz);
}
void stopWriting() {
pthread_mutex_lock(&mudegz);
lib->writing--;
pthread_cond_broadcast(&lib->read);
pthread_mutex_unlock(&mudegz);
}
void clear(){
free(readers);
free(dividers);
free(writers);
free(litterbox);
}
void initLibrary(){
l.reading = 0;
l.writing = 0;
pthread_mutex_init(&mudegz, 0);
pthread_cond_init(&l.read, 0);
pthread_cond_init(&l.write, 0);
lib = &l;
}
| 1
|
#include <pthread.h>
int sock_id;
int port_num;
int bind_ret;
int acc_ret;
struct sockaddr_in server_addr;
struct sthread {
int free;
int desc;
pthread_mutex_t mutex;
pthread_cond_t cond;
};
volatile int numconnected;
struct sthread arr[3];
pthread_t arrthread[3];
int i;
pthread_mutex_t mutex[1];
void handler(int sig)
{
if (sig == SIGINT)
{
int i;
close(sock_id);
for (i = 0; i < 3; ++i)
{
pthread_cancel(arrthread[i]);
}
for (i = 0; i < 3; ++i)
{
pthread_join(arrthread[i], 0);
pthread_cond_destroy(&(arr[i].cond));
pthread_mutex_destroy(&(arr[i].mutex));
}
pthread_mutex_destroy(&mutex[0]);
exit(0);
}
}
const char msgok[] = "hello";
void* fthread(void* arg)
{
struct sthread* ptr = (struct sthread*) arg;
while (1)
{
pthread_mutex_lock(&(ptr->mutex));
pthread_cond_wait(&(ptr->cond), &(ptr->mutex));
ptr->free = 0;
pthread_mutex_unlock(&(ptr->mutex));
write(ptr->desc, msgok, strlen(msgok) + 1);
close(ptr->desc);
pthread_mutex_lock(&(ptr->mutex));
pthread_mutex_lock(&(mutex[0]));
--numconnected;
ptr->free = 1;
pthread_mutex_unlock(&(mutex[0]));
pthread_mutex_unlock(&(ptr->mutex));
}
return 0;
}
const char msg1[] = "error";
int main(int argc, char** argv)
{
numconnected = 0;
if (argc != 2)
{
printf("fail argc\\n");
return -1;
}
port_num = atoi(argv[1]);
sock_id = socket(PF_INET, SOCK_STREAM, 0);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons((short)port_num);
server_addr.sin_addr.s_addr = INADDR_ANY;
bind_ret = bind(sock_id, (struct sockaddr*)(&server_addr), sizeof(struct sockaddr_in));
if (bind_ret == -1)
{
printf("fail bind\\n");
return -2;
}
listen(sock_id, 5);
signal(SIGINT, handler);
for(i = 0; i < 3; ++i)
{
pthread_mutex_init(&(arr[i].mutex), 0);
pthread_cond_init(&(arr[i].cond), 0);
}
for(i = 0; i < 3; ++i)
{
pthread_create(&arrthread[i], 0, fthread, &arr[i]);
}
pthread_mutex_init(&mutex[0], 0);
while (1)
{
int all_not_free;
acc_ret = accept(sock_id, 0, 0);
pthread_mutex_lock(&mutex[0]);
all_not_free = (numconnected == 3);
pthread_mutex_unlock(&mutex[0]);
if (all_not_free)
{
write(acc_ret, msg1, strlen(msg1) + 1);
continue;
}
pthread_mutex_lock(&mutex[0]);
++numconnected;
pthread_mutex_unlock(&mutex[0]);
for (i = 0; i < 3; ++i)
{
pthread_mutex_lock(&(arr[i].mutex));
if (arr[i].free == 1)
{
arr[i].free = 2;
arr[i].desc = acc_ret;
pthread_cond_signal(arr[i].cond);
break;
}
pthread_mutex_unlock(&(arr[i].mutex));
}
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t m[2];
pthread_t t[2];
int sum;
void* doIt(void *arg) {
int id = *(int *)arg, n;
while(sum < 100) {
pthread_mutex_lock(&m[id]);
if(sum < 100) {
printf("Thread %d\\nn = ", id);
scanf("%d", &n);
sum += n;
}
pthread_mutex_unlock(&m[1 - id]);
}
free(arg);
return 0;
}
int main() {
int c2p[2], i;
pipe(c2p);
if(fork()) {
close(c2p[0]);
for(i = 0; i < 2; ++ i)
pthread_mutex_init(&m[i], 0);
pthread_mutex_lock(&m[1]);
for(i = 0; i < 2; ++ i) {
int * x = (int *)malloc(sizeof(int));
*x = i;
pthread_create(&t[i], 0, doIt, x);
}
for(i = 0; i < 2 ; ++ i)
pthread_join(t[i], 0);
write(c2p[1], &sum, sizeof(int));
close(c2p[1]);
for(i = 0; i < 2; ++ i)
pthread_mutex_destroy(&m[i]);
exit(0);
}
close(c2p[1]);
int aux;
read(c2p[0], &aux, sizeof(int));
printf("Tata lor: %d\\n", aux);
wait(0);
return 0;
}
| 1
|
#include <pthread.h>
char** theArray;
int aSize=100;
int usr_port;
pthread_mutex_t* mutexArray;
void* ServerEcho(void *args);
int main(int argc, char * argv []){
int n = atoi(argv[2]);
usr_port = atoi(argv[1]);
if( (n==10)||(n==100)||(n==1000)||(n==10000) ){
aSize=n;
}
struct sockaddr_in sock_var;
int serverFileDescriptor=socket(AF_INET,SOCK_STREAM,0);
int clientFileDescriptor;
sock_var.sin_addr.s_addr=inet_addr("127.0.0.1");
sock_var.sin_port=usr_port;
sock_var.sin_family=AF_INET;
pthread_t* thread_handles;
double start,end,time;
if(bind(serverFileDescriptor,(struct sockaddr*)&sock_var,sizeof(sock_var))>=0)
{
printf("socket has been created \\n");
listen(serverFileDescriptor,2000);
while(1){
thread_handles = malloc(1000*sizeof(pthread_t));
theArray=malloc(aSize*sizeof(char*));
mutexArray=malloc(aSize*sizeof(pthread_mutex_t));
for (int i=0; i<aSize;i++){
theArray[i]=malloc(100*sizeof(char));
snprintf(theArray[i],100, "%s%d%s", "String ", i, ": the initial value" );
pthread_mutex_init(&mutexArray[i],0);
}
GET_TIME(start);
for(int i=0;i<1000;i++){
clientFileDescriptor=accept(serverFileDescriptor,0,0);
pthread_create(&thread_handles[i],0,ServerEcho,(void*)clientFileDescriptor);
}
for(int i = 0;i<1000;i++){
pthread_join(thread_handles[i],0);
}
GET_TIME(end);
time = end-start;
printf(" %f \\n", time);
for (int i=0; i<aSize;i++){
free(theArray[i]);
pthread_mutex_destroy(&mutexArray[i]);
}
free(mutexArray);
free(theArray);
free(thread_handles);
}
}
else{
printf("socket creation failed \\n");
return 1;
}
return 0;
}
void* ServerEcho(void* args){
long clientFileDescriptor = (long) args;
char buff[100];
read(clientFileDescriptor,buff,100);
int pos;
char operation;
int CSerror;
sscanf(buff, "%d %c", &pos,&operation);
if(operation=='r'){
char msg[100];
pthread_mutex_lock(&mutexArray[pos]);
CSerror=snprintf(msg,100, "%s", theArray[pos] );
pthread_mutex_unlock(&mutexArray[pos]);
if(CSerror<0){
printf("ERROR: could not read from position: %d \\n", pos);
sprintf(msg, "%s %d","Error reading from pos: ", pos );
}
write(clientFileDescriptor,msg,100);
close(clientFileDescriptor);
}
else if(operation=='w'){
char msg[100];
snprintf(msg,100, "%s%d%s","String ", pos, " has been modified by a write request" );
pthread_mutex_lock(&mutexArray[pos]);
CSerror=snprintf(theArray[pos],100, "%s", msg );
pthread_mutex_unlock(&mutexArray[pos]);
if(CSerror<0){
printf("ERROR: could not write position: %d \\n", pos);
sprintf(msg, "%s %d","Error writing to pos: ", pos );
}
write(clientFileDescriptor,msg,100);
close(clientFileDescriptor);
}
else{
printf("ERROR: could not communicate with client \\n");
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_cond_t wait = PTHREAD_COND_INITIALIZER;
pthread_cond_t start = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int tasks;
void *task()
{
pthread_mutex_unlock(&mutex);
for(int i = 1; i <= 4; i++)
{
printf("Trabajando....%d\\n", i);
pthread_cond_signal(&start);
}
pthread_mutex_lock(&mutex);
}
void *trabajo()
{
pthread_mutex_lock(&mutex);
while( pthread_cond_wait(&start, &mutex) != 0 );
pthread_mutex_unlock(&mutex);
printf("Fin del trabajo....\\n");
pthread_cond_signal(&wait);
}
int main(int argc, char *argv[])
{
int nthreads=atof(argv[1]);
pthread_t threads[nthreads];
pthread_create(&threads[0], 0, task, (void *)0);
for (long i = 1; i < nthreads; ++i)
pthread_create(&threads[i], 0, trabajo, (void *)i);
for (long i = 1; i < nthreads; ++i)
pthread_join(threads[i],0);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int NO_READERS;
int NO_WRITERS;
int NO_READERS_READING = 0;
int NO_WRITERS_WRITING = 0;
bool VERBOSE;
pthread_mutex_t resourceMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t readerMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t serviceMutex = PTHREAD_MUTEX_INITIALIZER;
void *readerJob(void *arg) {
while (1) {
pthread_mutex_lock(&serviceMutex);
pthread_mutex_lock(&readerMutex);
NO_READERS_READING++;
if (NO_READERS_READING == 1) {
pthread_mutex_lock(&resourceMutex);
}
pthread_mutex_unlock(&serviceMutex);
pthread_mutex_unlock(&readerMutex);
readMemory((int) (uintptr_t) arg, SHARED_ARRAY, SHARED_ARRAY_SIZE, RANGE, VERBOSE);
pthread_mutex_lock(&readerMutex);
NO_READERS_READING--;
if (NO_READERS_READING == 0) {
pthread_mutex_unlock(&resourceMutex);
}
pthread_mutex_unlock(&readerMutex);
}
return 0;
}
void *writerJob(void *arg) {
while (1) {
pthread_mutex_lock(&serviceMutex);
pthread_mutex_lock(&resourceMutex);
pthread_mutex_unlock(&serviceMutex);
writeMemory(SHARED_ARRAY, SHARED_ARRAY_SIZE, RANGE, VERBOSE);
pthread_mutex_unlock(&resourceMutex);
}
return 0;
}
int main(int argc, char *argv[]) {
parseArguments(argc, argv, 2, &NO_READERS, &NO_WRITERS, &VERBOSE);
printf("Readers–writers problem: third readers-writers problem (no thread shall be allowed to starve) with Mutex synchronization.\\n");
printf(" NO_READERS=%i, NO_WRITERS=%i, VERBOSE=%i\\n\\n",
NO_READERS, NO_WRITERS, VERBOSE);
pthread_t *readersThreadsIds = malloc(NO_READERS * sizeof(pthread_t));
if (readersThreadsIds == 0) { cannotAllocateMemoryError(); }
pthread_t *writersThreadsIds = malloc(NO_READERS * sizeof(pthread_t));
if (writersThreadsIds == 0) { cannotAllocateMemoryError(); }
srand(time(0));
initSharedArray();
for (int i = 0; i < NO_READERS; ++i) {
if (pthread_create(&readersThreadsIds[i], 0, readerJob, (void *) (uintptr_t) i) != 0) {
throwError("pthread_create error");
}
}
for (int i = 0; i < NO_WRITERS; ++i) {
if (pthread_create(&writersThreadsIds[i], 0, writerJob, 0) != 0) {
throwError("pthread_create error");
}
}
for (int i = 0; i < NO_READERS; ++i) {
if (pthread_join(readersThreadsIds[i], 0) != 0) {
throwError("pthread_join error");
}
}
for (int i = 0; i < NO_WRITERS; ++i) {
if (pthread_join(writersThreadsIds[i], 0) != 0) {
throwError("pthread_join error");
}
}
free(readersThreadsIds);
free(writersThreadsIds);
pthread_mutex_destroy(&resourceMutex);
pthread_mutex_destroy(&readerMutex);
pthread_mutex_destroy(&serviceMutex);
return 0;
}
| 0
|
#include <pthread.h>
void *threadfunc(void *arg);
pthread_mutex_t mutex;
pthread_cond_t cond;
int started;
int
main(int argc, char *argv[])
{
int ret, i;
pthread_t new;
void *joinval;
char *mem;
int fd;
mem = malloc(1<<20);
if (mem == 0)
err(1, "malloc");
fd = open("/dev/urandom", O_RDONLY, 0);
if (fd == 0)
err(1, "open");
printf("1: preempt test\\n");
pthread_cond_init(&cond, 0);
pthread_mutex_init(&mutex, 0);
pthread_mutex_lock(&mutex);
started = 0;
for (i = 0; i < 1; i++) {
ret = pthread_create(&new, 0, threadfunc, 0);
if (ret != 0)
err(1, "pthread_create");
}
while (started < 1) {
pthread_cond_wait(&cond, &mutex);
}
printf("1: Thread has started.\\n");
pthread_mutex_unlock(&mutex);
printf("1: After releasing the mutex.\\n");
ret = read(fd, mem, 1<<20);
close(fd);
assert(ret == 1<<20);
ret = pthread_join(new, &joinval);
if (ret != 0)
err(1, "pthread_join");
printf("1: Thread joined.\\n");
return 0;
}
void *
threadfunc(void *arg)
{
printf("2: Second thread.\\n");
printf("2: Locking mutex\\n");
pthread_mutex_lock(&mutex);
printf("2: Got mutex.\\n");
started++;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
sleep(1);
return 0;
}
| 1
|
#include <pthread.h>
char stanje[ 5 ];
int vilica[ 5 ];
pthread_cond_t uvjet[ 5 ];
pthread_mutex_t kljuc;
void ispis_stanja( int id ){
int i;
for ( i = 0; i < 5; ++i) {
printf( "%2c", stanje[i] );
}
printf( "(%d)\\n", id );
return;
}
void ulaz_k_o( int id ){
pthread_mutex_lock( &kljuc );
return;
}
void izlaz_k_o( int id ){
pthread_mutex_unlock( &kljuc );
return;
}
void misliti( int id ){ usleep( 1000000 ); return; }
void jesti( int id ){
ulaz_k_o( id );
stanje[ id ] = 'o';
while( vilica[ id ] == 0 || vilica[ ( id + 1 ) % 5 ] == 0 )
pthread_cond_wait( &uvjet[ id ], &kljuc );
stanje[id] = 'X';
vilica[ id ] = vilica[ (id + 1) % 5 ] = 0;
ispis_stanja( id );
izlaz_k_o( id );
usleep( 1000000 );
ulaz_k_o( id );
stanje[ id ] = 'O';
vilica[ id ] = vilica[ (id + 1) % 5 ] = 1;
pthread_cond_broadcast( &uvjet[( id + 1 ) % 5] );
pthread_cond_broadcast( &uvjet[( id + 4 ) % 5] );
ispis_stanja( id );
izlaz_k_o( id );
return;
}
void *filozof( void *arg ){
int id = *( int * )arg;
while( 1 ){
misliti( id );
jesti( id );
}
return 0;
}
void clean_exit( int sig ){
exit( 0 );
}
int main(int argc, char **argv) {
sigset( SIGINT, clean_exit );
pthread_t dretve[ 5 ];
int i;
int id[ 5 ];
strcpy( stanje, "OOOOO" );
pthread_mutex_init( &kljuc, 0 );
for ( i = 0; i < 5; ++i ) {
id[ i ] = i;
vilica[ i ] = 1;
if( pthread_create( &dretve[i], 0, filozof, &id[i] ) ){
printf( "Greska prilkom stvarnja dretve!\\n" );
exit( 0 );
}
}
for ( i = 0; i < 5; ++i ) {
pthread_join( dretve[i], 0 );
}
return 0;
}
| 0
|
#include <pthread.h>
static int top=0;
unsigned int arr[(5)];
pthread_mutex_t m;
_Bool flag=0;
void *t1(void *arg) {
for(int i=0; i<(5); i++) {
pthread_mutex_lock(&m);
assert(top!=(5));
arr[top]=i;
top++;
printf("pushed element %d\\n", i);
flag=1;
pthread_mutex_unlock(&m);
usleep(1000);
}
}
void *t2(void *arg) {
for(int i=0; i<(5); i++) {
pthread_mutex_lock(&m);
if (flag) {
assert(top!=0);
top--;
printf("poped element: %d\\n", arr[top]);
}
pthread_mutex_unlock(&m);
}
}
int main(void) {
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 1
|
#include <pthread.h>
struct node {
int value;
sem_t s;
struct node *next;
};
struct llist {
sem_t s;
pthread_mutex_t insert, delete;
struct node *head, *tail;
} List;
void list_init(struct llist *list) {
pthread_mutex_t blank = PTHREAD_MUTEX_INITIALIZER;
list->head = 0;
list->tail = 0;
list->insert = blank;
list->delete = blank;
if(sem_init(&list->s, 0, (3 +2)) == -1) {
perror("Initing semaphore");
exit(1);
}
}
struct node *make_node(int value, struct node *next) {
struct node *new = malloc(sizeof(struct node));
if (new == 0) {
return 0;
}
new->next = next;
new->value = value;
return new;
}
void insert_tail(struct llist *l, int item) {
struct node *new;
sem_wait(&l->s);
restart:
new = make_node(item, 0);
if (new == 0) {
printf("Cannot allocate memory."
" Not performing any insertions for a while");
sleep(60);
goto restart;
}
pthread_mutex_lock(&l->insert);
if (l->tail != 0) {
l->tail->next = new;
}
if (l->head == 0) {
l->head = new;
}
l->tail = new;
pthread_mutex_unlock(&l->insert);
sem_post(&l->s);
}
bool search(struct llist *l, int needle) {
sem_wait(&l->s);
struct node *straw = l->head;
while (straw) {
if (straw->value == needle) {
sem_post(&l->s);
return 1;
}
straw = straw->next;
}
sem_post(&l->s);
return 0;
}
void *inserter(void *idhack) {
uintptr_t id = (uintptr_t)idhack;
while (1) {
int value = get_random_number() % 10;
insert_tail(&List, value);
printf("[%lu]: Inserted the value %d at the tail.\\n", id, value);
sleep(1);
}
return 0;
}
void *deleter(void *idhack) {
uintptr_t id = (uintptr_t)idhack;
while (1) {
int needle = get_random_number() % 10;
struct node *prev = List.head;
struct node *straw = List.head;
pthread_mutex_lock(&List.delete);
pthread_mutex_lock(&List.insert);
for (int i = 0; i < (3 +2); ++i) {
sem_wait(&List.s);
}
if (straw != 0 && straw->value == needle) {
if (straw->next == 0) {
List.tail = 0;
}
List.head = straw->next;
free(straw);
printf("[%lu]: Removed the value %d from head of list.\\n", id,
needle);
goto around;
}
while (straw) {
if (straw->value == needle) {
prev->next = straw->next;
if (straw == List.tail) {
List.tail = prev;
}
free(straw);
printf("[%lu]: Removed the value %d.\\n", id, needle);
break;
}
straw = straw->next;
}
around:
for (int i = 0; i < (3 +2); ++i) {
sem_post(&List.s);
}
pthread_mutex_unlock(&List.insert);
pthread_mutex_unlock(&List.delete);
sleep(1);
}
return 0;
}
void *searcher(void *idhack) {
uintptr_t id = (uintptr_t)idhack;
while (1) {
int value = get_random_number() % 10;
if (search(&List, value)) {
printf("[%lu]: The list contains %d.\\n", id, value);
} else {
printf("[%lu]: The list doesn't contain %d.\\n", id, value);
}
sleep(1);
}
return 0;
}
int main() {
random_number_init();
list_init(&List);
pthread_t searchers[3];
pthread_t deleters[2];
pthread_t inserters[2];
for (unsigned long i = 0; i < 2; ++i) {
printf("%lu\\n", i);
pthread_create(&inserters[i], 0, inserter, (void*)i);
}
for (unsigned long i = 0; i < 3; ++i) {
pthread_create(&searchers[i], 0, searcher, (void*)i);
}
for (unsigned long i = 0; i < 2; ++i) {
pthread_create(&deleters[i], 0, deleter, (void*)i);
}
for (unsigned long i = 0; i < 2; ++i) {
pthread_join(inserters[i], 0);
}
for (unsigned long i = 0; i < 3; ++i) {
pthread_join(searchers[i], 0);
}
for (unsigned long i = 0; i < 2; ++i) {
pthread_join(deleters[i], 0);
}
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t *mutex_buf;
void locking_function(int mode, int n, const char *file, int line) {
if (mode & CRYPTO_LOCK)
pthread_mutex_lock(&(mutex_buf[n]));
else
pthread_mutex_unlock(&(mutex_buf[n]));
}
unsigned long id_function() {
return (unsigned long)pthread_self();
}
int CRYPTO_thread_setup() {
int i;
mutex_buf = (pthread_mutex_t*)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
if (!mutex_buf)
return -1;
for (i = 0; i < CRYPTO_num_locks(); i++)
pthread_mutex_init(&(mutex_buf[i]), 0);
CRYPTO_set_id_callback(id_function);
CRYPTO_set_locking_callback(locking_function);
return 0;
}
void CRYPTO_thread_cleanup() {
int i;
if (!mutex_buf)
return;
CRYPTO_set_id_callback(0);
CRYPTO_set_locking_callback(0);
for (i = 0; i < CRYPTO_num_locks(); i++)
pthread_mutex_destroy(&(mutex_buf[i]));
OPENSSL_free(mutex_buf);
mutex_buf = 0;
}
| 1
|
#include <pthread.h>
int capacity = 0;
pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
void *produce(void *args)
{
int i = 0;
for (; i < 10;) {
pthread_mutex_lock(&mylock);
if (capacity >= 5)
{
printf("缓冲区已满,无法放入产品\\n");
} else {
++capacity;
printf("生产者存入一个产品, 缓冲区大小为:%d\\n",capacity);
i++;
}
pthread_mutex_unlock(&mylock);
}
return ((void *) 0);
}
void *consume(void *args)
{
int i = 0;
for (; i < 10;) {
pthread_mutex_lock(&mylock);
if (capacity > 0) {
--capacity;
printf("消费者消耗一个产品,缓冲区大小为:%d\\n",capacity);
i++;
} else {
printf("缓冲区已空,无法消耗产品\\n");
}
pthread_mutex_unlock(&mylock);
}
return ((void *) 0);
}
int main(int argc, char **argv)
{
int err;
pthread_t produce_tid, consume_tid;
void *ret;
err = pthread_create(&produce_tid, 0, produce, 0);
if (err != 0) {
printf("线程创建失败:%s\\n", strerror(err));
exit(-1);
}
err = pthread_create(&consume_tid, 0, consume, 0);
if (err != 0) {
printf("线程创建失败:%s\\n", strerror(err));
exit(-1);
}
err = pthread_join(produce_tid, &ret);
if (err != 0) {
printf("生产着线程分解失败:%s\\n", strerror(err));
exit(-1);
}
err = pthread_join(consume_tid, &ret);
if (err != 0) {
printf("消费者线程分解失败:%s\\n", strerror(err));
exit(-1);
}
return (0);
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.