text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
static struct timespec timer;
static int timerset;
static unsigned int flags;
static pthread_cond_t cond;
static pthread_mutex_t mtx;
static pthread_t thr;
static void (*threadfunc)(void);
static void *thread(void *param){
(void)param;
threadfunc();
return 0;
}
int vfdm_cb_init(void (*threadmain)(void)) {
int res;
timerset = 0;
flags = 0;
pthread_mutex_init(&mtx, 0);
pthread_cond_init(&cond, 0);
threadfunc = threadmain;
res = pthread_create(&thr, 0, thread, 0);
if (res != 0) return -1;
return 0;
}
void vfdm_cb_close(void) {
pthread_join(thr, 0);
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&mtx);
}
static void timespec_add_ms(struct timespec *ts, unsigned int milliseconds) {
ts->tv_sec += milliseconds / 1000;
ts->tv_nsec += (milliseconds % 1000) * 1000000;
if (ts->tv_nsec > 1000000000) {
ts->tv_sec++;
ts->tv_nsec -= 1000000000;
}
}
void vfdm_cb_settimer(unsigned int milliseconds) {
timerset = 0;
clock_gettime(CLOCK_REALTIME, &timer);
timespec_add_ms(&timer, milliseconds);
timerset = 1;
}
void vfdm_cb_incrementtimer(unsigned int milliseconds) {
timespec_add_ms(&timer, milliseconds);
timerset = 1;
}
unsigned int vfdm_cb_wait(void) {
unsigned int flagscopy;
struct timespec timenow;
clock_gettime(CLOCK_REALTIME, &timenow);
if (timenow.tv_sec >= timer.tv_sec ||
(timenow.tv_sec == timer.tv_sec &&
timenow.tv_nsec >= timer.tv_nsec)) {
timerset = 0;
return VFDM_TIMEOUT;
}
pthread_mutex_lock(&mtx);
while(1)
{
if (flags)
{
flagscopy = flags;
flags = 0;
return flagscopy;
}
else
{
int res;
if (timerset) {
res = pthread_cond_timedwait(&cond, &mtx, &timer);
if (res == ETIMEDOUT) {
timerset = 0;
flags |= VFDM_TIMEOUT;
}
} else {
pthread_cond_wait(&cond, &mtx);
}
}
}
}
void vfdm_cb_signal(unsigned int flagstoset) {
flags |= flagstoset;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mtx);
}
void vfdm_cb_lock(void) {
pthread_mutex_lock(&mtx);
}
void vfdm_cb_unlock(void) {
pthread_mutex_unlock(&mtx);
}
| 1
|
#include <pthread.h>
struct memory_list {
struct memory_list *next;
};
struct chunk_list {
struct chunk_list *next;
struct memory_list *data;
};
static struct memory_list * _free_list[((16384)/(8))] = {0};
static pthread_mutex_t _free_list_locks[((16384)/(8))];
static struct chunk_list * _chunk_list = 0;
static pthread_mutex_t _chunk_list_lock;
void smallalloc_init() {
memset(_free_list, 0, sizeof(_free_list));
int i;
for (i = 0; i < ((16384)/(8)); i++)
pthread_mutex_init(&_free_list_locks[i], 0);
pthread_mutex_init(&_chunk_list_lock, 0);
}
void smallalloc_release() {
int count = 0;
struct chunk_list *tmp = _chunk_list;
while (tmp != 0) {
count++;
tmp = tmp->next;
}
struct chunk_list *list = malloc(sizeof(struct chunk_list)*count);
int i;
for (i=0,tmp=_chunk_list; i < count; i++,tmp=tmp->next)
memcpy(list+i, tmp, sizeof(struct chunk_list));
for (i = 0; i < count; i++)
free(list[i].data);
free(list);
for (i = 0; i < ((16384)/(8)); i++)
pthread_mutex_destroy(&_free_list_locks[i]);
pthread_mutex_destroy(&_chunk_list_lock);
}
static inline unsigned int __chunk_index(unsigned int size) {
unsigned int index = (size-1) / (8);
assert(index >= 0 && index < ((16384)/(8)));
return index;
}
static inline int __min(int a, int b) {
return a < b? a : b;
}
static struct memory_list * __alloc_chunk(unsigned int index) {
assert(_free_list[index] == 0);
int node_size = (index+1) * (8);
int chunk_size = __min(node_size*(64), (16384)/node_size*node_size);
struct memory_list *list = malloc(chunk_size);
int i;
struct memory_list *iter = list;
for (i = 0; i <= chunk_size-2*node_size; i+=node_size)
iter = iter->next = (struct memory_list *)((char *)iter + node_size);
iter->next = 0;
return list;
}
void * smallalloc_allocate(unsigned int size) {
unsigned int index = __chunk_index(size);
pthread_mutex_lock(&_free_list_locks[index]);
if (_free_list[index] == 0) {
struct memory_list *new_chunk = __alloc_chunk(index);
_free_list[index] = new_chunk;
struct chunk_list *node;
if (__chunk_index(sizeof(struct chunk_list)) == index) {
node = (struct chunk_list *)_free_list[index];
_free_list[index] = _free_list[index]->next;
}
else {
node = smallalloc_allocate(sizeof(struct chunk_list));
}
pthread_mutex_lock(&_chunk_list_lock);
node->data = new_chunk;
node->next = _chunk_list;
_chunk_list = node;
pthread_mutex_unlock(&_chunk_list_lock);
}
struct memory_list *ret = _free_list[index];
_free_list[index] = ret->next;
pthread_mutex_unlock(&_free_list_locks[index]);
return (void *)ret;
}
void smallalloc_deallocate(void *mem, unsigned int size) {
unsigned int index = __chunk_index(size);
pthread_mutex_lock(&_free_list_locks[index]);
struct memory_list *tmp = mem;
tmp->next = _free_list[index];
_free_list[index] = tmp;
pthread_mutex_unlock(&_free_list_locks[index]);
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error() ;
static int iTThreads = 2;
static int iRThreads = 1;
static int data1Value = 0;
static int data2Value = 0;
pthread_mutex_t *data1Lock;
pthread_mutex_t *data2Lock;
void lock(pthread_mutex_t *);
void unlock(pthread_mutex_t *);
void *funcA(void *param) {
pthread_mutex_lock(data1Lock);
data1Value = 1;
pthread_mutex_unlock(data1Lock);
pthread_mutex_lock(data2Lock);
data2Value = data1Value + 1;
pthread_mutex_unlock(data2Lock);
return 0;
}
void *funcB(void *param) {
int t1 = -1;
int t2 = -1;
pthread_mutex_lock(data1Lock);
if (data1Value == 0) {
pthread_mutex_unlock(data1Lock);
return 0;
}
t1 = data1Value;
pthread_mutex_unlock(data1Lock);
pthread_mutex_lock(data2Lock);
t2 = data2Value;
pthread_mutex_unlock(data2Lock);
if (t2 != (t1 + 1)) {
fprintf(stderr, "Bug found!\\n");
ERROR: __VERIFIER_error();
;
}
return 0;
}
int main(int argc, char *argv[]) {
int i,err;
if (argc != 1) {
if (argc != 3) {
fprintf(stderr, "./twostage <param1> <param2>\\n");
exit(-1);
} else {
sscanf(argv[1], "%d", &iTThreads);
sscanf(argv[2], "%d", &iRThreads);
}
}
data1Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
data2Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
if (0 != (err = pthread_mutex_init(data1Lock, 0))) {
fprintf(stderr, "pthread_mutex_init error: %d\\n", err);
exit(-1);
}
if (0 != (err = pthread_mutex_init(data2Lock, 0))) {
fprintf(stderr, "pthread_mutex_init error: %d\\n", err);
exit(-1);
}
pthread_t tPool[iTThreads];
pthread_t rPool[iRThreads];
for (i = 0; i < iTThreads; i++) {
if (0 != (err = pthread_create(&tPool[i], 0, &funcA, 0))) {
fprintf(stderr, "Error [%d] found creating 2stage thread.\\n", err);
exit(-1);
}
}
for (i = 0; i < iRThreads; i++) {
if (0 != (err = pthread_create(&rPool[i], 0, &funcB, 0))) {
fprintf(stderr, "Error [%d] found creating read thread.\\n", err);
exit(-1);
}
}
for (i = 0; i < iTThreads; i++) {
if (0 != (err = pthread_join(tPool[i], 0))) {
fprintf(stderr, "pthread join error: %d\\n", err);
exit(-1);
}
}
for (i = 0; i < iRThreads; i++) {
if (0 != (err = pthread_join(rPool[i], 0))) {
fprintf(stderr, "pthread join error: %d\\n", err);
exit(-1);
}
}
return 0;
}
void lock(pthread_mutex_t *lock) {
int err;
if (0 != (err = pthread_mutex_lock(lock))) {
fprintf(stderr, "Got error %d from pthread_mutex_lock.\\n", err);
exit(-1);
}
}
void unlock(pthread_mutex_t *lock) {
int err;
if (0 != (err = pthread_mutex_unlock(lock))) {
fprintf(stderr, "Got error %d from pthread_mutex_unlock.\\n", err);
exit(-1);
}
}
| 1
|
#include <pthread.h>
struct db
{
uint32_t num_keys;
uint32_t *keys;
uint32_t *num_values;
uint32_t **values;
pthread_mutex_t lock;
};
struct db *
db_open (const char *path, const int parallel)
{
struct db *d = malloc (sizeof *d);
(void) path;
(void) parallel;
if (0 != d)
{
d->num_keys = 0;
d->keys = 0;
d->num_values = 0;
d->values = 0;
}
pthread_mutex_init (&d->lock, 0);
return d;
}
bool
db_close (struct db *d)
{
if (0 == d)
return 0;
while (d->num_keys--)
free (d->values[d->num_keys]);
free (d->values);
free (d->num_values);
free (d->keys);
free (d);
pthread_mutex_destroy (&d->lock);
return 1;
}
bool
db_insert (struct db *d, const uint32_t key, const uint32_t value)
{
uint32_t i;
bool retval = 0;
pthread_mutex_lock (&d->lock);
if (0 == d)
goto exit;
for (i = 0; i < d->num_keys; i++)
if (key == d->keys[i])
break;
if (d->num_keys <= i)
{
if (0 == (d->keys = realloc (d->keys, (sizeof *d->keys)
* (++d->num_keys))))
goto exit;
d->keys[i] = key;
if (0 == (d->num_values = realloc (d->num_values,
(sizeof *d->num_values)
* d->num_keys)))
goto exit;
d->num_values[i] = 0;
if (0 == (d->values = realloc (d->values, (sizeof *d->values)
* d->num_keys)))
goto exit;
d->values[i] = 0;
}
if (0 == (d->values[i] = realloc (d->values[i], (sizeof *d->values[i])
* (d->num_values[i] + 1))))
goto exit;
d->values[i][d->num_values[i]++] = value;
retval = 1;
exit:
pthread_mutex_unlock (&d->lock);
return retval;
}
int32_t
db_query (struct db *d, const uint32_t key, uint32_t **values)
{
uint32_t i, j;
int32_t retval = -1;
pthread_mutex_lock (&d->lock);
if (0 == d)
goto exit;
for (i = 0; i < d->num_keys; i++)
if (key == d->keys[i])
break;
if (d->num_keys <= i)
{
retval = 0;
goto exit;
}
if (0 == (*values = malloc ((sizeof **values) * d->num_values[i])))
goto exit;
for (j = 0; j < d->num_values[i]; j++)
*values[j] = d->values[i][j];
retval = d->num_values[i];
exit:
pthread_mutex_unlock (&d->lock);
return retval;
}
| 0
|
#include <pthread.h>
int philosopherMonitor = 1;
int philosopherState[5];
int philosopherFood = 1;
pthread_t philosopherThread[5];
pthread_mutex_t philosopherMonitorMutex;
pthread_cond_t philosopherReadyResource;
void *create_philosopher(void *number);
void pickup_forks(int,int,int);
void return_forks(int,int,int);
int main()
{
int counter;
pthread_mutex_init(&philosopherMonitorMutex,0);
pthread_cond_init(&philosopherReadyResource,0);
for ( counter = 0; counter < 5; counter++ )
{
int *argument = malloc(sizeof(*argument));
*argument = counter;
pthread_create(&philosopherThread[counter],0,create_philosopher,argument);
}
for ( counter = 0; counter < 5; counter++ )
{
pthread_join(philosopherThread[counter],0);
}
return 0;
}
void *create_philosopher(void *number)
{
int philosopherID, leftFork, rightFork;
philosopherID = *((int *) number);
philosopherState[philosopherID] = 0;
printf("The philosopher (ID %d) is currently pondering.\\n", philosopherID);
rightFork = philosopherID;
leftFork = (philosopherID + 1)%5;
while (philosopherFood > 0)
{
pickup_forks(philosopherID,leftFork,rightFork);
sleep(rand() % 3);
}
return (0);
}
void pickup_forks(int philosopherID,int f1,int f2)
{
pthread_mutex_lock(&philosopherMonitorMutex);
philosopherState[philosopherID] = philosopherMonitor;
if ( ( philosopherState[(philosopherID+4)%5] != 2 ) && ( philosopherState[philosopherID] == 1 ) )
{
philosopherState[philosopherID] = 2;
pthread_cond_signal(&philosopherReadyResource);
}
if ( philosopherState[philosopherID] != 2 )
{
pthread_cond_wait(&philosopherReadyResource,&philosopherMonitorMutex);
printf("The philosopher (ID %d) is now consuming the food.\\n", philosopherID);
return_forks(philosopherID,f1,f2);
sleep(rand() % 3);
}
pthread_mutex_unlock(&philosopherMonitorMutex);
}
void return_forks(int philosopherID,int f1,int f2)
{
philosopherState[philosopherID] = 0;
philosopherID = (philosopherID+4)%5;
if ( ( philosopherState[(philosopherID+4)%5] != 2 ) && ( philosopherState[philosopherID] == 1 ) )
{
philosopherState[philosopherID] = 2;
pthread_cond_signal(&philosopherReadyResource);
}
philosopherID = (philosopherID+1)%5;
if ( ( philosopherState[(philosopherID+4)%5] != 2 ) && ( philosopherState[philosopherID] == 1 ) )
{
philosopherState[philosopherID] = 2;
pthread_cond_signal(&philosopherReadyResource);
}
}
| 1
|
#include <pthread.h>
static FILE* log_fp = 0;
static int log_count = 0;
static pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER;
int log_open(const char* name, const char* mode)
{
pthread_mutex_lock(&log_lock);
if (!log_fp) {
log_fp = fopen(name, mode);
if (!log_fp) {
perror("log_open");
pthread_mutex_unlock(&log_lock);
return -1;
}
}
log_count++;
pthread_mutex_unlock(&log_lock);
return 0;
}
void log_close()
{
pthread_mutex_lock(&log_lock);
if (log_count > 0) {
if ((--log_count == 0) && log_fp && log_fp != stdout) {
fclose(log_fp);
log_fp = 0;
}
}
pthread_mutex_unlock(&log_lock);
}
void log_msg(int err, const char* fmt, ...)
{
va_list args;
pthread_mutex_lock(&log_lock);
if (log_fp) {
__builtin_va_start((args));
if (err) {
char s[256];
vsnprintf(s, sizeof(s), fmt, args);
fprintf(stderr, "%s", s);
fprintf(log_fp, "%s", s);
fflush(log_fp);
} else {
vfprintf(log_fp, fmt, args);
fflush(log_fp);
}
;
} else {
__builtin_va_start((args));
if (err) {
vfprintf(stderr, fmt, args);
} else {
vfprintf(stdout, fmt, args);
fflush(stdout);
}
;
}
pthread_mutex_unlock(&log_lock);
}
| 0
|
#include <pthread.h>
const int MAX = 10;
int thread_number = -1;
pthread_mutex_t mutex;
char _getch();
void* thread_print(void*);
int main()
{
char ch;
pthread_t thread[MAX];
pthread_mutex_init(&mutex, 0);
while(1)
{
ch = _getch();
switch(ch)
{
case '+':
thread_number++;
if(thread_number < MAX-1)
{
if (pthread_create(&thread[thread_number],
0,
thread_print,
&thread_number) != 0)
puts("Error of creating thread");
}
break;
case '-':
if(thread_number >= 0)
{
pthread_mutex_lock(&mutex);
pthread_cancel(thread[thread_number]);
pthread_mutex_unlock(&mutex);
thread_number--;
}
else
printf("There aren't any threads");
break;
case 'q':
while(thread_number > 0)
{
pthread_mutex_lock(&mutex);
pthread_cancel(thread[thread_number]);
pthread_mutex_unlock(&mutex);
thread_number--;
}
pthread_mutex_destroy(&mutex);
return 0;
break;
}
}
return 0;
}
void* thread_print(void *arg)
{
int i = 0;
char string[30];
int id = * (int *) arg;
sprintf(string, "Thread %d is running", id+1);
while(1)
{
pthread_mutex_lock(&mutex);
for(i = 0; i < strlen(string); i++)
{
printf("%c",string[i]);
usleep(30000);
fflush(stdout);
}
printf("\\n");
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_exit(0);
}
char _getch()
{
struct termios old, new;
char ch;
tcgetattr(0, &old);
new = old;
new.c_lflag &= ~(ICANON | ECHO);
tcsetattr(0, TCSANOW, &new);
ch = getchar();
tcsetattr(0, TCSANOW, &old);
return ch;
}
| 1
|
#include <pthread.h>
static struct {
char error_str[512];
char __zero;
} io_util;
void io_sleep_to(struct ds_timespec *abstime)
{
pthread_mutex_t tmp_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t tmp_cond = PTHREAD_COND_INITIALIZER;
struct timespec time;
time.tv_sec = abstime->tv_sec;
time.tv_nsec = abstime->tv_nsec;
pthread_mutex_lock(&tmp_mutex);
pthread_cond_timedwait(&tmp_cond, &tmp_mutex, &time);
pthread_mutex_unlock(&tmp_mutex);
}
void io_usleep(unsigned int usec)
{
struct ds_timespec abstime;
ds_make_timeout_us(&abstime, usec);
io_sleep_to(&abstime);
}
bool io_set_fd_nonblocking(int fd)
{
int ret, flags;
flags = fcntl(fd, F_GETFL, 0);
if (flags < 0)
flags = 0;
ret = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
if (ret < 0)
return 0;
return 1;
}
void io_set_latest_error(const char *fmt, ...)
{
va_list ap;
__builtin_va_start((ap));
vsnprintf(io_util.error_str, sizeof(io_util.error_str), fmt, ap);
;
}
const char *io_get_latest_error(void)
{
return io_util.error_str;
}
| 0
|
#include <pthread.h>
extern int makethread(void *(*)(void *), void *);
struct to_info {
void (*to_fn)(void *);
void *to_arg;
struct timespec to_wait;
};
void clock_gettime(struct timespec *tsp)
{
struct timeval tv;
gettimeofday(&tv, 0);
tsp -> tv_sec = tv.tv_sec;
tsp -> tv_nsec = tv.tv_usec * 1000;
}
void *timeout_helper(void *arg)
{
struct to_info *tip;
tip = (struct to_info*)arg;
nanosleep(&tip->to_wait, 0);
(*tip->to_fn)(tip->to_arg);
free(arg);
return (void *)0;
}
void
timeout(const struct timespec *when, void (*func)(void *), void *arg)
{
struct timespec now;
struct to_info *tip;
int err;
clock_gettime(&now);
if ((when -> tv_sec > now.tv_sec) ||
(when -> tv_sec == now.tv_sec && when -> tv_nsec > now.tv_nsec)) {
tip = malloc(sizeof(struct to_info));
if (tip != 0) {
tip -> to_fn = func;
tip -> to_arg = arg;
tip -> to_wait.tv_sec = when -> tv_sec - now.tv_sec;
if (when -> tv_nsec >= now.tv_nsec) {
tip -> to_wait.tv_nsec = when -> tv_nsec - now.tv_nsec;
} else {
tip -> to_wait.tv_sec--;
tip -> to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec;
}
err = makethread(timeout_helper, (void *)tip);
if (err == 0)
return;
else
free(tip);
}
}
(*func)(arg);
}
pthread_mutexattr_t attr;
pthread_mutex_t mutex;
void retry(void *arg)
{
pthread_mutex_lock(&mutex);
printf("arg is %lu\\n", (unsigned long)arg);
pthread_mutex_unlock(&mutex);
}
int main(void)
{
int err, condition, arg;
struct timespec when;
condition = 0;
arg = 0;
if ((err = pthread_mutexattr_init(&attr)) != 0)
err_exit(err, "pthread_mutexattr_init failed");
if ((err = pthread_mutexattr_settype(&attr,
PTHREAD_MUTEX_RECURSIVE)) != 0)
err_exit(err, "pthread_mutexattr_settype failed");
if ((err = pthread_mutex_init(&mutex, &attr)) != 0)
err_exit(err, "can't create recursive mutex");
pthread_mutex_lock(&mutex);
while (condition++ < 10) {
clock_gettime(&when);
when.tv_sec += 10;
timeout(&when, retry, (void *)(unsigned long)arg++);
}
pthread_mutex_unlock(&mutex);
sleep(11);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t ready_queue_mutex;
pthread_barrier_t init_barrier;
int* marked;
int id;
struct ready_queue *next;
};
struct ready_queue *head;
struct ready_queue *tail;
struct ready_queue *empty_queue;
int lower_bound;
int upper_bound;
int k;
int work_ready;
};
struct work **jobs;
int slave_num;
pthread_t id;
pthread_cond_t cond;
pthread_mutex_t mutex;
};
struct slave **slaves;
void *slaveLogic(void *arg){
struct slave *slave_info = (struct slave*)arg;
struct ready_queue *queue_position = malloc(sizeof(struct ready_queue));
struct work *slave_work = jobs[slave_info->slave_num];
int i;
queue_position->id = slave_info->slave_num;
pthread_barrier_wait(&init_barrier);
for(;;){
pthread_mutex_lock(&ready_queue_mutex);
if(tail == empty_queue){
head = queue_position;
tail = head;
}
else{
tail->next = queue_position;
tail = tail->next;
tail->next = empty_queue;
}
pthread_mutex_unlock(&ready_queue_mutex);
pthread_mutex_lock(&slave_info->mutex);
while(slave_work->work_ready != 1)
pthread_cond_wait(&slave_info->cond,&slave_info->mutex);
pthread_mutex_unlock(&slave_info->mutex);
for(i=slave_work->lower_bound;i<=slave_work->upper_bound;i++){
if(i%(slave_work->k) == 0){
marked[i] = 1;
}
}
slave_work->work_ready = 0;
}
return 0;
}
int main(int argc, char *argv[]){
int num_threads, n, chunk_size, i;
int chunks,j;
if(argc != 4){
printf("Usage ./%s -p -n -c\\n",argv[0]);
return 1;
}
else{
num_threads = atoi(argv[1]);
n=atoi(argv[2]);
chunk_size=atoi(argv[3]);
}
struct timeval start_time, end_time;
gettimeofday(&start_time,0);
printf("Calculating whether %d is prime using %d threads with a chunk size of %d.\\n",n,num_threads,chunk_size);
pthread_barrier_init(&init_barrier,0,num_threads+1);
jobs = malloc(sizeof(struct work*)*num_threads);
for(i=0;i<num_threads;i++){
jobs[i] = malloc(sizeof(struct work));
jobs[i]->work_ready = 0;
}
marked = malloc(sizeof(int)*(n+1));
for(i=0;i<n+1;i++)
marked[i] = 0;
empty_queue = malloc(1);
head = empty_queue;
tail = empty_queue;
slaves = malloc(sizeof(struct slave*)*num_threads);
for(i=0;i<num_threads;i++){
slaves[i] = malloc(sizeof(struct slave));
}
for(i=0;i<num_threads;i++){
slaves[i]->slave_num = i;
pthread_cond_init(&slaves[i]->cond,0);
pthread_create(&slaves[i]->id,0,slaveLogic,(void*)slaves[i]);
}
pthread_barrier_wait(&init_barrier);
int curr_id;
double percent;
long int elapsed;
for(i=2;i<(int)(floor(sqrt(n)));i++){
if(!marked[i]){
chunks = ceil((n-(i*i))/chunk_size);
for(j=0;j<=chunks;j++){
pthread_mutex_lock(&ready_queue_mutex);
while(head==empty_queue){
pthread_mutex_unlock(&ready_queue_mutex);
pthread_mutex_lock(&ready_queue_mutex);
}
curr_id = head->id;
if(head == tail){
head=empty_queue;
tail=empty_queue;
}
else head=head->next;
pthread_mutex_unlock(&ready_queue_mutex);
jobs[curr_id]->k=i;
jobs[curr_id]->lower_bound = (i*i)+(chunk_size*j);
jobs[curr_id]->upper_bound = ((i*i)+(chunk_size*(j+1)))-1;
if(jobs[curr_id]->upper_bound > n) jobs[curr_id]->upper_bound = n;
jobs[curr_id]->work_ready = 1;
pthread_cond_broadcast(&slaves[curr_id]->cond);
}
}
percent = (i/sqrt(n))*100;
gettimeofday(&end_time,0);
long int elapsed = (end_time.tv_usec + 1000000 *end_time.tv_sec) - (start_time.tv_usec + 1000000 * start_time.tv_sec);
printf("\\r");
printf("%02f%% completed. Time elapsed: %02ld.%06ld",percent,elapsed/1000000,elapsed%1000000);
}
printf("\\n");
for(i=0;i<num_threads;i++){
if(jobs[i]->work_ready==1) i=0;
}
gettimeofday(&end_time,0);
elapsed = (end_time.tv_usec + 1000000 *end_time.tv_sec) - (start_time.tv_usec + 1000000 * start_time.tv_sec);
printf("Caclulation complete.\\nTotal time elapsed:%ld seconds.\\n",elapsed/1000000);
if(marked[n]==0) printf("%d is prime\\n",n);
else printf("%d is not prime\\n",n);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t forks[5];
pthread_t phils[5];
void *philosopher (void *id);
int food_on_table ();
void get_fork (int, int, char *);
void down_forks (int, int);
pthread_mutex_t foodlock;
pthread_mutex_t nforks;
pthread_cond_t cond;
int sleep_seconds = 0;
int succeed = 0;
int main (int argc, char *argv[]) {
int i;
if (argc == 2)
sleep_seconds = atoi(argv[1]);
pthread_mutex_init (&foodlock, 0);
for (i = 0; i < 5; i++)
pthread_mutex_init(&forks[i], 0);
for (i = 0; i < 5; i++)
pthread_create (&phils[i], 0, philosopher, (void *)i);
for (i = 0; i < 5; i++)
pthread_join (phils[i], 0);
return 0;
}
void *philosopher(void *num) {
int id;
int left_fork, right_fork, f;
id = (int) num;
printf("Philosopher %d sitting down to dinner.\\n", id);
right_fork = id;
left_fork = id + 1;
if (left_fork == 5)
left_fork = 0;
while (f = food_on_table()) {
if (id == 1)
sleep(sleep_seconds);
printf("Philosopher %d: get dish %d.\\n", id, f);
pthread_mutex_lock(&nforks);
do {
if (pthread_mutex_trylock(&forks[right_fork]) == 0) {
succeed = 1;
}
if (pthread_mutex_trylock(&forks[left_fork]) != 0) {
if (succeed == 1)
pthread_mutex_unlock(&forks[right_fork]);
succeed = 0;
}
if (!succeed) pthread_cond_wait(&cond, &nforks);
} while (!succeed);
pthread_mutex_unlock(&nforks);
printf("Philosopher %d: eating.\\n", id);
usleep(30000 * (50 - f + 1));
down_forks(left_fork, right_fork);
}
printf("Philosopher %d is done eating.\\n", id);
return 0;
}
int food_on_table() {
static int food = 50;
int myfood;
pthread_mutex_lock(&foodlock);
if (food > 0) {
food--;
}
myfood = food;
pthread_mutex_unlock(&foodlock);
return myfood;
}
void get_fork (int phil, int fork, char *hand) {
pthread_mutex_lock (&forks[fork]);
printf ("Philosopher %d: got %s fork %d\\n", phil, hand, fork);
}
void down_forks(int f1, int f2) {
pthread_mutex_lock(&nforks);
pthread_mutex_unlock(&forks[f1]);
pthread_mutex_unlock(&forks[f2]);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&nforks);
}
| 1
|
#include <pthread.h>
int volatile total = 0;
int thread_count;
char* messages[100];
pthread_mutex_t total_mutex;
pthread_cond_t cond_var;
void Usage(char prog_name[]);
void *Thread_work(void* rank);
int main(int argc, char* argv[]) {
long i;
pthread_t* thread_handles;
if (argc != 2) Usage(argv[0]);
thread_count = strtol(argv[1], 0, 10);
thread_handles = malloc (thread_count*sizeof(pthread_t));
pthread_mutex_init(&total_mutex, 0);
pthread_cond_init(&cond_var, 0);
for (i = 0; i < thread_count; i++) {
pthread_create(&thread_handles[i], 0, Thread_work, (void*) i);
}
for (i = 0; i < thread_count; i++)
pthread_join(thread_handles[i], 0);
pthread_mutex_destroy(&total_mutex);
pthread_cond_destroy(&cond_var);
for (i = 0; i < thread_count; i++)
free(messages[i]);
free(thread_handles);
return 0;
}
void Usage(char prog_name[]) {
fprintf(stderr, "usage: %s <number of threads>\\n", prog_name);
exit(0);
}
void *Thread_work(void* rank) {
long my_rank = (long) rank;
int dest = (my_rank + 1) % thread_count;
messages[dest] = malloc(100*sizeof(char));
sprintf(messages[dest], "Greetings to %d from %ld", dest, my_rank);
pthread_mutex_lock(&total_mutex);
total++;
pthread_mutex_unlock(&total_mutex);
if (total == thread_count){
total =0;
pthread_cond_broadcast(&cond_var);
pthread_mutex_unlock(&total_mutex);
}else{
while(pthread_cond_wait(&cond_var, &total_mutex)!=0);
}
pthread_mutex_unlock(&total_mutex);
printf("Thread %ld > total = %d, %s\\n", my_rank, total,
messages[my_rank]);
return 0;
}
| 0
|
#include <pthread.h>
int start;
int end;
int *arr;
} thread_data_t;
static int g_swapped;
pthread_barrier_t barrier;
pthread_mutex_t mutex;
int *generate_data(int size) {
int *p = malloc(sizeof(int) * size);
int i;
for(i = 0; i < size; i++) {
p[i] = rand() % 1000;
}
return p;
}
void show(int p[], int size) {
int i;
for(i = 1; i < size; i++) {
assert(p[i-1] <= p[i]);
}
}
void swap(int *p, int i, int j) {
int tmp = p[i];
p[i] = p[j];
p[j] = tmp;
}
void serial_odd_even_sort(int *p, int size) {
int swapped, i;
do {
swapped = 0;
for(i = 1; i < size-1; i += 2) {
if(p[i] > p[i+1]) {
swap(p, i, i+1);
swapped = 1;
}
}
for(i = 0; i < size-1; i += 2) {
if(p[i] > p[i+1]) {
swap(p, i, i+1);
swapped = 1;
}
}
} while(swapped);
}
void *thread(void *arg) {
int start = ((thread_data_t *) arg)->start;
int end = ((thread_data_t *) arg)->end;
int *arr = ((thread_data_t *) arg)->arr;
int swapped, i;
do {
pthread_barrier_wait(&barrier);
g_swapped = 0;
swapped = 0;
for (i = start + 1; i < end - 1; i += 2) {
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = 1;
}
}
pthread_barrier_wait(&barrier);
for (i = start; i < end - 1; i += 2) {
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = 1;
}
}
pthread_mutex_lock(&mutex);
g_swapped = swapped | g_swapped;
pthread_mutex_unlock(&mutex);
pthread_barrier_wait(&barrier);
} while (g_swapped);
pthread_exit(0);
}
void parallel_odd_even_sort(int thread_count, int *p, int size) {
int i, frac = size/thread_count;
pthread_barrier_init(&barrier, 0, thread_count);
pthread_t threads[thread_count];
for (i = 0; i < thread_count; i++) {
thread_data_t *thread_data = (thread_data_t *) malloc(sizeof(thread_data_t));
int iintof = i * frac;
if (iintof % 2 == 1) {
thread_data->start = iintof - 1;
} else {
thread_data->start = iintof;
}
thread_data->end = iintof + frac + 1;
thread_data->arr = p;
assert(!pthread_create(&threads[i], 0, thread, (void *) thread_data));
}
for (i = 0; i < thread_count; i++) {
pthread_join(threads[i], 0);
}
pthread_barrier_destroy(&barrier);
}
int main() {
FILE *f = fopen("data.csv", "w");
int i, thr;
struct timespec start, end;
for(i = 100; i < 10000; i += 100) {
int *p = generate_data(i);
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
{
serial_odd_even_sort(p, i);
}
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
uint64_t delta_us = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
;
fprintf(f, "%d,%d,%lu\\n", 1, i, delta_us);
for(thr = 2; thr < 9; thr += 2) {
int size = sizeof(int) * i;
int *pp = malloc(size);
memcpy(pp, p, size);
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
{
parallel_odd_even_sort(thr, p, i);
}
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
uint64_t delta_us = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
;
fprintf(f, "%d,%d,%lu\\n", thr, i, delta_us);
}
free(p);
}
}
| 1
|
#include <pthread.h>
int thread_count = 3;
char input[1] = "\\0";
char buffer[100] = "\\0";
int file_read_complete = 0;
int file_process_complete = 0;
int end_of_buffer_index = 0;
int buffer_ready = 0;
pthread_mutex_t mutex_t1_t2 = PTHREAD_MUTEX_INITIALIZER;
int remove_last_word(char* string) {
int i = 0;
int j = 0;
int k = 0;
int just_found_space = 0;
while (string[i] != '\\0') {
if (string[i] == ' ') {
if (!just_found_space) {
k = j;
}
j = i;
just_found_space = 1;
} else {
just_found_space = 0;
}
i++;
}
if (just_found_space) {
if (k == 0) {
string[k] = '\\0';
return k;
} else {
string[k+1] = '\\0';
return k+1;
}
} else {
if (j == 0) {
string[j] = '\\0';
return j;
} else {
string[j+1] = '\\0';
return j+1;
}
}
}
void* read_input(void* file_name) {
char* f_name = (char*) file_name;
int fd = open(f_name, O_RDONLY);
int bytes_read = 1;
while (bytes_read == 1) {
pthread_mutex_lock(&mutex_t1_t2);
bytes_read = read(fd, input, 1);
pthread_mutex_unlock(&mutex_t1_t2);
}
file_read_complete = 1;
return 0;
}
void* process_input(void* arg) {
while (!file_read_complete) {
pthread_mutex_lock(&mutex_t1_t2);
while (buffer_ready);
switch (input[0]) {
case '*':
if (end_of_buffer_index > 0) {
end_of_buffer_index--;
buffer[end_of_buffer_index] = '\\0';
}
break;
case '@':
buffer_ready = 1;
break;
case '\\n':
buffer_ready = 1;
break;
case '$':
end_of_buffer_index = remove_last_word(buffer);
break;
case '&':
buffer[0] = '\\0';
end_of_buffer_index = 0;
break;
default:
strcat(buffer, input);
end_of_buffer_index++;
}
input[0] = '\\0';
pthread_mutex_unlock(&mutex_t1_t2);
}
file_process_complete = 1;
buffer_ready = 1;
return 0;
}
void* print_buffer(void* arg) {
while (!file_process_complete) {
while (!buffer_ready);
printf("%s\\n", buffer);
buffer[0] = '\\0';
end_of_buffer_index = 0;
buffer_ready = 0;
}
return 0;
}
int main(int argc, char* argv[]) {
if (argc != 2) {
printf("Usage: %s file-name\\n", argv[1]);
} else {
int rc[thread_count];
pthread_t threads[thread_count];
rc[0] = pthread_create(&threads[0], 0, read_input, (void*) argv[1]);
if (rc[0]) {
printf("ERROR: Return Code: %d\\n", rc[0]);
}
int thread_id = 2;
rc[1] = pthread_create(&threads[1], 0, process_input, (void*) thread_id);
if (rc[1]) {
printf("ERROR: Return Code: %d\\n", rc[1]);
}
thread_id = 3;
rc[2] = pthread_create(&threads[2], 0, print_buffer, (void*) thread_id);
if (rc[2]) {
printf("ERROR: Return Code: %d\\n", rc[2]);
}
int i;
for (i = 0; i < thread_count; i++) {
pthread_join(threads[i], 0);
}
return 0;
}
}
| 0
|
#include <pthread.h>
void **data;
size_t head, tail, used, cap;
sem_t empty_sem, filled_sem;
pthread_mutex_t buffer_mutex;
pthread_cond_t buffer_ready;
} RB_LOCK;
RB_LOCK *rb_lock_init(size_t capacity) {
if (capacity < 1) return 0;
RB_LOCK *rb = malloc(sizeof(RB_LOCK));
rb->data = malloc(capacity * sizeof(void *));
rb->cap = capacity;
rb->head = 0;
rb->tail = 0;
rb->used = 0;
pthread_mutex_init(&rb->buffer_mutex, 0);
pthread_cond_init (&rb->buffer_ready, 0);
sem_init(&rb->empty_sem, 0, capacity);
sem_init(&rb->filled_sem, 0, 0);
pthread_cond_broadcast(&rb->buffer_ready);
return rb;
}
void rb_lock_free(RB_LOCK *rb) {
if (rb == 0) return;
free(rb->data);
sem_destroy(&rb->empty_sem);
sem_destroy(&rb->filled_sem);
pthread_mutex_destroy(&rb->buffer_mutex);
pthread_cond_destroy (&rb->buffer_ready);
free(rb);
}
int rb_lock_isfull(RB_LOCK *rb) {
if (rb == 0) return -1;
return rb->used == rb->cap;
}
int rb_lock_isempty(RB_LOCK *rb) {
if (rb == 0) return -1;
return rb->used == 0;
}
int rb_lock_size(RB_LOCK *rb) {
if (rb == 0) return -1;
return rb->used;
}
int rb_lock_pushback(RB_LOCK *rb, void *data) {
int ret;
if (rb == 0) return -1;
while(1) {
pthread_testcancel();
ret = sem_wait(&rb->empty_sem);
if (ret == -1 && errno == EINTR) continue;
pthread_mutex_lock(&rb->buffer_mutex);
if (!rb_lock_isfull(rb)) {
*(rb->data + rb->tail) = (void *)data;
rb->tail = (rb->tail + 1) % rb->cap;
rb->used++;
ret = 0;
} else ret = -1;
pthread_mutex_unlock(&rb->buffer_mutex);
sem_post(&rb->filled_sem);
return ret;
}
}
void *rb_lock_popfront(RB_LOCK *rb) {
int ret;
if (rb == 0) return 0;
void *result = 0;
while (1) {
pthread_testcancel();
ret = sem_wait(&rb->filled_sem);
if (ret == -1 && errno == EINTR) continue;
pthread_mutex_lock(&rb->buffer_mutex);
if (!rb_lock_isempty(rb)) {
result = (rb->data)[rb->head];
rb->head = (rb->head + 1) % rb->cap;
rb->used--;
}
pthread_mutex_unlock(&rb->buffer_mutex);
sem_post(&rb->empty_sem);
return result;
}
}
int rb_lock_drain(RB_LOCK *rb, void **dest, size_t max) {
int ret;
size_t count;
while (rb) {
pthread_testcancel();
ret = sem_wait(&rb->filled_sem);
if (ret == -1 && errno == EINTR) continue;
count = 1;
while ( count < max) {
ret = sem_trywait(&rb->filled_sem);
if (ret == -1 && errno == EINTR) continue;
if (ret == -1 && errno == EAGAIN) break;
count++;
}
pthread_mutex_lock(&rb->buffer_mutex);
for (int i = 0; i < count; i++) {
dest[i] = (rb->data)[rb->head];
rb->head = (rb->head + 1) % rb->cap;
rb->used--;
}
pthread_mutex_unlock(&rb->buffer_mutex);
for (int i = 0; i < count; i++)
sem_post(&rb->empty_sem);
return count;
}
return -1;
}
| 1
|
#include <pthread.h>
sem_t barber_ready;
sem_t cust_ready;
pthread_mutex_t access_seats = PTHREAD_MUTEX_INITIALIZER, dummy_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t barber_busy = PTHREAD_COND_INITIALIZER;
int free_seats = 5;
void barber()
{
while(1)
{
sem_wait(&cust_ready);
pthread_mutex_lock(&access_seats);
free_seats += 1;
sem_post(&barber_ready);
pthread_mutex_unlock(&access_seats);
printf("The barber is cutting\\n");
pthread_mutex_lock(&dummy_mutex);
pthread_cond_wait(&barber_busy , &dummy_mutex);
pthread_mutex_unlock(&dummy_mutex);
}
}
void customer(void* c)
{
int cust_no = *((int*)c);
while(1)
{
pthread_mutex_lock(&access_seats);
if(free_seats>0)
{
free_seats--;
sem_post(&cust_ready);
pthread_mutex_unlock(&access_seats);
sem_wait(&barber_ready);
printf("Customer %d is having a hair cut\\n", cust_no);
sleep(rand()%4);
printf("Customer %d finished haircut\\n", cust_no);
pthread_cond_signal(&barber_busy);
}
else
{
pthread_mutex_unlock(&access_seats);
printf("Customer %d leaving without haircut\\n", cust_no);
}
sleep(4);
}
}
int main()
{
int i, id[5 +2];
sem_init(&barber_ready, 0, 0);
sem_init(&cust_ready, 0, 0);
pthread_t brbr, cust[5 +2];
pthread_attr_t brbr_attr;
pthread_attr_init(&brbr_attr);
pthread_create(&brbr, &brbr_attr, (void*)&barber, 0);
for(i=0 ; i<5 +2 ; ++i)
{
id[i] = i;
pthread_create(&cust[i], 0, (void*)customer, (void*)(&id[i]));
}
pthread_join(cust[0], 0);
return 0;
}
| 0
|
#include <pthread.h>
struct product_cons
{
int buffer[5];
pthread_mutex_t lock;
int readpos,writepos;
pthread_cond_t notempty;
pthread_cond_t notfull;
}buffer;
void init (struct product_cons *p)
{
pthread_mutex_init(&p->lock,0);
pthread_cond_init(&p->notempty,0);
pthread_cond_init(&p->notfull,0);
p->readpos=0;
p->writepos=0;
}
void finish(struct product_cons *p)
{
pthread_mutex_destroy(&p->lock);
pthread_cond_destroy(&p->notempty);
pthread_cond_destroy(&p->notfull);
p->readpos=0;
p->writepos=0;
}
void put(struct product_cons *p,int data )
{
printf("Now PUTs!!\\n");
pthread_mutex_lock(&p->lock);
if((p->writepos+1)%5==p->readpos)
{
printf("producer wait for not full\\n");
pthread_cond_wait(&p->notfull,&p->lock);
}
p->buffer[p->writepos]=data;
p->writepos ++;
if(p->writepos>=5)
p->writepos=0;
pthread_cond_signal(&p->notempty);
pthread_mutex_unlock(&p->lock);
}
int get(struct product_cons *p)
{
int data;
printf("Now Gets!!!\\n");
pthread_mutex_lock(&p->lock);
if((p->readpos==p->writepos)&&(p->writepos))
{
printf("consumer wait for not empty\\n");
pthread_cond_wait(&p->notempty,&p->lock);
}
data=p->buffer[p->readpos];
p->readpos++;
if(p->readpos>=5)
p->readpos=0;
pthread_cond_signal(&p->notfull);
pthread_mutex_unlock(&p->lock);
return data;
}
void *producer(void *data)
{
int n;
for (n=1;n<=20;++n)
{
sleep(1);
printf("\\nPut the %d product ..\\n",n);
put(&buffer,n);
printf("Put the %d product success \\n",n);
}
printf("producer stopped\\n");
return 0;
}
void *consumer(void *data)
{
static int cnt =0;
int num;
while (1)
{
sleep(2);
printf("\\nGet the %d product...\\n",num);
num=get(&buffer);
printf("get the %d product success\\n",num);
if(++cnt==30)
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);
finish(&buffer);
return 0;
}
| 1
|
#include <pthread.h>
{
int id;
int tieneTabaco;
int tienePapel;
int tieneFosforo;
int estaFumando;
int estaProduciendo;
int idProduccion;
} Fumador;
{
int hayTabaco;
int hayPapel;
int hayFosforo;
} Mesa;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
Fumador * fumadores;
Mesa mesa;
void * fumadorCtrl(void *);
void * productorCtrl(void *);
void printMesa();
void printFumador(int);
int main(int argc, const char * argv[])
{
pthread_t * tFumador = (pthread_t*)malloc(sizeof(pthread_t) * 3);
pthread_t * tProductor = (pthread_t*)malloc(sizeof(pthread_t) * 3);
fumadores = (Fumador*)malloc(sizeof(Fumador) * 3);
srand((int)time(0));
for (int i = 0; i < 3; ++i)
{
fumadores[i].id = i;
fumadores[i].tieneTabaco = 0;
fumadores[i].tienePapel = 0;
fumadores[i].tieneFosforo = 0;
fumadores[i].estaFumando = 0;
fumadores[i].estaProduciendo = 0;
fumadores[i].idProduccion = i % 3;
pthread_create((tFumador + i), 0, fumadorCtrl, (void*)(fumadores + i));
pthread_create((tProductor + i), 0, productorCtrl, (void*)(fumadores + i));
}
mesa.hayTabaco = 0;
mesa.hayPapel = 0;
mesa.hayFosforo = 0;
for (int i = 0; i < 3; ++i)
{
pthread_join(*(tFumador + i), 0);
pthread_join(*(tProductor + i), 0);
}
free(fumadores);
return 0;
}
void * fumadorCtrl(void * arg)
{
Fumador* data = (struct Fumador*)arg;
while (1 == 1)
{
int aFumar = 0;
pthread_mutex_lock(&mutex);
if (data->estaFumando == 0 && data->estaProduciendo == 0 &&
data->tienePapel == 1 && data->tieneTabaco == 1 && data->tieneFosforo == 1)
{
aFumar = 1;
data->estaFumando = 1;
data->tienePapel = 0;
data->tieneTabaco = 0;
data->tieneFosforo = 0;
}
pthread_mutex_unlock(&mutex);
if (aFumar == 1)
{
printf("Fumador (%d) :: esta fumando\\n", data->id);
sleep(2);
printf("Fumador (%d) :: esperando\\n", data->id);
sleep(1);
}
pthread_mutex_lock(&mutex);
data->estaFumando = 0;
if (mesa.hayPapel == 1 && data->tienePapel == 0)
{
printf("Fumador (%d) :: obtiene papel\\n", data->id);
data->tienePapel = 1;
mesa.hayPapel = 0;
printFumador(data->id);
printMesa();
}
if (mesa.hayTabaco == 1 && data->tieneTabaco == 0)
{
printf("Fumador (%d) :: obtiene tabaco\\n", data->id);
data->tieneTabaco = 1;
mesa.hayTabaco = 0;
printFumador(data->id);
printMesa();
}
if (mesa.hayFosforo == 1 && data->tieneFosforo == 0)
{
printf("Fumador (%d) :: obtiene fosforo\\n", data->id);
data->tieneFosforo = 1;
mesa.hayFosforo = 0;
printFumador(data->id);
printMesa();
}
pthread_mutex_unlock(&mutex);
}
}
void * productorCtrl(void * arg)
{
Fumador* data = (struct Fumador*)arg;
while (1 == 1)
{
int aProducir;
pthread_mutex_lock(&mutex);
if (data->estaProduciendo == 0 && data->estaFumando == 0)
{
aProducir = 1;
data->estaProduciendo = 1;
}
pthread_mutex_unlock(&mutex);
if (aProducir == 1)
sleep(1);
pthread_mutex_lock(&mutex);
int idProduccion = data->idProduccion;
if (idProduccion % 3 == 0 && mesa.hayPapel == 0)
{
mesa.hayPapel = 1;
printf("Produciendo papel\\n");
printMesa();
}
if (idProduccion % 3 == 1 && mesa.hayTabaco == 0)
{
mesa.hayTabaco = 1;
printf("Produciendo tabaco\\n");
printMesa();
}
if (idProduccion % 3 == 2 && mesa.hayFosforo == 0)
{
mesa.hayFosforo = 1;
printf("Produciendo fosforo\\n");
printMesa();
}
data->estaProduciendo = 0;
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void printMesa()
{
printf(" Mesa -> ");
printf(mesa.hayPapel ? "P" : "-");
printf(mesa.hayFosforo ? "F" : "-");
printf(mesa.hayTabaco ? "T" : "-");
printf("\\n");
}
void printFumador(int id)
{
printf(" Fumador -> ");
printf(fumadores[id].tienePapel ? "P" : "-");
printf(fumadores[id].tieneFosforo ? "F" : "-");
printf(fumadores[id].tieneTabaco ? "T" : "-");
printf("\\n");
}
| 0
|
#include <pthread.h>
int mediafirefs_chmod(const char *path, mode_t mode)
{
printf("FUNCTION: chmod. path: %s\\n", path);
(void)path;
(void)mode;
struct mediafirefs_context_private *ctx;
ctx = fuse_get_context()->private_data;
pthread_mutex_lock(&(ctx->mutex));
fprintf(stderr, "chmod not implemented\\n");
pthread_mutex_unlock(&(ctx->mutex));
return -ENOSYS;
}
| 1
|
#include <pthread.h>
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* threadAlarme (void* arg);
void* threadCompteur (void* arg);
int main (void)
{
pthread_t monThreadCompteur;
pthread_t monThreadAlarme;
pthread_create (&monThreadCompteur, 0, threadCompteur, (void*)0);
pthread_create (&monThreadAlarme, 0, threadAlarme, (void*)0);
pthread_join (monThreadCompteur, 0);
pthread_join (monThreadAlarme, 0);
return 0;
}
void* threadCompteur (void* arg)
{
int compteur = 0, nombre = 0;
srand(time(0));
while(1)
{
nombre = rand()%10;
compteur += nombre;
printf("\\n%d", compteur);
if(compteur >= 20)
{
pthread_mutex_lock (&mutex);
pthread_cond_signal (&condition);
pthread_mutex_unlock (&mutex);
compteur = 0;
}
sleep (1);
}
pthread_exit(0);
}
void* threadAlarme (void* arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait (&condition, &mutex);
printf("\\nLE COMPTEUR A DÉPASSÉ 20.");
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
char buffer[8000];
int bufCnt=0;
int numThreads=0;
void * readFile(void * fname)
{
int offset = numThreads*2000;
pthread_mutex_t lock_g;
pthread_mutex_lock(&lock_g);
int threadNum = numThreads++;
int readCnt=0;
char symbol='?';
FILE *f = fopen( (char*)fname, "rt" );
if ( !f )
{
fprintf( stderr, "Thread %d unable to open file %s\\n",threadNum, (char*)fname );
pthread_exit( (void*) -1 );
}
printf("thread %d reading file %s into buffer\\n", threadNum, (char*) fname);
pthread_mutex_unlock(&lock_g);
pthread_mutex_lock(&lock_g);
while (fscanf(f, "%c",&symbol) == 1 )
{
printf("%c",symbol);
buffer[offset+readCnt++]=symbol;
++bufCnt;
}
pthread_mutex_unlock(&lock_g);
return (void*)readCnt;
}
int main(int argc, char ** argv)
{
void* readCnts[4];
pthread_t threads[4];
for( int i=0 ; i<4 ; i++)
{
pthread_mutex_t lock_h;
pthread_mutex_lock(&lock_h);
pthread_create(&threads[i], 0, readFile, (void *)argv[i+1]);
pthread_mutex_unlock(&lock_h);
}
for( int i=0 ; i<4 ; i++)
{
pthread_mutex_t lock_h;
pthread_mutex_lock(&lock_h);
pthread_join( threads[i], &readCnts[i] );
pthread_mutex_unlock(&lock_h);
}
int each = 8000/4;
for (int i=0 ; i < bufCnt ; ++i )
printf("%5d:%c\\n", i, buffer[i]);
printf( "\\n");
for (int i=0 ; i < 4 ; ++i )
printf( "Thread %d read in %d symbols from file %s\\n", i+1, (int)readCnts[i] , argv[i+1] );
return 0;
}
| 1
|
#include <pthread.h>
int tcp_log = 1;
int imcp_log = 0;
pthread_mutex_t stdout_lock = PTHREAD_MUTEX_INITIALIZER;
void logger_ipv6(char *buffer) {
struct ip6_hdr *hdr = (struct ip6_hdr *) buffer;
struct in6_addr *src = &hdr->ip6_src;
struct in6_addr *dst = &hdr->ip6_dst;
uint8_t proto = hdr->ip6_ctlun.ip6_un1.ip6_un1_nxt;
char src_string[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, src, src_string, INET6_ADDRSTRLEN);
char dst_string[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, dst, dst_string, INET6_ADDRSTRLEN);
char *protocols[3] = {"icmp", "tcp", "udp"};
switch (proto) {
case IPPROTO_ICMPV6: {
if (imcp_log == 0) {
logger(protocols[0], src_string, dst_string, 0, 0);
imcp_log = 1;
} else {
imcp_log = 0;
}
break;
}
case IPPROTO_TCP: {
struct tcphdr *tcp = (struct tcphdr *) (buffer + sizeof(struct ip6_hdr));
if (ntohs(tcp->fin) != 0) {
if (tcp_log == 0) {
logger(protocols[1], src_string, dst_string, ntohs(tcp->th_sport), ntohs(tcp->th_dport));
tcp_log = 1;
} else {
tcp_log = 0;
}
}
break;
}
case IPPROTO_UDP: {
struct udphdr *udp = (struct udphdr *) (buffer + sizeof(struct ip6_hdr));
logger(protocols[2], src_string, dst_string, ntohs(udp->uh_sport), ntohs(udp->uh_dport));
break;
}
default: {
}
}
}
void logger(const char *protocol, const char *src, const char *dst, unsigned int src_port, unsigned int dst_port) {
pthread_mutex_lock(&stdout_lock);
time_t now;
struct tm ts;
char buf[80];
time(&now);
ts = *localtime(&now);
strftime(buf, sizeof(buf), "%Y/%m/%d %H:%M:%S", &ts);
char *out;
char src_port_s[10];
char dst_port_s[10];
if (src_port != -1 && dst_port != -1) {
sprintf(src_port_s, "%u", src_port);
sprintf(dst_port_s, "%u", dst_port);
}
asprintf(&out, "%s %s %s %s %s %s -\\n", buf, src, dst, protocol,
(src_port == 0) ? "-": src_port_s,
(dst_port == 0) ? "-": dst_port_s);
fprintf(stdout, "%s", out);
fflush(stdout);
fwrite(out, strlen(out), 1, log_file);
fflush(log_file);
pthread_mutex_unlock(&stdout_lock);
}
void open_log(char *name) {
log_file = fopen(name, "wt");
if (log_file == 0) {
fprintf(stderr, "ERROR: Unable to create log file\\n");
exit(2);
}
}
void close_log() {
if (fclose(log_file) == EOF) {
fprintf(stderr, "ERROR: Unable to close log file\\n");
exit(2);
}
}
| 0
|
#include <pthread.h>
int in = 0;
int out = 0;
int buff[10] = {0};
sem_t empty_sem;
sem_t full_sem;
pthread_mutex_t mutex;
int product_id = 0;
int prochase_id = 0;
void print()
{
int i;
for(i = 0; i < 10; i++)
printf("%d ", buff[i]);
printf("\\n");
}
void *product()
{
int id = ++product_id;
while(1)
{
sleep(1);
sem_wait(&empty_sem);
pthread_mutex_lock(&mutex);
in = in % 10;
printf("product%d in %d. like: \\t", id, in);
buff[in] = 1;
print();
++in;
pthread_mutex_unlock(&mutex);
sem_post(&full_sem);
}
}
void *prochase()
{
int id = ++prochase_id;
while(1)
{
sleep(1);
sem_wait(&full_sem);
pthread_mutex_lock(&mutex);
out = out % 10;
printf("prochase%d in %d. like: \\t", id, out);
buff[out] = 0;
print();
++out;
pthread_mutex_unlock(&mutex);
sem_post(&empty_sem);
}
}
int main()
{
pthread_t id1[2];
pthread_t id2[2];
int i;
int ret[2];
int ini1 = sem_init(&empty_sem, 0, 10);
int ini2 = sem_init(&full_sem, 0, 0);
if(ini1 && ini2 != 0)
{
printf("sem init failed %d%d\\n",ini1,ini2);
exit(1);
}
int ini3 = pthread_mutex_init(&mutex, 0);
if(ini3 != 0)
{
printf("mutex init failed \\n");
exit(1);
}
for(i = 0; i < 2; i++)
{
ret[i] = pthread_create(&id1[i], 0, product, (void *)(&i));
if(ret[i] != 0)
{
printf("product%d creation failed \\n", i);
exit(1);
}
}
for(i = 0; i < 2; i++)
{
ret[i] = pthread_create(&id2[i], 0, prochase, 0);
if(ret[i] != 0)
{
printf("prochase%d creation failed \\n", i);
exit(1);
}
}
for(i = 0; i < 2; i++)
{
pthread_join(id1[i],0);
pthread_join(id2[i],0);
}
exit(0);
}
| 1
|
#include <pthread.h>
void* funProd(void *arg);
void* funPosr(void *arg);
void* funKons(void *arg);
struct bufor
{
int dane[16];
int licznik;
int we;
int wy;
pthread_cond_t *zmWar;
pthread_mutex_t *semafor;
};
int czytaj(bufor_t *buf);
void zapisz(bufor_t *buf, int wartosc);
void inicjalizacjaBufora(bufor_t *buf, pthread_cond_t *zmWar, pthread_mutex_t *semafor);
int main()
{
bufor_t bufProdPosr;
bufor_t bufPosrKons;
pthread_cond_t zmWarProdPosr = PTHREAD_COND_INITIALIZER;
pthread_mutex_t semaforProdPosr = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t zmWarPosrKons = PTHREAD_COND_INITIALIZER;
pthread_mutex_t semaforPosrKons = PTHREAD_MUTEX_INITIALIZER;
inicjalizacjaBufora(&bufProdPosr, &zmWarProdPosr, &semaforProdPosr);
inicjalizacjaBufora(&bufPosrKons, &zmWarPosrKons, &semaforPosrKons);
pthread_t producent;
pthread_t posrednik;
pthread_t konsument;
bufor_t *tablica[] = {&bufProdPosr, &bufPosrKons};
pthread_create(&producent, 0, funProd, &bufProdPosr);
pthread_create(&posrednik, 0, funPosr, tablica);
pthread_create(&konsument, 0, funKons, &bufPosrKons);
pthread_join(producent, 0);
pthread_join(posrednik, 0);
pthread_join(konsument, 0);
return 0;
}
void* funProd(void *arg)
{
bufor_t *buf = (bufor_t *) arg;
int i;
for (i=0; i<20; i++)
{
sleep(1);
zapisz(buf, i);
}
}
void* funPosr(void *arg)
{
bufor_t **buf = (bufor_t **) arg;
bufor_t *buf1 = buf[0];
bufor_t *buf2 = buf[1];
int i;
for (i=0; i<20; i++)
{
int x = czytaj(buf1);
x *=2;
zapisz(buf2, x);
}
}
void* funKons(void *arg)
{
bufor_t *buf = (bufor_t *) arg;
int i;
for (i=0; i<20; i++)
{
int x = czytaj(buf);
printf("x = %d\\n", x);
}
}
int czytaj(bufor_t *buf)
{
pthread_mutex_lock(buf->semafor);
do
{
if (buf->licznik > 0)
break;
pthread_cond_wait(buf->zmWar, buf->semafor);
}
while (1);
buf->licznik--;
int wynik = buf->dane[buf->wy];
buf->wy++;
buf->wy %= 16;
pthread_mutex_unlock(buf->semafor);
pthread_cond_signal (buf->zmWar);
return wynik;
}
void zapisz(bufor_t *buf, int wartosc)
{
pthread_mutex_lock(buf->semafor);
for ( ; ; )
{
if (buf->licznik < 16)
break;
pthread_cond_wait(buf->zmWar, buf->semafor);
}
buf->licznik++;
buf->dane[buf->we] = wartosc;
buf->we++;
buf->we %= 16;
pthread_mutex_unlock(buf->semafor);
pthread_cond_signal (buf->zmWar);
}
void inicjalizacjaBufora(bufor_t *buf, pthread_cond_t *zmWar, pthread_mutex_t *semafor)
{
memset(buf, 0, sizeof(struct bufor));
buf->zmWar = zmWar;
buf->semafor = semafor;
}
| 0
|
#include <pthread.h>
struct prodcons
{
int buffer[16];
pthread_mutex_t lock;
int readpos, writepos;
pthread_cond_t notempty;
pthread_cond_t notfull;
};
void init(struct prodcons *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 prodcons *b, int data)
{
pthread_mutex_lock(&b->lock);
if ((b->writepos + 1) % 16 == b->readpos)
{
pthread_cond_wait(&b->notfull, &b->lock);
}
b->buffer[b->writepos] = data;
b->writepos++;
if (b->writepos >= 16)
b->writepos = 0;
pthread_cond_signal(&b->notempty);
pthread_mutex_unlock(&b->lock);
}
int get(struct prodcons *b)
{
int data;
pthread_mutex_lock(&b->lock);
if (b->writepos == b->readpos)
{
pthread_cond_wait(&b->notempty, &b->lock);
}
data = b->buffer[b->readpos];
b->readpos++;
if (b->readpos >= 16)
b->readpos = 0;
pthread_cond_signal(&b->notfull);
pthread_mutex_unlock(&b->lock);
return data;
}
struct prodcons buffer;
void *producer(void *data)
{
int n;
for (n = 0; n < 10; n++)
{
printf("%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("--->%d \\n", d);
}
return 0;
}
int main(void)
{
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;
}
| 1
|
#include <pthread.h>
int n=0;
pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
void* thread_func(void* arg) {
int param = (int) arg;
char c='1'+param;
int ret, i=0;
for(; i < 10; i++) {
pthread_mutex_lock(&mylock);
while(param != n) {
ret = pthread_cond_wait(&qready, &mylock);
if(ret == 0) {
} else {
}
}
printf("%c ",c);
n = (n+1)%4;
pthread_mutex_unlock(&mylock);
pthread_cond_broadcast(&qready);
}
return (void*) 0;
}
int main( int argc, char** argv) {
int i =0, err;
pthread_t tid[4];
void* tret;
for(; i<4; i++) {
err = pthread_create(&tid[i], 0, thread_func, (void*)i);
if(err != 0) {
printf("thread_create error:%s\\n", strerror(err));
exit(-1);
}
}
for(i=0; i < 4; i++) {
err = pthread_join(tid[i], &tret);
if(err != 0) {
printf("can not join with thread %d:%s\\n", i, strerror(err));
exit(-1);
}
}
printf("\\n");
return 0;
}
| 0
|
#include <pthread.h>
struct msg {
struct msg *next;
int num;
};
struct msg *head;
pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void *consumer(void *p) {
struct msg *mp;
for (;;) {
pthread_mutex_lock(&lock);
while (head == 0){
pthread_cond_wait(&has_product, &lock);
}
mp = head;
head = mp->next;
pthread_mutex_unlock(&lock);
printf("Consumer %d\\n", mp->num);
free(mp);
sleep(rand() % 5);
}
}
void *producer(void *p) {
struct msg *mp;
for (;;) {
mp = malloc(sizeof(struct msg));
mp->num = rand() % 1000 + 1;
printf("Produce %d\\n", mp->num);
pthread_mutex_lock(&lock);
mp->next = head;
head = mp;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&has_product);
sleep(rand() % 5);
}
}
int main(int argc, char const *argv[])
{
pthread_t pid, cid;
srand(time(0));
pthread_create(&pid, 0, producer, 0);
pthread_create(&cid, 0, consumer, 0);
pthread_join(pid, 0);
pthread_join(cid, 0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
int count;
int next_index;
void * chunk(void * thread_id){
int id=*(int *) thread_id;
int counter=0;
int i, start=0;
while(1){
pthread_mutex_lock(&lock);
start=next_index;
next_index+=100;
pthread_mutex_unlock(&lock);
if((start+100)>(100000*8)){
break;
}
for(i=start;i<start+100;i++){
if(is_prime_sqrt(i))
counter++;
}
}
pthread_mutex_lock(&lock);
count+=counter;
pthread_mutex_unlock(&lock);
}
int main(){
pthread_t threads[8];
int i;
int thread_num[8];
int time;
next_index=0;
count=0;
time=get_time_sec();
for(i=0;i<8;i++){
thread_num[i]=i;
pthread_create(&threads[i],0,chunk,(void*)&thread_num[i]);
}
for(i=0;i<8;i++){
pthread_join(threads[i],0);
}
printf("Number of primes=%d, took %fs\\n",count, get_time_sec()-time);
return 0;
}
| 0
|
#include <pthread.h>
struct AHRS ahrs;
struct GPSDATA gps;
pthread_mutex_t mutex_ahrs;
pthread_mutex_t mutex_gps;
void *threadFunc(void *ptr)
{
struct msg_packet packet;
int ret,msgid;
while(1){
msgid = msgget(MSGKEY,IPC_EXCL);
if(msgid<0)
{
continue;
}
ret = msgrcv(msgid,&packet,sizeof(struct msg_packet),0,IPC_NOWAIT);
if(ret == sizeof(struct msg_packet))
{
switch(packet.msgType)
{
case MSG_TYPE_AHRS:
pthread_mutex_lock(&mutex_ahrs);
ahrs.time = packet.body.ahrs.time;
ahrs.roll = packet.body.ahrs.roll;
ahrs.pitch = packet.body.ahrs.pitch;
ahrs.yaw = packet.body.ahrs.yaw;
pthread_mutex_unlock(&mutex_ahrs);
break;
case MSG_TYPE_GPS:
pthread_mutex_lock(&mutex_gps);
gps.status = packet.body.gps.status;
gps.speed = packet.body.gps.speed;
gps.lat = packet.body.gps.lat;
gps.lng = packet.body.gps.lng;
gps.alt = packet.body.gps.alt;
pthread_mutex_unlock(&mutex_gps);
break;
}
}
}
}
int ListenForPilotData(void)
{
pthread_t id;
int ret;
if(pthread_mutex_init(&mutex_ahrs,0) != 0)
{
return -1;
}
if(pthread_mutex_init(&mutex_gps,0) != 0)
{
return -1;
}
ret=pthread_create(&id,0,threadFunc,0);
if(ret!=0){
return -1;
}
return 0;
}
int GetAHRS(float* roll,float* pitch,float* yaw,unsigned long* t)
{
struct timeval tv;
struct timezone tz;
gettimeofday(&tv,&tz);
{
pthread_mutex_lock(&mutex_ahrs);
*roll = ahrs.roll;
*pitch = ahrs.pitch;
*yaw = ahrs.yaw;
*t = tv.tv_sec;
pthread_mutex_unlock(&mutex_ahrs);
return 0;
}
return -1;
}
int GetGps(struct GPSDATA* pGps)
{
struct timeval tv;
struct timezone tz;
gettimeofday(&tv,&tz);
if(pGps == 0)
return -1;
{
pthread_mutex_lock(&mutex_gps);
pGps->status = gps.status;
pGps->speed = gps.speed;
pGps->lat = gps.lat;
pGps->lng = gps.lng;
pGps->alt = gps.alt;
pthread_mutex_unlock(&mutex_gps);
return 0;
}
return -1;
}
| 1
|
#include <pthread.h>
pthread_mutex_t livelock_001_glb_A;
pthread_mutex_t livelock_001_glb_B;
static int x,y;
void *mythreadA(void *pram)
{
while(1)
{
pthread_mutex_lock(&livelock_001_glb_A);
x=x+1;
pthread_mutex_unlock(&livelock_001_glb_A);
int status=pthread_mutex_trylock(&livelock_001_glb_B);
if(status==0)
{
continue;
}
}
return 0;
}
void* mythreadB(void *arg)
{
while(1)
{
pthread_mutex_lock(&livelock_001_glb_B);
y=y+1;
pthread_mutex_unlock(&livelock_001_glb_B);
int status=pthread_mutex_trylock(&livelock_001_glb_A);
if(status==0)
{
continue;
}
}
return 0;
}
void livelock_001()
{
pthread_t pthreadA,pthreadB;
pthread_mutex_init(&livelock_001_glb_A,0);
pthread_mutex_init(&livelock_001_glb_B,0 );
pthread_create(&pthreadA,0,mythreadA,0);
pthread_create(&pthreadB,0,(void *) &mythreadB,0);
pthread_join(pthreadA,0);
pthread_join(pthreadB,0);
}
extern volatile int vflag;
void livelock_main ()
{
if (vflag> 0)
{
livelock_001 ();
}
}
| 0
|
#include <pthread.h>
struct philosopher {
int lchopstick_id;
int rchopstick_id;
char *name;
};
int chopstick_list[5];
struct philosopher nerds[5];
pthread_mutex_t miyagi;
void think(struct philosopher n) {
int slptm = (rand()%20) + 1;
printf("%s is thinking for %d seconds! Go %s!\\n", n.name,
slptm, n.name);
srand(time(0));
sleep(slptm);
return;
}
void eat(struct philosopher n) {
int eattm = (rand()%8) + 2;
printf("%s is eating for %d seconds! Delicious!\\n", n.name,
eattm);
sleep(eattm);
return;
}
void grab(struct philosopher n) {
WAX_ON:
while(can_i_miyagi(n) == 0){}
pthread_mutex_lock(&miyagi);
if (can_i_miyagi(n) == 0) {
pthread_mutex_unlock(&miyagi);
goto WAX_ON;
}
sleep(0.5);
chopstick_list[n.lchopstick_id] = 0;
chopstick_list[n.rchopstick_id] = 0;
printf("%s is grabbing chopsticks %d, %d! Dinner time!\\n", n.name,
n.lchopstick_id,
n.rchopstick_id);
pthread_mutex_unlock(&miyagi);
return;
}
void set(struct philosopher n) {
chopstick_list[n.lchopstick_id] = 1;
chopstick_list[n.rchopstick_id] = 1;
printf("%s is letting go of chopsticks %d, %d. He ate about %d noodles!\\n",
n.name,
n.lchopstick_id,
n.rchopstick_id,
rand()%5000+1);
}
int can_i_miyagi(struct philosopher n) {
if (chopstick_list[n.lchopstick_id] == 1
&& chopstick_list[n.rchopstick_id] == 1) {
return 1;
} else
return 0;
}
void *philosophize(void *na) {
struct philosopher *nat = (struct philosopher*)na;
struct philosopher n = *nat;
int cntr = 0;
for (;;){
think(n);
grab(n);
eat(n);
set(n);
}
return 0;
}
int main() {
srand(time(0));
chopstick_list[0] = 1;
chopstick_list[1] = 1;
chopstick_list[2] = 1;
chopstick_list[3] = 1;
chopstick_list[4] = 1;
nerds[0].name = "Paul Of Tarsis";
nerds[0].lchopstick_id = 0;
nerds[0].rchopstick_id = 1;
nerds[1].name = "Jesus Christ of Nazareth";
nerds[1].lchopstick_id = 1;
nerds[1].rchopstick_id = 2;
nerds[2].name = "Sophocles";
nerds[2].lchopstick_id = 2;
nerds[2].rchopstick_id = 3;
nerds[3].name = "Friedreich Heinrich Jacobi";
nerds[3].lchopstick_id = 3;
nerds[3].rchopstick_id = 4;
nerds[4].name = "Caspar John Hare";
nerds[4].lchopstick_id = 4;
nerds[4].rchopstick_id = 0;
pthread_t nerd_threads[5];
int cnt = 0;
for (cnt = 0; cnt < 5; cnt++) {
pthread_create(&(nerd_threads[cnt]),
0,
philosophize,
(void*)&nerds[cnt]);
}
for (cnt = 0; cnt < 5; cnt++) {
pthread_join(nerd_threads[cnt], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
void reader_function(void);
void writer_function(void);
int buffer_has_item = 0;
pthread_mutex_t mutex;
main()
{
pthread_t reader;
pthread_mutex_init(&mutex, 0);
pthread_create( &reader, 0, (void*)&reader_function, 0);
writer_function();
}
void writer_function(void)
{
while(1)
{
pthread_mutex_lock( &mutex );
if ( buffer_has_item == 0 )
{
printf("make_new_item\\n");
buffer_has_item = 1;
}
pthread_mutex_unlock( &mutex );
}
}
void reader_function(void)
{
while(1)
{
pthread_mutex_lock( &mutex );
if ( buffer_has_item == 1)
{
printf("consume_item\\n");
buffer_has_item = 0;
}
pthread_mutex_unlock( &mutex );
}
}
| 0
|
#include <pthread.h>
void do_one_thing(int *);
void do_another_thing(int *);
void do_wrap_up(int, int);
void mon(int );
int r1 = 0, r2 = 0;
int i;
struct proc_time *timer;
pthread_mutex_t printfLock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t xx = PTHREAD_MUTEX_INITIALIZER;
main(void)
{
pthread_t thread1[5], thread2;
int ii;
time_t t1, t2;
timer = init_timer();
time(&t1);
start_timer(timer);
for (i = 0; i < 5; ++i) {
if (pthread_create(&(thread1[i]), 0, (void *) do_one_thing,
(void *) &i) != 0)
perror("pthread_create"), exit(1);
}
for (ii = 0; ii < 5;ii++)
if (pthread_join(thread1[ii], 0) != 0)
perror("pthread_join"),exit(1);
stop_timer(timer);
print_time_interval(timer);
printf("\\nThe loop ran for %ld.%06ld seconds\\n",
timer->tot_usage.ru_utime.tv_sec,
timer->tot_usage.ru_utime.tv_usec);
time(&t2);
printf("my diff time %d \\n",t2-t1);
return 0;
}
void do_one_thing(int *thindx)
{
printf("doing one thing %d \\n", * thindx);
printf("the thread id is %d \\n",pthread_self());
mon(* thindx);
}
void do_wrap_up(int one_times, int another_times)
{
int total;
total = one_times + another_times;
printf("All done, one thing %d, another %d for a total of %d\\n",
one_times, another_times, total);
}
void mon(int th)
{
pthread_mutex_lock(&printfLock);
printf("in the monitor %d\\n",th);
pthread_mutex_unlock(&printfLock);
pthread_mutex_lock(&xx);
printf("in the monitor %d\\n",th);
pthread_mutex_unlock(&xx);
pthread_mutex_unlock(&xx);
}
| 1
|
#include <pthread.h>
int contador;
pthread_mutex_t mutex;
sem_t semaforo_productor;
void agregar(char c);
void quitar();
void * productor()
{
while(1)
{
char c = 'a' + rand()%24;
agregar(c);
usleep(1000);
}
}
void * consumidor()
{
while(1)
{
quitar();
usleep(1000);
}
}
void * imprimir()
{
while(1){
int i;
printf("%d",contador);
printf("\\n");
usleep(1000);
}
}
int main()
{
pthread_t thread_consumidor;
pthread_t thread_productor;
contador = 0;
pthread_mutex_init(&mutex, 0);
sem_init(&semaforo_productor, 0, 10);
pthread_create(&thread_consumidor, 0, consumidor, 0 );
pthread_create(&thread_productor, 0, productor, 0 );
pthread_join(thread_consumidor, 0);
return 0;
}
void agregar(char c)
{
sem_wait(&semaforo_productor);
pthread_mutex_lock(&mutex);
contador++;
printf("%d\\n",contador);
pthread_mutex_unlock(&mutex);
}
void quitar()
{
if(contador>0)
{
pthread_mutex_lock(&mutex);
contador--;
printf("%d\\n",contador);
pthread_mutex_unlock(&mutex);
sem_post(&semaforo_productor);
}
}
| 0
|
#include <pthread.h>
static pthread_t thread;
static pthread_cond_t cond;
static pthread_mutex_t mutex;
static int flag = 1;
void * thr_fn(void * arg)
{
struct timeval now;
struct timespec outtime;
pthread_mutex_lock(&mutex);
while (flag) {
printf("*****\\n");
gettimeofday(&now, 0);
outtime.tv_sec = now.tv_sec + 5;
outtime.tv_nsec = now.tv_usec * 1000;
pthread_cond_timedwait(&cond, &mutex, &outtime);
}
pthread_mutex_unlock(&mutex);
printf("cond thread exit\\n");
}
int main(void)
{
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
if (0 != pthread_create(&thread, 0, thr_fn, 0)) {
printf("error when create pthread,%d\\n", errno);
return 1;
}
char c ;
while ((c = getchar()) != 'q');
printf("Now terminate the thread!\\n");
pthread_mutex_lock(&mutex);
flag = 0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
printf("Wait for thread to exit\\n");
pthread_join(thread, 0);
printf("Bye\\n");
return 0;
}
| 1
|
#include <pthread.h>
int buffer[3];
int add = 0;
int rem = 0;
int num = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c_cons = PTHREAD_COND_INITIALIZER;
pthread_cond_t c_prod = PTHREAD_COND_INITIALIZER;
void *producer (void *param);
void *consumer (void *param);
int main(int argc, char *argv[]) {
pthread_t tid1, tid2;
int i;
if(pthread_create(&tid1, 0, producer, 0) != 0) {
fprintf(stderr, "Unable to create producer thread\\n");
exit(1);
}
if(pthread_create(&tid2, 0, consumer, 0) != 0) {
fprintf(stderr, "Unable to create consumer thread\\n");
exit(1);
}
pthread_join(tid1, 0);
pthread_join(tid2, 0);
printf("Parent quiting\\n");
return 0;
}
void *producer(void *param) {
int i;
for (i=1; i<=20; i++) {
pthread_mutex_lock (&m);
if (num > 3) {
exit(1);
}
while (num == 3) {
pthread_cond_wait (&c_prod, &m);
}
buffer[add] = i;
add = (add+1) % 3;
num++;
pthread_mutex_unlock (&m);
pthread_cond_signal (&c_cons);
printf ("producer: inserted %d\\n", i);
fflush (stdout);
}
printf("producer quiting\\n");
fflush(stdout);
return 0;
}
void *consumer(void *param) {
int i;
while(1) {
pthread_mutex_lock (&m);
if (num < 0) {
exit(1);
}
while (num == 0) {
pthread_cond_wait (&c_cons, &m);
}
i = buffer[rem];
rem = (rem+1) % 3;
num--;
pthread_mutex_unlock (&m);
pthread_cond_signal (&c_prod);
printf ("Consume value %d\\n", i); fflush(stdout);
}
return 0;
}
| 0
|
#include <pthread.h>
int lista[10];
int inicio_cola;
int fin_cola;
} lista_circular;
static lista_circular almacen;
pthread_mutex_t mutex_cola;
pthread_cond_t condicion_vacio,condicion_lleno;
void productor()
{
int aux=0;
while (1) {
sleep(1);
aux = aux+1;
printf ("Productor: el elemento %i ha sido producido\\n",aux);
pthread_mutex_lock(&mutex_cola);
printf("Productor: bloqueo mutex_cola\\n");
while ((almacen.inicio_cola+1) % 10 == almacen.fin_cola){
printf("Productor: la cola esta llena, me bloqueo\\n");
pthread_cond_wait(&condicion_lleno,&mutex_cola);
}
printf("Productor: inserto el elemento %d en la lista, "
"en la posicion %d\\n", aux, almacen.inicio_cola);
almacen.lista[almacen.inicio_cola] = aux;
almacen.inicio_cola =(almacen.inicio_cola +1) % 10;
printf("Ahora mismo la situacion es: inicio:%d fin:%d\\n",
almacen.inicio_cola,
almacen.fin_cola);
pthread_cond_signal(&condicion_vacio);
pthread_mutex_unlock(&mutex_cola);
}
}
void consumidor ()
{
int aux;
while (1) {
pthread_mutex_lock(&mutex_cola);
printf("Consumidor: bloqueo mutex_cola\\n");
while (almacen.inicio_cola == almacen.fin_cola){
printf("Consumidor: la cola esta vacia, me bloqueo\\n");
pthread_cond_wait(&condicion_vacio,&mutex_cola);
}
printf("Consumidor: cojo el elemento %d de la lista, "
"en la posicion %d\\n", aux, almacen.fin_cola);
aux = almacen.lista[almacen.fin_cola];
almacen.fin_cola =(almacen.fin_cola +1) % 10;
printf("Ahora mismo la situacion es: inicio:%d fin:%d\\n",
almacen.inicio_cola,
almacen.fin_cola);
pthread_cond_signal(&condicion_lleno);
pthread_mutex_unlock(&mutex_cola);
sleep(2);
printf ("Consumidor: el elemento %i ha sido consumido\\n",aux);
}
}
int main ()
{
int x;
pthread_attr_t attr_productores[3],attr_consumidores[4];
pthread_t hilos_consumidores[4],
hilos_productores[3];
for (x=0;x<3;x++){
pthread_attr_init(&attr_productores[x]);
}
for (x=0;x<4;x++){
pthread_attr_init(&attr_consumidores[x]);
}
pthread_mutex_init(&mutex_cola,0);
pthread_cond_init(&condicion_vacio,0);
pthread_cond_init(&condicion_lleno,0);
almacen.fin_cola = 0;
almacen.inicio_cola = 0;
for(x=0;x<4;x++){
printf ("Creando thread consumidor %d\\n", x);
pthread_create(&hilos_consumidores[x],&attr_consumidores[x],(void *)&consumidor,0);
}
for(x=0;x<3;x++){
printf ("Creando thread productor %d\\n",x);
pthread_create(&hilos_productores[x],&attr_productores[x],(void *)&productor,0);
}
sleep (30);
printf ("Finalizando el programa\\n");
for(x=0;x<4;x++)
pthread_cancel(hilos_consumidores[x]);
for(x=0;x<3;x++)
pthread_cancel(hilos_productores[x]);
exit(0);
}
| 1
|
#include <pthread.h>
void enqueue(struct vder_queue *q, struct vde_buff *b)
{
pthread_mutex_lock(&q->lock);
if (!q->may_enqueue(q, b)) {
free(b);
pthread_mutex_unlock(&q->lock);
return;
}
b->next = 0;
if (!q->head) {
q->head = b;
q->tail = b;
} else {
q->tail->next = b;
q->tail = b;
}
q->size += b->len;
q->n++;
pthread_mutex_unlock(&q->lock);
if (q->policy != QPOLICY_TOKEN) {
if (q->type != QTYPE_PRIO)
sem_post(&q->semaphore);
else
sem_post(q->prio_semaphore);
}
}
struct vde_buff *prio_dequeue(struct vder_iface *vif)
{
struct vder_queue *q;
int i;
struct vde_buff *ret = 0;
sem_wait(&vif->prio_semaphore);
for (i = 0; i < PRIO_NUM; i++) {
q = &(vif->prio_q[i]);
pthread_mutex_lock(&q->lock);
if (q->size == 0){
pthread_mutex_unlock(&q->lock);
continue;
}
if (q->n) {
ret = q->head;
q->head = ret->next;
q->n--;
q->size -= ret->len;
if (q->n == 0) {
q->tail = 0;
q->head = 0;
}
pthread_mutex_unlock(&q->lock);
break;
}
pthread_mutex_unlock(&q->lock);
}
return ret;
}
struct vde_buff *dequeue(struct vder_queue *q)
{
struct vde_buff *ret = 0;
if (q->type != QTYPE_PRIO)
sem_wait(&q->semaphore);
else
return 0;
pthread_mutex_lock(&q->lock);
if (q->n) {
ret = q->head;
q->head = ret->next;
q->n--;
q->size -= ret->len;
if (q->n == 0) {
q->tail = 0;
q->head = 0;
}
}
pthread_mutex_unlock(&q->lock);
return ret;
}
int qunlimited_may_enqueue(struct vder_queue *q, struct vde_buff *b)
{
return 1;
}
void qunlimited_setup(struct vder_queue *q)
{
pthread_mutex_lock(&q->lock);
if (q->policy == QPOLICY_TOKEN) {
vder_timed_dequeue_del(q);
}
q->policy = QPOLICY_UNLIMITED;
q->may_enqueue = qunlimited_may_enqueue;
pthread_mutex_unlock(&q->lock);
}
int qfifo_may_enqueue(struct vder_queue *q, struct vde_buff *b)
{
if (q->policy_opt.fifo.limit > q->size)
return 1;
else {
q->policy_opt.fifo.stats_drop++;
return 0;
}
}
void qfifo_setup(struct vder_queue *q, uint32_t limit)
{
pthread_mutex_lock(&q->lock);
if (q->policy == QPOLICY_TOKEN) {
vder_timed_dequeue_del(q);
}
q->policy = QPOLICY_FIFO;
q->policy_opt.fifo.limit = limit;
q->policy_opt.fifo.stats_drop = 0;
q->may_enqueue = qfifo_may_enqueue;
pthread_mutex_unlock(&q->lock);
}
int qred_may_enqueue(struct vder_queue *q, struct vde_buff *b)
{
double red_probability;
if (q->policy_opt.red.min > q->size) {
return 1;
} else if (q->policy_opt.red.max > q->size) {
red_probability = q->policy_opt.red.P *
((double)q->size - (double)q->policy_opt.red.min /
((double)q->policy_opt.red.max - (double)q->policy_opt.red.min));
} else if (q->policy_opt.red.limit > q->size) {
red_probability = q->policy_opt.red.P;
} else {
q->policy_opt.red.stats_drop++;
return 0;
}
if (drand48() < red_probability) {
q->policy_opt.red.stats_probability_drop++;
return 0;
}
return 1;
}
void qred_setup(struct vder_queue *q, uint32_t min, uint32_t max, double P, uint32_t limit)
{
pthread_mutex_lock(&q->lock);
if (q->policy == QPOLICY_TOKEN) {
vder_timed_dequeue_del(q);
}
q->policy = QPOLICY_RED;
q->policy_opt.red.min = min;
q->policy_opt.red.max = max;
q->policy_opt.red.P = P;
q->policy_opt.red.limit = limit;
q->policy_opt.red.stats_drop = 0;
q->policy_opt.red.stats_probability_drop = 0;
q->may_enqueue = qred_may_enqueue;
pthread_mutex_unlock(&q->lock);
}
int qtoken_may_enqueue(struct vder_queue *q, struct vde_buff *b)
{
if (q->policy_opt.token.limit > q->size)
return 1;
else {
q->policy_opt.token.stats_drop++;
return 0;
}
}
void qtoken_setup(struct vder_queue *q, uint32_t bitrate, uint32_t limit)
{
pthread_mutex_lock(&q->lock);
q->policy_opt.token.interval = (1000000 * 1500) / ((bitrate >> 3));
q->policy_opt.token.limit = limit;
q->policy_opt.token.stats_drop = 0U;
if (q->policy == QPOLICY_TOKEN) {
vder_timed_dequeue_del(q);
}
q->policy = QPOLICY_TOKEN;
vder_timed_dequeue_add(q, q->policy_opt.token.interval);
q->may_enqueue = qtoken_may_enqueue;
pthread_mutex_unlock(&q->lock);
}
| 0
|
#include <pthread.h>
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
int fd, dp;
int allsize = 0;
int counter = 0;
int temp = 0;
void *thread_copy(void *arg)
{
int len;
int buf = (int)arg;
int str[4096];
pthread_mutex_lock(&counter_mutex);
allsize = counter;
lseek(fd, allsize, 0);
lseek(dp, allsize, 0);
len = read(fd, str, buf);
write(dp, str, len);
counter += buf;
printf("进度: %d\\n", counter);
pthread_mutex_unlock(&counter_mutex);
return 0;
}
int main(int argc, char *argv[])
{
if (argc != 4)
{
printf("error input\\n");
exit(-1);
}
struct stat buf;
int i;
int num = atoi(argv[3]);
pthread_t array[num];
fd = open(argv[1], O_RDWR);
if (fd < 0)
{
perror("open failed");
exit(-1);
}
fstat(fd, &buf);
dp = open(argv[2], O_RDWR | O_CREAT, 0777);
if (dp < 0)
{
perror("open dp failed");
exit(-1);
}
for (i = 0; i < num; i++)
{
pthread_create(&array[i], 0, thread_copy, (void *)(buf.st_size/num));
}
for (i = 0; i < num; i++)
{
pthread_join(array[i], 0);
}
close(dp);
close(fd);
return 0;
}
| 1
|
#include <pthread.h>
uint32_t max_size;
const char * log_dir;
char * log_file;
pthread_mutex_t log_mutex;
uint8_t to_file;
uint8_t to_sys;
static void log_rotate() {
int buf_len;
char newfile[2048 +1];
buf_len = strlen(log_file) + 30;
struct timeval tv;
gettimeofday(&tv, 0);
char tmbuf[500];
strftime(tmbuf, 500, "%Y-%m-%d_%H:%M:%S", localtime(&tv.tv_sec));
snprintf(newfile, buf_len, "%s.%s", log_file, tmbuf);
int r = rename(log_file, newfile);
if (r < 0) {
perror("error rotating current");
}
}
void DebugPrintFunc(int log_lv, const char *file, int line, const char *errmsg, ...){
char buf[2048 +1];
char logdata[2048 +1];
va_list ap;
__builtin_va_start((ap));
vsnprintf(buf, 2048, errmsg, ap);
buf[2048] = '\\0';
if(dbg_lv == DDBG){
printf("[%s:%d] %s\\n", file, line, buf);
}
else if (log_lv & to_sys)
syslog(LOG_CRIT, "[%s:%d] %s\\n", file, line, buf);
else if(log_lv & to_file) {
int len, written;
int fd ;
off_t filesize;
len = snprintf(logdata, 2048, "(%lu)[%s:%d] %s", (unsigned long)time(0), file, line, buf);
pthread_mutex_lock(&log_mutex);
fd = open(log_file, O_CREAT | O_APPEND | O_WRONLY, 0644);
if (fd < 0) {
perror("Failed to rotating log.");
pthread_mutex_unlock(&log_mutex);
return;
}
written = write(fd, logdata, len);
if(written == len){
if (logdata[len-1] != '\\n') {
write(fd, "\\n", 1);
}
}
else
perror("Failed to write log.");
filesize = lseek(fd, 0, 2);
close(fd);
if (filesize >= max_size - 2000) {
log_rotate();
}
pthread_mutex_unlock(&log_mutex);
}
;
}
int init_log(uint32_t log_size, const char * log_path, const char *log_name, uint8_t tofile, uint8_t tosys){
int file_len = strlen(log_path) + strlen(log_name) ;
to_file = tofile;
to_sys = tosys;
max_size = log_size;
log_dir = log_path;
log_file = malloc(file_len + 2);
snprintf(log_file, file_len + 2, "%s/%s", log_path, log_name);
pthread_mutex_init(&log_mutex,0);
return 1;
}
int clean_log(){
free(log_file);
pthread_mutex_destroy(&log_mutex);
return 1;
}
| 0
|
#include <pthread.h>
pthread_t tid [2];
int mine [5][5];
int minetot,p1,p2;
char namap1[50], namap2[50];
pthread_mutex_t lock;
void isiranjau(int num)
{
int i,j;
if (num % 4 == 0){
i = (num/4)-1;
j = (num%4)-1;
}
else{
i = num/4;
j = num%4;
}
if (!mine[i][j]) minetot++;
mine [i][j] = 1;
}
int cekranjau (int num)
{
int i,j;
if (num % 4 == 0){
i = (num/4)-1;
j = (num%4)-1;
}
else{
i = num/4;
j = num%4;
}
if (mine[i][j]) return 1;
else return 0;
}
void* play1 (void* arg)
{
int ranjau,pasang,tebak;
pthread_mutex_lock (&lock);
printf("p1 (%s) memasang ranjau!\\n",namap1);
while (1)
{
printf("Berapa banyak ranjau yg mau dipasang oleh p1 (%s)? ",namap1);
scanf("%d",&ranjau);
if (ranjau > 4) printf("input invalid! Masukkan 1-4 saja!\\n");
else if (ranjau >= 0 && ranjau <= 4) break;
}
for (int i=0;i<ranjau;i++)
{
printf("Ranjau mau dipasang dilubang mana? ");
scanf("%d",&pasang);
isiranjau (pasang);
printf("Ranjau sudah dipasang di lubang %d\\n",pasang);
}
printf("\\np2 (%s) menebak ranjau sebanyak 4 kali!\\n",namap2);
for (int i=0;i<4;i++){
printf("Mau tebak lubang mana saja? ");
scanf("%d",&tebak);
int temp = cekranjau (tebak);
if (temp) printf("p2 (%s) Kena RANJAU!\\n",namap2);
p1 += temp;
}
printf("\\n\\nStatus => p1 (%s) : %d \\t p2 (%s) : %d\\n\\n",namap1,p1,namap2,p2);
pthread_mutex_unlock (&lock);
}
void* play2 (void* arg)
{
int ranjau,pasang,tebak;
pthread_mutex_lock (&lock);
printf("p2 (%s) memasang ranjau!\\n",namap2);
while (1)
{
printf("Berapa banyak ranjau yg mau dipasang oleh p2 (%s)? ",namap2);
scanf("%d",&ranjau);
if (ranjau > 4) printf("input invalid! Masukkan 1-4 saja!\\n");
else if (ranjau >= 0 && ranjau <= 4) break;
}
for (int i=0;i<ranjau;i++)
{
printf("Ranjau mau dipasang dilubang mana? ");
scanf("%d",&pasang);
isiranjau (pasang);
printf("Ranjau sudah dipasang di lubang %d\\n",pasang);
}
printf("p1 (%s) menebak ranjau sebanyak 4 kali!\\n",namap1);
for (int i=0;i<4;i++){
printf("Mau tebak lubang mana saja? ");
scanf("%d",&tebak);
int temp = cekranjau (tebak);
if (temp) printf("p1 (%s) Kena RANJAU!\\n",namap1);
p2 += temp;
}
printf("\\n\\nStatus => p1 (%s) : %d \\t p2 (%s) : %d\\n\\n",namap1,p1,namap2,p2);
pthread_mutex_unlock (&lock);
}
int main()
{
minetot = 0; p1 = 0; p2 = 0;
printf("LET'S PLAY!\\n");
printf("Masukkan nama pemain 1 : ");
scanf("%s",namap1);
printf("Masukkan nama pemain 2 : ");
scanf("%s",namap2);
while (1)
{
if (minetot>15 || p1 > 9 || p2 > 9){
printf("Sudah selesai!\\n");
pthread_cancel (tid[0]);
pthread_cancel (tid[1]);
break;
}
pthread_create (&tid[0], 0, &play1, 0);
pthread_create (&tid[1], 0, &play2, 0);
}
pthread_join (tid[0],0);
pthread_join (tid[1],0);
pthread_mutex_destroy (&lock);
printf("Winner of this Game!\\n");
printf("\\n\\nSkor Akhir => p1 (%s) : %d \\t p2 (%s) : %d\\n\\n",namap1,p1,namap2,p2);
if (p1 > p2) printf("\\n=====\\np1(%s) win\\n=====\\n",namap1);
else if (p2 > p1) printf("\\n=====\\np2 (%s) win\\n=====\\n",namap2);
else printf("No one win\\n");
return 0;
}
| 1
|
#include <pthread.h>
void mission(float x_cons, float y_cons, float z_cons, float angle_cons, float * pitch_cmd, float * roll_cmd, float * angular_speed_cmd, float * vertical_speed_cmd)
{
pthread_mutex_lock(&mutex_mission);
if(newCoordXY!=0) {
x = loca_x;
y = loca_y;
newCoordXY = 0;
}
if(newCoordZ!=0) {
z = navData_z;
newCoordZ = 0;
}
if(newAngle!=0) {
angle = navData_angle;
newAngle = 0;
}
float dx = x_cons - x;
float dy = y_cons - y;
float dz = z_cons - z;
convert_angle(&angle);
convert_angle(&angle_cons);
controller(dx, dy, dz, angle_cons, angle, pitch_cmd, roll_cmd, angular_speed_cmd, vertical_speed_cmd);
pthread_mutex_unlock(&mutex_mission);
}
void newNavData(float z_baro, float heading, float forward_backward_speed, float left_right_speed)
{
pthread_mutex_lock(&mutex_mission);
navData_z = z_baro;
navData_angle = heading-BIAIS;
convert_angle(&navData_angle);
navData_fb_speed = forward_backward_speed;
navData_lr_speed = left_right_speed;
newCoordZ = 1;
newAngle = 1;
newSpeed = 1;
pthread_mutex_unlock(&mutex_mission);
}
void newLocalization(float x_drone, float y_drone)
{
pthread_mutex_lock(&mutex_mission);
loca_x = x_drone;
loca_y = y_drone;
newCoordXY = 1;
pthread_mutex_unlock(&mutex_mission);
}
float getX()
{
pthread_mutex_lock(&mutex_mission);
float x_local = x ;
pthread_mutex_unlock(&mutex_mission);
return x_local;
}
float getY()
{
pthread_mutex_lock(&mutex_mission);
float y_local = y ;
pthread_mutex_unlock(&mutex_mission);
return y_local;
}
float getZ()
{
pthread_mutex_lock(&mutex_mission);
float z_local = z ;
pthread_mutex_unlock(&mutex_mission);
return z_local;
}
float getAngle()
{
pthread_mutex_lock(&mutex_mission);
float angle_local = angle ;
pthread_mutex_unlock(&mutex_mission);
return angle_local;
}
void controller(float dx, float dy, float dz, float angle_drone_cons, float angle_drone, float * pitch_cmd, float * roll_cmd, float * angular_speed_cmd, float * vertical_speed_cmd)
{
convert_angle(&angle_drone_cons);
convert_angle(&angle_drone);
room_to_drone(dx,dy,angle_drone,pitch_cmd,roll_cmd);
*pitch_cmd *= -GAIN_PITCH;
*roll_cmd *= GAIN_ROLL;
*angular_speed_cmd = -GAIN_ANGULAR * diff_angle(angle_drone,angle_drone_cons);
*vertical_speed_cmd = GAIN_VERTICAL * dz;
if(*pitch_cmd>PITCH_CMD_MAX) {
*pitch_cmd = PITCH_CMD_MAX;
}
else if(*pitch_cmd<-PITCH_CMD_MAX) {
*pitch_cmd = -PITCH_CMD_MAX;
}
if(*roll_cmd>ROLL_CMD_MAX) {
*roll_cmd = ROLL_CMD_MAX;
}
else if(*roll_cmd<-ROLL_CMD_MAX) {
*roll_cmd = -ROLL_CMD_MAX;
}
if(*angular_speed_cmd>ANGULAR_CMD_MAX) {
*angular_speed_cmd = ANGULAR_CMD_MAX;
}
else if(*angular_speed_cmd<-ANGULAR_CMD_MAX) {
*angular_speed_cmd = -ANGULAR_CMD_MAX;
}
if(*vertical_speed_cmd>VERTICAL_CMD_MAX) {
*vertical_speed_cmd = VERTICAL_CMD_MAX;
}
else if(*vertical_speed_cmd<-VERTICAL_CMD_MAX) {
*vertical_speed_cmd = -VERTICAL_CMD_MAX;
}
}
void drone_to_room(float forward_backward_speed, float left_right_speed, float angle_drone, float * x_speed, float * y_speed)
{
*x_speed = forward_backward_speed * sinf(deg_to_rad(angle_drone)) - left_right_speed * cosf(deg_to_rad(angle_drone));
*y_speed = forward_backward_speed * cosf(deg_to_rad(angle_drone)) + left_right_speed * sinf(deg_to_rad(angle_drone));
}
void room_to_drone(float dx, float dy, float angle_drone, float * pitch, float * roll)
{
*pitch = dy * cosf(deg_to_rad(angle_drone)) + dx * sinf(deg_to_rad(angle_drone));
*roll = dy * sinf(deg_to_rad(angle_drone)) - dx * cosf(deg_to_rad(angle_drone));
}
void convert_angle(float * angleToConvert)
{
while(*angleToConvert>180.0 || *angleToConvert<-180.0 ) {
if(*angleToConvert>180.0) {
*angleToConvert -= 360.0;
}
else if(*angleToConvert<-180.0) {
*angleToConvert += 360.0;
}
}
}
float diff_angle(float angle1, float angle2)
{
float diff;
diff = angle2-angle1;
convert_angle(&diff);
return diff;
}
float deg_to_rad(float angleToRad)
{
return (angleToRad*PI/180.0);
}
| 0
|
#include <pthread.h>
int udp_send(void* arg)
{
int* status = arg;
printf("udp sending starts.\\n");
char* rec_cmd = "rec -q -t raw -b 16 -c 1 -e s -r 44100 -";
FILE* rec_fp;
if ((rec_fp = popen(rec_cmd, "r")) == 0) fail("failed to rec...\\n");
int s = udp_socket[99];
unsigned char data[N];
printf("start sending.(num_user = %d)\\n[", num_user);
int i;
int j = 0;
while (1) {
int n_read = fread(data, sizeof(*data), N, rec_fp);
for (i = 0; i < num_user; i++) {
if (j == 0) {
printf("udp sending now(user=%d).(status = %d)\\n[pair udp port] = %d\\n[myself udp port] = %d\\n",num_user, *status, user[num_user-1]->pair_udp_port, user[num_user-1]->myself_udp_port);
j++;
}
sendto(s, data, N, 0, (struct sockaddr *)&user[i]->addr, sizeof(user[i]->addr));
}
if (n_read < N) break;
}
return 0;
}
int udp_recv(void* arg)
{
pthread_mutex_lock(&mutex);
int* status = arg;
printf("recv thread starts.(status = %d, num_user = %d)\\n", *status, num_user);
char* play_cmd = "play -q -t raw -b 16 -c 1 -e s -r 44100 -";
FILE* play_fp;
if ((play_fp = popen(play_cmd, "w")) == 0) fail("failed to play...\\n");
unsigned char data[N];
int s = user[num_user-1]->udp_socket;
*status = 0;
pthread_mutex_unlock(&mutex);
printf("start recv.(user=%d)\\n[user id] = %d\\n[pair udp port] = %d\\n[myself udp port] = %d\\n", num_user, user[num_user-1]->user_id, user[num_user-1]->pair_udp_port, user[num_user-1]->myself_udp_port);
while (1) {
memset(data, 0, N);
recvfrom(s, data, N, 0, 0, 0);
fwrite(data, sizeof(*data), N, play_fp);
}
return 0;
}
| 1
|
#include <pthread.h>
int redpack = 20;
int N = 10;
pthread_t thread[10];
pthread_mutex_t mut;
int count = 0;
int who = 1;
int my_rand(int s, void * arg)
{
int *p = (int *)arg;
time_t ts;
srand((unsigned int)time(&ts) + *p);
int a = 0;
while(a == 0)
{
a = rand() % s;
}
return a;
}
void *thread_0(void * agr)
{
int *p = (int *)agr;
int num = 0;
if(N == 0 && count == redpack)
{
num = 20 - count;
for(int i = 0; i < 10; i++)
{
if(*p != thread[i])
pthread_cancel(thread[i]);
}
}
pthread_mutex_lock(&mut);
if(N == 1)
{
num = redpack - count;
count += num;
printf("%d抢到的钱数我强到了最后一个红包%d\\n",who++,num);
printf("红包剩余钱数%d\\n",redpack - count);
}
else if(N > 1)
{
count += num = my_rand(redpack/10 + 2, p);
N--;
printf("%d抢到的钱数%d\\n",who++,num);
printf("红包剩余钱数%d\\n",redpack - count);
}
pthread_mutex_unlock(&mut);
pthread_exit(0);
}
void thread_wait(void)
{
for(int i = 0; i < 10; i++)
{
if(thread[i] != 0)
{
pthread_join(thread[i], 0);
}
}
}
void thread_create(void)
{
int temp;
memset(&thread, 0, sizeof(thread));
for(int i = 0; i < 10; i++)
{
if((temp = pthread_create(&thread[i], 0, thread_0, &thread[i])) != 0)
{
}
else
{
}
}
}
int main()
{
pthread_mutex_init(&mut, 0);
printf("我是主函数,我正在创建线程\\n");
thread_create();
printf("我是主函数,我正在等待线程完成任务\\n");
thread_wait();
return 0;
}
| 0
|
#include <pthread.h>
const unsigned int ARRAY_SEED = 332484;
const double EPSILON = 1.0;
unsigned long ARRAY_DIMENSIONS;
unsigned long NUM_THREADS;
unsigned long loopIt;
pthread_mutex_t epsilon_mutex;
pthread_barrier_t barrier;
double **array;
double **resultArray;
double highestChange = 0.0;
struct Rows
{
unsigned int startRow;
unsigned int endRow;
};
void row_thread(struct Rows* rows)
{
printf("Thread starting\\n");
int start = rows->startRow, end = rows->endRow;
do
{
pthread_barrier_wait(&barrier);
double change = 0.0;
for (unsigned int i = start; i < end; i++)
{
for (unsigned int j = 1; j < ARRAY_DIMENSIONS -1; j++)
{
double result = (array[i - 1][j] +
array[i][j + 1] +
array[i + 1][j] +
array[i][j - 1]) / 4.0;
resultArray[i][j] = result;
double diff = result - array[i][j];
if (diff < 0.0)
diff *= -1.0;
if (diff > change)
change = diff;
}
}
pthread_barrier_wait(&barrier);
pthread_mutex_lock(&epsilon_mutex);
if (change > highestChange)
highestChange = change;
pthread_mutex_unlock(&epsilon_mutex);
pthread_barrier_wait(&barrier);
} while (highestChange > EPSILON);
}
void populateArrayRand(int aSeed)
{
printf("Populating array");
srand(aSeed);
for (int i = 0; i < ARRAY_DIMENSIONS; i++)
{
for (int j = 0; j < ARRAY_DIMENSIONS; j++)
{
array[i][j] = rand() % 100;
resultArray[i][j] = array[i][j];
}
}
printf("Populated Array\\n");
}
int main(int argc, char *argv[])
{
if (argc != 4)
{
printf("Invalid Arguments");
return 1;
}
ARRAY_DIMENSIONS = strtoul(argv[1], 0, 10);
NUM_THREADS = strtoul(argv[2], 0, 10);
loopIt = strtoul(argv[3], 0, 10);
array = malloc(sizeof(double*) * ARRAY_DIMENSIONS);
if (array == 0)
{
printf("Malloc Failed");
return 1;
}
resultArray = malloc(sizeof(double*) * ARRAY_DIMENSIONS);
if (resultArray == 0)
{
printf("Malloc Failed");
return 1;
}
for (int i = 0; i < ARRAY_DIMENSIONS; i++)
{
array[i] = malloc(sizeof(double) * ARRAY_DIMENSIONS);
if (array[i] == 0)
{
printf("Malloc Failed");
return 1;
}
resultArray[i] = malloc(sizeof(double) * ARRAY_DIMENSIONS);
if (resultArray[i] == 0)
{
printf("Malloc Failed");
return 1;
}
}
printf("Starting\\n");
populateArrayRand(ARRAY_SEED);
pthread_barrier_init(&barrier, 0, NUM_THREADS);
int rowsPerThread = ARRAY_DIMENSIONS / NUM_THREADS;
time_t startTime;
startTime = time(0);
pthread_mutex_init(&epsilon_mutex, 0);
struct Rows rows[16];
for (int i = 0; i < NUM_THREADS; i++)
{
rows[i].startRow = (i * rowsPerThread) + 1;
rows[i].endRow = ((i + 1) * rowsPerThread) + 1;
}
rows[NUM_THREADS - 1].endRow += ARRAY_DIMENSIONS % NUM_THREADS - 2;
printf("Firing off threads\\n");
pthread_t threads[15];
for (int i = 0; i < NUM_THREADS - 1; i++)
{
pthread_create(&threads[i], 0, (void*(*)(void*))row_thread, &rows[i]);
}
{
do
{
double **temp = resultArray;
resultArray = array;
array = temp;
pthread_barrier_wait(&barrier);
highestChange = 0;
double change = 0.0;
for (unsigned int i = rows[NUM_THREADS - 1].startRow; i < rows[NUM_THREADS - 1].endRow; i++)
{
for (unsigned int j = 1; j < ARRAY_DIMENSIONS - 1; j++)
{
double result = (array[i - 1][j] +
array[i][j + 1] +
array[i + 1][j] +
array[i][j - 1]) / 4.0;
resultArray[i][j] = result;
double diff = result - array[i][j];
if (diff < 0.0)
diff *= -1.0;
if (diff > change)
change = diff;
}
}
pthread_barrier_wait(&barrier);
pthread_mutex_lock(&epsilon_mutex);
if (change > highestChange)
highestChange = change;
pthread_mutex_unlock(&epsilon_mutex);
pthread_barrier_wait(&barrier);
} while (highestChange > EPSILON);
}
for (int i = 0; i < NUM_THREADS - 1; i++)
{
pthread_join(threads[i], 0);
}
time_t endTime;
endTime = time(0);
struct tm * timeinfo;
timeinfo = localtime(&startTime);
double timeTaken = difftime(endTime, startTime);
char string[100] = "";
sprintf(string, "ParallelResults-%ld-%ld.txt", NUM_THREADS, loopIt);
FILE *f = fopen(string, "w");
fprintf(f, "Number of threads %ld\\n", NUM_THREADS);
fprintf(f, "Size of array: %ld\\n", ARRAY_DIMENSIONS);
fprintf(f, "\\nTime taken: ");
fprintf(f, "%lf\\n", timeTaken);
for (int i = 0; i < ARRAY_DIMENSIONS; i++)
{
for (int j = 0; j < ARRAY_DIMENSIONS; j++)
{
fprintf(f, "%lf ", resultArray[i][j]);
}
fprintf(f, "\\n");
}
fclose(f);
return 0;
}
| 1
|
#include <pthread.h>
struct _char_channel{
char queue[100];
int front;
int back;
int MAX_SIZE;
int size;
bool poisoned;
pthread_mutex_t lock;
pthread_cond_t write_ready;
pthread_cond_t read_ready;
};
int _init_char_channel(struct _char_channel *channel){
if(pthread_mutex_init(&channel->lock, 0) != 0){
printf("Mutex init failed");
return 1;
}
if(pthread_cond_init(&channel->write_ready, 0) +
pthread_cond_init(&channel->read_ready, 0 ) != 0){
printf("Cond init failed");
return 1;
}
channel->MAX_SIZE = 100;
channel->front = 0;
channel->back = 0;
channel->poisoned = 0;
return 0;
}
void _enqueue_char(char element, struct _char_channel *channel){
pthread_mutex_lock(&channel->lock);
while(channel->size >= channel->MAX_SIZE)
pthread_cond_wait(&channel->write_ready, &channel->lock);
assert(channel->size < channel->MAX_SIZE);
assert(!(channel->poisoned));
channel->queue[channel->back] = element;
channel->back = (channel->back + 1) % channel->MAX_SIZE;
channel->size++;
pthread_cond_signal(&channel->read_ready);
pthread_mutex_unlock(&channel->lock);
}
char _dequeue_char(struct _char_channel *channel){
pthread_mutex_lock(&channel->lock);
assert(channel->size != 0);
char result = channel->queue[channel->front];
channel->front = (channel->front + 1) % channel->MAX_SIZE;
channel->size--;
pthread_cond_signal(&channel->write_ready);
pthread_mutex_unlock(&channel->lock);
return result;
}
void _poison(struct _char_channel *channel) {
pthread_mutex_lock(&channel->lock);
channel->poisoned = 1;
pthread_cond_signal(&channel->read_ready);
pthread_mutex_unlock(&channel->lock);
}
bool _wait_for_more(struct _char_channel *channel) {
pthread_mutex_lock(&channel->lock);
while(channel->size == 0) {
if(channel->poisoned){
pthread_mutex_unlock(&channel->lock);
return 0;
}
else {
pthread_cond_wait(&channel->read_ready, &channel->lock);
}
}
pthread_mutex_unlock(&channel->lock);
return 1;
}
struct _pthread_node{
pthread_t thread;
struct _pthread_node *next;
};
struct _pthread_node* _head = 0;
pthread_mutex_t _thread_list_lock;
pthread_t* _make_pthread_t(){
pthread_mutex_lock(&_thread_list_lock);
struct _pthread_node *new_pthread = (struct _pthread_node *) malloc(sizeof(struct _pthread_node));
new_pthread->next = _head;
_head = new_pthread;
pthread_mutex_unlock(&_thread_list_lock);
return &(new_pthread->thread);
}
void _wait_for_finish(){
struct _pthread_node* curr = _head;
while(curr){
pthread_join(curr->thread, 0);
curr = curr->next;
}
}
struct _tokenGen_args {
struct _char_channel *ochan;
char input;
};
void *tokenGen(void *_args) {
char input = ((struct _tokenGen_args *) _args)->input;
struct _char_channel *ochan = ((struct _tokenGen_args *) _args)->ochan;
_enqueue_char(input, ochan);
_poison(ochan);
return 0;
}
struct _printer_args {
struct _char_channel *chan;
};
void *printer(void *_args) {
struct _char_channel *chan = ((struct _printer_args *) _args)->chan;
while (_wait_for_more(chan)) {
printf("%c\\n", _dequeue_char(chan));
}
return 0;
}
struct _interleaver_args {
struct _char_channel *chan1;
struct _char_channel *chan2;
struct _char_channel *ochan;
};
void *interleaver(void *_args) {
struct _char_channel *chan1 = ((struct _interleaver_args *) _args)->chan1;
struct _char_channel *chan2 = ((struct _interleaver_args *) _args)->chan2;
struct _char_channel *ochan = ((struct _interleaver_args *) _args)->ochan;
while(_wait_for_more(chan1) || _wait_for_more(chan2)) {
if (_wait_for_more(chan1)) _enqueue_char(_dequeue_char(chan1), ochan);
if (_wait_for_more(chan2)) _enqueue_char(_dequeue_char(chan2), ochan);
}
_poison(ochan);
return 0;
}
int main() {
pthread_mutex_init(&_thread_list_lock, 0);
struct _char_channel *chan1 = (struct _char_channel *) malloc(sizeof(struct _char_channel));
_init_char_channel(chan1);
struct _char_channel *chan2 = (struct _char_channel *) malloc(sizeof(struct _char_channel));
_init_char_channel(chan2);
struct _char_channel *ochan = (struct _char_channel *) malloc(sizeof(struct _char_channel));
_init_char_channel(ochan);
char char1 = 'a';
char char2 = 'b';
{
pthread_t* _t = _make_pthread_t();
struct _tokenGen_args _args = {
chan1,
char1,
};
pthread_create(_t, 0, tokenGen, (void *) &_args);
};
{
pthread_t* _t = _make_pthread_t();
struct _tokenGen_args _args = {
chan2,
char2,
};
pthread_create(_t, 0, tokenGen, (void *) &_args);
};
{
pthread_t* _t = _make_pthread_t();
struct _interleaver_args _args = {
chan1,
chan2,
ochan,
};
pthread_create(_t, 0, interleaver, (void *) &_args);
};
{
pthread_t* _t = _make_pthread_t();
struct _printer_args _args = {
ochan,
};
pthread_create(_t, 0, printer, (void *) &_args);
};
_wait_for_finish();
return 0;
}
| 0
|
#include <pthread.h>
extern int diosock;
extern int verbose;
extern pthread_mutex_t dio_comm_lock;
void *DIO_ready_controlprogram(struct ControlProgram *arg)
{
struct ROSMsg s_msg,r_msg;
ros_msg_init(&s_msg);
ros_msg_init(&r_msg);
ros_msg_set_command(&s_msg,CtrlProg_READY,"ctrlprog_ready","NONE");
pthread_mutex_lock(&dio_comm_lock);
if (arg!=0) {
if (arg->parameters!=0) {
ros_msg_add_var(&s_msg,arg->parameters,sizeof(struct ControlPRM),"parameters","ControlPRM");
ros_msg_send(diosock, &s_msg);
ros_msg_recv(diosock, &r_msg);
}
}
pthread_mutex_unlock(&dio_comm_lock);
ros_msg_free_buffer(&s_msg);
ros_msg_free_buffer(&r_msg);
pthread_exit(0);
};
void *DIO_pretrigger(void *arg)
{
struct ROSMsg s_msg, r_msg;
ros_msg_init(&s_msg);
ros_msg_init(&r_msg);
ros_msg_set_command(&s_msg,PRETRIGGER,"pretrigger","NONE");
pthread_mutex_lock(&dio_comm_lock);
ros_msg_send(diosock, &s_msg);
ros_msg_recv(diosock, &r_msg);
pthread_mutex_unlock(&dio_comm_lock);
ros_msg_free_buffer(&s_msg);
ros_msg_free_buffer(&r_msg);
pthread_exit(0);
};
void *DIO_aux_msg(struct ROSMsg *msg_p)
{
struct ROSMsg s_msg,r_msg;
ros_msg_init(&s_msg);
ros_msg_init(&r_msg);
pthread_mutex_lock(&dio_comm_lock);
memmove(&s_msg,msg_p,sizeof(struct ROSMsg));
ros_msg_send(diosock, &s_msg);
ros_msg_recv(diosock, &r_msg);
memmove(msg_p,&r_msg,sizeof(struct ROSMsg));
pthread_mutex_unlock(&dio_comm_lock);
pthread_exit(0);
};
void *DIO_ready_clrsearch(struct ControlProgram *arg)
{
struct ROSMsg s_msg,r_msg;
ros_msg_init(&s_msg);
ros_msg_init(&r_msg);
ros_msg_set_command(&s_msg,CLRSEARCH_READY,"clrsearch_ready","NONE");
pthread_mutex_lock(&dio_comm_lock);
if (arg!=0) {
if (arg->parameters!=0) {
ros_msg_add_var(&s_msg,&arg->clrfreqsearch,sizeof(struct CLRFreqPRM),"clrfreqsearch","struct CLRFreqRPM");
ros_msg_add_var(&s_msg,&arg->parameters->radar,sizeof(int32),"radar","int32");
ros_msg_add_var(&s_msg,&arg->parameters->channel,sizeof(int32),"channel","int32");
ros_msg_send(diosock, &s_msg);
ros_msg_recv(diosock, &r_msg);
}
}
pthread_mutex_unlock(&dio_comm_lock);
ros_msg_free_buffer(&s_msg);
ros_msg_free_buffer(&r_msg);
pthread_exit(0);
};
void *DIO_pre_clrsearch(struct ControlProgram *arg)
{
struct ROSMsg s_msg,r_msg;
ros_msg_init(&s_msg);
ros_msg_init(&r_msg);
ros_msg_set_command(&s_msg,PRE_CLRSEARCH,"pre_clrsearch","NONE");
pthread_mutex_lock(&dio_comm_lock);
if(arg!=0) {
if(arg->parameters!=0) {
ros_msg_send(diosock, &s_msg);
ros_msg_recv(diosock, &r_msg);
}
}
pthread_mutex_unlock(&dio_comm_lock);
ros_msg_free_buffer(&s_msg);
ros_msg_free_buffer(&r_msg);
pthread_exit(0);
};
void *DIO_post_clrsearch(struct ControlProgram *arg)
{
struct ROSMsg s_msg,r_msg;
ros_msg_init(&s_msg);
ros_msg_init(&r_msg);
ros_msg_set_command(&s_msg,POST_CLRSEARCH,"post_clrsearch","NONE");
pthread_mutex_lock(&dio_comm_lock);
if(arg!=0) {
if(arg->parameters!=0) {
ros_msg_send(diosock, &s_msg);
ros_msg_recv(diosock, &r_msg);
}
}
pthread_mutex_unlock(&dio_comm_lock);
ros_msg_free_buffer(&s_msg);
ros_msg_free_buffer(&r_msg);
pthread_exit(0);
};
void *dio_site_settings(void *arg)
{
struct ROSMsg s_msg,r_msg;
struct SiteSettings *site_settings;
site_settings=arg;
ros_msg_init(&s_msg);
ros_msg_init(&r_msg);
ros_msg_set_command(&s_msg,SITE_SETTINGS,"site_settings","NONE");
if (site_settings!=0) {
ros_msg_add_var(&s_msg,&site_settings->ifmode,sizeof(int32),"ifmode","int32");
ros_msg_add_var(&s_msg,&site_settings->rf_settings,sizeof(struct RXFESettings),"rf_rxfe_settings","RFXESetting");
ros_msg_add_var(&s_msg,&site_settings->if_settings,sizeof(struct RXFESettings),"if_rxfe_settings","RXFESetting");
}
pthread_mutex_lock(&dio_comm_lock);
ros_msg_send(diosock, &s_msg);
ros_msg_recv(diosock, &r_msg);
pthread_mutex_unlock(&dio_comm_lock);
ros_msg_free_buffer(&s_msg);
ros_msg_free_buffer(&r_msg);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
const int MAX_KEY = 100000000;
struct list_node_s {
int data;
struct list_node_s* next;
};
struct list_node_s* head = 0;
int thread_count; int total_ops;
double insert_percent; double search_percent; double delete_percent;
pthread_mutex_t mutex;
pthread_mutex_t count_mutex;
int member_total=0, insert_total=0, delete_total=0;
void Get_input(int* inserts_in_main_p) {
printf("Cuantas inserciones desea hacer ? \\n");
scanf("%d", inserts_in_main_p);
printf("Cuantas operacones en total desea hacer? \\n");
scanf("%d", &total_ops);
printf("Porcetaje para busquedas: \\n");
scanf("%lf", &search_percent);
printf("Porcentajes de inserciones: \\n");
scanf("%lf", &insert_percent);
delete_percent = 1.0 - (search_percent + insert_percent);
}
int Insert(int value) {
struct list_node_s* curr = head;
struct list_node_s* pred = 0;
struct list_node_s* temp;
while (curr != 0 && curr->data < value) {
pred = curr;
curr = curr->next;
}
if (curr == 0 || curr->data > value) {
temp = malloc(sizeof(struct list_node_s));
temp->data = value;
temp->next = curr;
if (pred == 0)
head = temp;
else
pred->next = temp;
return 1;
} else {
return 0;
}
}
int Member(int value) {
struct list_node_s* temp;
temp = head;
while (temp != 0 && temp->data < value)
temp = temp->next;
if (temp == 0 || temp->data > value) {
return 0;
} else {
return 1;
}
}
int Delete(int value) {
struct list_node_s* curr = head;
struct list_node_s* pred = 0;
while (curr != 0 && curr->data < value) {
pred = curr;
curr = curr->next;
}
if (curr != 0 && curr->data == value) {
if (pred == 0) {
head = curr->next;
free(curr);
} else {
pred->next = curr->next;
free(curr);
}
return 1;
} else {
return 0;
}
}
void* Thread_work(void* rank) {
long my_rank = (long) rank;
int i, val;
double which_op;
unsigned seed = my_rank + 1;
int my_member=0, my_insert=0, my_delete=0;
int ops_per_thread = total_ops/thread_count;
for (i = 0; i < ops_per_thread; i++) {
which_op = my_drand(&seed);
val = my_rand(&seed) % MAX_KEY;
if (which_op < search_percent) {
pthread_mutex_lock(&mutex);
Member(val);
pthread_mutex_unlock(&mutex);
my_member++;
} else if (which_op < search_percent + insert_percent) {
pthread_mutex_lock(&mutex);
Insert(val);
pthread_mutex_unlock(&mutex);
my_insert++;
} else {
pthread_mutex_lock(&mutex);
Delete(val);
pthread_mutex_unlock(&mutex);
my_delete++;
}
}
pthread_mutex_lock(&count_mutex);
member_total += my_member;
insert_total += my_insert;
delete_total += my_delete;
pthread_mutex_unlock(&count_mutex);
return 0;
}
int main(int argc, char* argv[]) {
long i;
int key, success, attempts;
pthread_t* thread_handles;
int inserts_in_main;
unsigned seed = 1;
double start, finish;
thread_count = strtol(argv[1],0,10);
Get_input(&inserts_in_main);
i = attempts = 0;
while ( i < inserts_in_main && attempts < 2*inserts_in_main ) {
key = my_rand(&seed) % MAX_KEY;
success = Insert(key);
attempts++;
if (success) i++;
}
printf("Inserto %ld nodos en lista\\n", i);
thread_handles = malloc(thread_count*sizeof(pthread_t));
pthread_mutex_init(&mutex, 0);
pthread_mutex_init(&count_mutex, 0);
GET_TIME(start);
for (i = 0; i < thread_count; i++)
pthread_create(&thread_handles[i], 0, Thread_work, (void*) i);
for (i = 0; i < thread_count; i++)
pthread_join(thread_handles[i], 0);
GET_TIME(finish);
printf("Tiempo Transcurrido = %e seconds\\n", finish - start);
printf("Operaciones Totales = %d\\n", total_ops);
printf("Ops Busqueda = %d\\n", member_total);
printf("Ops Inserciones = %d\\n", insert_total);
printf("Ops Borrado= %d\\n", delete_total);
pthread_mutex_destroy(&mutex);
pthread_mutex_destroy(&count_mutex);
free(thread_handles);
return 0;
}
| 0
|
#include <pthread.h>
int g_buffer[5];
unsigned short in = 0;
unsigned short out = 0;
unsigned short produce_id = 0;
unsigned short consume_id = 0;
sem_t g_sem_full;
sem_t g_sem_empty;
pthread_mutex_t g_mutex;
pthread_t g_thread[2 + 2];
void *consume(void *arg)
{
int i;
int num = (int)arg;
while (1)
{
printf("%d wait buffer not empty\\n", num);
sem_wait(&g_sem_empty);
pthread_mutex_lock(&g_mutex);
for (i = 0; i < 5; i++)
{
printf("%02d ", i);
if (g_buffer[i] == -1)
printf("%s", "null");
else
printf("%d", g_buffer[i]);
if (i == out)
printf("\\t<--consume");
printf("\\n");
}
consume_id = g_buffer[out];
printf("%d begin consume product %d\\n", num, consume_id);
g_buffer[out] = -1;
out = (out + 1) % 5;
printf("%d end consume product %d\\n", num, consume_id);
pthread_mutex_unlock(&g_mutex);
sem_post(&g_sem_full);
sleep(1);
}
return 0;
}
void *produce(void *arg)
{
int num = (int)arg;
int i;
while (1)
{
printf("%d wait buffer not full\\n", num);
sem_wait(&g_sem_full);
pthread_mutex_lock(&g_mutex);
for (i = 0; i < 5; i++)
{
printf("%02d ", i);
if (g_buffer[i] == -1)
printf("%s", "null");
else
printf("%d", g_buffer[i]);
if (i == in)
printf("\\t<--produce");
printf("\\n");
}
printf("%d begin produce product %d\\n", num, produce_id);
g_buffer[in] = produce_id;
in = (in + 1) % 5;
printf("%d end produce product %d\\n", num, produce_id++);
pthread_mutex_unlock(&g_mutex);
sem_post(&g_sem_empty);
sleep(5);
}
return 0;
}
int main(void)
{
int i;
for (i = 0; i < 5; i++)
g_buffer[i] = -1;
sem_init(&g_sem_full, 0, 5);
sem_init(&g_sem_empty, 0, 0);
pthread_mutex_init(&g_mutex, 0);
for (i = 0; i < 2; i++)
pthread_create(&g_thread[i], 0, consume, (void *)i);
for (i = 0; i < 2; i++)
pthread_create(&g_thread[2 + i], 0, produce, (void *)i);
for (i = 0; i < 2 + 2; i++)
pthread_join(g_thread[i], 0);
sem_destroy(&g_sem_full);
sem_destroy(&g_sem_empty);
pthread_mutex_destroy(&g_mutex);
return 0;
}
| 1
|
#include <pthread.h>
long long d_to_proc=0;
int tCount=0;
char *outDir="/tmp";
struct linux_dirent {
long d_ino;
off_t d_off;
unsigned short d_reclen;
char d_name[];
};
struct qEnt {
char *dName;
struct qEnt* next;
};
struct qEnt* head = 0;
struct qEnt* tail = 0;
pthread_mutex_t lock_pp;
char *qPop(){
struct qEnt* t = head;
char *rVal;
if ( head==0 ) {
return 0;
}
if ( head==tail ){
rVal=strdup(t->dName);
head=tail=0;
} else {
rVal=strdup(t->dName);
head=head->next;
}
free(t->dName);
free(t);
return(rVal);
}
qPush( char *s ) {
struct qEnt* t = (struct qEnt*)malloc(sizeof(struct qEnt));
t->dName=strdup(s);
if ( t->dName == 0 ) {
printf("Out of memory\\n");
exit(-1);
}
t->next=0;
if ( head==0 && tail==0 ) {
head=tail=t;
return;
}
tail->next=t;
tail=t;
}
void *rdirect(void *threadId){
int myTid;
int fd;
int nread;
int BUF_SIZE=10*1024*1024;
char *buf=(char *)malloc(BUF_SIZE);
char *dN;
char myOFile[1024];
FILE *oFile;
pthread_mutex_lock(&lock_pp);
myTid=tCount;
++tCount;
sprintf(myOFile,"%s/cnh_rd_%5.5d.txt",outDir,myTid);
pthread_mutex_unlock(&lock_pp);
oFile=fopen(myOFile,"w");
if ( oFile == 0 ) {
return;
}
while(1){
dN=0;
while ( dN == 0 && d_to_proc > 0 ) {
pthread_mutex_lock(&lock_pp);
dN = qPop();
pthread_mutex_unlock(&lock_pp);
}
if ( dN==0 ) {
return;
}
fd = open(dN , O_RDONLY | O_DIRECTORY);
if (fd == -1) { return; }
for ( ; ; ) {
nread = syscall(SYS_getdents, fd, buf, BUF_SIZE);
if (nread == -1)
return;
if (nread == 0)
break;
struct linux_dirent *d;
char d_type;
int bpos;
for (bpos = 0; bpos < nread;) {
d = (struct linux_dirent *) (buf + bpos);
d_type = *(buf + bpos + d->d_reclen - 1);
if ( strcmp(d->d_name,".") != 0 &&
strcmp(d->d_name,".." ) != 0 ) {
fprintf(oFile,"%-2s ", (d_type == DT_REG) ? "r" :
(d_type == DT_DIR) ? "d" :
(d_type == DT_FIFO) ? "o" :
(d_type == DT_SOCK) ? "o" :
(d_type == DT_LNK) ? "l" :
(d_type == DT_BLK) ? "o" :
(d_type == DT_CHR) ? "o" : "o");
fprintf(oFile,"%s/%s%c %d\\n",dN,d->d_name,(char)0,myTid);
}
if ( d_type == DT_DIR &&
strcmp(d->d_name,".") != 0 &&
strcmp(d->d_name,"..") != 0 ) {
char *dNext=(char *)malloc(strlen(dN)+1+strlen(d->d_name)+1);
sprintf(dNext,"%s/%s",dN,d->d_name);
pthread_mutex_lock(&lock_pp);
qPush(dNext);
++d_to_proc;
pthread_mutex_unlock(&lock_pp);
free(dNext);
}
bpos += d->d_reclen;
}
}
close(fd);
free(dN);
pthread_mutex_lock(&lock_pp);
--d_to_proc;
pthread_mutex_unlock(&lock_pp);
}
}
main(int argc, char *argv[]){
int rc;
long th;
pthread_t threads[12];
char *dNext;
if ( argc != 2 ) {
printf("Usage \\"%s root_directory\\"\\n",argv[0]);
exit(-1);
}
dNext=(char *)malloc(strlen(argv[1]+1));
sprintf(dNext,"%s",argv[1]);
qPush( argv[1] );
++d_to_proc;
free(dNext);
if ( pthread_mutex_init(&lock_pp, 0) != 0 ) {
printf("Usage \\"Lock failed\\"\\n");
exit(-1);
}
for(th=0;th<12;th++){
printf("In main: creating thread %ld\\n", th);
rc = pthread_create(&threads[th], 0, rdirect, (void *)th);
if (rc){
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int **m1;
int **m2;
int **m3;
int n;
int numT;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condizione = PTHREAD_COND_INITIALIZER;
void stampa(int **m){
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
printf("%d\\t",m[i][j]);
}
printf("\\n");
}
}
void *funzione1(void *p){
int i = *(int*)p;
sleep(1);
for (int j=0;j<n;j++){
pthread_mutex_lock(&mutex);
m3[i][j]=m1[i][j]+m2[i][j];
numT--;
pthread_mutex_unlock(&mutex);
}
if (numT<=0){
pthread_mutex_lock(&mutex);
pthread_cond_signal(&condizione);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void *funzione2(void *p){
pthread_mutex_lock(&mutex);
while(numT>0){
pthread_cond_wait(&condizione,&mutex);
}
pthread_mutex_unlock(&mutex);
stampa(m3);
pthread_exit(0);
}
int main(int argc ,char *argv[]){
if(argc<2){
perror("Errore argomenti");
exit(1);
}
n=atoi(argv[1]);
numT=n;
pthread_t threads[n];
m1=(int**)malloc(sizeof(int*)*n);
m2=(int**)malloc(sizeof(int*)*n);
m3=(int**)malloc(sizeof(int*)*n);
for (int i=0;i<n;i++){
m1[i]=(int*)malloc(sizeof(int)*n);
m2[i]=(int*)malloc(sizeof(int)*n);
m3[i]=(int*)malloc(sizeof(int)*n);
for(int j=0;j<n;j++){
m1[i][j]=1+rand()%10;
m2[i][j]=1+rand()%10;
m3[i][j]=0;
}
}
stampa(m1);
printf("\\n");
stampa(m2);
printf("\\n");
for (int i=0;i<n;i++){
int *indice =malloc(sizeof(int));
*indice = i;
pthread_create(&threads[i],0,funzione1,indice);
}
pthread_create(&threads[n],0,funzione2,0);
for (int i=0;i<n;i++){
pthread_join(threads[i],0);
}
return 0;
}
| 1
|
#include <pthread.h>
unsigned int _memUsed = 0;
struct LinkedListNode * _CreateNode (void);
struct LinkedListNode * _DeleteNode (struct LinkedListNode *target);
void _LockList (struct List *target);
void _UnlockList (struct List *target);
void _LockList (struct List *target) {
pthread_mutex_lock(&target->nodeLock);
}
void _UnlockList (struct List *target) {
pthread_mutex_unlock(&target->nodeLock);
}
struct LinkedListNode * _CreateNode (void) {
struct LinkedListNode * newNode = calloc(1,sizeof(struct LinkedListNode));
_memUsed += sizeof(struct LinkedListNode);
return newNode;
}
struct LinkedListNode * _DeleteNode (struct LinkedListNode *target) {
if (target == 0)
return 0;
struct LinkedListNode *next = target->next;
free(target);
target = 0;
_memUsed -= sizeof(struct LinkedListNode);
return next;
}
struct List * CreateList (void) {
struct List *newList = calloc(1,sizeof(struct List));
_memUsed += sizeof(struct List);
pthread_mutex_init(&newList->nodeLock,0);
return newList;
}
void DeleteList (struct List *list) {
if (list == 0)
return;
ClearList(list);
pthread_mutex_destroy(&list->nodeLock);
free(list);
_memUsed -= sizeof(struct List);
list = 0;
}
void Insert (struct List *list, int data) {
if (list == 0)
return;
struct LinkedListNode *newNode = _CreateNode();
struct LinkedListNode *oldHead = 0;
newNode->data = data;
_LockList(list);
if (list->root == 0) {
list->root = newNode;
list->end = newNode;
list->iter = 0;
} else {
oldHead = list->root;
list->root = newNode;
newNode->next = oldHead;
}
_UnlockList(list);
}
void Append (struct List *list, int data) {
if (list == 0)
return;
struct LinkedListNode *newNode = _CreateNode();
newNode->data = data;
_LockList(list);
if (list->root == 0) {
list->root = newNode;
list->end = newNode;
list->iter = 0;
} else {
list->end->next = newNode;
list->end = newNode;
}
_UnlockList(list);
}
void RemoveFromStart (struct List * list) {
struct LinkedListNode *target = 0;
if (list == 0) return;
_LockList(list);
if (list->root != 0) {
target = list->root;
if (list->root == list->end) {
list->root = 0;
list->end = 0;
list->iter = 0;
} else {
list->root = list->root->next;
}
_DeleteNode(target);
target = 0;
}
_UnlockList(list);
}
void RemoveFromEnd (struct List * list) {
struct LinkedListNode
*prev = 0,
*iter = 0
;
if (list == 0) return;
_LockList(list);
if (list->root != 0) {
if (list->root->next == 0) {
_DeleteNode(list->root);
list->root = 0;
list->end = 0;
list->iter = 0;
} else {
iter = list->root->next;
prev = list->root;
while (iter->next != 0) {
prev = iter;
iter = iter->next;
}
_DeleteNode(iter);
prev->next = 0;
list->end = prev;
}
}
_UnlockList(list);
}
void ClearList (struct List *list) {
struct LinkedListNode *iter = 0, *next = 0;
_LockList(list);
iter = list->root;
while (iter != 0) {
next = iter->next;
_DeleteNode(iter);
iter = next;
}
list->root = 0;
list->end = 0;
list->iter = 0;
_UnlockList(list);
}
void StartIteration (struct List *list) {
if (list == 0) return;
_LockList(list);
list->iter = list->root;
}
void EndIteration (struct List * list) {
if (list == 0) return;
_UnlockList(list);
}
bool GetValueAtIter (struct List *list, int *data) {
if (list == 0 || data == 0) return 0;
if (list->iter == 0) {
return 0;
} else {
*data = list->iter->data;
list->iter = list->iter->next;
return 1;
}
}
int GetMemUsed (void) {
return _memUsed;
}
| 0
|
#include <pthread.h>
struct test_struct {
int disconnected_count;
int connected_count;
int server_fgalive_count;
int client_fgalive_count;
int client_confirmed_count;
sem_t *sem;
pthread_mutex_t *mutex;
};
static int
server_callback (void *arg, struct fgevent *fgev,
struct fgevent * UNUSED(ansev))
{
struct test_struct *counters = (struct test_struct *) arg;
pthread_mutex_lock (counters->mutex);
if (fgev == 0)
{
PRINT_FAIL("fgevent error test %d", counters->server_fgalive_count);
exit(1);
}
switch (fgev->id)
{
case FG_CONNECTED:
counters->connected_count++;
break;
case FG_ALIVE_CONFRIM:
counters->server_fgalive_count++;
break;
case FG_DISCONNECTED:
counters->disconnected_count++;
break;
default:
goto FAIL;
break;
}
if (counters->server_fgalive_count >= 4 * 10)
sem_post (counters->sem);
pthread_mutex_unlock (counters->mutex);
return 0;
FAIL:
PRINT_FAIL("test %d", counters->server_fgalive_count);
exit(1);
}
static int
client_callback (void *arg, struct fgevent *fgev,
struct fgevent * UNUSED(ansev))
{
struct test_struct *counters = (struct test_struct *) arg;
pthread_mutex_lock (counters->mutex);
if (fgev == 0)
{
PRINT_FAIL ("fgevent error test %d", counters->client_fgalive_count);
exit (1);
}
switch (fgev->id)
{
case FG_CONFIRMED:
counters->client_confirmed_count++;
break;
case FG_ALIVE:
counters->client_fgalive_count++;
break;
default:
goto FAIL;
break;
}
pthread_mutex_unlock (counters->mutex);
return 0;
FAIL:
PRINT_FAIL ("test %d", counters->client_fgalive_count);
exit (1);
}
int
main (void)
{
int s;
int i;
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[10];
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);
for (i = 0; i < 10 / 2; i++)
{
fg_events_client_init_inet (&clients[i], &client_callback, 0, &test_data, "127.0.0.1", server.port, 2 + i);
printf("spawned %d client\\n", 2 + i);
}
for (; i < 10; i++)
{
fg_events_client_init_unix (&clients[i], &client_callback, 0, &test_data, server.addr, 2 + i);
printf("spawned %d client\\n", 2 + i);
}
clock_gettime (CLOCK_REALTIME, &ts);
ts.tv_sec += 5;
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);
for (i = 0; i < 10; i++)
{
fg_events_client_shutdown (&clients[i]);
}
sleep (1);
fg_events_server_shutdown (&server);
if (test_data.connected_count != test_data.disconnected_count ||
test_data.server_fgalive_count != test_data.client_fgalive_count ||
test_data.client_confirmed_count != test_data.connected_count)
{
PRINT_FAIL ("some events missed ([%d, %d, %d], [%d, %d])",
test_data.connected_count,
test_data.disconnected_count,
test_data.client_confirmed_count,
test_data.server_fgalive_count,
test_data.client_fgalive_count);
exit (1);
}
PRINT_SUCCESS ("all tests passed");
return 0;
}
| 1
|
#include <pthread.h>
struct thread_data {
long long soffset, foffset, offset;
pthread_t tid;
};
struct thread_data wthread[(1024)];
int nthreads;
unsigned int bwritten = 0;
pthread_mutex_t bwritten_mutex = PTHREAD_MUTEX_INITIALIZER;
long long fake_read(char *buffer, size_t size) ;
long long fake_write(char *buffer, size_t size, size_t offset)
;
long long fake_read(char *buffer, size_t size) {
size_t i;
for (i = 0; i < size; ++i)
buffer[i] = rand() % 26 + 'a';
return size;
}
long long fake_write(char *buffer, size_t size, size_t offset) {
size_t i;
for (i = 0; i < size; ++i)
fprintf(stderr, "%lu: %c\\n", offset + i, buffer[i]);
return size;
}
void *http_get(struct thread_data *td) {
long long foffset;
char *rbuf;
pthread_t tid;
tid = pthread_self();
rbuf = (char *)calloc((8192), sizeof(char));
foffset = td->foffset;
td->offset = td->soffset;
while (td->offset < foffset) {
long long dr, dw;
memset(rbuf, (8192), 0);
dr = fake_read(rbuf, (8192));
if (td->offset + dr > foffset)
dw = fake_write(rbuf, foffset - td->offset, td->offset);
else
dw = fake_write(rbuf, dr, td->offset);
td->offset += dw;
pthread_mutex_lock(&bwritten_mutex);
bwritten += dw;
pthread_mutex_unlock(&bwritten_mutex);
}
return 0;
}
long long calc_offset(long long total, int part, int nthreads) {
return (part * (total / nthreads));
}
int main(int argc, char *argv[]) {
int i;
long long clength;
if (argc < 3) {
return 1;
}
clength = atoi(argv[1]);
nthreads = atoi(argv[2]);
for (i = 0; i < nthreads; ++i) {
long long soffset = calc_offset(clength, i, nthreads);
long long foffset = calc_offset(clength, i + 1, nthreads);
wthread[i].soffset = soffset;
wthread[i].foffset = (i == nthreads - 1 ? clength : foffset);
pthread_create(&(wthread[i].tid), 0,
(void *(*)(void *))http_get, &(wthread[i]));
}
for (i = 0; i < nthreads; ++i)
pthread_join(wthread[i].tid, 0);
return 0;
}
| 0
|
#include <pthread.h>
struct mq_attr attr;
FILE *logFile;
void *LoggerThread(void *args)
{ printf("%s\\n","Logger created");
uint32_t data_to_log;
uint32_t ret;
uint32_t bytes_read;
LogMsg *logmsg3;
printf("Log file create status - %d,\\n", create_log_file(&logFile, "some"));
if(create_log_struct(&logmsg3)!=DONE){
printf("%s\\n","Error creating struct");
}
logmsg3->requestID=100;
while(1)
{
pthread_mutex_lock(&dataQ_mutex);
pthread_cond_wait(&condvar,&dataQ_mutex);
pthread_mutex_unlock(&dataQ_mutex);
if(flag_mask & SIGINT_EVENT)
{
printf("%s\\n","Logger got SIGINT");
mq_close(data_queue_handle);
fclose(logFile);
break;
}
if((flag_mask_copy & TIMER_EVENT) || (flag_mask_copy & ASYNC_EVENT))
{
mq_getattr(data_queue_handle, &attr);
while(attr.mq_curmsgs > 0)
{
pthread_mutex_lock(&logQ_mutex);
bytes_read = mq_receive(data_queue_handle, (char *)&logmsg3, MAX_SEND_BUFFER+1, &data_to_log);
if (bytes_read == -1)
{
perror("[LoggerThread] Failed to recieve:");
}
else
{
printf("[LoggerThread] Queue %s currently holds %ld messages\\n",QLog,attr.mq_curmsgs);
mq_getattr(data_queue_handle, &attr);
if(logmsg3->requestID == LOG_DATA)
{
printf("Logging status -%d\\n",log_item(logFile,logmsg3) );
printf ("[LoggerThread] source ID: %d \\n", logmsg3->sourceId);
printf ("[LoggerThread] Log Level: %d \\n", logmsg3->level);
printf ("[LoggerThread] Payload: %s \\n\\n", logmsg3->payload);
printf ("[LoggerThread] Timestamp: %s \\n", ctime(&logmsg3->timestamp));
}
}
pthread_mutex_unlock(&logQ_mutex);
}
}
}
printf("%s\\n","Outside Logger Thread");
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int main(int argc, char* argv[]){
pthread_t Les_Threads[2];
int delai[2], i = 0;
void Une_Tache (void *arg);
if (argc != 3) {
printf("Utilisation : %s delai_1 delai_2 !\\n", argv[0]);
return 1;
}
for (i = 0; i < 2 ; i++){
delai[i] = atoi(argv[i+1]);
pthread_create(Les_Threads+i, 0,(void *) Une_Tache, (void *) (delai+i));
}
for (i = 0 ; i < 2 ; i++){
pthread_join(Les_Threads[i],0);
printf("main (tid %d) fin de tid %d\\n", (int)pthread_self(), (int)Les_Threads[i]);
}
return 0;
}
void Une_Tache (void *arg) {
int *Ptr;
int compteur, delai;
pthread_cond_t var_cond;
pthread_mutex_t verrou;
struct timespec time;
Ptr = (int *)arg;
delai = *Ptr;
pthread_cond_init(&var_cond, 0);
pthread_mutex_init(&verrou, 0);
compteur = 0;
while (compteur < 10){
pthread_mutex_lock(&verrou);
clock_gettime (CLOCK_REALTIME, &time);
time.tv_sec += delai ;
compteur = compteur + 1;
printf("tid %d : date (s.ns) : %d.%d, compteur %d, delai %d\\n",
(int)pthread_self(), (int)time.tv_sec, (int)time.tv_nsec, compteur, delai);
pthread_cond_timedwait (&var_cond, &verrou, &time);
pthread_mutex_unlock(&verrou);
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
void prepare(void)
{
printf("preparing locks...\\n");
pthread_mutex_lock(&lock1);
pthread_mutex_lock(&lock2);
}
void parent(void)
{
printf("parent unlocking locks...\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void child(void)
{
printf("child unlocking locks...\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void *thr_fn(void *arg)
{
printf("thread started...\\n");
pause();
return (void *)0;
}
int main(void)
{
int err;
pid_t pid;
pthread_t tid;
if ((err = pthread_atfork(prepare, parent, child)) != 0)
err_exit(err, "can't install fork handler");
if ((err = pthread_create(&tid, 0, thr_fn, 0)) != 0)
err_exit(err, "can't create thread");
sleep(2);
printf("parent about to fork...\\n");
if ((pid = fork()) < 0)
err_quit("fork failed");
else if (pid == 0)
printf("child returned from fork\\n");
else
printf("parent returned from fork\\n");
return 0;
}
| 1
|
#include <pthread.h>
struct msgreg_t {
int mtype;
short rvport;
};
struct msggetnode_t {
int mtype;
};
struct node {
struct sockaddr_in address;
long port;
int del;
};
struct listmsg_t {
int mtype;
struct node nodeList[10];
};
struct recvmsg_t {
int mtype;
long port;
};
int nodes = 0;
struct node nodeList[10];
struct listmsg_t listmsg;
pthread_mutex_t mtx_msg = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mtxMaxBees = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condMaxBees = PTHREAD_COND_INITIALIZER;
char s[10];
int n;
int addNode(struct sockaddr_in nodeAddr, long port)
{
nodeList[nodes].address = nodeAddr;
nodeList[nodes].port = port;
nodeList[nodes].del = 0;
listmsg.nodeList[nodes].address = nodeAddr;
listmsg.nodeList[nodes].port = port;
listmsg.nodeList[nodes].del = 0;
nodes++;
return 0;
}
int remNode(struct sockaddr_in nodeAddr, int port)
{
int i;
for (i=0;i<nodes;i++)
{
if (nodes == 1)
{
nodeList[0].del = 1;
nodes--;
return 0;
}
if (nodeAddr.sin_addr.s_addr == nodeList[i].address.sin_addr.s_addr && nodeAddr.sin_port == nodeList[i].address.sin_port)
{
int j;
int k;
for (j=i;j<nodes;j++)
nodeList[j] = nodeList[j+1];
nodeList[nodes].del = 1;
nodes--;
}
}
return 0;
}
void* handleThem(void* arg)
{
int sock = *((int*) arg);
int i, len;
struct recvmsg_t recvmsg;
struct sockaddr_in address;
len = sizeof(address);
getpeername(sock, (struct sockaddr*)&address, &len);
i = recv(sock, &recvmsg, sizeof(struct recvmsg_t), 0);
if (i < 0)
{
perror("[DRONE] recv error:");
return 0;
}
if (recvmsg.mtype == 1)
{
pthread_mutex_lock(&mtxMaxBees);
while(nodes >= n)
{
printf("[EAGER BEE] Too many bees (nodes); Waiting...\\n");
pthread_cond_wait(&condMaxBees, &mtxMaxBees);
}
addNode(address, recvmsg.port);
printf("[DRONE] ++ %d nodes.\\n",nodes);
printf("[DRONE] Added bee %s : %ld\\n",inet_ntoa((*(struct in_addr *)&nodeList[nodes-1].address.sin_addr.s_addr)), nodeList[nodes-1].port);
i = 0;
printf("[DRONE] Currently available:\\n");
while (nodeList[i].address.sin_port != 0)
{
printf("\\t[%d] %s : %ld\\n", i+1, inet_ntoa(nodeList[i].address.sin_addr),nodeList[i].port);
i = i + 1;
}
pthread_cond_broadcast(&condMaxBees);
pthread_mutex_unlock(&mtxMaxBees);
}
else if (recvmsg.mtype == 2)
{
int ok;
listmsg.mtype = 3;
ok = send(sock, &listmsg, sizeof(struct listmsg_t ), 0);
if (ok<0)
{
perror("[DRONE] Send error:");
}
printf("[DRONE] Sent polen to the client.\\n");
i = 0;
printf("[DRONE] Currently available:\\n");
while (nodeList[i].address.sin_port != 0)
{
printf("\\t[%d] %s : %ld\\n", i+1, inet_ntoa(listmsg.nodeList[i].address.sin_addr),listmsg.nodeList[i].port);
i = i + 1;
}
}
else
{
printf("[DRONE] This is some kind of weird bee...\\n");
}
sleep(1);
close(sock);
return 0;
}
int main() {
struct sockaddr_in address, them;
int sock, sock_them;
int len;
printf("[USER] Insert number of flowers: ");
gets(s);
n = atoi(s);
pthread_t thr;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock<0) {
perror("[DRONE] Error creating:");
}
printf("[DRONE] Created sock...\\n");
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(1026);
if (bind(sock, (struct sockaddr*) &address, sizeof(struct sockaddr))<0) {
perror("[DRONE] Error binding:");
}
printf("[DRONE] Binded...\\n");
listen(sock, 20);
while(1) {
len = sizeof(struct sockaddr_in);
sock_them = accept(sock, (struct sockaddr*) &them, &len);
printf("[DRONE] Accepted...\\n");
pthread_create(&thr, 0, handleThem, &sock_them);
sleep(1+rand()%2);
}
return 0;
}
| 0
|
#include <pthread.h>
struct CRYPTO_dynlock_value
{ pthread_mutex_t mutex;
};
void sigpipe_handle(int x)
{
}
static pthread_mutex_t *mutex_buf;
static struct CRYPTO_dynlock_value *dyn_create_function(const char *file, int line)
{ struct CRYPTO_dynlock_value *value;
value = (struct CRYPTO_dynlock_value*)malloc(sizeof(struct CRYPTO_dynlock_value));
if (value)
pthread_mutex_init(&(value->mutex), 0);
return value;
}
static void dyn_lock_function(int mode, struct CRYPTO_dynlock_value *l, const char *file, int line)
{ if (mode & CRYPTO_LOCK)
pthread_mutex_lock(&(l->mutex));
else
pthread_mutex_unlock(&(l->mutex));
}
static void dyn_destroy_function(struct CRYPTO_dynlock_value *l, const char *file, int line)
{ pthread_mutex_destroy(&(l->mutex));
free(l);
}
void kms_locking_function(int mode, int n, const char *file, int line)
{ if (mode & CRYPTO_LOCK)
pthread_mutex_lock(&(mutex_buf[n]));
else
pthread_mutex_unlock(&(mutex_buf[n]));
}
unsigned long id_function(void )
{ return (unsigned long)pthread_self();
}
extern int ssl_init();
int K_SetupSSL()
{ int i;
mutex_buf = (pthread_mutex_t*)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
if (!mutex_buf) {
return 0;
}
for (i = 0; i < CRYPTO_num_locks(); i++)
pthread_mutex_init(&(mutex_buf[i]), 0);
if (CRYPTO_get_id_callback() == 0)
CRYPTO_set_id_callback(id_function);
if (CRYPTO_get_locking_callback() == 0)
CRYPTO_set_locking_callback(kms_locking_function);
CRYPTO_set_dynlock_create_callback(dyn_create_function);
CRYPTO_set_dynlock_lock_callback(dyn_lock_function);
CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function);
signal(SIGPIPE, sigpipe_handle);
OpenSSL_add_all_ciphers();
OpenSSL_add_all_digests();
ssl_init();
return 1;
}
void K_CleanupSSL()
{ int i;
if (!mutex_buf)
return;
CRYPTO_set_dynlock_create_callback(0);
CRYPTO_set_dynlock_lock_callback(0);
CRYPTO_set_dynlock_destroy_callback(0);
for (i = 0; i < CRYPTO_num_locks(); i++)
pthread_mutex_destroy(&(mutex_buf[i]));
OPENSSL_free(mutex_buf);
mutex_buf = 0;
}
int K_SetupCallbacks( struct soap *i_pSoap )
{
return 1;
}
| 1
|
#include <pthread.h>
double x;
double y;
} vec2;
vec2 position;
vec2 velocity;
double mass;
} planet;
int num_threads;
int num_planets;
int num_timesteps;
int output;
int portion;
vec2** local_forces;
int counter;
pthread_mutex_t mutex;
pthread_cond_t cond_var;
vec2* forces;
planet* planets;
void barrier() {
pthread_mutex_lock(&mutex);
counter++;
if (counter == num_threads)
{
counter = 0;
pthread_cond_broadcast(&cond_var);
}
else
{
while (pthread_cond_wait(&cond_var, &mutex) != 0);
}
pthread_mutex_unlock(&mutex);
}
void parse_args(int argc, char** argv){
if(argc != 4){
printf("Useage: nbody num_timesteps num_threads output\\n");
printf("output:\\n");
printf("0 - One file at end of simulation\\n");
printf("1 - One file for each timestep, with planet positions (for movie)\\n");
exit(-1);
}
num_timesteps = strtol(argv[1], 0, 10);
num_threads = strtol(argv[2], 0, 10);
output = strtol(argv[3], 0, 10);
}
void read_planets(){
FILE* file = fopen("planets.txt", "r");
if(file == 0){
printf("'planets.txt' not found. Exiting\\n");
exit(-1);
}
char line[200];
fgets(line, 200, file);
sscanf(line, "%d", &num_planets);
planets = (planet*)malloc(sizeof(planet)*num_planets);
for(int p = 0; p < num_planets; p++){
fgets(line, 200, file);
sscanf(line, "%lf %lf %lf %lf %lf",
&planets[p].position.x,
&planets[p].position.y,
&planets[p].velocity.x,
&planets[p].velocity.y,
&planets[p].mass);
}
fclose(file);
}
void write_planets(int timestep, int output){
char name[20];
if(output == 1){
sprintf(name, "%04d.dat", timestep);
}
else{
sprintf(name, "planets_out.txt");
}
FILE* file = fopen(name, "wr+");
for(int p = 0; p < num_planets; p++){
if(output == 1){
fprintf(file, "%f %f\\n",
planets[p].position.x,
planets[p].position.y);
}
else{
fprintf(file, "%f %f %f %f %f\\n",
planets[p].position.x,
planets[p].position.y,
planets[p].velocity.x,
planets[p].velocity.y,
planets[p].mass);
}
}
fclose(file);
}
vec2 compute_force(planet p, planet q){
vec2 force;
vec2 dist;
dist.x = q.position.x - p.position.x;
dist.y = q.position.y - p.position.y;
double abs_dist= sqrt(dist.x*dist.x + dist.y*dist.y);
double dist_cubed = abs_dist*abs_dist*abs_dist;
force.x = 0.6*p.mass*q.mass/dist_cubed * dist.x;
force.y = 0.6*p.mass*q.mass/dist_cubed * dist.y;
return force;
}
void* loop(void* arg)
{
int rank = (long)arg;
int start_p = portion * rank;
int end_p;
if (num_planets >= portion + start_p)
end_p = portion + start_p;
else
end_p = num_planets;
for(int t = 0; t < num_timesteps; t++){
if (rank == 0 && output == 1){
write_planets(t, 1);
}
for(int i = start_p; i < end_p; i++){
forces[i].x = 0;
forces[i].y = 0;
}
for(int p = start_p; p < end_p; p++){
for(int q = p+1; q < num_planets; q++){
vec2 f = compute_force(planets[p], planets[q]);
local_forces[rank][p].x += f.x;
local_forces[rank][p].y += f.y;
local_forces[rank][q].x -= f.x;
local_forces[rank][q].y -= f.y;
}
}
barrier();
for (int i = 0; i < num_threads; i++)
{
for(int p = start_p; p < end_p; p++)
{
forces[p].x += local_forces[i][p].x;
local_forces[i][p].x = 0;
forces[p].y += local_forces[i][p].y;
local_forces[i][p].y = 0;
}
}
for(int p = start_p; p < end_p; p++){
planets[p].position.x += 0.2 * planets[p].velocity.x;
planets[p].position.y += 0.2 * planets[p].velocity.y;
planets[p].velocity.x += 0.2 * forces[p].x / planets[p].mass;
planets[p].velocity.y += 0.2 * forces[p].y / planets[p].mass;
}
barrier();
}
return 0;
}
int main(int argc, char** argv){
parse_args(argc, argv);
read_planets();
forces = (vec2*)malloc(sizeof(vec2)*num_planets);
local_forces = (vec2**)malloc(sizeof(vec2*)*num_threads);
for (int i = 0; i < num_threads; i++)
{
local_forces[i] = (vec2*)malloc(sizeof(vec2)*num_planets);
for (int p = 0; p < num_planets; p++)
local_forces[i][p].x = local_forces[i][p].y = 0;
}
pthread_t threads[num_threads-1];
portion = num_planets / num_threads + 1;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond_var,0);
for (int i = 0; i < num_threads-1; i++)
{
pthread_create(&threads[i], 0, loop, (void*)((long)(i+1)));
}
loop(0);
for (int i = 0; i < num_threads-1; i++)
{
pthread_join(threads[i], 0);
}
if(output == 0){
write_planets(num_timesteps,0);
}
}
| 0
|
#include <pthread.h>
int nitems;
struct {
pthread_mutex_t mutex;
int buff[10000000];
int nput;
int nval;
} shared={
PTHREAD_MUTEX_INITIALIZER
};
void consume_wait(int i){
for(;;){
pthread_mutex_lock(&shared.mutex);
if(i<shared.nput){
pthread_mutex_unlock(&shared.mutex);
return;
}
pthread_mutex_unlock(&shared.mutex);
}
}
void* produce(void*),*consume(void*);
int min(int a,int b){
return (a>=b)?b:a;
}
int main(int argc,char* argv[]){
int i,nthreads,count[100];
pthread_t tid_produce[100],tid_consume;
nitems=min(atoi(argv[1]),10000000);
nthreads=min(atoi(argv[2]),100);
clock_t st,ed;
double gap;
st=clock();
for(i=0;i<nthreads;i++){
count[i]=0;
pthread_create(&tid_produce[i],0,produce,&count[i]);
}
pthread_create(&tid_consume,0,consume,0);
for(i=0;i<nthreads;i++){
pthread_join(tid_produce[i],0);
printf("count[%d]=%d\\n",i,count[i]);
}
pthread_join(tid_consume,0);
ed=clock();
gap=(double)(ed-st);
printf("gap time %f\\n",gap/CLOCKS_PER_SEC);
return 0;
}
void* produce(void* arg){
for(;;){
pthread_mutex_lock(&shared.mutex);
if(shared.nput>=nitems){
pthread_mutex_unlock(&shared.mutex);
break;
}
shared.buff[shared.nput]=shared.nval;
shared.nval++;
shared.nput++;
pthread_mutex_unlock(&shared.mutex);
*((int*)arg)+=1;
}
}
void* consume(void* arg){
int i;
for(i=0;i<nitems;i++){
consume_wait(i);
if(shared.buff[i]!=i)
printf("buff[%d]=%d\\n",i,shared.buff[i]);
}
}
| 1
|
#include <pthread.h>
static char* output_string = 0;
static pthread_mutex_t output_lock;
static int initialized = 0;
static pthread_t thread;
static int has_battery = 0;
static void* query_battery_thread() {
FILE *fp;
if( output_string == 0 ) {
output_string = calloc( 32, sizeof(char) );
}
if( !has_battery ) {
pthread_mutex_lock( &output_lock );
strncpy( output_string, "100% **", 32 -1 );
pthread_mutex_unlock( &output_lock );
return 0;
}
while( initialized ) {
char charge_status[32];
pthread_mutex_lock( &output_lock );
fp = fopen( "/sys/class/power_supply/BAT0/capacity", "r" );
fscanf( fp, "%s", output_string );
strncat( output_string, "% ", 32 -1 );
fclose(fp);
fp = fopen( "/sys/class/power_supply/BAT0/status", "r" );
fscanf( fp, "%s", charge_status );
fclose(fp);
if ( strcmp( charge_status, "Charging" ) == 0 ) {
strncat( output_string, "++", 32 -1 );
}
else if ( strcmp( charge_status, "Discharging" ) == 0 ) {
strncat( output_string, "--", 32 -1 );
}
else {
strncat( output_string, "??", 32 -1 );
log_error( "Failed to fetch charging status." );
}
pthread_mutex_unlock( &output_lock );
sleep( 2 );
}
free( output_string );
output_string = 0;
return 0;
}
int battery_init() {
if( initialized ) return 0;
pthread_mutex_init( &output_lock, 0 );
pthread_create( &thread, 0, &query_battery_thread, 0 );
struct stat s;
if( stat("/sys/class/power_supply/BAT0", &s) == -1 ) {
has_battery = 0;
}
else {
has_battery = 1;
}
initialized = 1;
return 1;
}
int battery_destroy() {
if( !initialized ) return 0;
initialized = 0;
pthread_join( thread, 0 );
pthread_mutex_destroy( &output_lock );
return 1;
}
char* get_battery_information() {
if( !initialized ) return 0;
char* battery_string = calloc( 32, sizeof(char) );
pthread_mutex_lock( &output_lock );
if( output_string )
strncpy( battery_string, output_string, 32 -1 );
pthread_mutex_unlock( &output_lock );
return battery_string;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex[3] = {
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER
};
void *lock_forward (void *arg)
{
int i, iterate, backoffs;
int status;
for (iterate = 0; iterate < 10; iterate++) {
backoffs = 0;
status = pthread_mutex_lock (&mutex[0]);
for (i = 1; i < 3; i++) {
status = pthread_mutex_trylock (&mutex[i]);
if (status == EBUSY) {
backoffs++;
printf("forward locker backing off at %d\\n",i);
for (; i >= 0; i--)
status = pthread_mutex_unlock (&mutex[i]);
}
else
printf(" forward locker got %d\\n", i);
}
sleep (1);
}
printf (
"lock forward got all locks, %d backoffs\\n", backoffs);
pthread_mutex_unlock (&mutex[2]);
pthread_mutex_unlock (&mutex[1]);
pthread_mutex_unlock (&mutex[0]);
sleep (1);
return 0;
}
void *lock_backward (void *arg)
{
int i, iterate, backoffs;
int status;
for (iterate = 0; iterate < 10; iterate++) {
backoffs = 0;
status = pthread_mutex_lock (&mutex[2]);
for (i = 1; i >= 0; i--) {
status = pthread_mutex_trylock (&mutex[i]);
if (status == EBUSY) {
backoffs++;
printf("backward locker backing off at %d\\n",i);
for (; i <3; i++)
status = pthread_mutex_unlock (&mutex[i]);
}
else
printf(" backward locker got %d\\n", i);
}
sleep (1);
}
printf (
"lock forward got all locks, %d backoffs\\n", backoffs);
pthread_mutex_unlock (&mutex[2]);
pthread_mutex_unlock (&mutex[1]);
pthread_mutex_unlock (&mutex[0]);
sleep (1);
return 0;
}
int main (int argc, char *argv[])
{
pthread_t forward, backward;
int status;
if (argc > 2)
yield_flag = atoi (argv[2]);
status = pthread_create (
&forward, 0, lock_forward, 0);
if (status != 0)
err_abort (status, "Create forward");
status = pthread_create (
&backward, 0, lock_backward, 0);
if (status != 0)
err_abort (status, "Create backward");
pthread_exit (0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex1, mutex2, mutex3;
void * th1(){
while(1){
pthread_mutex_lock(&mutex1);
printf("1\\n");
fflush(stdout);
sleep(1);
pthread_mutex_unlock(&mutex2);
}
}
void * th2(){
while(1){
pthread_mutex_lock(&mutex2);
printf("2\\n");
fflush(stdout);
sleep(2);
pthread_mutex_unlock(&mutex3);
}
}
void * th3(){
while(1){
pthread_mutex_lock(&mutex3);
printf("3\\n");
fflush(stdout);
sleep(3);
pthread_mutex_unlock(&mutex1);
}
}
int main(int argc, char **argv){
pthread_t thread1, thread2, thread3;
pthread_mutex_init(&mutex1, 0);
pthread_mutex_init(&mutex2, 0);
pthread_mutex_init(&mutex3, 0);
pthread_mutex_lock(&mutex2);
pthread_mutex_lock(&mutex3);
if(pthread_create(&thread1, 0, th1, 0)) {
fprintf(stderr, "Error creating thread\\n");
return 1;
}
if(pthread_create(&thread2, 0, th2, 0)) {
fprintf(stderr, "Error creating thread\\n");
return 1;
}
if(pthread_create(&thread3, 0, th3, 0)) {
fprintf(stderr, "Error creating thread\\n");
return 1;
}
if(pthread_join(thread1, 0)) {
fprintf(stderr, "Error joining thread\\n");
return 1;
}
return 0;
}
| 0
|
#include <pthread.h>
{
void *(*process)(void *arg);
void *arg;
struct worker *next;
} CThread_worker;
{
pthread_mutex_t queue_lock;
pthread_cond_t queue_ready;
CThread_worker *queue_head;
int shutdown;
pthread_t *threadid;
int max_thread_num;
int cur_queue_size;
} CThread_pool;
void *thread_routine(void* arg);
int pool_add_worker(void *process(void*),void*);
static CThread_pool *poll = 0;
void poll_init(int max_thread_num)
{
poll = (CThread_pool*)malloc(sizeof(CThread_pool));
poll->threadid = (pthread_t*)malloc(sizeof(pthread_t)*max_thread_num);
poll->queue_head = 0;
pthread_mutex_init(&(poll->queue_lock),0);
pthread_cond_init(&(poll->queue_ready),0);
poll->shutdown = 0;
poll->max_thread_num = max_thread_num;
poll->cur_queue_size = 0;
int i = 0;
for(i = 0;i<max_thread_num;i++)
{
pthread_create(&poll->threadid[i],0,thread_routine,0);
}
}
int pool_add_worker(void *(*process)(void*),void* arg)
{
CThread_worker *newWorker = (CThread_worker*)malloc(sizeof(CThread_worker));
newWorker->process = process;
newWorker->arg = arg;
newWorker->next = 0;
pthread_mutex_lock(&(poll->queue_lock));
CThread_worker* tmp = poll->queue_head;
if(tmp == 0)
poll->queue_head = newWorker;
else
{
while(tmp->next)
tmp = tmp->next;
tmp->next = newWorker;
}
assert(poll->queue_head != 0);
poll->cur_queue_size++;
pthread_mutex_unlock(&(poll->queue_lock));
pthread_cond_signal(&(poll->queue_ready));
}
void* thread_routine(void* arg)
{
printf("start thread ID is :%d\\n",pthread_self());
while(1)
{
pthread_mutex_lock(&(poll->queue_lock));
while(poll->cur_queue_size == 0 && poll->shutdown == 0)
{
printf("thread %d is waiting\\n",pthread_self());
pthread_cond_wait(&poll->queue_ready,&poll->queue_lock);
}
if(poll->shutdown == 1)
{
pthread_mutex_unlock(&poll->queue_lock);
printf("thead 0x%x is exit\\n",pthread_self());
pthread_exit(0);
}
printf("thread %d starting work\\n",pthread_self());
assert(poll->cur_queue_size != 0);
assert(poll->queue_head != 0);
poll->cur_queue_size--;
CThread_worker* tmp = poll->queue_head;
poll->queue_head = tmp->next;
pthread_mutex_unlock(&poll->queue_lock);
*tmp->process(tmp->arg);
free(tmp);
tmp = 0;
}
}
int poll_destroty()
{
if(poll->shutdown)
return -1;
int i =0;
poll->shutdown = 1;
pthread_cond_broadcast(&poll->queue_ready);
for(i = 0;i<poll->max_thread_num;i++)
pthread_join(poll->threadid[i],0);
free(poll->threadid);
CThread_worker* head = poll->queue_head;
while(head)
{
CThread_worker* next = head->next;
free(head);
head = 0;
head = next;
}
pthread_mutex_destroy(&poll->queue_lock);
pthread_cond_destroy(&poll->queue_ready);
free(poll);
poll=0;
}
void* myprocess(void* arg)
{
printf("threadid is 0x%x,working on task %d\\m",pthread_self(),*(int*)arg);
sleep(1);
return 0;
}
int main(void)
{
poll_init(2);
int i = 0;
int *worknum = (int*)malloc(sizeof(int)*10);
for(i = 0;i<2;i++)
{
worknum[i] = i;
pool_add_worker(myprocess,&worknum[i]);
}
sleep(5);
poll_destroty();
free(worknum);
return 0;
}
| 1
|
#include <pthread.h>
struct sigfd_compat_info
{
sigset_t mask;
int fd;
};
static void *sigwait_compat(void *opaque)
{
struct sigfd_compat_info *info = opaque;
sigset_t all;
sigfillset(&all);
pthread_sigmask(SIG_BLOCK, &all, 0);
while (1) {
int sig;
int err;
err = sigwait(&info->mask, &sig);
if (err != 0) {
if (errno == EINTR) {
continue;
} else {
return 0;
}
} else {
struct qemu_signalfd_siginfo buffer;
size_t offset = 0;
memset(&buffer, 0, sizeof(buffer));
buffer.ssi_signo = sig;
while (offset < sizeof(buffer)) {
ssize_t len;
len = write(info->fd, (char *)&buffer + offset,
sizeof(buffer) - offset);
if (len == -1 && errno == EINTR)
continue;
if (len <= 0) {
return 0;
}
offset += len;
}
}
}
return 0;
}
extern pthread_mutex_t mm_mutex;
static int qemu_signalfd_compat(const sigset_t *mask)
{
pthread_attr_t attr;
pthread_t tid;
struct sigfd_compat_info *info;
int fds[2];
info = qemu_malloc(sizeof(*info));
if (info == 0) {
errno = ENOMEM;
return -1;
}
if (pipe(fds) == -1) {
free(info);
return -1;
}
qemu_set_cloexec(fds[0]);
qemu_set_cloexec(fds[1]);
memcpy(&info->mask, mask, sizeof(*mask));
info->fd = fds[1];
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_mutex_lock(&mm_mutex);
pthread_create(&tid, &attr, sigwait_compat, info);
pthread_mutex_unlock(&mm_mutex);
pthread_attr_destroy(&attr);
return fds[0];
}
int qemu_signalfd(const sigset_t *mask)
{
return qemu_signalfd_compat(mask);
}
bool qemu_signalfd_available(void)
{
return 0;
}
| 0
|
#include <pthread.h>
int ticketcount = 20;
pthread_mutex_t lock;
void *salewind1(void *args)
{
while(1)
{
pthread_mutex_lock(&lock);
if(ticketcount > 0)
{
printf("windows1 start sale ticket! the ticket is :%d\\n", ticketcount);
sleep(3);
ticketcount--;
printf("sale ticket finish!, the last ticket is:%d\\n", ticketcount);
}else
{
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
pthread_mutex_unlock(&lock);
sleep(1);
}
}
void *salewind2(void *args)
{
while(1)
{
pthread_mutex_lock(&lock);
if(ticketcount > 0)
{
printf("windows2 start sale ticket! the ticket is :%d\\n", ticketcount);
sleep(3);
ticketcount--;
printf("sale ticket finish!, the last ticket is:%d\\n", ticketcount);
}else
{
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
pthread_mutex_unlock(&lock);
sleep(1);
}
}
int
main()
{
pthread_t pthid1 = 0;
pthread_t pthid2 = 0;
pthread_mutex_init(&lock, 0);
pthread_create(&pthid1,0, salewind1,0);
pthread_create(&pthid2,0, salewind2,0);
pthread_join(pthid1,0);
pthread_join(pthid2,0);
pthread_mutex_destroy(&lock);
return 0;
}
| 1
|
#include <pthread.h>
int count = 0;
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *inc_count(void *t)
{
int j,i;
double result=0.0;
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);
sleep(1);
}
pthread_exit(0);
}
void *watch_count(void *t)
{
long my_id = (long)t;
printf("Starting watch_count(): thread %ld\\n", my_id);
pthread_mutex_lock(&count_mutex);
if (count < 12) {
printf("watch_count(): thread %ld going into wait...\\n", my_id);
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %ld Condition signal received.\\n", my_id);
count += 125;
printf("watch_count(): thread %ld count now = %d.\\n", my_id, count);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int i, rc;
long t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, watch_count, (void *)t1);
pthread_create(&threads[1], &attr, inc_count, (void *)t2);
pthread_create(&threads[2], &attr, inc_count, (void *)t3);
for (i = 0; i < 3; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited on %d threads. 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);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex3 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t pourLire = PTHREAD_COND_INITIALIZER;
pthread_cond_t pourEcrire = PTHREAD_COND_INITIALIZER;
void put(int);
int get();
int buf[12];
int indCons, indProd;
int nbElements;
void* loop_Prod(void* nb){
int* ptr = nb;
int a = *ptr;
while(1){
put(a);
printf("[%d] production\\t[nb elt = %d]\\n", a, nbElements);
sleep(1);
}
}
void* loop_Cons(void* nb){
int* ptr = nb;
int a = *ptr;
while(1){
int n = get();
printf("[%d] lecture %d\\t[nb elt = %d]\\n", a, n, nbElements);
sleep(1);
}
}
void put(int v){
pthread_mutex_lock( &mutex1 );
while(nbElements == 12)
pthread_cond_wait(&pourEcrire, &mutex1);
buf[indProd] = v;
indProd = (indProd+1) % 12;
nbElements++;
pthread_cond_signal(&pourLire);
pthread_mutex_unlock( &mutex1 );
}
int get(){
pthread_mutex_lock( &mutex2 );
while(nbElements == 0){
pthread_cond_wait(&pourLire, &mutex2);
}
int res = buf[indCons];
indCons = (indCons+1) % 12;
nbElements--;
pthread_cond_signal(&pourEcrire);
pthread_mutex_unlock( &mutex2 );
return res;
}
int main(int argc, char* argv[]){
nbElements = 0;
indCons = 0;
indProd = 0;
int thr_id;
pthread_t p_thread[1000];
int nbThread = 0;
pthread_attr_t attr;
int choix;
do{
printf("Faite votre choix :\\n");
printf("\\t1. créer producteur\\n");
printf("\\t2. créer consommateur\\n");
printf("\\t3. visualiser état\\n");
printf("\\tVotre choix : ");
scanf("%d", &choix);
switch(choix){
case 1:
pthread_attr_init(&attr);
thr_id = pthread_create(&(p_thread[nbThread]), &attr, loop_Prod, (void*) &nbThread);
nbThread++;
break;
case 2:
pthread_attr_init(&attr);
thr_id = pthread_create(&(p_thread[nbThread]), &attr, loop_Cons, (void*) &nbThread);
nbThread++;
break;
case 3:
printf("Nb threads : %d\\n", nbThread);
printf("Tampon : ");
pthread_mutex_lock( &mutex1 );
pthread_mutex_lock( &mutex2 );
int i;
for(i = 0; i < nbElements; i++){
printf("buf[%d] = %d\\n", (indCons+i)%12, buf[(indCons+i)%12]);
}
sleep(3);
pthread_mutex_unlock( &mutex1 );
pthread_mutex_unlock( &mutex2 );
break;
default:
printf("Choix incorrect !\\n");
break;
}
}while(1);
}
| 1
|
#include <pthread.h>
pthread_t geigerThread;
int geigerThreadID;
extern int geigerCount;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int count = 0;
int openGPIO(unsigned int gpio){
int fd, value;
char buf[64];
snprintf(buf, sizeof(buf), "echo %i >/sys/class/gpio/export", gpio);
system(buf);
snprintf(buf, sizeof(buf), "echo in > /sys/class/gpio/gpio%i/direction", gpio);
system(buf);
}
int GPIOValue(unsigned int gpio)
{
char buf[64];
snprintf(buf, sizeof(buf), "/sys/class/gpio/gpio%i/value", gpio);
int fd = open(buf, O_RDONLY);
if (fd > 0){
char ch = 0;
read(fd, &ch, 1);
close(fd);
if (ch != '0') {
return 1;
} else {
return 0;
}
}else{
return -1;
}
}
void *geigerHandler(){
while(1){
if(GPIOValue(18) == 1){
pthread_mutex_lock( &mutex );
count++;
pthread_mutex_unlock( &mutex );
}
}
}
int readGeigerCount()
{
pthread_mutex_lock( &mutex );
geigerCount = count;
count = 0;
pthread_mutex_unlock( &mutex );
return 1;
}
int initialiseGeiger()
{
openGPIO(18);
if((geigerThreadID = pthread_create(&geigerThread, 0, &geigerHandler, 0))){
printf("failed\\n");
}
return 1;
}
| 0
|
#include <pthread.h>
struct ozy_ringbuffer* ozy_output_buffer;
pthread_mutex_t ozy_output_buffer_mutex;
int ozy_put_bytes=0;
int ozy_get_bytes=0;
struct ozy_ringbuffer* new_ozy_ringbuffer(int n) {
struct ozy_ringbuffer* buffer;
fprintf(stderr,"new_ozy_ringbuffer: %d\\n",n);
buffer=malloc(sizeof(struct ozy_ringbuffer));
if(buffer!=0) {
buffer->size=n;
buffer->entries=0;
buffer->buffer=malloc(sizeof(char)*n);
buffer->insert_index=0;
buffer->remove_index=0;
}
return buffer;
}
int ozy_ringbuffer_space(struct ozy_ringbuffer* buffer) {
return buffer->size-buffer->entries;
}
int ozy_ringbuffer_entries(struct ozy_ringbuffer* buffer) {
return buffer->entries;
}
int ozy_ringbuffer_put(struct ozy_ringbuffer* buffer,char* f,int n) {
int i;
ozy_put_bytes+=n;
if(debug_buffers) fprintf(stderr,"ozy_ring_buffer_put n=%d\\n",n);
pthread_mutex_lock(&ozy_output_buffer_mutex);
if(ozy_ringbuffer_space(buffer)<=n) {
buffer->remove_index=buffer->insert_index;
buffer->entries=0;
}
if(ozy_ringbuffer_space(buffer)>n) {
memcpy(&buffer->buffer[buffer->insert_index],f,n);
buffer->entries+=n;
buffer->insert_index+=n;
if(buffer->insert_index>=buffer->size) {
buffer->insert_index=0;
}
i=n;
} else {
fprintf(stderr,"ozy_ringbuffer_put: overflow space=%d entries=%d\\n",ozy_ringbuffer_space(buffer),ozy_ringbuffer_entries(buffer));
i=0;
}
pthread_mutex_unlock(&ozy_output_buffer_mutex);
if(debug_buffers) fprintf(stderr,"ozy_ring_buffer_put space=%d entries=%d total=%d\\n",ozy_ringbuffer_space(buffer),ozy_ringbuffer_entries(buffer),ozy_put_bytes);
return i;
}
int ozy_ringbuffer_get(struct ozy_ringbuffer* buffer,char* f,int n) {
int entries;
pthread_mutex_lock(&ozy_output_buffer_mutex);
entries=n;
if(buffer->entries<n) entries=buffer->entries;
ozy_get_bytes+=entries;
if(debug_buffers) fprintf(stderr,"ozy_ring_buffer_get n=%d\\n",n);
if((buffer->remove_index+entries)<=buffer->size) {
memcpy(f,&buffer->buffer[buffer->remove_index],entries);
} else {
memcpy(f,&buffer->buffer[buffer->remove_index],buffer->size-buffer->remove_index);
memcpy(&f[buffer->size-buffer->remove_index],buffer->buffer,entries-(buffer->size-buffer->remove_index));
}
buffer->entries-=entries;
buffer->remove_index+=entries;
if(buffer->remove_index>=buffer->size) {
buffer->remove_index-=buffer->size;
}
pthread_mutex_unlock(&ozy_output_buffer_mutex);
if(debug_buffers) fprintf(stderr,"ozy_ring_buffer_get space=%d entries=%d total=%d\\n",ozy_ringbuffer_space(buffer),ozy_ringbuffer_entries(buffer),ozy_get_bytes);
return entries;
}
int create_ozy_ringbuffer(int n) {
pthread_mutex_init(&ozy_output_buffer_mutex, 0);
ozy_output_buffer=new_ozy_ringbuffer(n);
}
| 1
|
#include <pthread.h>
void *printInfo(void *arg);
void *getDate(void *arg);
void *getStocks(void *arg);
void *updateTime(void *arg);
void *getVolume(void *arg);
char *weekrussian(int num);
char *monthrussian(int num);
char *dayrussian(int num);
char *day;
char *weekday;
char *month;
int h,m,s,y;
} DateTime;
volatile DateTime datetime;
pthread_t th[4];
pthread_mutex_t mutex;
volatile struct tm *current;
volatile char *volume;
int main() {
int err[3];
pthread_mutex_init(&mutex,0);
err[0] = pthread_create(&(th[0]),0,&printInfo,0);
err[1] = pthread_create(&(th[1]),0,&updateTime,0);
err[2] = pthread_create(&(th[2]),0,&getDate,0);
for (int i=0; i<4; i++) {
if (err[i] != 0)
printf("\\ncan't create thread :[%s]", strerror(err[i]));
else
printf("\\n Thread %d created successfully\\n",i);
}
for(int i=0; i<4; i++)
(void) pthread_join(th[i],0);
return 0;
}
void *printInfo(void *arg) {
char output[100];
sleep(1);
while(1){
pthread_mutex_lock(&mutex);
sprintf(output,"echo '%s - %s, %s, %d - %02d:%02d:%02d '",datetime.weekday,datetime.day,datetime.month,datetime.y,datetime.h,datetime.m,datetime.s);
system(output);
pthread_mutex_unlock(&mutex);
usleep(500000);
}
return 0;
}
void *getVolume(void *arg) {
}
void *updateTime(void *arg){
time_t aux;
int h,m,s;
struct tm *tempo;
while(1){
pthread_mutex_lock(&mutex);
time(&aux);
current = localtime(&aux);
datetime.h = current->tm_hour;
datetime.m = current->tm_min;
datetime.s = current->tm_sec;
pthread_mutex_unlock(&mutex);
usleep(250000);
}
return 0;
}
void *getDate(void *arg) {
int day,week,month,year;
char *aux_day, *aux_week, *aux_month;
while(1){
pthread_mutex_lock(&mutex);
day = current->tm_mday;
week = current->tm_wday;
month = current->tm_mon;
year = current->tm_year;
pthread_mutex_unlock(&mutex);
aux_day = dayrussian(day);
aux_week = weekrussian(week);
aux_month = monthrussian(month);
pthread_mutex_lock(&mutex);
datetime.day = aux_day;
datetime.weekday = aux_week;
datetime.month = aux_month;
datetime.y = year+1900;
pthread_mutex_unlock(&mutex);
sleep(60);
}
return 0;
}
char *weekrussian(int num){
switch(num){
case 0:
return "Воскресенье";
case 1:
return "Понедельник";
case 2:
return "Вторник";
case 3:
return "Среда";
case 4:
return "Четверг";
case 5:
return "Пятница";
case 6:
return "Суббота";
}
return "ERROR DAYWEEK";
}
char *monthrussian (int num) {
switch(num){
case 0:
return "января";
case 1:
return "февраля";
case 2:
return "марта";
case 3:
return "апреля";
case 4:
return "мая";
case 5:
return "июня";
case 6:
return "июля";
case 7:
return "августа";
case 8:
return "сентября";
case 9:
return "октября";
case 10:
return "ноября";
case 11:
return "декабря";
}
return "ERROR MONTH";
}
char *dayrussian(int num) {
switch(num) {
case 1:
return "Первое";
case 2:
return "Второе";
case 3:
return "Третье";
case 4:
return "Четвертое";
case 5:
return "Пятое";
case 6:
return "Шестое";
case 7:
return "Седьмое";
case 8:
return "Восьмое";
case 9:
return "Девятое";
case 10:
return "Десятое";
case 11:
return "Одиннадцатое";
case 12:
return "Двенадцатое";
case 13:
return "Тринадцатое";
case 14:
return "Четырнадцатое";
case 15:
return "Пятнадцатое";
case 16:
return "Шестнадцатое";
case 17:
return "Семнадцатое";
case 18:
return "Восемнадцатое";
case 19:
return "Девятнадцатое";
case 20:
return "Двадцатое";
case 21:
return "Двадцать Первое";
case 22:
return "Двадцать Второе";
case 23:
return "Двадцать Третье";
case 24:
return "Двадцать Четвертое";
case 25:
return "Двадцать Пятое";
case 26:
return "Двадцать Шестое";
case 27:
return "Двадцать Седьмое";
case 28:
return "Двадцать Восьмое";
case 29:
return "Двадцать Девятое";
case 30:
return "Тридцатое";
case 31:
return "Тридцать Первое";
}
return "ERROR DAY IN RUSSIAN";
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
int resource = 5;
void *allocator(void *param);
int main(void)
{
int i;
pthread_t tids[10];
pthread_mutex_init(&mutex, 0);
for (i = 0; i < 10; i++)
{
pthread_create(&tids[i], 0, allocator, i+1);
}
for (i = 0; i < 10; i++)
{
pthread_join(tids[i], 0);
}
printf("*** Mutex Test Done ***\\n");
return 0;
}
void *allocator(void *param)
{
sleep((int)random()%10);
allocate_resource();
if (resource == 0)
printf("No resource is available for thread: %d\\n", param);
else
{
pthread_mutex_lock(&mutex);
if (resource < 0)
{
fprintf(stderr,"***resource ALREADY IN USE****\\n");
}
else
fprintf(stderr,"***resource not in use****\\n");
pthread_mutex_unlock(&mutex);
sleep((int)random()%10);
printf("Release the resource now, thread: %d\\n", param);
release_resource();
}
}
void allocate_resource(void)
{
if (pthread_mutex_lock(&mutex) != 0)
fprintf(stderr,"Unable to acquire lock\\n");
else
{
fprintf(stderr,"Acquire the lock\\n");
if (resource != 0)
{
fprintf(stderr,"Resource available. Allocated the resource\\n");
resource--;
}
else
fprintf(stderr,"Resource is in use\\n");
}
if (pthread_mutex_unlock(&mutex) != 0)
fprintf(stderr,"Unable to release mutex\\n");
else
fprintf(stderr,"Release the mutex lock \\n");
}
void release_resource(void)
{
if (pthread_mutex_lock(&mutex) != 0)
fprintf(stderr,"Unable to acquire mutex lock\\n");
else
{
fprintf(stderr,"Acquire the lock...now release the resource\\n");
resource++;
}
if (pthread_mutex_unlock(&mutex) != 0)
fprintf(stderr,"Unable to release mutex lock\\n");
}
| 1
|
#include <pthread.h>
pthread_mutex_t sleep_lock_001_glb_mutex_;
pthread_mutex_t *sleep_lock_001_glb_mutex = &sleep_lock_001_glb_mutex_;
void sleep_lock_001_glb_mutex_lock () {}
void sleep_lock_001_glb_mutex_unlock () {}
int sleep_lock_001_glb_data = 0;
void* sleep_lock_001_tsk_001 (void *pram)
{
pthread_mutex_lock(sleep_lock_001_glb_mutex);
sleep_lock_001_glb_data = (sleep_lock_001_glb_data % 100) + 1;
pthread_mutex_unlock(sleep_lock_001_glb_mutex);
return 0;
}
void sleep_lock_001 ()
{
pthread_t tid1;
pthread_mutex_init(sleep_lock_001_glb_mutex, 0);
pthread_create(&tid1, 0, sleep_lock_001_tsk_001, 0);
pthread_join(tid1, 0);
pthread_mutex_destroy(sleep_lock_001_glb_mutex);
}
int sleep_lock_002_glb_data = 0;
pthread_mutex_t sleep_lock_002_glb_mutex_;
pthread_mutex_t *sleep_lock_002_glb_mutex = &sleep_lock_002_glb_mutex_;
void* sleep_lock_002_tsk_001 (void *pram)
{
pthread_mutex_lock(sleep_lock_002_glb_mutex);
sleep_lock_002_glb_data = (sleep_lock_002_glb_data % 100) + 1;
pthread_mutex_unlock(sleep_lock_002_glb_mutex);
return 0;
}
void sleep_lock_002 ()
{
pthread_t tid1;
pthread_mutex_init(sleep_lock_002_glb_mutex, 0);
pthread_create(&tid1, 0, sleep_lock_002_tsk_001, 0);
pthread_join(tid1, 0);
pthread_mutex_destroy(sleep_lock_002_glb_mutex);
}
pthread_mutex_t sleep_lock_003_glb_mutex_;
pthread_mutex_t *sleep_lock_003_glb_mutex = &sleep_lock_003_glb_mutex_;
int sleep_lock_003_glb_data = 0;
void sleep_lock_003_func_001 ()
{
}
void* sleep_lock_003_tsk_001 (void *pram)
{
pthread_mutex_lock(sleep_lock_003_glb_mutex);
sleep_lock_003_glb_data = (sleep_lock_003_glb_data % 100) + 1;
sleep_lock_003_func_001();
pthread_mutex_unlock(sleep_lock_003_glb_mutex);
return 0;
}
void sleep_lock_003 ()
{
pthread_t tid1;
pthread_mutex_init(sleep_lock_003_glb_mutex, 0);
pthread_create(&tid1, 0, sleep_lock_003_tsk_001, 0);
pthread_join(tid1, 0);
pthread_mutex_destroy(sleep_lock_003_glb_mutex);
}
extern volatile int vflag;
void sleep_lock_main ()
{
if (vflag == 1 || vflag ==888)
{
sleep_lock_001();
}
if (vflag == 2 || vflag ==888)
{
sleep_lock_002();
}
if (vflag == 3 || vflag ==888)
{
sleep_lock_003();
}
}
| 0
|
#include <pthread.h>
void print_motor_status();
void print_MC_faults();
void testMotorForward(long dur);
void testMotorFast(long dur);
void genericThrottleTest(char* name,long dur,int speed, int throttle);
int main(int argc, char *argv[])
{
MC_Setup();
long dur=5000;
testFunc funcArray[(10)];
int funcNum=0;
int i=0;
pthread_mutex_init(&Motor_info_mutex, 0);
pthread_mutex_init(&MC_faults_mutex, 0);
InitDIO(TOTAL_GPIO);
if(argc==0){
testMotorForward(dur);
}
else{
for(i=0;i<argc;i++){
char* locate=strstr(argv[i],("dur"));
if(locate){
char* at=strchr(argv[i],':')+1;
dur=atol(at);
continue;
}
locate=strstr(argv[i],("forwardTest"));
if(locate){
funcArray[funcNum++]=&testMotorForward;
continue;
}
locate=strstr(argv[i],("fastTest"));
if(locate){
funcArray[funcNum++]=&testMotorFast;
continue;
}
}
}
for(i=0;i<funcNum;i++){
funcArray[i](dur);
}
print_MC_faults();
return 0;
}
void testMotorForward(long dur){
genericThrottleTest("MotorForward",dur, 50,5);
}
void testMotorFast(long dur){
genericThrottleTest("MotorFast",dur, 100,10);
}
void genericThrottleTest(char* name,long dur, int speed, int throttle){
long elapsed=0;
struct timeval init, curr;
struct timezone zone;
struct tm* time;
gettimeofday(&init, &zone);
time=localtime(&init.tv_sec);
printf("Starting %s test at %d:%02d:%02d %d \\nSet to last for %ld microsec\\n",name, (int)time->tm_hour, (int)time->tm_min,
(int)time->tm_sec, (int)init.tv_usec, dur);
MC_Setup();
MC_Command(SET_TORQUE_CONTROL);
MC_SetRegister(MC_THROTTLE_REGISTER, throttle);
MC_SetRegister(MC_SPEED_REGISTER, speed);
while(elapsed<dur) {
if (CheckKillswitch()) {
MC_SetRegister(MC_THROTTLE_REGISTER, 0);
MC_SetRegister(MC_SPEED_REGISTER, 0);
printf("Software killswitch pressed. Motor stopped.\\n");
}
gettimeofday(&curr, &zone);
time=localtime(&curr.tv_sec);
elapsed=curr.tv_usec-init.tv_usec;
report_motor_status();
report_fault_status();
}
MC_SetRegister(MC_THROTTLE_REGISTER, 0);
MC_SetRegister(MC_SPEED_REGISTER, 0);
printf("Ending %s test at %d:%02d:%02d %d\\n",name, (int)time->tm_hour, (int)time->tm_min,
(int)time->tm_sec, (int)init.tv_usec);
MC_CloseConnection();
}
void print_motor_status()
{
printf("*********************\\n");
printf("print_motor_status():\\n");
printf("*********************\\n");
pthread_mutex_lock(&Motor_info_mutex);
printf("speed_rpm: %d\\n", Motor_info.speed_rpm);
printf("airgap_pos: %d\\n", Motor_info.airgap_pos);
printf("direction: %d\\n", Motor_info.direction);
printf("target_speed: %d\\n", Motor_info.target_speed);
printf("target_phase_current: %d\\n", Motor_info.target_phase_current);
printf("throttle: %d\\n", Motor_info.throttle);
printf("brake_indicator: %d\\n", Motor_info.brake_indicator);
pthread_mutex_unlock(&Motor_info_mutex);
printf("*********************\\n");
}
void print_MC_faults()
{
printf("********************");
printf("print_MC_faults():\\n");
printf("********************");
pthread_mutex_lock(&MC_faults_mutex);
printf("type 1: %d\\n", MC_faults.fault_1);
printf("type 2: %d\\n", MC_faults.fault_2);
printf("type 3: %d\\n", MC_faults.fault_3);
printf("type 4: %d\\n", MC_faults.fault_4);
pthread_mutex_unlock(&MC_faults_mutex);
printf("*********************\\n");
}
| 1
|
#include <pthread.h>
void generate(int n);
void Read(int n);
void *func1(void *arg);
void *func2(void *arg);
void *func3(void *arg);
void calculate();
void resultToFile();
int A[1000];
int B[20][1000];
int prefix_sum[20][1000]={0};
pthread_t tids[20][1000];
pthread_mutex_t mutex;
int n;
struct S
{
int i ;
int j ;
};
int main()
{
printf("please input the scale of input : ");
scanf("%d",&n);
generate(n);
Read(n);
clock_t start = clock();
calculate();
resultToFile();
clock_t finish = clock();
printf("the time cost is : %.6f seconds\\n",(double)(finish-start)/CLOCKS_PER_SEC);
return 0;
}
void calculate()
{
int h,i,j,k,l,flag;
for(i=1;i<=n;i++)
{
struct S *s;
s = (struct S *)malloc(sizeof(struct S));
s->i = i;
if( pthread_create(&tids[0][i],0,func1,s) )
{
perror("Fail to create thread!");
exit(1);
}
}
for(j=1;j<=n;j++)
pthread_join(tids[0][j],0);
printf("Show the A[i]: ");
for(j=1;j<=n;j++)
printf("%d ",A[j]);
printf("\\nShow the B[0][j]:");
for(j=1;j<=n;j++)
printf("%d ",B[0][j]);
printf("\\n");
for(h=1;h<=log2(n);h++)
{
for(j=1;j<=n/pow(2,h);j++)
{
struct S *s;
s = (struct S*)malloc(sizeof(struct S));
s->i = h;
s->j = j;
if( pthread_create(&tids[h][j],0,func2,s) )
{
perror("sth is wrong");
exit(1);
}
}
for(j=1;j<=n/pow(2,h);j++)
pthread_join(tids[h][j],0);
}
printf("Data Flow Forward:\\n");
for(h=0;h<=log2(n);h++)
{
for(l=1;l<=2*h+1;l++)
printf(" ");
for(j=1;j<=n/pow(2,h);j++)
{
printf("%d",B[h][j]);
for(l=1;l<=1+h;l++)
printf(" ");
}
printf("\\n");
}
for(h=log2(n);h>=0;h--)
{
for(j=1;j<=n/pow(2,h);j++)
{
struct S *s;
s = (struct S*)malloc(sizeof(struct S));
s->i = h;
s->j = j;
if( pthread_create(&tids[h][j],0,func3,s) )
{
perror("sth is wrong");
exit(1);
}
}
for(j=1;j<=n/pow(2,h);j++)
pthread_join(tids[h][j],0);
}
printf("Data Flow Backward:\\n");
for(h=log2(n);h>=0;h--)
{
for(l=1;l<=2*h+1;l++)
printf(" ");
for(j=1;j<=n/pow(2,h);j++)
{
printf("%d ",prefix_sum[h][j]);
for(l=1;l<=h;l++)
printf(" ");
}
printf("\\n");
}
}
void resultToFile()
{
int i;
FILE *file ;
file = fopen("/home/leaguenew/parallel_computing/prefixSumResult.txt","wt");
for(i=1;i<=n;i++)
{
fprintf(file,"%-6d",prefix_sum[0][i]);
}
}
void *func1(void *arg)
{
int i;
struct S *p;
p = (struct S*)arg;
i = p->i;
pthread_mutex_lock(&mutex);
B[0][i]=A[i];
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void *func2(void *args)
{
int h , j;
struct S *p;
p = (struct S*)args;
h = p->i;
j = p->j;
pthread_mutex_lock(&mutex);
B[h][j]=B[h-1][2*j-1]+B[h-1][2*j];
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void *func3(void *arg)
{
int h,j;
struct S *p;
p = (struct S*)arg;
h = p->i;
j = p->j;
pthread_mutex_lock(&mutex);
if(j==1) prefix_sum[h][1] = B[h][1];
else if (j%2==0) prefix_sum[h][j] = prefix_sum[h+1][j/2] ;
else prefix_sum[h][j] = prefix_sum[h+1][(j-1)/2] + B[h][j] ;
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void generate(int n)
{
FILE *file1;
if( (file1=fopen("/home/leaguenew/parallel_computing/arrayA.txt","wt") )==0 )
{
perror("fopen");
exit(1);
}
int i,j;
srand( (unsigned)time(0) );
for( i = 1 ; i <= n ;i++)
fprintf(file1,"%-8d",rand()%99);
fprintf(file1,"\\n");
fclose(file1);
}
void Read(int n)
{
FILE *file1;
if( (file1=fopen("/home/leaguenew/parallel_computing/arrayA.txt","rt") )==0 )
{
perror("fopen");
exit(1);
}
int i,j;
srand( (unsigned)time(0) );
for( i = 1 ; i <= n ;i++)
fscanf(file1,"%d",&A[i]);
fclose(file1);
}
| 0
|
#include <pthread.h>
int piao = 100;
pthread_mutex_t mut;
void* tprocess1(void* args){
int a = 0;
while(1){
pthread_mutex_lock(&mut);
if(piao>0){
sleep(1);
piao--;
printf("xiancheng 1----------------»¹Ê£%dÕÅÆ±\\n",piao);
}else{
a = 1;
}
pthread_mutex_unlock(&mut);
sleep(1);
if(a == 1) {
break;
}
}
return 0;
}
void* tprocess2(void* args){
int a = 0;
while(1){
pthread_mutex_lock(&mut);
if(piao>0){
sleep(1);
piao--;
printf("xiancheng 2----------------»¹Ê£%dÕÅÆ±\\n",piao);
}else{
a = 1;
}
pthread_mutex_unlock(&mut);
sleep(1);
if(a == 1) {
break;
}
}
return 0;
}
void* tprocess3(void* args){
int a = 0;
while(1){
pthread_mutex_lock(&mut);
if(piao>0){
sleep(1);
piao--;
printf("xiancheng 3----------------»¹Ê£%dÕÅÆ±\\n",piao);
}else{
a = 1;
}
pthread_mutex_unlock(&mut);
sleep(1);
if(a == 1) {
break;
}
}
return 0;
}
void* tprocess4(void* args){
int a = 0;
while(1){
pthread_mutex_lock(&mut);
if(piao>0){
sleep(1);
piao--;
printf("xiancheng 4----------------yu%dÕÅÆ±\\n",piao);
}else{
a = 1;
}
pthread_mutex_unlock(&mut);
sleep(1);
if(a == 1) {
break;
}
}
return 0;
}
int main(){
pthread_mutex_init(&mut,0);
pthread_t t1;
pthread_t t2;
pthread_t t3;
pthread_t t4;
pthread_create(&t4,0,tprocess4,0);
pthread_create(&t1,0,tprocess1,0);
pthread_create(&t2,0,tprocess2,0);
pthread_create(&t3,0,tprocess3,0);
printf("tony test-----end0\\n");
sleep(102);
printf("tony test-----end1\\n");
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int comida = 6;
struct filosofo{
char * nombre;
int cantComida;
struct tenedor * ten1;
struct tenedor * ten2;
};
struct tenedor{
int estado;
};
void * comer( void * h1)
{
struct filosofo * fil;
fil = (struct filosofo*) h1;
pthread_mutex_lock( &mutex );
printf("%s %s \\n", fil->nombre, "esta pensando");
while(fil->cantComida > 0){
if(fil->ten1->estado == 0 && fil->ten2->estado == 0){
printf("%s %s \\n", fil->nombre, "tiene hambre");
fil->ten1->estado = fil->ten2->estado = 1;
printf("%s %s \\n", fil->nombre, "agarro los 2 tenedores");
while(fil->cantComida > 0){
fil->cantComida--;
printf("%s %s \\n", fil->nombre, "esta comiendo");
}
}
else{
printf("%s %s \\n", fil->nombre, "no puede comer");
}
}
fil->ten1->estado = fil->ten2->estado = 0;
printf("%s %s \\n", fil->nombre, "termino de comer");
pthread_mutex_unlock( &mutex );
}
int main() {
pthread_t thread1, thread2,thread3,thread4,thread5;
struct tenedor * ten1 = (struct tenedor *) malloc (sizeof(struct tenedor));
struct tenedor * ten2 = (struct tenedor *) malloc (sizeof(struct tenedor));
struct tenedor * ten3 = (struct tenedor *) malloc (sizeof(struct tenedor));
struct tenedor* ten4 = (struct tenedor *) malloc (sizeof(struct tenedor));
struct tenedor * ten5 = (struct tenedor *) malloc (sizeof(struct tenedor));
struct filosofo * fil1 = (struct filosofo *) malloc (sizeof(struct filosofo));
struct filosofo* fil2 = (struct filosofo *) malloc (sizeof(struct filosofo));
struct filosofo * fil3 = (struct filosofo *) malloc (sizeof(struct filosofo));
struct filosofo * fil4 = (struct filosofo *) malloc (sizeof(struct filosofo));
struct filosofo * fil5 = (struct filosofo *) malloc (sizeof(struct filosofo));
ten1->estado = ten2->estado = ten3->estado = ten4->estado = ten5->estado = 0;
fil1->nombre = "Platon";
fil1->cantComida = comida;
fil1->ten1 = ten1;
fil1->ten2 = ten2;
fil2->nombre = "Descartes";
fil2->cantComida = comida;
fil2->ten1 = ten2;
fil2->ten2 = ten3;
fil3->nombre = "Nietsche";
fil3->cantComida = comida;
fil3->ten1 = ten3;
fil3->ten2 = ten4;
fil4->nombre = "Hegel";
fil4->cantComida = comida;
fil4->ten1 = ten4;
fil4->ten2 = ten5;
fil5->nombre = "Aristoteles";
fil5->cantComida = comida;
fil5->ten1 = ten5;
fil5->ten2 = ten1;
int iret1, iret2,iret3,iret4,iret5;
iret1 = pthread_create( &thread1, 0, comer, (void*) fil1);
iret2 = pthread_create( &thread2, 0, comer, (void*) fil2);
iret3 = pthread_create( &thread3, 0, comer, (void*) fil3);
iret4 = pthread_create( &thread4, 0, comer, (void*) fil4);
iret5 = pthread_create( &thread5, 0, comer, (void*) fil5);
pthread_join( thread1, 0);
pthread_join( thread2, 0);
pthread_join( thread3, 0);
pthread_join( thread4, 0);
pthread_join( thread5, 0);
printf("Thread 1 returns: %d\\n",iret1);
printf("Thread 2 returns: %d\\n",iret2);
printf("Thread 3 returns: %d\\n",iret3);
printf("Thread 4 returns: %d\\n",iret4);
printf("Thread 5 returns: %d\\n",iret5);
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(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
}
return(fp);
}
void
foo_hold(struct foo *fp)
{
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
struct foo *
foo_find(int id)
{
struct foo *fp;
pthread_mutex_lock(&hashlock);
for (fp = fh[(((unsigned long)id)%29)]; fp != 0; fp = fp->f_next) {
if (fp->f_id == id) {
foo_hold(fp);
break;
}
}
pthread_mutex_unlock(&hashlock);
return(fp);
}
void
foo_rele(struct foo *fp)
{
struct foo *tfp;
int idx;
pthread_mutex_lock(&fp->f_lock);
if (fp->f_count == 1) {
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_lock(&hashlock);
pthread_mutex_lock(&fp->f_lock);
if (fp->f_count != 1) {
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
return;
}
idx = (((unsigned long)fp->f_id)%29);
tfp = fh[idx];
if (tfp == fp) {
fh[idx] = fp->f_next;
} else {
while (tfp->f_next != fp)
tfp = tfp->f_next;
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
} else {
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
}
}
void print_foo( struct foo* strf)
{
printf("\\n");
printf("f_cont = %d \\n", strf->f_count);
printf("f_lock = %d \\n", strf->f_lock);
printf("f_id = %d \\n", strf->f_id);
printf("f_cont = %d \\n", strf->f_count);
}
int main()
{
struct foo * strf = foo_alloc(1);
print_foo(strf);
foo_hold(strf);
print_foo(strf);
foo_hold(strf);
print_foo(strf);
foo_rele(strf);
print_foo(strf);
foo_rele(strf);
print_foo(strf);
foo_rele(strf);
print_foo(strf);
sleep(1);
int a = 1;
foo_rele(strf);
print_foo(strf);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
int counter=0;
void thread1(void *arg);
void thread2(void *arg);
int main(int argc, char *argv[])
{
pthread_t id1,id2;
if(pthread_mutex_init(&mutex, 0) != 0) {
perror("Mutex initialization");
exit(1);
}
if(pthread_create(&id1,0,(void *)thread1, 0) != 0) {
perror("Thread create");
exit(1);
}
if(pthread_create(&id2,0,(void *)thread2, 0) != 0) {
perror("Thread create");
exit(1);
}
if(pthread_join(id1,0) != 0) {
perror("Thread join");
exit(1);
}
if(pthread_join(id2,0) != 0) {
perror("Thread join");
exit(1);
}
pthread_mutex_destroy(&mutex);
printf("最后的 counter 值为%d\\n",counter);
exit(0);
}
void thread1(void *arg)
{
int i,val;
for(i=1;i<=5;i++){
pthread_mutex_lock(&mutex);
val = ++counter;
printf("第 1 个线程:第%d 次循环,第 1 次引用 counter=%d\\n",i,counter);
sleep(1);
printf("第 1 个线程:第%d 次循环,第 2 次引用 counter=%d\\n",i,counter);
counter = val;
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void thread2(void *arg)
{
int i,val;
for(i=1;i<=5;i++){
pthread_mutex_lock(&mutex);
val = ++counter;
sleep(2);
printf("第 2 个线程:第%d 次循环,counter=%d\\n",i,counter);
counter = val;
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t resource[100];
pthread_t task0, task1, task2;
int selfid[1000];
int lselfid = 0;
int self2id(int self){
int i = 0;
for (i = 0; i < lselfid; ++i)
{
if(self == selfid[i])return i;
}
selfid[i] = self;
lselfid ++;
return i;
}
int lock2id(int lock){
return self2id(lock);
}
int map[1000];
int visited[1000];
void add_edge(int s, int t){
map[s+1] = t+1;
}
void remove_edge(int s, int t){
if(map[s+1] == t+1)
map[s+1] = 0;
}
int is_there_a_loop(int s){
memset(visited, 0, sizeof(visited));
int cur = map[s+1];
visited[cur] = 1;
while(map[cur] != 0){
cur = map[cur];
if(visited[cur]){
return 1;
}
visited[cur] = 1;
}
return 0;
}
void print_a_loop(int s){
printf("Loop: ");
memset(visited, 0, sizeof(visited));
int cur = map[s+1];
visited[cur] = 1;
printf("%d", cur-1);
while(map[cur] != 0){
cur = map[cur];
printf(" to %d", cur-1);
if(visited[cur]){
printf("\\n");
return;
}
visited[cur] = 1;
}
}
void pthread_mutex_lock_extended(pthread_mutex_t *lock){
int thread_id = self2id(pthread_self());
int lock_id = lock2id((unsigned int)lock);
add_edge(thread_id, lock_id);
if(is_there_a_loop(thread_id))
{
printf("There is deadlock!\\n");
print_a_loop(thread_id);
exit(1);
}else{
pthread_yield();
usleep(rand()%100000);
pthread_mutex_lock(lock);
usleep(rand()%100000);
}
remove_edge(thread_id, lock_id);
add_edge(lock_id, thread_id);
}
void pthread_mutex_unlock_extended(pthread_mutex_t *lock){
int thread_id = self2id(pthread_self());
int lock_id = lock2id((unsigned int)lock);
remove_edge(lock_id, thread_id);
pthread_mutex_unlock(lock);
}
void* fun0(void* arg){
pthread_mutex_lock_extended(&resource[0]);
pthread_mutex_lock_extended(&resource[1]);
pthread_mutex_unlock_extended(&resource[0]);
pthread_mutex_unlock_extended(&resource[1]);
pthread_exit(0);
}
void* fun1(void* arg){
pthread_mutex_lock_extended(&resource[1]);
pthread_mutex_lock_extended(&resource[0]);
pthread_mutex_unlock_extended(&resource[1]);
pthread_mutex_unlock_extended(&resource[0]);
pthread_exit(0);
}
void* fun2(void* arg){
pthread_mutex_lock_extended(&resource[2]);
pthread_mutex_lock_extended(&resource[1]);
pthread_mutex_unlock_extended(&resource[2]);
pthread_mutex_unlock_extended(&resource[1]);
pthread_exit(0);
}
int main(){
int i;
srand(time(0));
for (i = 0; i < 100; ++i)
{
pthread_mutex_init(&resource[i], 0);
}
pthread_create(&task0, 0, fun0, 0);
pthread_create(&task1, 0, fun1, 0);
pthread_create(&task2, 0, fun2, 0);
pthread_join(task0, 0);
pthread_join(task1, 0);
pthread_join(task2, 0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond;
char buf[1024] = { 0 };
void *write_thread(void *arg)
{
while (1) {
pthread_mutex_lock(&mutex);
printf(">");
fgets(buf, sizeof(buf), stdin);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
if (strncmp(buf, "quit", 4) == 0)
pthread_exit(0);
usleep(100);
}
}
void *read_thread(void *arg)
{
while (1) {
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
fputs(buf, stdout);
pthread_mutex_unlock(&mutex);
if (strncmp(buf, "quit", 4) == 0)
pthread_exit(0);
usleep(100);
}
}
int main(int argc, const char *argv[])
{
pthread_t tid[2];
int ret = 0;
pthread_cond_init(&cond, 0);
if ((ret = pthread_create(&tid[0], 0, read_thread, 0)) != 0) {
do { errno = ret; perror("msg"); exit(1); } while (0);
}
if ((ret = pthread_create(&tid[1], 0, write_thread, 0)) != 0) {
do { errno = ret; perror("msg"); exit(1); } while (0);
}
pthread_join(tid[0], 0);
pthread_join(tid[1], 0);
return 0;
}
| 0
|
#include <pthread.h>
void miframman_init(struct miframman *ram, void *start_dram, size_t size_pool)
{
pthread_mutex_init(&ram->lock, 0);
ram->num_blocks = size_pool / MIFRAMMAN_BLOCK_SIZE;
if (ram->num_blocks == 0) {
SLSI_ERR_NODEV("Pool size < BLOCK_SIZE\\n");
return;
}
if (ram->num_blocks > MIFRAMMAN_NUM_BLOCKS) {
SLSI_ERR_NODEV("Not enough memory\\n");
return;
}
memset(ram->bitmap, BLOCK_FREE, sizeof(ram->bitmap));
ram->start_dram = start_dram;
ram->size_pool = size_pool;
ram->free_mem = ram->num_blocks * MIFRAMMAN_BLOCK_SIZE;
}
void *__miframman_alloc(struct miframman *ram, size_t nbytes)
{
unsigned int index = 0;
unsigned int available;
unsigned int i;
size_t num_blocks;
void *free_mem = 0;
if (!nbytes || nbytes > ram->free_mem) {
goto end;
}
num_blocks = nbytes / MIFRAMMAN_BLOCK_SIZE + ((nbytes % MIFRAMMAN_BLOCK_SIZE) > 0 ? 1 : 0);
if (num_blocks > ram->num_blocks) {
goto end;
}
pthread_mutex_lock(&ram->lock);
while (index <= (ram->num_blocks - num_blocks)) {
available = 0;
for (i = 0; i < num_blocks; i++) {
if (ram->bitmap[i + index] != BLOCK_FREE) {
break;
}
available++;
}
if (available == num_blocks) {
free_mem = ram->start_dram + MIFRAMMAN_BLOCK_SIZE * index;
ram->bitmap[index++] = BLOCK_BOUND;
for (i = 1; i < num_blocks; i++) {
ram->bitmap[index++] = BLOCK_INUSE;
}
ram->free_mem -= num_blocks * MIFRAMMAN_BLOCK_SIZE;
pthread_mutex_unlock(&ram->lock);
goto exit;
} else {
index = index + available + 1;
}
}
pthread_mutex_unlock(&ram->lock);
end:
SLSI_ERR_NODEV("Not enough memory\\n");
return 0;
exit:
return free_mem;
}
bool is_power_of_2(unsigned long n)
{
return (n != 0 && ((n & (n - 1)) == 0));
}
void *miframman_alloc(struct miframman *ram, size_t nbytes, size_t align)
{
void *mem, *align_mem;
if (!is_power_of_2(align) || nbytes == 0) {
return 0;
}
if (align < sizeof(void *)) {
align = sizeof(void *);
}
mem = __miframman_alloc(ram, nbytes + align + sizeof(void *));
if (!mem) {
return 0;
}
align_mem = ((void *)((((uintptr_t)(mem) + (align + sizeof(void *))) & (~(uintptr_t)(align - 1)))));
(*(((void **)((uintptr_t)(align_mem) & (~(uintptr_t)(sizeof(void *)-1)))) - 1)) = mem;
return align_mem;
}
void __miframman_free(struct miframman *ram, void *mem)
{
unsigned int index, num_blocks = 0;
pthread_mutex_lock(&ram->lock);
if (ram->start_dram == 0 || !mem) {
SLSI_ERR_NODEV("Mem is NULL\\n");
pthread_mutex_unlock(&ram->lock);
return;
}
index = (unsigned int)((mem - ram->start_dram)
/ MIFRAMMAN_BLOCK_SIZE);
if (index >= ram->num_blocks) {
pr_err("%s: Incorrect index %d\\n", __func__, index);
goto end;
}
if (ram->bitmap[index] != BLOCK_BOUND) {
pr_err("%s: Incorrect Block descriptor\\n", __func__);
goto end;
}
ram->bitmap[index++] = BLOCK_FREE;
num_blocks++;
while (index < ram->num_blocks && ram->bitmap[index] == BLOCK_INUSE) {
ram->bitmap[index++] = BLOCK_FREE;
num_blocks++;
}
ram->free_mem += num_blocks * MIFRAMMAN_BLOCK_SIZE;
end:
pthread_mutex_unlock(&ram->lock);
}
void miframman_free(struct miframman *ram, void *mem)
{
if (mem) {
__miframman_free(ram, (*(((void **)((uintptr_t)(mem) & (~(uintptr_t)(sizeof(void *)-1)))) - 1)));
}
}
void miframman_deinit(struct miframman *ram)
{
memset(ram->bitmap, BLOCK_INUSE, sizeof(ram->bitmap));
ram->num_blocks = 0;
ram->start_dram = 0;
ram->size_pool = 0;
ram->free_mem = 0;
}
| 1
|
#include <pthread.h>
void *thread_func1(void *ptr);
void *thread_func2(void *ptr);
void *log_thread(void *ptr);
char buf[256]={0};
pthread_mutex_t buf_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t buf_empty = PTHREAD_COND_INITIALIZER;
int main() {
pthread_t t1, t2, t_log;
int ret;
ret = pthread_create(&t1, 0, &thread_func1, 0);
if (ret != 0) {
printf("create thread1 failed\\n");
return ret;
}
ret = pthread_create(&t2, 0, &thread_func2, 0);
if (ret != 0) {
printf("create thread2 failed\\n");
return ret;
}
ret = pthread_create(&t_log, 0, &log_thread, 0);
if (ret != 0) {
printf("create log thread failed\\n");
return ret;
}
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_join(t_log, 0);
exit(0);
}
void *log_thread(void *ptr){
int write_times=5*2;
while(1){
pthread_mutex_lock(&buf_mutex);
if(strcmp(buf,"\\0")){
printf("%s\\n",buf);
write_log_file("log", buf);
memset(&buf,0,sizeof(buf));
}
pthread_cond_signal(&buf_empty);
pthread_mutex_unlock(&buf_mutex);
usleep(1000);
}
}
void *thread_func1(void *ptr) {
int i;
for (i = 0; i < 5; i++) {
pthread_mutex_lock(&buf_mutex);
while(strcmp(buf,"\\0")!=0)
pthread_cond_wait(&buf_empty, &buf_mutex);
sprintf(buf, "thread1 write into logfile.\\n");
printf("thread1 write into buf.\\n");
pthread_mutex_unlock(&buf_mutex);
}
}
void *thread_func2(void *ptr) {
int i;
for (i = 0; i < 5; i++) {
pthread_mutex_lock(&buf_mutex);
while(strcmp(buf,"\\0")!=0)
pthread_cond_wait(&buf_empty, &buf_mutex);
sprintf(buf, "thread %lx write into logfile.\\n", pthread_self());
printf("thread2 write into buf.\\n");
pthread_mutex_unlock(&buf_mutex);
}
}
| 0
|
#include <pthread.h>
void * enano (void * arg);
void mina (int noEnano);
void cerrarCocina (int ids);
void comer (int noEnano);
void salirACaminar ();
void * blancanieves (void * arg);
pthread_t * enanos;
pthread_mutex_t mutexSillas = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutexEnanos = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t sillaLibre = PTHREAD_COND_INITIALIZER;
pthread_cond_t comidaLista = PTHREAD_COND_INITIALIZER;
int comiendo = 1;
int sillasOcupadas = 0;
int enanosEsperando = 0;
int main(int argc, char const *argv[])
{
signal(SIGINT,cerrarCocina);
enanos = (pthread_t *)malloc(7 * sizeof(pthread_t));
pthread_t * auxEnano = enanos;
for(; auxEnano< (enanos + 7); ++auxEnano){
sleep(1);
pthread_create(auxEnano,0, enano, (void *) ((enanos + 7)-auxEnano));
}
pthread_t hiloBlancanieves;
pthread_create(&hiloBlancanieves, 0, blancanieves, 0);
pthread_exit(0);
return 0;
}
void * enano (void * arg){
int noEnano = (int) arg;
int listo = 0;
int platos = 0;
while (platos <= 3){
mina(noEnano);
pthread_mutex_lock(&mutexSillas);
if (sillasOcupadas >= 4){
while (!listo){
printf("Todas las sillas están ocupadas, enano %d dormirá\\n", noEnano);
pthread_cond_wait(&sillaLibre, &mutexSillas);
listo = sillasOcupadas < 4;
}
}
sillasOcupadas++;
pthread_mutex_unlock(&mutexSillas);
printf("Enanito %d esperando a comer\\n", noEnano);
pthread_mutex_lock(&mutexEnanos);
enanosEsperando++;
pthread_cond_wait(&comidaLista, &mutexEnanos);
pthread_mutex_unlock(&mutexEnanos);
comer(noEnano);
printf("Soy el enano %d y voy a desocupar mi silla \\n",noEnano);
pthread_mutex_lock(&mutexSillas);
sillasOcupadas--;
pthread_mutex_unlock(&mutexSillas);
pthread_cond_broadcast(&sillaLibre);
platos++;
}
printf("Soy el enano %d y ya comí %d platos\\n", noEnano, 3);
pthread_exit(0);
}
void * blancanieves (void * arg){
while (comiendo){
pthread_mutex_lock(&mutexEnanos);
if (enanosEsperando > 0){
printf("Soy Blancanieves y la comida esta lista.\\n");
enanosEsperando--;
pthread_cond_signal(&comidaLista);
pthread_mutex_unlock(&mutexEnanos);
}else {
pthread_mutex_unlock(&mutexEnanos);
salirACaminar();
}
}
}
void mina (int noEnano) {
printf("Soy el enano %d y estoy en la mina\\n",noEnano);
sleep(2);
}
void comer (int noEnano){
printf("Soy el enano %d y estoy comiendo\\n",noEnano);
sleep(2);
}
void cerrarCocina (int ids){
printf("Cerrando cocina...\\n");
comiendo = 0;
}
void salirACaminar () {
printf("No tengo enanos que alimentar entonces salí a pasear\\n");
sleep(3);
}
| 1
|
#include <pthread.h>
int last_threadID = 1;
int threadRunCounts[5] = {0};
pthread_mutex_t myTurnMutex;
pthread_cond_t myTurnSignal;
int checkArray(int arrayToCheck[]) {
for (int i = 0; i < 5; i++){
int x = threadRunCounts[i];
printf("Thread number %d has been run %d times\\n", i, x);
if(threadRunCounts[i] >= 10)
return 0;
}
return 1;
}
void *threadHello(void *t) {
long my_id = (long)t;
pthread_mutex_lock(&myTurnMutex);
while(checkArray(threadRunCounts)) {
threadRunCounts[my_id - 1] += 1;
if((long)last_threadID != my_id) {
printf("Not my turn: %ld\\n", my_id);
pthread_cond_signal(&myTurnSignal);
pthread_cond_wait(&myTurnSignal, &myTurnMutex);
continue;
}
else {
printf("My turn: %ld\\n", my_id);
if(last_threadID == 5)
last_threadID = 1;
else
last_threadID++;
pthread_cond_signal(&myTurnSignal);
pthread_cond_wait(&myTurnSignal, &myTurnMutex);
}
}
pthread_mutex_unlock(&myTurnMutex);
pthread_cond_signal(&myTurnSignal);
pthread_exit(0);
}
int main(int argc, char* argv[]) {
pthread_t threads[5];
int rc;
long t;
pthread_attr_t attr;
pthread_mutex_init(&myTurnMutex, 0);
pthread_cond_init (&myTurnSignal, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(t = 1; t <= 5; t++) {
printf("In main: creating thread %ld\\n", t);
rc = pthread_create(&threads[t], &attr, threadHello, (void *)t);
}
for (int i=0; i<5; i++) {
pthread_join(threads[i], 0);
}
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&myTurnMutex);
pthread_cond_destroy(&myTurnSignal);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
{
int value;
struct cell *next;
}
*cell;
{
int length;
cell first;
cell last;
}
*list;
list add (int v, list l)
{
cell c = (cell) malloc (sizeof (struct cell));
c->value = v;
c->next = 0;
if (l == 0){
l = (list) malloc (sizeof (struct list));
l->length = 0;
l->first = c;
}else{
l->last->next = c;
}
l->length++;
l->last = c;
return l;
}
void put (int v,list *l)
{
(*l) = add (v,*l);
}
int get (list *l)
{
int res;
list file = *l;
if (l == 0) {
fprintf (stderr, "get error!\\n");
return 0;
}
res = file->first->value;
file->length--;
if (file->last == file->first){
file = 0;
}else{
file->first = file->first->next;
}
return res;
}
int size (list l)
{
if (l==0) return 0;
return l->length;
}
list in = 0, out = 0;
pthread_mutex_t producer_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t consumer_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t new_input = PTHREAD_COND_INITIALIZER;
pthread_cond_t new_output = PTHREAD_COND_INITIALIZER;
void process_value (int v)
{
int i,j;
for (i=0;i<PROCESSING;i++) j++;
pthread_mutex_lock(&consumer_mutex);
put(-v,&out);
pthread_cond_signal (&new_output);
pthread_mutex_unlock(&consumer_mutex);
}
void* process (void *args)
{
pthread_mutex_lock(&producer_mutex);
while (1) {
if (size(in) > 0){
int v = get(&in);
pthread_mutex_unlock(&producer_mutex);
process_value(v);
pthread_mutex_lock(&producer_mutex);
}else{
pthread_cond_wait (&new_input,&producer_mutex);
}
}
return 0;
}
void* produce (void *args)
{
int v = 0;
while (v < PRODUCED) {
pthread_mutex_lock(&producer_mutex);
if (size(in) < FILE_SIZE){
put (v,&in);
PRINT("%d produced\\n",v);
pthread_cond_signal (&new_input);
v++;
pthread_mutex_unlock (&producer_mutex);
}else{
pthread_mutex_unlock(&producer_mutex);
sched_yield();
}
}
return 0;
}
void* consume (void *args)
{
int v = 0;
while (v < PRODUCED) {
pthread_mutex_lock(&consumer_mutex);
if (size(out) > 0){
int res = get (&out);
PRINT("consume %d\\n",res);
v++;
}else{
pthread_cond_wait (&new_output,&consumer_mutex);
}
pthread_mutex_unlock(&consumer_mutex);
}
exit (0);
return 0;
}
int main(void)
{
int i;
pthread_t producer,consumer;
pthread_t thread_array[MAX_THREADS];
for (i=0; i<MAX_THREADS; i++){
pthread_create (&thread_array[i],0,process,0);
}
pthread_create (&producer,0,produce,0);
pthread_create (&consumer,0,consume,0);
pthread_exit (0);
return 0;
}
| 1
|
#include <pthread.h>
int nitems;
struct {
pthread_mutex_t mutex;
int buff[10000000];
int nput;
int nval;
} shared={
PTHREAD_MUTEX_INITIALIZER
};
struct{
pthread_mutex_t mutex;
pthread_cond_t cond;
int nready;
}ready={PTHREAD_MUTEX_INITIALIZER,
PTHREAD_COND_INITIALIZER
};
void consume_wait(int i){
for(;;){
pthread_mutex_lock(&shared.mutex);
if(i<shared.nput){
pthread_mutex_unlock(&shared.mutex);
return;
}
pthread_mutex_unlock(&shared.mutex);
}
}
void* produce(void*),*consume(void*);
int min(int a,int b){
return (a>=b)?b:a;
}
int main(int argc,char* argv[]){
int i,nthreads,count[100];
pthread_t tid_produce[100],tid_consume;
nitems=min(atoi(argv[1]),10000000);
nthreads=min(atoi(argv[2]),100);
clock_t st,ed;
double gap;
st=clock();
for(i=0;i<nthreads;i++){
count[i]=0;
pthread_create(&tid_produce[i],0,produce,&count[i]);
}
pthread_create(&tid_consume,0,consume,0);
for(i=0;i<nthreads;i++){
pthread_join(tid_produce[i],0);
printf("count[%d]=%d\\n",i,count[i]);
}
pthread_join(tid_consume,0);
ed=clock();
gap=(double)(ed-st);
printf("gap time %f\\n",gap/CLOCKS_PER_SEC);
return 0;
}
void* produce(void* arg){
int dosignal;
for(;;){
pthread_mutex_lock(&shared.mutex);
if(shared.nput>=nitems){
pthread_mutex_unlock(&shared.mutex);
break;
}
shared.buff[shared.nput]=shared.nval;
shared.nval++;
shared.nput++;
pthread_mutex_unlock(&shared.mutex);
pthread_mutex_lock(&ready.mutex);
dosignal=(ready.nready==0);
ready.nready++;
pthread_mutex_unlock(&ready.mutex);
if(dosignal)
pthread_cond_signal(&ready.cond);
*((int*)arg)+=1;
}
}
void* consume(void* arg){
int i;
for(i=0;i<nitems;i++){
pthread_mutex_lock(&ready.mutex);
while(ready.nready==0)
pthread_cond_wait(&ready.cond,&ready.mutex);
ready.nready--;
pthread_mutex_unlock(&ready.mutex);
if(shared.buff[i]!=i)
printf("buff[%d]=%d\\n",i,shared.buff[i]);
}
}
| 0
|
#include <pthread.h> TOUCH_START = 0,
TOUCH_DRAG = 1,
TOUCH_RELEASE = 2,
TOUCH_HOLD = 3,
TOUCH_REPEAT = 4
} TOUCH_STATE;
int draw_dot(int x, int y)
{
if(x < 0 || y < 0){
return -1;
}
pthread_mutex_lock(&gUpdateMutex);
gr_color(0, 0, 255, 255);
gr_fill(x, y, 2, 2);
pthread_mutex_unlock(&gUpdateMutex);
return 0;
}
int draw_line(int x1, int y1, int x2, int y2)
{
int x, y;
if(x1 == x2){
x = x1;
for(y = ((y1) < (y2) ? (y1) : (y2)); y <= ((y1) > (y2) ? (y1) : (y2)); y++)
draw_dot(x, y);
}else if(y1 == y2){
y = y1;
for(x = ((x1) < (x2) ? (x1) : (x2)); x <= ((x1) > (x2) ? (x1) : (x2)); x++)
draw_dot(x, y);
}else if(((x1-x2) >= 0 ? (x1-x2) : (-(x1-x2))) > ((y1-y2) >= 0 ? (y1-y2) : (-(y1-y2)))){
for(x = ((x1) < (x2) ? (x1) : (x2)); x <= ((x1) > (x2) ? (x1) : (x2)); x++){
y = ((y2 - y1) * (x - x1)) / (x2 - x1) + y1;
draw_dot(x, y);
}
}else{
for(y = ((y1) < (y2) ? (y1) : (y2)); y <= ((y1) > (y2) ? (y1) : (y2)); y++){
x = ((x2 - x1) * (y - y1)) / (y2 - y1) + x1;
draw_dot(x, y);
}
}
return 0;
}
int last_x = 0, last_y = 0;
int NotifyTouch(int action, int x, int y)
{
switch(action){
case TOUCH_START:
draw_dot(x, y);
last_x = x;
last_y = y;
break;
case TOUCH_DRAG:
draw_line(last_x, last_y, x, y);
last_x = x;
last_y = y;
pthread_mutex_lock(&gUpdateMutex);
gr_flip();
pthread_mutex_unlock(&gUpdateMutex);
break;
case TOUCH_RELEASE:
pthread_mutex_lock(&gUpdateMutex);
gr_flip();
pthread_mutex_unlock(&gUpdateMutex);
break;
case TOUCH_HOLD:
break;
case TOUCH_REPEAT:
break;
default:
break;
}
return 0;
}
| 1
|
#include <pthread.h>
volatile int n;
pthread_mutex_t me;
sem_t s;
} barrier_t;
barrier_t b, b2;
int n, k;
int numer, denom;
volatile double result = 1;
void* numerator(void *);
void* denominator(void *);
int main(int argc, char **argv) {
pthread_t numer_tid, denom_tid;
if(argc != 3) {
fprintf(stderr, "Usage: %s n k\\n", argv[0]);
return 1;
}
if(!sscanf(argv[1], "%d", &n) || !sscanf(argv[2], "%d", &k) || n < 0 || k < 0) {
fprintf(stderr, "Parameters n and k must be positive integers\\n");
return 1;
}
b.n = 0;
pthread_mutex_init(&b.me, 0);
sem_init(&b.s, 0, 0);
b2.n = 0;
pthread_mutex_init(&b2.me, 0);
sem_init(&b2.s, 0, 0);
if(pthread_create(&numer_tid, 0, numerator, 0) == -1) {
perror("Impossible to create numerator thread");
return 1;
}
if(pthread_create(&denom_tid, 0, denominator, 0) == -1) {
perror("Impossible to create denominator thread");
return 1;
}
pthread_join(numer_tid, 0);
pthread_join(denom_tid, 0);
printf("Result = %d\\n", (int)result);
return 0;
}
void* numerator(void *p) {
int i;
int is_last;
for(i = n; i >= n - k + 1; i -= 2) {
if(i > n - k + 1) {
numer = i * (i - 1);
} else {
numer = i;
}
pthread_mutex_lock(&b.me);
is_last = b.n;
b.n = (b.n + 1) % 2;
if(is_last) {
result *= ((double)numer) / denom;
sem_post(&b.s);
sem_post(&b.s);
}
pthread_mutex_unlock(&b.me);
sem_wait(&b.s);
pthread_mutex_lock(&b2.me);
is_last = b2.n;
b2.n = (b2.n + 1) % 2;
if(is_last) {
sem_post(&b2.s);
sem_post(&b2.s);
}
pthread_mutex_unlock(&b2.me);
sem_wait(&b2.s);
}
return 0;
}
void* denominator(void *p) {
int i;
int is_last;
for(i = 1; i <= k; i += 2) {
if(i < k) {
denom = i * (i + 1);
} else {
denom = i;
}
pthread_mutex_lock(&b.me);
is_last = b.n;
b.n = (b.n + 1) % 2;
if(is_last) {
result *= ((double)numer) / denom;
sem_post(&b.s);
sem_post(&b.s);
}
pthread_mutex_unlock(&b.me);
sem_wait(&b.s);
pthread_mutex_lock(&b2.me);
is_last = b2.n;
b2.n = (b2.n + 1) % 2;
if(is_last) {
sem_post(&b2.s);
sem_post(&b2.s);
}
pthread_mutex_unlock(&b2.me);
sem_wait(&b2.s);
}
return 0;
}
| 0
|
#include <pthread.h>
extern struct connection svr_conn[];
void net_add_close_func(
int sd,
void (*func)(int))
{
pthread_mutex_lock(svr_conn[sd].cn_mutex);
if (svr_conn[sd].cn_active != Idle)
svr_conn[sd].cn_oncl = func;
pthread_mutex_unlock(svr_conn[sd].cn_mutex);
}
| 1
|
#include <pthread.h>
struct entry {
struct entry *next;
const char *word;
pthread_mutex_t mtx;
int count;
};
struct bucket {
pthread_mutex_t mtx;
struct entry *entries;
} H[10007];
unsigned hash(const char *s)
{
unsigned h = 10007 ^ ((unsigned)*s++ << 2);
unsigned len = 0;
while (*s) {
len++;
h ^= (((unsigned)*s) << (len % 3)) +
((unsigned)*(s - 1) << ((len % 3 + 7)));
s++;
}
h ^= len;
return h % 10007;
}
void count(const char *word)
{
unsigned h = hash(word);
pthread_mutex_lock(&H[h].mtx);
struct entry *ep = H[h].entries;
for (; ep != 0; ep = ep->next)
if (strcmp(word, ep->word) == 0) {
pthread_mutex_unlock(&H[h].mtx);
pthread_mutex_lock(&ep->mtx);
ep->count++;
pthread_mutex_unlock(&ep->mtx);
return;
}
if ((ep = calloc(1, sizeof(*ep))) == 0)
err(1, "calloc");
if ((ep->word = strdup(word)) == 0)
err(1, "strdup");
ep->count = 1;
ep->next = H[h].entries;
H[h].entries = ep;
pthread_mutex_unlock(&H[h].mtx);
}
void *count_all_words(void *arg)
{
const char *fname = (const char *)arg;
FILE *fp;
int c;
char word[8192];
char *ptr;
if ((fp = fopen(fname, "r")) == 0)
err(1, "fopen: %s", fname);
ptr = 0;
while ((c = getc(fp)) != EOF)
if (isalpha(c)) {
if (ptr == 0) {
ptr = word;
*ptr++ = c;
} else if (ptr < &word[8192 - 1])
*ptr++ = c;
else {
*ptr++ = '\\0';
count(word);
ptr = 0;
}
} else if (ptr != 0) {
*ptr++ = '\\0';
count(word);
ptr = 0;
}
if (ptr != 0) {
*ptr++ = '\\0';
count(word);
}
fclose(fp);
return 0;
}
void print_counts()
{
struct entry *ep;
for (int i = 0; i < 10007; i++)
for (ep = H[i].entries; ep != 0; ep = ep->next)
printf("%d %s\\n", ep->count, ep->word);
}
int main(int argc, char *argv[])
{
int pflag = 0;
int arg = 1;
if (argc > 1 && strcmp(argv[1], "-p") == 0) {
pflag++;
arg++;
}
if (argv[arg] == 0) {
fprintf(stderr, "usage: %s [-p] wordfiles...\\n", argv[0]);
exit(1);
}
int nfiles = argc - arg;
pthread_t tids[nfiles];
for (int i = 0; i < nfiles; i++)
if ((errno = pthread_create(&tids[i], 0,
count_all_words, (void *)argv[arg++])) != 0)
err(1, "pthread_create %d of %d", i, nfiles);
for (int i = 0; i < nfiles; i++)
pthread_join(tids[i], 0);
if (pflag)
print_counts();
exit(0);
}
| 0
|
#include <pthread.h>
int occurrences = 0;
{
char *character;
char *file;
} s_request;
void *scanFile( s_request *request );
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void main ( int argumentCount, char *argumentVariables[] )
{
if (argumentCount > 50)
{
perror("Too many arguments. Enter less than 50.\\n");
exit(1);
}
int i;
char *searchCharacter;
searchCharacter = argumentVariables[1];
if (searchCharacter == 0)
{
perror(" Incorrect usage. \\n\\n Correct execution: ./mycount <char> <filename>...<filename_n>\\n");
exit(1);
}
int len = strlen(searchCharacter);
if (len > 1)
{
perror(" Incorrect usage. \\n\\n Correct execution: ./mycount <char> <filename>...<filename_n>\\n");
exit(1);
}
int threads = argumentCount - 2;
pthread_t thread[threads];
int newThread = 0;
s_request request[threads];
for (int i = 0; i < threads; i++)
{
request[i].file = argumentVariables[i + 2];
request[i].character = searchCharacter;
if (newThread = pthread_create(&thread[i], 0, *scanFile, &request[i]) != 0)
{
printf("Error - pthread_create() return code: %d\\n", newThread);
exit(1);
}
}
for (int j = 0; j < threads; j++)
{
pthread_join(thread[j], 0);
}
printf("%d occurrences of the letter %s found in %d threads.\\n", occurrences, searchCharacter, threads);
exit(0);
}
void *scanFile( s_request *request )
{
char requestedCharacter = *request->character;
int integerRequestedCharacter = (int)requestedCharacter;
int comparison;
FILE *openFile;
openFile = fopen(request->file, "r");
if (openFile)
{
while ((comparison = getc(openFile)) != EOF)
{
if (comparison == integerRequestedCharacter)
{
pthread_mutex_lock( &mutex );
occurrences += 1;
pthread_mutex_unlock( &mutex );
}
}
fclose(openFile);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int val;
struct node * next;
} node_t;
node_t * head = 0;
void insert(int val) {
node_t *new_node = malloc(sizeof(node_t));
new_node->val = val;
pthread_mutex_lock(&lock);
if (head == 0) {
head = new_node;
} else {
node_t *curr = head;
while (curr->next != 0) {
curr = curr->next;
}
curr->next = new_node;
}
pthread_mutex_unlock(&lock);
printf("Node inserted\\n");
}
void print() {
pthread_mutex_lock(&lock);
if (head == 0) {
printf("Empty!\\n");
} else {
node_t *curr = head;
while (curr != 0) {
printf("(%d)->", curr->val);
curr = curr->next;
}
}
pthread_mutex_unlock(&lock);
}
void delete(int val) {
pthread_mutex_lock(&lock);
if (head == 0) {
return;
}
if (head->val == val) {
head = head->next;
}
node_t *curr = head;
while (curr->next != 0) {
if (curr->next->val == val) {
node_t *tmp = curr->next;
curr->next = curr->next->next;
free(tmp);
break;
}
curr = curr->next;
}
pthread_mutex_lock(&lock);
}
int main() {
insert(1);
insert(2);
print();
return 0;
}
| 0
|
#include <pthread.h>
int flag = 1;
pthread_mutex_t mutex;
pthread_cond_t condvar;
void *tf(void *param){
int i = 0;
while (i < 1000000000000000000) {
pthread_mutex_lock(&mutex);
if (flag == 2) {
write(STDOUT_FILENO, "2", 1);
i++;
flag = 1;
pthread_cond_signal(&condvar);
} else {
pthread_cond_wait(&condvar, &mutex);
}
pthread_mutex_unlock(&mutex);
}
printf("\\nSubthread written %d times \\"2\\" to terminal\\n", i);
pthread_exit(0);
}
int main(void) {
int i = 0;
pthread_t ti_arr;
pthread_mutex_init(&mutex, 0);
pthread_cond_init (&condvar, 0);
if (pthread_create(&ti_arr, 0, tf, 0) != 0) {
printf("Error in creating a thread\\n");
exit(1);
}
while (i < 1000000000000000000) {
pthread_mutex_lock(&mutex);
if (flag == 1) {
write(STDOUT_FILENO, "1", 1);
i++;
flag = 2;
pthread_cond_signal(&condvar);
} else {
pthread_cond_wait(&condvar, &mutex);
}
pthread_mutex_unlock(&mutex);
}
printf("\\nMain thread written %d times \\"1\\" to terminal\\n", i);
pthread_join(ti_arr, 0);
printf("Done.\\n");
return 0;
}
| 1
|
#include <pthread.h>
{
int
*a;
int
*b;
int sum;
int veclen;
} DOTDATA;
DOTDATA dotstr;
pthread_t callThd[3];
pthread_mutex_t mutexsum;
void *dotprod(void *arg)
{
int i, start, end, len;
long offset;
int mysum, *x, *y;
offset = *(long *)arg;
len = dotstr.veclen;
start = offset*len;
end = start + len;
x = dotstr.a;
y = dotstr.b;
mysum = 0;
for (i=start; i<end ; i++)
mysum += (x[i] * y[i]);
pthread_mutex_lock (&mutexsum);
dotstr.sum += mysum;
printf("\\nThread %ld did %d to %d: mysum=%d global sum=%d\\n",offset,start,end-1,mysum,dotstr.sum);
pthread_mutex_unlock (&mutexsum);
pthread_exit((void*) 0);
}
int main (int argc, char *argv[])
{
long i[3],j;
int *a, *b;
void *status;
pthread_attr_t attr;
srand(time(0));
a = (int*) malloc (3*3*sizeof(int));
b = (int*) malloc (3*3*sizeof(int));
for (j=0; j<3*3; j++)
{
a[j]=rand()%11;
b[j]=rand()%11;
}
printf("a:\\t");
for (j=0; j<3*3; j++)
printf("%d\\t", a[j]);
printf("\\nb:\\t");
for (j=0; j<3*3; j++)
printf("%d\\t", b[j]);
dotstr.veclen = 3;
dotstr.a = a;
dotstr.b = b;
dotstr.sum=0;
pthread_mutex_init(&mutexsum, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(j=0;j<3;j++)
i[j]=j;
for(j=0;j<3;j++)
pthread_create(&callThd[j], &attr, dotprod, (void *)&i[j]);
pthread_attr_destroy(&attr);
for(j=0;j<3;j++)
pthread_join(callThd[j], &status);
printf ("Sum = %d \\n", dotstr.sum);
free (a);
free (b);
pthread_mutex_destroy(&mutexsum);
}
| 0
|
#include <pthread.h>
long m,sum;
int n;
pthread_mutex_t mutex;
void* thread(void* i){
long ssum = 0;
printf("ii = %d\\n",(int)i);
for(long j = m/n*(int)i + 1; j <= m/n*((int)i+1) ; j++){
printf("j = %ld\\n",j);
ssum+=j;
}
pthread_mutex_lock(&mutex);
sum+=ssum;
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main(){
pthread_t threid;
pthread_mutex_init(&mutex,0);
m = 1000000000;
scanf("%d",&n);
for(int i = 0; i < n; i++){
printf("i = %d\\n",i);
if(pthread_create(&threid , 0 , thread , (void*)i) != 0){
printf("线程创建失败\\n");
}
}
sleep(1);
printf("sum = %ld\\n",sum);
}
| 1
|
#include <pthread.h>
double *A;
double *B;
double *C;
int n;
double matrix_norm;
double *b;
double *c;
int num_of_columns;
pthread_mutex_t *mutex;
} matrix_slice;
void *matrix_slice_multiply(void *arg){
matrix_slice *slice = arg;
int i, j;
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n, slice->num_of_columns, n, 1.0, A, n, slice->b, n, 0.0, slice->c, n);
double slice_norm = 0.0;
for(j = 0; j < slice->num_of_columns; j++) {
double column_sum=0.;
for(i = 0; i < n; i++)
column_sum += *(slice->c + i * n + j);
if(column_sum>slice_norm)
slice_norm=column_sum;
}
pthread_mutex_lock(slice->mutex);
if (slice_norm>matrix_norm)
matrix_norm=slice_norm;
pthread_mutex_unlock(slice->mutex);
pthread_exit(0);
}
int main(void) {
int num_of_thrds, num_of_columns_per_slice;
pthread_t *working_thread;
matrix_slice *slice;
pthread_mutex_t *mutex;
int i = 0;
printf ("Please enter matrix dimension n : ");
scanf("%d", &n);
printf ("Please enter number of threads : ");
scanf("%d", &num_of_thrds);
while (num_of_thrds > n) {
printf("number of threads must not be greater than matrix dimension\\n");
printf ("Please enter number of threads : ");
scanf("%d", &num_of_thrds);
}
A = (double *)malloc(n * n * sizeof(double));
if (!A) {
printf("memory failed \\n");
exit(1);
}
B = (double *)malloc(n * n * sizeof(double));
if (!B) {
printf("memory failed \\n");
exit(1);
}
C = (double *)malloc(n * n * sizeof(double));
if (!C) {
printf("memory failed \\n");
exit(1);
}
for (i = 0; i < n * n; i++) {
A[i] = rand() % 15;
B[i] = rand() % 10;
C[i] = 0.;
}
clock_t t1 = clock();
working_thread = malloc(num_of_thrds * sizeof(pthread_t));
slice = malloc(num_of_thrds * sizeof(matrix_slice));
mutex = malloc(sizeof(pthread_mutex_t));
num_of_columns_per_slice = n / num_of_thrds;
for(i = 0; i < num_of_thrds; i++){
slice[i].b = B + i * num_of_columns_per_slice;
slice[i].c = C + i * num_of_columns_per_slice;
slice[i].mutex = mutex;
slice[i].num_of_columns = (i == num_of_thrds - 1) ? n-i * num_of_columns_per_slice : num_of_columns_per_slice;
pthread_create(&working_thread[i], 0, matrix_slice_multiply, (void *)&slice[i]);
}
for(i = 0; i < num_of_thrds; i++)
pthread_join(working_thread[i], 0);
clock_t t2=clock();
printf("elapsed time: %f\\n", (double)(t2 - t1)/CLOCKS_PER_SEC);
printf("column sum norm is %f\\n", matrix_norm);
free(A);
free(B);
free(C);
free(working_thread);
free(slice);
return 0;
}
| 0
|
#include <pthread.h>
pthread_t thread1, thread2;
pthread_mutex_t kill_thread_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t operacao_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t fazer_operacao = PTHREAD_COND_INITIALIZER;
void *functionCount1() {
int thread_status = 0;
thread_status = pthread_mutex_trylock(&kill_thread_mutex);
while (thread_status == EBUSY) {
pthread_mutex_lock(&operacao_mutex);
pthread_cond_wait(&fazer_operacao, &operacao_mutex);
if ((thread_status = pthread_mutex_trylock(&kill_thread_mutex)) != EBUSY) {
break;
}
pthread_mutex_unlock(&operacao_mutex);
}
pthread_mutex_unlock(&kill_thread_mutex);
printf("Desligando thread!\\n");
sleep(2);
printf("Thread Desligada!\\n");
pthread_exit(0);
}
void *functionThreadMenu() {
int termina_escalonador = 0;
int op;
pthread_mutex_lock(&kill_thread_mutex);
pthread_create( &thread2, 0, functionCount1, 0);
while (termina_escalonador == 0) {
printf("Digite a opção\\n");
scanf("%d", &op);
switch(op) {
case 0:
printf("%d", op);
break;
case 1 :
pthread_mutex_lock(&operacao_mutex);
printf("%d. Vou fazer a operação.\\n", op);
pthread_cond_signal(&fazer_operacao);
pthread_mutex_unlock(&operacao_mutex);
printf("Operação concluída\\n");
break;
case 2 :
printf("%d. Vou cancelar a execução.\\n", op);
pthread_mutex_unlock(&kill_thread_mutex);
pthread_cond_signal(&fazer_operacao);
termina_escalonador = 1;
break;
}
}
pthread_join( thread2, 0);
pthread_exit(0);
}
int main() {
pthread_create( &thread1, 0, functionThreadMenu, 0);
pthread_join( thread1, 0);
printf("Threads terminadas com sucesso!");
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex[10];
void *new_start_routine( void * arg ) {
for (int i = 1; i < 10; i += 2) {
pthread_mutex_lock(mutex + i);
}
for (int i = 1; i < 10; i += 2) {
pthread_mutex_lock(mutex + i - 1);
pthread_mutex_unlock(mutex + i - 1);
printf("CHILD\\n");
pthread_mutex_unlock(mutex + i);
}
return 0;
}
int main( int argc, char **argv ) {
pthread_t thread;
pthread_mutexattr_t mutex_attr;
if (0 != pthread_mutexattr_init(&mutex_attr)) {
perror("Could not init mutex attributes\\n");
return 1;
}
if (0 != pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_ERRORCHECK)) {
perror("Could not set mutex attributes type\\n");
return 1;
}
for (int i = 0; i < 10; i++) {
if (0 != pthread_mutex_init(mutex + i, &mutex_attr)) {
perror("Could not initialize mutex\\n");
return 1;
}
if ( !(i % 2) ) {
pthread_mutex_lock(mutex + i);
}
}
if (0 != pthread_create(&thread, 0, new_start_routine, 0)) {
perror("Could not create routine\\n");
return 1;
}
sleep(1);
for (int i = 0; i < 10; i += 2) {
printf("PARENT\\n");
pthread_mutex_unlock(mutex + i);
pthread_mutex_lock(mutex + i + 1);
pthread_mutex_unlock(mutex + i + 1);
}
for (int i = 0; i < 10; i++) {
if (0 != pthread_mutex_destroy(mutex + i)) {
perror("Could not destroy mutex\\n");
return 1;
}
}
if (0 != pthread_mutexattr_destroy(&mutex_attr)) {
perror("Could not destroy mutex attributes\\n");
return 1;
}
return 0;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.