text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
int32_t payload[] = {0x01, 0x02, 0x03, 0x04, 0x05};
struct fgevent event = {ABI, 0, 0, 1, 5, &(payload[0])};
struct test_struct {
int has_been_rejected;
int has_answered;
sem_t *sem;
pthread_mutex_t *mutex;
struct fg_events_data *client_to_disable;
};
static int
server_callback (void * UNUSED(arg), struct fgevent * UNUSED(fgev),
struct fgevent * UNUSED(ansev))
{
return 0;
}
static int
client_callback (void *arg, struct fgevent *fgev,
struct fgevent * UNUSED(ansev))
{
struct test_struct *test_data = (struct test_struct *) arg;
pthread_mutex_lock (test_data->mutex);
if (fgev == 0)
{
PRINT_FAIL ("fgevent error");
exit (1);
}
switch (fgev->id)
{
case FG_CONFIRMED:
break;
case FG_ALIVE:
break;
case FG_USER_OFFLINE:
test_data->has_been_rejected = 1;
break;
case ABI:
if (fgev->receiver != 2)
goto FAIL;
pthread_cancel (test_data->client_to_disable->events_t);
test_data->has_answered = 1;
break;
default:
goto FAIL;
break;
}
if (test_data->has_answered && test_data->has_been_rejected)
sem_post (test_data->sem);
pthread_mutex_unlock (test_data->mutex);
return 0;
FAIL:
PRINT_FAIL ("test");
exit (1);
}
int
main (void)
{
int s;
sem_t pass_test_sem;
pthread_mutex_t mutex;
struct timespec ts;
struct test_struct test_data;
struct fg_events_data server;
struct fg_events_data clients[2];
struct fgevent fgev;
sem_init (&pass_test_sem, 0, 0);
memset (&test_data, 0, sizeof (test_data));
test_data.sem = &pass_test_sem;
pthread_mutex_init (&mutex, 0);
test_data.mutex = &mutex;
fg_events_server_init (&server, &server_callback, &test_data, 0, "/tmp/client_alive.sock", 1);
fg_events_client_init_inet (&clients[0], &client_callback, 0, &test_data, "127.0.0.1", server.port, 2);
fg_events_client_init_unix (&clients[1], &client_callback, 0, &test_data, server.addr, 2 + 1);
sleep (1);
pthread_mutex_lock (test_data.mutex);
memcpy (&fgev, &event, sizeof (struct fgevent));
fgev.id = ABI;
fgev.receiver = 2;
test_data.client_to_disable = &clients[1];
fg_send_event (&clients[1], &fgev);
pthread_mutex_unlock (test_data.mutex);
sleep (6);
pthread_mutex_lock (test_data.mutex);
memcpy (&fgev, &event, sizeof (struct fgevent));
fgev.id = ABI;
fgev.receiver = 2 + 1;
fg_send_event (&clients[0], &fgev);
pthread_mutex_unlock (test_data.mutex);
clock_gettime (CLOCK_REALTIME, &ts);
ts.tv_sec += 1;
s = sem_timedwait (&pass_test_sem, &ts);
if (s < 0)
{
if (errno == ETIMEDOUT)
PRINT_FAIL ("test timeout");
else
PRINT_FAIL ("unknown error");
exit (1);
}
sem_destroy (&pass_test_sem);
pthread_mutex_destroy (&mutex);
fg_events_client_shutdown (&clients[0]);
fg_events_server_shutdown (&server);
PRINT_SUCCESS ("all tests passed");
return 0;
}
| 1
|
#include <pthread.h>
struct Philosopher {
int courses_left;
};
struct State {
struct Philosopher *philo;
pthread_mutex_t locks[3];
pthread_cond_t conds[3];
bool *forks;
int id;
int num;
};
void *PrintHello(struct State *state) {
int id;
id = state->id;
while (state->philo->courses_left > 0) {
if (!state->forks[id]) {
continue;
}
pthread_mutex_lock(&(state->locks[id]));
state->forks[id] = 0;
int here, next, prev;
bool right, left;
pthread_mutex_t *lock, *rlock, *llock;
pthread_cond_t *cond, *rcond, *lcond;
next = (id + 1) % state->num;
int n = id - 1;
int m = state->num;
prev = ((n % m) + m) % m;
if (state->forks[next]) {
pthread_mutex_lock(&(state->locks[next]));
state->forks[next] = 0;
sleep(1);
state->philo->courses_left -= 1;
printf("philo %d has %d courses_left\\n", id, state->philo->courses_left);
pthread_mutex_unlock(&(state->locks[next]));
state->forks[next] = 1;
} else if (state->forks[prev]) {
pthread_mutex_lock(&(state->locks[prev]));
state->forks[prev] = 0;
sleep(1);
state->philo->courses_left -= 1;
printf("philo %d has %d courses_left\\n", id, state->philo->courses_left);
pthread_mutex_unlock(&(state->locks[prev]));
state->forks[prev] = 1;
}
pthread_mutex_unlock(&(state->locks[id]));
state->forks[id] = 1;
}
return 0;
}
int main(int argc, char *argv[]) {
int num_threads = atoi(argv[1]);
pthread_t threads[num_threads];
int rc;
long t;
struct Philosopher *philos;
pthread_mutex_t *locks;
pthread_cond_t *conds;
bool *forks;
struct State *states;
philos = (struct Philosopher *)malloc(num_threads*sizeof(*philos));
locks = (pthread_mutex_t *)malloc(num_threads*sizeof(*locks));
conds = (pthread_cond_t *)malloc(num_threads*sizeof(*conds));
forks = (bool *)malloc(num_threads*sizeof(*forks));
states = (struct State *)malloc(num_threads*sizeof(*states));
for(t = 0; t < num_threads; t++){
if (pthread_mutex_init(&locks[t], 0) != 0) {
printf("\\n mutex init failed\\n");
return 1;
}
if (pthread_cond_init(&conds[t], 0) != 0) {
printf("\\n cond init failed\\n");
return 1;
}
forks[t] = 1;
philos[t] = (struct Philosopher) {
.courses_left = 3
};
struct State * state = &(struct State) {
.philo = &(philos[t]),
.locks = locks,
.forks = forks,
.id = t,
.num = num_threads
};
states[t] = *state;
rc = pthread_create(&threads[t], 0, PrintHello, &states[t]);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
for (t = 0; t < num_threads; t++) {
pthread_join(threads[t], 0);
}
for (t = 0; t < num_threads; t++) {
pthread_mutex_destroy(&locks[t]);
}
free(locks);
free(conds);
free(forks);
free(states);
}
| 0
|
#include <pthread.h>
int id;
int arrival_time;
int processing_time;
int cpu_done_so_far;
int queue_no;
int create_flag;
int turnaround;
int quantum_used;
} process;
int time_slice;
} queue;
int num_queue;
int priority_boost;
int num_processes;
} details;
details * conf=0;
int counter=0;
int run=0;
int master;
process * proc[20];
queue * Q[20];
pthread_mutex_t normal_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t normal_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t main_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t main_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t running_cond = PTHREAD_COND_INITIALIZER;
details * getConfig (char *filename){
for(int i=0; i<20; i++){
proc[i] = (process *)malloc(sizeof(process));
Q[i] = (queue *)malloc(sizeof(queue));
}
details * conf = (details *)malloc(sizeof(details));
FILE *file = fopen (filename, "r");
if(file != 0){
char line[255];
int i = 0;
while(!feof(file)){
fscanf(file, "%d", &conf->num_queue);
int j;
for(j=1;j<=conf->num_queue;j++){
fscanf(file, "%d", &Q[j]->time_slice);
}
fscanf(file, "%d", &conf->priority_boost);
fscanf(file, "%d", &conf->num_processes);
int v=conf->num_processes;
int i;
for(i=1;i<v+1;i++){
fscanf(file,"%d", &proc[i]->id);
fscanf(file, "%d", &proc[i]->arrival_time);
fscanf(file, "%d", &proc[i]->processing_time);
}
}
fclose(file);
}
return conf;
}
int find_process(){
int i;
for(i=1;i<=conf->num_processes;i++){
if(proc[i]->arrival_time == counter && proc[i]->create_flag==0){
return i;
}
}
return 0;
}
int higher_process(int n){
int i;
for(i=1;i<=conf->num_processes;i++){
if(i!=n && proc[i]->cpu_done_so_far!=proc[i]->processing_time && proc[i]->queue_no<proc[n]->queue_no && proc[i]->create_flag==1){
return i;
}
}
return 0;
}
int completion(){
int i;
for(i=1;i<=conf->num_processes;i++){
if(proc[i]->cpu_done_so_far != proc[i]->processing_time){
return 0;
}
}
return 1;
}
void boost(){
int i;
for(i=1;i<=conf->num_processes;i++){
proc[i]->queue_no=1;
proc[i]->quantum_used=0;
}
}
void * process_function(void *param){
pthread_mutex_lock(&normal_lock);
int * var=param;
while(proc[*var]->cpu_done_so_far != proc[*var]->processing_time){
while(master==1 || run==1 || higher_process(proc[*var]->id)){
master=1;
pthread_cond_signal(&main_cond);
pthread_cond_wait(&normal_cond,&normal_lock);
}
run=1;
while(proc[*var]->quantum_used<Q[proc[*var]->queue_no]->time_slice && proc[*var]->cpu_done_so_far!=proc[*var]->processing_time){
proc[*var]->cpu_done_so_far++;
proc[*var]->quantum_used++;
counter++;
master=1;
pthread_cond_signal(&main_cond);
if(run==1){
pthread_cond_wait(&running_cond,&normal_lock);
}
else{
pthread_cond_wait(&normal_cond,&normal_lock);
}
if(counter%(conf->priority_boost)==0){
boost();
}
if(proc[*var]->cpu_done_so_far == proc[*var]->processing_time){
run=0;
proc[*var]->turnaround = counter-proc[*var]->arrival_time;
printf("Process %d is over\\n", proc[*var]->id);
break;
}
if(proc[*var]->quantum_used==Q[proc[*var]->queue_no]->time_slice){
if(proc[*var]->queue_no!=conf->num_queue){
proc[*var]->queue_no++;
}
proc[*var]->quantum_used=0;
run=0;
printf("Quantum of Process %d over\\n", proc[*var]->id);
break;
}
}
master=1;
pthread_cond_signal(&main_cond);
pthread_cond_wait(&normal_cond,&normal_lock);
}
if(proc[*var]->turnaround==0){
proc[*var]->turnaround = counter-proc[*var]->arrival_time;
}
master=1;
pthread_cond_signal(&main_cond);
pthread_mutex_unlock(&normal_lock);
}
int main(){
conf=getConfig("mlfq_conf.conf");
pthread_t tid;
pthread_mutex_lock(&normal_lock);
master=0;
while(completion()==0){
int num=find_process();
while(num!=0){
printf("Process %d created\\n",num);
pthread_create(&tid, 0,process_function, &proc[num]->id);
proc[num]->create_flag=1;
num=find_process();
}
master=0;
if(run==0){
pthread_cond_broadcast(&normal_cond);
}
else{
pthread_cond_signal(&running_cond);
}
pthread_cond_wait(&main_cond,&normal_lock);
}
pthread_mutex_unlock(&normal_lock);
int i;
for(i=1;i<=conf->num_processes;i++){
printf("Turnaround time for Process: %d is %d\\n",i,proc[i]->turnaround);
}
return 0;
}
| 1
|
#include <pthread.h>
unsigned int count;
unsigned int data[12];
int in;
int out;
pthread_mutex_t mutex;
pthread_cond_t empty;
pthread_cond_t full;
} buffer_t;
static buffer_t shared_buffer = {
.count = 0,
.in = 0,
.out = 0,
.mutex = PTHREAD_MUTEX_INITIALIZER,
.empty = PTHREAD_COND_INITIALIZER,
.full = PTHREAD_COND_INITIALIZER
};
static const char *progname = "bounded";
static int
next()
{
static unsigned int cnt = 0;
return ++cnt;
}
static void
check(unsigned int num)
{
static unsigned int cnt = 0;
assert(num == ++cnt);
}
static void*
producer(void *data)
{
buffer_t *buffer = (buffer_t *) data;
while (1) {
pthread_mutex_lock(&buffer->mutex);
while (buffer->count == 12) {
pthread_cond_wait(&buffer->empty, &buffer->mutex);
}
buffer->data[buffer->in] = next();
buffer->in = (buffer->in + 1) % 12;
buffer->count++;
pthread_cond_signal(&buffer->full);
pthread_mutex_unlock(&buffer->mutex);
}
return 0;
}
static void*
consumer(void *data)
{
buffer_t *buffer = (buffer_t *) data;
while (1) {
pthread_mutex_lock(&buffer->mutex);
while (buffer->count == 0) {
pthread_cond_wait(&buffer->full, &buffer->mutex);
}
check(buffer->data[buffer->out]);
buffer->out = (buffer->out + 1) % 12;
buffer->count--;
pthread_cond_signal(&buffer->empty);
pthread_mutex_unlock(&buffer->mutex);
}
return 0;
}
static int
run(int nc, int np)
{
int err, n = nc + np;
pthread_t thread[n];
for (int i = 0; i < n; i++) {
err = pthread_create(&thread[i], 0,
i < nc ? consumer : producer, &shared_buffer);
if (err) {
fprintf(stderr, "%s: %s: unable to create thread %d: %d\\n",
progname, __func__, i, err);
return 1;
}
}
for (int i = 0; i < n; i++) {
if (thread[i]) (void) pthread_join(thread[i], 0);
}
return 0;
}
int
main(int argc, char *argv[])
{
int c, nc = 1, np = 1;
while ((c = getopt(argc, argv, "c:p:h")) >= 0) {
switch (c) {
case 'c':
if ((nc = atoi(optarg)) <= 0) {
fprintf(stderr, "number of consumers must be > 0\\n");
exit(1);
}
break;
case 'p':
if ((np = atoi(optarg)) <= 0) {
fprintf(stderr, "number of producers must be > 0\\n");
exit(1);
}
break;
case 'h':
printf("Usage: %s [-c consumers] [-p producers] [-h]\\n", progname);
exit(0);
}
}
return run(nc, np);
}
| 0
|
#include <pthread.h>
void add_opened_fork(struct afp_volume * volume, struct afp_file_info * fp)
{
pthread_mutex_lock(&volume->open_forks_mutex);
fp->largelist_next=volume->open_forks;
volume->open_forks=fp;
pthread_mutex_unlock(&volume->open_forks_mutex);
}
void remove_opened_fork(struct afp_volume * volume, struct afp_file_info * fp)
{
struct afp_file_info * p, * prev = 0;
pthread_mutex_lock(&volume->open_forks_mutex);
for (p=volume->open_forks;p;p=p->largelist_next)
{
if (p==fp) {
if (prev)
prev->largelist_next=p->largelist_next;
else
volume->open_forks=p->largelist_next;
goto done;
}
prev=p;
}
done:
pthread_mutex_unlock(&volume->open_forks_mutex);
}
void remove_fork_list(struct afp_volume * volume)
{
struct afp_file_info * p, * next;
pthread_mutex_lock(&volume->open_forks_mutex);
for (p=volume->open_forks;p;p=next)
{
next=p->largelist_next;
afp_flushfork(volume,p->forkid);
afp_closefork(volume,p->forkid);
volume->open_forks=p->largelist_next;
free(p);
}
pthread_mutex_unlock(&volume->open_forks_mutex);
}
| 1
|
#include <pthread.h>
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo {
int f_count;
pthread_mutex_t f_lock;
int f_id;
struct foo * f_next;
};
struct foo *
foo_alloc(int id)
{
struct foo *fp;
int idx;
if ((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 1;
fp->f_id = id;
if (pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return (0);
}
idx = (((unsigned long)id)%29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
}
return (fp);
}
void
foo_hold(struct foo *fp)
{
pthread_mutex_lock(&hashlock);
fp->f_count++;
pthread_mutex_unlock(&hashlock);
}
struct foo *
foo_find(int id)
{
struct foo *fp;
pthread_mutex_lock(&hashlock);
for (fp = fh[(((unsigned long)id)%29)]; fp != 0; fp = fp->f_next) {
if (fp->f_id == id) {
fp->f_count++;
break;
}
}
pthread_mutex_unlock(&hashlock);
return (fp);
}
void
foo_rele(struct foo *fp)
{
struct foo *tfp;
int idx;
pthread_mutex_lock(&hashlock);
if (--fp->f_count == 0) {
idx = (((unsigned long)fp->f_id)%29);
tfp = fh[idx];
if (tfp == fp) {
fh[idx] = fp->f_next;
} else {
while (tfp->f_next != fp)
tfp = tfp->f_next;
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_destory(&fp->f_lock);
free(fp);
} else {
pthread_mutex_unlock(&hashlock);
}
}
| 0
|
#include <pthread.h>
void * alarm_func( void * arg );
int sec;
char msg[256];
FILE * fp;
pthread_t pt;
struct alarm_str * prev;
struct alarm_str * next;
} alarm_t;
alarm_t * head = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main( int argc, char ** argv ) {
alarm_t * alarm;
FILE * fp;
char line[256];
if( argc < 2 ) return( 1 );
fp = fopen( argv[1], "w" );
while( 1 ) {
printf( "Alarm ( sec msg ) --> " );
fgets( line, sizeof( line ), stdin );
if( strlen( line ) <= 1 ) {
continue;
}
if( memcmp( line, "quit", 4 ) == 0 ) break;
alarm = malloc( sizeof( alarm_t ));
alarm -> fp = fp;
if( sscanf( line, "%d %s", &alarm -> sec, alarm -> msg ) < 2 ) {
continue;
}
pthread_mutex_lock( &mutex );
alarm -> next = head;
alarm -> prev = 0;
if( head ) {
head -> prev = alarm;
}
head = alarm;
pthread_mutex_unlock( &mutex );
pthread_create( &alarm -> pt, 0, &alarm_func, alarm );
pthread_detach( alarm -> pt );
}
pthread_mutex_destroy( &mutex );
fclose( fp );
return 0;
}
void * alarm_func( void * arg ) {
alarm_t * alarm = ( alarm_t * )arg;
alarm_t * current = 0;
int cnt;
for( cnt = 0; cnt < alarm -> sec; cnt ++ ) {
flockfile( alarm -> fp );
fprintf( alarm -> fp, "[%d] (%d) %s\\n",
alarm -> sec, cnt, alarm -> msg );
fflush( alarm -> fp );
funlockfile( alarm -> fp );
sleep( 1 );
}
pthread_mutex_lock( &mutex );
for( current = head; current; current = current -> next ) {
if( current -> pt != pthread_self( )) {
continue;
}
if( current -> next != 0 ) {
current -> next -> prev = current -> prev;
}
if( current -> prev != 0 ) {
current -> prev -> next = current -> next;
}
if( head == current ) {
head = current -> next;
}
break;
}
free( current );
pthread_mutex_unlock( &mutex );
return 0;
}
| 1
|
#include <pthread.h>
pthread_t thread1, thread2;
static pthread_mutex_t verrou1, verrou2;
int var=5, N=10, i=1,j=1;
void *lire(void *nom_du_thread) {
pthread_mutex_lock(&verrou1);
printf(">lire variable = %d\\n",var);
for (i=0;i<N-1;i++) {
pthread_mutex_unlock(&verrou2);
pthread_mutex_lock(&verrou1);
printf(">lire variable = %d\\n",var);
}
pthread_exit(0);
}
void *ecrire(void *nom_du_thread)
{
for( j=0;j<N-1;j++){
printf("ecriture %d dans variable \\n",var);
sleep(1);
pthread_mutex_unlock(&verrou1);
pthread_mutex_lock(&verrou2);
var=var+1;
}
printf("ecriture %d dans variable \\n",var);
pthread_mutex_unlock(&verrou1);
pthread_exit(0);
}
int main()
{
pthread_mutex_init(&verrou1,0);
pthread_mutex_init(&verrou2,0);
pthread_mutex_lock(&verrou1);
pthread_mutex_lock(&verrou2);
pthread_create(&thread1,0,lire,0);
pthread_create(&thread2,0,ecrire,0);
pthread_join(thread1,0);
pthread_join(thread2,0);
}
| 0
|
#include <pthread.h>
static void Hub_catchSignal(int sig);
static int _Hub_close(void);
static void Hub_close(void);
static void Hub_usage(char* arg0);
void Hub_exitError(void) {
Hub_Logging_log(INFO, "Terminating hub due to error condition");
exit(1);
}
void Hub_exit(void) {
Hub_close();
exit(0);
}
bool Hub_fileExists(const char* file) {
struct stat s;
return stat(file, &s) != -1;
}
static void Hub_catchSignal(int sig) {
if(sig == SIGTERM || sig == SIGINT) {
Hub_Net_preClose();
pthread_detach(Task_background(_Hub_close));
return;
}
Hub_Logging_log(CRITICAL, "Scary signal caught! Shutting down!");
Hub_exitError();
}
static int _Hub_close(void) {
Hub_close();
return 0;
}
static void Hub_close(void) {
static pthread_mutex_t hub_close_lock = PTHREAD_MUTEX_INITIALIZER;
static bool closed = 0;
pthread_mutex_lock(&hub_close_lock);
if(!closed) {
Hub_Logging_log(INFO, "Closing");
Hub_Net_close();
Hub_Var_close();
Hub_Logging_close();
Hub_Config_close();
Util_close();
MemPool_close();
}
closed = 1;
pthread_mutex_unlock(&hub_close_lock);
}
static void Hub_usage(char* arg0) {
printf("Usage: %s [-h] [-c conf]\\n", arg0);
}
int main(int argc, char** argv) {
int opt;
char* conf_file = 0;
while((opt = getopt(argc, argv, ":hc:")) != -1) {
switch(opt) {
case 'h':
Hub_usage(argv[0]);
exit(0);
break;
case 'c':
conf_file = optarg;
break;
case ':':
fprintf(stderr, "Option '%c' requires an argument\\n", optopt);
Hub_usage(argv[0]);
exit(1);
default:
fprintf(stderr, "Invalid option '%c'\\n", optopt);
Hub_usage(argv[0]);
exit(1);
break;
}
}
signal(SIGPIPE, SIG_IGN);
signal(SIGINT, Hub_catchSignal);
signal(SIGHUP, Hub_catchSignal);
signal(SIGTERM, Hub_catchSignal);
if(conf_file) {
Hub_Config_loadConfig(conf_file);
}
Hub_Config_init();
Hub_Var_init();
Hub_Logging_init();
Hub_Net_init();
MemPool_init();
atexit(Hub_close);
Hub_Net_mainLoop();
Hub_close();
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cvFull = PTHREAD_COND_INITIALIZER, cvEmpty = PTHREAD_COND_INITIALIZER;
int queue[4], fll = 0, *tmpP = queue, *tmpC = queue;
void *producerFunction()
{
while(1)
{
pthread_mutex_lock(&mx);
printf("Producer locked mutex\\n");
while (fll >= 4)
{
printf("Buffer is FULL - Producer will wait for Consumer's signal\\n");
pthread_cond_wait(&cvFull,&mx);
printf("Producer was signalled by Consumer\\n");
}
if (tmpP-queue>=4) tmpP = queue;
*tmpP = 99;
fll++;
printf("***Producer's buffer pointer = %p\\n",tmpP);
printf("Producer put a %d - fill count is %d\\n",99,fll);
tmpP++;
printf("Producer is signalling Consumer\\n");
pthread_cond_signal(&cvEmpty);
pthread_mutex_unlock(&mx);
printf("Producer released mutex\\n");
sleep(1);
}
}
void *consumerFunction()
{
while(1)
{
pthread_mutex_lock(&mx);
printf("Consumer locked mutex\\n");
while (fll == 0)
{
printf("Buffer is EMPTY - Consumer will wait for Producer's signal\\n");
pthread_cond_wait(&cvEmpty,&mx);
printf("Consumer was signalled by Producer\\n");
}
if (tmpC-queue>=4) tmpC = queue;
int consumerVar = *tmpC;
fll--;
printf("***Consumer's buffer pointer = %p\\n",tmpC);
printf("Consumer got a %d - fill count is %d\\n",consumerVar,fll);
tmpC++;
printf("Consumer is signalling Producer\\n");
pthread_cond_signal(&cvFull);
pthread_mutex_unlock(&mx);
printf("Consumer released mutex\\n");
sleep(3);
}
}
void main()
{
pthread_t producerThread, consumerThread;
int producerError, consumerError;
int ret = pthread_cond_init(&cvEmpty,0);
if(consumerError = pthread_create(&consumerThread, 0, &consumerFunction, 0)) printf("Consumer thread creation failed: %d\\n", consumerError);
if(producerError=pthread_create(&producerThread, 0, &producerFunction, 0)) printf("Producer thread creation failed: %d\\n", producerError);
pthread_join(producerThread, 0);
pthread_join(consumerThread, 0);
exit(0);
}
| 0
|
#include <pthread.h>
int sumaTiempos[2];
float prom[2];
pthread_mutex_t count_mutexs[2];
int tid;
double stuff;
} thread_data_t;
void *thr_func(void *arg) {
struct timeval startTime, finishTime;
int i=0;
thread_data_t *data = (thread_data_t *)arg;
printf("hello from thr_func, thread id: %d\\n", data->tid);
for (i=0;i<1000;i++){
gettimeofday(&startTime, 0);
usleep(10000);
gettimeofday(&finishTime, 0);
pthread_mutex_lock(count_mutexs+data->tid);
sumaTiempos[data->tid]+=(finishTime.tv_sec * 1000000 + finishTime.tv_usec) - (startTime.tv_sec * 1000000 + startTime.tv_usec)-10000;
pthread_mutex_unlock(count_mutexs+data->tid);
}
pthread_exit(0);
}
int main(int argc, char **argv) {
pthread_t thr[2];
thread_data_t thr_data[2];
int i,rc;
sumaTiempos[0]=0;
sumaTiempos[1]=0;
for (i = 0; i < 2; ++i) {
thr_data[i].tid = i;
if ((rc = pthread_create(&thr[i], 0, thr_func, &thr_data[i]))) {
fprintf(stderr, "error: pthread_create, rc: %d\\n", rc);
return 1;
}
}
for (i = 0; i < 2; ++i) {
pthread_join(thr[i], 0);
}
prom[0]=((float)sumaTiempos[0])/1000;
prom[1]=((float)sumaTiempos[1])/1000;
printf("La suma de tiempo del thread 0 fue de %f uSeg y del thread 1 de %f uSeg \\n",prom[0],prom[1]);
return 0;
}
| 1
|
#include <pthread.h>
long data_type;
char data[1024];
} t_data;
int number;
int fd;
} tide;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *snd_message(void *arg);
void *rcv_message(void *arg);
int main(int argc,char *argv[]){
pthread_t snd_thread,rcv_thread;
int fd;
void *thread_result;
tide num;
num.fd = msgget((key_t)12345,IPC_CREAT|0666);
if(argc!=2){
printf("잘못 눌렀습니다. 다시 눌르세요\\n");
exit(1);
}
num.number = atoi(argv[1]);
pthread_create(&snd_thread,0,snd_message,&num);
pthread_create(&rcv_thread,0,rcv_message,&num);
pthread_join(rcv_thread,&thread_result);
pthread_join(snd_thread,&thread_result);
return 0;
}
void *snd_message(void *arg){
tide* num;
num = (tide*)arg;
pthread_t tid;
char buf[1024];
char buff[1024];
t_data datas;
int c;
while(1){
memset(buf,'\\0',1024);
memset(buff,'\\0',1024);
scanf("%d",&c);
getchar();
fgets(buf,1024,stdin);
*(buf+(strlen(buf)-1))='\\0';
datas.data_type = c;
sprintf(buff,"[%d sned] : %s\\n",(*num).number,buf);
strcpy(datas.data,buff);
pthread_mutex_lock(&mutex);
msgsnd((*num).fd,&datas,sizeof(datas)-sizeof(long),0);
pthread_mutex_unlock(&mutex);
}
}
void *rcv_message(void *arg){
tide* num;
num = (tide*)arg;
char buf[1024];
int i;
t_data datas;
while(1){
if((msgrcv((*num).fd,&datas,sizeof(datas)-sizeof(long),(*num).number,0))>0){
printf("%s\\n",datas.data);
}
}
}
| 0
|
#include <pthread.h>
struct SharedData {
int isopen;
unsigned int front;
unsigned int count;
unsigned int bufsize;
char buf[16];
pthread_mutex_t mutex;
pthread_cond_t dataAvailable;
pthread_cond_t spaceAvailable;
};
void
initialize( struct SharedData * sptr )
{
sptr->isopen = 1;
sptr->front = 0;
sptr->count = 0;
sptr->bufsize = 16;
pthread_mutex_init( &sptr->mutex, 0 );
pthread_cond_init( &sptr->spaceAvailable, 0 );
pthread_cond_init( &sptr->dataAvailable, 0 );
}
void *
consumer( void * arg )
{
struct SharedData * d = (struct SharedData *)arg;
char buffer[200];
int i;
pthread_detach( pthread_self() );
while ( d->isopen )
{
pthread_mutex_lock( &d->mutex );
while ( d->count == 0 )
{
pthread_cond_signal( &d->spaceAvailable );
printf( "BKR consumer() waits when shared buffer is empty.\\n" );
pthread_cond_wait( &d->dataAvailable, &d->mutex );
}
sleep( 1 );
printf( "BKR consumer() now takes %d bytes from buffer.\\n", d->count );
for ( i = 0 ; (d->count > 0) && (i < sizeof(buffer) ) ; i++ )
{
buffer[i] = d->buf[d->front];
d->front = (d->front + 1) % d->bufsize;
--d->count;
}
pthread_cond_signal( &d->spaceAvailable );
pthread_mutex_unlock( &d->mutex );
}
return 0;
}
void *
producer( void * arg )
{
struct SharedData * d = (struct SharedData *)arg;
int i;
int limit;
int back;
char p2[100];
pthread_detach( pthread_self() );
while ( printf( "Enter something->" ), scanf( " %[^\\n]\\n", p2 ) > 0 )
{
pthread_mutex_lock( &d->mutex );
limit = strlen( p2 ) + 1;
for ( i = 0 ; i < limit ; i++ )
{
while ( d->count == d->bufsize )
{
pthread_cond_signal( &d->dataAvailable );
printf( "BKR producer() >%c< waits when shared buffer is full.\\n", p2[i] );
pthread_cond_wait( &d->spaceAvailable, &d->mutex );
}
back = (d->front + d->count) % d->bufsize;
d->buf[back] = p2[i];
++d->count;
}
pthread_cond_signal( &d->dataAvailable );
pthread_mutex_unlock( &d->mutex );
}
d->isopen = 0;
return 0;
}
int main( int argc, char ** argv )
{
pthread_t ignore;
char * func = "main";
struct SharedData * sharedData;
if ( (sharedData = (struct SharedData *)malloc( sizeof(struct SharedData) )) == 0 )
{
printf( "malloc() failed in %s.\\n", func );
return 1;
}
else
{
initialize( sharedData );
pthread_create( &ignore, 0, consumer, sharedData );
pthread_create( &ignore, 0, producer, sharedData );
pthread_exit( 0 );
}
}
| 1
|
#include <pthread.h>
int buf_1=0;
int buf_2=0;
pthread_mutex_t l1;
pthread_mutex_t l2;
int buf_3=0;
int buf_4=0;
pthread_mutex_t l3;
pthread_mutex_t l4;
void *prod1()
{
int aux=0;
while(1){
pthread_mutex_lock(l1);
if(buf_1 < 6){
aux=buf_1;
buf_1=aux+1;
aux=0;
}
pthread_mutex_unlock(l1);
}
}
void *prod2()
{
int aux=0;
while(1){
pthread_mutex_lock(l2);
if(buf_2 < 6){
aux=buf_2;
buf_2=aux+1;
aux=0;
}
pthread_mutex_unlock(l2);
}
}
void *cons()
{
int aux=0;
while(1){
pthread_mutex_lock(l1);
if(buf_1 > 0){
aux=buf_1;
buf_1=aux-1;
}
pthread_mutex_unlock(l1);
pthread_mutex_lock(l2);
if(buf_2 > 0){
aux=buf_2;
buf_2=aux-1;
}
pthread_mutex_unlock(l2);
}
}
void *prod3()
{
int aux=0;
while(1){
pthread_mutex_lock(l3);
if(buf_3 < 6){
aux=buf_3;
buf_3=aux+1;
aux=0;
}
pthread_mutex_unlock(l3);
}
}
void *prod4()
{
int aux=0;
while(1){
pthread_mutex_lock(l4);
if(buf_4 < 6){
aux=buf_4;
buf_4=aux+1;
aux=0;
}
pthread_mutex_unlock(l4);
}
}
void *cons2()
{
int aux=0;
while(1){
pthread_mutex_lock(l3);
if(buf_3 > 0){
aux=buf_3;
buf_3=aux-1;
}
pthread_mutex_unlock(l3);
pthread_mutex_lock(l4);
if(buf_4 > 0){
aux=buf_4;
buf_4=aux-1;
}
pthread_mutex_unlock(l4);
}
}
int main()
{
pthread_t id1;
pthread_t id2;
pthread_t id3;
pthread_t id4;
pthread_t id5;
pthread_t id6;
pthread_mutex_init(l1, 0);
pthread_mutex_init(l2, 0);
pthread_mutex_init(l3, 0);
pthread_mutex_init(l4, 0);
pthread_create(id1, 0, prod1, 0);
pthread_create(id2, 0, prod2, 0);
pthread_create(id3, 0, cons, 0);
pthread_create(id4, 0, prod3, 0);
pthread_create(id5, 0, prod4, 0);
pthread_create(id6, 0, cons2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
pthread_join(id3, 0);
pthread_join(id4, 0);
pthread_join(id5, 0);
pthread_join(id6, 0);
}
| 0
|
#include <pthread.h>
FILE *arq, *arqSaida;
int nThreads;
pthread_mutex_t arq_mutex;
void insereCaracteres(long int* cnt, char* s);
void merge(long int* a, long int* b);
void print(long int* c, FILE* arq);
void* ContaChar(void* arg)
{
char aux[1023 + 1];
size_t n = 0;
long int temp_l[127];
int i, tid = *(int *)arg;
for(i = 0; i < 127; i++) temp_l[i] = 0;
while(!feof(arq))
{
pthread_mutex_lock(&arq_mutex);
n = fread((void *)aux, sizeof(char), 1023, arq);
pthread_mutex_unlock(&arq_mutex);
if(n < 1023) aux[n] = '\\0';
insereCaracteres(temp_l, aux);
}
pthread_exit((void *)temp_l);
}
int main(int argc, char** argv)
{
int i, arg;
pthread_t* system_id;
long int charCount[127];
double start, end;
for (i = 0; i < 127; i++) charCount[i] = 0;
if(argc < 4)
{
printf("Entrada deve ser da forma <arquivo de entrada>.txt <arquivo de saida>.txt <numero de threads>\\n");
exit(-1);
}
arq = fopen(argv[1], "r");
if(arq == 0) {
fprintf(stderr, "Erro ao abrir o arquivo de entrada.\\n");
exit(-1);
}
arqSaida = fopen(argv[2], "w");
if(arqSaida == 0) {
fprintf(stderr, "Erro ao abrir o arquivo de saida.\\n");
exit(-1);
}
nThreads = atoi(argv[3]);
system_id = malloc(sizeof(pthread_t) * nThreads);
GET_TIME(start);
pthread_mutex_init(&arq_mutex, 0);
for(i = 0; i < nThreads; i++)
{
arg = i;
if(pthread_create(&system_id[i], 0, ContaChar, (void*)&arg))
{ printf("Erro pthread_create"); exit(-1);}
}
long int* ret;
for(i = 0; i < nThreads; i++)
{
if(pthread_join(system_id[i], (void**) &ret))
{ printf("Erro pthread_join"); exit(-1);}
merge(charCount, ret);
}
pthread_mutex_destroy(&arq_mutex);
GET_TIME(end);
printf("Caractere, Qtde\\n");
print(charCount, arqSaida);
printf("Tempo decorrido %lf\\n", end - start);
fclose(arq);
fclose(arqSaida);
pthread_exit(0);
}
void insereCaracteres(long int* cnt, char* s)
{
int i, size = strlen(s);
for (i = 0; i < size; i++)
if(s[i] >= 0 && s[i] < 127) cnt[s[i]]++;
}
void merge(long int* a, long int* b)
{
int i;
for(i = 0; i < 127; i++)
a[i] += b[i];
}
int checkChar(char c)
{
if(c >= 'A' && c <= 'Z') return 1;
if(c >= 'a' && c <= 'z') return 1;
if(c >= '0' && c <= '9') return 1;
if(c == '?' || c == '!'
|| c == '.' || c == ','
|| c == ';' || c == ':'
|| c == '_' || c == '-'
|| c == '(' || c == ')'
|| c == '@' || c == '%'
|| c == '&' || c == '$'
return 0;
}
void print(long int* c, FILE* arq)
{
int i;
for (i = 0; i < 127; i++)
{
if(checkChar(i) && c[i] > 0) fprintf(arq, "%c, %ld\\n", i, c[i]);
}
}
| 1
|
#include <pthread.h>
int pthread_setspecific(pthread_key_t key, const void* value_const)
{
void* value = (void*) value_const;
struct pthread* thread = pthread_self();
if ( key < thread->keys_length )
return thread->keys[key] = value, 0;
pthread_mutex_lock(&__pthread_keys_lock);
assert(key < __pthread_keys_length);
assert(__pthread_keys[key].destructor);
pthread_mutex_unlock(&__pthread_keys_lock);
size_t old_length = thread->keys_length;
size_t new_length = __pthread_keys_length;
size_t new_size = new_length * sizeof(void*);
void** new_keys = (void**) realloc(thread->keys, new_size);
if ( !new_keys )
return errno;
thread->keys = new_keys;
thread->keys_length = new_length;
for ( size_t i = old_length; i < new_length; i++ )
new_keys[i] = 0;
return thread->keys[key] = value, 0;
}
| 0
|
#include <pthread.h>
int total_num_eats = 100, exclusiveVar;
pthread_mutex_t chopstick[5];
pthread_cond_t cond_var;
void *eat(void *i);
int main()
{
int i;
for(i = 0; i < 5; i++)
{
if(pthread_mutex_init(&chopstick[i], 0) < 0)
{
fprintf(stderr, "Error: cold not initialize semaphore.");
return -1;
}
}
pthread_cond_init(&cond_var, 0);
int params[5] = {0,1,2,3,4};
pthread_t tid1, tid2, tid3, tid4, tid5;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tid1,&attr, eat, ¶ms[0]);
pthread_create(&tid2,&attr, eat, ¶ms[1]);
pthread_create(&tid3,&attr, eat, ¶ms[2]);
pthread_create(&tid4,&attr, eat, ¶ms[3]);
pthread_create(&tid5,&attr, eat, ¶ms[4]);
int index;
while(total_num_eats > 0)
{
for(index = 0; index < 5; index++)
{
pthread_mutex_lock(&chopstick[index]);
exclusiveVar = index;
pthread_cond_signal(&cond_var);
pthread_mutex_unlock(&chopstick[index]);
}
}
pthread_join(tid1, 0);
pthread_join(tid2, 0);
pthread_join(tid3, 0);
pthread_join(tid4, 0);
pthread_join(tid5, 0);
return 0;
}
void *eat(void *i)
{
int index = *(int *)i;
while(total_num_eats > 0)
{
pthread_mutex_lock(&chopstick[index]);
while(exclusiveVar != index)
{
pthread_cond_wait(&cond_var, &chopstick[index]);
}
printf("num eats remaining: %d\\n", total_num_eats--);
printf("Philospher %d ate.\\n", index+1);
pthread_mutex_unlock(&chopstick[index]);
sleep(1);
}
}
| 1
|
#include <pthread.h>
volatile int shared_counter = 0;
pthread_t people[100];
pthread_mutex_t lock;
void* returnToChair() {
for(int i=0; i<1000;i++) {
pthread_mutex_lock(&lock);
shared_counter++;
pthread_mutex_unlock(&lock);
}
return 0;
}
int main(void) {
if (pthread_mutex_init(&lock, 0) != 0) {
printf("\\n Mutex Initialization failed!\\n");
return 1;
}
clock_t begin, end;
double individual_time_spent;
double total_time_spent = 0.0;
double average_time_spent;
int threadReturn;
for (int j = 0; j < 10; j++) {
printf("\\n> Run - %d\\n", (j+1));
begin = clock();
int i = 0;
while(i < 100) {
threadReturn = pthread_create(&(people[i]), 0, &returnToChair, 0);
if (threadReturn != 0)
printf("\\ncan't create thread :[%s]", strerror(threadReturn));
else
i++;
}
end = clock();
individual_time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
total_time_spent += individual_time_spent;
printf(" --- Time: %f\\n", individual_time_spent);
printf(" --- Counter: %d\\n", shared_counter);
shared_counter = 0;
}
pthread_mutex_destroy(&lock);
average_time_spent = total_time_spent/10;
printf("\\nTotal Time Taken: %f\\n", total_time_spent);
printf("Average Time for each run: %f\\n", average_time_spent);
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 = (struct foo *) 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 (&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)
{
fp->f_count++;
break;
}
}
pthread_mutex_unlock (&hashlock );
}
void foo_rele (struct foo * fp )
{
struct foo * tfp;
int idx;
pthread_mutex_lock (&hashlock );
if (--fp->f_count == 0)
{
idx = (((unsigned long) fp->f_id) %29);
tfp = fh[idx];
if (tfp == fp)
fh[idx] = fp -> f_next;
else
{
while (tfp -> f_next != fp)
tfp = tfp -> f_next;
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock (&hashlock );
pthread_mutex_destroy (&fp->f_lock );
free (fp);
}
pthread_mutex_unlock (&fp->f_lock );
}
| 1
|
#include <pthread.h>
void *suma(void *rango);
pthread_mutex_t mtx;
pthread_cond_t cond;
int obtenidoRango;
pthread_attr_t attr;
int f=0;
pthread_t thread[10];
int main() {
int i=0, n=0, rango=0, *estado, pestado=0, nbytes=0, nreg=0;
estado=&pestado;
pthread_attr_init(&attr);
if((f=open("numeros.dat", O_RDONLY))==-1) {
fprintf(stderr,"Error en la apertura del fichero\\n");
return(-1);
}
nbytes=lseek(f,0,2);
nreg=nbytes/sizeof(int);
for(i=0;i<10;i++) {
obtenidoRango=0;
pthread_mutex_lock(&mtx);
pthread_create(&thread[i],&attr,suma,&rango);
while (obtenidoRango==0)
pthread_cond_wait(&cond, &mtx);
pthread_mutex_unlock(&mtx);
rango+=100;
}
for(i=0;i<10;i++) {
pthread_join(thread[i],(void **)&estado);
printf("Suma Parciales en Prog. Principal: %d\\n",*estado);
n+=*estado;
}
printf("Suma Total: %d\\n",n);
printf("Total numeros sumados: %d\\n",nreg);
close(f);
return(0);
}
void *suma(void *rango) {
int j=0, valor, *suma, num=0;
pthread_mutex_lock(&mtx);
valor=*((int *)rango);
obtenidoRango=1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mtx);
suma=(int *)malloc (sizeof (int));
*suma=0;
printf("Rango: %d a %d\\n",valor+1,valor+100);
lseek(f,valor * sizeof(int),0);
for(j=0;j<100;j++) {
read(f,&num,sizeof(int));
*suma+=num;
}
printf("\\tSuma Parcial: %d\\n",*suma);
pthread_exit(suma);
}
| 0
|
#include <pthread.h>
union mynum {
long long longlong;
double flonum;
};
int nthreads;
int pleasequit=0;
long long maxiterations=0;
pthread_mutex_t maxiter_mutex=PTHREAD_MUTEX_INITIALIZER;
void * calculate(void *param) {
double localpi=0.0;
long long threadno=((union mynum *)param)->longlong;
long long i=threadno;
long long tocheck;
pthread_mutex_lock(&maxiter_mutex);
while(!pleasequit || i<maxiterations+threadno) {
tocheck=i+1000000*nthreads;
if (tocheck>maxiterations && !pleasequit) maxiterations=tocheck;
pthread_mutex_unlock(&maxiter_mutex);
for (i; i< tocheck ; i+=nthreads) {
localpi += 1.0/(i*4.0 + 1.0);
localpi -= 1.0/(i*4.0 + 3.0);
}
fprintf(stderr, "Thread %lld working, %lld iterations passed\\n",
threadno,
i-threadno);
pthread_mutex_lock(&maxiter_mutex);
}
pthread_mutex_unlock(&maxiter_mutex);
fprintf(stderr, "Thread %lld finished, %lld iterations, partial sum %.16f\\n",
threadno,
i-threadno,
localpi);
((union mynum *)param)->flonum=localpi;
return param;
}
void handlesigint2(int sig) {
fputs("Wait, I'm quitting right now...\\n", stderr);
signal(sig, handlesigint2);
}
void handlesigint(int sig) {
pleasequit=1;
signal(sig, handlesigint2);
}
int
main(int argc, char** argv) {
double pi = 0;
int i;
pthread_t * ids;
union mynum * params;
if (argc >= 1) nthreads=atol(argv[1]);
if (nthreads < 1) {
fprintf(stderr, "usage: %s threadnum\\n", argv[0]);
exit(0);
}
signal(SIGINT, handlesigint);
params=malloc(nthreads*sizeof(union mynum));
ids=malloc(nthreads*sizeof(pthread_t));
for(i=0; i< nthreads; i++) {
params[i].longlong=i;
pthread_create(ids+i, 0, calculate, (void*)(params+i));
}
for(i=0; i<nthreads; i++) {
union mynum * res;
pthread_join(ids[i], (void **)&res);
pi+=res->flonum;
}
pi *= 4.0;
printf ("pi = %.16f\\n", pi);
return (0);
}
| 1
|
#include <pthread.h>
int counter;
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
void *doit(void *);
int main(int argc, char **argv)
{
pthread_t tidA, tidB;
pthread_create(&tidA, 0, doit, 0);
pthread_create(&tidB, 0, doit, 0);
pthread_join(tidA, 0);
pthread_join(tidB, 0);
return 0;
}
void *doit(void *vptr)
{
int i, val;
int localcnt=0;
pthread_mutex_t localmutex;
for (i = 0; i < 5000; i++) {
pthread_mutex_lock(&localmutex);
val = localcnt;
printf("%x: %d\\n", (unsigned int)pthread_self(), val+ 1);
localcnt = val + 1;
pthread_mutex_unlock(&localmutex);
}
return 0;
}
| 0
|
#include <pthread.h>
int counter = 0;
pthread_mutex_t my_mutex[5];
pthread_cond_t cond[5];
void *test_mutex(void *tid)
{
int thread_id;
int rnd;
int *tt;
tt = tid;
thread_id = (int) *tt;
rnd = rand() % 5;
sleep(rnd);
printf(" starting %d \\n",thread_id);
pthread_cond_wait( &cond[thread_id], &my_mutex[thread_id] );
counter = counter + thread_id;
thread_id, counter);
pthread_mutex_unlock(&my_mutex[thread_id]);
pthread_mutex_destroy(&my_mutex[thread_id]);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
pthread_t thread1[5];
int t;
int ec;
int thread_ids[5];
srand(time(0));
for(t=0;t<5;t++){
pthread_mutex_init(&my_mutex[t], 0);
pthread_mutex_lock(&my_mutex[t]);
}
for(t=0;t<5;t++){
pthread_cond_init(&cond[t],0);
}
for(t=0;t<5;t++){
thread_ids[t] = t;
printf("In main: creating thread %d\\n", t);
ec = pthread_create(&thread1[t], 0, test_mutex, (void *)&thread_ids[t] );
}
sleep(7);
for(t=0;t<5;t++){
sleep(1);
pthread_cond_signal(&cond[t]);
}
for(t=0;t<5;t++){
pthread_join(thread1[t], 0);
}
printf( "the results is %d \\n",counter);
for(t=0;t<5;t++){
pthread_cond_destroy( &cond[t]);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int ticketcount = 10;
pthread_mutex_t lock;
pthread_cond_t cond;
void* salewinds1(void* args)
{
while(1)
{
pthread_mutex_lock(&lock);
if(ticketcount > 0)
{
printf("windows1 start sale ticket!the ticket is:%d\\n",ticketcount);
ticketcount --;
if(ticketcount == 0)
pthread_cond_signal(&cond);
printf("sale ticket finish!,the last ticket is:%d\\n",ticketcount);
}
pthread_mutex_unlock(&lock);
sleep(1);
}
}
void* salewinds2(void* args)
{
while(1)
{
pthread_mutex_lock(&lock);
if(ticketcount > 0)
{
printf("windows2 start sale ticket!the ticket is:%d\\n",ticketcount);
ticketcount --;
if(ticketcount == 0)
pthread_cond_signal(&cond);
printf("sale ticket finish!,the last ticket is:%d\\n",ticketcount);
}
pthread_mutex_unlock(&lock);
sleep(1);
}
}
void *setticket(void *args)
{
pthread_mutex_lock(&lock);
while(1)
{
if(ticketcount > 0)
pthread_cond_wait(&cond,&lock);
ticketcount = 10;
pthread_mutex_unlock(&lock);
sleep(1);
}
pthread_exit(0);
}
main()
{
pthread_t pthid1,pthid2,pthid3;
pthread_mutex_init(&lock,0);
pthread_cond_init(&cond,0);
pthread_create(&pthid1,0, salewinds1,0);
pthread_create(&pthid2,0, salewinds2,0);
pthread_create(&pthid3,0, setticket,0);
pthread_join(pthid1,0);
pthread_join(pthid2,0);
pthread_join(pthid3,0);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error() ;
unsigned int __VERIFIER_nondet_uint();
static int top = 0;
static unsigned int arr[800];
pthread_mutex_t m;
_Bool flag = 0;
void error(void)
{
ERROR:
__VERIFIER_error();
return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
top == 0 ? 1 : 0;
}
int push(unsigned int *stack, int x)
{
if (top == 800)
{
printf("stack overflow\\n");
return -1;
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (top == 0)
{
printf("stack underflow\\n");
return -2;
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for (i = 0; i < 800; i++)
{
__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();
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 (top > 0)
{
if (pop(arr) == (-2))
error();
}
pthread_mutex_unlock(&m);
}
}
}
int main(void)
{
pthread_t id1;
pthread_t id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t destination_lock;
int mutex_init(){
pthread_mutex_init(&destination_lock, 0);
return 1;
}
int set_global_stop_array(int floor, int value){
global_stop_array[floor]=value;
return 1;
}
int get_global_stop_array(int floor){
return global_stop_array[floor];
}
int set_global_destination(int value){
pthread_mutex_lock(&destination_lock);
global_destination = value;
pthread_mutex_unlock(&destination_lock);
return 1;
}
int get_global_destination(){
pthread_mutex_lock(&destination_lock);
int temp = global_destination;
pthread_mutex_unlock(&destination_lock);
return temp;
}
int floor_to_string(int floor, char* floor_string){
if(floor>=0 && floor <= 9999){
if(floor<10){
sprintf(floor_string, "000%d", floor);
}
else if(floor<100){
sprintf(floor_string, "00%d",floor);
}
else if(floor<1000){
sprintf(floor_string, "0%d",floor);
}
else{
sprintf(floor_string, "%d",floor);
}
return 1;
}
else{
perror("Invalid floor in floor_to_string\\n");
sprintf(floor_string,"%d",-1);
return 0;
}
}
int insert_floor_into_buffer(int floor, char* buffer){
if(sizeof(buffer)<5){
printf("Invalid buffer size in insert_floor_into_buffer\\n");
return 0;
}
char floor_string[5];
floor_to_string(floor,floor_string);
for(int i=0; i<4; i++){
buffer[i+1]=floor_string[i];
}
return 1;
}
int get_floor_from_buffer(char* buffer){
if(sizeof(buffer)<5){
printf("Invalid buffer size in get_floor_from_buffer\\n");
return -1;
}
char floor_string[5];
floor_string[4]='\\0';
for(int i=0; i<4; i++){
floor_string[i]=buffer[i+1];
}
int floor = atoi(floor_string);
return floor;
}
int get_elevator_from_buffer(char* buffer){
if(sizeof(buffer)<8){
printf("Invalid buffer size in get_elevato_from_buffer: %lu\\n",sizeof(buffer));
return -1;
}
char elevator_string[5];
elevator_string[4]='\\0';
for(int i=0; i<4; i++){
elevator_string[i]=buffer[i+5];
}
int elevator = atoi(elevator_string);
return elevator;
}
int insert_elevator_into_buffer(int elevator, char* buffer){
if(sizeof(buffer)<8){
printf("Invalid buffer size in insert_elevator_into_buffer: %lu\\n", sizeof(buffer));
return -1;
}
char elevator_string[5];
floor_to_string(elevator,elevator_string);
for(int i=0; i<4; i++){
buffer[i+5]=elevator_string[i];
}
return 1;
}
| 0
|
#include <pthread.h>
bool isTimer = 0;
uint32_t g_ucsecond = 0;
bool bTImerStart = 0;
pthread_mutex_t timermutex;
void* timercounter(void* p) {
time_t old;
time_t new;
while(1) {
if(bTImerStart) {
pthread_mutex_lock(&timermutex);
old = time(0);
while(1) {
new = time(0);
if(new - old >= g_ucsecond) {
bTImerStart = 0;
isTimer = 1;
break;
}
}
pthread_mutex_unlock(&timermutex);
}
}
}
bool GetTimerStatus() {
return isTimer;
}
int settimer(uint32_t ucsecond) {
pthread_mutex_lock(&timermutex);
isTimer= 0;
bTImerStart = 1;
g_ucsecond = ucsecond;
pthread_mutex_unlock(&timermutex);
return 0;
}
int main(int argc, char** args) {
uint32_t ucsecond = 0;
uint32_t ucminute = 0;
uint32_t uchour = 0;
pthread_t tid;
uint32_t loop = 0;
pthread_mutex_init(&timermutex,0);
pthread_create(&tid, 0, timercounter, 0);
pthread_detach(tid);
while(1) {
printf("%02d:%02d:%02d ", uchour, ucminute, ucsecond);
settimer(1);
while(GetTimerStatus() != 1);
ucsecond++;
if(ucsecond == 60) {
ucsecond = 0;
ucminute++;
}
if(ucminute == 60) {
ucminute = 0;
uchour++;
}
if(uchour == 60) {
uchour =0;
}
loop = loop%185;
if (loop < 60) {
printf("100\\n");
} else if(loop >= 60 && loop < 180) {
printf("010\\n");
} else {
if (loop%2 == 0) {
printf("001\\n");
} else {
printf("000\\n");
}
}
loop++;
}
pthread_mutex_destroy(&timermutex);
}
| 1
|
#include <pthread.h>
int num;
pthread_t tid[256];
pthread_mutex_t count_mutex[256];
void *philosopher(void *arg)
{
int i = *(int *)arg;
int left_i, right_i;
if (i == 0)
left_i = num-1;
else
left_i = i-1;
right_i = i;
while (1)
{
sleep(rand()%5);
pthread_mutex_lock(&count_mutex[left_i]);
printf("Philosopher%d fetches chopstick %d\\n",i + 1, left_i + 1);
pthread_mutex_lock(&count_mutex[right_i]);
printf("Philosopher%d fetches chopstick %d\\n",i + 1, right_i + 1);
sleep(rand()%5);
pthread_mutex_unlock(&count_mutex[left_i]);
pthread_mutex_unlock(&count_mutex[right_i]);
printf("Philosopher%d releases chopsticks %d %d\\n",i + 1, left_i + 1, right_i + 1);
}
return 0;
}
int main(int argc, const char *argv[])
{
int i;
if (argc != 2)
{
printf("Input format is %s number\\n",argv[0]);
exit(1);
}
num = atoi(argv[1]);
for (i = 0; i < num; i++)
{
pthread_mutex_init(&count_mutex[i], 0);
}
for (i = 0; i < num; i++)
{
pthread_create(&tid[i], 0, philosopher, &i);
}
while (1)
{
;
}
return 0;
}
| 0
|
#include <pthread.h>
int stoj = 0, daryLovci = 0, daryZberaci = 0, ludiaVChrame = 0;
int VOLNY_CHRAM = 1, ZBERACI_DNU = 0, LOVCI_DNU = 0;
pthread_mutex_t mutexSynchronizacia = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condChram = PTHREAD_COND_INITIALIZER;
pthread_cond_t condLovci = PTHREAD_COND_INITIALIZER;
pthread_cond_t condZberaci = PTHREAD_COND_INITIALIZER;
void lov(void) {
sleep(6);
}
void dar_lov(void) {
if(stoj){
pthread_mutex_unlock(&mutexSynchronizacia);
return ;
}
pthread_mutex_lock(&mutexSynchronizacia);
while(ZBERACI_DNU || (LOVCI_DNU && ludiaVChrame >= 2)){
if(stoj){
pthread_mutex_unlock(&mutexSynchronizacia);
return ;
}
pthread_cond_wait(&condChram, &mutexSynchronizacia);
}
ludiaVChrame++;
if(ludiaVChrame == 1){
printf("LOVCI vosli do chramu \\n");
LOVCI_DNU = 1;
while(LOVCI_DNU && ludiaVChrame < 2){
if(stoj){
pthread_mutex_unlock(&mutexSynchronizacia);
return ;
}
pthread_cond_wait(&condLovci, &mutexSynchronizacia);
}
} else if(ludiaVChrame == 2){
pthread_cond_broadcast(&condLovci);
}
pthread_mutex_unlock(&mutexSynchronizacia);
sleep(2);
pthread_mutex_lock(&mutexSynchronizacia);
ludiaVChrame--;
if(ludiaVChrame == 0){
daryLovci++;
printf("LOVCI vysli von | darovali: %d krat\\n", daryLovci);
LOVCI_DNU = 0;
pthread_cond_broadcast(&condChram);
}
pthread_mutex_unlock(&mutexSynchronizacia);
}
void *lovec( void *ptr ) {
while(!stoj) {
lov();
dar_lov();
}
return 0;
}
void zber(void) {
sleep(4);
}
void dar_zber(void) {
if(stoj){
pthread_mutex_unlock(&mutexSynchronizacia);
return ;
}
pthread_mutex_lock(&mutexSynchronizacia);
while(LOVCI_DNU || (ZBERACI_DNU && ludiaVChrame >= 4)){
if(stoj){
pthread_mutex_unlock(&mutexSynchronizacia);
return ;
}
pthread_cond_wait(&condChram, &mutexSynchronizacia);
}
ludiaVChrame++;
if(ludiaVChrame == 1){
ZBERACI_DNU = 1;
printf("ZBERACI vosli do chramu\\n");
while(ZBERACI_DNU && ludiaVChrame < 4){
if(stoj){
pthread_mutex_unlock(&mutexSynchronizacia);
return ;
}
pthread_cond_wait(&condZberaci, &mutexSynchronizacia);
}
} else if(ludiaVChrame == 4){
pthread_cond_broadcast(&condZberaci);
}
pthread_mutex_unlock(&mutexSynchronizacia);
sleep(1);
pthread_mutex_lock(&mutexSynchronizacia);
ludiaVChrame--;
if(ludiaVChrame == 0){
daryZberaci++;
ZBERACI_DNU = 0;
printf("ZBERACI vysli von | darovali: %d krat\\n", daryZberaci);
pthread_cond_broadcast(&condChram);
}
pthread_mutex_unlock(&mutexSynchronizacia);
}
void *zberac( void *ptr ) {
while(!stoj) {
zber();
dar_zber();
}
return 0;
}
int main(void) {
int i;
pthread_t lovci[6];
pthread_t zberaci[12];
for (i=0;i<6;i++) pthread_create( &lovci[i], 0, &lovec, 0);
for (i=0;i<12;i++) pthread_create( &zberaci[i], 0, &zberac, 0);
sleep(30);
pthread_mutex_lock(&mutexSynchronizacia);
printf("Koniec Simulacie !!!\\n");
stoj = 1;
pthread_cond_broadcast(&condChram);
pthread_cond_broadcast(&condLovci);
pthread_cond_broadcast(&condZberaci);
pthread_mutex_unlock(&mutexSynchronizacia);
for (i=0;i<6;i++) pthread_join( lovci[i], 0);
for (i=0;i<12;i++) pthread_join( zberaci[i], 0);
printf("LOVCI - Darovali: %d krat\\n", daryLovci);
printf("ZBERACI - Darovali: %d krat\\n", daryZberaci);
exit(0);
}
| 1
|
#include <pthread.h>
pthread_cond_t stable,
workshop,
santaSleeping,
elfWaiting,
santaWaitElf;
pthread_mutex_t elfAndReindeerCount,
elfwWaitingLock;
int minWait, maxWait;
int elfCount;
int reindeerCount;
int elfDoor;
void *reindeerThread(void *args)
{
while(1)
{
reindeerHelper();
}
}
void reindeerHelper() {
pthread_mutex_lock(&elfAndReindeerCount);
int amount = ((rand() % (maxWait - minWait)) + minWait) * 1000;
printf("Reindeer on vacation.\\n");
usleep(amount);
reindeerCount++;
if (reindeerCount == 9)
{
printf("Last Reindeer is waking santa santa.\\n");
pthread_cond_signal(&santaSleeping);
pthread_cond_wait(&stable, &elfAndReindeerCount);
}
else
{
printf("Reindeer is in the stable waiting for santa.\\n");
pthread_cond_wait(&stable, &elfAndReindeerCount);
}
pthread_mutex_unlock(&elfAndReindeerCount);
}
| 0
|
#include <pthread.h>
static volatile int run_flag = 1;
pthread_mutex_t m ;
pthread_cond_t c = PTHREAD_COND_INITIALIZER;
pthread_cond_t w = PTHREAD_COND_INITIALIZER;
int done=0;
int sent=1;
float pitch_buffer[151];
float roll_buffer[151];
float avg_val[2]={0,0};
void do_when_interrupted()
{
run_flag = 0;
}
double timestamp()
{
struct timeval tv;
double sec_since_epoch;
gettimeofday(&tv, 0);
sec_since_epoch = (double) tv.tv_sec + (double) tv.tv_usec/1000000.0;
return sec_since_epoch;
}
void* read_data(void *arg)
{ NINEDOF *ninedof;
mraa_init();
ninedof = ninedof_init(A_SCALE_4G, G_SCALE_245DPS, M_SCALE_2GS);
float *pitch, *roll;
printf("collecting data in 9DOF thread\\n");
while(run_flag)
{ float pitch_avg_local=0;
float roll_avg_local=0;
pitch=calloc(151,sizeof(float));
roll=calloc(151,sizeof(float));
pitch[0]=0;
roll[0]=1;
ninedof_read(ninedof,(pitch),(roll));
int i=0;
pthread_mutex_lock(&m);
while(sent==0)
pthread_cond_wait(&w, &m);
for (i = 0; i < 151; i++)
{
pitch_avg_local=pitch_avg_local + pitch[i];
roll_avg_local=roll_avg_local + roll[i];
}
avg_val[0] = pitch_avg_local/150;
avg_val[1]=roll_avg_local/150;
printf("done collecting in 9DOF thread\\n");
sent=0;
done =1;
pthread_cond_signal(&c);
printf("pthread signal\\n");
pthread_mutex_unlock(&m);
printf("done with this iteration in 9DOF thread\\n");
free(pitch);
free(roll);
}
}
void* client_handle_connection(void *arg)
{ printf("in client \\n");
int n;
int rc;
char buffer[256];
char ready_buf[10];
double sec_since_epoch;
int i;
int client;
int server_signal;
client = *(int *)arg;
ioctl(client, FIONBIO, 0);
sprintf(ready_buf, "ready");
ready_buf[strlen(ready_buf)] = '\\0';
while (run_flag)
{
memset(buffer, 0, 256);
sec_since_epoch = timestamp();
int i;
printf("waiting\\n");
rc=pthread_mutex_lock(&m);
if(rc==EBUSY)
{
printf("lock busy\\n");
continue;
}
while (done==0)
pthread_cond_wait(&c, &m);
n = write(client, ready_buf, sizeof(ready_buf));
printf("Pitch Data: \\n");
n = read(client, buffer, sizeof(buffer));
buffer[strlen(buffer)] = '\\0';
printf("read from server(pitch): %s\\n", buffer);
if (n > 0 && strcmp(buffer, "pitch")==0)
{
printf("writing pitch buffer to server\\n");
n = write(client, avg_val, 8);
if (n < 0) {
client_error("ERROR writing to socket");
}
printf("sent pitch buffer\\n");
}
done=0;
sent = 1;
pthread_cond_signal(&w);
pthread_mutex_unlock(&m);
printf("exited from client\\n");
usleep(10000);
}
close(client);
}
int main(int argc, char *argv[])
{
int client_socket_fd;
signal(SIGINT, do_when_interrupted);
int *client;
(client_socket_fd) = client_init(argc, argv);
client=&client_socket_fd;
if (client_socket_fd < 0) {
return -1;
}
pthread_t manage_9dof_tid, manage_client_tid;
int rc;
rc = pthread_create(&manage_9dof_tid, 0, read_data, 0);
if (rc != 0) {
fprintf(stderr, "Failed to create manage_9dof thread. Exiting Program.\\n");
exit(0);
}
rc = pthread_create(&manage_client_tid, 0, client_handle_connection, (void*)client);
if (rc != 0) {
fprintf(stderr, "Failed to create thread. Exiting program.\\n");
exit(0);
}
pthread_join(manage_9dof_tid, 0);
pthread_join(manage_client_tid, 0);
printf("\\n...cleanup operations complete. Exiting main.\\n");
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_mutex_t mutex2;
void *func(void *arg)
{
while (1)
{
pthread_mutex_lock(&mutex);
usleep(100);
if (pthread_mutex_trylock(&mutex2) == 0)
{
printf("Thread 1 surpassed\\n");
pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&mutex2);
break;
}
printf("Thread 1 waiting for thread 2\\n");
pthread_mutex_unlock(&mutex);
}
return 0;
}
void *func2(void *arg)
{
while (1)
{
pthread_mutex_lock(&mutex2);
if (pthread_mutex_trylock(&mutex) == 0)
{
printf("Thread 2 surpassed\\n");
pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&mutex2);
break;
}
printf("Thread 2 waiting for thread 1\\n");
pthread_mutex_unlock(&mutex2);
}
return 0;
}
int main(int argc, char *argv[])
{
int i;
pthread_t thr[2];
pthread_create(&thr[0], 0, func, 0);
pthread_create(&thr[1], 0, func2, 0);
pthread_mutex_init(&mutex, 0);
pthread_mutex_init(&mutex2, 0);
for (i = 0 ; i < 2 ; i++)
{
pthread_join(thr[i] , 0) ;
}
return 0;
}
| 0
|
#include <pthread.h>
int ticket = -1;
int usedTickets[100000000];
int lockValue = 0;
pthread_mutex_t mutex;
void *lock(void)
{
pthread_mutex_lock(&mutex);
}
void *unlock(void)
{
pthread_mutex_unlock(&mutex);
}
void *grabATicket(void *unused) {
lock();
int i;
bool ticketsReused = 0;
for (i = 0; i < 100000000 / 16; i++) {
ticket++;
int localTicket = ticket;
if (usedTickets[localTicket])
ticketsReused = 1;
usedTickets[localTicket] = 1;
}
if (ticketsReused) puts("At least one ticket was reused.");
unlock();
return 0;
}
int main(void) {
pthread_mutex_init(&mutex, 0);
pthread_t threads[16];
pthread_t thread1, thread2;
int i;
for (i = 0; i < 16; i++)
pthread_create(&threads[i], 0, grabATicket, 0);
for (i = 0; i < 16; i++)
pthread_join(threads[i], 0);
printf("The number of tickets grabbed = %d\\n", ticket + 1);
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
int playersDone = 0;
int playTimes[10];
pthread_mutex_t entryMutex = PTHREAD_MUTEX_INITIALIZER;
void* runClient(void*);
int main(int argc, char** argv)
{
int i;
char playTimeStr[80];
pthread_t clientThreads[3];
for(i = 0; i < 10; i++){
scanf("%d", &playTimes[i]);
}
for(i = 0; i < 3; i++){
if(pthread_create(&clientThreads[i], 0, runClient, 0) != 0)
perror("Thread creation failed.");
}
for(i = 0; i < 3; i++){
if(pthread_join(clientThreads[i], 0) != 0)
perror("Thread joining failed.");
}
pthread_mutex_destroy(&entryMutex);
printf("Main thread done.\\n");
return 0;
}
void* runClient(void *ignore)
{
int curPlayerId, curPlayTime;
while(playersDone < 10){
pthread_mutex_lock(&entryMutex);
if(playersDone < 10){
curPlayerId = playersDone;
curPlayTime = playTimes[playersDone];
playersDone++;
} else {
pthread_mutex_unlock(&entryMutex);
pthread_exit(0);
}
pthread_mutex_unlock(&entryMutex);
printf("Player with ID %d playing for %d seconds...\\n",
curPlayerId,
curPlayTime);
sleep(curPlayTime);
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t mut1=PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mut2=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond3 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond4 = PTHREAD_COND_INITIALIZER;
void* op1(void* arg)
{
struct timespec tps={0, 100000}, tps0, *tpsinit=(struct timespec*)arg;
pthread_mutex_lock(&mut1);
clock_gettime(CLOCK_REALTIME, &tps0);
printf("op1 begins at %ld.%ld\\n", tps0.tv_sec-tpsinit->tv_sec, tps0.tv_nsec-tpsinit->tv_nsec);
nanosleep(&tps, 0);
pthread_mutex_unlock(&mut1);
clock_gettime(CLOCK_REALTIME, &tps0);
printf("op1 ends at %ld.%ld\\n", tps0.tv_sec-tpsinit->tv_sec, tps0.tv_nsec-tpsinit->tv_nsec);
pthread_cond_signal(&cond1);
}
void* op2(void* arg)
{
struct timespec tps={0, 10000000}, tps0, *tpsinit=(struct timespec*)arg;
pthread_mutex_lock(&mut2);
clock_gettime(CLOCK_REALTIME, &tps0);
printf("op1 begins at %ld.%ld\\n", tps0.tv_sec-tpsinit->tv_sec, tps0.tv_nsec-tpsinit->tv_nsec);
nanosleep(&tps, 0);
pthread_mutex_unlock(&mut2);
clock_gettime(CLOCK_REALTIME, &tps0);
printf("op1 ends at %ld.%ld\\n", tps0.tv_sec-tpsinit->tv_sec, tps0.tv_nsec-tpsinit->tv_nsec);
pthread_cond_signal(&cond2);
}
void* op3(void* arg)
{
struct timespec tps={0, 100000000}, tps0, *tpsinit=(struct timespec*)arg;
pthread_mutex_lock(&mut1);
pthread_cond_wait(&cond1, &mut1);
clock_gettime(CLOCK_REALTIME, &tps0);
printf("op1 begins at %ld.%ld\\n", tps0.tv_sec-tpsinit->tv_sec, tps0.tv_nsec-tpsinit->tv_nsec);
nanosleep(&tps, 0);
pthread_mutex_unlock(&mut2);
clock_gettime(CLOCK_REALTIME, &tps0);
printf("op1 ends at %ld.%ld\\n", tps0.tv_sec-tpsinit->tv_sec, tps0.tv_nsec-tpsinit->tv_nsec);
pthread_cond_signal(&cond3);
}
void* op4(void* arg)
{
struct timespec tps={0, 10000000}, tps0, *tpsinit=(struct timespec*)arg;
pthread_mutex_lock(&mut1);
pthread_t tst1, tst2;
pthread_cond_wait(&cond3, &mut1);
pthread_cond_wait(&cond2, &mut1);
clock_gettime(CLOCK_REALTIME, &tps0);
printf("op1 begins at %ld.%ld\\n", tps0.tv_sec-tpsinit->tv_sec, tps0.tv_nsec-tpsinit->tv_nsec);
nanosleep(&tps, 0);
pthread_mutex_unlock(&mut1);
clock_gettime(CLOCK_REALTIME, &tps0);
printf("op1 ends at %ld.%ld\\n", tps0.tv_sec-tpsinit->tv_sec, tps0.tv_nsec-tpsinit->tv_nsec);
pthread_cond_signal(&cond4);
}
void* op5(void* arg)
{
struct timespec tps={0, 201000000}, tps0, *tpsinit=(struct timespec*)arg;
pthread_mutex_lock(&mut1);
pthread_cond_wait(&cond4, &mut1);
clock_gettime(CLOCK_REALTIME, &tps0);
printf("op1 begins at %ld.%ld\\n", tps0.tv_sec-tpsinit->tv_sec, tps0.tv_nsec-tpsinit->tv_nsec);
nanosleep(&tps, 0);
pthread_mutex_unlock(&mut1);
clock_gettime(CLOCK_REALTIME, &tps0);
printf("op1 ends at %ld.%ld\\n", tps0.tv_sec-tpsinit->tv_sec, tps0.tv_nsec-tpsinit->tv_nsec);
}
int main(int argc, char** argv)
{
int produits, demande=strtol(argv[1], 0, 10);
struct timespec tpsinit;
clock_gettime(CLOCK_REALTIME, &tpsinit);
for(produits=0 ; produits<demande ; produits++)
{
pthread_t th1, th2, th3, th4, th5;
int ptid1=pthread_create(&th1, 0, op1, &tpsinit);
int ptid2=pthread_create(&th2, 0, op2, &tpsinit);
int ptid3=pthread_create(&th3, 0, op3, &tpsinit);
int ptid4=pthread_create(&th4, 0, op4, &tpsinit);
int ptid5=pthread_create(&th5, 0, op5, &tpsinit);
pthread_join(th5, 0);
}
return(0);
}
| 1
|
#include <pthread.h>
void add_to_global();
int global = 0;
pthread_mutex_t lock;
int main() {
int i;
int return_value;
pthread_t tid[10];
void *arg;
printf("Create threads with sleep().\\n");
return_value = pthread_mutex_init(&lock, 0);
if(return_value < 0) {
perror("Can't initialize mutex");
exit(-1);
}
for(i = 1; i <= 10; i++) {
return_value = pthread_create(&tid[i], 0, (void *)add_to_global, arg);
if(return_value < 0) {
perror("Cannot create thread.");
exit(-1);
}
}
for(i = 1; i <= 10; i++) {
pthread_join(tid[i], 0);
}
return 0;
}
void add_to_global(void* arg) {
pthread_mutex_lock(&lock);
int local;
fprintf(stderr, "Hello, I'm thread %u.\\n", (unsigned int)pthread_self());
local = global;
sleep(1);
fprintf(stderr, "Local: %d, TID: %u\\n", local, (unsigned int)pthread_self());
local += 10;
sleep(1);
fprintf(stderr, "Local: %d, TID: %u\\n", local, (unsigned int)pthread_self());
global = local;
pthread_mutex_unlock(&lock);
sleep(1);
}
| 0
|
#include <pthread.h>
static pthread_cond_t vsync;
static pthread_mutex_t vsync_lock = PTHREAD_MUTEX_INITIALIZER;
static int vsync_enabled = 0;
static struct timespec vsync_time;
static int fb_fd = -1;
static struct timespec ts_add_nsec(struct timespec* lhs, long nsec)
{
struct timespec result = *lhs;
result.tv_sec = lhs->tv_sec + (nsec / (1000*(1000*1000)));
result.tv_nsec = lhs->tv_nsec + (nsec % (1000*(1000*1000)));
if (result.tv_nsec >= (1000*(1000*1000))) {
result.tv_sec++;
result.tv_nsec -= (1000*(1000*1000));
}
return result;
}
static struct timespec ts_sub(struct timespec* lhs, struct timespec* rhs)
{
struct timespec result;
result.tv_sec = lhs->tv_sec - rhs->tv_sec;
result.tv_nsec = lhs->tv_nsec - rhs->tv_nsec;
if (result.tv_nsec < 0) {
result.tv_sec--;
result.tv_nsec += (1000*(1000*1000));
}
return result;
}
static int vsync_control(int enable)
{
int ret = 0;
clock_gettime(CLOCK_MONOTONIC, &vsync_time);
if (vsync_enabled != enable) {
if (fb_fd <= 0 || ioctl(fb_fd, MSMFB_OVERLAY_VSYNC_CTRL, &enable) < 0) {
perror("vsync control failed!");
ret = -errno;
} else {
vsync_enabled = enable;
}
}
return ret;
}
static void *vsync_loop(void *data)
{
char vsync_node_path[255];
char vdata[64];
int fd = -1;
int err = 0, len = 0;
struct timespec now, diff;
struct pollfd pfd;
snprintf(vsync_node_path, sizeof(vsync_node_path),
"/sys/class/graphics/fb%d/vsync_event", 0);
fd = open(vsync_node_path, O_RDONLY);
if (fd < 0) {
perror("unable to initialize vsync\\n");
return 0;
}
pread(fd, vdata, 64, 0);
pfd.fd = fd;
pfd.events = POLLPRI | POLLERR;
printf("%s: vsync thread started\\n", __func__);
while (1) {
err = poll(&pfd, 1, -1);
if (err <= 0) {
continue;
}
if (pfd.revents & POLLPRI) {
len = pread(pfd.fd, vdata, 64, 0);
if (len > 0) {
if (!strncmp(vdata, "VSYNC=", strlen("VSYNC="))) {
pthread_cond_signal(&vsync);
}
} else {
perror("unable to read vsync timestamp!\\n");
}
}
clock_gettime(CLOCK_MONOTONIC, &now);
diff = ts_sub(&now, &vsync_time);
if (diff.tv_sec > 0 || (diff.tv_nsec > (60 * 1000 * 1000))) {
vsync_control(0);
}
}
}
void wait_for_vsync()
{
static struct timespec now, timeout;
int ret = 0;
vsync_control(1);
clock_gettime(CLOCK_MONOTONIC, &now);
timeout = ts_add_nsec(&now, 20 * 1000 * 1000);
pthread_mutex_lock(&vsync_lock);
pthread_cond_timedwait(&vsync, &vsync_lock, &timeout);
pthread_mutex_unlock(&vsync_lock);
}
int vsync_init(int fd)
{
pthread_t vsync_thread;
int ret = 0;
fb_fd = fd;
pthread_mutex_init(&vsync_lock, 0);
pthread_cond_init(&vsync, 0);
ret = pthread_create(&vsync_thread, 0, vsync_loop, 0);
if (ret != 0) {
perror("failed to create vsync thread!");
}
return ret;
}
| 1
|
#include <pthread.h>
int m_error;
unsigned char *mapHead;
unsigned char *arenaHead;
int numBits;
int bmSize;
int memAvailable;
int numBlocksFree;
int scanner=0;
pthread_mutex_t lock;
int numNodesFreeList=0;
int memAvailable=0;
int Mem_Init(int size) {
static int initialized=0;
int pageSize;
if(initialized == 1)
{
fprintf(stderr,"Mem_Init called more than once\\n");
m_error = 1;
return -1;
}
if(size <= 0)
{
fprintf(stderr,"Mem_Init called with incorrect size\\n");
m_error = 1;
return -1;
}
pageSize= getpagesize();
if(size % pageSize != 0)
{
size = size + pageSize - (size % pageSize);
}
int fd = open("/dev/zero", O_RDWR);
void *ptr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
if (ptr == MAP_FAILED) { perror("mmap"); exit(1); }
mapHead=ptr;
bmSize= (size/16)/CHAR_BIT;
numBits=(size-bmSize)/16;
arenaHead=ptr+bmSize;
int i;
for(i=0; i<bmSize; i++)
mapHead[i]&=0;
numBlocksFree=numBits;
memAvailable=numBits*16;
close(fd);
if (pthread_mutex_init(&lock, 0) != 0)
{
fprintf(stderr,"mutex init failed\\n");
return -1;
}
initialized=1;
return 0;
}
void *Mem_Alloc(int size) {
if (size==0)
{
m_error=1;
return 0;
}
if (size % 16 != 0)
size = size + 16 - (size%16);
int blocksReq=size/16;
pthread_mutex_lock(&lock);
int available;
int i, bit;
int ctr=0;
while(ctr<numBits)
{
ctr++;
if(scanner==numBits)
scanner=0;
available=0;
for(i=0;i<blocksReq; i++)
{
bit = mapHead[ (i+scanner)/CHAR_BIT ] >> ((i+scanner)%CHAR_BIT) & 1;
if(bit!=FREE)
break;
available++;
}
if(available==blocksReq)
{
void *ptr=arenaHead+(scanner*16);
for(i=0; i<blocksReq; i++)
mapHead[(scanner+i)/CHAR_BIT]|= USED << ((scanner+i)%CHAR_BIT);
numBlocksFree-=blocksReq;
memAvailable-= blocksReq*16;
pthread_mutex_unlock(&lock);
return ptr;
}
else
scanner=scanner+available+1;
}
m_error=2;
pthread_mutex_unlock(&lock);
return 0;
}
int Mem_Free(void* ptr) {
if(ptr==0)
return -1;
int arenaIndex= (int) ( (unsigned char*)ptr - arenaHead);
int mapIndex=arenaIndex/16;
pthread_mutex_lock(&lock);
int boundarybit=mapHead[mapIndex/CHAR_BIT] >> (mapIndex%CHAR_BIT) & 1;
if(boundarybit==FREE || arenaIndex%16!=0)
{
m_error=3;
pthread_mutex_unlock(&lock);
return -1;
}
mapHead[mapIndex/CHAR_BIT] &= ~(1 << mapIndex%CHAR_BIT);
numBlocksFree+=1;
memAvailable+=1*16;
pthread_mutex_unlock(&lock);
return 0;
}
int Mem_Available() {
return memAvailable;
}
void Mem_Dump(){
printf("==================MEM DUMP=================\\n");
printf("Number of Free Blocks:%d Total free space:%d", numBlocksFree, memAvailable);
int i,bit;
for(i=0;i<numBits;i++)
{
bit=mapHead[i/CHAR_BIT] >> (i%CHAR_BIT) & 1;
printf("%d", bit);
}
printf("\\n");
}
| 0
|
#include <pthread.h>
char atravessar_corda(int num, char monte);
char atravessar_a_pra_b (int num);
char atravessar_b_pra_a (int num);
pthread_mutex_t lock_atravessar = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock_macacos_a_b_cont = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock_macacos_b_a_cont = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock_macacos_a_cont = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock_macacos_b_cont = PTHREAD_MUTEX_INITIALIZER;
int macacos_a_cont = 0;
int macacos_b_cont = 0;
int macacos_a_b_cont = 0;
int macacos_b_a_cont = 0;
void * macaco(void * arg){
char monte = 'a';
int num = *((int*)arg);
int atravessar;
while(1){
atravessar = rand()%10;
if(atravessar<2){
if(monte == 'a'){
monte = atravessar_a_pra_b(num);
}else{
monte = atravessar_b_pra_a(num);
}
}else{
sleep(10);
}
}
}
char atravessar_a_pra_b (int num){
printf("Macaco %d - Quer ir de A para B\\n",num);
pthread_mutex_lock(&lock_macacos_a_b_cont);
macacos_a_b_cont++;
if(macacos_a_b_cont == 1){
pthread_mutex_lock(&lock_atravessar);
}
pthread_mutex_lock(&lock_macacos_a_cont);
macacos_a_cont--;
pthread_mutex_unlock(&lock_macacos_a_b_cont);
pthread_mutex_unlock(&lock_macacos_a_cont);
printf("Macaco %d - Atravessando de A para B\\n",num);
sleep(5);
pthread_mutex_lock(&lock_macacos_a_b_cont);
macacos_a_b_cont--;
printf("Macacos - Número de macacos atravessando de A para B %d\\n",macacos_a_b_cont);
if(macacos_a_b_cont == 0){
pthread_mutex_unlock(&lock_atravessar);
}
pthread_mutex_lock(&lock_macacos_b_cont);
macacos_b_cont++;
printf("Macacos - Número de macacos em A %d\\n",macacos_a_cont);
printf("Macacos - Número de macacos em B %d\\n",macacos_b_cont);
pthread_mutex_unlock(&lock_macacos_a_b_cont);
pthread_mutex_unlock(&lock_macacos_b_cont);
printf("Macaco %d - Atravessou de A para B\\n",num);
return 'b';
}
char atravessar_b_pra_a (int num){
printf("Macaco %d - Quer ir de B para A\\n",num);
pthread_mutex_lock(&lock_macacos_b_a_cont);
macacos_b_a_cont++;
if(macacos_b_a_cont == 1){
pthread_mutex_lock(&lock_atravessar);
}
pthread_mutex_lock(&lock_macacos_b_cont);
macacos_b_cont--;
pthread_mutex_unlock(&lock_macacos_b_a_cont);
pthread_mutex_unlock(&lock_macacos_b_cont);
printf("Macaco %d - Atravessando de B para A\\n",num);
sleep(5);
pthread_mutex_lock(&lock_macacos_b_a_cont);
macacos_b_a_cont--;
printf("Macacos - Número de macacos atravessando de B para A %d\\n",macacos_b_a_cont);
if(macacos_b_a_cont == 0){
pthread_mutex_unlock(&lock_atravessar);
}
pthread_mutex_lock(&lock_macacos_a_cont);
macacos_a_cont++;
printf("Macacos - Número de macacos em A %d\\n",macacos_a_cont);
printf("Macacos - Número de macacos em B %d\\n",macacos_b_cont);
pthread_mutex_unlock(&lock_macacos_b_a_cont);
pthread_mutex_unlock(&lock_macacos_a_cont);
printf("Macaco %d - Atravessou de B para A\\n",num);
return 'a';
}
int main(){
pthread_t m[20];
int i;
int *id;
srand((unsigned)time(0));
macacos_a_cont = (int)20;
for(i = 0; i < 20; i++){
id = (int*) malloc(sizeof(int));
*id = i;
pthread_create(&m[i], 0, macaco, (void *) (id));
}
pthread_join(m[0],0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
void* thread_worker(void*);
void critical_section(int thread_num, int i);
int main(void) {
int rtn, i;
pthread_t pthread_id = 0;
rtn = pthread_create(&pthread_id, 0,
thread_worker, 0 );
if(rtn != 0) {
printf("pthread_create ERROR!\\n");
return -1;
}
for (i=0; i<10000; i++) {
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2);
critical_section(1, i);
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
}
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
return 0;
}
void* thread_worker(void* p) {
int i;
for (i=0; i<10000; i++) {
pthread_mutex_trylock(&mutex2);
pthread_mutex_trylock(&mutex1);
critical_section(2, i);
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
}
}
void critical_section(int thread_num, int i) {
printf("Thread%d: %d\\n", thread_num, i);
}
| 0
|
#include <pthread.h>
void list_init(struct list_descriptor *list) {
list->head = list->tail = 0;
list->list_len = 0;
pthread_mutex_init(&(list->list_lock),0);
pthread_cond_init(&(list->list_newnode),0);
}
void *list_head(struct list_descriptor *list) {
void *ret;
struct list_node *nextnode;
pthread_mutex_lock(&(list->list_lock));
if (list->head == 0) {
pthread_cond_wait(&(list->list_newnode),&(list->list_lock));
}
ret = list->head->data;
nextnode = list->head->next;
free(list->head);
list->head = nextnode;
list->list_len--;
pthread_mutex_unlock(&(list->list_lock));
return ret;
}
void list_append(struct list_descriptor *list, void *data) {
struct list_node *node;
node = (struct list_node *)malloc(sizeof(struct list_node));
node->next = 0;
node->data = data;
pthread_mutex_lock(&(list->list_lock));
if (list->head == 0) {
list->head = list->tail = node;
}
else {
list->tail->next = node;
list->tail = list->tail->next;
}
list->list_len++;
pthread_mutex_unlock(&(list->list_lock));
pthread_cond_signal(&(list->list_newnode));
}
void *list_find(struct list_descriptor *list, int (*compare)(void*, void *), void *comparedata) {
struct list_node *current;
void *ret;
pthread_mutex_lock(&(list->list_lock));
current = list->head;
ret = 0;
while (current != 0) {
if (compare(current->data,comparedata)) {
ret = current->data;
break;
}
current = current->next;
}
pthread_mutex_unlock(&(list->list_lock));
return ret;
}
void *list_find_del(struct list_descriptor *list, int (*compare)(void*, void *), void *comparedata) {
struct list_node *current, *back;
void *ret;
pthread_mutex_lock(&(list->list_lock));
current = list->head;
ret = 0;
if (current)
if (compare(current->data,comparedata))
ret = list_head(list);
else
while (1) {
back = current;
current = current->next;
if (!current)
break;
if (compare(current->data,comparedata)) {
ret = current->data;
back->next = current->next;
free(current);
break;
}
}
pthread_mutex_unlock(&(list->list_lock));
return ret;
}
| 1
|
#include <pthread.h>
pthread_mutex_t I2Clock;
int i2c_device = 0;
int i2c_init(uint8_t addr) {
if(pthread_mutex_init(&I2Clock, 0)) {
printf("ERROR : cannot create mutex\\n");
return -2;
}
i2c_device = wiringPiI2CSetup(addr);
return i2c_device;
}
uint8_t I2Cread8(uint8_t addr, uint8_t reg) {
uint8_t result;
if(i2c_device <= 0) {
if(i2c_init(addr) < 0) {
printf("I2Cread8 : ERROR cannot open device\\n");
return -1;
}
} else if(ioctl(i2c_device, 0x0703, addr)<0) {
printf("I2Cread8 : ERROR cannot connect to selected device at address 0x%x\\n", addr);
return -2;
}
pthread_mutex_lock(&I2Clock);
result = wiringPiI2CReadReg8 (i2c_device, reg);
pthread_mutex_unlock(&I2Clock);
return result;
}
uint16_t I2Cread16(uint8_t addr, uint8_t reg) {
uint16_t result;
if(i2c_device <= 0) {
if(i2c_init(addr) < 0) {
printf("I2Cread16 : ERROR cannot open device\\n");
return -1;
}
} else if(ioctl(i2c_device, 0x0703, addr)<0) {
printf("I2Cread16 : ERROR cannot connect to selected device at address 0x%x\\n", addr);
return -2;
}
pthread_mutex_lock(&I2Clock);
result = wiringPiI2CReadReg16 (i2c_device, reg);
pthread_mutex_unlock(&I2Clock);
return result;
}
uint32_t I2Cread32(uint8_t addr, uint8_t reg) {
uint32_t result;
result = I2Cread16(addr, reg);
result += I2Cread16(addr, reg + 2) << 16;
return result;
}
float I2CreadFloat(uint8_t addr, uint8_t reg) {
uint32_t result_as_int = I2Cread32(addr, reg);
float result;
memcpy(&result, &result_as_int, sizeof(result_as_int));
return result;
}
static void releaseI2Clock() {
pthread_mutex_unlock(&I2Clock);
}
int I2Cwrite8(uint8_t addr, uint8_t reg, uint8_t value) {
int result;
if(i2c_device <= 0) {
if(i2c_init(addr) < 0) {
printf("I2Cwrite8 : ERROR cannot open device\\n");
return -1;
}
} else if(ioctl(i2c_device, 0x0703, addr)<0) {
printf("I2Cwrite8 : ERROR cannot connect to selected device at address 0x%x\\n", addr);
return -2;
}
pthread_mutex_lock(&I2Clock);
result = wiringPiI2CWriteReg8 (i2c_device, reg, value);
scheduleIn(2, releaseI2Clock);
return result;
}
int I2Cwrite16(uint8_t addr, uint8_t reg, uint16_t value) {
int result;
if(i2c_device <= 0) {
if(i2c_init(addr) < 0) {
printf("I2Cwrite16 : ERROR cannot open device\\n");
return -1;
}
} else if(ioctl(i2c_device, 0x0703, addr)<0) {
printf("I2Cwrite16 : ERROR cannot connect to selected device at address 0x%x\\n", addr);
return -2;
}
pthread_mutex_lock(&I2Clock);
result = wiringPiI2CWriteReg16(i2c_device, reg, value);
scheduleIn(2, releaseI2Clock);
return result;
}
int I2Cwrite32(uint8_t addr, uint8_t reg, uint32_t value) {
I2Cwrite16(addr, reg, value);
return I2Cwrite16(addr, reg + 2, value >> 16);
}
int I2CwriteFloat(uint8_t addr, uint8_t reg, float value){
uint32_t to_send;
memcpy(&to_send, &value, sizeof(value));
return I2Cwrite32(addr, reg, to_send);
}
| 0
|
#include <pthread.h>
static int tun_open(void)
{
if (!*server.tundev)
return -1;
if ((server.tunfd = open(server.tundev, O_RDWR)) < 0)
return -1;
return 0;
}
struct in6_ifreq {
struct in6_addr ifr6_addr;
__u32 ifr6_prefixlen;
int ifr6_ifindex;
};
static int tun_alloc(void)
{
struct ifreq ifr;
int fd, err;
if ((fd = open("/dev/net/tun", O_RDWR)) < 0)
return tun_open();
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_flags = IFF_TUN;
if (*server.tundev)
strncpy(ifr.ifr_name, server.tundev, IFNAMSIZ);
if ((err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0) {
perror("Allocate tundev");
close(fd);
return err;
}
strcpy(server.tundev, ifr.ifr_name);
server.tunfd = fd;
return 0;
}
static int tun_linux_setaddr(void)
{
char errbuf[64];
struct in6_ifreq ifr6;
struct ifreq ifr;
int fd;
memcpy((char *) &ifr6.ifr6_addr, (char *) &server.v6sockaddr.sin6_addr,
sizeof(struct in6_addr));
fd = socket(AF_INET6, SOCK_DGRAM, 0);
if (fd < 0) {
tspslog(LOG_ERR, "No support for INET6 on this system");
return -1;
}
strcpy(ifr.ifr_name, server.tundev);
if (ioctl(fd, SIOGIFINDEX, &ifr) < 0) {
strerror_r(errno, errbuf, sizeof(errbuf));
tspslog(LOG_ERR, "Getting interface index error: %s", errbuf);
return -1;
}
ifr6.ifr6_ifindex = ifr.ifr_ifindex;
ifr6.ifr6_prefixlen = server.v6prefixlen;
if (ioctl(fd, SIOCSIFADDR, &ifr6) < 0) {
strerror_r(errno, errbuf, sizeof(errbuf));
tspslog(LOG_ERR, "Setting interface address error: %s", errbuf);
return -1;
}
strcpy(ifr.ifr_name, server.tundev);
if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) {
strerror_r(errno, errbuf, sizeof(errbuf));
tspslog(LOG_ERR, "Getting interface flags error: %s", errbuf);
return -1;
}
strcpy(ifr.ifr_name, server.tundev);
ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
if (ioctl(fd, SIOCSIFFLAGS, &ifr) < 0) {
strerror_r(errno, errbuf, sizeof(errbuf));
tspslog(LOG_ERR, "Setting interface flags error: %s", errbuf);
return -1;
}
return 0;
}
int tun_setaddr(void)
{
return tun_linux_setaddr();
}
int bind_tunif(void)
{
return tun_alloc();
}
static pthread_mutex_t tun_lock = PTHREAD_MUTEX_INITIALIZER;
void tun_read(void *data, ssize_t *len)
{
struct tun_pi *pi = (struct tun_pi *)data;
struct ip6_hdr *ip6 = (struct ip6_hdr *)(pi + 1);
static const int hdrlen = sizeof(struct tun_pi) + sizeof(struct ip6_hdr);
int offset = 0, datalen = 0;
pthread_mutex_lock(&tun_lock);
memset(data, 0xFF, PHDRSZ + MTU);
do {
*len = read(server.tunfd, data + offset, PHDRSZ + MTU - offset);
if (*len == -1 &&
errno != EAGAIN && errno != EINTR) {
tspslog(LOG_ERR, "Fail to read from server tun interface");
exit(1);
}
if (*len > 0)
offset += *len;
if (datalen == 0 && offset >= hdrlen) {
if (ntohs(pi->proto) != ETH_P_IPV6)
break;
datalen = ntohs(ip6->ip6_plen) + hdrlen;
}
} while (*len <= 0 || datalen == 0 || offset < datalen);
pthread_mutex_unlock(&tun_lock);
}
void tun_write(void *data, size_t len)
{
struct tun_pi *pi;
int rc, offset = 0;
if (sizeof(struct tun_pi) > PHDRSZ) {
tspslog(LOG_ERR, "Preserved header space not enough");
exit(1);
}
pi = (struct tun_pi *)((uint8_t *)data - sizeof(struct tun_pi));
len += sizeof(struct tun_pi);
pi->flags = 0;
pi->proto = htons(ETH_P_IPV6);
pthread_mutex_lock(&tun_lock);
do {
rc = write(server.tunfd, ((void *)pi) + offset, len - offset);
if (rc == -1 &&
errno != EAGAIN && errno != EINTR) {
tspslog(LOG_ERR, "Fail to write to server tun interface");
break;
}
if (rc > 0)
offset += rc;
} while (rc <= 0 || offset < len);
pthread_mutex_unlock(&tun_lock);
}
| 1
|
#include <pthread.h>
int global=0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void*wait1(void*p){
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
global=1;
pthread_mutex_unlock(&mutex);
}
void*wait2(void*p){
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
global=2;
pthread_mutex_unlock(&mutex);
}
void*sig1(void*p){
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond);
global=3;
pthread_mutex_unlock(&mutex);
}
void*sig2(void*p){
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond);
global=4;
pthread_mutex_unlock(&mutex);
}
int main(int argc, char **argv)
{
pthread_t tid[4];
pthread_create(&tid[0], 0, wait1, 0);
pthread_create(&tid[1], 0, wait2, 0);
pthread_create(&tid[2], 0, sig1, 0);
pthread_create(&tid[3], 0, sig2, 0);
pthread_join(tid[0], 0);
pthread_join(tid[1], 0);
pthread_join(tid[2], 0);
pthread_join(tid[3], 0);
printf("GLOBAL:%d\\n",global);
return 0;
}
| 0
|
#include <pthread.h>
char buf[4];
int occupied;
int nextin, nextout;
pthread_mutex_t mutex;
pthread_cond_t more;
pthread_cond_t less;
} buffer_t;
buffer_t buffer;
void * producer(void *);
void * consumer(void *);
pthread_t tid[2];
main( int argc, char *argv[] )
{
int i;
pthread_cond_init(&(buffer.more), 0);
pthread_cond_init(&(buffer.less), 0);
pthread_create(&tid[1], 0, consumer, 0);
pthread_create(&tid[0], 0, producer, 0);
for ( i = 0; i < 2; i++)
pthread_join(tid[i], 0);
printf("\\nmain() reporting that all %d threads have terminated\\n", i);
}
void * producer(void * parm)
{
char item[30]="IT'S A SMALL WORLD, AFTER ALL.";
int i;
printf("producer started.\\n");
for(i=0;i<30;i++)
{
if (item[i] == '\\0') break;
pthread_mutex_lock(&(buffer.mutex));
if (buffer.occupied >= 4) printf("producer waiting.\\n");
while (buffer.occupied >= 4)
pthread_cond_wait(&(buffer.less), &(buffer.mutex) );
printf("producer executing.\\n");
buffer.buf[buffer.nextin++] = item[i];
buffer.nextin %= 4;
buffer.occupied++;
pthread_cond_signal(&(buffer.more));
pthread_mutex_unlock(&(buffer.mutex));
}
printf("producer exiting.\\n");
pthread_exit(0);
}
void * consumer(void * parm)
{
char item;
int i;
printf("consumer started.\\n");
for(i=0;i<30;i++){
pthread_mutex_lock(&(buffer.mutex) );
if (buffer.occupied <= 0) printf("consumer waiting.\\n");
while(buffer.occupied <= 0)
pthread_cond_wait(&(buffer.more), &(buffer.mutex) );
printf("consumer executing.\\n");
item = buffer.buf[buffer.nextout++];
printf("%c\\n",item);
buffer.nextout %= 4;
buffer.occupied--;
pthread_cond_signal(&(buffer.less));
pthread_mutex_unlock(&(buffer.mutex));
}
printf("consumer exiting.\\n");
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
pthread_key_t key;
int counter;
void print(void)
{
char *string = (char*)pthread_getspecific(key);
printf("%s", string);
}
void *thread(void *arg)
{
int number;
pthread_mutex_lock(&mutex);
number = counter; counter++;
pthread_mutex_unlock(&mutex);
pthread_setspecific(key, ((char**)arg)[number]);
if(!number)
{
print();
pthread_cond_signal(&cond);
}
else
{
pthread_cond_wait(&cond);
print();
}
return(0);
}
int main()
{
char* strings[] = {"hello ", "world\\n"};
pthread_t thread1, thread2;
pthread_init();
mutex = PTHREAD_MUTEX_INITIALIZER;
cond = PTHREAD_COND_INITIALIZER;
pthread_key_create(&key, 0);
counter = 0;
pthread_create(&thread1, 0, thread, strings);
pthread_create(&thread2, 0, thread, strings);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
return(0);
}
| 0
|
#include <pthread.h>
int balance = 1000;
pthread_mutex_t mutx = PTHREAD_MUTEX_INITIALIZER;
void *deposit(void *arg)
{
int amt = 50, i;
for(i=0; i<50; i++)
{
pthread_mutex_lock(&mutx);
balance = balance + amt;
pthread_mutex_unlock(&mutx);
}
return 0;
}
void *withdraw(void *arg)
{
int amt = 20, i;
for(i=0; i<20; i++)
{
pthread_mutex_lock(&mutx);
balance = balance - amt;
pthread_mutex_unlock(&mutx);
}
return 0;
}
int main()
{
pthread_t t1, t2;
int ret;
ret = pthread_create(&t1, 0, deposit, 0);
if(ret != 0)
{
printf("Thread Create Error.\\n");
return 0;
}
ret = pthread_create(&t2, 0, withdraw, 0);
if(ret != 0)
{
printf("Thread Create Error.\\n");
return 0;
}
ret = pthread_join(t1, 0);
if(ret != 0)
{
printf("Thread Join Error.\\n");
return 0;
}
ret = pthread_join(t2, 0);
if(ret != 0)
{
printf("Thread Join Error.\\n");
return 0;
}
printf("Balance is : %d\\n", balance);
return 0;
}
| 1
|
#include <pthread.h>
unsigned int read_load = 0;
unsigned int write_load = 0;
pthread_mutex_t read_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t write_mutex = PTHREAD_MUTEX_INITIALIZER;
void * disk_load_checker(void * dev)
{
int last_read_bytes, last_write_bytes;
int old_state, old_type;
char * dev_name = (char *) dev;
char root_dev[4];
char stat_file_path[256];
memcpy(root_dev, &dev_name[5], 3);
root_dev[3] = '\\0';
sprintf(stat_file_path, "/sys/block/%s/stat", root_dev);
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_state);
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &old_type);
while (1)
{
FILE * fp;
int read_bytes_increment, write_bytes_increment;
if((fp = fopen(stat_file_path, "r")) != 0)
{
char val[32];
int i, read_bytes, write_bytes;
for (i = 0 ; i < 11 ; i++)
{
fscanf(fp, "%s", val);
if (i == 2)
{
read_bytes = atoi(val);
} else if (i == 6)
{
write_bytes = atoi(val);
}
}
read_bytes_increment = (read_bytes - last_read_bytes) * 512;
write_bytes_increment = (write_bytes - last_write_bytes) * 512;
last_read_bytes = read_bytes;
last_write_bytes = write_bytes;
fclose(fp);
}
pthread_mutex_lock(&read_mutex);
pthread_mutex_lock(&write_mutex);
read_load = (unsigned int)(read_bytes_increment / 1024);
write_load = (unsigned int)(write_bytes_increment / 1024);
pthread_mutex_unlock(&read_mutex);
pthread_mutex_unlock(&write_mutex);
sleep(1);
pthread_testcancel();
}
return 0;
}
int get_current_load(enum op_type load)
{
int result = 0;
switch (load)
{
case READ:
pthread_mutex_lock(&read_mutex);
result = read_load;
pthread_mutex_unlock(&read_mutex);
break;
case WRITE:
pthread_mutex_lock(&write_mutex);
result = write_load;
pthread_mutex_unlock(&write_mutex);
break;
}
return result;
}
int check_load_available(struct ac_data data, unsigned int bytes, enum op_type load)
{
int result;
unsigned int current_load = get_current_load(load);
unsigned int disk_speed;
unsigned int required_kb = bytes * 1024;
switch(load)
{
case READ:
disk_speed = (int)(data.disk_read_speed * 1024);
break;
case WRITE:
disk_speed = (int)(data.disk_write_speed * 1024);
break;
}
if (disk_speed - current_load >= required_kb)
{
result = 1;
} else
{
result = 0;
}
return result;
}
int get_disk_data(struct ac_data * data)
{
FILE *fp;
if ((fp = popen("dd if=/dev/zero of=/tmp/output bs=250k count=1024 oflag=direct 2>&1 | tail -n1 | awk '{print $8}'",
"r")) != 0)
{
char response[32];
fscanf(fp, "%s", response);
fclose(fp);
data->disk_write_speed = atoi(response);
} else
{
return -errno;
}
if ((fp = popen("/sbin/sysctl -w vm.drop_caches=3", "r")) == 0)
{
return -errno;
} else
{
fclose(fp);
}
if ((fp = popen("dd if=/tmp/output of=/dev/null bs=250k count=1024 iflag=direct 2>&1 | tail -n1 | awk '{print $8 }'",
"r")) != 0)
{
char response[32];
fscanf(fp, "%s", response);
fclose(fp);
data->disk_read_speed = atoi(response);
} else
{
return -errno;
}
remove("/tmp/output");
return 0;
}
int get_device_name(const char * root_dir, char * dev)
{
int result;
FILE * fp;
char cmd[256];
sprintf(cmd, "df %s | tail -n1 | awk '{print $1}'", root_dir);
if ((fp = popen(cmd, "r")) != 0)
{
fscanf(fp, "%s", dev);
fclose(fp);
} else
{
result = -errno;
}
return result;
}
| 0
|
#include <pthread.h>
char buf[200] = {0};
pthread_mutex_t mutex;
pthread_cond_t cond;
unsigned int flag = 0;
void *func(void *arg)
{
while (flag == 0)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
printf("本次输入了%d个字符\\n", strlen(buf));
memset(buf, 0, sizeof(buf));
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main(void)
{
int ret = -1;
pthread_t th = -1;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
ret = pthread_create(&th, 0, func, 0);
if (ret != 0)
{
printf("pthread_create error.\\n");
exit(-1);
}
printf("输入一个字符串,以回车结束\\n");
while (1)
{
scanf("%s", buf);
pthread_cond_signal(&cond);
if (!strncmp(buf, "end", 3))
{
printf("程序结束\\n");
flag = 1;
break;
}
}
printf("等待回收子线程\\n");
ret = pthread_join(th, 0);
if (ret != 0)
{
printf("pthread_join error.\\n");
exit(-1);
}
printf("子线程回收成功\\n");
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
| 1
|
#include <pthread.h>
int producer_keep_running = 1;
pthread_mutex_t lock;
pthread_cond_t emptycond;
pthread_cond_t filledcond;
struct pid_node{
char* pid_str;
struct pid_node *next_node;
};
struct the_queue{
pid_node head_node;
int queue_current_size;
int queue_max_size;
unsigned int filled;
} pid_queue;
void insertPID(char* pid){
pid_node new_p_node = (pid_node) malloc(sizeof(struct pid_node));
new_p_node->pid_str = pid;
new_p_node->next_node = pid_queue.head_node;
pid_queue.head_node = new_p_node;
pid_queue.queue_current_size++;
if (pid_queue.queue_current_size == pid_queue.queue_max_size)
pid_queue.filled = 1;
else
pid_queue.filled = 0;
}
char* removePID(){
pid_node pnode = pid_queue.head_node;
pid_queue.head_node = pnode->next_node;
pid_queue.queue_current_size--;
if (pid_queue.queue_current_size == 0)
pid_queue.filled = 0;
return pnode->pid_str;
}
void queue_filler(){
char* pid;
const char *prefix = "12345/";
const char charset[] = "ABCDEFGHIJKLMNOPQRSTUVXYZ1234567890";
int i, key;
while(!pid_queue.filled){
pid = (char*) malloc(((6 + 14)+1)*sizeof(char));
strncpy(pid,prefix,6);
for (i = 6; i < (6 + 14); i++) {
key = rand() % (int) (sizeof charset - 1);
if (i == 10 || i == 15)
pid[i] = '-';
else
pid[i] = charset[key];
}
pid[(6 + 14)] = '\\0';
insertPID(pid);
}
printf("Producer is done with filling the queue\\n");
}
char* getPID(){
char *pid;
pthread_mutex_lock(&lock);
while(!pid_queue.filled)
{
pthread_cond_wait(&filledcond, &lock);
}
pid = removePID();
if(!pid_queue.filled)
pthread_cond_signal(&emptycond);
pthread_mutex_unlock(&lock);
return pid;
}
void putPID(){
while(producer_keep_running)
{
pthread_mutex_lock(&lock);
while(pid_queue.filled)
{
pthread_cond_wait(&emptycond,&lock);
}
queue_filler();
pthread_cond_broadcast(&filledcond);
pthread_mutex_unlock(&lock);
}
}
void* pid_consumer(void* cid){
int i;
int pid_element;
long c_id = (long)cid;
char *pid_list[500];
printf("consumer[%ld] started to ask for PIDs\\n",c_id);
for(i = 0; i < 500;i++)
pid_list[i] = getPID();
pid_element = rand() % (int) (500 - 1);
printf("cosumer[%ld] got his %d PIDs, PID[%d] = %s \\n",c_id,500,pid_element,pid_list[pid_element]);
pthread_exit(0);
}
void* pid_producer(){
putPID();
pthread_exit(0);
}
void init_pid_queue(){
pid_queue.filled = 0;
pid_queue.queue_max_size = 1000;
pid_queue.queue_current_size = 0;
}
void init_pthread_variables(){
pthread_mutex_init(&lock,0);
pthread_cond_init(&emptycond,0);
pthread_cond_init(&filledcond,0);
}
int main(int argc, const char * argv[]) {
long i;
pthread_t consumer_threads[10];
pthread_t producer_thread;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
init_pthread_variables();
init_pid_queue();
for (i = 0;i < 10;i++){
pthread_create(&consumer_threads[i], &attr, pid_consumer, (void *)i);
}
pthread_create(&producer_thread, &attr, pid_producer,0);
for(i=0; i<10; i++)
pthread_join(consumer_threads[i], 0);
producer_keep_running = 0;
return 0;
}
| 0
|
#include <pthread.h>
char **P;
pthread_mutex_t m;
pthread_cond_t cond;
} Est;
Est *E = 0;
void myInit(){
if(E == 0){
E = (Est*)malloc(sizeof(Est));
pthread_mutex_init(&E->m, 0);
pthread_cond_init(&E->cond, 0);
E->P = (char**)malloc(5*sizeof(char*));
}
}
int ubicar(char *nom, int k){
myInit();
int f = -1;
int c = 0;
for(int i=0; i<5; i++){
if(E->P[i]==0){
c++;
if(c==k){
f=i+1-c;
return f;
}
}
else {
c=0; f=-1;
}
}
return f;
}
int reservar(char *nom, int k){
myInit();
pthread_mutex_lock(&E->m);
int p = ubicar(nom,k);
while((p = ubicar(nom,k)) == -1){
pthread_cond_wait(&E->cond,&E->m);
}
for(int i = 0; i<k;i++){
E->P[p+i] = (char*)malloc(strlen(nom)+1);
strcpy(E->P[p+i], nom);
}
pthread_cond_broadcast(&E->cond);
pthread_mutex_unlock(&E->m);
return p;
}
void liberar(char *nom){
pthread_mutex_lock(&E->m);
for(int i=0; i<5;i++){
if(E->P[i] != 0){
if(strcmp(E->P[i],nom)==0){
free(E->P[i]);
E->P[i] = 0;
}
}
}
pthread_cond_broadcast(&E->cond);
pthread_mutex_unlock(&E->m);
}
void printE(){
for(int i=0;i<5;i++){
printf("[%s]",E->P[i]);
}
printf("\\n");
}
| 1
|
#include <pthread.h>
int verbosity;
pthread_mutex_t mutex;
} __plugin_logging_t__;
static __plugin_logging_t__ __plugin_loging_data__;
int __lock_plugin_logging__(void)
{
pthread_mutex_lock(&__plugin_loging_data__.mutex);
return __plugin_loging_data__.verbosity;
}
void __unlock_plugin_logging__(void)
{
pthread_mutex_unlock(&__plugin_loging_data__.mutex);
}
void init_plugin_logging(int verbosity)
{
__plugin_loging_data__.verbosity = verbosity;
pthread_mutex_init(&__plugin_loging_data__.mutex, 0);
}
void clear_plugin_logging(void)
{
pthread_mutex_destroy(&__plugin_loging_data__.mutex);
}
size_t string_array_len(const char *array[])
{
size_t i = 0;
if (array) {
while (array[i])
++i;
}
return i;
}
char ** clone_string_array(const char *array[])
{
size_t i;
size_t array_len = string_array_len(array);
size_t string_len = 0;
char **new_array = (char**)malloc(sizeof(char*) * (array_len + 1));
new_array[array_len] = 0;
for (i = 0; i < array_len; i++) {
string_len = strlen(array[i]);
new_array[i] = (char*)malloc(sizeof(char) * (string_len + 1));
memcpy(new_array[i], array[i], string_len);
new_array[i][string_len] = '\\0';
}
return new_array;
}
void free_cloned_string_array(char *array[])
{
size_t i;
for (i = 0; array[i]; i++)
free(array[i]);
free(array);
}
const char * get_openvpn_env(const char *name, const char *envp[])
{
size_t i;
const size_t namelen = strlen(name);
const char *cp = 0;
if (envp) {
for (i = 0; envp[i]; i++) {
if(!strncmp(envp[i], name, namelen)) {
cp = envp[i] + namelen;
if ( *cp == '=' )
return cp + 1;
}
}
}
return 0;
}
static unsigned char is_in_list(const char *value, size_t value_len, const char *exclude[])
{
size_t i;
if (!exclude)
return 0;
for (i = 0; exclude[i]; i++) {
if (!strncmp(value, exclude[i], value_len))
return 1;
}
return 0;
}
char * openvpn_envp_to_json(const char *envp[], const char *exclude[])
{
size_t i, j;
size_t buffer_size = 0;
size_t buffer_pos = 0;
const size_t str_space = 15;
char *json_str;
const char *value_pos;
if (!envp)
return 0;
for (i = 0; envp[i]; i++)
buffer_size += strlen(envp[i]) + str_space;
json_str = (char*)malloc(sizeof(char) * buffer_size);
memset(json_str, 0, buffer_size);
json_str[buffer_pos] = '{'; buffer_pos++;
for (i = 0; envp[i]; i++) {
value_pos = 0;
for (j = 0; envp[i][j]; j++) {
if (envp[i][j] == '=') {
value_pos = envp[i] + j + 1;
break;
}
}
if (!value_pos)
continue;
if (is_in_list(envp[i], j, exclude))
continue;
if (buffer_pos != 1) {
json_str[buffer_pos] = ','; buffer_pos++;
json_str[buffer_pos] = ' '; buffer_pos++;
}
json_str[buffer_pos] = '\\"'; buffer_pos++;
memcpy(json_str + buffer_pos, envp[i], j);
buffer_pos += j;
json_str[buffer_pos] = '\\"'; buffer_pos++;
json_str[buffer_pos] = ':'; buffer_pos++;
json_str[buffer_pos] = '\\"'; buffer_pos++;
memcpy(json_str + buffer_pos, value_pos, strlen(value_pos));
buffer_pos += strlen(value_pos);
json_str[buffer_pos] = '\\"'; buffer_pos++;
}
json_str[buffer_pos] = '}'; buffer_pos++;
return json_str;
}
| 0
|
#include <pthread.h>
pthread_mutex_t print_mutex;
pthread_mutex_t wait_chairs_mutex;
int wait_chairs_open = 5;
pthread_cond_t wait_chairs_cv;
sem_t customer;
sem_t barber;
void getHairCut (void *t) {
long my_id = *(long *)t;
pthread_mutex_lock (&print_mutex);
printf ("Customer: %c is getting a hair cut\\n", my_id);
pthread_mutex_unlock (&print_mutex);
}
void balk (void *t) {
long my_id = *(long *)t;
pthread_mutex_lock (&print_mutex);
printf ("Customer: %c is balking, walking away!\\n", my_id);
pthread_mutex_unlock (&print_mutex);
pthread_exit(0);
}
void cutHair (void *t) {
long my_id = (long)t;
int busyTime;
pthread_mutex_lock (&print_mutex);
printf ("Barber is doing a hair cut\\n");
pthread_mutex_unlock (&print_mutex);
srand(time(0));
busyTime = (rand() % 2);
sleep(busyTime);
}
void *barberTask (void *t) {
long my_id = (long)t;
while (1) {
sem_wait ( &customer );
pthread_mutex_lock ( &wait_chairs_mutex );
wait_chairs_open++;
pthread_mutex_unlock ( &wait_chairs_mutex );
cutHair(t);
sem_post ( &barber );
}
}
void *customerTask (void *id) {
long my_id = *(long *)id;
pthread_mutex_lock ( &wait_chairs_mutex );
if (wait_chairs_open > 0) {
wait_chairs_open--;
pthread_mutex_unlock ( &wait_chairs_mutex );
sem_post ( &customer );
sem_wait ( &barber );
getHairCut(id);
} else {
pthread_mutex_unlock ( &wait_chairs_mutex );
balk (id);
}
}
int main (int argc, char *argv[])
{
int i, rc;
int tn[26];
long barber_id = 7;
int customerArrivalDelay;
pthread_t threads[26];
pthread_attr_t attr;
srand(time(0));
for (i=0; i<26; i++)
tn[i] = (long)('A'+i);
sem_init ( &customer, 1, 0 );
sem_init ( &barber, 1, 0 );
pthread_mutex_init( &wait_chairs_mutex, 0 );
pthread_create(&threads[i], 0, barberTask, (void *)&barber_id);
for (i=0; i<26; i++) {
customerArrivalDelay = (rand() % 3);
sleep(customerArrivalDelay);
pthread_create(&threads[i], 0, customerTask, (void *)&tn[i]);
}
for (i=0; i<26; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited on %d threads. Done.\\n", 26);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
static void *start(void *str)
{
char buffer[1024];
snprintf(buffer, sizeof (buffer), "thread in %s\\n", str);
printf("%s", buffer);
pthread_mutex_lock(&mutex);
return 0;
}
int main(int argc, char **argv)
{
char buffer[1024];
pthread_mutex_init(&mutex, 0);
pthread_mutex_lock(&mutex);
pthread_t thread;
if (pthread_create(&thread, 0, start, argv[0])) {
fprintf(stderr, "pthread_create(): %m\\n");
return 1;
}
void *handle = dlopen(SHARED_LIBRARY, RTLD_NOW | RTLD_LOCAL);
if (!handle) {
fprintf(stderr, "dlopen(%s): %s\\n", SHARED_LIBRARY, dlerror());
} else {
union {
void *addr;
void *(*fn)(void *);
} sym;
sym.addr = dlsym(handle, "hello");
if (!sym.addr) {
fprintf(stderr, "%s: symbol 'hello' not found\\n", SHARED_LIBRARY);
dlclose(handle);
return 1;
}
sym.fn(argv[0]);
dlclose(handle);
}
pthread_mutex_unlock(&mutex);
pthread_join(thread, 0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
void *Fvis1();
void *Fvis2();
void *Fvis3();
void *Fboss();
int nbotle_refr = 10;
int vis[3][2];
bool bossdo=0;
int i;
pthread_mutex_t refr;
pthread_t vis1,vis2,vis3, boss;
int main()
{
initscr();
pthread_create(&boss, 0, Fboss, 0);
pthread_create(&vis1, 0, Fvis1, 0);
pthread_create(&vis2, 0, Fvis2, 0);
pthread_create(&vis3, 0, Fvis3, 0);
vis[1][2]=0;
vis[2][2]=0;
vis[3][2]=0;
while(1)
{
for(i=1; i<=3; i++)
{
if(i==1)
printw("Vasyan ");
if(i==2)
printw("Hattab ");
if(i==3)
printw("Ivan ");
printw("vypil %d butilok. Teper' on ", vis[i][2]);
if(vis[i][1]==1)
printw("v o4eredi.");
if(vis[i][1]==2)
printw("beret butilku.");
if(vis[i][1]==3)
printw("vypivaet.");
if(vis[i][1]==4)
printw("dryhnet.");
printw("\\n");
}
if(bossdo==1)
printw("Boss kladet 1 butilku. Gosti ne mogut podoyti k holodilniku.\\n");
if(bossdo==0)
printw("Boss gulyaet\\n");
printw("Butilok v holodilnike = %d\\n", nbotle_refr );
refresh();
napms(1000);
clear();
if(nbotle_refr==0)
{
printw("The END");
refresh();
napms(60000);
endwin();
return 0;
}
}
}
void *Fboss()
{
pthread_mutex_init(&refr, 0);
srand(time(0));
while(1)
{
if(rand()%25 +1 == 1)
{
bossdo=1;
pthread_mutex_init(&refr, 0);
pthread_mutex_lock(&refr);
napms(30000);
pthread_mutex_unlock(&refr);
nbotle_refr+=1;
bossdo=0;
}
napms(1000);
}
}
void *Fvis1()
{
while(1)
{
vis[1][1]=1;
pthread_mutex_lock(&refr);
vis[1][1]=2;
napms(5000);
if(bossdo==0)
pthread_mutex_unlock(&refr);
vis[1][1]=3;
napms(20000);
nbotle_refr--;
vis[1][2]++;
if(vis[1][2]==7)
{
vis[1][1]=4;
napms(120000);
}
}
}
void *Fvis2()
{
while(1)
{
vis[2][1]=1;
pthread_mutex_lock(&refr);
vis[2][1]=2;
napms(5000);
if(bossdo==0)
pthread_mutex_unlock(&refr);
vis[2][1]=3;
napms(20000);
nbotle_refr--;
vis[2][2]++;
if(vis[2][2]==7)
{
vis[2][1]=4;
napms(120000);
}
}
}
void *Fvis3()
{
while(1)
{
vis[3][1]=1;
pthread_mutex_lock(&refr);
vis[3][1]=2;
napms(5000);
if(bossdo==0)
pthread_mutex_unlock(&refr);
vis[3][1]=3;
napms(20000);
nbotle_refr--;
vis[3][2]++;
if(vis[3][2]==7)
{
vis[3][1]=4;
napms(120000);
}
}
}
| 1
|
#include <pthread.h>
buffer_t buffer[10];
int buffer_index;
pthread_mutex_t buffer_lock;
pthread_cond_t full_cond, empty_cond;
void insertbuffer(buffer_t value) {
if (buffer_index < 10) {
buffer[buffer_index++] = value;
} else {
printf("Buffer overflow\\n");
}
}
buffer_t dequeuebuffer() {
if (buffer_index > 0) {
return buffer[--buffer_index];
} else {
printf("Buffer underflow\\n");
}
return 0;
}
int isempty() {
if (buffer_index == 0)
return 1;
return 0;
}
int isfull() {
if (buffer_index == 10)
return 1;
return 0;
}
void *producer(void *thread_n) {
int i = 0;
int value;
int thread_numb = *(int *)thread_n;
while (i++ < 2) {
sleep(rand() % 10);
value = rand() % 100;
pthread_mutex_lock(&buffer_lock);
while (isfull()) {
pthread_cond_wait(&full_cond, &buffer_lock);
}
if (isempty()) {
insertbuffer(value);
pthread_cond_signal(&empty_cond);
} else {
insertbuffer(value);
}
printf("Producer thread %d inserted %d\\n", thread_numb, value);
pthread_mutex_unlock(&buffer_lock);
}
pthread_exit(0);
}
void *consumer(void *thread_n) {
int i = 0;
buffer_t value;
int thread_numb = *(int *)thread_n;
while (i++ < 2) {
pthread_mutex_lock(&buffer_lock);
while(isempty()) {
pthread_cond_wait(&empty_cond, &buffer_lock);
}
if (isfull()) {
value = dequeuebuffer();
pthread_cond_signal(&full_cond);
} else {
value = dequeuebuffer();
}
printf("Consumer thread %d processed %d\\n", thread_numb, value);
pthread_mutex_unlock(&buffer_lock);
}
pthread_exit(0);
}
int main(int argc, int *argv[]) {
buffer_index = 0;
pthread_t thread[10];
int thread_num[10];
pthread_mutex_init(&buffer_lock, 0);
pthread_cond_init(&empty_cond, 0);
pthread_cond_init(&full_cond, 0);
int i = 0;
for (i = 0; i < 10; ) {
thread_num[i] = i;
pthread_create(&thread[i],
0,
producer,
&thread_num[i]);
i++;
thread_num[i] = i;
pthread_create(&thread[i],
0,
consumer,
&thread_num[i]);
i++;
}
for (i = 0; i < 10; i++)
pthread_join(thread[i], 0);
pthread_mutex_destroy(&buffer_lock);
pthread_cond_destroy(&full_cond);
pthread_cond_destroy(&empty_cond);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
void sys_err(char *s,int ret)
{
fprintf(stderr,"%s error: %s\\n",*s,strerror(ret));
exit(1);
}
void *pthrd_fun(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
printf("hello ");
sleep(rand()%3);
printf("world\\n");
pthread_mutex_unlock(&mutex);
sleep(rand()%3);
}
return 0;
}
int main()
{
int n = 5;
pthread_t tid;
int ret;
ret = pthread_create(&tid,0,pthrd_fun,0);
if(ret != 0)
{
sys_err("pthread_create",ret);
}
pthread_mutex_init(&mutex,0);
if(ret != 0)
{
sys_err("pthread_mutex_init",ret);
}
while(n--)
{
pthread_mutex_lock(&mutex);
printf("HELLO ");
sleep(rand()%3);
printf("WORLD\\n");
pthread_mutex_unlock(&mutex);
sleep(rand()%3);
}
pthread_cancel(tid);
pthread_join(tid,0);
ret = pthread_mutex_destroy(&mutex);
if(ret != 0)
{
sys_err("pthread_create_destory",ret);
}
return 0;
}
| 1
|
#include <pthread.h>
int musicd_av_lockmgr(void **mutex, enum AVLockOp operation) {
switch (operation) {
case AV_LOCK_CREATE:
*mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
pthread_mutex_init((pthread_mutex_t *)(*mutex), 0);
break;
case AV_LOCK_OBTAIN:
pthread_mutex_lock((pthread_mutex_t *)(*mutex));
break;
case AV_LOCK_RELEASE:
pthread_mutex_unlock((pthread_mutex_t *)(*mutex));
break;
case AV_LOCK_DESTROY:
pthread_mutex_destroy((pthread_mutex_t *)(*mutex));
free(*mutex);
break;
}
return 0;
}
const char *avcodec_get_name(enum AVCodecID id)
{
AVCodec *codec;
codec = avcodec_find_decoder(id);
if (codec) {
return codec->name;
}
codec = avcodec_find_encoder(id);
if (codec) {
return codec->name;
}
return "unknown_codec";
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int shmid;
key_t key;
int SHMSZ = sizeof(int);
struct Stuff {
int* shm_ptr;
int tid;
};
enum { STATE_A, STATE_B, STATE_C, STATE_D } state = STATE_A;
pthread_cond_t condA = PTHREAD_COND_INITIALIZER;
pthread_cond_t condB = PTHREAD_COND_INITIALIZER;
pthread_cond_t condC = PTHREAD_COND_INITIALIZER;
pthread_cond_t condD = PTHREAD_COND_INITIALIZER;
void* CountA(void * stuff)
{
int i, tmp, j;
int* ptr = ((struct Stuff*) stuff)->shm_ptr;
int tid = ((struct Stuff*) stuff)->tid;
for(i = 0 ; i < (10000)/5; i++)
{
pthread_mutex_lock(&mutex);
while (state != STATE_A)
pthread_cond_wait(&condA, &mutex);
pthread_mutex_unlock(&mutex);
for(j = 0; j < 5; j++)
{
pthread_mutex_lock (&mutex);
tmp = *ptr;
tmp = tmp+1;
*ptr = tmp;
pthread_mutex_unlock (&mutex);
}
pthread_mutex_lock(&mutex);
state = STATE_B;
pthread_cond_signal(&condB);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void* CountB(void * stuff)
{
int i, tmp, j;
int* ptr = ((struct Stuff*) stuff)->shm_ptr;
int tid = ((struct Stuff*) stuff)->tid;
for(i = 0 ; i < (10000)/5; i++)
{
pthread_mutex_lock(&mutex);
while (state != STATE_B)
pthread_cond_wait(&condB, &mutex);
pthread_mutex_unlock(&mutex);
for(j = 0; j < 5; j++)
{
pthread_mutex_lock (&mutex);
tmp = *ptr;
tmp = tmp+1;
*ptr = tmp;
pthread_mutex_unlock (&mutex);
}
pthread_mutex_lock(&mutex);
state = STATE_C;
pthread_cond_signal(&condC);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void* CountC(void * stuff)
{
int i, tmp, j;
int* ptr = ((struct Stuff*) stuff)->shm_ptr;
int tid = ((struct Stuff*) stuff)->tid;
for(i = 0 ; i < (10000)/5; i++)
{
pthread_mutex_lock(&mutex);
while (state != STATE_C)
pthread_cond_wait(&condC, &mutex);
pthread_mutex_unlock(&mutex);
for(j = 0; j < 5; j++)
{
pthread_mutex_lock (&mutex);
tmp = *ptr;
tmp = tmp+1;
*ptr = tmp;
pthread_mutex_unlock (&mutex);
}
pthread_mutex_lock(&mutex);
state = STATE_D;
pthread_cond_signal(&condD);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void* CountD(void * stuff)
{
int i, tmp, j;
int* ptr = ((struct Stuff*) stuff)->shm_ptr;
int tid = ((struct Stuff*) stuff)->tid;
for(i = 0 ; i < (10000)/5; i++)
{
pthread_mutex_lock(&mutex);
while (state != STATE_D)
pthread_cond_wait(&condD, &mutex);
pthread_mutex_unlock(&mutex);
for(j = 0; j < 5; j++)
{
pthread_mutex_lock (&mutex);
tmp = *ptr;
tmp = tmp+1;
*ptr = tmp;
pthread_mutex_unlock (&mutex);
}
pthread_mutex_lock(&mutex);
state = STATE_A;
pthread_cond_signal(&condA);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main(int argc, char * argv[])
{
pthread_t tid1, tid2, tid3, tid4;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_mutex_init(&mutex, 0);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
key = IPC_PRIVATE;
if ((shmid = shmget(key, SHMSZ, IPC_PRIVATE | IPC_CREAT | 0666 )) < 0) {
perror("shmget");
exit(1);
}
int* shm;
shm = (int *) shmat(shmid, 0, 0);
*shm = 0;
struct Stuff stuffs;
stuffs.shm_ptr = shm;
pthread_create(&tid1, &attr, CountA, &stuffs);
pthread_create(&tid2, &attr, CountB, &stuffs);
pthread_create(&tid3, &attr, CountC, &stuffs);
pthread_create(&tid4, &attr, CountD, &stuffs);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
pthread_join(tid3, 0);
pthread_join(tid4, 0);
if (*shm < 4 * 10000)
printf("\\n BOOM! cnt is [%d], should be %d\\n", *shm, 4*10000);
else
printf("\\n OK! cnt is [%d]\\n", *shm);
shmctl(shmid, IPC_RMID, 0);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
struct prodcons {
int buffer[2];
pthread_mutex_t lock;
int readpos, writepos;
pthread_cond_t notempty;
pthread_cond_t notfull;
};
void init(struct prodcons *prod) {
pthread_mutex_init(&prod->lock, 0);
pthread_cond_init(&prod->notempty, 0);
pthread_cond_init(&prod->notfull, 0);
prod->readpos = 0;
prod->writepos = 0;
}
void put(struct prodcons *prod, int data) {
pthread_mutex_lock(&prod->lock);
while ((prod->writepos + 1) % 2 == prod->readpos) {
printf("producer wait for not full\\n");
pthread_cond_wait(&prod->notfull, &prod->lock);
}
prod->buffer[prod->writepos] = data;
prod->writepos++;
if (prod->writepos >= 2) {
prod->writepos = 0;
}
pthread_cond_signal(&prod->notempty);
pthread_mutex_unlock(&prod->lock);
}
int get(struct prodcons *prod) {
int data;
pthread_mutex_lock(&prod->lock);
while (prod->writepos == prod->readpos) {
printf("consumer wait for not empty\\n");
pthread_cond_wait(&prod->notempty, &prod->lock);
}
data = prod->buffer[prod->readpos];
prod->readpos++;
if (prod->readpos >= 2) {
prod->readpos = 0;
}
pthread_cond_signal(&prod->notfull);
pthread_mutex_unlock(&prod->lock);
return data;
}
struct prodcons buffer;
void *producer(void *data) {
int n;
for (n = 0; n < 5; n++) {
printf("producer sleep 1 second......\\n");
sleep(1);
printf("put the %d product\\n", n);
put(&buffer, n);
}
for (n = 5; n < 10; n++) {
printf("producer sleep 3 second......\\n");
sleep(3);
printf("put the %d product\\n", n);
put(&buffer, n);
}
put(&buffer, (-1));
printf("producer stopped!\\n");
return 0;
}
void *consumer(void *data) {
int d = 0;
while (1) {
printf("consumer sleep 2 second......\\n");
sleep(2);
d = get(&buffer);
printf("get the %d product\\n", d);
if (d == (-1)) {
break;
}
}
printf("consumer stopped!\\n");
return 0;
}
int main(int argc, char *argv[]) {
pthread_t th_a, th_b;
void *retval;
init(&buffer);
pthread_create(&th_a, 0, producer, 0);
pthread_create(&th_b, 0, consumer, 0);
pthread_join(th_a, &retval);
pthread_join(th_b, &retval);
return 0;
}
| 0
|
#include <pthread.h>
pthread_t * ids;
int fl;
bool threadFlag = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int iloscRekordow;
int iloscWatkow;
void * threadFunc(void *);
void atexitFunc();
struct rekord{
int id;
char * txt;
};
int main(int argc, char const *argv[])
{
atexit(atexitFunc);
if (argc != 5) {
printf("Niepoprawna ilosc argumentow\\n");
exit(-1);
}
iloscWatkow = atoi(argv[1]);
iloscRekordow = atoi(argv[3]);
char slowo[strlen(argv[4])];
strcpy(slowo, argv[4]);
ids = malloc(sizeof(pthread_t)*iloscWatkow);
fl = open(argv[2],O_RDONLY);
if(fl == -1){
printf("Blad otwierania pliku\\n%s\\n",strerror(errno));
exit(-1);
}
int c;
for(int i=0; i<iloscWatkow; i++){
c = pthread_create(ids+i,0,threadFunc,slowo);
if(c!=0){
printf("Blad podczas tworzenia watku nr %d\\n%s\\n",i,strerror(c));
exit(-1);
}
}
threadFlag = 1;
for(int i=0; i<iloscWatkow; i++){
c = pthread_join(ids[i],0);
if(c!=0){
printf("Blad podczas joinowania watku nr %d\\n%s\\n",i,strerror(c));
exit(-1);
}
}
return 0;
}
void * threadFunc(void * slowo){
int czytaj = 1;
struct rekord bufor[iloscRekordow];
int c;
c = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
if(c!=0) {
printf("Blad podczas ustawiania typu\\n%s\\n",strerror(c));
exit(-1);
}
while(!threadFlag);
char *tmp = malloc(sizeof(char)*1024);
char *strtmp = malloc(sizeof(char)*1024);
char *nmb = malloc(sizeof(char)*3);
int j;
int k;
while(czytaj>0) {
pthread_mutex_lock(&mutex);
for (int i = 0; i<iloscRekordow; i++) {
j = 0;
czytaj = read(fl,tmp,1024 +1);
if(czytaj == -1){
printf("Blad podczas czytania z pliku\\n%s\\n",strerror(errno));
exit(-1);
}
while((int)tmp[j]!=32) {
nmb[j] = tmp[j];
j++;
}
bufor[i].id = atoi(nmb);
bufor[i].txt = malloc(sizeof(char)*(1024));
j++;
k = 0;
while((int)tmp[j]!=0){
strtmp[k] = tmp[j];
j++;
k++;
}
j++;
strcpy(bufor[i].txt,strtmp);
}
pthread_mutex_unlock(&mutex);
char * szukacz;
for(int i=0; i<iloscRekordow; i++) {
szukacz = strstr(bufor[i].txt,slowo);
if (szukacz != 0){
printf("Watek o TID: %lu Znalazl slowo w rekordzie o identyfikatorze %d\\n",(unsigned long)pthread_self(),bufor[i].id);
}
}
}
for (int l = 0; l < iloscWatkow; l++) {
if(ids[l]!=pthread_self()){
pthread_cancel(ids[l]);
}
}
return 0;
}
void atexitFunc(){
free(ids);
close(fl);
}
| 1
|
#include <pthread.h>
int variable_global=0;
pthread_mutex_t verrou = PTHREAD_MUTEX_INITIALIZER;
struct data {
int *Tab1;
int *Tab2;
int i;
};
void * Mul(void * par){
pthread_t moi = pthread_self();
int resultat;
struct data *mon_D1 = (struct data*)par;
pthread_mutex_lock(&verrou);
mon_D1->i=mon_D1->i+1;
resultat=(*mon_D1).Tab1[(*mon_D1).i] * (*mon_D1).Tab2[(*mon_D1).i] ;
variable_global+=resultat;
pthread_mutex_unlock(&verrou);
pthread_exit(0);
}
int main(){
float temps;
clock_t t1, t2;
t1 = clock();
FILE * fp;
fp = fopen ("file.txt", "r");
int taille=0;
printf("Entrez la taille de vos vecteurs\\n");
fscanf(fp, "%d",&taille);
int *T1=malloc(sizeof(int)*taille), *T2=malloc(sizeof(int)*taille);
printf("Entrez la valeur du premier vecteur\\n");
for(int i=0;i<taille;i++){
fscanf(fp, "%d",&T1[i]);
}
printf("Entrez la valeur du deuxieme vecteur\\n");
for(int i=0;i<taille;i++){
fscanf(fp, "%d",&T2[i]);
}
struct data D1; D1.Tab1=T1; D1.Tab2=T2; D1.i=0;
pthread_t *TabDeThread = malloc(taille*sizeof(pthread_t));
for(int i=0;i<taille;i++){
pthread_create(&(TabDeThread[i]),0,Mul,&D1);
}
for(int i=0;i<taille;i++){
pthread_join(TabDeThread[i],0);
}
printf("La somme des vecteurs : V1(");
for(int i=0;i<taille-1;i++){
printf("%i,",T1[i]);
}
printf("%i) et V2(",T1[taille-1]);
for(int i=0;i<taille-1;i++){
printf("%i,",T2[i]);
}
printf("%i) a pour resultat : %i\\n",T2[taille-1], variable_global);
t2 = clock();
temps = (float)(t2-t1)/CLOCKS_PER_SEC;
printf("Calul fait en temps = %f\\n", temps);
return 0;
}
| 0
|
#include <pthread.h>
int rang;
int typeMsg;
int nbFois;
} Parametres;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
void thdErreur(int codeErr, char *msgErr, int valeurErr) {
int *retour = malloc(sizeof(int));
*retour = valeurErr;
fprintf(stderr, "%s: %d soit %s \\n", msgErr, codeErr, strerror(codeErr));
pthread_exit(retour);
}
void initialiserVarPartagees (void) {
;
}
int ncp = 0;
int sensCourant = 0;
int nbOnRoad = 0;
int init = 1;
void demandeAccesVU (int sens, int rangProd) {
pthread_mutex_lock(&mut);
}
void libererAccesVU (int sens, int rangConso) {
pthread_mutex_unlock(&mut);
}
void * vehiculeN (void *arg) {
int i;
Parametres param = *(Parametres *)arg;
srand(pthread_self());
for (i = 0; i < param.nbFois; i++) {
demandeAccesVU(param.typeMsg, param.rang);
printf("Vehicule %d sens %d roule dans la voie unique)\\n",
param.rang, param.typeMsg);
usleep(100);
libererAccesVU(param.typeMsg, param.rang);
printf("Vehicule %d sens %d fini de rouler dans la voie unique)\\n",
param.rang, param.typeMsg);
}
pthread_exit(0);
}
int main(int argc, char *argv[]) {
int i, etat;
int nbThds, nbProd;
Parametres paramThds[20 + 20];
pthread_t idThdProd[20];
if (argc <= 2) {
printf ("Usage: %s <Nb vehicule <= %d> <Nb fois> \\n",
argv[0], 20);
exit(2);
}
nbProd = atoi(argv[1]);
if (nbProd > 20)
nbProd = 20;
nbThds = nbProd;
int nbFoisProd = 10;
nbFoisProd = atoi(argv[2]);
initialiserVarPartagees();
for (i = 0; i < nbThds; i++) {
paramThds[i].typeMsg = i%2;
paramThds[i].rang = i;
paramThds[i].nbFois = nbFoisProd;
if ((etat = pthread_create(&idThdProd[i], 0, vehiculeN, ¶mThds[i])) != 0)
thdErreur(etat, "Creation vehiculeN1", etat);
}
for (i = 0; i < nbThds; i++) {
if ((etat = pthread_join(idThdProd[i], 0)) != 0)
thdErreur(etat, "Join threads producteurs", etat);
}
return 0;
}
| 1
|
#include <pthread.h>
void sfwrite(pthread_mutex_t *lock, FILE* stream, char *fmt, ...){
va_list ap;
__builtin_va_start((ap));
pthread_mutex_lock(lock);
vfprintf(stream, fmt, ap);
fflush(0);
pthread_mutex_unlock(lock);
;
}
| 0
|
#include <pthread.h>
bool
receiver_data_zlib(struct mux *mx, uint8_t chnum)
{
struct muxbuf *mxb = &mx->mx_buffer[MUX_IN][chnum];
struct mux_stream_zlib *stream = mx->mx_stream;
z_stream *z = &stream->ms_zstream_in;
uint16_t mss;
uint8_t *cmd = mx->mx_recvcmd;
size_t len, len1, len2, tail;
int err, zflag;
if (!sock_recv(mx->mx_socket, cmd, MUX_CMDLEN_DATA - 2)) {
logmsg_err("Receiver(DATA) Error: recv");
return (0);
}
mss = GetWord(cmd);
if ((mss == 0) || (mss > mxb->mxb_mss)) {
logmsg_err("Receiver(DATA) Error: invalid length: %u", mss);
return (0);
}
if (!sock_recv(mx->mx_socket, stream->ms_zbuffer_in, (size_t)mss)) {
logmsg_err("Receiver(DATA) Error: recv");
return (0);
}
z->next_in = stream->ms_zbuffer_in;
z->avail_in = mss;
do {
if ((err = pthread_mutex_lock(&mxb->mxb_lock)) != 0) {
logmsg_err("Receiver(DATA) Error: mutex lock: %s",
strerror(err));
return (0);
}
if (mxb->mxb_state != MUX_STATE_RUNNING) {
logmsg_err("Receiver(DATA) Error: not running: %u",
chnum);
mxb->mxb_state = MUX_STATE_ERROR;
pthread_mutex_unlock(&mxb->mxb_lock);
return (0);
}
while ((len = mxb->mxb_bufsize - mxb->mxb_length) == 0) {
logmsg_debug(DEBUG_BASE, "Receriver: Sleep(%u): %u %u",
chnum, mxb->mxb_length, mxb->mxb_bufsize);
if ((err = pthread_cond_wait(&mxb->mxb_wait_in,
&mxb->mxb_lock)) != 0) {
logmsg_err("Receiver(DATA) Error: cond_wait: "
"%s", strerror(err));
mxb->mxb_state = MUX_STATE_ERROR;
pthread_mutex_unlock(&mxb->mxb_lock);
return (0);
}
logmsg_debug(DEBUG_BASE, "Receriver: Wakeup(%u): %u",
chnum, mxb->mxb_length);
if (mxb->mxb_state != MUX_STATE_RUNNING) {
logmsg_err("Receiver(DATA) Error: "
"not running: %u", chnum);
mxb->mxb_state = MUX_STATE_ERROR;
pthread_mutex_unlock(&mxb->mxb_lock);
return (0);
}
}
tail = mxb->mxb_head + mxb->mxb_length;
if (tail >= mxb->mxb_bufsize)
tail -= mxb->mxb_bufsize;
if ((len1 = tail + len) > mxb->mxb_bufsize) {
len2 = len1 - mxb->mxb_bufsize;
len1 = len - len2;
zflag = 0;
} else {
len2 = 0;
zflag = Z_FINISH;
}
z->next_out = &mxb->mxb_buffer[tail];
z->avail_out = len1;
err = inflate(z, zflag);
if ((err != Z_STREAM_END) && (err != Z_OK)) {
logmsg_err("Receiver(DATA) Error: INFLATE: %s",
z->msg);
mxb->mxb_state = MUX_STATE_ERROR;
pthread_mutex_unlock(&mxb->mxb_lock);
return (0);
}
if ((z->avail_in != 0) && (len2 > 0)) {
z->next_out = mxb->mxb_buffer;
z->avail_out = len2;
err = inflate(z, Z_FINISH);
if ((err != Z_STREAM_END) && (err != Z_OK)) {
logmsg_err("Receiver(DATA) Error: INFLATE: %s",
z->msg);
mxb->mxb_state = MUX_STATE_ERROR;
pthread_mutex_unlock(&mxb->mxb_lock);
return (0);
}
}
mx->mx_xfer_in += z->total_out;
mxb->mxb_length += z->total_out;
z->total_out = 0;
if ((err = pthread_cond_signal(&mxb->mxb_wait_out)) != 0) {
logmsg_err("Receiver(DATA) Error: cond signal: %s",
strerror(err));
mxb->mxb_state = MUX_STATE_ERROR;
pthread_mutex_unlock(&mxb->mxb_lock);
return (0);
}
if ((err = pthread_mutex_unlock(&mxb->mxb_lock)) != 0) {
logmsg_err("Receiver(DATA) Error: mutex unlock: %s",
strerror(err));
return(0);
}
} while (z->avail_in > 0);
if (inflateReset(z) != Z_OK) {
logmsg_err("Receiver(DATA) Error: INFLATE(reset): %s", z->msg);
return (0);
}
return (1);
}
| 1
|
#include <pthread.h>
struct FileLock* next;
FILE* file;
pthread_mutex_t mutex;
} FileLock;
pthread_mutex_t lock;
FileLock* buckets[ 32 ];
} LockTable;
static LockTable* _lockTable;
static pthread_once_t _lockTable_once = PTHREAD_ONCE_INIT;
static void
lock_table_init( void )
{
_lockTable = malloc(sizeof(*_lockTable));
if (_lockTable != 0) {
pthread_mutex_init(&_lockTable->lock, 0);
memset(_lockTable->buckets, 0, sizeof(_lockTable->buckets));
}
}
static LockTable*
lock_table_lock( void )
{
pthread_once( &_lockTable_once, lock_table_init );
pthread_mutex_lock( &_lockTable->lock );
return _lockTable;
}
static void
lock_table_unlock( LockTable* t )
{
pthread_mutex_unlock( &t->lock );
}
static FileLock**
lock_table_lookup( LockTable* t, FILE* f )
{
uint32_t hash = (uint32_t)(void*)f;
FileLock** pnode;
hash = (hash >> 2) ^ (hash << 17);
pnode = &t->buckets[hash % 32];
for (;;) {
FileLock* node = *pnode;
if (node == 0 || node->file == f)
break;
pnode = &node->next;
}
return pnode;
}
void
flockfile(FILE * fp)
{
LockTable* t = lock_table_lock();
if (t != 0) {
FileLock** lookup = lock_table_lookup(t, fp);
FileLock* lock = *lookup;
if (lock == 0) {
pthread_mutexattr_t attr;
lock = malloc(sizeof(*lock));
if (lock == 0) {
lock_table_unlock(t);
return;
}
lock->next = 0;
lock->file = fp;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init( &lock->mutex, &attr );
*lookup = lock;
}
lock_table_unlock(t);
pthread_mutex_lock(&lock->mutex);
}
}
int
ftrylockfile(FILE *fp)
{
int ret = -1;
LockTable* t = lock_table_lock();
if (t != 0) {
FileLock** lookup = lock_table_lookup(t, fp);
FileLock* lock = *lookup;
lock_table_unlock(t);
if (lock != 0 && !pthread_mutex_trylock(&lock->mutex)) {
ret = 0;
}
}
return ret;
}
void
funlockfile(FILE * fp)
{
LockTable* t = lock_table_lock();
if (t != 0) {
FileLock** lookup = lock_table_lookup(t, fp);
FileLock* lock = *lookup;
if (lock != 0)
pthread_mutex_unlock(&lock->mutex);
lock_table_unlock(t);
}
}
void
__fremovelock(FILE* fp)
{
LockTable* t = lock_table_lock();
if (t != 0) {
FileLock** lookup = lock_table_lookup(t, fp);
FileLock* lock = *lookup;
if (lock != 0) {
*lookup = lock->next;
lock->file = 0;
}
lock_table_unlock(t);
free(lock);
}
}
| 0
|
#include <pthread.h>
{
int index, pocetak, kraj, stupci;
pthread_mutex_t lock;
char *matrica;
}thr_struct;
void* thr_fun(void *arg)
{
int index = ((thr_struct*)arg)->index;
int pocetak = ((thr_struct*)arg)->pocetak;
int kraj = ((thr_struct*)arg)->kraj;
pthread_mutex_t lock = ((thr_struct*)arg)->lock;
int stupci = ((thr_struct*)arg)->stupci;
char* matrica = ((thr_struct*)arg)->matrica;
for(int i=pocetak; i<kraj; ++i)
if(matrica[i] == 'o')
{
pthread_mutex_lock(&lock);
printf("(%d,%d)\\n", i/stupci, i%stupci);
pthread_mutex_unlock(&lock);
}
return 0;
}
int main(int argc, char** argv)
{
char c, *matrica;
int k=0, M, N;
pthread_mutex_t lock;
if (pthread_mutex_init(&lock, 0) != 0)
{
fprintf(stderr, "\\n mutex init failed\\n");
exit(1);
}
if(argc != 5)
{
fprintf(stderr, "Greska pri upisu komandne linije:\\n%s \\n", argv[0]);
exit(1);
}
int broj_dretvi;
broj_dretvi = atoi(argv[1]);
M = atoi(argv[2]);
N = atoi(argv[3]);
int duljina = M*(N+1);
if(broj_dretvi<=0 || M<=0 || N<=0)
{
fprintf(stderr, "svi parametri moraju biti pozitivni\\n");
exit(1);
}
FILE *f;
f = fopen(argv[4], "r");
if( f == 0 )
{
fprintf(stderr, "greska pri otvaranju datoteke\\n");
exit(1);
}
if((matrica = (char*) malloc(M*N*sizeof(char)))==0)
{
fprintf(stderr, "memory allocation error: matrica\\n");
exit(1);
}
for(int i=0; i<duljina; ++i)
{
fscanf(f, "%c", &c);
if(c == 'o' || c == '.')
matrica[k++]=c;
}
fclose(f);
pthread_t *thr_idx;
if ((thr_idx = (pthread_t *) calloc(broj_dretvi, sizeof(pthread_t))) == 0) {
fprintf(stderr, "%s: memory allocation error\\n", argv[0]);
exit(1);
}
int dijeljenje =M*N/broj_dretvi;
int ukupno = 0, dodatak;
int ostatak = M*N-broj_dretvi*dijeljenje;
thr_struct *podaci;
if((podaci = (thr_struct*)malloc(broj_dretvi*sizeof(thr_struct)))==0)
{
fprintf(stderr, "memory allocation error: podaci \\n");
exit(1);
}
for (int i = 0; i < broj_dretvi; ++i)
{
if(broj_dretvi-ostatak<=i) dodatak = 1;
else dodatak = 0;
podaci[i].index = i;
podaci[i].pocetak = ukupno;
podaci[i].kraj = ukupno+dijeljenje+dodatak;
podaci[i].lock = lock;
ukupno = podaci[i].kraj;
podaci[i].stupci = N;
podaci[i].matrica = matrica;
if (pthread_create(&thr_idx[i], 0, thr_fun,(void*)&podaci[i]))
{
fprintf( stderr,"%s: error creating thread %d\\n", argv[0], i);
exit(1);
}
}
for (int i = 0; i < broj_dretvi; ++i)
if (pthread_join(thr_idx[i], 0))
{
fprintf(stderr, "%s: error joining thread %d\\n", argv[0], i);
exit(1);
}
free(matrica);
free(thr_idx);
free(podaci);
return 0;
}
| 1
|
#include <pthread.h>
int value;
struct List* next;
} List;
List* head = 0;
List* tail = 0;
int elem_num;
pthread_mutex_t my_mutex;
sem_t my_sem;
void push_back(int value)
{
List* node = malloc(sizeof(List));
node->value = value;
node->next = 0;
if(head == 0) {
head = node;
tail = node;
}
else {
if(head == tail) {
tail = node;
head->next = node;
} else {
tail->next = node;
tail = node;
}
}
elem_num++;
}
int pop_front()
{
int ret = -1;
if(head != 0) {
if(head == tail) {
ret = head->value;
free(head);
head = 0;
tail = 0;
}
else {
List* old_head = head;
ret = head->value;
head = head->next;
free(old_head);
}
elem_num--;
}
return ret;
}
int is_empty()
{
if(head == 0)
return 1;
else
return 0;
}
int get_elem_num()
{
return elem_num;
}
void show_all()
{
List* temp = head;
while(temp != 0) {
printf("value = %d\\n", temp->value);
temp = temp->next;
}
}
void* thread_write(void *arg)
{
while(1) {
for(int i = 0; i < 10 ; i++) {
pthread_mutex_lock(&my_mutex);
push_back(i);
pthread_mutex_unlock(&my_mutex);
sem_post(&my_sem);
}
sleep(10);
}
return 0;
}
void* thread_read(void *arg)
{
int sem_val;
while(1) {
sem_wait(&my_sem);
pthread_mutex_lock(&my_mutex);
printf("thread_read = %li | value = %d | elem_num = %d\\n", pthread_self(), pop_front(), elem_num);
pthread_mutex_unlock(&my_mutex);
}
}
int main()
{
pthread_t thread_pool[3];
pthread_mutex_init(&my_mutex, 0);
sem_init(&my_sem, 0, 0);
for(int i = 0 ; i < 3 ; i++)
{
pthread_create(&thread_pool[i],
0,
(i == 0) ? &thread_write : &thread_read,
0);
}
for(int i = 0 ; i < 3 ; i++) {
pthread_join(thread_pool[i], 0);
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer[5];
int in = 0, out = 0;
void *producer(void *ptr) {
int i;
for (i = 0; i < 100; i++) {
pthread_mutex_lock(&the_mutex);
while (((in + 1) % 5) == out)
pthread_cond_wait(&condp, &the_mutex);
buffer[in] = i;
printf("ProBuffer[%d]:%2d\\n", in, buffer[in]);
in = (in + 1) % 5;
pthread_cond_signal(&condc);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
void *consumer(void *ptr) {
int i;
for (i = 0; i < 100; i++) {
pthread_mutex_lock(&the_mutex);
while (in == out)
pthread_cond_wait(&condc, &the_mutex);
buffer[out] = 0;
printf("ConBuffer[%d]:%2d\\n", out, buffer[out]);
out = (out + 1) % 5;
pthread_cond_signal(&condp);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
int main(int argc, char **argv) {
pthread_t pro, con;
pthread_mutex_init(&the_mutex, 0);
pthread_cond_init(&condc, 0);
pthread_cond_init(&condp, 0);
pthread_create(&con, 0, consumer, 0);
pthread_create(&pro, 0, producer, 0);
pthread_join(con, 0);
pthread_join(pro, 0);
pthread_mutex_destroy(&the_mutex);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
}
| 1
|
#include <pthread.h>
char buffer[9][18];
FILE *infile;
FILE *outfile;
int flag = 0;
int slot = 0;
int item_buff=0;
pthread_t produce;
pthread_t consume;
pthread_mutex_t buf_lock =PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t empty_slot=PTHREAD_COND_INITIALIZER;
pthread_cond_t avail_item=PTHREAD_COND_INITIALIZER;
void *producer();
void *consumer();
int main(int argc, char *argv[]){
if(pthread_mutex_init(&buf_lock, 0) !=0){
printf("Mutex myLocke1 failed \\n");
return 1;
}
if(pthread_cond_init(&empty_slot, 0) !=0){
printf("Mutex myLocke1 failed \\n");
return 1;
}
if(pthread_cond_init(&avail_item, 0) !=0){
printf("Mutex myLocke1 failed \\n");
return 1;
}
if(argc != 3)
{
printf("Correct Usage: prog3 infile outfile \\n");
exit(0);
}
else{
infile = fopen(argv[1], "r");
outfile = fopen(argv[2], "w");
if( infile == 0 )
{
printf("Could not open file\\n");
}
else{
memset(buffer, 0, sizeof buffer);
pthread_create(&produce, 0, producer,(void *) infile);
pthread_create(&consume, 0, consumer,(void *) outfile);
pthread_join(produce, 0);
pthread_join(consume, 0);
pthread_cond_destroy(&empty_slot);
pthread_cond_destroy(&avail_item);
fclose(infile);
fclose(outfile);
}
}
pthread_exit(0);
}
void *producer(FILE *infile){
int c;
int i;
int j;
int index = 0;
int next_produced[18];
int end_producer = 0;
do{
pthread_mutex_lock(&buf_lock);
while(slot == 8){
pthread_cond_wait(&empty_slot,&buf_lock);
}
for(i = 0; i < 18; i++){
if((c = fgetc(infile)) != EOF){
next_produced[i] = c;
}
else{
end_producer = 1;
}
}
for(j = 0; j < 18; j++){
buffer[index][j] = (char)next_produced[j];
}
index++;
index = index % 9;
slot++;
memset(next_produced, 0, sizeof next_produced);
pthread_cond_signal(&avail_item);
pthread_mutex_unlock(&buf_lock);
if(end_producer){
flag = end_producer;
break;
}
}while(1);
pthread_exit(0);
}
void *consumer(FILE *outfile){
int s;
int r;
char next_consumed[18];
do{
slot--;
pthread_mutex_lock(&buf_lock);
while(slot == 0){
if(flag && slot == 0){
break;
}
pthread_cond_wait(&avail_item,&buf_lock);
}
for(r=0; r<18; r++){
next_consumed[r] = buffer[item_buff][r];
}
for(r=0; r<18;r++){
fputc(next_consumed[r],outfile);
}
memset(next_consumed, 0, sizeof next_consumed);
item_buff++;
item_buff= item_buff % 9;
pthread_cond_signal(&empty_slot);
pthread_mutex_unlock(&buf_lock);
if(flag && slot == 0){
break;
}
}while(1);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t balance_mutex;
int balance = 100;
int withdraw(int amount)
{
pthread_mutex_lock(&balance_mutex);
if (balance >= amount)
{
balance -= amount;
pthread_mutex_unlock(&balance_mutex);
return amount;
}
else
{
pthread_mutex_unlock(&balance_mutex);
return -1;
}
}
void *try_to_withdraw(void *tid)
{
int* thread_id = (int*)tid;
sleep(2);
printf("T %d: trying to withdraw %d\\n", *thread_id, 35);
if (withdraw(35) == 35)
printf("T %d: Successfully withdrawn\\n", *thread_id);
else
printf("T %d: Failed to withdraw\\n", *thread_id);
return 0;
}
int main()
{
pthread_t threads[4];
int thread_ids[4];
if (sysconf(_SC_THREADS) == -1)
{
fprintf(stderr, "Error: Threads aren't supported.\\n");
return -1;
}
pthread_mutex_init(&balance_mutex, 0);
for (int i=0; i<4; i++)
{
thread_ids[i] = i+1;
if (pthread_create(&threads[i], 0, try_to_withdraw, &thread_ids[i]) != 0)
fprintf(stderr, "Failed to create thread %d!\\n", thread_ids[i]);
else
printf("Main: Thread %d started...\\n", thread_ids[i]);
}
printf("Main: Wait for all threads to finish...\\n\\n");
for (int j=0; j<4; j++)
pthread_join(threads[j], 0);
pthread_mutex_destroy(&balance_mutex);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t empty = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t empty2 = PTHREAD_MUTEX_INITIALIZER;
int numInQ2,numInQ;
int size = 300000;
void putOnQ(int x) {
pthread_mutex_lock(&mutex);
printf("%d\\n",x);
numInQ+=1;
pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&empty);
}
void putOnQ2(int x) {
pthread_mutex_lock(&mutex2);
numInQ2+=1;
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&empty2);
}
void getOffQ(void) {
while (numInQ == 0) pthread_mutex_lock(&empty);
pthread_mutex_lock(&mutex);
numInQ-=1;
pthread_mutex_unlock(&mutex);
}
void getOffQ2(void) {
int thing;
printf("%d\\n",numInQ2);
while (numInQ2 == 0) pthread_mutex_lock(&empty2);
pthread_mutex_lock(&mutex2);
numInQ2-=1;
pthread_mutex_unlock(&mutex2);
}
void * prod(void *arg) {
int mynum;
int i;
mynum = *(int *)arg;
for (i = 0; i < size; i++) {
putOnQ(i);
}
}
void * con(void *arg) {
int i;
int stuff;
for (i = 0; i < size; i++) {
getOffQ();
putOnQ2(i);
}
pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&empty);
exit(0);
}
void * con2(void *arg) {
int i;
for (i = 0; i < size; i++) {
printf("%d**\\n",i);
getOffQ2();
}
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&empty2);
exit(0);
}
void main()
{
pthread_t threadp1;
pthread_t threadc2;
pthread_t threadc1;
int zero = 0; int one = 1;
pthread_create(&threadp1, 0, prod, &zero);
pthread_create(&threadc1, 0, con, 0);
pthread_create(&threadc2, 0, con2, 0);
pthread_join(threadc1,0);
pthread_join(threadp1,0);
pthread_join(threadc2,0);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int a = 0;
void* testThreadPool(int *t) {
printf("thread start: %d\\n", *t);
for (;;) {
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
}
return (void*) 0;
}
int main() {
int thread_num = 5;
pthread_t *mythread = (pthread_t*) malloc(thread_num* sizeof(*mythread));
int t;
for (t = 0; t < 5; t++) {
int *i=(int*)malloc(sizeof(int));
*i=t;
if (pthread_create(&mythread[t], 0, (void*)testThreadPool, (void*)i) != 0) {
printf("pthread_create");
}
}
for (t = 0; t < 100; t++) {
printf("main: a: %d\\n", t);
pthread_mutex_lock(&mutex);
a = t;
pthread_mutex_unlock(&mutex);
sleep(2);
}
}
| 1
|
#include <pthread.h>
void *ft_overninethousand(void)
{
ft_putendl("oh no");
return (0);
}
void print_mem(void *mem)
{
int i;
char *str;
pthread_mutex_lock(&g_lock);
i = -1;
str = (char *)mem;
while (++i < 16)
{
if (str[i] > 33 && str[i] < 127)
write(1, &str[i], 1);
else
write(1, ".", 1);
}
ft_putchar(10);
pthread_mutex_unlock(&g_lock);
}
| 0
|
#include <pthread.h>
{
int id;
int noproc;
int dim;
} parm;
{
int cur_count;
pthread_mutex_t barrier_mutex;
pthread_cond_t barrier_cond;
} barrier_t;
barrier_t barrier1;
double *finals;
int rootn;
void barrier_init(barrier_t * mybarrier)
{
pthread_mutexattr_t attr;
pthread_mutex_init(&(mybarrier->barrier_mutex), 0);
pthread_cond_init(&(mybarrier->barrier_cond), 0);
mybarrier->cur_count = 0;
}
void barrier(int numproc, barrier_t * mybarrier)
{
pthread_mutex_lock(&(mybarrier->barrier_mutex));
mybarrier->cur_count++;
if (mybarrier->cur_count!=numproc) {
pthread_cond_wait(&(mybarrier->barrier_cond), &(mybarrier->barrier_mutex));
}
else
{
mybarrier->cur_count=0;
pthread_cond_broadcast(&(mybarrier->barrier_cond));
}
pthread_mutex_unlock(&(mybarrier->barrier_mutex));
}
double f(a)
double a;
{
return (4.0 / (1.0 + a * a));
}
void * cpi(void *arg)
{
parm *p = (parm *) arg;
int myid = p->id;
int numprocs = p->noproc;
int i;
double PI25DT = 3.141592653589793238462643;
double mypi, pi, h, sum, x, a;
double startwtime, endwtime;
if (myid == 0)
{
startwtime = clock();
}
barrier(numprocs, &barrier1);
if (rootn==0)
finals[myid]=0;
else {
h = 1.0 / (double) rootn;
sum = 0.0;
for (i = myid + 1; i <=rootn; i += numprocs)
{
x = h * ((double) i - 0.5);
sum += f(x);
}
mypi = h * sum;
}
finals[myid] = mypi;
barrier(numprocs, &barrier1);
if (myid == 0)
{
pi = 0.0;
for (i =0; i < numprocs; i++)
pi += finals[i];
endwtime = clock();
printf("pi is approximately %.16f, Error is %.16f\\n",
pi, fabs(pi - PI25DT));
printf("wall clock time = %f\\n",
(endwtime - startwtime) / CLOCKS_PER_SEC);
}
return 0;
}
int main(argc, argv)
int argc;
char *argv[];
{
int done = 0, n, myid, numprocs, i, rc;
double startwtime, endwtime;
parm *arg;
pthread_t *threads;
pthread_attr_t pthread_custom_attr;
if (argc != 2)
{
printf("Usage: %s n\\n where n is no. of thread\\n", argv[0]);
exit(1);
}
n = atoi(argv[1]);
if ((n < 1) || (n > 20))
{
printf("The no of thread should between 1 and %d.\\n", 20);
exit(1);
}
threads = (pthread_t *) malloc(n * sizeof(*threads));
pthread_attr_init(&pthread_custom_attr);
barrier_init(&barrier1);
finals = (double *) malloc(n * sizeof(double));
rootn = 10000000;
arg=(parm *)malloc(sizeof(parm)*n);
for (i = 0; i < n; i++)
{
arg[i].id = i;
arg[i].noproc = n;
pthread_create(&threads[i], &pthread_custom_attr, cpi, (void *)(arg+i));
}
for (i = 0; i < n; i++)
{
pthread_join(threads[i], 0);
}
free(arg);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t *ssl_lock_array = 0;
static void lock_callback(int mode, int type, char *file, int line) {
(void)file;
(void)line;
if(mode & CRYPTO_LOCK) {
pthread_mutex_lock(&(ssl_lock_array[type]));
}
else {
pthread_mutex_unlock(&(ssl_lock_array[type]));
}
}
static unsigned long thread_id(void) {
return (unsigned long) pthread_self();
}
void init_ssl_locks(void) {
int i;
ssl_lock_array=(pthread_mutex_t *)OPENSSL_malloc(CRYPTO_num_locks() *
sizeof(pthread_mutex_t));
for(i=0; i<CRYPTO_num_locks(); i++) {
pthread_mutex_init(&(ssl_lock_array[i]), 0);
}
CRYPTO_set_id_callback((unsigned long (*)())thread_id);
CRYPTO_set_locking_callback((void (*)())lock_callback);
}
void shutdown_ssl_locks(void) {
int i;
if (ssl_lock_array) {
CRYPTO_set_locking_callback(0);
for(i=0; i<CRYPTO_num_locks(); i++)
pthread_mutex_destroy(&(ssl_lock_array[i]));
OPENSSL_free(ssl_lock_array);
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int comeco = 0;
int tamanho = 0;
int buffer[10] = 0;
void imprimeBuffer(void){
int i;
}
void *producer(void *ptr)
{
int i;
for (i = 1; i <= 1000000000; i++) {
pthread_mutex_lock(&the_mutex);
while (tamanho == 10)
pthread_cond_wait(&condp, &the_mutex);
buffer[(comeco+n)%10] = i;
printf("\\rprod=%d", i);
tamanho++;
if(tamanho - 1 == 0)
pthread_cond_signal(&condc);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
void *consumer(void *ptr)
{
int i;
for (i = 1; i <= 1000000000; i++) {
pthread_mutex_lock(&the_mutex);
while (tamanho == 0)
pthread_cond_wait(&condc, &the_mutex);
printf("\\r\\t\\tcons=%d", buffer[comeco]);
comeco++;
tamanho--;
if(tamanho + 1 == 10)
pthread_cond_signal(&condp);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
int main(void)
{
pthread_t pro, con;
pthread_mutex_init(&the_mutex, 0);
pthread_cond_init(&condc, 0);
pthread_cond_init(&condp, 0);
pthread_create(&con, 0, consumer, 0);
pthread_create(&pro, 0, producer, 0);
pthread_join(pro, 0);
pthread_join(con, 0);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
pthread_mutex_destroy(&the_mutex);
return 0;
}
| 1
|
#include <pthread.h>
char __resource[32 + 1];
unsigned long __resource_len = 0;
unsigned long __reader_count = 0;
pthread_mutex_t __write_mutex;
pthread_mutex_t __read_mutex;
void write_resource(unsigned long tid) {
char ch = 'a' + __resource_len % 26;
__resource[__resource_len] = ch;
++__resource_len;
printf("[ Writer %lu ] Writing..., len = %lu\\n", tid, __resource_len);
}
void read_resource(unsigned long tid) {
printf("[ Reader %lu ] %s\\n", tid, __resource);
}
void* writer(void* thread_id) {
unsigned long tid = (unsigned long)thread_id;
pthread_mutex_lock(&__write_mutex);
while (__resource_len < 32) {
write_resource(tid);
pthread_mutex_unlock(&__write_mutex);
sleep(0);
pthread_mutex_lock(&__write_mutex);
}
pthread_mutex_unlock(&__write_mutex);
pthread_exit(0);
}
void* reader(void* thread_id) {
unsigned long tid = (unsigned long)thread_id;
while (__resource_len < 32) {
pthread_mutex_lock(&__read_mutex);
++__reader_count;
if (__reader_count == 1) {
pthread_mutex_lock(&__write_mutex);
}
pthread_mutex_unlock(&__read_mutex);
read_resource(tid);
pthread_mutex_lock(&__read_mutex);
--__reader_count;
if (__reader_count == 0) {
pthread_mutex_unlock(&__write_mutex);
}
pthread_mutex_unlock(&__read_mutex);
sleep(0);
}
pthread_exit(0);
}
int main() {
pthread_mutex_init(&__write_mutex, 0);
pthread_mutex_init(&__read_mutex, 0);
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_t writers[4], readers[8];
for (unsigned long i = 0; i < 4; ++i) {
pthread_create(&writers[i], &attr, writer, (void*)i);
}
for (unsigned long i = 0; i < 8; ++i) {
pthread_create(&readers[i], &attr, reader, (void*)i);
}
for (unsigned long j = 0; j < 4; ++j) {
pthread_join(writers[j], 0);
}
for (unsigned long k = 0; k < 8; ++k) {
pthread_join(readers[k], 0);
}
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&__write_mutex);
pthread_mutex_destroy(&__read_mutex);
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
double now()
{
struct timeval tv;
gettimeofday(&tv, 0);
return tv.tv_sec * 1000000ll + tv.tv_usec;
}
FILE * fd;
char *file = "test_thread";
pthread_mutex_t input_queue;
void do_work(unsigned long buf)
{
}
void * work(void * data)
{
unsigned long line;
char buf[512];
while ( !feof(fd) )
{
pthread_mutex_lock(&input_queue);
fgets((char *)&buf, sizeof(buf), fd);
if (buf[strlen (buf) - 1] == '\\n')
buf[strlen (buf) - 1] = '\\0';
line = (unsigned long)buf;
pthread_mutex_unlock(&input_queue);
do_work( line );
}
return 0;
}
int main()
{
pthread_mutex_init(&input_queue, 0);
if( ( fd = fopen( file, "a+" ) ) == 0 ) {
fprintf( stderr, "Can't open input file\\n");
exit(0);
}
pthread_t thread_id[10];
int i=0;
for( i = 0 ; i < 10; i++)
{
if( pthread_create( &thread_id[i], 0, &work, 0) != 0 )
{
i--;
fprintf(stderr, "\\nError in creating thread\\n");
}
}
double current = now();
for( i = 0 ; i < 10; i++)
if( pthread_join( thread_id[i], 0) != 0 )
{
fprintf(stderr, "\\nError in joining thread\\n" );
}
printf("Time consumed by 10 threads in reading is %f \\n", now() - current);
fclose(fd);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t mtxCpt;
static FILE* f;
static pthread_mutex_t mtxAffichage;
static void print_prime_factors(uint64_t n)
{
uint64_t factors[MAX_FACTORS];
int j,k;
k=insererNombre(n,factors);
pthread_mutex_lock(&mtxAffichage);
printf("%ju: ",n);
for(j=0; j<k; j++)
{
printf("%ju ",factors[j]);
}
pthread_mutex_unlock(&mtxAffichage);
printf("\\n");
}
static void * gestion_threads(void * np)
{
char ligne [50];
pthread_mutex_lock(&mtxCpt);
while(fgets(ligne,sizeof(ligne),f) !=0)
{
pthread_mutex_unlock(&mtxCpt);
uint64_t n = (uint64_t)atoll(ligne);
print_prime_factors(n);
pthread_mutex_lock(&mtxCpt);
}
pthread_mutex_unlock(&mtxCpt);
return 0;
}
int main(void)
{
initialiserTableHashage();
pthread_t thread1;
pthread_t thread2;
pthread_mutex_init(&mtxCpt, 0);
f= fopen("small.txt", "r");
pthread_create(&thread1, 0, gestion_threads, 0 );
pthread_create(&thread2, 0, gestion_threads, 0 );
pthread_join(thread1, 0);
pthread_join(thread2, 0);
fclose(f);
return 0;
}
| 0
|
#include <pthread.h>
static const int MAX_QUEUE_SIZE = 10;
static const int MAX_ITERATIONS = 100000;
pthread_mutex_t mutex;
pthread_cond_t cv_queue_not_full, cv_queue_not_empty;
struct node
{
int data;
struct node * next;
};
struct queue
{
int size;
struct node * head;
struct node * tail;
};
struct queue * integers;
void enqueue(struct queue * q, int x)
{
struct node * n = (struct node *) malloc(sizeof(struct node));
n->data = x;
n->next = 0;
if(q->head == 0 && q->tail == 0)
{
q->head = n;
q->tail = n;
}
else
{
q->tail->next = n;
q->tail = n;
}
q->size++;
}
struct node * dequeue(struct queue * q)
{
struct node * n = q->head;
if(q->head == q->tail)
{
q->head = 0;
q->tail = 0;
}
else
{
q->head = q->head->next;
}
q->size--;
return n;
}
void destroy_queue(struct queue * q)
{
while (q->size > 0)
{
struct node * n = dequeue(q);
free(n);
}
free(q);
}
void print_queue(struct queue * q)
{
printf("(%02d) [ ", q->size);
struct node * n = q->head;
while (n != 0)
{
printf("%d ", n->data);
n = n->next;
}
printf("]");
}
void * produce()
{
srand(time(0));
int i, x;
for (i = 0; i < MAX_ITERATIONS; i++)
{
x = rand() % 100;
pthread_mutex_lock(&mutex);
while (integers->size >= MAX_QUEUE_SIZE)
{
pthread_cond_wait(&cv_queue_not_full, &mutex);
}
enqueue(integers, x);
printf("PRODUCE: ");
print_queue(integers);
printf("\\n");
pthread_cond_signal(&cv_queue_not_empty);
pthread_mutex_unlock(&mutex);
}
return 0;
}
void * consume()
{
int i;
for (i = 0; i < MAX_ITERATIONS; i++)
{
pthread_mutex_lock(&mutex);
while (integers->size <= 0)
{
pthread_cond_wait(&cv_queue_not_empty, &mutex);
}
struct node * n = dequeue(integers);
free(n);
printf("CONSUME: ");
print_queue(integers);
printf("\\n");
pthread_cond_signal(&cv_queue_not_full);
pthread_mutex_unlock(&mutex);
}
return 0;
}
int main(int argc, char ** argv)
{
int status = 0;
pthread_t producer, consumer;
pthread_mutex_init(&mutex, 0);
integers = (struct queue *) malloc(sizeof(struct queue));
if (integers == 0)
{
perror("Error : Unable to allocate memory for the integer queue ");
status++;
goto ret;
}
integers->size = 0;
integers->head = 0;
integers->tail = 0;
status += pthread_create(&producer, 0, produce, 0);
status += pthread_create(&consumer, 0, consume, 0);
if (status != 0)
{
perror("Error : Unable to create producer/consumer threads ");
goto ret;
}
status += pthread_join(producer, 0);
status += pthread_join(consumer, 0);
if (status != 0)
{
perror("Error : Unable to join producer/consumer threads ");
goto ret;
}
destroy_queue(integers);
ret:
return status;
}
| 1
|
#include <pthread.h>
int glob = 0;
pthread_mutex_t mtx;
void* threadFunc1(void *arg)
{
int loops = *((int *)arg);
int loc, j;
for(j=0;j<loops;j++)
{
pthread_mutex_lock(&mtx);
pthread_mutex_trylock(&mtx);
loc = glob;
loc++;
glob = loc;
pthread_mutex_unlock(&mtx);
}
}
void* threadFunc2(void *arg)
{
int loops = *((int *)arg);
int loc, j;
for(j=0;j<loops;j++)
{
pthread_mutex_lock(&mtx);
pthread_mutex_trylock(&mtx);
loc = glob;
loc++;
glob = loc;
pthread_mutex_unlock(&mtx);
}
}
int main()
{
pthread_t t1, t2;
long int loops, res,s;
loops = 150000;
pthread_create(&t1, 0, threadFunc1, &loops);
pthread_create(&t2, 0, threadFunc2, &loops);
pthread_join(t1,&res);
pthread_join(t2,&res);
printf("glob = %d\\n", glob);
return 0;
}
| 0
|
#include <pthread.h>
int threadRunCounts[3] = {0};
int producerSleep = 0;
int consumerSleep = 0;
int queueMaxSize = 45;
int queue = 0;
pthread_mutex_t queueMutex;
int checkFinished() {
if((threadRunCounts[0] || threadRunCounts[1]) && threadRunCounts[2] > 1000)
return 0;
else
return 1;
}
void *producerFunc(void *t) {
long my_id = (long)t;
while(checkFinished()) {
threadRunCounts[my_id - 1] += 1;
pthread_mutex_lock(&queueMutex);
if(queue >= queueMaxSize) {
producerSleep ++;
pthread_mutex_unlock(&queueMutex);
continue;
}
queue++;
pthread_mutex_unlock(&queueMutex);
}
pthread_exit(0);
}
void *consumerFunc(void *t) {
long my_id = (long)t;
while(checkFinished()) {
threadRunCounts[my_id - 1] += 1;
pthread_mutex_lock(&queueMutex);
if(queue <= 0) {
consumerSleep++;
pthread_mutex_unlock(&queueMutex);
continue;
}
queue--;
pthread_mutex_unlock(&queueMutex);
}
pthread_exit(0);
}
int main(int argc, char* argv[]) {
pthread_t threads[3];
long t1 = 1, t2 = 2, t3 = 3;
int rc;
long t;
pthread_attr_t attr;
pthread_mutex_init(&queueMutex, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, consumerFunc, (void *)t1);
pthread_create(&threads[1], &attr, producerFunc, (void *)t2);
pthread_create(&threads[2], &attr, producerFunc, (void *)t3);
for (int i=0; i<3; i++) {
pthread_join(threads[i], 0);
}
printf("For a queue size of: %d , the total number of times the consumer went to sleep was %d , and the total number of times the producer went to sleep was %d\\n", queue, consumerSleep, producerSleep);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&queueMutex);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
sem_t mutexOccupied;
sem_t mutexFree;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int slots[5];
int nrOfItems = 0;
void processArgs(unsigned* producers, unsigned* consumers, int argc, char* argv[]);
void rest(int duration);
void* consumer(void* arg);
void* producer(void* arg);
int produceItem();
void insertItem(int item);
int getItem();
int main(int argc, char* argv[])
{
unsigned producers = 0;
unsigned consumers = 0;
processArgs(&producers, &consumers, argc, argv);
srand((unsigned)time(0));
sem_init(&mutexOccupied, 0, 0);
sem_init(&mutexFree, 0, 5);
pthread_t* producerIDs = malloc(producers * sizeof(pthread_t));
pthread_t* consumerIDs = malloc(consumers * sizeof(pthread_t));
for (unsigned i = 0; i < producers; i++)
{
unsigned* p = malloc(sizeof(unsigned));
*p = i;
pthread_create(&producerIDs[i], 0, producer, (void*)p);
}
for (unsigned i = 0; i < consumers; i++)
{
unsigned* p = malloc(sizeof(unsigned));
*p = i;
pthread_create(&consumerIDs[i], 0, consumer, (void*)p);
}
rest(50);
return 0;
}
void processArgs(unsigned* producers, unsigned* consumers, int argc, char* argv[])
{
if (argc < 2)
{
printf("Usage: PRODUCERS CONSUMERS");
exit(0);
}
*producers = atoi(argv[1]);
*consumers = atoi(argv[2]);
}
void rest(int duration)
{
time_t now = time(0);
while(time(0) - now < duration);
}
void* consumer(void* arg)
{
int item;
while(1)
{
rest(rand() % 5 + 1);
sem_wait(&mutexOccupied);
pthread_mutex_lock(&lock);
item = getItem();
printf("\\t\\t\\t\\tConsumer nr %i consumed item %i\\n", *(int*)arg, item);
pthread_mutex_unlock(&lock);
sem_post(&mutexFree);
}
}
void* producer(void* arg)
{
int item;
while(1)
{
rest(rand() % 5 + 1);
item = produceItem();
sem_wait(&mutexFree);
pthread_mutex_lock(&lock);
insertItem(item);
printf("Producer nr %i produced item %i\\n", *(int*)arg, item);
pthread_mutex_unlock(&lock);
sem_post(&mutexOccupied);
}
}
int produceItem()
{
return rand() % 9000 + 1000;
}
void insertItem(int item)
{
slots[nrOfItems++] = item;
}
int getItem()
{
int item = slots[0];
for (int i = 0; i < 5 - 1; i++)
{
slots[i] = slots[i+1];
}
slots[nrOfItems--] = 0;
return item;
}
| 0
|
#include <pthread.h>
int hAliviados =0;
int mAliviadas=0;
int hTotal = 0;
int mTotal=0;
int numeroPessoasTotais;
int homens;
int homensEsperando;
int mulheres;
int mulheresEsperando;
pthread_mutex_t mutex;
pthread_cond_t condHomens;
pthread_cond_t condMulheres;
}dados;
static dados sharedData={
.homens=0,
.homensEsperando=0,
.mulheres=0,
.mulheresEsperando=0,
.mutex=PTHREAD_MUTEX_INITIALIZER,
.condHomens=PTHREAD_COND_INITIALIZER,
.condMulheres=PTHREAD_COND_INITIALIZER
};
void usaBanheiro(int tempo){
int num2 = rand() % 100;
if (num2 <= 10)
sleep(2.5*tempo);
else
sleep(tempo);
}
void fazerAlgoDaVida(){
int tempo = rand() % 60;
sleep(tempo);
}
void animate(){
system("clear");
printf("================================\\n");
printf("==== Sexo atual no banheiro ====\\n");
if(sharedData.mulheres > 0){
printf("==== Feminino ====\\n");
printf("==== Quantidade: %1d ====\\n", sharedData.mulheres);
}
else if(sharedData.homens > 0){
printf("==== Masculino ====\\n");
printf("==== Quantidade: %1d ====\\n", sharedData.homens);
}else{
printf("==== Vazio ====\\n");
}
printf("================================\\n");
printf("==== Filas ====\\n");
printf("==== Homens: %2d ====\\n", sharedData.homensEsperando);
printf("==== Mulheres: %2d ====\\n", sharedData.mulheresEsperando);
printf("================================\\n");
printf("==== Vezes ====\\n");
printf("==== Homens: %2d ====\\n", hAliviados);
printf("==== Mulheres: %2d ====\\n", mAliviadas);
printf("================================\\n");
}
void* homem(void *info){
dados *banheiro=(dados*)info;
fazerAlgoDaVida();
pthread_mutex_lock(&banheiro->mutex);
while(banheiro->mulheres>0||banheiro->homens>2){
banheiro->homensEsperando++;
animate();
pthread_cond_wait(&banheiro->condHomens, &banheiro->mutex);
banheiro->homensEsperando--;
}
banheiro->homens++;
animate();
pthread_mutex_unlock(&banheiro->mutex);
usaBanheiro(1);
pthread_mutex_lock(&banheiro->mutex);
hAliviados++;
animate();
banheiro->homens--;
if(banheiro->mulheresEsperando > 0)
pthread_cond_broadcast(&banheiro->condMulheres);
else
pthread_cond_signal(&banheiro->condHomens);
pthread_mutex_unlock(&banheiro->mutex);
return 0;
}
void* mulher(void *info){
dados *banheiro=(dados*)info;
fazerAlgoDaVida();
pthread_mutex_lock(&banheiro->mutex);
while(banheiro->homens>0||banheiro->mulheres>2){
banheiro->mulheresEsperando++;
animate();
pthread_cond_wait(&banheiro->condMulheres, &banheiro->mutex);
banheiro->mulheresEsperando--;
}
banheiro->mulheres++;
animate();
pthread_mutex_unlock(&banheiro->mutex);
usaBanheiro(3);
pthread_mutex_lock(&banheiro->mutex);
mAliviadas++;
animate();
banheiro->mulheres--;
if(banheiro->homensEsperando > 0)
pthread_cond_broadcast(&banheiro->condHomens);
else
pthread_cond_signal(&banheiro->condMulheres);
pthread_mutex_unlock(&banheiro->mutex);
return 0;
}
int main(){
int i;
while(1){
int numH, numM;
printf("Entre o numero de homens e mulheres:\\n");
scanf("%d %d", &numH, &numM);
numeroPessoasTotais=numH+numM;
pthread_t threads[numeroPessoasTotais];
for(i=0; i<numH; i++){
pthread_create(&threads[i], 0, homem, &sharedData);
}
for(i=numH; i<numM+numH; i++){
pthread_create(&threads[i], 0, mulher, &sharedData);
}
for(i=0; i<numeroPessoasTotais; i++){
pthread_join(threads[i], 0);
}
}
return 0;
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
unsigned int __VERIFIER_nondet_uint();
static int top=0;
static unsigned int arr[(400)];
pthread_mutex_t m;
_Bool flag=(0);
void error(void)
{
ERROR:
__VERIFIER_error(); return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
(top==0) ? (1) : (0);
}
int push(unsigned int *stack, int x)
{
if (top==(400))
{
printf("stack overflow\\n");
return (-1);
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (top==0)
{
printf("stack underflow\\n");
return (-2);
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for(
i=0; i<(400); i++)
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint()%(400);
if ((push(arr,tmp)==(-1)))
error();
pthread_mutex_unlock(&m);
}
}
void *t2(void *arg)
{
int i;
for(
i=0; i<(400); i++)
{
pthread_mutex_lock(&m);
if (top>0)
{
if ((pop(arr)==(-2)))
error();
}
pthread_mutex_unlock(&m);
}
}
int main(void)
{
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 0
|
#include <pthread.h>
extern pthread_mutex_t __sfp_mutex;
extern pthread_cond_t __sfp_cond;
extern struct glue __sglue;
extern int __sfp_state;
static void __swalk_lflush()
{
register FILE *fp, *savefp;
register int n, saven;
register struct glue *g, *saveg;
pthread_mutex_lock(&__sfp_mutex);
__sfp_state++;
pthread_mutex_unlock(&__sfp_mutex);
saven = 0;
saveg = 0;
savefp = 0;
for (g = &__sglue; g != 0; g = g->next) {
for (fp = g->iobs, n = g->niobs; --n >= 0; fp++) {
if ((fp->_flags & (__SLBF|__SWR)) == (__SLBF|__SWR)) {
if (fp->_bf._base && (fp->_bf._base - fp->_p)) {
if (ftrylockfile(fp)) {
if (!saven) {
saven = n;
saveg = g;
savefp = fp;
continue;
}
} else {
(void) __sflush(fp);
funlockfile(fp);
}
}
}
}
}
if (savefp) {
for (g = saveg; g != 0; g = g->next) {
for (fp = savefp, n = saven + 1; --n >= 0; fp++) {
if ((fp->_flags & (__SLBF|__SWR)) == (__SLBF|__SWR)) {
while (fp->_bf._base && (fp->_bf._base - fp->_p)) {
flockfile(fp);
(void) __sflush(fp);
funlockfile(fp);
}
}
}
}
}
pthread_mutex_lock(&__sfp_mutex);
if (! (--__sfp_state)) {
pthread_cond_signal(&__sfp_cond);
}
pthread_mutex_unlock(&__sfp_mutex);
}
__srefill(fp)
register FILE *fp;
{
__sinit ();
fp->_r = 0;
if (fp->_flags & __SEOF)
return (EOF);
if ((fp->_flags & __SRD) == 0) {
if ((fp->_flags & __SRW) == 0) {
errno = EBADF;
return (EOF);
}
if (fp->_flags & __SWR) {
if (__sflush(fp))
return (EOF);
fp->_flags &= ~__SWR;
fp->_w = 0;
fp->_lbfsize = 0;
}
fp->_flags |= __SRD;
} else {
if (HASUB(fp)) {
FREEUB(fp);
if ((fp->_r = fp->_ur) != 0) {
fp->_p = fp->_up;
return (0);
}
}
}
if (fp->_file == -1) {
fp->_flags |= __SEOF;
return(EOF);
}
if (fp->_bf._base == 0)
__smakebuf(fp);
if (fp->_flags & (__SLBF|__SNBF))
__swalk_lflush();
fp->_p = fp->_bf._base;
fp->_r = __sread(fp, (char *)fp->_p, fp->_bf._size);
fp->_flags &= ~__SMOD;
if (fp->_r <= 0) {
if (fp->_r == 0)
fp->_flags |= __SEOF;
else {
fp->_r = 0;
fp->_flags |= __SERR;
}
return (EOF);
}
return (0);
}
| 1
|
#include <pthread.h>
int comptador;
pthread_t ntid[100];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void barrera()
{
pthread_mutex_lock(&mutex);
comptador = comptador - 1;
if (comptador == 0) {
comptador = 100;
pthread_cond_broadcast(&cond);
} else {
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
}
void *thr_fn(void *arg)
{
int i, j;
j = 0;
for(i = 0; i < 10; i++)
{
j++;
barrera();
printf("%d ", j);
}
return ((void *)0);
}
int main(void)
{
int i, err;
comptador = 100;
for(i = 0; i < 100; i++) {
err = pthread_create(ntid+i, 0, thr_fn, 0);
if (err != 0) {
printf("no puc crear el fil numero %d.", i);
exit(1);
}
}
for(i = 0; i < 100; i++) {
err = pthread_join(ntid[i], 0);
if (err != 0) {
printf("error pthread_join al fil %d\\n", i);
exit(1);
}
}
}
| 0
|
#include <pthread.h>
sem_t clientes, foiChamado;
pthread_mutex_t mutex;
pthread_cond_t atendentes;
int proximoCliente, ultimoCliente;
void *Atendentes(void *arg){
int i, pid = * (int *) arg;
proximoCliente = pid;
while(1){
sem_wait(&clientes);
printf("Tem clientes na padaria!\\n");
pthread_mutex_lock(&mutex);
printf("Eu sou o atendente %d e chamo o cliente %d!\\n", pid, proximoCliente);
pthread_cond_broadcast(&atendentes);
sem_post(&foiChamado);
pthread_mutex_unlock(&mutex);
}
}
void *Clientes(void *arg){
int pid = * (int *) arg;
printf("Eu sou o cliente %d\\n", pid);
pthread_mutex_lock(&mutex);
while(pid > proximoCliente) {
printf("Eu sou o cliente %d e NÃO é a minha vez\\n", pid);
pthread_cond_wait(&atendentes, &mutex);
}
pthread_mutex_unlock(&mutex);
sem_post(&clientes);
sem_wait(&foiChamado);
printf("Eu sou o cliente %d e é minha vez\\n", pid);
printf("Cliente %d foi embora\\n", pid);
}
int main(int argc, char *argv[]) {
pthread_t atend[3];
pthread_t cli[20];
int i, *pid;
proximoCliente=0;
sem_init(&clientes, 0, 0);
sem_init(&foiChamado, 0, 0);
printf("Padaria abriu!\\n");
for (i = 0; i < 3; i++){
pid = malloc(sizeof(int));
if(pid == 0){
printf("--ERRO: malloc() em alocação threads\\n"); exit(-1);
}
*pid = i;
pthread_create(&atend[i], 0, Atendentes, (void *) pid);
}
for (i = 0; i < 20; i++){
pid = malloc(sizeof(int));
if(pid == 0){
printf("--ERRO: malloc() em alocação threads\\n"); exit(-1);
}
*pid = i;
pthread_create(&cli[i], 0, Clientes, (void *) pid);
}
for (i = 0; i < 20; i++) {
pthread_join(cli[i], 0);
}
printf("Padaria fechou!\\n");
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&atendentes);
return 0;
}
| 1
|
#include <pthread.h>
{
struct aahdr *prev;
struct aahdr *next;
char fun[64];
char what[64];
size_t size;
unsigned short dummy;
unsigned short magic;
} AAHDR;
static pthread_mutex_t aa_mtx;
static AAHDR *top = 0;
static int aa_debug = 0;
static inline int
aahdr_valid(AAHDR *ap)
{
unsigned char *cp;
if (ap == 0)
return 0;
if (ap->magic != 0x1234)
return 0;
cp = (unsigned char *) (ap+1);
if (cp[ap->size] != 0x56)
{
syslog(LOG_ERR, "aalloc: Buffer overrun for object at %p\\n", (ap+1));
return 0;
}
return 1;
}
void
a_dump(FILE *fp)
{
AAHDR *ap;
unsigned char *p;
fprintf(fp, "a_dump(): Start\\n");
pthread_mutex_lock(&aa_mtx);
ap = top;
while (ap)
{
p = (unsigned char *) (ap+1);
fprintf(fp, "%08p: magic=%04x:%02x, size=%lu, function=%s, object=%s\\n",
ap, ap->magic, p[ap->size], ap->size,
ap->fun ? ap->fun : "<null>",
ap->what ? ap->what : "<null>");
ap = ap->next;
}
pthread_mutex_unlock(&aa_mtx);
fprintf(fp, "a_dump(): Stop\\n");
}
void
a_init(void)
{
aa_debug = (getenv("AA_DEBUG") != 0);
top = 0;
pthread_mutex_init(&aa_mtx, 0);
}
static inline void *
safe_malloc(size_t size,
const char *fun,
const char *what)
{
int rsize;
void *p;
AAHDR *ap;
unsigned char *cp;
if (aa_debug)
rsize = size + sizeof(AAHDR) + 1;
else
rsize = size;
p = malloc(rsize);
if (p == 0)
{
syslog(LOG_ERR, "%s: %s: malloc(%lu - real=%lu): %m",
fun ? fun : "<unknown function>",
what ? what : "<unknown object>",
(unsigned long) size,
(unsigned long) rsize);
s_abort();
}
if (aa_debug)
{
ap = (AAHDR *) p;
pthread_mutex_lock(&aa_mtx);
ap->prev = 0;
if (top)
top->prev = ap;
ap->next = top;
top = ap;
ap->size = size;
strlcpy(ap->fun, fun, sizeof(ap->fun));
strlcpy(ap->what, what, sizeof(ap->what));
ap->magic = 0x1234;
cp = (unsigned char *) (ap+1);
cp[size] = 0x56;
p = (void *) cp;
pthread_mutex_unlock(&aa_mtx);
}
return p;
}
void *
a_malloc(size_t size, const char *what)
{
void *p;
p = safe_malloc(size, "a_malloc", what);
memset(p, 0, size);
return p;
}
void *
a_realloc(void *oldp, size_t nsize, const char *what)
{
void *p;
if (!oldp)
return safe_malloc(nsize, "a_realloc", what);
if (aa_debug)
{
AAHDR *ap;
ap = (AAHDR *) oldp;
--ap;
if (!aahdr_valid(ap))
{
syslog(LOG_ERR, "a_realloc: INVALID pointer");
s_abort();
}
p = safe_malloc(nsize, "a_realloc", what);
memcpy(p, oldp, ap->size > nsize ? nsize : ap->size);
a_free(oldp);
return p;
}
p = (void *) realloc(oldp, nsize);
if (p == 0)
{
syslog(LOG_ERR, "a_realloc: %s: realloc(...,%lu): %m",
what ? what : "<unknown object>",
(unsigned long) nsize);
s_abort();
}
return p;
}
void
a_free(void *p)
{
AAHDR *ap;
if (p == 0)
return;
if (aa_debug)
{
ap = (AAHDR *) p;
--ap;
if (!aahdr_valid(ap))
{
syslog(LOG_ERR, "a_free: INVALID pointer");
s_abort();
}
pthread_mutex_lock(&aa_mtx);
if (ap->prev)
ap->prev->next = ap->next;
if (ap->next)
ap->next->prev = ap->prev;
if (top == ap)
top = ap->next;
pthread_mutex_unlock(&aa_mtx);
}
free(p);
}
char *
a_strndup(const char *s,
size_t len,
const char *what)
{
char *ns;
if (s == 0)
return 0;
ns = (char *) safe_malloc(len+1, "a_strndup", what);
memcpy(ns, s, len);
ns[len] = '\\0';
return ns;
}
char *
a_strdup(const char *s,
const char *what)
{
char *ns;
int len;
if (s == 0)
return 0;
len = strlen(s);
ns = (char *) safe_malloc(len+1, "a_strdup", what);
memcpy(ns, s, len+1);
return ns;
}
| 0
|
#include <pthread.h>
static const int min_eat_ms[5] = {10, 10, 10, 10, 10};
static const int max_eat_ms[5] = {20, 20, 20, 20, 20};
static const int min_think_ms[5] = {10, 10, 10, 10, 10};
static const int max_think_ms[5] = {20, 20, 20, 20, 20};
static int times_eaten[5];
static void philosopher_cycle(int thread_num, pthread_mutex_t *left_fork,
pthread_mutex_t *right_fork, unsigned *seed);
static void millisleep(int ms);
static void sleep_rand_r(int min_ms, int max_ms, unsigned *seed);
static void sigint_handler(int sig);
int main(int argc, char **argv)
{
pthread_mutex_t forks[5];
struct sigaction act;
act.sa_handler = sigint_handler;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
sigaddset(&act.sa_mask, SIGINT);
sigaction(SIGINT, &act, 0);
time_t t = time(0);
for (int i = 0; i < 5; i++)
pthread_mutex_init(&forks[i], 0);
{
int thread_num = omp_get_thread_num();
pthread_mutex_t *left_fork = &forks[thread_num];
pthread_mutex_t *right_fork =
&forks[(thread_num + 1) % 5];
unsigned seed = t + thread_num;
while (1) {
philosopher_cycle(thread_num, left_fork, right_fork, &seed);
}
}
return 0;
}
static void philosopher_cycle(int thread_num, pthread_mutex_t *left_fork,
pthread_mutex_t *right_fork, unsigned *seed)
{
printf("Philosopher %d wants to eat!\\n", thread_num);
if (thread_num == 5 - 1) {
pthread_mutex_lock(right_fork);
printf("Philosopher %d picked up his right fork.\\n", thread_num);
millisleep(5);
pthread_mutex_lock(left_fork);
printf("Philosopher %d picked up his left fork and "
"started eating.\\n", thread_num);
} else {
pthread_mutex_lock(left_fork);
printf("Philosopher %d picked up his left fork.\\n", thread_num);
millisleep(5);
pthread_mutex_lock(right_fork);
printf("Philosopher %d picked up his right fork and "
"started eating.\\n", thread_num);
}
sleep_rand_r(min_eat_ms[thread_num], max_eat_ms[thread_num], seed);
times_eaten[thread_num]++;
pthread_mutex_unlock(left_fork);
pthread_mutex_unlock(right_fork);
printf("Philosopher %d is done eating and has released his "
"forks.\\n", thread_num);
sleep_rand_r(min_think_ms[thread_num], max_think_ms[thread_num], seed);
}
static void millisleep(int ms)
{
usleep(ms * 1000);
}
static void sleep_rand_r(int min_ms, int max_ms, unsigned *seed)
{
int range = max_ms - min_ms + 1;
int ms = rand_r(seed) % range + min_ms;
millisleep(ms);
}
static void sigint_handler(int sig)
{
putchar('\\n');
for (int i = 0; i < 5; i++) {
printf("Philsopher %d:\\n", i);
printf("\\t%d times eaten\\n\\n", times_eaten[i]);
}
exit(0);
}
| 1
|
#include <pthread.h>
int available_resources = 5;
pthread_mutex_t mtx;
int increase_count(int arg) {
pthread_mutex_lock(&mtx);
available_resources += arg;
printf("Released %d resources, %d remaining.\\n", arg, available_resources);
pthread_mutex_unlock(&mtx);
return 0;
}
int decrease_count(int arg)
{
pthread_mutex_lock(&mtx);
if (available_resources < arg)
return -1;
else
available_resources -= arg;
printf("Got %d resources, %d remaining.\\n", arg, available_resources);
pthread_mutex_unlock(&mtx);
return 0;
}
void *verif(void* arg)
{
if (!decrease_count(*(int*)arg))
{
increase_count(*(int*)arg);
}
}
int main()
{
if (pthread_mutex_init(&mtx, 0))
{
perror("The mutex could not be created!\\n");
return errno;
}
pthread_t thr[5];
int i, values[5] = {1, 1, 1, 1, 1};
for (i = 0; i < 5; ++i)
{
if (pthread_create(&thr[i], 0, verif, (void*)&values[i]))
{
perror("The thread could not be created!\\n");
return errno;
}
}
for (int i = 0; i < 5; ++i)
{
if (pthread_join(thr[i], 0))
{
perror("The thread could not be waited!\\n");
return errno;
}
}
return 0;
}
| 0
|
#include <pthread.h>
int divisor = 2;
int totalThread = 0;
pthread_mutex_t totalThreadMutex= PTHREAD_MUTEX_INITIALIZER;
struct threadInfo{
int threadNum;
int parentThreadCount;
};
int min(int a, int b){
if(a<=b){
return a;
}
else{
return b;
}
}
void *threadFunc(void *ptr){
struct threadInfo* parentInfo = (struct threadInfo*) ptr;
int numChildren = min(parentInfo->parentThreadCount/divisor, 16);
int i;
pthread_t pthreadArr[numChildren];
printf("START: %d\\n\\tparent children: %d\\n\\tchildren: %d\\n", parentInfo->threadNum, parentInfo->parentThreadCount, numChildren);
for(i = 0; i < numChildren; i++){
pthread_mutex_lock(&totalThreadMutex);
totalThread++;
struct threadInfo *childInfo = (struct threadInfo*)malloc(sizeof(struct threadInfo));
childInfo->threadNum = totalThread;
childInfo->parentThreadCount = numChildren;
pthread_mutex_unlock(&totalThreadMutex);
pthread_create(&pthreadArr[i], 0, threadFunc, childInfo);
}
for(i = 0; i < numChildren; i++){
pthread_join(pthreadArr[i], 0);
}
printf("END: %d\\n", parentInfo->threadNum);
return 0;
}
int main(void){
pthread_t pth;
struct threadInfo *info = (struct threadInfo*)malloc(sizeof(struct threadInfo));
pthread_mutex_lock(&totalThreadMutex);
totalThread++;
info->threadNum = totalThread;
pthread_mutex_unlock(&totalThreadMutex);
info->parentThreadCount = min(8/divisor, 16);
pthread_create(&pth, 0, threadFunc, info);
pthread_join(pth, 0);
printf("final ThreadCount: %d\\n", totalThread);
}
| 1
|
#include <pthread.h>
pthread_t ntid1;
pthread_t ntid2;
pthread_t ntid3;
pthread_mutex_t f_lock;
char c = 'c';
void
printids(const char *s)
{
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid %u tid %u (0x%x)\\n", s, (unsigned int)pid,
(unsigned int)tid, (unsigned int)tid);
}
void *
thr_fn1(void *arg)
{
while(1)
{
if(c == 'c')
{
pthread_mutex_lock(&f_lock);
c = 'a';
printf("%c \\n", c);
pthread_mutex_unlock(&f_lock);
}
else
{
continue;
}
}
return((void *)0);
}
void *
thr_fn2(void *arg)
{
while(1)
{
if(c == 'a')
{
pthread_mutex_lock(&f_lock);
c = 'b';
printf("%c \\n", c);
pthread_mutex_unlock(&f_lock);
}
else
{
continue;
}
}
return((void *)0);
}
void *
thr_fn3(void *arg)
{
while(1)
{
if(c == 'b')
{
pthread_mutex_lock(&f_lock);
c = 'c';
printf("%c \\n", c);
pthread_mutex_unlock(&f_lock);
}
else
{
continue;
}
}
return((void *)0);
}
int
main(int argc, char *argv[])
{
int err;
if (pthread_mutex_init(&f_lock, 0) != 0)
{
perror("mutex is out\\n");
}
err = pthread_create(&ntid1, 0, thr_fn1, 0);
if (err != 0)
{
perror("create thread error!\\n");
exit(0);
}
err = pthread_create(&ntid2, 0, thr_fn2, 0);
if (err != 0)
{
perror("create thread error!\\n");
exit(0);
}
pthread_detach(ntid2);
err = pthread_create(&ntid3, 0, thr_fn3, 0);
if (err != 0)
{
perror("create thread error!\\n");
exit(0);
}
pthread_detach(ntid2);
printids("main thread:");
sleep(1);
pthread_join(ntid1,0);
pthread_join(ntid2,0);
pthread_join(ntid3,0);
pthread_mutex_destroy(&f_lock);
exit(0);
}
| 0
|
#include <pthread.h>
struct producers{
int buffer[4];
pthread_mutex_t lock;
int readpos,writepos;
pthread_cond_t notempty;
pthread_cond_t notfull;
};
void init(struct producers *b){
pthread_mutex_init(&b->lock,0);
pthread_cond_init(&b->notempty,0);
pthread_cond_init(&b->notfull,0);
b->readpos = 0;
b->writepos = 0;
}
void put(struct producers *b,int data){
pthread_mutex_lock(&b->lock);
while((b->writepos + 1)%4 == b->readpos){
pthread_cond_wait(&b->notfull,&b->lock);
}
b->buffer[b->writepos] = data;
b->writepos++;
if(b->writepos >= 4) b->writepos = 0;
pthread_cond_signal(&b->notempty);
pthread_mutex_unlock(&b->lock);
}
int get(struct producers *b){
int data;
pthread_mutex_lock(&b->lock);
while(b->writepos == b->readpos){
pthread_cond_wait(&b->notempty,&b->lock);
}
data = b->buffer[b->readpos];
b->readpos++;
if(b->readpos >= 4)b->readpos = 0;
pthread_cond_signal(&b->notfull);
pthread_mutex_unlock(&b->lock);
return data;
}
struct producers buffer;
void * producer(void *data){
int n;
for(n = 0;n < 10;n++){
printf("Producer:%d --->\\n",n);
put(&buffer,n);
}
put(&buffer,(-1));
return 0;
}
void * consumer(void *data){
int d;
while(1){
d = get(&buffer);
if(d == (-1)) break;
printf("Consumer: --->%d\\n",d);
}
return 0;
}
int main(int argc,char * argv[]){
pthread_t tha,thb;
void *retval;
init(&buffer);
pthread_create(&tha,0,producer,0);
pthread_create(&thb,0,consumer,0);
pthread_join(tha,&retval);
pthread_join(thb,&retval);
return 0;
}
| 1
|
#include <pthread.h>
int arr[1000][1000];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void initArray()
{
int i = 0;
int j = 0;
for (i = 0; i < 1000; i++)
{
for (j = 0; j < 1000; j++)
{
srand(time(0));
arr[i][j] = rand() % 2;
}
}
}
int main()
{
initArray();
int sum = 0;
omp_set_num_threads(10);
int id;
int privatesum;
int startr;
int finishr;
int i;
int j;
{
id = omp_get_thread_num();
privatesum = 0;
startr = id * 100;
finishr = startr + 100;
for (i = startr; i < finishr; i++)
{
for (j = 0; j < 1000; j++)
{
privatesum += arr[i][j];
}
}
pthread_mutex_lock(&mutex);
sum += privatesum;
pthread_mutex_unlock(&mutex);
}
printf("%d", sum);
}
| 0
|
#include <pthread.h>
int sum = 0;
pthread_mutex_t sum_lock;
int** matrix;
{
int rows;
int cols;
int p;
int id;
}thread_arg;
void *threadSum(void *threadargs){
thread_arg* my_args;
my_args = (thread_arg*) threadargs;
int my_rows = my_args->rows;
int my_cols = my_args->cols;
int my_p = my_args->p;
int my_id = my_args->id;
int elements = my_rows * my_cols;
int local_sum, counter;
for(counter = my_id; counter < elements; counter += my_p){
local_sum += matrix[(counter / my_cols)][(counter % my_cols)];
}
pthread_mutex_lock(&sum_lock);
sum += local_sum;
pthread_mutex_unlock(&sum_lock);
pthread_exit(0);
}
int main(){
int row, col, p, rc, element;
printf("Number of rows: \\n");
scanf("%d", &row);
printf("Number of columns: \\n");
scanf("%d", &col);
printf("Number of threads: \\n");
scanf("%d", &p);
pthread_t threads[p];
thread_arg args[p];
matrix = malloc(row * sizeof(int));
for(int x =0; x < row; x++){
matrix[x] = malloc(col * sizeof(int));
}
element = 1;
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
matrix[i][j] = element;
element++;
}
}
pthread_mutex_init(&sum_lock, 0);
for(int k = 0; k < p; k++){
args[k].rows = row;
args[k].cols = col;
args[k].p = p;
args[k].id = k;
rc = pthread_create(&threads[k], 0, threadSum, (void*) &args[k]);
if(rc){
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
for(int q=0; q<p; q++){
pthread_join(threads[q], 0);
}
pthread_mutex_lock(&sum_lock);
printf("sum: %d \\n", sum);
pthread_mutex_unlock(&sum_lock);
pthread_mutex_destroy(&sum_lock);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
void *TRAIN_SIMA(){
struct Seg *B = blocks2[8][5];
struct Seg *N = blocks2[8][5];
struct Seg *A = blocks2[0][0];
int i = 0;
B->blocked = 1;
B->change = 1;
while(!stop){
while(1){
if(train_link[1] && train_link[1]->halt == 0){
break;
}
usleep(1000);
}
pthread_mutex_lock(&mutex_lockA);
N = Next2(B,1+i);
if(i > 0){
A = Next2(B,i);
}
if(!N){
while(1){
usleep(100000);
}
}
N->change = 1;
N->blocked = 1;
pthread_mutex_unlock(&mutex_lockA);
usleep(delayA/2);
pthread_mutex_lock(&mutex_lockA);
if(i>0){
A->change = 1;
A->blocked = 0;
}else{
B->change = 1;
B->blocked = 0;
}
pthread_mutex_unlock(&mutex_lockA);
usleep(delayA/2);
pthread_mutex_lock(&mutex_lockA);
if(N->type == 'T'){
i++;
}else{
B = N;
i = 0;
}
pthread_mutex_unlock(&mutex_lockA);
}
}
void *TRAIN_SIMB(){
struct Seg *B = blocks2[4][23];
struct Seg *N = blocks2[4][23];
struct Seg *A = blocks2[0][0];
int i = 0;
B->blocked = 1;
B->change = 1;
while(blocks2[4][23]->train == 0){}
while(!train_link[blocks2[4][23]->train]){}
train_link[blocks2[4][23]->train]->halt = 1;
while(train_link[blocks2[4][23]->train]->halt == 1){}
while(!stop){
while(1){
if(train_link[2] && train_link[2]->halt == 0){
break;
}
usleep(1000);
}
pthread_mutex_lock(&mutex_lockA);
N = Next2(B,1+i);
if(i > 0){
A = Next2(B,i);
}
if(!N){
while(1){
usleep(100000);
}
}
N->change = 1;
N->blocked = 1;
pthread_mutex_unlock(&mutex_lockA);
usleep(delayA/2);
pthread_mutex_lock(&mutex_lockA);
if(i>0){
A->change = 1;
A->blocked = 0;
}else{
B->change = 1;
B->blocked = 0;
}
pthread_mutex_unlock(&mutex_lockA);
usleep(delayA/2);
pthread_mutex_lock(&mutex_lockA);
if(N->type == 'T'){
i++;
}else{
B = N;
i = 0;
}
pthread_mutex_unlock(&mutex_lockA);
}
}
| 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) {
printf("inc_count(): thread %ld, count = %d Threshold reached. ",
my_id, count);
pthread_cond_signal(&count_threshold_cv);
printf("Just sent signal.\\n");
}
printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n",
my_id, count);
pthread_mutex_unlock(&count_mutex);
usleep(100000);
}
pthread_exit(0);
}
void *watch_count(void *t)
{
long my_id = (long)t;
printf("Starting watch_count(): thread %ld\\n", my_id);
pthread_mutex_lock(&count_mutex);
while (count < 12) {
printf("watch_count(): thread %ld Count = %d. Going into wait...\\n", my_id, count);
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %ld Condition signal received. Count= %d\\n", my_id, count);
printf("watch_count(): thread %ld Updating the value of count...\\n", my_id);
count += 125;
printf("watch_count(): thread %ld count now = %d.\\n", my_id, count);
}
printf("watch_count(): thread %ld Unlocking mutex.\\n", my_id);
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main(int argc, char argv[])
{
int i, rc;
long t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init(&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, watch_count, (void *)t1);
pthread_create(&threads[1], &attr, inc_count, (void *)t2);
pthread_create(&threads[2], &attr, inc_count, (void *)t3);
for (i = 0; i < 3; ++i) {
pthread_join(threads[i], 0);
}
printf("Main(): waited and joined with %d threads. Final value of count = %d. Done.\\n",
3, count);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_t t[7];
pthread_mutex_t mtx[10], m;
int sum[10];
int val[10][1000];
int cnt;
void * doIt(void *arg) {
while(cnt < 5) {
pthread_mutex_lock(&m);
if(cnt >= 5) {
pthread_mutex_unlock(&m);
break;
}
pthread_mutex_unlock(&m);
int x = rand() % 101;
int r = x % 10;
printf("%d ", x);
pthread_mutex_lock(&mtx[r]);
sum[r] += x;
val[r][ ++ val[r][0] ] = x;
if(x % 10 == 5)
++ cnt;
pthread_mutex_unlock(&mtx[r]);
}
return 0;
}
int main() {
srand(time(0));
int i, j;
pthread_mutex_init(&m, 0);
printf("Nr ");
for(i = 0; i < 10 ; ++ i)
pthread_mutex_init(&mtx[i], 0);
for(i = 0; i < 7; ++ i)
pthread_create(&t[i], 0, doIt, 0);
for(i = 0; i < 7; ++ i)
pthread_join(t[i], 0);
printf("\\n");
for(i = 0 ; i < 10 ; ++ i)
pthread_mutex_destroy(&mtx[i]);
pthread_mutex_destroy(&m);
printf("Numere cu ultima cifra 5: %d\\n", cnt);
for(i = 0; i < 10; ++ i) {
printf("sum[%d] = ", i);
for(j = 1; j <= val[i][0]; ++ j) {
if(j != 1)
printf("+ ");
printf("%d ", val[i][j]);
}
printf("= %d\\n", sum[i]);
}
pthread_mutex_destroy(&m);
return 0;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.