text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
struct job {
struct job* next;
};
struct job* job_queue;
extern void process_job (struct job*, int*);
pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t job_queue_count;
void initialize_job_queue ()
{
job_queue = 0;
sem_init (&job_queue_count, 0, 0);
}
void* thread_function (void* arg)
{
while (1) {
struct job* next_job;
sem_wait (&job_queue_count);
pthread_mutex_lock (&job_queue_mutex);
next_job = job_queue;
job_queue = job_queue->next;
pthread_mutex_unlock (&job_queue_mutex);
process_job (next_job,arg);
free (next_job);
}
return 0;
}
void enqueue_job ( )
{
struct job* new_job;
new_job = (struct job*) malloc (sizeof (struct job));
pthread_mutex_lock (&job_queue_mutex);
new_job->next = job_queue;
job_queue = new_job;
sem_post (&job_queue_count);
pthread_mutex_unlock (&job_queue_mutex);
}
void process_job(struct job* job, int* threadPos){
printf("Procesando job por thread: %d\\n",*threadPos);
}
void* listener(void* arg){
int aux = 0;
while(1){
printf("%s\\n", "Ingrese 1 para agregar un job");
scanf("%d",&aux);
if(aux != 1)
break;
enqueue_job();
}
}
int main(){
initialize_job_queue();
for(int i =0 ; i < 10 ; i++)
enqueue_job();
pthread_t entrada;
pthread_create(&entrada,0,&listener,0);
int tamanho = 5;
pthread_t threads[tamanho];
for(int i = 0 ; i < tamanho ; i++){
int* threadPos = malloc(sizeof(int));
*threadPos = i;
pthread_create(&(threads[i]),0,&thread_function,threadPos);
}
pthread_join(entrada,0);
for(int i = 0 ; i < tamanho ; i++)
pthread_join(threads[i],0);
return 0;
}
| 1
|
#include <pthread.h>
void *print(void *m);
struct data {
pthread_mutex_t lock1;
pthread_mutex_t lock2;
};
int main ()
{
int rt;
pthread_t tid;
pthread_attr_t attr;
struct data d;
struct data *dPtr = &d;
rt = pthread_mutex_init(&(d.lock1), 0);
rt = pthread_mutex_init(&(d.lock2), 0);
rt = pthread_mutex_lock(&(d.lock1));
rt = pthread_create(&tid, 0, print, dPtr);
printf("pthread create code: %d\\n", rt);
printf("Parent: I'm the first\\n");
pthread_mutex_unlock(&(d.lock1));
pthread_mutex_lock(&(d.lock2));
pthread_mutex_unlock(&(d.lock2));
pthread_mutex_lock(&(d.lock1));
sleep(3);
printf("Main: User has pressed enter");
pthread_mutex_unlock(&(d.lock1));
pthread_mutex_lock(&(d.lock2));
printf("Main: child thread has exited, system exiting...\\n");
pthread_mutex_unlock(&(d.lock2));
rt = pthread_mutex_destroy(&(d.lock1));
printf("Destroy main_lock code: %d\\n", rt);
rt = pthread_mutex_destroy(&(d.lock2));
printf("Destroy child_lock code: %d\\n", rt);
pthread_join(tid, 0);
pthread_exit(0);
return 0;
}
void *print(void *m)
{
int rt;
struct data *dataPtr = m;
rt = pthread_mutex_lock(&dataPtr->lock2);
rt = pthread_mutex_lock(&dataPtr->lock1);
printf("Child: I'm the second\\n");
rt = pthread_mutex_unlock(&dataPtr->lock2);
pthread_mutex_lock(&dataPtr->lock2);
rt = pthread_mutex_lock(&dataPtr->lock1);
printf("Child: Received main signal that user has pressed enter");
printf("Child: Child thread exiting...");
sleep(3);
pthread_mutex_unlock(&dataPtr->lock1);
pthread_mutex_unlock(&dataPtr->lock2);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t condition;
int value;
} my_struct_t;
my_struct_t data = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0};
void *waiting_thread(void *);
void *signalling_thread(void *);
int
main(int argc, char **argv)
{
pthread_t wait_thread_id[5];
pthread_t signal_thread_id;
int i;
for(i = 0; i < 5; i++)
pthread_create(&wait_thread_id[i], 0, waiting_thread, (void *)i);
pthread_create(&signal_thread_id, 0, signalling_thread, 0);
pthread_join(signal_thread_id, 0);
for(i = 0; i < 5; i++)
pthread_join(wait_thread_id[i], 0);
pthread_exit(0);
}
void *
waiting_thread(void *args)
{
int thread_number = (int)args;
pthread_mutex_lock(&data.mutex);
if(data.value == 0){
printf("The value of data is %d. \\n", data.value);
printf("Thread number %d waiting for the condition to be signalled. \\n", thread_number);
pthread_cond_wait(&data.condition, &data.mutex);
}
if(data.value != 0){
printf("Condition signalled to thread number %d. \\n", thread_number);
printf("The value of data = %d. \\n", data.value);
}
pthread_mutex_unlock(&data.mutex);
pthread_exit(0);
}
void *
signalling_thread(void *args)
{
int status;
sleep(5);
status = pthread_mutex_lock(&data.mutex);
data.value = 1;
status = pthread_cond_broadcast(&data.condition);
if(status != 0){
printf("Error acquiring mutex. \\n");
pthread_exit(0);
}
status = pthread_mutex_unlock(&data.mutex);
if(status != 0){
printf("Error acquiring mutex. \\n");
pthread_exit(0);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
struct mt
{
int num;
pthread_mutex_t mutex;
pthread_mutexattr_t mutexattr;
};
int main(void)
{
int fd,i;
struct mt *mm;
pid_t pid;
fd = open("m_test",O_CREAT | O_RDWR,0777);
ftruncate(fd,sizeof(*mm));
mm = mmap(0,sizeof(*mm),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
close(fd);
memset(mm,0,sizeof(*mm));
pthread_mutexattr_init(&mm->mutexattr);
pthread_mutexattr_setpshared(&mm->mutexattr,PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&mm->mutex,&mm->mutexattr);
pid = fork();
if(pid == 0)
{
for(i = 0; i < 10; i++)
{
pthread_mutex_lock(&mm->mutex);
(mm->num)++;
printf("num++:%d\\n",mm->num);
pthread_mutex_unlock(&mm->mutex);
sleep(1);
}
}
else if(pid > 0)
{
for(i = 0; i < 10; i++)
{
pthread_mutex_lock(&mm->mutex);
mm->num += 2;
printf("num+=2:%d\\n",mm->num);
pthread_mutex_unlock(&mm->mutex);
sleep(1);
}
wait(0);
}
pthread_mutex_destroy(&mm->mutex);
pthread_mutexattr_destroy(&mm->mutexattr);
munmap(mm,sizeof(*mm));
unlink("mt_test");
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
volatile int x = 1;
void *print_odd(void *arg)
{
int run = 1;
while (run) {
pthread_mutex_lock(&lock);
if (x % 2 == 0) {
pthread_cond_wait(&cond, &lock);
}
fprintf(stdout, "%u\\n", x);
fflush(stdout);
++x;
if (x >= 10) {
run = 0;
}
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
}
return 0;
}
void *print_even(void *arg)
{
int run = 1;
while (run) {
pthread_mutex_lock(&lock);
if (x % 2 == 1) {
pthread_cond_wait(&cond, &lock);
}
fprintf(stdout, "%u\\n", x);
fflush(stdout);
++x;
if (x >= 10) {
run = 0;
}
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
}
return 0;
}
int main(int argc, char **argv)
{
pthread_t th1;
pthread_t th2;
int ret = 0;
ret = pthread_create(&th1, 0, print_odd, 0);
if (ret != 0) {
fprintf(stderr, "pthread_create error\\n");
return -1;
}
ret = pthread_create(&th2, 0, print_even, 0);
if (ret != 0) {
fprintf(stderr, "pthread_create error\\n");
return -1;
}
pthread_join(th1, 0);
pthread_join(th2, 0);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_key_t key;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;
extern char **environ;
static void
thread_init(void)
{
pthread_key_create(&key, free);
}
char *
getenv(const char *name)
{
int i, len;
char *envbuf;
pthread_once(&init_done, thread_init);
pthread_mutex_lock(&env_mutex);
envbuf = (char *)pthread_getspecific(key);
if (envbuf == 0) {
envbuf = (char *)malloc(4096);
if (envbuf == 0) {
pthread_mutex_unlock(&env_mutex);
return(0);
}
pthread_setspecific(key, envbuf);
}
len = strlen(name);
for (i = 0; environ[i] != 0; i++) {
if ((strncmp(name, environ[i], len) == 0) &&
(environ[i][len] == '=')) {
strncpy(envbuf, &environ[i][len+1], 4096 -1);
pthread_mutex_unlock(&env_mutex);
return(envbuf);
}
}
pthread_mutex_unlock(&env_mutex);
return(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
int producedCake = 0;
int Table[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
void Mom(){
int momPosition = -1;
while(producedCake < 100){
if(momPosition == 10 -1){
momPosition = 0;
} else {
momPosition++;
}
printf("Mom checks if there is a cake on place %d on the table...\\n", momPosition+1);
if (Table[momPosition] == 1){
pthread_mutex_lock(&count_mutex);
printf("Mom watches TV...\\n");
pthread_cond_wait(&count_threshold_cv, &count_mutex);
pthread_mutex_unlock(&count_mutex);
}
printf("Mom starts baking a cake\\n");
sleep(2);
pthread_mutex_lock(&count_mutex);
Table[momPosition] = 1;
printf("Mom puts a cake on place %d on the table...\\n", momPosition + 1);
pthread_mutex_unlock(&count_mutex);
pthread_cond_signal(&count_threshold_cv);
producedCake++;
}
}
void Ivan(){
int ivanPosition = -1;
while(producedCake < 100){
if(ivanPosition == 10 -1){
ivanPosition = 0;
} else {
ivanPosition++;
}
printf("Ivan checks if there is a cake on place %d on the table.\\n", ivanPosition + 1);
if (Table[ivanPosition] == 0){
pthread_mutex_lock(&count_mutex);
printf("Ivan goes to play.\\n");
pthread_cond_wait(&count_threshold_cv, &count_mutex);
pthread_mutex_unlock(&count_mutex);
}
printf("Ivan is eating a cake.\\n");
sleep(1);
pthread_mutex_lock(&count_mutex);
Table[ivanPosition] = 0;
printf("Ivan ate the cake on place %d on the table.\\n", ivanPosition + 1);
pthread_mutex_unlock(&count_mutex);
pthread_cond_signal(&count_threshold_cv);
}
}
int main(){
int i;
pthread_t threads[1];
pthread_cond_init (&count_threshold_cv, 0);
pthread_mutex_init(&count_mutex, 0);
pthread_create(&threads[0], 0, Mom, 0);
pthread_create(&threads[1], 0, Ivan, 0);
pthread_join(threads[0], 0);
pthread_join(threads[1], 0);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
return 0;
}
| 1
|
#include <pthread.h>
char g_storage[20];
size_t g_stock = 0;
pthread_mutex_t g_mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t g_full = PTHREAD_COND_INITIALIZER;
pthread_cond_t g_empty = PTHREAD_COND_INITIALIZER;
void show (const char* who, const char* op, char prod) {
printf ("%s:", who);
size_t i;
for (i = 0; i < g_stock; i++)
printf ("%c", g_storage[i]);
printf ("%s%c\\n", op, prod);
}
void* producer (void* arg) {
const char* who = (const char*)arg;
for (;;) {
pthread_mutex_lock (&g_mtx);
while (g_stock >= 20) {
printf ("\\033[;;32m%s:满仓!\\033[0m\\n", who);
pthread_cond_wait (&g_full, &g_mtx);
}
char prod = 'A' + rand () % 26;
show (who, "<-", prod);
g_storage[g_stock++] = prod;
pthread_cond_broadcast (&g_empty);
pthread_mutex_unlock (&g_mtx);
usleep ((rand () % 100) * 1000);
}
return 0;
}
void* customer (void* arg) {
const char* who = (const char*)arg;
for (;;) {
pthread_mutex_lock (&g_mtx);
while (! g_stock) {
printf ("\\033[;;31m%s:空仓!\\033[0m\\n", who);
pthread_cond_wait (&g_empty, &g_mtx);
}
char prod = g_storage[--g_stock];
show (who, "->", prod);
pthread_cond_broadcast (&g_full);
pthread_mutex_unlock (&g_mtx);
usleep ((rand () % 100) * 1000);
}
return 0;
}
int main (void) {
srand (time (0));
pthread_attr_t attr;
int error = pthread_attr_init (&attr);
if (error) {
fprintf (stderr, "pthread_attr_init: %s\\n", strerror (error));
return -1;
}
if ((error = pthread_attr_setdetachstate (&attr,
PTHREAD_CREATE_DETACHED)) != 0) {
fprintf (stderr, "pthread_attr_setdetachstate: %s\\n",
strerror (error));
return -1;
}
pthread_t tid;
if ((error = pthread_create (&tid, &attr, producer,
"生产者1")) != 0) {
fprintf (stderr, "pthread_create: %s\\n", strerror (error));
return -1;
}
if ((error = pthread_create (&tid, &attr, producer,
"生产者2")) != 0) {
fprintf (stderr, "pthread_create: %s\\n", strerror (error));
return -1;
}
if ((error = pthread_create (&tid, &attr, customer,
"消费者1")) != 0) {
fprintf (stderr, "pthread_create: %s\\n", strerror (error));
return -1;
}
if ((error = pthread_create (&tid, &attr, customer,
"消费者2")) != 0) {
fprintf (stderr, "pthread_create: %s\\n", strerror (error));
return -1;
}
getchar ();
return 0;
}
| 0
|
#include <pthread.h>
struct zhw_cache_t {
void **pool;
size_t valid_num;
size_t cache_num;
size_t item_size;
pthread_mutex_t lock;
};
struct zhw_cache_t *zhw_cache_create(size_t cache_num, size_t item_size)
{
struct zhw_cache_t *p = calloc(1, sizeof(struct zhw_cache_t));
pthread_mutex_init(&p->lock, 0);
p->cache_num = cache_num;
p->item_size = item_size;
p->pool = calloc(cache_num, sizeof(void *));
if(p->pool == 0) {
pthread_mutex_destroy(&p->lock);
free(p);
p = 0;
}
size_t i = 0;
for(i = 0; i < p->cache_num; i++) {
p->pool[i] = calloc(1, p->item_size);
p->valid_num++;
}
return p;
}
void* zhw_cache_alloc(struct zhw_cache_t *p)
{
void *it = 0;
if(p->valid_num > 0) {
if(pthread_mutex_lock(&p->lock) == 0) {
if(p->valid_num > 0){
it = p->pool[--p->valid_num];
}
pthread_mutex_unlock(&p->lock);
}
}
if(!it) {
it = calloc(1, p->item_size);
}
return it;
}
void zhw_cache_free(struct zhw_cache_t *p, void *it)
{
if(p->valid_num < p->cache_num) {
if(pthread_mutex_lock(&p->lock) == 0) {
if(p->valid_num < p->cache_num) {
memset(it, 0, p->item_size);
p->pool[p->valid_num++] = it;
} else {
free(it);
}
pthread_mutex_unlock(&p->lock);
return;
}
}
free(it);
return;
}
void zhw_cache_destroy(struct zhw_cache_t *p)
{
if(!p) {
return;
}
size_t i;
for(i = 0; i < p->cache_num; i++) {
if(p->pool[i]) {
free(p->pool[i]);
}
}
free(p->pool);
pthread_mutex_destroy(&p->lock);
free(p);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static int next_id = 1;
static void milli_sleep(int millis) {
struct timespec tm;
tm.tv_sec = 0;
tm.tv_nsec = millis * 1000000;
nanosleep(&tm, 0);
}
static void* hid_thread(void* arg) {
int fd = (int)arg;
char buffer[4096];
int id, ret, offset;
struct usb_device *device;
struct usb_device_descriptor *device_desc;
int max_packet;
struct hidraw_report_descriptor desc;
int desc_length;
fprintf(stderr, "hid_thread start fd: %d\\n", fd);
if (ioctl(fd, HIDIOCGRDESCSIZE, &desc_length)) {
fprintf(stderr, "HIDIOCGRDESCSIZE failed\\n");
close(fd);
goto err;
}
desc.size = HID_MAX_DESCRIPTOR_SIZE - 1;
if (ioctl(fd, HIDIOCGRDESC, &desc)) {
fprintf(stderr, "HIDIOCGRDESC failed\\n");
close(fd);
goto err;
}
wait_for_device:
fprintf(stderr, "waiting for device fd: %d\\n", fd);
device = usb_wait_for_device();
max_packet = usb_device_get_device_descriptor(device)->bMaxPacketSize0;
max_packet--;
milli_sleep(500);
pthread_mutex_lock(&mutex);
id = next_id++;
ret = usb_device_control_transfer(device, USB_DIR_OUT | USB_TYPE_VENDOR,
ACCESSORY_REGISTER_HID, id, desc_length, 0, 0, 1000);
fprintf(stderr, "ACCESSORY_REGISTER_HID returned %d\\n", ret);
milli_sleep(500);
for (offset = 0; offset < desc_length; ) {
int count = desc_length - offset;
if (count > max_packet) count = max_packet;
fprintf(stderr, "sending ACCESSORY_SET_HID_REPORT_DESC offset: %d count: %d desc_length: %d\\n",
offset, count, desc_length);
ret = usb_device_control_transfer(device, USB_DIR_OUT | USB_TYPE_VENDOR,
ACCESSORY_SET_HID_REPORT_DESC, id, offset, &desc.value[offset], count, 1000);
fprintf(stderr, "ACCESSORY_SET_HID_REPORT_DESC returned %d errno %d\\n", ret, errno);
offset += count;
}
pthread_mutex_unlock(&mutex);
while (1) {
ret = read(fd, buffer, sizeof(buffer));
if (ret < 0) {
fprintf(stderr, "read failed, errno: %d, fd: %d\\n", errno, fd);
break;
}
ret = usb_device_control_transfer(device, USB_DIR_OUT | USB_TYPE_VENDOR,
ACCESSORY_SEND_HID_EVENT, id, 0, buffer, ret, 1000);
if (ret < 0 && errno != EPIPE) {
fprintf(stderr, "ACCESSORY_SEND_HID_EVENT returned %d errno: %d\\n", ret, errno);
goto wait_for_device;
}
}
fprintf(stderr, "ACCESSORY_UNREGISTER_HID\\n");
ret = usb_device_control_transfer(device, USB_DIR_OUT | USB_TYPE_VENDOR,
ACCESSORY_UNREGISTER_HID, id, 0, 0, 0, 1000);
fprintf(stderr, "hid thread exiting\\n");
err:
return 0;
}
static void open_hid(const char* name)
{
char path[100];
snprintf(path, sizeof(path), "/dev/%s", name);
int fd = open(path, O_RDWR);
if (fd < 0) return;
fprintf(stderr, "opened /dev/%s\\n", name);
pthread_t th;
pthread_create(&th, 0, hid_thread, (void *)fd);
}
static void* inotify_thread(void* arg)
{
open_hid("hidraw0");
open_hid("hidraw1");
open_hid("hidraw2");
open_hid("hidraw3");
open_hid("hidraw4");
open_hid("hidraw5");
open_hid("hidraw6");
open_hid("hidraw7");
open_hid("hidraw8");
open_hid("hidraw9");
int inotify_fd = inotify_init();
inotify_add_watch(inotify_fd, "/dev", IN_DELETE | IN_CREATE);
while (1) {
char event_buf[512];
struct inotify_event *event;
int event_pos = 0;
int event_size;
int count = read(inotify_fd, event_buf, sizeof(event_buf));
if (count < (int)sizeof(*event)) {
if(errno == EINTR)
continue;
fprintf(stderr, "could not get event, %s\\n", strerror(errno));
break;
}
while (count >= (int)sizeof(*event)) {
event = (struct inotify_event *)(event_buf + event_pos);
if (event->len) {
if(event->mask & IN_CREATE) {
fprintf(stderr, "created %s\\n", event->name);
milli_sleep(50);
open_hid(event->name);
} else {
fprintf(stderr, "lost %s\\n", event->name);
}
}
event_size = sizeof(*event) + event->len;
count -= event_size;
event_pos += event_size;
}
}
close(inotify_fd);
return 0;
}
void init_hid()
{
pthread_t th;
pthread_create(&th, 0, inotify_thread, 0);
}
| 0
|
#include <pthread.h>
struct foo *fh[29];
struct foo *fps[100] = {0};
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo
{
int f_count;
pthread_mutex_t f_lock;
struct foo * f_next;
int f_id;
};
struct foo * foo_alloc(int i)
{
struct foo *fp;
int idx;
fp = (struct foo *)malloc(sizeof(struct foo));
if(fp != 0)
{
if(pthread_mutex_init(&fp->f_lock, 0) != 0)
{
printf("pthread mutex init error");
free(fp);
return 0;
}
idx = ((uintptr_t)fp % 29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
fp->f_id = i;
pthread_mutex_unlock(&fp->f_lock);
return fp;
}
else
{
return 0;
}
}
void foo_hold(struct foo *fp)
{
int idx;
pthread_mutex_lock(&fp->f_lock);
idx = ((uintptr_t)fp % 29);
fp->f_count++;
printf("on fh[%d]:%d\\n", idx, fp->f_count);
pthread_mutex_unlock(&fp->f_lock);
}
void foo_release(struct foo *fp)
{
int idx;
struct foo * head;
pthread_mutex_lock(&hashlock);
if(fp->f_count <= 0)
{
return;
}
if(--fp->f_count == 0)
{
idx = ((uintptr_t)fp % 29);
head = fh[idx];
if(head == fp)
{
fh[idx] = fp->f_next;
}
else
{
while(head->f_next != fp)
{
head = head->f_next;
}
head->f_next = fp->f_next;
}
printf("release fps[%d]\\n", fp->f_id);
fps[fp->f_id] = 0;
free(fp);
pthread_mutex_unlock(&hashlock);
}
else
{
idx = ((uintptr_t)fp % 29);
printf("on fh[%d]:%d\\n", idx, fp->f_count);
pthread_mutex_unlock(&hashlock);
}
}
void * thread_func1(void *arg)
{
struct foo *fp = (struct foo *)arg;
foo_hold(fp);
pthread_exit((void *)0);
}
void * thread_func2(void *arg)
{
struct foo *fp = (struct foo *)arg;
foo_release(fp);
pthread_exit((void *)0);
}
void print_foos(void)
{
int i;
int count = 0;
struct foo *head;
for(i = 0; i < 29; i++)
{
count = 0;
head = fh[i];
while(head != 0)
{
count++;
head = head->f_next;
}
printf("fh[%d]:%d\\n", i, count);
}
}
int main(int argc, char *argv[])
{
pthread_t tids[100];
int i;
int j;
int err;
void *tret;
print_foos();
for(i = 0; i < 100; i++)
{
printf("alloc the %d'th fp\\n", i);
fps[i] = foo_alloc(i);
}
print_foos();
for(i = 0; i < 100; i++)
{
if(fps[i] == 0)
{
printf("fps[%d] is NULL now\\n", i);
continue;
}
for(j = 0; j < 100; j++)
{
if(j < 48)
{
err = pthread_create(&tids[j], 0, thread_func1, (void *)fps[i]);
}
}
}
return 0;
}
| 1
|
#include <pthread.h>
char buffer[1024];
pthread_mutex_t mutex;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *thread_play_0(void *arg);
void Error_print(int num,char *pStr)
{
if(num != 0) {
perror(pStr);
exit(1);
}
}
int main(void)
{
int ret;
pthread_t id;
pthread_attr_t thread_attr;
ret = pthread_attr_init(&thread_attr);
Error_print(ret,"Init error\\n");
ret = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
Error_print(ret,"Init error\\n");
ret = pthread_mutex_init(&mutex,0);
Error_print(ret,"Init error\\n");
ret = pthread_create(&id, &thread_attr,thread_play_0,0);
Error_print(ret,"Create error\\n");
while(scanf("%s",buffer)) {
if(strncmp("stop",buffer,4) == 0) {
pthread_mutex_lock(&mutex);
printf("-------Goodbye-------\\n");
sleep(1);
break;
}
if(strncmp("start",buffer,5) == 0) {
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
exit(0);
}
void *thread_play_0(void *arg)
{
while (1)
{
pthread_mutex_lock(&mutex);
printf("It's a flash,input stop to stop,input pause to pause.\\n");
pthread_mutex_unlock(&mutex);
sleep(1);
if (strncmp("stop", buffer, 4) == 0) {
break;
}
if (strncmp("pause", buffer, 5) == 0) {
strcpy(buffer," ");
pthread_mutex_lock(&mutex);
printf("---------Flash is paused---------\\n");
printf("Input start to play the flash again.\\n");
pthread_cond_wait(&cond,&mutex);
pthread_mutex_unlock(&mutex);
}
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
void *Producer();
void *Consumer();
char *BUFFER;
int BufferIndex=0;
pthread_cond_t Buffer_Not_Full=PTHREAD_COND_INITIALIZER;
pthread_cond_t Buffer_Not_Empty=PTHREAD_COND_INITIALIZER;
pthread_mutex_t mVar=PTHREAD_MUTEX_INITIALIZER;
int main()
{
pthread_t ptid,ctid;
BUFFER=(char *) malloc(sizeof(char) * 10);
pthread_create(&ptid,0,Producer,0);
pthread_create(&ctid,0,Consumer,0);
return 0;
}
void *Producer()
{
for(;;)
{
pthread_mutex_lock(&mVar);
if(BufferIndex==10)
{
pthread_cond_wait(&Buffer_Not_Full,&mVar);
}
BUFFER[BufferIndex++]='@';
printf("Produce : %d \\n",BufferIndex);
pthread_mutex_unlock(&mVar);
pthread_cond_signal(&Buffer_Not_Empty);
}
}
void *Consumer()
{
for(;;)
{
pthread_mutex_lock(&mVar);
if(BufferIndex==-1)
{
pthread_cond_wait(&Buffer_Not_Empty,&mVar);
}
printf("Consume : %d \\n",BufferIndex--);
pthread_mutex_unlock(&mVar);
pthread_cond_signal(&Buffer_Not_Full);
}
}
| 1
|
#include <pthread.h>
int p_id;
int p_fila;
int p_columna;
int p_weapon;
}people;
char** board;
int N;
int M;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void move_people(people *persona, char** board){
int i, j;
i = persona->p_fila;
j = persona->p_columna;
int contador = 0;
int mov = rand()%8;
while(contador < 8){
if (mov == 0){
if(j > 0 && board[i][j-1] == '0'){
persona->p_columna = j-1;
board[i][j-1] = 'P';
contador = 8;
}
contador = contador + 1;
}
if (mov == 1){
if(j < M-1 && board[i][j+1] == '0'){
persona->p_columna = j+1;
board[i][j+1] = 'P';
contador = 8;
}
contador = contador + 1;
}
if (mov == 2){
if(i < N-1 && board[i+1][j] == '0'){
persona->p_fila = i+1;
board[i+1][j] = 'P';
contador = 8;
}
contador = contador + 1;
}
if (mov == 3){
if(i > 0 && board[i-1][j] == '0'){
persona->p_fila = i-1;
board[i-1][j] = 'P';
contador = 8;
}
contador = contador + 1;
}
if (mov == 4){
if(i < N-1 && j > 0 && board[i+1][j-1] == '0'){
persona->p_fila = i+1;
persona->p_columna = j-1;
board[i+1][j-1] = 'P';
contador = 8;
}
contador = contador + 1;
}
if (mov == 5){
if(i > 0 && j > 0 && board[i-1][j-1] == '0'){
persona->p_fila = i-1;
persona->p_columna = j-1;
board[i-1][j-1] = 'P';
contador = 8;
}
contador = contador + 1;
}
if (mov == 6){
if(i < N-1 && j < M-1 && board[i+1][j+1] == '0'){
persona->p_fila = i+1;
persona->p_columna = j+1;
board[i+1][j+1] = 'P';
contador = 8;
}
contador = contador + 1;
}
if (mov == 7){
if(i > 0 && j < M-1 && board[i-1][j+1] == '0'){
persona->p_fila = i-1;
persona->p_columna = j+1;
board[i-1][j+1] = 'P';
contador = 8;
}
contador = contador + 1;
}
mov = (mov+1)%8;
}
}
void *create_people(void *arg){
people *p = (people*) arg;
pthread_mutex_lock(&mutex);
move_people(p, board);
pthread_mutex_unlock(&mutex);
}
void threads_peoples(int n_people, int N, int M){
int i;
pthread_t *threads_peoples = (pthread_t*) malloc(n_people*sizeof(pthread_t));
people *array_p = (people*)malloc(sizeof(people)*n_people);
for(i=0; i< n_people; i++){
array_p[i].p_id = i;
int fila = rand()%N;
int columna = rand()%M;
array_p[i].p_fila = fila;
array_p[i].p_columna = columna;
array_p[i].p_weapon = 0;
}
for (i=0; i < n_people; i++) {
pthread_create( &(threads_peoples[i]), 0, create_people, (void*) &(array_p[i]));
}
for (i=0; i < n_people; i++){
pthread_join(threads_peoples[i], 0);
}
}
char** spaceForBoard(int n, int m){
char *boardAux = (char*)calloc(n*m, sizeof(char));
char **board = (char**)calloc(n*m, sizeof(char*));
for (int i = 0; i < n; i++){
board[i] = boardAux + i*m;
}
return board;
}
char** board_created(char** board, int ancho, int largo){
int i, j;
for(i=0; i < ancho; i++){
for(j=0; j < largo; j++){
board[i][j] = '0';
}
}
return board;
}
void printBoard(int n, int m, char** board){
for(int j = 0; j < m; j++){
printf("\\n");
for(int i = 0; i < n; i++){
printf("%c",board[i][j]);
}
}
printf("\\n\\n");
}
int main (int argc, char *argv[]){
int n,m,p;
n = atoi(argv[1]);
m = atoi(argv[2]);
p = atoi(argv[3]);
N = n;
M = m;
board = spaceForBoard(n,m);
board = board_created(board, n, m);
threads_peoples(p, n, m);
printBoard(n, m, board);
exit(0);
}
| 0
|
#include <pthread.h>
int pthread_barrier_init(pthread_barrier_t* barrier,
const void* barrier_attr,
unsigned count) {
int rc;
_uv_barrier* b;
if (barrier == 0 || count == 0)
return EINVAL;
if (barrier_attr != 0)
return ENOTSUP;
b = uv__malloc(sizeof(*b));
if (b == 0)
return ENOMEM;
b->in = 0;
b->out = 0;
b->threshold = count;
if ((rc = pthread_mutex_init(&b->mutex, 0)) != 0)
goto error2;
if ((rc = pthread_cond_init(&b->cond, 0)) != 0)
goto error;
barrier->b = b;
return 0;
error:
pthread_mutex_destroy(&b->mutex);
error2:
uv__free(b);
return rc;
}
int pthread_barrier_wait(pthread_barrier_t* barrier) {
int rc;
_uv_barrier* b;
if (barrier == 0 || barrier->b == 0)
return EINVAL;
b = barrier->b;
if ((rc = pthread_mutex_lock(&b->mutex)) != 0)
return rc;
if (++b->in == b->threshold) {
b->in = 0;
b->out = b->threshold - 1;
rc = pthread_cond_signal(&b->cond);
assert(rc == 0);
pthread_mutex_unlock(&b->mutex);
return PTHREAD_BARRIER_SERIAL_THREAD;
}
do {
if ((rc = pthread_cond_wait(&b->cond, &b->mutex)) != 0)
break;
} while (b->in != 0);
b->out--;
pthread_cond_signal(&b->cond);
pthread_mutex_unlock(&b->mutex);
return rc;
}
int pthread_barrier_destroy(pthread_barrier_t* barrier) {
int rc;
_uv_barrier* b;
if (barrier == 0 || barrier->b == 0)
return EINVAL;
b = barrier->b;
if ((rc = pthread_mutex_lock(&b->mutex)) != 0)
return rc;
if (b->in > 0 || b->out > 0)
rc = EBUSY;
pthread_mutex_unlock(&b->mutex);
if (rc)
return rc;
pthread_cond_destroy(&b->cond);
pthread_mutex_destroy(&b->mutex);
uv__free(barrier->b);
barrier->b = 0;
return 0;
}
| 1
|
#include <pthread.h>
int sum = 0;
int arr[8][100];
pthread_mutex_t sum_mutex;
void* do_work(void* num)
{
int i, j;
int cols_start, cols_end;
int* int_num;
int local_sum = 0;
int_num = (int *) num;
cols_start = *int_num * 100 / 4;
cols_end = cols_start + 100 / 4;
printf ("Thread %d summing columns [%d] through [%d] from indices [%d] to [%d]\\n",
*int_num, 0, 8 -1, cols_start, cols_end-1);
for (i = 0; i < 8; i++) {
for (j = cols_start; j < cols_end; j++) {
local_sum += arr[i][j];
}
}
pthread_mutex_lock (&sum_mutex);
sum = sum + local_sum;
pthread_mutex_unlock (&sum_mutex);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int i, j;
int start, thread_nums[4];
pthread_t threads[4];
for (i = 0; i < 8; i++) {
for (j = 0; j < 100; j++) {
arr[i][j] = i * 100 + j;
}
}
pthread_mutex_init(&sum_mutex, 0);
for (i = 0; i < 4; i++) {
thread_nums[i] = i;
pthread_create(&threads[i], 0, do_work, (void *) &thread_nums[i]);
}
for (i = 0; i < 4; i++) {
pthread_join(threads[i], 0);
}
printf ("Threaded array sum = %d\\n", sum);
sum = 0;
for (i = 0; i < 8; i++) {
for (j = 0; j < 100; j++) {
sum += arr[i][j];
}
}
printf("Loop array sum = %d\\n", sum);
pthread_mutex_destroy(&sum_mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
enum
{
NUM_ASYNC_IO = 20,
PAGE_SIZE = 8,
PAGE_NUMBER = 32
};
enum TYPE_OF_OPERATION
{
READ,
WRITE
};
struct paging_file_info
{
char *file_name;
int fdw;
int fdr;
struct aiocb *aiocb_blocks;
};
struct buff_page_info
{
int is_active;
int page_number;
};
pthread_mutex_t mutex;
pthread_mutex_t aio_requests;
pthread_mutex_t *aio_mutexes;
int num_aiocb_ptrs;
char *buffer;
int total_aio_active;
struct buff_page_info *aiocb_info;
struct paging_file_info page_file;
void init_global()
{
int i;
page_file.file_name = malloc(16);
page_file.file_name = "paging_file.tmp";
page_file.fdw = creat(page_file.file_name, 0644);
page_file.fdr = open(page_file.file_name, O_RDONLY);
page_file.aiocb_blocks = malloc(NUM_ASYNC_IO * sizeof(struct aiocb));
if(page_file.aiocb_blocks == 0)
{
fprintf(stderr, "malloc failed\\n");
exit(1);
}
aiocb_info = malloc(NUM_ASYNC_IO * sizeof(struct buff_page_info));
if(aiocb_info == 0)
{
fprintf(stderr, "malloc failed\\n");
exit(1);
}
aio_mutexes = malloc(NUM_ASYNC_IO * sizeof(pthread_mutex_t));
if(aio_mutexes == 0)
{
fprintf(stderr, "malloc failed\\n");
exit(1);
}
for(i = 0; i < NUM_ASYNC_IO; i++)
{
aiocb_info[i].is_active = 0;
aiocb_info[i].page_number = -1;
}
pthread_mutex_lock(&aio_requests);
buffer = malloc(NUM_ASYNC_IO * PAGE_SIZE);
memset(buffer, 0, NUM_ASYNC_IO * PAGE_SIZE);
if(buffer == 0)
{
fprintf(stderr, "malloc failed\\n");
exit(1);
}
}
void done_global()
{
free(page_file.aiocb_blocks);
free(buffer);
free(aiocb_info);
free(aio_mutexes);
close(page_file.fdw);
close(page_file.fdr);
}
char *get_page_address_in_buff(int buff_page_number)
{
return buffer + buff_page_number * PAGE_SIZE;
}
int find_and_book_empty_aio(int page_number)
{
int i;
int ret;
pthread_mutex_lock(&mutex);
if(total_aio_active != NUM_ASYNC_IO)
{
for(i = 0; i < NUM_ASYNC_IO; i++)
{
if(aiocb_info[i].is_active && aiocb_info[i].page_number == page_number)
{
ret = i;
break;
}
}
if(i == NUM_ASYNC_IO)
{
for(i = 0; i < NUM_ASYNC_IO; i++)
{
if(!aiocb_info[i].is_active)
{
aiocb_info[i].is_active = 1;
aiocb_info[i].page_number = page_number;
ret = i;
break;
}
}
}
}
pthread_mutex_unlock(&mutex);
return ret;
}
void print_info(int buff_page_number, int page_number, enum TYPE_OF_OPERATION type)
{
printf("manage_page(%d,%d,%s)\\n", buff_page_number, page_number, type == READ ? "READ" : "WRITE");
}
void manage_page(int buff_page_number, int page_number, enum TYPE_OF_OPERATION type)
{
int i = find_and_book_empty_aio(page_number);
printf("i = %d\\n", i);
while(i == -1)
{
print_info(buff_page_number, page_number, type);
printf("hanging on aio_requests\\n");
pthread_mutex_lock(&aio_requests);
i = find_and_book_empty_aio(page_number);
print_info(buff_page_number, page_number, type);
printf("i = %d\\n", i);
}
pthread_mutex_lock(&aio_mutexes[i]);
page_file.aiocb_blocks[i].aio_fildes = dup(page_file.fdw);
page_file.aiocb_blocks[i].aio_offset = page_number * PAGE_SIZE;
page_file.aiocb_blocks[i].aio_nbytes = PAGE_SIZE;
page_file.aiocb_blocks[i].aio_buf = get_page_address_in_buff(buff_page_number);
page_file.aiocb_blocks[i].aio_sigevent.sigev_notify = SIGEV_NONE;
print_info(buff_page_number, page_number, type);
printf("aiocb structure is ready\\n");
int err;
if(type == READ)
err = aio_read(&page_file.aiocb_blocks[i]);
else
err = aio_write(&page_file.aiocb_blocks[i]);
print_info(buff_page_number, page_number, type);
printf("%s done\\n", type == READ ? "READ" : "WRITE");
if(err == -1)
{
fprintf(stderr, "aio_write failed\\n");
exit(1);
}
err = close(page_file.aiocb_blocks[i].aio_fildes);
if(err == -1)
{
fprintf(stderr, "closing of file descriptor failed\\n");
exit(1);
}
aiocb_info[i].is_active = 0;
pthread_mutex_unlock(&aio_mutexes[i]);
pthread_mutex_unlock(&aio_requests);
}
int main(int argc, char ** argv)
{
init_global();
int i;
for(i = 0; i < NUM_ASYNC_IO * PAGE_SIZE; i++)
buffer[i] = '0' + (i % 10);
for(i = 0; i < PAGE_NUMBER; i++)
manage_page(i % NUM_ASYNC_IO, i, WRITE);
done_global();
return 0;
}
| 1
|
#include <pthread.h>
char mfork[10];
struct cv_t{
pthread_mutex_t m;
pthread_cond_t cv;
};
struct cv_t mcv = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER};
void * mthread(void *num)
{
int sec;
int l, r;
int _i;
for (_i=0; _i<3; _i++){
sec = rand() % 3;
sleep(sec);
r = ((int)num) % 10;
l = ((int)num+1)% 10;
fprintf(stderr, "* Fil %d take %d, %d\\n", (int)num,l,r);
pthread_mutex_lock(&mcv.m);
while (mfork[l] == 1 || mfork[r] == 1)
pthread_cond_wait(&mcv.cv, &mcv.m);
mfork[l] = mfork[r] = 1;
pthread_mutex_unlock(&mcv.m);
fprintf(stderr, "Fil %d ma obe vidle\\n", (int)num);
pthread_mutex_lock(&mcv.m);
mfork[l] = mfork[r] = 0;
pthread_cond_broadcast(&mcv.cv);
pthread_mutex_unlock(&mcv.m);
}
pthread_exit(0);
}
int main(int argc, char *argv[])
{
pthread_t th[10];
memset(mfork, 0, 10);
int i;
for(i=0; i<10; i++)
{
pthread_create(&th[i], 0, mthread, (void*)i);
}
for(i=0; i<10; i++)
pthread_join(th[i], 0);
exit(0);
}
| 0
|
#include <pthread.h>
int calculateNext(int s2) {
int calculateNext_return;
do {
calculateNext_return = __nondet_int();
} while(calculateNext_return == s2 || calculateNext_return == 0);
return calculateNext_return;
}
int seed;
pthread_mutex_t m;
int PseudoRandomUsingAtomic_nextInt(int n) {
int read, nexts, casret, nextInt_return;
while(1) {
read = seed;
nexts = calculateNext(read);
assert(nexts != read);
casret = __sync_bool_compare_and_swap(&seed,read,nexts);
if(casret == 1){
nextInt_return = nexts % n;
break;
}
}
return nextInt_return;
}
void PseudoRandomUsingAtomic_monitor() {
while(1) {
assert(seed != 0);
}
}
void PseudoRandomUsingAtomic_constructor(int init) {
seed = init;
}
void PseudoRandomUsingAtomic__threadmain() {
int myrand;
myrand = PseudoRandomUsingAtomic_nextInt(10);
assert(myrand <= 10);
}
int state = 0;
void* thr1(void* arg) {
pthread_mutex_lock(&m);
switch(state) {
case 0:
PseudoRandomUsingAtomic_constructor(1);
state = 1;
pthread_mutex_unlock(&m);
PseudoRandomUsingAtomic_monitor();
break;
case 1:
pthread_mutex_unlock(&m);
PseudoRandomUsingAtomic__threadmain();
break;
}
return 0;
}
int main()
{
pthread_t t1,t2,t3;
pthread_create(&t1, 0, thr1, 0);
pthread_create(&t2, 0, thr1, 0);
pthread_create(&t3, 0, thr1, 0);
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 quitting\\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 id;
int tipo;
} Data;
Data fila[150];
int in = 0;
int out = 0;
int formados = 0;
int atendidos = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cajero_t = PTHREAD_COND_INITIALIZER;
pthread_cond_t cliente_t = PTHREAD_COND_INITIALIZER;
void * cajero(void *);
void * cliente(void *);
int main(int argc, const char * argv[])
{
int numThreads = 8 + 150;
pthread_t * threads = (pthread_t*)malloc(sizeof(pthread_t) * numThreads);
Data * datosCajeros = (Data*)malloc(sizeof(Data) * (8 + 1));
Data * datosClientes = (Data*)malloc(sizeof(Data) * (150 + 1));
pthread_t * aux;
int idCajero = 1;
srand((int)time(0));
for (aux = threads; aux < (threads + 8); aux++)
{
(datosCajeros + idCajero)->id = idCajero;
if (idCajero <= 5)
(datosCajeros + idCajero)->tipo = 1;
else
(datosCajeros + idCajero)->tipo = 2;
pthread_create(aux, 0, cajero, (void*)(datosCajeros + idCajero));
idCajero++;
}
int idCliente = 1;
for (; aux < (threads + numThreads); ++aux)
{
(datosClientes + idCliente)->id = idCliente;
if (idCliente <= 100)
(datosClientes + idCliente)->tipo = 1;
else
(datosClientes + idCliente)->tipo = 2;
pthread_create(aux, 0, cliente, (void*)(datosClientes + idCliente));
idCliente++;
}
for (aux = threads; aux < (threads + numThreads); ++aux)
pthread_join(*aux, 0);
free(datosClientes);
free(datosCajeros);
free(threads);
return 0;
}
void * cajero(void * arg)
{
Data* data = (struct Data*)arg;
int id = data->id;
int tipo = data->tipo;
while (atendidos < 150)
{
usleep(3 + rand() % 5);
pthread_mutex_lock(&mutex);
int hayCEmpresarial = 0;
for (int i = 0; i < formados; i++)
{
if (fila[out].tipo == 2)
hayCEmpresarial = 1;
}
if (formados > 0 &&
(tipo == 1
|| (tipo == 2 && hayCEmpresarial == 0)
|| (tipo == 2 && fila[out].tipo == 2)))
{
printf(" +++ Atendiendo a %d por caja %d de tipo %s\\n",
fila[out].id, id, fila[out].tipo == 1 ? "general" : "empresarial");
usleep(3);
atendidos++;
out++;
out %= 150;
formados--;
if (formados == 150 - 1)
pthread_cond_broadcast(&cliente_t);
}
else
{
pthread_cond_wait(&cajero_t, &mutex);
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void * cliente(void * arg)
{
Data* data = (struct Data*)arg;
int id = data->id;
int tipo = data->tipo;
int status = 1;
while (atendidos < 150)
{
if (tipo == 1)
usleep(10 + rand() % 5);
else
usleep(20 + rand() % 5);
pthread_mutex_lock(&mutex);
if (formados < 150 && status == 1)
{
fila[in] = *data;
printf("** Llego el cliente %d %s\\n", id, tipo == 1 ? "general" : "empresarial");
in++;
formados++;
in %= 150;
status = 0;
if (formados == 1)
pthread_cond_broadcast(&cajero_t);
}
else
{
pthread_cond_wait(&cliente_t, &mutex);
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
sem_t N_FREE, lock;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int available[4] = {1,1,1,1};
pthread_t machineArr[4];
pthread_t stationArr[4];
int k;
int m;
void* runMachine(void *m);
void* runStation(void *k);
void release(int machine);
void setup(int stations, int machines)
{
sem_init(&N_FREE, 0, 4);
sem_init(&lock, 0, 1);
for(k = 0; k < 4; k++)
{
pthread_create(&stationArr[k], 0, &runStation, (void *)&k);
}
for(m = 0; m < 4; m++)
{
pthread_create(&machineArr[m], 0, &runMachine,(void *)&m);
}
}
void *runMachine(void *ptr)
{
while(1)
{
printf("Machine %d\\n\\n", m);
sem_wait(&lock);
sleep(5);
release(m);
sem_post(&lock);
}
}
int allocate()
{
int i;
sem_wait(&N_FREE);
pthread_mutex_lock(&mutex);
for(i=0; i < 4; i++)
{
if(available[i] != 0)
{
available[i] = 0;
pthread_mutex_unlock(&mutex);
return i;
}
}
return 0;
}
void release(int machine)
{
pthread_mutex_lock(&mutex);
available[machine] = 1;
pthread_mutex_unlock(&mutex);
sem_post(&N_FREE);
}
void *runStation(void *ptr)
{
while(1)
{
allocate();
printf("Station %d\\n\\n", k);
}
}
int main()
{
setup(4,4);
while(1);
return 0;
}
| 0
|
#include <pthread.h>
const int MAX_THREADS = 1024;
const int MSG_MAX = 50;
void* send_msg(void* rank);
void get_args(int argc, char* argv[]);
void usage(char* prog_name);
long thread_count;
long long n;
int message_available, consumer;
char** messages;
pthread_mutex_t mutex;
int main(int argc, char* argv[] ) {
long thread;
pthread_t* thread_handles;
get_args(argc, argv);
thread_handles = malloc(thread_count * sizeof(pthread_t) );
messages = malloc(thread_count * sizeof(char*) );
pthread_mutex_init(&mutex, 0);
message_available = 0;
consumer = 0;
for(thread = 0; thread < thread_count; thread++) {
pthread_create(&thread_handles[thread], 0, send_msg, (void*) thread);
}
for(thread = 0; thread < thread_count; thread++) {
pthread_join(thread_handles[thread], 0);
}
pthread_mutex_destroy(&mutex);
free(messages);
free(thread_handles);
return 0;
}
void* send_msg(void* rank) {
long my_rank = (long) rank;
long dest = (my_rank + 1) % thread_count;
char* my_msg = malloc(MSG_MAX * sizeof(char) );
while(1) {
pthread_mutex_lock(&mutex);
if(my_rank == consumer) {
if(message_available) {
printf("CONSUMER thread %ld message: \\"%s\\"\\n", my_rank, messages[my_rank] );
pthread_mutex_unlock(&mutex);
break;
}
} else {
sprintf(my_msg, "Hello to consumer thread %ld from PRODUCER thread %ld", dest, my_rank);
messages[dest] = my_msg;
message_available = 1;
pthread_mutex_unlock(&mutex);
break;
}
pthread_mutex_unlock(&mutex);
}
return 0;
}
void get_args(int argc, char* argv[]) {
if (argc != 2) {
usage(argv[0]);
}
thread_count = strtol(argv[1], 0, 10);
if (thread_count <= 0 || thread_count > MAX_THREADS) {
usage(argv[0]);
}
}
void usage(char* prog_name) {
fprintf(stderr, "usage: %s <number of threads>\\n", prog_name);
exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t insert_lock;
pthread_mutex_t delete_lock;
pthread_mutex_t search_count_lock;
struct node *head = 0;
int search_count = 0;
struct node {
int val;
struct node* next;
};
void push()
{
struct node* new_node = malloc(sizeof(struct node));
new_node->val = rand() % 100 + 1;
new_node->next = 0;
if (head == 0) {
head = new_node;
} else {
struct node* current = head;
while (current->next != 0){
current = current->next;
}
current->next = new_node;
}
}
void pop()
{
struct node* temp;
if (head != 0) {
temp = head;
head = head->next;
free(temp);
}
}
void print_list()
{
struct node* current = head;
while (current != 0) {
printf(" %d ", current->val);
current = current->next;
}
printf("\\n");
}
void* delete(void* ptr)
{
pthread_mutex_lock(&insert_lock);
pthread_mutex_lock(&delete_lock);
printf("deleting start\\n");
pop();
print_list();
printf("deleting finish\\n");
pthread_mutex_unlock(&insert_lock);
pthread_mutex_unlock(&delete_lock);
pthread_exit(0);
}
void* search(void* ptr)
{
pthread_mutex_lock(&search_count_lock);
search_count++;
printf("searches in progress: %d\\n", search_count);
pthread_mutex_unlock(&search_count_lock);
struct node* current = head;
while (current != 0) {
pthread_mutex_lock(&delete_lock);
current = current->next;
printf("looking at current\\n");
pthread_mutex_unlock(&delete_lock);
}
pthread_mutex_lock(&search_count_lock);
search_count--;
printf("finished search: %d\\n", search_count);
pthread_mutex_unlock(&search_count_lock);
pthread_exit(0);
}
void* insert(void* ptr)
{
pthread_mutex_lock(&insert_lock);
printf("insert start\\n");
push();
print_list();
printf("insert finish\\n");
pthread_mutex_unlock(&insert_lock);
pthread_exit(0);
}
int main()
{
int choice = 0;
time_t t;
pthread_mutex_init(&insert_lock, 0);
pthread_mutex_init(&delete_lock, 0);
pthread_mutex_init(&search_count_lock, 0);
srand ((unsigned) time(&t));
pthread_t thread;
while (1) {
choice = rand () % 3 + 1;
if (choice == 1){
pthread_create(&thread, 0, search, 0);
} else if (choice == 2) {
pthread_create(&thread, 0, insert, 0);
} else if (choice == 3) {
pthread_create(&thread, 0, delete, 0);
}
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER;
int turn=0;
long Counter = 0;
void *Conter()
{
while(1)
{
pthread_mutex_lock( &condition_mutex );
if(turn==0) pthread_cond_wait( &condition_cond, &condition_mutex );
turn=1;
Counter++;
pthread_cond_signal( &condition_cond );
pthread_mutex_unlock( &condition_mutex );
}
}
void *Printer()
{
while(1)
{
pthread_mutex_lock( &condition_mutex );
if(turn==1) pthread_cond_wait( &condition_cond, &condition_mutex );
turn=1;
printf("Counter2 = %ld\\n", Counter);
sleep(1);
pthread_cond_signal( &condition_cond );
pthread_mutex_unlock( &condition_mutex );
}
}
void main()
{
int pid1, pid2, rc1, rc2;
pthread_t ConterThrd,PrinterThrd;
rc1 = pthread_create(&ConterThrd, 0, Conter, 0);
if (rc1) {
printf("Error:unable to create thread, error no: %d", rc1);
return;
}
rc2 = pthread_create(&PrinterThrd, 0, Printer, 0);
if (rc2) {
printf("Error:unable to create thread, error no: %d", rc2);
return;
}
pthread_join( ConterThrd, 0);
pthread_join( PrinterThrd, 0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
int count = 0;
int sum=0;
void *functionCount1();
void *functionCount2();
void main() {
pthread_t thread1, thread2;
pthread_create( &thread1, 0, &functionCount1, 0);
pthread_create( &thread2, 0, &functionCount2, 0);
pthread_join( thread1, 0);
pthread_join( thread2, 0);
printf("Final count: %d\\n",count);
}
void *functionCount1() {
for(;;) {
pthread_mutex_lock( &count_mutex );
pthread_cond_wait( &condition_var, &count_mutex );
count++;
sum = sum+count;
printf("Counter value functionCount1: %d\\n",count);
printf("summation value : %d \\n",sum);
pthread_mutex_unlock( &count_mutex );
if(count >= 10) return(0);
}
}
void *functionCount2() {
for(;;) {
pthread_mutex_lock( &count_mutex );
if( count < 5 )
{
pthread_cond_signal( &condition_var );
} else {
count++;
sum = sum+count;
printf("Counter value functionCount2: %d\\n",count);
printf("summation value : %d \\n",sum);
}
pthread_mutex_unlock(&count_mutex);
if(count >= 10) return(0);
}
}
| 0
|
#include <pthread.h>
int arr[1024];
pthread_mutex_t l = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
int lectores = 0;
int escritores = 0;
void *escritor(void *arg)
{
int i;
int num = *((int *)arg);
for (;;) {
pthread_mutex_lock(&l);
escritores++;
printf("Escritor %i adentro\\n", num);
sleep(random()%1);
while(lectores > 0)
pthread_cond_wait(&cond, &l);
for (i=1024 -1; i>=0; i--) {
arr[i] = num;
}
printf("Escritor %i afuera\\n", num);
escritores--;
pthread_cond_signal(&cond2);
pthread_mutex_unlock(&l);
}
return 0;
}
void *lector(void *arg)
{
int v, i, err;
int num = *((int *)arg);
for (;;) {
pthread_mutex_lock(&l);
lectores++;
pthread_mutex_unlock(&l);
sleep(random()%1);
err = 0;
v = arr[0];
for (i=1; i<1024; i++) {
if (arr[i]!=v) {
err=1;
break;
}
}
printf("lector fuera \\n");
if (err) printf("Lector %d, error de lectura\\n", num);
else printf("Lector %d, dato %d\\n", num, v);
lectores--;
if(lectores == 0)
pthread_cond_signal(&cond);
while(escritores > 0)
pthread_cond_wait(&cond2, &l);
pthread_mutex_unlock(&l);
}
return 0;
}
int main()
{
int i;
pthread_t lectores[20], escritores[20];
int arg[20];
for (i=0; i<1024; i++) {
arr[i] = -1;
}
for (i=0; i<20; i++) {
arg[i] = i;
pthread_create(&lectores[i], 0, lector, (void *)&arg[i]);
pthread_create(&escritores[i], 0, escritor, (void *)&arg[i]);
}
printf(" FUERA DEL FOR \\n");
pthread_join(lectores[0], 0);
return 0;
}
| 1
|
#include <pthread.h>
int is_prime(int n) {
int i;
if (n <= 2) return 1;
if (n % 2 == 0) return 0;
for (i = 3; i < n; i += 2) {
if (n % i == 0) return 0;
}
return 1;
}
struct search_range {
int start;
int end;
int count;
pthread_mutex_t *mutex;
};
void primes_loop(struct search_range *range)
{
int i;
for (i = range->start; i < range->end; ++i)
{
if (is_prime(i))
{
pthread_mutex_lock(range->mutex);
++(range->count);
pthread_mutex_unlock(range->mutex);
}
}
}
void *primes_thread(void *ctx) {
struct search_range *range;
range = (struct search_range *)ctx;
primes_loop(range);
return 0;
}
int main(int argc, char* argv[]) {
int nthreads, max;
pthread_t *threads;
struct search_range *ranges;
int i;
pthread_mutex_t mutex;
puts("Hit ENTER to start.");
getchar();
pthread_mutex_init(&mutex, 0);
if (argc >= 3) {
nthreads = atoi(argv[1]);
max = atoi(argv[2]);
}
else {
nthreads = 2;
max = 100000;
}
threads = (pthread_t *)malloc(sizeof(pthread_t) * nthreads);
ranges = (struct search_range *)malloc(sizeof(struct search_range) * nthreads);
for (i = 0; i < nthreads; ++i) {
ranges[i].start = i * (max / nthreads);
ranges[i].end = (i + 1) * (max / nthreads);
ranges[i].count = 0;
ranges[i].mutex = &mutex;
pthread_create(&threads[i], 0, primes_thread, &ranges[i]);
}
for (i = 0; i < nthreads; ++i) {
pthread_join(threads[i], 0);
printf("thread %d found %d primes\\n", i, ranges[i].count);
}
free(ranges);
free(threads);
return 0;
}
| 0
|
#include <pthread.h>
inline size_t
software_cas(size_t* reg, size_t oldval, size_t newval, pthread_mutex_t *lock)
{
pthread_mutex_lock(lock);
if (memcmp(reg, &oldval, sizeof(void*)) == 0)
{
memcpy(reg, &newval, sizeof(void*));
pthread_mutex_unlock(lock);
return oldval;
}
else
{
pthread_mutex_unlock(lock);
return *reg;
}
}
| 1
|
#include <pthread.h>
struct arg_set{
char *fname;
int count;
};
struct arg_set *mail_box;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t flag = PTHREAD_COND_INITIALIZER;
int main(int ac, char *av[]){
pthread_t t1, t2;
struct arg_set args1, args2;
void *count_word(void*);
int reports_in = 0;
int total_words = 0;
if(ac != 3){
fprintf(stderr, "usage: %s file1 file2\\n", av[0]);
exit(1);
}
pthread_mutex_lock(&lock);
args1.fname = av[1];
args1.count = 0;
pthread_create(&t1, 0, count_word, (void*)&args1);
args2.fname = av[2];
args2.count = 0;
pthread_create(&t2, 0, count_word, (void*)&args2);
while(reports_in < 2){
printf("MAIN: waiting for flag to go up\\n");
pthread_cond_wait(&flag, &lock);
printf("MAIN: got the lock\\n");
printf("%7d %s\\n", mail_box->count, mail_box->fname);
total_words += mail_box->count;
if(mail_box == &args1)
pthread_join(t1, 0);
if(mail_box == &args2)
pthread_join(t2, 0);
mail_box = 0;
pthread_cond_signal(&flag);
reports_in++;
}
printf("%7d total words\\n", total_words);
}
void *count_word(void *m){
struct arg_set *args = (struct arg_set *)m;
FILE *fp;
int c, prevc = '\\0';
if((fp = fopen(args->fname, "r")) != 0){
while((c = getc(fp)) != EOF){
if(!isalnum(c) && isalnum(prevc))
args->count++;
prevc = c;
}
fclose(fp);
}else
perror(args->fname);
printf("COUNT %s: waiting to get lock\\n", args->fname);
pthread_mutex_lock(&lock);
printf("COUNT %s: got the lock\\n", args->fname);
mail_box = args;
printf("COUNT %s: raise the flag\\n", args->fname);
pthread_cond_signal(&flag);
printf("COUNT %s: unlocking box\\n", args->fname);
pthread_mutex_unlock(&lock);
return 0;
}
| 0
|
#include <pthread.h>
sem_t queue_length;
struct transaction_queue_node_t *transaction_head, *transaction_tail;
pthread_mutex_t mutex_queue = PTHREAD_MUTEX_INITIALIZER;
volatile int transaction_id;
struct transaction_queue_node_t *dequeue_transaction()
{
struct transaction_queue_node_t *node;
sem_wait(&queue_length);
pthread_mutex_lock(&mutex_queue);
node = transaction_head;
if (transaction_head == 0) {
pthread_mutex_unlock(&mutex_queue);
return 0;
} else if (transaction_head->next == 0) {
transaction_head = transaction_tail = 0;
} else {
transaction_head = transaction_head->next;
}
pthread_mutex_unlock(&mutex_queue);
return node;
}
int enqueue_transaction(struct transaction_queue_node_t *node)
{
pthread_mutex_lock(&mutex_queue);
node->next = 0;
node->id = ++transaction_id;
if (transaction_tail != 0) {
transaction_tail->next = node;
transaction_tail = node;
} else {
transaction_head = transaction_tail = node;
}
sem_post(&queue_length);
pthread_mutex_unlock(&mutex_queue);
return OK;
}
int init_transaction_queue()
{
transaction_id = 0;
transaction_head = transaction_tail = 0;
if (sem_init(&queue_length, 0, 0) != 0) {
LOG_ERROR_MESSAGE("cannot init queue_length");
return ERROR;
}
return OK;
}
int signal_transaction_queue()
{
pthread_mutex_lock(&mutex_queue);
sem_post(&queue_length);
pthread_mutex_unlock(&mutex_queue);
return OK;
}
| 1
|
#include <pthread.h>
void *barber_entry(void *ptr);
void *customer_entry(void *ptr);
pthread_mutex_t mutex;
int freeseats = 5;
int maxseats = 5;
main()
{
pthread_mutex_init(&mutex, 0);
pthread_t thread1, thread2;
int iret1, iret2;
iret1 = pthread_create( &thread1, 0, barber_entry, 0);
iret2 = pthread_create( &thread2, 0, customer_entry, 0);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
exit(0);
}
void *barber_entry(void *ptr)
{
while(1)
{
pthread_mutex_lock(&mutex);
if(freeseats < maxseats)
{
freeseats++;
printf("Cutting\\n");
printf("Customers Waiting: %d/%d\\n", 5-freeseats, 5);
}
pthread_mutex_unlock(&mutex);
}
}
void *customer_entry(void *ptr)
{
while(1)
{
pthread_mutex_lock(&mutex);
if(freeseats > 0)
{
freeseats--;
printf("Customer added to queue\\n");
printf("Customers Waiting: %d/%d\\n", 5-freeseats, 5);
}
else
{
printf("Customer turned away\\n");
}
pthread_mutex_unlock(&mutex);
}
}
| 0
|
#include <pthread.h>
struct net_args {
int id;
struct addrinfo* addrinfo;
pthread_mutex_t* lock;
pthread_cond_t* cond;
pthread_barrier_t* barrier;
int* len;
char* data;
int* ready;
};
void print_usage(FILE* fp) {
fprintf(fp, "Usage:\\n\\n");
fprintf(fp, " -h\\t\\tshow usage\\n");
fprintf(fp, " -s\\t\\tspecify server hostname\\n");
fprintf(fp, " -p\\t\\tspecify server port\\n");
fprintf(fp, " -n\\t\\tspecify number of threads(optional)\\n");
fprintf(fp, "\\n");
}
void* net(void* arg) {
struct net_args* args = (struct net_args*) arg;
int id = args->id;
struct addrinfo* res = args->addrinfo;
pthread_mutex_t* lock = args->lock;
pthread_cond_t* cond = args->cond;
pthread_barrier_t* barrier = args->barrier;
int* len = args->len;
char* data = args->data;
int* ready = args->ready;
int sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if(sockfd == -1) {
pthread_mutex_lock(lock);
fprintf(stderr, "%d: socket() failed: %s\\n", id, strerror(errno));
pthread_mutex_unlock(lock);
return 0;
}
if(connect(sockfd, res->ai_addr, res->ai_addrlen) != 0) {
pthread_mutex_lock(lock);
fprintf(stderr, "%d: connect() failed: %s\\n", id, strerror(errno));
pthread_mutex_unlock(lock);
close(sockfd);
return 0;
}
while(1) {
pthread_mutex_lock(lock);
while(!(*ready)){
pthread_cond_wait(cond, lock);
}
pthread_mutex_unlock(lock);
send(sockfd, data, *len, 0);
pthread_barrier_wait(barrier);
}
close(sockfd);
return 0;
}
int main(int argc, char* argv[]) {
int sflag = 0, pflag = 0, nflag = 0;
char* server_address = 0;
char* port = 0;
int thread_num = 0;
int opt = 0;
while((opt = getopt(argc, argv, "hs:p:n:")) != -1) {
switch(opt) {
case 'h':
print_usage(stdout);
return 0;
case 's':
sflag = 1;
server_address = optarg;
break;
case 'p':
pflag = 1;
port = optarg;
break;
case 'n':
nflag = 1;
thread_num = atoi(optarg);
break;
default:
print_usage(stderr);
return 1;
}
}
if(sflag == 0 || pflag == 0) {
print_usage(stderr);
return 1;
}
if(nflag == 0) {
thread_num = 1;
} else {
if(thread_num <= 0) {
fprintf(stderr, "the number of threads specified by -n must be >= 1\\n");
return 1;
}
}
struct addrinfo hints = {0};
struct addrinfo* res = 0;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
int ret = getaddrinfo(server_address, port, &hints, &res);
if(ret != 0) {
fprintf(stderr, "getaddrinfo(): %s\\n", gai_strerror(ret));
return 1;
}
pthread_mutex_t lock;
if(pthread_mutex_init(&lock, 0) != 0) {
fprintf(stderr, "pthread_mutex_init() failed\\n");
freeaddrinfo(res);
return 1;
}
pthread_cond_t cond;
if(pthread_cond_init(&cond, 0) != 0) {
fprintf(stderr, "pthread_cond_init() failed\\n");
freeaddrinfo(res);
pthread_mutex_destroy(&lock);
return 1;
}
pthread_barrier_t barrier;
pthread_t* net_threads = calloc(sizeof(pthread_t), thread_num);
struct net_args* nargs = calloc(sizeof(struct net_args), thread_num);
if(net_threads == 0 || nargs == 0) {
fprintf(stderr, "calloc() failed\\n");
freeaddrinfo(res);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
free(net_threads);
free(nargs);
return 1;
}
int len = 0, buffsize = 1000;
char* buffer = calloc(buffsize, 1);
if(buffer == 0) {
fprintf(stderr, "calloc() failed\\n");
freeaddrinfo(res);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
free(net_threads);
free(nargs);
return 1;
}
int i = 0, ready = 0;
int created_threads = 0;
for(i = 0; i < thread_num; i++) {
struct net_args* narg = &nargs[i];
narg->id = i;
narg->addrinfo = res;
narg->lock = &lock;
narg->cond = &cond;
narg->barrier = &barrier;
narg->len = &len;
narg->data = buffer;
narg->ready = &ready;
if(pthread_create(&net_threads[i], 0, net, &(nargs[i])) != 0) {
pthread_mutex_lock(&lock);
fprintf(stderr, "pthread_create() for %d failed: %s\\n", i, strerror(errno));
pthread_mutex_unlock(&lock);
} else {
created_threads += 1;
}
}
if(pthread_barrier_init(&barrier, 0, created_threads+1) != 0) {
fprintf(stderr, "pthread_barrier_init() failed\\n");
freeaddrinfo(res);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
free(net_threads);
free(nargs);
free(buffer);
return 1;
}
while(1) {
len = read(0, buffer, buffsize);
if(len == 0) {
fprintf(stderr, "read() reaches end of file\\n");
return 0;
} else if(len < 0) {
perror("read()");
return 1;
}
pthread_mutex_lock(&lock);
ready = 1;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&lock);
pthread_barrier_wait(&barrier);
ready = 0;
}
freeaddrinfo(res);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
free(net_threads);
free(nargs);
free(buffer);
pthread_barrier_destroy(&barrier);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
void *myfunc(void *arg)
{
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
return 0;
}
void *fork_thread(void *arg)
{
pthread_t t;
pthread_create(&t, 0, myfunc, 0);
if (fork() == 0) {
pthread_mutex_init(&mutex, 0);
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
exit(0);
}
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
wait(0);
return 0;
}
int main()
{
pthread_t t;
pthread_mutex_init(&mutex, 0);
pthread_create(&t, 0, fork_thread, 0);
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
pthread_join(t, 0);
printf("test done\\n");
return 0;
}
| 0
|
#include <pthread.h>
void *test_connect(void *arg);
int count = 0;
pthread_mutex_t lock;
char *host = 0;
int main(int argc, char *argv[]) {
host = argv[1];
pthread_t thread[12];
int i;
pthread_mutex_init(&lock, 0);
for (i = 0; i < 12; i++)
pthread_create(&thread[i], 0, test_connect, 0);
fprintf(stderr, "[%ld] xxxxxxx\\n", (long) time(0));
while (1) {
fprintf(stderr, "[%ld] count: %d \\n", (long) time(0), count);
sleep(1);
}
fprintf(stderr, "[%ld] yyyyyyy\\n", (long) time(0));
for (i = 0; i < 12; i++)
pthread_join(thread[i], 0);
return 0;
}
void *test_connect(void *arg) {
int sockfd, i;
for (i = 0; i < 5000; i++) {
{
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == sockfd) {
printf("create socket failed, errno %d\\n", errno);
exit(1);
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(host);
addr.sin_port = htons(8088);
if (-1 == connect(sockfd, (struct sockaddr *) &addr, sizeof(struct sockaddr))) {
printf("connect failed, errno %d, %m\\n", errno);
exit(1);
}
pthread_mutex_lock(&lock);
++count;
pthread_mutex_unlock(&lock);
}
}
while (1) {
}
pthread_exit(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 i;
long my_id = (long)t;
for (i=0; i < 10; i++) {
pthread_mutex_lock(&count_mutex);
count++;
if (count == 12) {
printf("inc_count(): thread %ld, count = %d Threshold reached. ",
my_id, count);
pthread_cond_signal(&count_threshold_cv);
printf("Just sent signal.\\n");
}
printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count);
pthread_mutex_unlock(&count_mutex);
sleep(1);
}
pthread_exit(0);
}
void *watch_count(void *t)
{
long my_id = (long)t;
printf("Starting watch_count(): thread %ld\\n", my_id);
pthread_mutex_lock(&count_mutex);
while (count < 12) {
printf("watch_count(): thread %ld Count= %d. Going into wait...\\n", my_id,count);
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %ld Condition signal received. Count= %d\\n", my_id,count);
printf("watch_count(): thread %ld Updating the value of count...\\n", my_id);
count += 125;
printf("watch_count(): thread %ld count now = %d.\\n", my_id, count);
}
printf("watch_count(): thread %ld Unlocking mutex.\\n", my_id);
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int i, rc;
long t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, watch_count, (void *)t1);
pthread_create(&threads[1], &attr, inc_count, (void *)t2);
pthread_create(&threads[2], &attr, inc_count, (void *)t3);
for (i = 0; i < 3; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited and joined with %d threads. Final value of count = %d. Done.\\n",
3, count);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit (0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct {
int status;
int value;
} memory;
void *consume(void *pv)
{
for (;;) {
pthread_mutex_lock(&mutex);
if (memory.status == 1) {
printf("%d\\n", memory.value);
memory.status = 0;
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_exit(0);
}
void *produce(void *pv)
{
int i = 0;
while (i++ < 100000) {
pthread_mutex_lock(&mutex);
if (memory.status == 0) {
memory.status = 1;
memory.value = memory.value + 1;
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main(void)
{
pthread_t th1, th2, th3, th4, th5;
pthread_create(&th1, 0, produce, 0);
pthread_create(&th2, 0, produce, 0);
pthread_create(&th3, 0, produce, 0);
pthread_create(&th4, 0, produce, 0);
pthread_create(&th5, 0, consume, 0);
pthread_join(th1, 0);
pthread_join(th2, 0);
pthread_join(th3, 0);
pthread_join(th4, 0);
pthread_join(th5, 0);
pthread_exit(0);
exit(0);
}
| 1
|
#include <pthread.h>
struct alarm_elem {
int seconds;
time_t alarm_time;
struct alarm_elem *link;
char message[64];
};
struct alarm_elem *alarm_list = 0;
time_t current = 0;
pthread_mutex_t alarm_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t alarm_cond = PTHREAD_COND_INITIALIZER;
void alarm_insert(struct alarm_elem *new);
void *alarm_thread(void *arg)
{
struct timespec ts;
printf("Alarm thread start\\n");
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 1000;
while (1) {
int status;
struct alarm_elem *first;
pthread_mutex_lock(&alarm_mutex);
status = pthread_cond_timedwait(&alarm_cond, &alarm_mutex, &ts);
printf("alarm_thread: unblocked");
if (status == ETIMEDOUT) {
printf(" by timeout\\n");
struct alarm_elem **iter, *next;
for (iter = &alarm_list; *iter;) {
next = (*iter)->link;
if ((*iter)->alarm_time > time(0))
break;
printf("Alarm: (%d) %s\\n", (int)(*iter)->seconds, (*iter)->message);
free(*iter);
*iter = next;
}
} else {
printf(" by signal\\n");
}
first = alarm_list;
pthread_mutex_unlock(&alarm_mutex);
printf("New alarm check.. \\n");
if (first == 0) {
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 1000;
} else {
clock_gettime(CLOCK_REALTIME, &ts);
printf("New alarm detect: \\n");
printf(" now %d, alarm %d\\n", ts.tv_sec, first->alarm_time);
ts.tv_sec = first->alarm_time;
}
printf("new alarm time %d\\n", ts.tv_sec);
}
pthread_exit(0);
}
int main()
{
pthread_t alarm_thread_pid;
pthread_create(&alarm_thread_pid, 0, alarm_thread, 0);
while (1) {
struct alarm_elem *new_alarm = 0;
new_alarm = (struct alarm_elem*)calloc(1, sizeof (struct alarm_elem));
printf("Alarm > ");
scanf("%d %64[^\\n]", (int*)&new_alarm->seconds, new_alarm->message);
new_alarm->alarm_time = time(0) + new_alarm->seconds;
printf("New alarm, apoch %u\\n", (unsigned)new_alarm->alarm_time);
pthread_mutex_lock(&alarm_mutex);
alarm_insert(new_alarm);
pthread_mutex_unlock(&alarm_mutex);
pthread_cond_signal(&alarm_cond);
}
return 0;
}
void alarm_insert(struct alarm_elem *new)
{
struct alarm_elem **next;
next = &alarm_list;
while (*next) {
if (new->alarm_time < (*next)->alarm_time)
break;
next = &(*next)->link;
}
new->link = *next;
*next = new;
next = &alarm_list;
while (*next) {
printf("(%d) %s -> ", (int)(*next)->alarm_time, (*next)->message);
next = &(*next)->link;
}
printf("end\\n");
}
| 0
|
#include <pthread.h>
enum memmodel
{
MEMMODEL_RELAXED = 0,
MEMMODEL_CONSUME = 1,
MEMMODEL_ACQUIRE = 2,
MEMMODEL_RELEASE = 3,
MEMMODEL_ACQ_REL = 4,
MEMMODEL_SEQ_CST = 5
};
inline static void mysync(int id, int volatile * b){
if(id == 0) {
*b = 1;
} else {
while(*b == 0);
}
}
int main(void){
int core[48] = {0};
int a [48 / 2] = {0};
int b [48 / 2] = {0};
int c [48 / 2] = {0};
int r1[10000][48 / 2] = {{0}};
int r2[10000][48 / 2] = {{0}};
pthread_mutex_t mutex1;
pthread_mutex_t mutex2;
pthread_mutex_init(&mutex1, 0);
pthread_mutex_init(&mutex2, 0);
{
core[omp_get_thread_num()] = sched_getcpu();
for(int i = 0; i < 10000; i++){
if (omp_get_thread_num() % 2 == 0)
{
int id = omp_get_thread_num() / 2;
mysync(0, &(c[id]));
pthread_mutex_lock(&mutex1);
a[id] = 1;
pthread_mutex_unlock(&mutex1);
r1[i][id] = b[id];
}
else {
int id = (omp_get_thread_num() - 1) / 2;
mysync(1, &(c[id]));
pthread_mutex_lock(&mutex1);
b[id] = 1;
pthread_mutex_unlock(&mutex1);
r2[i][id] = a[id];
}
}
}
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
printf("Cores used: ");
for(int i = 0; i < 48; i++)
printf(" %d", core[i]);
printf("\\n");
for(int i = 0; i < 10000; i++)
for(int j = 0; j < 48 / 2; j++)
printf("r1 = %d, r2 = %d\\n", r1[i][j], r2[i][j]);
return 0;
}
| 1
|
#include <pthread.h>
void *password_comparer(void *thread_arg) {
struct thread_data *t_data;
struct crypt_data *c_data;
int comp_len, i;
ssize_t read = 0;
char *password, *result;
pid_t tid = syscall(SYS_gettid);
t_data = (struct thread_data *) thread_arg;
c_data = t_data->c_data;
c_data->initialized = 0;
pthread_mutex_lock(&mtx_manager);
pthread_cond_signal(&changed_num_threads);
pthread_mutex_unlock(&mtx_manager);
pthread_rwlock_rdlock(&pass_lock);
while (shared_data.password == 0) {
pthread_rwlock_unlock(&pass_lock);
pthread_mutex_lock(&mtx_reader);
while (shared_data.line == 0) {
pthread_cond_signal(&cnd_r_pass);
pthread_cond_wait(&cnd_p_pass, &mtx_reader);
pthread_rwlock_rdlock(&pass_lock);
if (shared_data.password != 0) {
pthread_mutex_unlock(&mtx_reader);
goto exit;
}
pthread_rwlock_unlock(&pass_lock);
}
pthread_mutex_lock(&mtx_manager);
if (shared_data.num_threads > t_data->thread_id) {
pthread_mutex_unlock(&mtx_manager);
password = shared_data.line;
read = shared_data.read;
shared_data.line = 0;
pthread_cond_signal(&cnd_r_pass);
pthread_mutex_unlock(&mtx_reader);
password[read - 1] = '\\0';
result = crypt_r(password, t_data->spassword, c_data);
for (i = 0, comp_len = 0; result[i] == t_data->spassword[i]; i++)
if (result[i] == '\\0')
comp_len = 1;
if (comp_len) {
pthread_rwlock_wrlock(&pass_lock);
shared_data.password = password;
for (comp_len = 0; result[comp_len] != '\\0'; comp_len++);
shared_data.hash = malloc((comp_len + 1) * sizeof(char));
for (i = 0; i < comp_len+1; i++)
shared_data.hash[i] = result[i];
pthread_rwlock_unlock(&pass_lock);
pthread_mutex_lock(&mtx_comparer);
pthread_cond_broadcast(&done);
pthread_mutex_unlock(&mtx_comparer);
} else free(password);
pthread_rwlock_wrlock(&c_proc_lock);
shared_data.pass_proced_c++;
pthread_rwlock_unlock(&c_proc_lock);
} else {
pthread_mutex_unlock(&mtx_reader);
pthread_cond_signal(&changed_num_threads);
pthread_mutex_unlock(&mtx_manager);
pthread_mutex_lock(&mtx_comparer_hold);
pthread_cond_wait(&hold_breaker, &mtx_comparer_hold);
pthread_mutex_unlock(&mtx_comparer_hold);
pthread_mutex_lock(&mtx_manager);
t_data->thread_id = shared_data.num_threads - 1;
pthread_cond_signal(&changed_num_threads);
pthread_mutex_unlock(&mtx_manager);
}
pthread_rwlock_rdlock(&pass_lock);
}
exit:
pthread_rwlock_unlock(&pass_lock);
pthread_mutex_lock(&mtx_manager);
pthread_cond_signal(&changed_num_threads);
pthread_mutex_unlock(&mtx_manager);
free(c_data);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
void *dinner_order(void *ph);
void dinner_start();
{
int status;
const char *name;
pthread_mutex_t *fork_left, *fork_right;
pthread_t thread;
}Philos;
int main()
{
dinner_start();
return 0;
}
void dinner_start()
{
int i;
int fail_attemp;
const char *names[] = { "Sam", "Yi", "Lawrence", "Kevin", "Flash" };
Philos *phil;
pthread_mutex_t forks[5];
Philos philosophers[5];
for (i = 0; i < 5; i++)
{
fail_attemp = pthread_mutex_init(&forks[i], 0);
if (fail_attemp)
{
printf("Error: fail to initialize mutexe.");
exit(1);
}
}
for (i = 0; i < 5; i++)
{
phil = &philosophers[i];
phil->name = names[i];
phil->fork_left = &forks[i];
phil->fork_right = &forks[(i + 1) % 5];
phil->status = pthread_create( &phil->thread, 0, dinner_order, phil);
}
for(i = 0; i < 5; i++)
{
phil = &philosophers[i];
if ( !phil->status && pthread_join( phil->thread, 0) )
{
printf("Error: fail to join thread %s", phil->name);
exit(1);
}
}
}
void *dinner_order(void *ph)
{
int fail_attemp;
int attemp = 2;
Philos *phil = (Philos*)ph;
pthread_mutex_t *fork_left, *fork_right;
pthread_mutex_t *temp;
while (1)
{
printf("%s is thinking\\n", phil->name);
sleep( 1 + rand()%20);
fork_left = phil->fork_left;
fork_right = phil->fork_right;
printf("%s get fork\\n", phil->name);
while(fail_attemp)
{
fail_attemp = pthread_mutex_lock( fork_left);
fail_attemp = (attemp > 0) ? pthread_mutex_trylock(fork_right) : pthread_mutex_lock(fork_right);
if (fail_attemp)
{
pthread_mutex_unlock( fork_left);
temp = fork_left;
fork_left = fork_right;
fork_right = temp;
attemp -= 1;
}
}
if (!fail_attemp)
{
printf("%s is eating\\n", phil->name);
sleep( 2 + rand() % 9);
pthread_mutex_unlock( fork_right);
pthread_mutex_unlock( fork_left);
printf("%s put fork\\n", phil->name);
}
}
return 0;
}
| 1
|
#include <pthread.h>
void*rightCounter();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int rightcounter = 0;
void*leftCounter();
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
int leftcounter = 0 ;
int right[]={1,2,2,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0};
int left[]={1,2,2,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0};
int rright[]={-1};
int lleft[]={-1};
bool L = 0;
bool R = 0;
bool flagr = 1;
bool flagl = 1;
bool FLAG = 1;
int q = 0;
int main()
{
pthread_t thread1, thread2;
int rc1, rc2;
int counter =0;
int b = 0; int c=0;
int d=0;
bool REJECT = 0;
int reject[sizeof(right)/sizeof(right[0])];
int good[2*sizeof(right)/sizeof(right[0])];
printf("size of good %lu\\n",sizeof(good)/sizeof(good[0]));
while(FLAG){
if((pthread_create(&thread1, 0, &rightCounter, 0)))
{
printf("Thread creation failed: %d\\n", rc1);
}
if((pthread_create(&thread2, 0, &leftCounter,0)))
{
printf("Thread creation failed: %d\\n",rc2);
}
printf("in comparision\\n");
pthread_join(thread1, 0);
pthread_join(thread2, 0);
if(rright[0]==lleft[0]){
good[c]=rright[0];
printf("%d added to good from right\\n",rright[0]);
c++;
good[c]=lleft[0];
printf("%d added to good from left\\n",lleft[0]);
c++;
}else{
printf("%d from right is not equal to %d from left\\n",rright[0],lleft[0]);
reject[d]=rright[0];
printf("%d added to reject from right\\n",rright[0]);
d++;
reject[d]=lleft[0];
printf("%d added to rejct from left\\n",lleft[0]);
d++;
REJECT = 1;
}
flagr=1;
flagl=1;
rright[0]=-1;
R=0;
lleft[0]=-1;
L=0;
q++;
b++;
if(b >= sizeof(right)/sizeof(right[0])){
FLAG = 0;
printf("COMPLETE\\n");
printf("Reject = %s\\n",REJECT ? "true" : "false");
}
}
}
void*rightCounter()
{
pthread_mutex_lock(&mutex1);
while(flagr){
if(rright[0] < 0 && R == 0){
rright[0]=right[q];
flagr = 0;
R=1;
}else{
flagr = 1;
}
}
pthread_mutex_unlock(&mutex1);
return 0;
}
void*leftCounter()
{
pthread_mutex_lock(&mutex1);
while(flagl){
if(lleft[0] < 0 && L == 0){
lleft[0]=left[q];
flagl = 0;
L=1;
}else{
flagl = 1;
}
}
pthread_mutex_unlock(&mutex1);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t e1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t e2 = PTHREAD_COND_INITIALIZER;
void* behav1 (void *args)
{
pthread_mutex_lock (&mutex1);
pthread_cond_broadcast (&e1);
fprintf (stdout,"broadcast e1\\n");
pthread_mutex_unlock (&mutex1);
pthread_mutex_lock (&mutex2);
fprintf (stdout,"wait e2\\n");
pthread_cond_wait (&e2,&mutex2);
fprintf (stdout,"receive e2\\n");
pthread_mutex_unlock (&mutex2);
fprintf (stdout,"end of behav1\\n");
return 0;
}
void* behav2 (void *args)
{
pthread_mutex_lock (&mutex1);
fprintf (stdout,"wait e1\\n");
pthread_cond_wait (&e1,&mutex1);
fprintf (stdout,"receive e1\\n");
pthread_mutex_unlock (&mutex1);
pthread_mutex_lock (&mutex2);
pthread_cond_broadcast (&e2);
fprintf (stdout,"broadcast e2\\n");
pthread_mutex_unlock (&mutex2);
fprintf (stdout,"end of behav2\\n");
return 0;
}
int main(void)
{
int c, *cell = &c;
pthread_t th1, th2;
pthread_create (&th1,0,behav1,0);
pthread_create (&th2,0,behav2,0);
pthread_join(th1,(void**)&cell);
pthread_join(th2,(void**)&cell);
fprintf (stdout,"exit\\n");
exit (0);
}
| 1
|
#include <pthread.h>
void
pthread_create_(pthread_t * thread, const pthread_attr_t * attr,
void * start_routine, void * arg)
{
if ((pthread_create(thread, attr, start_routine, arg)) != 0) {
fprintf(stderr, "[ERROR] Pthread creating error\\n");
exit(1);
}
}
void
pthread_join_(pthread_t thread, void ** retval)
{
if ((pthread_join(thread, retval)) != 0) {
fprintf(stderr, "[ERROR] Pthread joining error\\n");
exit(1);
}
}
void
pthread_mutex_init_(pthread_mutex_t * mutex, pthread_mutexattr_t * attr)
{
if ((pthread_mutex_init(mutex, attr)) != 0) {
fprintf(stderr, "[ERROR] Mutex initialization error.\\n");
exit(1);
}
}
void
pthread_mutex_lock_(pthread_mutex_t * mutex)
{
if ((pthread_mutex_lock(mutex)) != 0) {
fprintf(stderr, "[ERROR] Mutex locking error\\n");
exit(1);
}
}
void
pthread_mutex_unlock_(pthread_mutex_t * mutex)
{
if ((pthread_mutex_unlock(mutex)) != 0) {
fprintf(stderr, "[ERROR] Mutex unlocking error\\n");
exit(1);
}
}
void
pthread_mutex_destroy_(pthread_mutex_t * mutex)
{
if ((pthread_mutex_destroy(mutex)) != 0) {
fprintf(stderr, "[ERROR] Mutex destroying error\\n");
exit(1);
}
}
void
sem_init_(sem_t * sem, int shared, unsigned int value)
{
if ((sem_init(sem, shared, value)) == -1) {
perror("[ERROR] Semaphore initialization error.");
exit(1);
}
}
void
sem_wait_(sem_t * sem)
{
if ((sem_wait(sem)) == -1) {
perror("[ERROR] Semaphore wait error.");
exit(1);
}
}
void
sem_post_(sem_t * sem)
{
if ((sem_post(sem)) == -1) {
perror("[ERROR] Semaphore post error.");
exit(1);
}
}
void
sem_destroy_(sem_t * sem)
{
if ((sem_destroy(sem)) == -1) {
perror("[ERROR] Semaphore destroying error.");
exit(1);
}
}
void
pthread_cond_init_(pthread_cond_t * cond, pthread_condattr_t * attr)
{
if ((pthread_cond_init(cond, attr)) != 0) {
fprintf(stderr, "[ERROR] cond initialization error.\\n");
exit(1);
}
}
void
pthread_cond_wait_(pthread_cond_t * cond, pthread_mutex_t * mutex)
{
if ((pthread_cond_wait(cond, mutex)) != 0) {
fprintf(stderr, "[ERROR] cond wait error\\n");
exit(1);
}
}
void
pthread_cond_signal_(pthread_cond_t * cond)
{
if ((pthread_cond_signal(cond)) != 0) {
fprintf(stderr, "[ERROR] cond signal error\\n");
exit(1);
}
}
void
pthread_cond_destroy_(pthread_cond_t * cond)
{
if ((pthread_cond_destroy(cond)) != 0) {
fprintf(stderr, "[ERROR] cond destroying error\\n");
exit(1);
}
}
| 0
|
#include <pthread.h>
char str[50];
pthread_mutex_t mutex;
void * write_thread (void *p)
{
printf("\\n In Write thread\\n");
if(pthread_mutex_lock(&mutex)==0)
{
printf(" Enter A string : ");
fgets(str,25,stdin);
printf("\\n Write job is over\\n");
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void * read_thread(void *p)
{
printf("\\n In Read thread \\n");
if(pthread_mutex_unlock(&mutex)==EPERM)
printf("\\n Error :: Cannot unlock mutex owned by other thread\\n");
if(pthread_mutex_lock(&mutex)==0)
{
printf(" %s \\n",str);
pthread_mutex_unlock(&mutex);
}
printf(" Read job is over\\n");
pthread_exit(0);
}
int main ()
{
pthread_t tid1,tid2;
pthread_mutexattr_t attr;
int rv;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_ERRORCHECK);
pthread_mutex_init(&mutex,&attr);
rv = pthread_create(&tid1, 0, write_thread, 0);
if(rv)
puts("Failed to create thread");
rv = pthread_create(&tid2, 0, read_thread, 0);
if(rv)
puts("Failed to create thread");
pthread_join(tid1,0);
pthread_join(tid2,0);
puts(" Exit Main");
return 0;
}
| 1
|
#include <pthread.h>
pthread_t thread[2];
pthread_mutex_t mut;
int number=0, i;
void *thread1()
{
printf("thread 1 start\\n");
for(i=0;i< 10;i++)
{
printf("thread 1[%d]=%d \\n",i, number);
pthread_mutex_lock(&mut);
number++;
pthread_mutex_unlock(&mut);
sleep(2);
}
printf("thread 1 finished\\n");
pthread_exit(0);
}
void *thread2()
{
printf("thread 2 start\\n");
for(i=0;i<10;i++)
{
printf("thread 2[%d]=%d \\n",i, number);
pthread_mutex_lock(&mut);
number++;
pthread_mutex_unlock(&mut);
sleep(3);
}
printf("thread 2 finished\\n");
pthread_exit(0);
}
void thread_create(void)
{
int temp=0;
memset(&thread, 0, sizeof(thread));
if((temp=pthread_create(&thread[0], 0, thread1, 0)) != 0)
{
printf("thread 1 create fail\\n");
}
else
{
printf("thread 1 created\\n");
}
if((temp=pthread_create(&thread[1], 0, thread2, 0)) != 0)
{
printf("thread 2 fail\\n");
}
else
{
printf("thread 2 created\\n");
}
}
void thread_wait(void)
{
if(thread[0]!=0)
{
pthread_join(thread[0],0);
printf("thread 1 finished\\n");
}
if(thread[1]!=0)
{
pthread_join(thread[1],0);
printf("thread 2 finished\\n");
}
}
int main()
{
pthread_mutex_init(&mut,0);
printf("thread main\\n");
thread_create();
printf("thread main wait sub thread finish\\n");
thread_wait();
return 0;
}
| 0
|
#include <pthread.h>
int q[2];
int qsiz;
pthread_mutex_t mq;
void queue_init ()
{
pthread_mutex_init (&mq, 0);
qsiz = 0;
}
void queue_insert (int x)
{
int done = 0;
printf ("prod: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz < 2)
{
done = 1;
q[qsiz] = x;
qsiz++;
}
pthread_mutex_unlock (&mq);
}
}
int queue_extract ()
{
int done = 0;
int x = -1, i = 0;
printf ("consumer: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz > 0)
{
done = 1;
x = q[0];
qsiz--;
for (i = 0; i < qsiz; i++) q[i] = q[i+1];
__VERIFIER_assert (qsiz < 2);
q[qsiz] = 0;
}
pthread_mutex_unlock (&mq);
}
return x;
}
void swap (int *t, int i, int j)
{
int aux;
aux = t[i];
t[i] = t[j];
t[j] = aux;
}
int findmaxidx (int *t, int count)
{
int i, mx;
mx = 0;
for (i = 1; i < count; i++)
{
if (t[i] > t[mx]) mx = i;
}
__VERIFIER_assert (mx >= 0);
__VERIFIER_assert (mx < count);
t[mx] = -t[mx];
return mx;
}
int source[4];
int sorted[4];
void producer ()
{
int i, idx;
for (i = 0; i < 4; i++)
{
idx = findmaxidx (source, 4);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 4);
queue_insert (idx);
}
}
void consumer ()
{
int i, idx;
for (i = 0; i < 4; i++)
{
idx = queue_extract ();
sorted[i] = idx;
printf ("m: i %d sorted = %d\\n", i, sorted[i]);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 4);
}
}
void *thread (void * arg)
{
(void) arg;
producer ();
return 0;
}
int main ()
{
pthread_t t;
int i;
__libc_init_poet ();
for (i = 0; i < 4; i++)
{
source[i] = __VERIFIER_nondet_int(0,20);
printf ("m: init i %d source = %d\\n", i, source[i]);
__VERIFIER_assert (source[i] >= 0);
}
queue_init ();
pthread_create (&t, 0, thread, 0);
consumer ();
pthread_join (t, 0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_t thread_id;
int client_fd;
struct thread_node *next;
} thread_node;
static int running;
thread_node *head;
int start_index;
int sock_fd;
FILE *editor_fp;
struct addrinfo hints, *result;
pthread_mutex_t mutex;
char text[1048576];
void sync_send() {
thread_node *curr = head->next;
thread_node *next = 0;
while (curr != 0) {
next = curr->next;
printf("sending message to %lu\\n", curr->thread_id);
printf("next is NULL: %d\\n", next == 0);
if ((send(curr->client_fd, text, strlen(text), 0)) == -1) {
printf("Failed to send result to %d\\n", curr->client_fd);
}
curr = next;
}
}
void *client_interaction(void *client_fd) {
int client = *((int *) client_fd);
size_t len;
char buffer[1000];
while (1) {
if ((len = read(client, buffer, 1000 - 1)) == -1) {
perror("recv");
exit(1);
}
else if (len == 0) {
printf("%d: Connection closed\\n", client);
pthread_exit(0);
break;
}
buffer[len] = '\\0';
pthread_mutex_lock(&mutex);
fprintf(editor_fp, "%s", buffer);
int curr = start_index;
for (; curr < start_index + strlen(buffer); curr++)
text[curr] = buffer[curr - start_index];
start_index = strlen(text);
sync_send();
pthread_mutex_unlock(&mutex);
printf("%d - Msg sent: %s\\n", client, text);
}
}
void sigint_handler() {
printf("Cleaning up before exiting...\\n");
running = 0;
thread_node *curr = head;
thread_node *next = 0;
while (curr != 0) {
next = curr->next;
if (curr->client_fd != -1)
close(curr->client_fd);
free(curr);
curr = next;
}
free(result);
close(sock_fd);
fclose(editor_fp);
pthread_mutex_destroy(&mutex);
exit(0);
}
int main(int argc, char **argv) {
start_index = 0;
text[0] = '\\0';
pthread_mutex_init(&mutex, 0);
editor_fp = fopen("temp.txt", "a+");
running = 1;
signal(SIGINT, sigint_handler);
head = malloc(sizeof(thread_node));
head->next = 0;
head->thread_id = pthread_self();
head->client_fd = -1;
int s;
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
s = getaddrinfo(0, "5555", &hints, &result);
if (s != 0) {
fprintf(stderr, "getaddrinfo: %s\\n", gai_strerror(s));
exit(1);
}
int optval = 1;
setsockopt(sock_fd, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval));
if (bind(sock_fd, result->ai_addr, result->ai_addrlen) != 0) {
perror("bind()");
exit(1);
}
if (listen(sock_fd, 10) != 0) {
perror("listen()");
exit(1);
}
struct sockaddr_in *result_addr = (struct sockaddr_in *) result->ai_addr;
printf("Listening on file descriptor %d, port %d\\n", sock_fd, ntohs(result_addr->sin_port));
int client_fd;
thread_node *curr_node = head;
while (running) {
if ((client_fd = accept(sock_fd, 0, 0)) == -1) {
perror("accept_error");
exit(1);
} else {
pthread_t new_user;
if (pthread_create(&new_user, 0, client_interaction, &client_fd)) {
printf("Connection failed with client_fd=%d\\n", client_fd);
} else {
thread_node *new_node = malloc(sizeof(thread_node));
new_node->next = 0;
new_node->thread_id = new_user;
new_node->client_fd = client_fd;
curr_node->next = new_node;
curr_node = new_node;
printf("Connection made: client_fd=%d, thread:%lu\\n", client_fd, new_user);
}
}
}
if (head != 0)
sigint_handler();
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
struct {
pthread_mutex_t mutex;
pthread_cond_t cond;
int id;
int parameter;
} tp = {PTHREAD_MUTEX_INITIALIZER,PTHREAD_COND_INITIALIZER,0,0};
char services[25][50] = {
"AddTwoNumbers","SubtractTwoNumbers","MultiplyTwoNumbers","DivideTwoNumbers","SquarRoot","Square","Area","Volume","Perimeter",
"Circumference","SurfaceArea","Integrate","Differentiate","Power","Logarithm","StringLength","Encrypt","Decrypt","EdgeDetection",
"FFT","RayTracing","VolumRendering","ZBuffer","TextureMapping","MotionBlurr"};
void *client_handler(void *arg);
void *server_handler(void *arg);
int generate_random(int limit);
int c = 0,p;
int **tuple;
int main(int argc, char const *argv[]) {
int i;
p = generate_random(10);
printf("Thread Number : %d\\n",p);
tuple = (int**)malloc(p*sizeof(int*));
pthread_t client[p], server;
for (int i = 0; i < p; ++i) {
pthread_create(&client[i], 0, client_handler, &c);
sleep(1);
}
pthread_create(&server, 0, server_handler, &c);
for (int i = 0; i < p; ++i) {
pthread_join(client[i], 0);
}
pthread_join(server, 0);
free(tuple);
return 0;
}
void *server_handler(void *arg){
int n = 0;
for (; ;) {
pthread_mutex_lock(&tp.mutex);
if (c!=0) {
printf("\\nServer:- tuple <%d %s %d> found for client[%d]\\n",tuple[n][0],services[tuple[n][1]-1],tuple[n][2],n+1);
c -= 1;
pthread_cond_signal(&tp.cond);
}
++n;
pthread_mutex_unlock(&tp.mutex);
sleep(1);
}
}
void *client_handler(void *arg) {
int n = *((int *)arg);
tuple[n] = (int*)malloc(3*sizeof(int));
pthread_mutex_lock(&mutex1);
tp.id += 1;
tuple[n][0] = tp.id;
tuple[n][1] = generate_random(25);
tuple[n][2] = generate_random(3);
n = n+1;
++c;
pthread_mutex_unlock(&mutex1);
pthread_mutex_lock(&tp.mutex);
while(c!=0) {
pthread_cond_wait(&tp.cond, &tp.mutex);
printf("client[%d]:- tuples <%d %s %d> has been provided.\\n",n,tuple[n-1][0],services[tuple[n-1][1]-1],tuple[n-1][2]);
}
pthread_mutex_unlock(&tp.mutex);
}
int generate_random(int limit) {
int r,i;
time_t t;
srand ( time(0) );
r = 0;
r = rand()%limit+1;
return r;
}
| 1
|
#include <pthread.h>
void *display_task(void *arg)
{
struct task_par *tp;
tp = (struct task_par *)arg;
double dt_p = 0 , dt_v = 0, dt_t = 0;
int p, b;
double t = 0;
set_period(tp);
while(1)
{
pthread_mutex_lock(&mux_page);
p = page;
b = but;
pthread_mutex_unlock(&mux_page);
if(b == 0)
{
dt_p = 0;
dt_v = 0;
dt_t = 0;
}
if(p == WORK_PAGE)
{
pthread_mutex_lock(&mux_p[n_p]);
geo_motor(ctrmpx, ctrmpy, out_ctr_p[n_p]);
pthread_mutex_unlock(&mux_p[n_p]);
pthread_mutex_lock(&mux_v[n_v]);
geo_motor(ctrmvx, ctrmvy, (long double)(out_ctr_v[n_v]*t));
pthread_mutex_unlock(&mux_v[n_v]);
pthread_mutex_lock(&mux_t[n_t]);
geo_motor(ctrmtx, ctrmty, out_ctr_t[n_t]/motor_t[n_t].b);
pthread_mutex_unlock(&mux_t[n_t]);
}
if(b == 1)
{
trends_pos(&dt_p, tp);
trends_vel(&dt_v, tp);
trends_tor(&dt_t, tp);
}
t += GRAPHIC_PERIOD*0.001;
if(deadline_miss(tp))
{
printf("Missed deadline of graphical thread!!\\n");
}
wait_for_period(tp);
}
}
| 0
|
#include <pthread.h>
int valid;
pthread_cond_t cv;
pthread_mutex_t mtx;
int predicate;
int barrier_val;
int blocked_threads;
} barrier_t;
pthread_mutex_t barrier_init_mutex = PTHREAD_MUTEX_INITIALIZER;
int barrier_init(barrier_t *b, int val)
{
int rv;
if ((rv=pthread_mutex_lock(&barrier_init_mutex))!=0)
return (rv);
if (b->valid == 546731) {
if ((rv=pthread_mutex_lock(&b->mtx))!=0){
pthread_mutex_unlock(&barrier_init_mutex);
return(rv);
}
if (b->blocked_threads !=0 ){
pthread_mutex_unlock(&b->mtx);
pthread_mutex_unlock(&barrier_init_mutex);
return(EBUSY);
}
b->barrier_val=val;
if ((rv=pthread_mutex_unlock(&b->mtx))!=0) {
pthread_mutex_unlock(&barrier_init_mutex);
return(rv);
}
}else {
if ((rv=pthread_mutex_init(&b->mtx, 0))!=0)
return (rv);
if ((rv=pthread_cond_init(&b->cv, 0)) !=0) {
pthread_mutex_unlock(&barrier_init_mutex);
return (rv);
}
b->barrier_val=val;
b->blocked_threads =0;
b->predicate =0;
b->valid = 546731;
}
if ((rv=pthread_mutex_unlock(&barrier_init_mutex))!=0)
return (rv);
return (0);
}
int barrier_wait(barrier_t *b)
{
int rv, predicate;
if (b->valid != 546731)
return(EINVAL);
if ((rv=pthread_mutex_lock(&b->mtx)) != 0)
return (rv);
predicate = b->predicate;
b->blocked_threads++;
if (b->blocked_threads == b->barrier_val) {
b->predicate += 1;
b->blocked_threads = 0;
if ((rv=pthread_cond_broadcast(&b->cv))!= 0) {
pthread_mutex_unlock(&b->mtx);
return(rv);
}
}else{
while (b->predicate == predicate){
rv = pthread_cond_wait(&b->cv, &b->mtx);
if ((rv!=0)&&(rv!=EINTR)){
pthread_mutex_unlock(&b->mtx);
return(rv);
}
}
}
if ((rv=pthread_mutex_unlock(&b->mtx))!=0)
return(rv);
return(0);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER;
void output_init()
{
return;
}
void output( char * string, ... )
{
va_list ap;
char *ts="[??:??:??]";
struct tm * now;
time_t nw;
pthread_mutex_lock(&m_trace);
nw = time(0);
now = localtime(&nw);
if (now == 0)
printf(ts);
else
printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec);
__builtin_va_start((ap));
vprintf(string, ap);
;
pthread_mutex_unlock(&m_trace);
}
void output_fini()
{
return;
}
| 0
|
#include <pthread.h>
char work_area[1024];
int time2exit = 0;
pthread_mutex_t work_mutex;
void *slave(void *arg)
{
sleep(1);
pthread_mutex_lock(&work_mutex);
while (strncmp("end", work_area, 3) != 0)
{
printf("you input %d characters\\n", strlen(work_area) - 1);
work_area[0] = '\\0';
pthread_mutex_unlock(&work_mutex);
sleep(1);
pthread_mutex_lock(&work_mutex);
while (work_area[0] == '\\0')
{
pthread_mutex_unlock(&work_mutex);
sleep(1);
pthread_mutex_lock(&work_mutex);
}
}
time2exit = 1;
work_area[0] = '\\0';
pthread_mutex_unlock(&work_mutex);
pthread_exit(0);
}
int main() {
int res;
pthread_t a_thread;
void *thread_result;
res = pthread_mutex_init(&work_mutex, 0);
if (res != 0) {
perror("mutex initialized failed");
exit(1);
}
res = pthread_create(&a_thread, 0, slave, 0);
if (res != 0) {
perror("pthread creation failed");
exit(1);
}
pthread_mutex_lock(&work_mutex);
printf("input some text, enter 'end' to finish\\n");
while (!time2exit) {
fgets(work_area, 1024, stdin);
pthread_mutex_unlock(&work_mutex);
while (1) {
pthread_mutex_lock(&work_mutex);
if (work_area[0] != '\\0') {
pthread_mutex_unlock(&work_mutex);
sleep(1);
} else {
break;
}
}
}
pthread_mutex_unlock(&work_mutex);
printf("waiting for thread to finish...\\n");
res = pthread_join(a_thread, &thread_result);
if (res != 0) {
perror("pthread join failed");
exit(1);
}
printf("thread joined\\n");
pthread_mutex_destroy(&work_mutex);
printf("thread exited, main exited.\\n");
exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
void *fun1() {
for (int i = 0 ; i < 1000000 ; i++) {
pthread_mutex_lock(&lock);
pthread_mutex_unlock(&lock);
}
return 0;
}
void *fun2() {
for (int i = 0 ; i < 1000000 ; i++) {
pthread_mutex_lock(&lock);
pthread_mutex_unlock(&lock);
}
return 0;
}
int main(int argc, char *argv[]) {
pthread_t t1, t2;
struct timespec start, end;
struct timespec total;
struct timeval uStart, uEnd;
struct timeval uTotal;
clock_gettime(CLOCK_REALTIME, &start);
gettimeofday(&uStart, 0);
pthread_create(&t1, 0, fun1, 0);
pthread_create(&t2, 0, fun2, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
clock_gettime(CLOCK_REALTIME, &end);
gettimeofday(&uEnd, 0);
if ((end.tv_nsec - start.tv_nsec) < 0) {
total.tv_sec = end.tv_sec - start.tv_sec - 1;
total.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
} else {
total.tv_sec = end.tv_sec - start.tv_sec;
total.tv_nsec = end.tv_nsec - start.tv_nsec;
}
if ((uEnd.tv_usec - uStart.tv_usec) < 0) {
uTotal.tv_sec = uEnd.tv_sec - uStart.tv_sec - 1;
uTotal.tv_usec = 1000000 + uEnd.tv_usec - uStart.tv_usec;
} else {
uTotal.tv_sec = uEnd.tv_sec - uStart.tv_sec;
uTotal.tv_usec = uEnd.tv_usec - uStart.tv_usec;
}
long mTotal = uTotal.tv_usec / 1000;
printf("second=%ld\\n", total.tv_sec);
printf("millisecond=%ld\\n", mTotal);
printf("microsecond=%ld\\n", uTotal.tv_usec);
printf("nanosecond=%ld\\n", total.tv_nsec);
printf("\\n");
return 0;
}
| 0
|
#include <pthread.h>
void oo_wqlock_init(struct oo_wqlock* wql)
{
wql->lock = 0;
pthread_mutex_init(&wql->mutex, 0);
pthread_cond_init(&wql->cond, 0);
}
void oo_wqlock_lock_slow(struct oo_wqlock* wql)
{
pthread_mutex_lock(&wql->mutex);
while( 1 ) {
uintptr_t v = wql->lock;
if( v == 0 ) {
if( ci_cas_uintptr_succeed(&wql->lock, 0, OO_WQLOCK_LOCKED) )
break;
}
else {
if( ! (v & OO_WQLOCK_NEED_WAKE) )
ci_cas_uintptr_succeed(&wql->lock, v, v | OO_WQLOCK_NEED_WAKE);
else
pthread_cond_wait(&wql->cond, &wql->mutex);
}
}
pthread_mutex_unlock(&wql->mutex);
}
void oo_wqlock_unlock_slow(struct oo_wqlock* wql,
void (*cb)(void* cb_arg, void* work),
void* cb_arg)
{
uintptr_t v;
while( 1 ) {
v = wql->lock;
assert(v & OO_WQLOCK_LOCKED);
if( (v & OO_WQLOCK_WORK_BITS) == 0 )
if( ci_cas_uintptr_succeed(&wql->lock, v, 0) )
break;
oo_wqlock_try_drain_work(wql, cb, cb_arg);
}
if( v & OO_WQLOCK_NEED_WAKE ) {
pthread_mutex_lock(&wql->mutex);
pthread_mutex_unlock(&wql->mutex);
pthread_cond_broadcast(&wql->cond);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock[5];
int sum = 40;
void *fun(void *p)
{
int n = *(int *)p;
while(1)
{
sleep(1);
if(n == 1)
{
if(sum==0)
{
printf("eatting finished\\n");
break;
}
pthread_mutex_lock(&lock[4]);
printf("the P1 get the chopstick 5 \\n");
pthread_mutex_lock(&lock[0]);
printf("the P1 get the chopstick 1 \\n");
sum--;
usleep(rand() % 10);
pthread_mutex_unlock(&lock[4]);
pthread_mutex_unlock(&lock[0]);
printf("the P1 release the chopstick 5 and 1 \\n");
if(sum==0)
{
printf("eatting finished\\n");
break;
exit(1);
}
}
else
{
if(sum==0)
{
printf("eatting finished\\n");
break;
}
pthread_mutex_lock(&lock[n-2]);
printf("the P%d get the chopstick %d \\n",n, n - 1);
pthread_mutex_lock(&lock[n-1]);
printf("the P%d get the chopstick %d \\n",n, n);
sum--;
usleep(rand() % 10);
pthread_mutex_unlock(&lock[n-2]);
pthread_mutex_unlock(&lock[n-1]);
printf("the P%d release the chopstick %d %d \\n",n, n - 1, n);
if(sum==0)
{
printf("eatting finished\\n");
break;
exit(1);
}
}
usleep(rand() % 10);
}
}
int main(void)
{
pthread_t tid[5];
int n;
srand(time(0));
for(n=0; n<5; n++)
pthread_mutex_init(&lock[n], 0);
for(n=1; n<6; n++)
{
pthread_create(&tid[n - 1], 0, fun, &n);
}
for(n=1; n<6; n++)
{
pthread_join(tid[n - 1], 0);
}
return 0;
}
| 0
|
#include <pthread.h>
static pthread_key_t key;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;
extern char **environ;
static void thread_init(void) {
pthread_key_create(&key, free);
}
char *getenv(const char *name) {
int i, len;
char *envbuf;
pthread_once(&init_done, thread_init);
pthread_mutex_lock(&env_mutex);
envbuf = (char *)pthread_getspecific(key);
if (envbuf == 0) {
envbuf = malloc(4096);
if (envbuf == 0) {
pthread_mutex_unlock(&env_mutex);
return (0);
}
pthread_setspecific(key, envbuf);
}
len = strlen(name);
for (i = 0; environ[i] != 0; i++) {
if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) {
strncpy(envbuf, &environ[i][len + 1], 4096 - 1);
pthread_mutex_unlock(&env_mutex);
return (envbuf);
}
}
pthread_mutex_unlock(&env_mutex);
return (0);
}
| 1
|
#include <pthread.h>
unsigned pegapassos(int argc, char** argv) {
if (argc < 2 || argc > 2) {
printf("O programa recebe o número de passos.\\n");
exit(0);
}
return strtoul(argv[1], 0, 10);
}
static unsigned STEP_NUM;
static unsigned THREAD_NUM;
static double STEP;
static double pi = 0.0;
static pthread_mutex_t mutex;
static void* worker_thread (void* arg) {
unsigned chunk_size = STEP_NUM/THREAD_NUM,
id = (long)arg;
register unsigned i;
register double sum = 0.0, x;
register double step = STEP;
register unsigned begin = id*chunk_size,
end = begin+chunk_size+(id+1==THREAD_NUM)*(STEP_NUM%THREAD_NUM);
for (i = begin; i < end; i++) {
x = (i+0.5)*step;
sum += 4.0/(1.0+x*x);
}
pthread_mutex_lock(&mutex);
pi += sum*step;
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main (int argc, char** argv) {
unsigned long i;
pthread_t *threads;
THREAD_NUM = (unsigned)sysconf(_SC_NPROCESSORS_ONLN);
STEP_NUM = pegapassos(argc, argv);
STEP = 1.0/(double)STEP_NUM;
threads = (pthread_t*)malloc(THREAD_NUM*sizeof(*threads));
pthread_mutex_init(&mutex, 0);
for (i = 0; i < THREAD_NUM; i++)
pthread_create(&threads[i], 0, worker_thread, (void*)i);
for (i = 0; i < THREAD_NUM; i++)
pthread_join(threads[i], 0);
free(threads);
pthread_mutex_destroy(&mutex);
printf("Pi = %.16g\\n", pi);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
static int threads = 0;
static struct mpi_bench_param_bounds_s param_bounds =
{
.min = 0,
.max = THREADS_DEFAULT,
.mult = 1,
.incr = 1
};
static int compute_stop = 0;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_t tids[THREADS_MAX];
static void*do_compute(void*_dummy)
{
int stop = 0;
while(!stop)
{
int k;
for(k = 0; k < 10000; k++)
{
r *= 2.213890;
}
pthread_mutex_lock(&lock);
stop = compute_stop;
pthread_mutex_unlock(&lock);
}
return 0;
}
static const struct mpi_bench_param_bounds_s*mpi_bench_overlap_Nload_getparams(void)
{
param_bounds.max = mpi_bench_get_threads();
return ¶m_bounds;
}
static void mpi_bench_overlap_Nload_setparam(int param)
{
int i;
pthread_mutex_lock(&lock);
compute_stop = 0;
pthread_mutex_unlock(&lock);
threads = param;
for(i = 0; i < threads; i++)
{
pthread_create(&tids[i], 0, &do_compute, 0);
}
}
static void mpi_bench_overlap_Nload_endparam(void)
{
int i;
pthread_mutex_lock(&lock);
compute_stop = 1;
pthread_mutex_unlock(&lock);
for(i = 0; i < threads; i++)
{
pthread_join(tids[i], 0);
}
threads = 0;
}
static void mpi_bench_overlap_Nload_server(void*buf, size_t len)
{
MPI_Recv(buf, len, MPI_CHAR, mpi_bench_common.peer, TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Send(buf, len, MPI_CHAR, mpi_bench_common.peer, TAG, MPI_COMM_WORLD);
}
static void mpi_bench_overlap_Nload_client(void*buf, size_t len)
{
MPI_Send(buf, len, MPI_CHAR, mpi_bench_common.peer, TAG, MPI_COMM_WORLD);
MPI_Recv(buf, len, MPI_CHAR, mpi_bench_common.peer, TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
}
const struct mpi_bench_s mpi_bench_overlap_Nload =
{
.label = "mpi_bench_overlap_Nload",
.name = "MPI overlap with N threads",
.param_label = "number of computation threads",
.rtt = MPI_BENCH_RTT_HALF,
.server = &mpi_bench_overlap_Nload_server,
.client = &mpi_bench_overlap_Nload_client,
.getparams = &mpi_bench_overlap_Nload_getparams,
.setparam = &mpi_bench_overlap_Nload_setparam,
.endparam = &mpi_bench_overlap_Nload_endparam
};
| 1
|
#include <pthread.h>
void *produce(void*);
void *consume(void*);
struct {
pthread_mutex_t mutex;
int buff[1000000];
int n;
} shared = { PTHREAD_MUTEX_INITIALIZER };
int main(int argc, char *argv[]) {
int i;
int count[5];
pthread_t producers[5];
pthread_t consumer;
for(i = 0; i < 5; i++) {
count[i] = 0;
pthread_create(&producers[i], 0, produce, &count[i]);
}
for(i = 0; i < 5; i++) {
pthread_join(producers[i], 0);
printf("count[%d] = %d\\n", i, count[i]);
}
pthread_create(&consumer, 0, consume, 0);
pthread_join(consumer, 0);
return 0;
}
void *produce(void *arg) {
for(;;) {
pthread_mutex_lock(&shared.mutex);
if(shared.n >= 1000000) {
pthread_mutex_unlock(&shared.mutex);
return 0;
}
shared.buff[shared.n] = shared.n;
shared.n++;
pthread_mutex_unlock(&shared.mutex);
*((int *)arg) += 1;
}
}
void *consume(void *arg) {
int i;
for(i = 0; i < 1000000; i++) {
if(shared.buff[i] != i) {
printf("buff[%d] = %d\\n", i, shared.buff[i]);
}
}
return 0;
}
| 0
|
#include <pthread.h>
struct ogst_connecter *ogst_connecter_new(struct ogst_connecter *(*gen)(void),
char *path)
{
int len;
struct ogst_connecter *sock;
sock = gen();
if ((sock->sd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
sock->socket.sun_family = AF_UNIX;
strcpy(sock->socket.sun_path, path);
unlink(path);
len = strlen(path) + sizeof(sock->socket.sun_family);
if (bind(sock->sd, (struct sockaddr *)&sock->socket, len) == -1) {
perror("bind");
exit(1);
}
return sock;
}
struct ogst_connection *ogst_connecter_accept(struct ogst_connection *(*gen)(void),
struct ogst_connecter *sock)
{
unsigned int len;
struct ogst_connection *remote_sock;
if (listen(sock->sd, 5) == -1) {
perror("listen");
exit(1);
}
remote_sock = gen();
if ((remote_sock->sd = accept
(sock->sd,
(struct sockaddr *) &remote_sock->socket,
&len)) == -1) {
perror("accept");
exit(1);
}
remote_sock->end_bool = 0;
return remote_sock;
}
int ogst_connection_end_check(struct ogst_connection *socket)
{
int value;
pthread_mutex_lock(&socket->end_mutex);
value = socket->end_bool;
pthread_mutex_unlock(&socket->end_mutex);
return value;
}
void ogst_connection_end_mutate(struct ogst_connection *socket, int value)
{
pthread_mutex_lock(&socket->end_mutex);
socket->end_bool = value;
pthread_mutex_unlock(&socket->end_mutex);
}
void ogst_connection_kill(struct ogst_connection *user_socket)
{
int true_val = 1;
pthread_mutex_lock(&user_socket->done_mutex);
ogst_connection_end_mutate(user_socket, 1);
setsockopt(user_socket->sd, SOL_SOCKET,SO_REUSEADDR,
&true_val, sizeof(int));
pthread_mutex_unlock(&user_socket->done_mutex);
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void read_fifo(int r_fd)
{
int n;
char buf[1024];
while (1)
{
pthread_cond_wait(&cond,&lock);
n = read(r_fd,buf,sizeof(buf));
buf[n] = '\\0';
fprintf(stdout,"Read %d types from %d : %s\\n",n,r_fd,buf);
pthread_mutex_unlock(&lock);
if (strncmp(buf,"quit",4) == 0)
{
break;
}
}
return;
}
void write_fifo(int w_fd)
{
int n;
char buf[1024];
while (1)
{
pthread_mutex_lock(&lock);
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1] = '\\0';
write(w_fd,buf,strlen(buf));
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
if (strncmp(buf,"quit",4) == 0)
{
break;
}
usleep(500);
}
return;
}
int main(int argc, const char *argv[])
{
int w_fd;
int r_fd;
pid_t pid;
if (argc < 3)
{
fprintf(stderr,"Usage : %s write_fifo read_fifo\\n",argv[0]);
exit(1);
}
if (mkfifo(argv[1],0666) != 0 && errno != EEXIST)
{
perror("Fail to mkfifo");
exit(1);
}
if (mkfifo(argv[2],0666) != 0 && errno != EEXIST)
{
perror("Fail to mkfifo");
exit(1);
}
w_fd = open(argv[1],O_WRONLY|O_CREAT|O_TRUNC,0666);
if (w_fd < 0)
{
perror("Fail to open");
exit(1);
}
r_fd = open(argv[2],O_RDONLY);
if (r_fd < 0)
{
perror("Fail to open");
exit(1);
}
printf("w_fd = %d\\n",w_fd);
pid = fork();
if (pid < 0)
{
perror("Fail to fork");
exit(1);
}
if (pid == 0)
{
read_fifo(r_fd);
}
if (pid > 0)
{
write_fifo(w_fd);
}
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t getgr_mutex = PTHREAD_MUTEX_INITIALIZER;
static int
convert (struct group *ret, struct group *result,
char *buf, int buflen)
{
int len;
int count;
char **gr_mem;
char *buf1;
if (!buf) return -1;
*result = *ret;
result->gr_name = (char *) buf;
len = strlen (ret->gr_name) + 1;
if (len > buflen) return -1;
buflen -= len;
buf += len;
strcpy (result->gr_name, ret->gr_name);
result->gr_passwd = (char *) buf;
len = strlen (ret->gr_passwd) + 1;
if (len > buflen) return -1;
buflen -= len;
buf += len;
strcpy (result->gr_passwd, ret->gr_passwd);
count = 0;
gr_mem = ret->gr_mem;
while (*gr_mem){
count++;
gr_mem++;
}
len = sizeof (*gr_mem)*(count+1);
if (len > buflen) return -1;
buf1 = buf;
buflen -= len;
buf += len;
gr_mem = ret->gr_mem;
while (*gr_mem){
len = strlen (*gr_mem) + 1;
if (len > buflen) return -1;
buf1 = buf;
strcpy (buf, *gr_mem);
buflen -= len;
buf += len;
buf1 += sizeof (buf1);
gr_mem++;
}
buf1 = 0;
return 0;
}
int getgrnam_r (const char *name, struct group *result,
char *buffer, size_t buflen,
struct group ** resptr)
{
struct group * p;
int retval;
pthread_mutex_lock (&getgr_mutex);
p = getgrnam (name);
if (p == 0) {
*resptr = 0;
retval = ESRCH;
} else
if (convert (p, result, buffer, buflen) != 0) {
*resptr = 0;
retval = ERANGE;
} else {
*resptr = result;
retval = 0;
}
pthread_mutex_unlock (&getgr_mutex);
return retval;
}
int getgrgid_r (uid_t uid, struct group *result,
char *buffer, size_t buflen,
struct group ** resptr)
{
struct group * p;
int retval;
pthread_mutex_lock (&getgr_mutex);
p = getgrgid (uid);
if (p == 0) {
*resptr = 0;
retval = ESRCH;
} else
if (convert (p, result, buffer, buflen) != 0) {
*resptr = 0;
retval = ERANGE;
} else {
*resptr = result;
retval = 0;
}
pthread_mutex_unlock (&getgr_mutex);
return retval;
}
| 1
|
#include <pthread.h>
static FILE *fv_log_file = 0;
static struct fv_buffer fv_log_buffer = FV_BUFFER_STATIC_INIT;
static pthread_t fv_log_thread;
static bool fv_log_has_thread = 0;
static pthread_mutex_t fv_log_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t fv_log_cond = PTHREAD_COND_INITIALIZER;
static bool fv_log_finished = 0;
struct fv_error_domain
fv_log_error;
bool
fv_log_available(void)
{
return fv_log_file != 0;
}
void
fv_log(const char *format, ...)
{
va_list ap;
time_t now;
struct tm tm;
if (!fv_log_available())
return;
pthread_mutex_lock(&fv_log_mutex);
time(&now);
gmtime_r(&now, &tm);
fv_buffer_append_printf(&fv_log_buffer,
"[%4d-%02d-%02dT%02d:%02d:%02dZ] ",
tm.tm_year + 1900,
tm.tm_mon + 1,
tm.tm_mday,
tm.tm_hour,
tm.tm_min,
tm.tm_sec);
__builtin_va_start((ap));
fv_buffer_append_vprintf(&fv_log_buffer, format, ap);
;
fv_buffer_append_c(&fv_log_buffer, '\\n');
pthread_cond_signal(&fv_log_cond);
pthread_mutex_unlock(&fv_log_mutex);
}
static void
block_sigint(void)
{
sigset_t sigset;
sigemptyset(&sigset);
sigaddset(&sigset, SIGINT);
sigaddset(&sigset, SIGTERM);
if (pthread_sigmask(SIG_BLOCK, &sigset, 0) == -1)
fv_warning("pthread_sigmask failed: %s", strerror(errno));
}
static void *
fv_log_thread_func(void *data)
{
struct fv_buffer alternate_buffer;
struct fv_buffer tmp;
bool had_error = 0;
block_sigint();
fv_buffer_init(&alternate_buffer);
pthread_mutex_lock(&fv_log_mutex);
while (!fv_log_finished || fv_log_buffer.length > 0) {
size_t wrote;
while (!fv_log_finished && fv_log_buffer.length == 0)
pthread_cond_wait(&fv_log_cond, &fv_log_mutex);
if (had_error) {
fv_buffer_set_length(&fv_log_buffer, 0);
} else {
tmp = fv_log_buffer;
fv_log_buffer = alternate_buffer;
alternate_buffer = tmp;
pthread_mutex_unlock(&fv_log_mutex);
wrote = fwrite(alternate_buffer.data, 1 ,
alternate_buffer.length, fv_log_file);
if (wrote != alternate_buffer.length)
had_error = 1;
else
fflush(fv_log_file);
fv_buffer_set_length(&alternate_buffer, 0);
pthread_mutex_lock(&fv_log_mutex);
}
}
pthread_mutex_unlock(&fv_log_mutex);
fv_buffer_destroy(&alternate_buffer);
return 0;
}
bool
fv_log_set_file(const char *filename, struct fv_error **error)
{
FILE *file;
file = fopen(filename, "a");
if (file == 0) {
fv_file_error_set(error,
errno,
"%s: %s",
filename,
strerror(errno));
return 0;
}
fv_log_close();
fv_log_file = file;
fv_log_finished = 0;
return 1;
}
void
fv_log_start(void)
{
if (!fv_log_available() || fv_log_has_thread)
return;
fv_log_thread = fv_thread_create(fv_log_thread_func,
0 );
fv_log_has_thread = 1;
}
void
fv_log_close(void)
{
if (fv_log_has_thread) {
pthread_mutex_lock(&fv_log_mutex);
fv_log_finished = 1;
pthread_cond_signal(&fv_log_cond);
pthread_mutex_unlock(&fv_log_mutex);
pthread_join(fv_log_thread, 0);
fv_log_has_thread = 0;
}
fv_buffer_destroy(&fv_log_buffer);
fv_buffer_init(&fv_log_buffer);
if (fv_log_file) {
fclose(fv_log_file);
fv_log_file = 0;
}
}
| 0
|
#include <pthread.h>
struct element{
void* value;
element *next;
};
struct queue{
llist in;
llist out;
};
pthread_mutex_t push = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t pop = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t blocking = PTHREAD_MUTEX_INITIALIZER;
pthread_t id1;
struct queue* queue_new(void){
struct queue* new_queue = 0;
new_queue = malloc(sizeof(struct queue));
new_queue->in = 0;
new_queue->out = 0;
return new_queue;
}
void queue_free(struct queue *queue){
llist temp;
while (queue->in != 0){
temp = queue->in->next;
free(queue->in);
queue->in = temp;
}
while (queue->out != 0){
temp = queue->out->next;
free(queue->out);
queue->out = temp;
}
free(queue);
}
void queue_push(struct queue *q, void *value){
element *new_element = malloc(sizeof(element));
pthread_mutex_lock(&push);
new_element->value = value;
new_element->next = q->in;
q->in = new_element;
pthread_mutex_unlock(&push);
pthread_mutex_unlock(&blocking);
}
void* queue_pop_blocking(struct queue *q){
void* ret;
llist temp;
pthread_mutex_lock(&pop);
if (q->out == 0){
if (q->in == 0){
pthread_mutex_lock(&blocking);
}
pthread_mutex_lock(&push);
while (q->in != 0){
temp = q->in;
q->in = q->in->next;
if (q->out == 0){
q->out = temp;
q->out->next = 0;
}
else{
temp->next = q->out;
q->out = temp;
}
}
q->in = 0;
pthread_mutex_unlock(&push);
}
ret = q->out->value;
temp = q->out->next;
free(q->out);
q->out = temp;
if (q->out == 0 && q->in == 0)
pthread_mutex_lock(&blocking);
pthread_mutex_unlock(&pop);
return ret;
}
void* queue_pop(struct queue *q){
void* ret;
llist temp;
pthread_mutex_lock(&pop);
if (q->out == 0){
pthread_mutex_lock(&push);
if (q->in == 0)
return 0;
while (q->in != 0){
temp = q->in;
q->in = q->in->next;
if (q->out == 0){
q->out = temp;
q->out->next = 0;
}
else{
temp->next = q->out;
q->out = temp;
}
}
pthread_mutex_unlock(&push);
}
ret = q->out->value;
temp = q->out->next;
free(q->out);
q->out = temp;
pthread_mutex_unlock(&pop);
return ret;
}
void test_q1(void){
struct queue *q = 0;
int a = 2, b = 3, c = 1, d = 6;
q = queue_new();
queue_push(q, (void*)&a);
queue_push(q, (void*)&b);
queue_push(q, (void*)&c);
printf("%d\\n", (*(int*)queue_pop(q)));
printf("%d\\n", (*(int*)queue_pop(q)));
queue_push(q, (void*)&d);
printf("%d\\n", (*(int*)queue_pop(q)));
printf("%d\\n", (*(int*)queue_pop(q)));
queue_free(q);
}
void* thread1(void *arg){
int i;
struct queue *q = (struct queue*)arg;
for (i = 0; i < 10000; i++){
queue_push(q, (void*)i);
}
return 0;
}
void test_q2(void){
struct queue *q = 0;
int i;
pthread_mutex_lock(&blocking);
q = queue_new();
pthread_create(&id1, 0, thread1, (void*)q);
for (i = 0; i < 10000; i++){
printf("%d\\n", (int)queue_pop_blocking(q));
}
pthread_join(id1, 0);
pthread_mutex_unlock(&blocking);
queue_free(q);
}
int main(void){
test_q1();
test_q2();
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex[10] = {
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER
};
unsigned long delay=0;
void *lock_A (void *arg)
{
int i, iterate, backoffs;
int status;
pthread_t tid = pthread_self();
for (iterate = 0; iterate < 10; iterate++) {
printf("for-loop: %d in thread %d", iterate, tid);
backoffs = 0;
for (i = 0; i < 10; i++) {
for (delay=0; delay<= 1000000;delay++) {
}
if (i == 0) {
status = pthread_mutex_lock (&mutex[i]);
if (status != 0)
err_abort (status, "First lock");
}
else {
status = pthread_mutex_lock (&mutex[i]);
if (status != 0)
err_abort (status, "Lock mutex");
DPRINTF ((" A locker got %d\\n", i));
}
sleep (1);
}
printf ("A got all locks, \\n");
for (i=0; i<10;i++) {
pthread_mutex_unlock (&mutex[i]);
}
sched_yield ();
}
return 0;
}
void *lock_B (void *arg)
{
int i, iterate;
int status;
for (iterate = 0; iterate < 10; iterate++) {
for (i = 10 -1; i >= 0; i--) {
if (i == 10 -1) {
status = pthread_mutex_lock (&mutex[i]);
if (status != 0)
err_abort (status, "First lock");
} else {
status = pthread_mutex_lock (&mutex[i]);
if (status != 0)
err_abort (status, "Lock mutex");
DPRINTF ((" B locker got %d\\n", i));
}
sleep (1);
}
printf("B got all locks\\n");
for (i=0; i<10;i++) {
pthread_mutex_unlock (&mutex[i]);
}
sched_yield ();
}
return 0;
}
int main (int argc, char *argv[])
{
pthread_t A, B;
int status;
status = pthread_create (&A, 0, lock_A, 0);
if (status != 0)
err_abort (status, "Create A");
status = pthread_create (&B, 0, lock_B, 0);
if (status != 0)
err_abort (status, "Create B");
pthread_exit (0);
}
| 0
|
#include <pthread.h>
char buf[200] = {0};
pthread_mutex_t mutex;
unsigned int flag = 0;
pthread_cond_t cond;
void *func(void *arg)
{
while (flag == 0)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
printf("本次输入了%d个字符\\n", strlen(buf));
memset(buf, 0, sizeof(buf));
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main(void)
{
int ret = -1;
pthread_t th = -1;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
ret = pthread_create(&th, 0, func, 0);
if (ret != 0)
{
printf("pthread_create error.\\n");
exit(-1);
}
printf("输入一个字符串,以回车结束\\n");
while (1)
{
scanf("%s", buf);
pthread_cond_signal(&cond);
if (!strncmp(buf, "end", 3))
{
printf("程序结束\\n");
flag = 1;
break;
}
}
printf("等待回收子线程\\n");
ret = pthread_join(th, 0);
if (ret != 0)
{
printf("pthread_join error.\\n");
exit(-1);
}
printf("子线程回收成功\\n");
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
| 1
|
#include <pthread.h>
int state[5];
pthread_cond_t philArray[5];
pthread_mutex_t the_mutex;
void test(int i) {
if (state[i] == 1 && state[(i + 4) % 5] != 2 && state[(i + 1) % 5] != 2) {
state[i] = 2;
printf("Philosopher %d starts eating.\\n", i);
printf("[%d, %d, %d, %d, %d]\\n", state[0], state[1], state[2], state[3], state[4]);
pthread_cond_signal(&philArray[i]);
}
else {
if (state[i] == 0) {
printf("Philosopher %d is deep in thought.\\n", i);
}
}
}
void takeFork(int i) {
pthread_mutex_lock(&the_mutex);
printf("Philosopher %d is hungry.\\n", i);
state[i] = 1;
test(i);
if(state[i] != 2) {
printf("Philosopher %d does not have enough chopsticks available\\n", i);
printf("[%d, %d, %d, %d, %d]\\n", state[0], state[1], state[2], state[3], state[4]);
pthread_cond_wait(&philArray[i], &the_mutex);
}
pthread_mutex_unlock(&the_mutex);
}
void putFork(int i) {
pthread_mutex_lock(&the_mutex);
state[i] = 0;
printf("Philosopher %d puts down the forks and starts thinking.\\n", i);
printf("[%d, %d, %d, %d, %d]\\n", state[0], state[1], state[2], state[3], state[4]);
test((i + 4) % 5);
test((i + 1) % 5);
pthread_mutex_unlock(&the_mutex);
}
void * phil(void * tid) {
int temp = *((int*)tid);
while(1) {
takeFork(temp);
putFork(temp);
}
}
int main()
{
pthread_t tid[5];
int i;
pthread_mutex_init(&the_mutex, 0);
for(i = 0; i < 5; i++) {
state[i] = 0;
pthread_cond_init(&philArray[i], 0);
}
for(i = 0; i < 5; i++) {
pthread_create(&tid[i], 0, phil, (void *)(&i));
}
for(i = 0; i < 5; i++) {
pthread_join(tid[i], 0);
}
for(i = 0; i < 5; i++) {
pthread_cond_destroy(&philArray[i]);
}
pthread_mutex_destroy(&the_mutex);
return 0;
}
| 0
|
#include <pthread.h>
extern char hash[TCP_HASH_SIZE+1];
extern void *hash_flows2;
void bulk_tcp(struct seg6_sock *sk, struct nlattr **attrs, struct nlmsghdr *nlh) {
struct parser_tcp *tcphdr ;
struct parser_ipv6 *ip6hdr ;
struct tcp_flow_2 *flow2;
struct bulk_buffer *buffer;
struct tcp_process tcp_info;
int res;
unsigned int ipv6_hash=0, tmp, *pos;
if((res = get_tcp_info(attrs, &tcp_info, &tcphdr, &ip6hdr, &ipv6_hash)) != 0){
send_ip6_packet(sk,
(int) nla_get_u32(attrs[SEG6_ATTR_PACKET_LEN]),
nla_data(attrs[SEG6_ATTR_PACKET_DATA]));
return ;
}
if(tcp_info.pkt_len >= (int) BUFFER_SIZE || tcphdr == 0 || ip6hdr == 0) {
send_ip6_packet(sk, tcp_info.pkt_len, tcp_info.pkt_data);
return ;
}
if(get_tcp_flag(tcphdr, FLAG_URG | FLAG_SYN | FLAG_RST) ) {
send_ip6_packet(sk, tcp_info.pkt_len, tcp_info.pkt_data);
return ;
}
pos = (unsigned int *) ((char *) ip6hdr + offsetof(struct parser_ipv6, length));
tmp = *pos;
*pos = ipv6_hash;
flow2 = get_tcp_flow_2_or_create((struct tcp_flow_2 **) &hash_flows2,
(char *) pos, (char *) &(tcphdr->src));
*pos = tmp;
buffer = flow2->b;
pthread_mutex_lock(buffer->lock);
insert_tcp_to_buffer(sk, buffer, &tcp_info, &(flow2->seq), &(flow2->opt));
if(get_tcp_flag(tcphdr, FLAG_FIN | FLAG_PSH) )
send_buffer(sk, buffer, OP_BUF_UPDLEN | OP_BUF_UPDCKSUM | OP_BUF_UPDALL_LEN);
pthread_mutex_unlock(buffer->lock);
}
void bulk_tcp_list(struct seg6_sock *sk, struct nlattr **attrs, struct nlmsghdr *nlh) {
struct parser_tcp *tcphdr ;
struct parser_ipv6 *ip6hdr;
struct tcp_flow_list_2 *flow2;
struct bulk_list *list;
struct el_bulk_list *el, *pivot;
struct tcp_process *tcp_info;
struct timeval a, b, c, d;
int ipv6_hash=0;
tcp_info = (struct tcp_process *) malloc(sizeof(struct tcp_process));
get_tcp_info(attrs, tcp_info, &tcphdr, &ip6hdr, &ipv6_hash);
if(tcp_info->pkt_len >= (int) BUFFER_SIZE || tcphdr == 0 || ip6hdr == 0) {
send_ip6_packet(sk, tcp_info->pkt_len, tcp_info->pkt_data);
free(tcp_info);
return;
}
if(get_tcp_flag(tcphdr, FLAG_URG | FLAG_SYN | FLAG_RST) ) {
send_ip6_packet(sk, tcp_info->pkt_len, tcp_info->pkt_data);
free(tcp_info);
return ;
}
flow2 = get_tcp_flow_list_2_or_create((struct tcp_flow_list_2 **) &hash_flows2,
(char *) &(ip6hdr->src), (char *) &(tcphdr->src));
list = flow2->b;
el = (struct el_bulk_list *) malloc(sizeof(struct el_bulk_list));
el->tcp = tcp_info;
el->seq = ntohl(tcphdr->seq_nbr);
el->len = el->tcp->pkt_len - el->tcp->tcp_offset - el->tcp->tcp_len;
pthread_mutex_lock(list->lock);
pivot = insert_tcp_to_list(sk, list, el);
if(get_tcp_flag(tcphdr, FLAG_FIN | FLAG_PSH) ) {
send_list(sk, list, OP_BUF_UPDLEN | OP_BUF_UPDCKSUM | OP_BUF_UPDALL_LEN);
} else if(pivot != 0) {
send_list_until(sk, list, pivot->next, OP_BUF_UPDLEN | OP_BUF_UPDCKSUM | OP_BUF_UPDALL_LEN );
}
pthread_mutex_unlock(list->lock);
}
| 1
|
#include <pthread.h>
char *word;
int count;
struct dict *next;
} dict_t;
char *
make_word( char *word ) {
return strcpy( malloc( strlen( word )+1 ), word );
}
FILE *infile1;
pthread_mutex_t lock;
dict_t *wds = 0;
dict_t *
make_dict(char *word) {
dict_t *nd = (dict_t *) malloc( sizeof(dict_t) );
nd->word = make_word( word );
nd->count = 1;
nd->next = 0;
return nd;
}
dict_t *
insert_word( dict_t *d, char *word ) {
dict_t *nd;
dict_t *pd = 0;
dict_t *di = d;
while(di && ( strcmp(word, di->word ) >= 0) ) {
if( strcmp( word, di->word ) == 0 ) {
di->count++;
return d;
}
pd = di;
di = di->next;
}
nd = make_dict(word);
nd->next = di;
if (pd) {
pd->next = nd;
return d;
}
return nd;
}
void print_dict(dict_t *d) {
while (d) {
printf("[%d] %s\\n", d->count, d->word);
d = d->next;
}
}
int
get_word( char *buf, int n, FILE *infile) {
int inword = 0;
int c;
while( (c = fgetc(infile)) != EOF ) {
if (inword && !isalpha(c)) {
buf[inword] = '\\0';
return 1;
}
if (isalpha(c)) {
buf[inword++] = c;
}
}
return 0;
}
void *
words( void *args ) {
char wordbuf[1024];
pthread_mutex_lock(&lock);
while( get_word( wordbuf, 1024, infile1 ) ) {
wds = insert_word(wds, wordbuf);
}
pthread_mutex_unlock(&lock);
}
int
main( int argc, char *argv[] ) {
dict_t *d = 0;
infile1 = stdin;
if (argc >= 2) {
infile1 = fopen (argv[1],"r");
}
if( !infile1 ) {
printf("Unable to open %s\\n",argv[1]);
exit( 1 );
}
int t;
pthread_t tid[4];
for(t=0;t<4;t++){
pthread_create(&tid[t],0,&words,0);
}
for(t=0;t<4;t++){
pthread_join(tid[t],0);
}
print_dict( wds );
fclose( infile1 );
}
| 0
|
#include <pthread.h>
pthread_mutex_t mtx[3];
pthread_t t[10];
int cnt[3];
void* doIt(void *arg) {
while(cnt[0] < 5 || cnt[1] < 5 || cnt[2] < 5) {
int x = 1 + rand() % 900;
printf("Thread: %d\\n", x);
if(x <= 300) {
pthread_mutex_lock(&mtx[0]);
cnt[0] ++;
pthread_mutex_unlock(&mtx[0]);
}
else if(x <= 600) {
pthread_mutex_lock(&mtx[1]);
++ cnt[1];
pthread_mutex_unlock(&mtx[1]);
}
else {
pthread_mutex_lock(&mtx[2]);
++ cnt[2];
pthread_mutex_unlock(&mtx[2]);
}
}
return 0;
}
int main() {
srand(time(0));
int i;
if(fork() == 0) {
for(i = 0; i < 3; ++ i)
pthread_mutex_init(&mtx[i], 0);
for(i = 0; i < 10; ++ i)
pthread_create(&t[i], 0, doIt, 0);
for(i = 0; i < 10; ++ i)
pthread_join(t[i], 0);
for(i = 0; i < 3; ++ i)
pthread_mutex_destroy(&mtx[i]);
printf("Subprocess\\n");
int c2p = open("c2p", O_WRONLY);
for(i = 0; i < 3; ++ i) {
printf("%d ", cnt[i]);
write(c2p, &cnt[i], sizeof(int));
}
close(c2p);
printf("\\n");
exit(0);
}
int c2p = open("c2p", O_RDONLY);
for(i = 0; i < 3; ++ i)
read(c2p, &cnt[i], sizeof(int));
close(c2p);
printf("Main Process\\n");
for(i = 0; i < 3; ++ i)
printf("%d ", cnt[i]);
printf("\\n");
wait(0);
return 0;
}
| 1
|
#include <pthread.h>
int get_round(int length);
void *Merge(void*args);
void print_array(int length);
int number_array[4096];
int barrier;
pthread_mutex_t mutex;
pthread_cond_t cond;
pthread_t tid[4096];
int left;
int mid;
int right;
}args;
int main(int argc, char *argv[])
{
FILE *stream;
stream = fopen("indata.txt","r");
char input[20000];
fgets(input,20000,stream);
char *number;
int i=0;
number = strtok(input, " \\t\\r\\n\\a");
while(number!=0){
number_array[i] = atoi(number);
i++;
number = strtok(0, " \\t\\r\\n\\a");
}
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
int length=i;
int round=get_round(length);
int round_count;
int subset_length=2;
int subset_num=length;
int tid_ptr=0;
for(round_count=0;round_count<round;round_count++){
int thread_number=subset_num/2;
barrier=thread_number;
args arguements[thread_number];
int subset;
for(subset=0;subset<thread_number;subset++){
arguements[subset].left=subset_length*subset;
arguements[subset].mid=(subset_length/2-1)+subset_length*subset;
arguements[subset].right=(subset_length-1)+subset_length*subset;
}
for(subset=0;subset<thread_number;subset++){
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tid[tid_ptr],&attr,Merge,(void*)&arguements[subset]);
tid_ptr++;
}
pthread_mutex_lock(&mutex);
while(barrier>0){
pthread_cond_wait(&cond,&mutex);
}pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
subset_num=subset_num/2;
subset_length=subset_length*2;
}
print_array(length);
return 0;
}
int get_round(int length){
int l=length, round=0;
while (l!=1){
l=l/2;
round++;
}
return round;
}
void *Merge(void*args)
{
struct args* arguements=(struct args*)args;
int left=arguements->left;
int mid=arguements->mid;
int right=arguements->right;
int *tempArray=(int *)malloc((right-left+1)*sizeof(int));
int pos=0,lpos = left,rpos = mid + 1;
while(lpos <= mid && rpos <= right){
if(number_array[lpos] < number_array[rpos]){
tempArray[pos++] = number_array[lpos++];
}else{
tempArray[pos++] = number_array[rpos++];
}
}
while(lpos <= mid){
tempArray[pos++] = number_array[lpos++];
}
while(rpos <= right){
tempArray[pos++] = number_array[rpos++];
}
int iter;
for(iter = 0;iter < pos; iter++){
number_array[iter+left] = tempArray[iter];
}
free(tempArray);
pthread_mutex_lock(&mutex);
barrier--;
while(barrier>0){
pthread_cond_wait(&cond,&mutex);
}
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
return;
}
void print_array(int length)
{
int index;
for(index=0; index<length; index++){
printf("%d ", number_array[index]);
}
printf("\\n");
}
| 0
|
#include <pthread.h>
void *enteroffice(void * arg);
void *answerQ(void * arg);
pthread_mutex_t print_mutex;
pthread_mutex_t qa_mutex;
sem_t q_asked;
sem_t answered;
sem_t office_max;
struct Params{
int studentNumber;
int questionNumber;
};
int main(int argc, char **argv){
int args[3] = { 0 };
if(argc != 4){
perror("Number of arguments is incorrect");
exit(0);
}
int i;
for(i=0; i<argc-1; ++i){
args[i] = atoi(argv[i + 1]);
}
int numStudents = args[0];
int officeCap = args[1];
int questionNum = args[2];
if(numStudents<1||officeCap<1||questionNum<1){
printf("All arguments must be greater than zero\\n");
exit(0);
}
pthread_mutex_init(&print_mutex, 0);
pthread_mutex_init(&qa_mutex, 0);
int start = sem_init(&office_max, 0, officeCap);
if (start < 0){
perror("Semaphore initialization failed");
exit(0);
}
int qstart = sem_init(&q_asked, 0, 0);
if(qstart<0){
perror("Sempahore initialization failed");
exit(0);
}
int anstart = sem_init(&answered,0,0);
if(anstart<0){
perror("Semaphore initialization failed");
exit(0);
}
struct Params *parameter;
pthread_t students[numStudents];
for(i =0; i<numStudents;i++){
parameter = (struct Params *)calloc(1,sizeof(struct Params));
parameter->studentNumber = i+1;
parameter->questionNumber = questionNum;
pthread_create(&students[i], 0, (void *)enteroffice, (void *)parameter);
}
struct Params *TAparam;
TAparam = (struct Params *)calloc(1,sizeof(struct Params));
TAparam->studentNumber = numStudents;
TAparam->questionNumber = questionNum;
pthread_t TA;
pthread_create(&TA, 0, (void *)answerQ, (void *)TAparam);
for(i=0;i<numStudents;i++){
pthread_join(students[i], 0);
}
pthread_join(TA,0);
pthread_mutex_destroy(&print_mutex);
pthread_mutex_destroy(&qa_mutex);
sem_destroy(&office_max);
sem_destroy(&q_asked);
sem_destroy(&answered);
printf("All questions answered by TA.\\n");
return 0;
}
void * enteroffice(void * arg){
struct Params *answer;
answer = (struct Params *) arg;
int sN = answer->studentNumber;
if(sem_trywait(&office_max)){
printf("I am student %d and I'm waiting outside the TA's door\\n", sN);
}
printf("I am student %d and I am entering the room\\n", sN);
int qNum = answer->questionNumber;
int q;
for(q = 0; q<qNum;q++){
pthread_mutex_lock(&qa_mutex);
pthread_mutex_lock(&print_mutex);
int printnum = q +1;
printf("I am student %d asking question %d\\n", sN, printnum);
pthread_mutex_unlock(&qa_mutex);
sem_post(&answered);
sem_wait(&q_asked);
pthread_mutex_unlock(&print_mutex);
}
printf("I am student %d and I am leaving the room\\n", sN);
sem_post(&office_max);
}
void * answerQ(void * arg){
struct Params *answer;
answer = (struct Params *) arg;
int questions = answer->questionNumber * answer->studentNumber;
while(questions>0){
sem_wait(&answered);
printf("I am TA and this will be discussed in class\\n");
sem_post(&q_asked);
questions--;
}
}
| 1
|
#include <pthread.h>
int
_aasg_bidalloc(struct aasg_peer *aasgp,
void (*completion_handler)(struct asg_batch_id_t *),
struct asg_batch_id_t **bid)
{
int id;
struct aasg_transport *aasgx;
aasgx = aasgp->aasgx;
*bid = malloc(sizeof(struct asg_batch_id_t));
if (*bid == 0)
return -ENOMEM;
memset(*bid, 0, sizeof(struct asg_batch_id_t));
(*bid)->ctx = malloc(sizeof(struct context));
memset((*bid)->ctx, 0, sizeof(struct context));
if ((*bid)->ctx == 0) {
free(*bid);
return -ENOMEM;
}
id = 0;
pthread_mutex_lock(&aasgx->mp);
while (aasgx->map[id] == 1 && id < AASG_NGRP) {
id++;
}
if (id < AASG_NGRP) {
aasgx->map[id] = 1;
}
pthread_mutex_unlock(&aasgx->mp);
if (id == AASG_NGRP) {
free((*bid)->ctx);
free(*bid);
return -ENOBUFS;
}
(*bid)->aasgp = aasgp;
(*bid)->id = id;
(*bid)->completion_handler = completion_handler;
(*bid)->error = -EINPROGRESS;
(*bid)->setret = 0;
(*bid)->ctx->bid = *bid;
(*bid)->cmdbuf = 0;
(*bid)->mbitc = 0;
(*bid)->len = 0;
return 0;
}
void
_aasg_bidfree(struct asg_batch_id_t *bid)
{
struct aasg_transport *aasgx;
aasgx = bid->aasgp->aasgx;
pthread_mutex_lock(&aasgx->mp);
aasgx->map[bid->id] = 0;
pthread_mutex_unlock(&aasgx->mp);
}
| 0
|
#include <pthread.h>
void usage();
int factorial(int n);
void *T1(void *t);
void *T2(void *t);
bool finished = 0;
int count = 0 ;
pthread_mutex_t count_mutex;
int data_array[10];
} thread_data;
thread_data global_data;
int main(int argc, char *argv[])
{
if(argc!=3)
{usage(); return(1);}
int numOfProducerThreads = atoi(argv[1]);
int numOfConsumerThreads = atoi(argv[2]);
if((numOfProducerThreads<1) || (numOfProducerThreads>5) || (numOfConsumerThreads<1) || (numOfConsumerThreads>5))
{usage(); return(1);}
pthread_t thread[numOfProducerThreads + numOfConsumerThreads];
pthread_attr_t attr;
int t;
void *status;
pthread_mutex_init(&count_mutex, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(t=0; t<numOfProducerThreads; t++)
{pthread_create(&thread[t], &attr, T1, (void *)&t);}
for(t=0; t<numOfConsumerThreads; t++)
{pthread_create(&thread[t+numOfProducerThreads], &attr, T2, (void *)&t);}
sleep(30);
finished = 1;
for(t=0; t<numOfProducerThreads+numOfConsumerThreads; t++)
{pthread_join(thread[t], &status);}
printf("Main program exiting after joining threads\\n");
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_exit(0);
return 0;
}
int factorial(int n){
int fact = 1;
for (int i = 1; i <= n; i++)
{fact *= i;}
return fact;
}
void usage()
{
printf("Usage: This program takes 2 numbers from the command line, each number between 1 and 5 inclusive. The first of these numbers indicate the number of producer threads to create, the second of these numbers indicates the number of consumer threads to create.\\n");
}
void *T1(void *t)
{
printf("Producer started.\\n");
int i;
while(!finished) {
int randomNumber = rand() % 10;
sleep(randomNumber);
i = rand() % 10;
if(count<10)
{
pthread_mutex_lock(&count_mutex);
global_data.data_array[count] = i;
count++ ;
printf("Producer added %d to queue, size = %d\\n", i, count);
pthread_mutex_unlock(&count_mutex);
}
else
{
printf("Unable to add\\n");
}
}
printf("Producer finished\\n");
pthread_exit(0);
}
void *T2(void *t)
{
printf("Consumer started.\\n");
int i;
while(!finished) {
int randomNumber = rand() % 10;
sleep(randomNumber);
if(count>0)
{
pthread_mutex_lock(&count_mutex);
i = global_data.data_array[count];
count-- ;
printf("Consumer removed %d, computed %d! = %d, queue size = %d\\n", i, i, factorial(i), count);
pthread_mutex_unlock(&count_mutex);
}
else
{
printf("Unable to remove\\n");
}
}
printf("Consumer finished\\n");
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int count=0,pos=0,num=0;
char *str;
char buffer[5];
FILE *fp;
pthread_mutex_t count_mutex;
pthread_cond_t condc, condp;
int readf(FILE *fp)
{
if((fp=fopen("message.txt", "r"))==0){
printf("ERROR: can't open string.txt!\\n");
return 0;
}
str=(char *)malloc(sizeof(char)*1024);
if(str==0){
printf("ERROR: Out of memory!\\n");
return -1;
}
str=fgets(str, 1024, fp);
num=strlen(str);
}
void *producer(void *t)
{
int i;
for (i = 0; i <= num; i++) {
pthread_mutex_lock(&count_mutex);
while (count == 5)
pthread_cond_wait(&condp, &count_mutex);
buffer[count] = str[pos];
count++;
pos++;
pthread_cond_signal(&condc);
pthread_mutex_unlock(&count_mutex);
}
pthread_exit(0);
}
void *consumer(void *t)
{
pthread_mutex_lock(&count_mutex);
while (pos<num) {
pthread_cond_wait(&condc, &count_mutex);
printf("%s", buffer);
count = 0;
pthread_cond_signal(&condp);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main (int argc, char *argv[])
{
readf(fp);
pthread_t pro, con;
long t1=1, t2=2;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init(&condc, 0);
pthread_cond_init(&condp, 0);
pthread_create(&con, 0, consumer, (void *)t1);
pthread_create(&pro, 0, producer, (void *)t2);
pthread_join(con, 0);
pthread_join(pro, 0);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
sem_t c[5];
pthread_mutex_t lock;
void* func(void *y)
{
int valuel;
int valuer;
int l = (int)y;
int r;
sem_getvalue(&c[l], &valuel);
r = (l+1)%5;
sem_getvalue(&c[r], &valuer);
printf("\\nThe value of left is %d", valuel);
printf("\\nThe value of right is %d", valuer);
pthread_mutex_lock(&lock);
if(valuel>0&&valuer>0)
{
sem_wait(&c[l]);
sem_wait(&c[r]);
}
pthread_mutex_unlock(&lock);
printf(" \\n PHILOSOPHER %d IS EATING WITH FORK %d and %d ",l,l,r);
sem_post(&c[l]);
sem_post(&c[r]);
printf("\\n RELEASED RESOURCE: %d : %d",l,r);
printf("\\n Philosopher %d is thinking",l);
}
int main()
{
int i = 0;
int j=0;
pthread_t th[5];
pthread_mutex_init(&lock, 0);
for(i=0;i<=4;i++)
sem_init(&c[i],0,1);
while(j!=-1)
{
for(i=0;i<=4;i++)
{
pthread_create(&(th[i]), 0, func, (void*)i);
}
for(i=0;i<=4;i++)
{
pthread_join(th[i], 0);
}
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex_dernier_thread = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_dernier_thread = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex_libere = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_libere = PTHREAD_COND_INITIALIZER;
void* chaine(void* arg)
{
int nb = (*((int *) arg));
if (nb <= 1)
{
pthread_mutex_lock(&mutex_libere);
pthread_cond_signal(&cond_dernier_thread);
pthread_cond_wait(&cond_libere, &mutex_libere);
pthread_mutex_unlock(&mutex_libere);
}
else
{
int res;
pthread_t sub;
int* sub_arg = malloc(sizeof(int));
(*sub_arg) = nb - 1;
res = pthread_create(&sub, 0, chaine, sub_arg);
if (0 != res)
{
perror("pthread_create failed\\n");
exit(res);
}
pthread_join(sub, 0);
}
pthread_exit(0);
}
void handler_sigint(int s) {return;}
int main(int args, char* argv[])
{
int res;
int N = 3;
if (N <= 0) {exit(0);}
sigset_t new_mask;
sigfillset(&new_mask);
sigprocmask(SIG_BLOCK, &new_mask, 0);
pthread_t first;
int* first_arg = malloc(sizeof(int));
(*first_arg) = N;
res = pthread_create(&first, 0, chaine, first_arg);
if (0 != res)
{
perror("pthread_create failed\\n");
exit(res);
}
pthread_mutex_lock(&mutex_dernier_thread);
pthread_cond_wait(&cond_dernier_thread, &mutex_dernier_thread);
pthread_mutex_unlock(&mutex_dernier_thread);
printf("[%s] Tous mes decendants sont crees\\n",__FUNCTION__);
signal(SIGINT, handler_sigint);
sigset_t but_int_mask;
sigemptyset(&but_int_mask);
sigaddset(&but_int_mask, SIGINT);
sigprocmask(SIG_UNBLOCK, &but_int_mask, 0);
pause();
pthread_mutex_lock(&mutex_libere);
pthread_cond_signal(&cond_libere);
pthread_mutex_unlock(&mutex_libere);
pthread_join(first, 0);
printf("[%s] Tous mes descendants se sont terminés\\n",__FUNCTION__);
return 0;
}
| 0
|
#include <pthread.h>
buffer_item buffer[5];
sem_t full,empty;
pthread_mutex_t mutex;
int in = 0, out = 0;
int insert_item(buffer_item item) {
sem_wait(&empty);
pthread_mutex_lock(&mutex);
buffer[in] = item;
printf("buffer[%d]:", in);
in = (in + 1) % 5;
pthread_mutex_unlock(&mutex);
sem_post(&full);
return 0;
}
int remove_item(buffer_item *item) {
sem_wait(&full);
pthread_mutex_lock(&mutex);
*item = buffer[out];
buffer[out] = -1;
printf("buffer[%d]:", out);
out = (out + 1) % 5;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
return 0;
}
void *producer(void *param) {
buffer_item rand_item;
int sleep_time;
while (1) {
sleep_time = rand() % 10 + 1;
sleep(sleep_time);
rand_item = rand() % 1000 + 1;
if (insert_item(rand_item))
printf("Insert item %d failed!\\n", rand_item);
printf("Producer produced %d\\n", rand_item);
}
}
void *consumer(void * param) {
buffer_item rand_item;
int sleep_time;
while (1) {
sleep_time = rand() % 10 + 1;
sleep(sleep_time);
if (remove_item (&rand_item))
printf("Remove item failed!\\n");
printf("Consumer consumed %d\\n", rand_item);
}
}
int main(int argc, char *argv[]) {
int producer_num, consumer_num, sleep_time;
pthread_t pid[5];
pthread_t cid[5];
int i, value;
for (i = 0; i < 5; ++i) buffer[i] = -1;
if (argc >= 4) {
producer_num = atoi(argv[1]);
consumer_num = atoi(argv[2]);
sleep_time = atoi(argv[3]);
}
else {
if (argc == 3) {
producer_num = atoi(argv[1]);
consumer_num = atoi(argv[2]);
sleep_time = 60;
}
else {
if (argc == 2) {
producer_num = atoi(argv[1]);
consumer_num = 5;
sleep_time = 60;
}
else {
producer_num = 5;
consumer_num = 5;
sleep_time = 60;
}
}
}
if (producer_num > 5) {
printf("MAX_PRODUCER_NUM = 5!\\n");
producer_num = 5;
}
if (consumer_num > 5) {
printf("MAX_CONSUMER_NUM = 5!\\n");
consumer_num = 5;
}
if (sleep_time > 60) {
printf("MAX_SLEEP_TIME = 60!\\n");
sleep_time = 60;
}
printf("producer num = %d, consumer num = %d, sleep time = %d\\n", producer_num, consumer_num, sleep_time);
sem_init(&full, 0, 0);
sem_init(&empty, 0, 5);
pthread_mutex_init(&mutex, 0);
srand(time(0));
for (i = 0; i < producer_num; ++i) {
value = pthread_create(&pid[i], 0, (void *)producer, 0);
if (value != 0)
perror("Create producers error!\\n");
}
for (i = 0; i < consumer_num; ++i) {
value = pthread_create(&cid[i], 0, (void *)consumer, 0);
if (value != 0)
perror("Create consumers error!\\n");
}
sleep(sleep_time);
return 0;
}
| 1
|
#include <pthread.h>
unsigned char jrgba[] = { 1,2,3,255, 4,5,6,255, 7,8,9,255, 10,11,12,255, 13,14,15,255, 16,17,18,255,
19,20,21,255, 22,23,24,255, 25,26,27,255, 28,29,30,255 };
unsigned char jrgb[30];
{
unsigned char *rgba;
int rgba_len;
unsigned char *rgb;
int rgb_len;
int stripe;
} thread_parameters;
volatile int running_threads = 0;
pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER;
void *stripe_thread(void *param)
{
int i, j;
thread_parameters *params = (thread_parameters *) param;
unsigned char *rgba = params->rgba, *rgb = params->rgb;
for (i=params->stripe, j=params->stripe; i<params->rgba_len; i+= 4)
{
rgb[j] = rgba[i];
j += 3;
}
pthread_mutex_lock(&running_mutex);
running_threads--;
pthread_mutex_unlock(&running_mutex);
}
int main(int argc, char **argv)
{
pthread_t threads[3];
thread_parameters params[3];
int thread;
for (thread =0; thread<3; thread++)
{
params[thread].rgba = jrgba;
params[thread].rgba_len = sizeof(jrgba);
params[thread].rgb = jrgb;
params[thread].rgb_len = sizeof(jrgb);
params[thread].stripe = thread;
if (pthread_create(&threads[thread], 0, stripe_thread, (void *) ¶ms[thread]) != 0)
{
perror("Thread creation");
exit(1);
}
else
{
pthread_mutex_lock(&running_mutex);
running_threads++;
pthread_mutex_unlock(&running_mutex);
}
}
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 100000000L;
while (running_threads > 0)
{
if (nanosleep(&ts, 0) < 0)
break;
}
if (running_threads <= 0)
{
for (thread =0; thread<3; thread++)
pthread_join(threads[thread], 0);
}
for (thread=0; thread<sizeof(jrgb); thread++)
printf("%3d ", jrgb[thread]);
printf("\\n");
}
| 0
|
#include <pthread.h>
void *status_thread_handler(void *arg)
{
int led;
int beep;
int temperature;
char buf[4];
while (1)
{
pthread_mutex_lock(&SHM->led_mutex_start);
led = SHM->led_emit_status;
pthread_mutex_unlock(&SHM->led_mutex_start);
pthread_mutex_lock(&SHM->beep_mutex_status);
beep = SHM->beep_emit_status;
pthread_mutex_unlock(&SHM->beep_mutex_status);
pthread_mutex_lock(&SHM->status_mutex_temperature);
temperature = SHM->status_temperature;
pthread_mutex_unlock(&SHM->status_mutex_temperature);
lseek(*((int *)arg), 60, 0);
if (1 == led)
{
write(*((int *)arg), "ON ", 3);
}
else
{
write(*((int *)arg), "OFF", 3);
}
lseek(*((int *)arg), 82, 0);
if (1 == beep)
{
write(*((int *)arg), "ON ", 3);
}
else
{
write(*((int *)arg), "OFF", 3);
}
lseek(*((int *)arg), 106, 0);
if (100 <= temperature)
{
buf[0] = temperature / 100 + 0x30;
buf[1] = (temperature % 100) / 10 + 0x30;
buf[2] = temperature % 10 + 0x30;
buf[3] = '\\0';
write(*((int *)arg), buf, 3);
}
else if (10 <= temperature && 100 > temperature)
{
buf[0] = temperature / 10 + 0x30;
buf[1] = temperature % 10 + 0x30;
buf[2] = 0x20;
buf[3] = '\\0';
write(*((int *)arg), buf, 3);
}
else if (0 <= temperature && 9 >= temperature)
{
buf[0] = temperature + 0x30;
buf[1] = 0x20;
buf[2] = 0x20;
buf[3] = '\\0';
write(*((int *)arg), buf, 3);
}
usleep(500000);
}
}
| 1
|
#include <pthread.h>
sem_t officeSpace;
pthread_mutex_t globalLock ;
pthread_cond_t answerCond;
pthread_mutex_t answer_lock;
pthread_cond_t askedCond;
pthread_mutex_t asked_lock;
int askerId ;
int studentId ;
int sQuestionId;
pthread_mutex_t proflock;
int studentsLeft;
pthread_mutex_t student_lock;
int asked = 0;
int answer = 0;
int main(int argc, char * argv[]){
int students;
int totalStudents;
if(argc < 3 || argc > 3){
printf("Not enough arguments\\n");
return 2;
}
if(strcmp(argv[1], "0") == 0){
students = 0;
}else{
students = atoi(argv[1]);
if(students <= 0){
printf("Invalid input!\\n");
return 1;
}
}
studentsLeft = students;
totalStudents = students ;
int officeCapacity;
if(strcmp(argv[2], "0") == 0){
printf("Minimum office capacity is 1.\\n");
return 5;
}else{
officeCapacity = atoi(argv[2]);
if(officeCapacity <= 0){
printf("Invalid input!\\n");
return 2;
}
}
if(atoi(argv[1]) > THREADMAX){
printf("The professor cannot handle that many students\\n");
return 3;
}
printf("%d student(s) and an office capacity of %d\\n",students,
officeCapacity);
sem_init(&officeSpace, 0, officeCapacity);
pthread_mutex_init(&proflock, 0);
pthread_mutex_init(&answer_lock, 0);
pthread_mutex_init(&asked_lock, 0);
pthread_mutex_init(&student_lock, 0);
pthread_mutex_init(&globalLock, 0) ;
pthread_cond_init(&answerCond, 0);
pthread_cond_init(&askedCond, 0);
pthread_t professor_tid;
pthread_create(&professor_tid, 0, professor, 0);
printf("The professor has entered the office.\\n");
int i;
pthread_t studentThreadIDs[students];
for(i = 0; i < totalStudents; i++){
pthread_create(&studentThreadIDs[i], 0,
Student, (void*)i);
}
int j ;
for(j = 0; j < totalStudents; j++){
pthread_join(studentThreadIDs[j], 0);
}
printf("\\nAll of the students are finished!\\n");
pthread_join(professor_tid, 0);
printf("\\nProfessor is going home!\\n");
return 0;
}
void *professor(void* arg){
pthread_mutex_lock(&student_lock);
while(studentsLeft > 0){
pthread_mutex_unlock(&student_lock);
pthread_mutex_lock(&student_lock);
pthread_mutex_lock(&asked_lock);
while(!asked){
pthread_cond_wait(&askedCond, &asked_lock);
if(studentsLeft == 0){
break ;
}
}
if(studentsLeft == 0){
break ;
}
asked = 0;
pthread_mutex_unlock(&asked_lock);
pthread_mutex_lock(&answer_lock);
AnswerStart();
AnswerDone();
answer = 1;
pthread_cond_signal(&answerCond);
pthread_mutex_unlock(&answer_lock);
pthread_mutex_unlock(&student_lock);
}
pthread_exit(0);
}
void *Student(void* ID){
int id = (int)ID ;
int noQuestions;
sem_wait(&officeSpace);
pthread_mutex_lock(&globalLock) ;
studentId = id ;
pthread_mutex_unlock(&globalLock) ;
EnterOffice();
for(noQuestions = (id % 4) + 1; noQuestions > 0; noQuestions--){
pthread_mutex_lock(&proflock);
askerIdLock(id) ;
pthread_mutex_lock(&asked_lock);
QuestionStart();
askerIdLock(id) ;
asked = 1;
pthread_cond_signal(&askedCond);
pthread_mutex_unlock(&asked_lock);
pthread_mutex_lock(&answer_lock);
while(!answer){
pthread_cond_wait(&answerCond, &answer_lock);
askerIdLock(id) ;
}
QuestionDone();
pthread_mutex_unlock(&answer_lock);
answer = 0;
pthread_mutex_unlock(&proflock);
usleep(100000) ;
}
askerIdLock(id) ;
LeaveOffice();
sem_post(&officeSpace);
studentsLeft--;
if( (studentsLeft == 0) ) {
pthread_cond_signal(&askedCond);
}
pthread_exit(0) ;
}
void QuestionStart(){
printf("Student %d is asking a question.\\n", askerId);
}
void QuestionDone(){
printf("Student %d is satisfied with the professor's answer.\\n", askerId);
usleep(1000) ;
}
void AnswerStart(){
printf("The professor is answering a question for student %d.\\n", askerId);
}
void AnswerDone(){
printf("The professor has finished answering the question for student %d.\\n",
askerId);
}
void EnterOffice(){
printf("Student %d has entered the office\\n", studentId);
}
void LeaveOffice(){
printf("Student %d is leaving the office\\n", askerId);
}
void askerIdLock(int id){
pthread_mutex_lock(&globalLock);
askerId = id ;
pthread_mutex_unlock(&globalLock) ;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t POS_Turret_Write_Lock = PTHREAD_MUTEX_INITIALIZER;
static int POS_Turret_Pitch_Percent;
static int POS_Turret_Yaw_Percent;
void Init_Turret(void)
{
pthread_mutex_unlock(&POS_Turret_Write_Lock);
POS_Turret_Pitch_Percent=0;
POS_Turret_Yaw_Percent=0;
}
void Set_Turret_Yaw_Setting(int rawdata)
{
while(pthread_mutex_lock(&POS_Turret_Write_Lock) != 0)
{
usleep(39+(rawdata%16));
}
POS_Turret_Yaw_Percent=rawdata%100;
pthread_mutex_unlock(&POS_Turret_Write_Lock);
return;
}
void Set_Turret_Pitch_Setting(int rawdata)
{
while(pthread_mutex_lock(&POS_Turret_Write_Lock) != 0)
{
usleep(25+(rawdata%16));
}
POS_Turret_Pitch_Percent=rawdata%100;
pthread_mutex_unlock(&POS_Turret_Write_Lock);
return;
}
void Update_Turret(int pitch, int yaw)
{
while(pthread_mutex_lock(&POS_Turret_Write_Lock) != 0)
{
usleep(29+(pitch%16));
}
POS_Turret_Pitch_Percent=pitch%100;
POS_Turret_Yaw_Percent=yaw%100;
pthread_mutex_unlock(&POS_Turret_Write_Lock);
return;
}
int Get_Turret_Yaw_Setting(void)
{
if(POS_Turret_Yaw_Percent > 0)
{
return (POS_Turret_Yaw_Percent * TURRET_YAW_FORDWARD_INDEX)
+TURRET_YAW_SERVO_CENTER;
}else{
return (POS_Turret_Yaw_Percent * TURRET_YAW_BACKWARD_INDEX)
+TURRET_YAW_SERVO_CENTER;
}
return 0;
}
int Get_Turret_Pitch_Setting(void)
{
if(POS_Turret_Pitch_Percent > 0)
{
return (POS_Turret_Pitch_Percent * TURRET_PITCH_FORDWARD_INDEX)
+TURRET_PITCH_SERVO_CENTER;
}else{
return (POS_Turret_Pitch_Percent * TURRET_PITCH_BACKWARD_INDEX)
+TURRET_PITCH_SERVO_CENTER;
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t thereAreOxygen, thereAreHydrogen;
int numberOxygen = 0 , numberHydrogen=0;
int activeOxygen = 0 , activeHydrogen=0;
long currentOxygen = 0 , currentHydrogen=0;
int flagExit=0;
void dataIn(){
int var=-3;
if(numberHydrogen==1 && flagExit==0){
while (var<-1) {
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n");
printf("Aviso: Queda 1 atomo de hidrogeno.\\nIngrese atomos de hidrogeno o ingrese -1 para salir:", numberHydrogen );
scanf("%d",&var);
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n");
}
if(var==-1){
flagExit=1;
}else{
numberHydrogen+=var;
}
}
var=-3;
if(numberOxygen==0 && numberHydrogen>0 && flagExit==0){
while (var<-1) {
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n");
printf("Aviso: Hay %d atomo(s) de hidrogeno, se necesitan %d atomo(s) de oxigeno.\\nIngrese atomos de oxigeno o ingrese -1 para salir: ", numberHydrogen,(numberHydrogen/2));
scanf("%d",&var);
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n");
}
if(var==-1){
flagExit=1;
}else{
numberOxygen+=var;
}
}
var=-3;
if(numberHydrogen==0 && numberOxygen>0 && flagExit==0){
while (var<-1) {
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n");
printf("Aviso: Hay %d atomo(s) de oxigeno, se necesitan %d atomo(s) hidrogeno.\\nIngrese atomos de hidrogeno o ingrese -1 para salir: ", numberOxygen, (numberOxygen*2) );
scanf("%d",&var);
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n");
}
if(var==-1){
flagExit=1;
}else{
numberHydrogen+=var;
}
}
if (flagExit==1) {
printf("Escriba 1 para salir, o cualquier numero para cancelar.. :");
scanf("%d",&var);
if(var==1){
exit(0);
}
else{
flagExit=0;
dataIn();
}
}
}
void startOxygen(){
pthread_mutex_lock(&lock);
++activeOxygen;
while (activeHydrogen<2 && activeOxygen>1) {
pthread_cond_wait(&thereAreOxygen, &lock);
}
++currentOxygen;
--numberOxygen;
pthread_mutex_unlock(&lock);
}
void doneOxygen() {
pthread_mutex_lock(&lock);
--activeOxygen;
pthread_cond_broadcast(&thereAreHydrogen);
pthread_mutex_unlock(&lock);
}
void startHydrogen(){
pthread_mutex_lock(&lock);
++activeHydrogen;
while (activeOxygen<1 && activeHydrogen>2) {
pthread_cond_wait(&thereAreHydrogen, &lock);
}
--numberHydrogen;
++currentHydrogen;
pthread_mutex_unlock(&lock);
}
void doneHydrogen() {
pthread_mutex_lock(&lock);
--activeHydrogen;
pthread_cond_signal(&thereAreOxygen);
pthread_mutex_unlock(&lock);
}
void *Oxigeno(void *id) {
long tid = (long)id;
printf("oxigeno (%ld) preparado para ser H2O \\n", tid);
startOxygen();
printf("oxigeno (%ld) convirtiendose \\n",tid);
sleep(rand()%5);
printf("oxigeno (%ld) es H2O \\n", tid);
doneOxygen();
dataIn();
sleep(rand()%5);
pthread_exit(0);
}
void *Hidrogeno(void *id) {
long tid = (long)id;
startHydrogen();
sleep(rand()%5);
doneHydrogen();
sleep(rand()%5);
pthread_exit(0);
}
int main(int argc, char const *argv[]) {
int n_oxygen=-3;
int n_hydrogen=-3;
pthread_t oxygen, hydrogen[2];
long i=0;
srand(time(0));
printf("\\n--------------Nombre del programa--------------\\n\\tCreación de moleculas de agua\\n\\n");
while (n_oxygen<-1){
printf("Ingrese numero de Oxigeno: ");
scanf("%d",&n_oxygen);
}
numberOxygen+=n_oxygen;
while (n_hydrogen<-1) {
printf("Ingrese numero de hidrogeno:");
scanf("%d",&n_hydrogen);
}
numberHydrogen+=n_hydrogen;
while ( numberOxygen>0 && numberHydrogen>0) {
for (i=0; i<2; i++) {
if (pthread_create(&hydrogen[i], 0, Hidrogeno, (void *)(i))) {
printf("Error creando thread hidrogeno[%ld]\\n", i);
exit(1);
}
}
i=0;
if (pthread_create(&oxygen, 0,Oxigeno, (void *)currentOxygen)) {
printf("Error creando thread oxigeno[%ld]\\n", i);
exit(1);
}
void *status;
for (i=0; i<2; i++)
{
pthread_join(hydrogen[i],&status);
}
pthread_join(oxygen,&status);
}
return 0;
}
| 0
|
#include <pthread.h>
char shared_read_buffer[(unsigned long)80*1024];
long shared_word_count = 0;
pthread_mutex_t count_mutex;
struct thread_info {
pthread_t thread_id;
int thread_num;
};
struct read_bound {
unsigned long boundary_array[1 +1];
} bound_struct;
unsigned long find_word_bound(unsigned long init_pos, unsigned long prev_pos, unsigned long buffer_size)
{
int search_direction = 1, search_distance = 1;
while(isalpha(shared_read_buffer[init_pos]) && init_pos > prev_pos && init_pos < buffer_size)
{
init_pos += search_distance * search_direction;
search_direction = - search_direction;
search_distance++;
}
return init_pos;
}
void map(int thread_count, unsigned long buffer_size)
{
unsigned long previous_bound = 0;
bound_struct.boundary_array[0] = 0;
bound_struct.boundary_array[thread_count] = buffer_size-1;
for(int i=1;i<thread_count;i++)
{
previous_bound = find_word_bound((buffer_size/thread_count)*i,previous_bound,buffer_size-1);
bound_struct.boundary_array[i] = previous_bound;
}
}
void* reduce(void* t_info_arg)
{
struct thread_info *tinfo = t_info_arg;
unsigned long start, end;
int last_was_alnum = 0;
start = bound_struct.boundary_array[tinfo->thread_num-1];
end = bound_struct.boundary_array[tinfo->thread_num];
while(start < end)
{
if(isalnum(shared_read_buffer[start]))
{
if(!last_was_alnum)
{
pthread_mutex_lock(&count_mutex);
shared_word_count++;
pthread_mutex_unlock(&count_mutex);
last_was_alnum = 1;
}
}
else
{
last_was_alnum = 0;
}
start++;
}
return 0;
}
void spawn_threads(int thread_count)
{
int tnum;
struct thread_info *t_info;
t_info = calloc(thread_count, sizeof(struct thread_info));
for (tnum = 1; tnum <= thread_count; tnum++) {
t_info[tnum].thread_num = tnum;
if(pthread_create(&t_info[tnum].thread_id,0,&reduce,&t_info[tnum]))
{
fprintf(stderr,"Error during thread creation.\\n");
exit(3);
}
}
tnum--;
while(tnum)
{
pthread_join(t_info[tnum].thread_id,0);
tnum--;
}
free(t_info);
}
int main(int argc, const char * argv[]) {
FILE* f_stream = 0;
unsigned long bytes_read = 0;
if(!(argc == 2)){
fprintf(stderr,"Error: Must call word count with the target file as the command line argument\\n");
exit(1);
}
f_stream = fopen(argv[1],"r");
if(!f_stream)
{
if(errno == ENOENT)
{
fprintf(stderr, "Target file specified does not exist\\n");
}
else
{
fprintf(stderr,"Error: Problem opening target file.\\n");
}
exit(2);
}
pthread_mutex_init(&count_mutex,0);
bytes_read = fread(shared_read_buffer,1,(unsigned long)80*1024,f_stream);
while(bytes_read > 0)
{
map(1, bytes_read);
spawn_threads(1);
bytes_read = fread(shared_read_buffer,1,(unsigned long)80*1024,f_stream);
}
fclose(f_stream);
printf("%li words\\n",shared_word_count);
pthread_mutex_destroy(&count_mutex);
return 0;
}
| 1
|
#include <pthread.h>
FILE *fdatabase, *fquery, *fout;
pthread_mutex_t mutex;
int bmhs(char *string, int n, char *substr, int m) {
int d[256];
int i, j, k;
for (j = 0; j < 256; j++)
d[j] = m + 1;
for (j = 0; j < m; j++)
d[(int) substr[j]] = m - j;
i = m - 1;
while (i < n) {
k = i;
j = m - 1;
while ((j >= 0) && (string[k] == substr[j])) {
j--;
k--;
}
if (j < 0)
return k + 1;
i = i + d[(int) string[i + 1]];
}
return -1;
}
void openfiles(char *database, char *query) {
fdatabase = fopen(database, "r+");
if (fdatabase == 0) {
perror(database);
exit(1);
}
fquery = fopen(query, "r");
if (fquery == 0) {
perror(query);
exit(1);
}
fout = fopen("output/dna.out", "w");
if (fout == 0) {
perror("fout");
exit(1);
}
}
void closefiles() {
fflush(fdatabase);
fclose(fdatabase);
fflush(fquery);
fclose(fquery);
fflush(fout);
fclose(fout);
}
inline void remove_eol(char *line) {
int i = strlen(line) - 1;
while (line[i] == '\\n' || line[i] == '\\r') {
line[i] = 0;
i--;
}
}
int get_next_query_descripton(char query_description[]) {
fgets(query_description, 100, fquery);
remove_eol(query_description);
if(!feof(fquery))
return 1;
return 0;
}
void get_next_query_string(char *str) {
char line[100];
int i = 0;
long prev_pos = ftell(fquery);
fgets(line, 100, fquery);
remove_eol(line);
str[0] = 0;
i = 0;
do {
strcat(str + i, line);
prev_pos = ftell(fquery);
if (fgets(line, 100, fquery) == 0)
break;
remove_eol(line);
i += 80;
} while (line[0] != '>');
fseek(fquery, prev_pos, 0);
}
int get_next_base_description(char base_description[]) {
fgets(base_description, 100, fdatabase);
remove_eol(base_description);
if(!feof(fdatabase))
return 1;
return 0;
}
void get_next_base_string(char *base) {
char line[100];
int i = 0;
long prev_pos = ftell(fdatabase);
base[0] = 0;
i = 0;
fgets(line, 100, fdatabase);
remove_eol(line);
do {
strcat(base + i, line);
prev_pos = ftell(fdatabase);
if (fgets(line, 100, fdatabase) == 0)
break;
remove_eol(line);
i += 80;
} while (line[0] != '>');
fseek(fdatabase, prev_pos, 0);
}
void* findQuery() {
char desc_dna[100], desc_query[100];
char *base = (char*) malloc(sizeof(char) * 1000001);
char *str = (char*) malloc(sizeof(char) * 1000001);
pthread_mutex_lock(&mutex);
get_next_query_descripton(desc_query);
get_next_query_string(str);
pthread_mutex_unlock(&mutex);
}
int main(int argc, char *argv[]) {
if (argc != 4) {
printf("Insufficient number of parameters!\\nUsage: %s <database file> <query file> <nthreads>\\n\\n", argv[0]);
exit(1);
}
const int nthreads = atoi(argv[3]);
pthread_mutex_init(&mutex,0);
struct timeval start_computation, end_computation;
struct timeval start_total, end_total;
unsigned long int time_computation = 0, time_total;
gettimeofday(&start_total, 0);
openfiles(argv[1], argv[2]);
char *base = (char*) malloc(sizeof(char) * 1000001);
if (base == 0) {
perror("malloc");
exit(1);
}
char *str = (char*) malloc(sizeof(char) * 1000001);
if (str == 0) {
perror("malloc str");
exit(1);
}
char desc_dna[100], desc_query[100];
int found, result;
while (get_next_query_descripton(desc_query)) {
fprintf(fout, "%s\\n", desc_query);
get_next_query_string(str);
found = 0;
fseek(fdatabase, 0, 0);
while (get_next_base_description(desc_dna)) {
get_next_base_string(base);
gettimeofday(&start_computation, 0);
result = bmhs(base, strlen(base), str, strlen(str));
gettimeofday(&end_computation, 0);
time_computation += (end_computation.tv_sec - start_computation.tv_sec) * 1000000 + end_computation.tv_usec - start_computation.tv_usec;
if (result > 0) {
fprintf(fout, "%s\\n%d\\n", desc_dna, result);
found++;
}
}
if (!found)
fprintf(fout, "NOT FOUND\\n");
}
closefiles();
free(str);
free(base);
pthread_mutex_destroy(&mutex);
gettimeofday(&end_total, 0);
time_total = (end_total.tv_sec - start_total.tv_sec) * 1000000 + end_total.tv_usec - start_total.tv_usec;
printf("Elapsed computing time: %ld microseconds.\\nI/O time: %ld microseconds\\n", time_computation, time_total - time_computation);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex_numero_disponibili = PTHREAD_MUTEX_INITIALIZER;
void incrementaconttorepadre(struct threadnumero *numerothreadprinc)
{
pthread_mutex_lock( &mutex_numero_disponibili );
if(numerothreadprinc->threadliberi>=MASSIMO_THREAD_LIBERI)
{
printf("ADDIO %d\\n",(int)pthread_self());
pthread_exit(0);
}
else
numerothreadprinc->threadliberi++;
pthread_mutex_unlock( &mutex_numero_disponibili );
}
void decrementaconttorepadre(struct threadnumero *numerothreadprinc)
{
pthread_mutex_lock( &mutex_numero_disponibili );
numerothreadprinc->threadliberi--;
pthread_mutex_unlock( &mutex_numero_disponibili );
}
void *lavorothreadfigli(void *arg){
struct datiutiliaithread *datiutili=(struct datiutiliaithread *)arg;
int cont;
for(cont=0;cont<ITERAZIONI_MASSIME_THREAD;cont++){
incrementaconttorepadre(datiutili->numero);
int connsd;
if ((connsd = accept(datiutili->datiaccept, (struct sockaddr *)0, 0)) < 0) {
perror("errore in accept");
exit(1);
}
printf("accept %d\\n",(int)pthread_self());
sleep(1);
decrementaconttorepadre(datiutili->numero);
char* buff="HTTP/1.1 200 OK\\nContent-length: 46\\nContent-Type: text/html\\n\\n<html><body><H1>Hello world</H1></body></html>";
if (write(connsd,buff,strlen(buff))<0) {
perror("errore in write");
exit(1);
}
printf("write\\n");
if (close(connsd) == -1) {
perror("errore in close");
exit(1);
}
printf("close\\n");
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
struct barrier {
int num;
int hit;
int hits[16];
pthread_cond_t ncond;
pthread_mutex_t nlock;
pthread_cond_t brcond;
pthread_mutex_t brlock;
pthread_t tids[16];
int tid_count;
pthread_t daemon_tid;
};
void *pbdaemon(void *arg) {
struct barrier * pb = (struct barrier *)arg;
while (pb->hit < pb->num) {
pthread_mutex_lock( &(pb->nlock) );
pthread_cond_wait( &(pb->ncond), &(pb->nlock) );
printf("Daemon: %d hits!\\n", pb->hit);
pthread_mutex_unlock( &(pb->nlock) );
}
int bn = pb->hit;
while (bn-- > 0) {
pthread_mutex_lock( &(pb->brlock) );
pthread_mutex_unlock( &(pb->brlock) );
pthread_cond_signal( &(pb->brcond) );
printf("%s\\n", "Daemon: signal -> some thread, I don't even know.");
}
return 0;
}
void pbinit(struct barrier * br, int bn) {
int err = 0;
if (bn > 16) {
fprintf(stderr, "%s\\n", "pbinit(): threads number too big");
exit(1);
}
br->tid_count = -1;
br->num = bn;
br->hit = 0;
err = pthread_cond_init( &(br->ncond), 0 );
if (err != 0) err_exit(err, "br->ncond init failed");
err = pthread_mutex_init( &(br->nlock), 0 );
if (err != 0) err_exit(err, "br->nlock init failed");
err = pthread_cond_init( &(br->brcond), 0);
if (err != 0) err_exit(err, "br->brcond init failed");
err = pthread_mutex_init( &(br->brlock), 0);
if (err != 0) err_exit(err, "br->brlock init failed");
err = pthread_create( &(br->daemon_tid), 0, pbdaemon, br);
if (err != 0) err_exit(err, "creating barrier daemon thread failed");
err = pthread_detach( br->daemon_tid );
if (err != 0) err_exit(err, "detaching barrier daemon thread failed");
return;
}
void pbw(struct barrier *br) {
int id;
pthread_mutex_lock( &(br->nlock) );
id = ++(br->tid_count);
br->hit++;
pthread_cond_signal( &(br->ncond) );
printf("%d: signal -> daemon!\\n", id);
pthread_mutex_unlock( &(br->nlock) );
pthread_mutex_lock( &(br->brlock) );
pthread_cond_wait(
&(br->brcond),
&(br->brlock)
);
pthread_mutex_unlock( &(br->brlock) );
return;
}
struct barrier b;
void * thr(void *arg) {
pbw(&b);
printf("It's child thread %x\\n", pthread_self());
pthread_exit(0);
}
int main() {
pthread_t tid1, tid2;
int err;
pbinit(&b, 3);
err = pthread_create(&tid1, 0, thr, (void *)1);
if (err != 0)
err_exit(err, "error creating thr1");
err = pthread_create(&tid2, 0, thr, (void *)2);
if (err != 0)
err_exit(err, "error creating thr2");
printf("%s\\n", "It's parent");
sleep(1);
pbw(&b);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
return 0;
}
| 0
|
#include <pthread.h>
int circbuf_init(struct circbuf *cbuf, char *buffer, int len, const char *name)
{
cbuf->buffer = buffer;
cbuf->posWrite = cbuf->posRead = 0;
cbuf->nlen = len;
pthread_mutex_init(&cbuf->lock, 0);
pthread_cond_init(&cbuf->notEmpty, 0);
pthread_cond_init(&cbuf->notFull, 0);
cbuf->name = name;
return 0;
}
int circbuf_destroy(struct circbuf *cbuf)
{
pthread_mutex_destroy(&cbuf->lock);
pthread_cond_destroy(&cbuf->notEmpty);
pthread_cond_destroy(&cbuf->notFull);
return 0;
}
int circbuf_is_full(struct circbuf *cbuf)
{
return CIRC_SPACE(cbuf->posWrite, cbuf->posRead, cbuf->nlen) == 0 ? 1 : 0;
}
int circbuf_is_empty(struct circbuf *cbuf)
{
return CIRC_CNT(cbuf->posWrite, cbuf->posRead, cbuf->nlen) == 0 ? 1 : 0;
}
int circbuf_available(struct circbuf *cbuf)
{
return CIRC_SPACE(cbuf->posWrite, cbuf->posRead, cbuf->nlen);
}
int circbuf_available_to_end(struct circbuf *cbuf)
{
return CIRC_SPACE_TO_END(cbuf->posWrite, cbuf->posRead, cbuf->nlen);
}
int circbuf_cnt(struct circbuf *cbuf)
{
return CIRC_CNT(cbuf->posWrite, cbuf->posRead, cbuf->nlen);
}
int circbuf_cnt_to_end(struct circbuf *cbuf)
{
return CIRC_CNT_TO_END(cbuf->posWrite, cbuf->posRead, cbuf->nlen);
}
int circbuf_write(struct circbuf *cbuf, char *buf, int len)
{
int avail;
int nwrite;
int ncnt;
char *pbuf = buf;
struct timespec timeout;
pthread_mutex_lock(&cbuf->lock);
while(circbuf_is_full(cbuf)) {
timeout.tv_sec=time(0);
timeout.tv_nsec=256000;
pthread_cond_timedwait(&cbuf->notFull, &cbuf->lock, &timeout);
}
avail = circbuf_available(cbuf);
if(avail > len) {
ncnt = len;
} else {
ncnt = avail;
}
nwrite = ncnt;
while(nwrite > 0) {
int cnt = 0;
int avail2end = circbuf_available_to_end(cbuf);
if(nwrite > avail2end) {
cnt = avail2end;
} else {
cnt = nwrite;
}
memcpy(cbuf->buffer + cbuf->posWrite, pbuf, cnt);
nwrite -= cnt;
cbuf->posWrite += cnt;
cbuf->posWrite %= cbuf->nlen;
pbuf += cnt;
}
pthread_cond_signal(&cbuf->notEmpty);
pthread_mutex_unlock(&cbuf->lock);
return ncnt;
}
int circbuf_block_write(struct circbuf *cbuf, char *buf, int len)
{
int ncnt = 0;
int ret;
char *pbuf = buf;
ncnt = len;
while(ncnt > 0) {
ret = circbuf_write(cbuf, pbuf, ncnt);
ncnt -= ret;
pbuf += ret;
}
return len - ncnt;
}
int circbuf_read(struct circbuf *cbuf, char *buf, int len)
{
int ncnt;
int nread;
int avail;
char *pbuf = buf;
pthread_mutex_lock(&cbuf->lock);
while(circbuf_is_empty(cbuf)) {
pthread_cond_wait(&cbuf->notEmpty, &cbuf->lock);
}
avail = circbuf_cnt(cbuf);
if(avail > len) {
nread = len;
} else {
nread = avail;
}
ncnt = nread;
while(nread > 0) {
int cnt;
int cnt2end = circbuf_cnt_to_end(cbuf);
if(nread > cnt2end) {
cnt = cnt2end;
} else {
cnt = nread;
}
memcpy(pbuf, cbuf->buffer + cbuf->posRead, cnt);
nread -= cnt;
cbuf->posRead += cnt;
cbuf->posRead %= cbuf->nlen;
pbuf += cnt;
}
pthread_cond_signal(&cbuf->notFull);
pthread_mutex_unlock(&cbuf->lock);
return ncnt;
}
int circbuf_block_read(struct circbuf *cbuf, char *buf, int len)
{
int ncnt = 0;
int ret = 0;
char *pbuf = buf;
ncnt = len;
while(ncnt > 0) {
ret = circbuf_read(cbuf, pbuf, ncnt);
pbuf += ret;
ncnt -= ret;
}
return len - ncnt;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t lock;
static void* thread(void* idp) {
int tid = (intptr_t)idp;
int i;
atomic_printf("thread %d starting ...\\n", tid);
for (i = 0; i < 1000; ++i) {
pthread_mutex_lock(&lock);
sched_yield();
pthread_mutex_unlock(&lock);
}
atomic_printf(" ... thread %d done.\\n", tid);
return 0;
}
int main(void) {
pthread_mutexattr_t attr;
pthread_t threads[10];
int i, err;
pthread_mutexattr_init(&attr);
test_assert(0 == pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT));
if ((err = pthread_mutex_init(&lock, &attr))) {
test_assert(ENOTSUP == err);
test_assert(0 == pthread_mutex_init(&lock, 0));
}
for (i = 0; i < 10; ++i) {
test_assert(0 ==
pthread_create(&threads[i], 0, thread, (void*)(intptr_t)i));
}
for (i = 0; i < 10; ++i) {
test_assert(0 == pthread_join(threads[i], 0));
}
atomic_puts("EXIT-SUCCESS");
return 0;
}
| 0
|
#include <pthread.h>
int PBSD_mgr_put(
int c,
int function,
int command,
int objtype,
char *objname,
struct attropl *aoplp,
char *extend)
{
int rc = PBSE_NONE;
int sock;
struct tcp_chan *chan = 0;
pthread_mutex_lock(connection[c].ch_mutex);
sock = connection[c].ch_socket;
if ((chan = DIS_tcp_setup(sock)) == 0)
{
pthread_mutex_unlock(connection[c].ch_mutex);
rc = PBSE_PROTOCOL;
return rc;
}
else if ((rc = encode_DIS_ReqHdr(chan, function, pbs_current_user)) ||
(rc = encode_DIS_Manage(chan, command, objtype, objname, aoplp)) ||
(rc = encode_DIS_ReqExtend(chan, extend)))
{
connection[c].ch_errtxt = strdup(dis_emsg[rc]);
pthread_mutex_unlock(connection[c].ch_mutex);
DIS_tcp_cleanup(chan);
rc = PBSE_PROTOCOL;
return rc;
}
if (DIS_tcp_wflush(chan))
{
pthread_mutex_unlock(connection[c].ch_mutex);
rc = PBSE_PROTOCOL;
}
pthread_mutex_unlock(connection[c].ch_mutex);
DIS_tcp_cleanup(chan);
return rc;
}
| 1
|
#include <pthread.h>
inline void client_set_id(struct client_t *target, const unsigned id)
{
target->cl_id = id;
}
inline void client_set_sock(struct client_t *target, const int sock)
{
target->cl_sock = sock;
}
inline void client_set_room(struct client_t *target, struct room_t *room)
{
target->cl_room = room;
}
inline void client_buff_clear(struct client_t *target)
{
memset(target->cl_buff, 0, CLIENT_BUFFER_SIZE);
target->cl_free = CLIENT_BUFFER_SIZE;
}
void client_dc(struct client_t *target)
{
close(target->cl_sock);
memset(target->cl_buff, 0, CLIENT_BUFFER_SIZE);
target->cl_write_p = target->cl_buff;
room_remove_member(target->cl_room, target);
}
static void client_dump_buffer(struct client_t *target)
{
if (send(target->cl_sock, target->cl_buff, CLIENT_BUFFER_SIZE, 0) < 0) {
perror("send");
client_dc(target);
}
memset(target->cl_buff, 0, CLIENT_BUFFER_SIZE);
target->cl_write_p = target->cl_buff;
}
int client_buff_push(struct client_t *target, char *buff, size_t sz)
{
int c = 0;
pthread_mutex_lock(&target->cl_buff_locked);
while (c < sz && target->cl_free > 0) {
*target->cl_write_p = *buff++;
++c;
--target->cl_free;
++target->cl_write_p;
}
if (target->cl_free == 0) {
client_dump_buffer(target);
target->cl_free = CLIENT_BUFFER_SIZE;
}
pthread_mutex_unlock(&target->cl_buff_locked);
if (sz > c)
return c + client_buff_push(target, buff, sz);
return c;
}
struct client_t *client_init(void)
{
struct client_t *ret;
ret = (struct client_t *) malloc(1 * sizeof(struct client_t));
ret->cl_id = 0;
ret->cl_sock = 0;
ret->cl_write_p = ret->cl_buff;
ret->cl_free = CLIENT_BUFFER_SIZE;
ret->cl_room = 0;
memset(ret->cl_buff, 0, CLIENT_BUFFER_SIZE);
pthread_mutex_init(&ret->cl_buff_locked, 0);
return ret;
}
void client_destroy(struct client_t *target)
{
if (target == 0)
return;
close(target->cl_sock);
pthread_mutex_destroy(&target->cl_buff_locked);
free(target);
}
static inline void client_wrq(struct client_t *target, char *buff, size_t sz)
{
room_add_buff(target->cl_room, buff, sz, target);
}
inline int client_pull(struct client_t *target, char *buff, size_t sz)
{
return recv(target->cl_sock, buff, sz, 0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void mutex_cleanup(void *arg)
{
pthread_mutex_unlock((pthread_mutex_t*)arg);
return;
}
void *pthread1(void *arg)
{
int ret;
pthread_mutex_lock(&mutex);
pthread_cleanup_push(mutex_cleanup, &mutex);
fprintf(stdout, "pthread1 got mutex\\n");
sleep(3);
fprintf(stdout, "cancel pthread here not appear\\n");
pthread_cleanup_pop(1);
pthread_exit(0);
}
void *pthread2(void *arg)
{
sleep(1);
pthread_cancel((pthread_t)arg);
pthread_mutex_lock(&mutex);
fprintf(stdout, "pthread2 got mutex\\n");
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
pthread_t ptrdid1, ptrdid2;
pthread_create(&ptrdid1, 0, pthread1, 0);
pthread_create(&ptrdid2, 0, pthread2, (void **)ptrdid1);
void *status;
pthread_join(ptrdid1, &status);
if (PTHREAD_CANCELED != status) {
fprintf(stdout, "pthread1 status %p\\n", status);
}
pthread_join(ptrdid2, &status);
if (0 != status) {
fprintf(stdout, "pthread2 status %p\\n", status);
}
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
void *getMoney(char *);
int totalMoney = 4000;
int * moneyPtr = &totalMoney;
pthread_mutex_t mutex1;
int main()
{
pthread_t stu1, stu2, stu3;
char a='a',b ='b',c ='c';
char * charptrA = &a, *charptrB=&b, *charptrC=&c;
pthread_mutex_init(&mutex1, 0);
while (totalMoney > 1)
{
pthread_create(&stu1, 0, getMoney, charptrA);
pthread_create(&stu2, 0, *getMoney, charptrB);
pthread_create(&stu3, 0, &getMoney, charptrC);
}
}
void * getMoney(char * charPtr)
{
int amtReceived = 0;
int amtGiven = 0;
pthread_mutex_lock(&mutex1);
{
amtGiven = ceil(*moneyPtr * .25);
printf("amtGiven %c: $%i\\n",*charPtr, amtGiven );
*moneyPtr = *moneyPtr - amtGiven;
amtReceived = amtReceived + amtGiven;
}
pthread_mutex_unlock(&mutex1);
sleep(1);
}
| 0
|
#include <pthread.h> extern void __VERIFIER_error() ;
void __VERIFIER_assert(int cond) { if (!(cond)) { ERROR: __VERIFIER_error(); } return; }
int myglobal;
pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
void *thread_function_mutex(void *arg)
{
int i,j;
for ( i=0; i<20; i++ )
{
pthread_mutex_lock(&mymutex);
j=myglobal;
j=j+1;
printf("\\nIn thread_function_mutex..\\t");
myglobal=j;
pthread_mutex_unlock(&mymutex);
}
return 0;
}
int main(void)
{
pthread_t mythread;
int i;
printf("\\n\\t\\t---------------------------------------------------------------------------");
printf("\\n\\t\\t Centre for Development of Advanced Computing (C-DAC)");
printf("\\n\\t\\t Email : hpcfte@cdac.in");
printf("\\n\\t\\t---------------------------------------------------------------------------");
myglobal = 0;
if ( pthread_create( &mythread, 0, thread_function_mutex, 0) )
{
exit(-1);
}
for ( i=0; i<20; i++)
{
pthread_mutex_lock(&mymutex);
myglobal=myglobal+1;
pthread_mutex_unlock(&mymutex);
}
if ( pthread_join ( mythread, 0 ) )
{
exit(-1);
}
__VERIFIER_assert(myglobal == 40);
exit(0);
}
| 1
|
#include <pthread.h>
static sem_t no_judge;
static sem_t exit_sem;
static sem_t all_gone;
static pthread_mutex_t mutex;
static pthread_mutex_t rand_lock;
static pthread_cond_t confirmed;
static pthread_cond_t all_signed_in;
static int num_immigs, num_specs;
static int entered = 0;
static int checked = 0;
static int judge_inside = 0;
void *spectator(void *v)
{
int i, id;
while (1)
{
id = spec_arrive();
sem_wait(&no_judge);
spec_enter(id);
sem_post(&no_judge);
spec_spec(id);
pthread_mutex_lock(&rand_lock);
i = (rand() % 2*(num_specs+num_immigs)) + 1;
pthread_mutex_unlock(&rand_lock);
sleep(i);
spec_leave(id);
}
return 0;
}
void *immigrant(void *v)
{
int id;
while (1)
{
id = immi_arrive();
sem_wait(&no_judge);
entered++;
immi_enter(id);
sem_post(&no_judge);
pthread_mutex_lock(&mutex);
if (entered == ++checked && judge_inside)
pthread_cond_signal(&all_signed_in);
immi_checkin(id);
immi_sit(id);
pthread_cond_wait(&confirmed, &mutex);
pthread_mutex_unlock(&mutex);
immi_swear(id);
immi_getcert(id);
sem_wait(&exit_sem);
immi_leave(id);
if (!--checked)
sem_post(&all_gone);
else
sem_post(&exit_sem);
}
return 0;
}
void *judge(void *v)
{
while (1)
{
sleep(3);
sem_wait(&no_judge);
pthread_mutex_lock(&mutex);
judge_inside = 1;
judge_enter();
while (entered > checked)
pthread_cond_wait(&all_signed_in, &mutex);
judge_confirm();
pthread_cond_broadcast(&confirmed);
pthread_mutex_unlock(&mutex);
entered = judge_inside = 0;
judge_leave();
if (checked)
{
sem_post(&exit_sem);
sem_wait(&all_gone);
}
sem_post(&no_judge);
}
return 0;
}
int main()
{
pthread_t thr_judge;
pthread_t *thr_immig;
pthread_t *thr_specs;
int i;
srand(time(0));
sem_init(&no_judge, 0, 1);
sem_init(&exit_sem, 0, 0);
sem_init(&all_gone, 0, 0);
pthread_mutex_init(&mutex, 0);
pthread_mutex_init(&rand_lock, 0);
pthread_cond_init(&confirmed, 0);
pthread_cond_init(&all_signed_in, 0);
printf("Digite o numero de espectadores desejado (max = 5): \\n");
scanf(" %d", &num_specs);
printf("Digite o numero de imigrantes desejado (max = 4): \\n");
scanf(" %d", &num_immigs);
if (!(i = init(num_specs, num_immigs)))
{
thr_immig = (pthread_t *)malloc(sizeof(pthread_t) * num_immigs);
thr_specs = (pthread_t *)malloc(sizeof(pthread_t) * num_specs);
for (i = 0; i < num_immigs; i++)
pthread_create(thr_immig + i, 0, immigrant, 0);
for (i = 0; i < num_specs; i++)
pthread_create(thr_specs + i, 0, spectator, 0);
pthread_create(&thr_judge, 0, judge, 0);
pthread_join(thr_judge, 0);
for (i = 0; i < num_specs; i++)
pthread_join(thr_specs[i], 0);
for (i = 0; i < num_immigs; i++)
pthread_join(thr_immig[i], 0);
i = 0;
}
finish();
free(thr_immig);
free(thr_specs);
sem_destroy(&no_judge);
sem_destroy(&exit_sem);
sem_destroy(&all_gone);
pthread_mutex_destroy(&mutex);
pthread_mutex_destroy(&rand_lock);
pthread_cond_destroy(&confirmed);
pthread_cond_destroy(&all_signed_in);
return i;
}
| 0
|
#include <pthread.h>
struct executionTimeMotor forwardMotorExecutionArr[(32* (TURNS + 1)) + ((TURNS + 1) * 2)];
struct executionTimeMotor backwardMotorExecutionArr[(32* (TURNS + 1)) + ((TURNS + 1) * 2)];
struct motorBlockTime forwardMotorBlockArr[(32* (TURNS + 1)) + ((TURNS + 1) * 2)];
struct motorBlockTime backwardMotorBlockArr[(32* (TURNS + 1)) + ((TURNS + 1) * 2)];
struct d arr[(32* (TURNS + 1)) + ((TURNS + 1) * 2)];
void step1() {
digitalWrite(25, 1);
usleep(1000);
digitalWrite(25, 0);
}
void step2() {
digitalWrite(24, 1);
digitalWrite(25, 1);
usleep(1000);
digitalWrite(25, 0);
digitalWrite(24, 0);
}
void step3() {
digitalWrite(24, 1);
usleep(1000);
digitalWrite(24, 0);
}
void step4() {
digitalWrite(23, 1);
digitalWrite(24, 1);
usleep(1000);
digitalWrite(23, 0);
digitalWrite(24, 0);
}
void step5() {
digitalWrite(23, 1);
usleep(1000);
digitalWrite(23, 0);
}
void step6() {
digitalWrite(18, 1);
digitalWrite(23, 1);
usleep(1000);
digitalWrite(18, 0);
digitalWrite(23, 0);
}
void step7() {
digitalWrite(18, 1);
usleep(1000);
digitalWrite(18, 0);
}
void step8() {
digitalWrite(18, 1);
digitalWrite(25, 1);
usleep(1000);
digitalWrite(18, 0);
digitalWrite(25, 0);
}
void stepForward() {
step1();
step2();
step3();
step4();
step5();
step6();
step7();
step8();
}
void stepBackward() {
step8();
step7();
step6();
step5();
step4();
step3();
step2();
step1();
}
void *motor(void* val) {
int i = 0, x = 0, y = 0;
int save = 0, co = 0, coTwo = 0;
int policy;
struct sched_param param;
if(pthread_getschedparam(pthread_self(), &policy, ¶m) != 0) {
printf("error\\n");
}
printf(" Motor policy=%s, priority=%d\\n",
(policy == SCHED_FIFO) ? "SCHED_FIFO" :
(policy == SCHED_RR) ? "SCHED_RR" :
(policy == SCHED_OTHER) ? "SCHED_OTHER" :
"???",
param.sched_priority);
pthread_barrier_wait(&barrier);
for(y = 0; y <= TURNS ; y++) {
for (x = 0; x < 17; x++) {
co = count;
if(blockTime == 1) {
clock_gettime(CLOCK_REALTIME, &forwardMotorBlockArr[co].start);
}
pthread_mutex_lock(&lock);
arr[count].position = x;
arr[count].motor = save;
pthread_mutex_unlock(&lock);
if(blockTime == 1) {
clock_gettime(CLOCK_REALTIME, &forwardMotorBlockArr[co].end);
}
usleep(200000);
if(executionTime == 1) {
clock_gettime(CLOCK_REALTIME, &forwardMotorExecutionArr[co].start);
}
if(x != 17) {
for(i = 0; i < 17; i++) {
stepForward();
}
}
save++;
count++;
if(executionTime == 1) {
clock_gettime(CLOCK_REALTIME, &forwardMotorExecutionArr[co].end);
}
}
for (x = 17; x >= 0; x--) {
if(blockTime == 1) {
clock_gettime(CLOCK_REALTIME, &backwardMotorBlockArr[coTwo].start);
}
pthread_mutex_lock(&lock);
arr[count].motor = save;
arr[count].position = x;
pthread_mutex_unlock(&lock);
if(blockTime == 1) {
clock_gettime(CLOCK_REALTIME, &backwardMotorBlockArr[coTwo].end);
}
usleep(200000);
if(executionTime == 1) {
clock_gettime(CLOCK_REALTIME, &backwardMotorExecutionArr[coTwo].start);
}
if(x != 0) {
for(i = 0; i < 17; i++) {
stepBackward();
}
}
count++;
save++;
if(executionTime == 1) {
clock_gettime(CLOCK_REALTIME, &backwardMotorExecutionArr[coTwo].end);
}
coTwo++;
}
}
count--;
abbruch = 1;
printf("motor %d\\n", save);
printf("count %d\\n", count);
return 0;
}
| 1
|
#include <pthread.h>
struct mod_arr{
int *arr;
int size;
};
struct arr_merge{
struct mod_arr* arr1;
struct mod_arr* arr2;
struct mod_arr* arr3;
int count;
};
pthread_mutex_t mutex_var = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_var = PTHREAD_COND_INITIALIZER;
void threadfunc(void*);
int main()
{
int i;
pthread_t* threads;
struct arr_merge *arr_obj;
arr_obj = (struct arr_merge*)malloc(sizeof(struct arr_merge));
arr_obj->arr1 = (struct mod_arr*)malloc(sizeof(struct mod_arr));
arr_obj->arr2 = (struct mod_arr*)malloc(sizeof(struct mod_arr));
arr_obj->arr3 = (struct mod_arr*)malloc(sizeof(struct mod_arr));
printf("Enter the number of elements for array1:");
scanf("%d",&(arr_obj->arr1->size));
arr_obj->arr1->arr = (int*)malloc(sizeof(int)* (arr_obj->arr1->size));
printf("Enter the elements of array1: ");
for(i=0;i<arr_obj->arr1->size;i++){
scanf("%d",&(arr_obj->arr1->arr[i]));
}
printf("Enter the number of elements for array2:");
scanf("%d",&(arr_obj->arr2->size));
arr_obj->arr2->arr = (int*)malloc(sizeof(int)* (arr_obj->arr2->size));
printf("Enter the elements of array2: ");
for(i=0;i<arr_obj->arr2->size;i++){
scanf("%d",&(arr_obj->arr2->arr[i]));
}
arr_obj->arr3->size = arr_obj->arr1->size + arr_obj->arr2->size;
arr_obj->arr3->arr = (int*)malloc(sizeof(int)*arr_obj->arr3->size);
arr_obj->count = 0;
threads = (pthread_t*)malloc(arr_obj->arr3->size*sizeof(pthread_t*));
for(i=0;i<arr_obj->arr3->size;i++){
if(pthread_create(&threads[i],0,threadfunc,(void*)arr_obj) != 0){
perror("Thread creation failed\\n");
return 1;
}
pthread_mutex_lock(&mutex_var);
pthread_cond_wait(&cond_var, &mutex_var);
arr_obj->count++;
pthread_mutex_unlock(&mutex_var);
}
for(i=0;i<arr_obj->arr3->size;i++){
pthread_join(threads[i],0);
}
printf("The new array is as follows\\n");
for(i=0;i<arr_obj->arr3->size;i++){
printf("%d ",arr_obj->arr3->arr[i]);
}
printf("\\n");
free(threads);
free(arr_obj->arr1->arr);
free(arr_obj->arr1);
free(arr_obj->arr2->arr);
free(arr_obj->arr2);
free(arr_obj->arr3->arr);
free(arr_obj->arr3);
free(arr_obj);
return 0;
}
void threadfunc(void* arrobj){
struct arr_merge* temp_arrobj;
int lower, upper,pos, middle,i,cnt,temp_cnt;
struct mod_arr *temp_arr1, *temp_arr2;
temp_arrobj = (struct arr_merge*)arrobj;
pthread_mutex_lock(&mutex_var);
temp_cnt = temp_arrobj->count;
pthread_cond_signal(&cond_var);
pthread_mutex_unlock(&mutex_var);
if(temp_cnt < temp_arrobj->arr1->size){
temp_arr1 = temp_arrobj->arr1;
temp_arr2 = temp_arrobj->arr2;
cnt = temp_cnt;
}else{
temp_arr1 = temp_arrobj->arr2;
temp_arr2 = temp_arrobj->arr1;
cnt = temp_cnt - temp_arrobj->arr1->size;
}
printf("Thread %d Count: %d\\n",temp_cnt,cnt);
if(*(temp_arr1->arr+cnt) < *(temp_arr2->arr)){
printf("Thread %d: Case1\\n",temp_cnt);
pos = cnt;
printf("Thread %d: Position: %d\\n",temp_cnt, pos);
}
else if(*(temp_arr1->arr+cnt) > *(temp_arr2->arr+(temp_arr2->size)-1)){
printf("Thread %d: Case2\\n",temp_cnt);
pos = temp_arr2->size+cnt;
printf("Thread %d: Position: %d\\n",temp_cnt, pos);
}
else{
printf("Thread %d: Case3\\n",temp_cnt);
lower = 0;
upper = temp_arr2->size - 1;
while(upper > lower){
middle = (upper + lower)/2;
if(*(temp_arr1->arr+cnt) > *(temp_arr2->arr+middle) && *(temp_arr1->arr+cnt) < *(temp_arr2->arr+middle+1)){
break;
}
else if(*(temp_arr1->arr+cnt) < *(temp_arr2->arr+middle))
upper = middle;
else if(*(temp_arr1->arr+cnt) > *(temp_arr2->arr+middle))
lower = middle + 1;
}
pos = cnt + middle + 1;
printf("Thread %d: Position: %d\\n",temp_cnt, pos);
}
temp_arrobj->arr3->arr[pos] = *(temp_arr1->arr+cnt);
}
| 0
|
#include <pthread.h>
unsigned long long int data=0;
int current_readers=0;
sem_t sem_readers;
pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t protect_readers_count = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t protect_start = PTHREAD_MUTEX_INITIALIZER;
void* readers(void *arg)
{
pthread_mutex_lock(&protect_start);
pthread_mutex_unlock(&protect_start);
sem_wait(&sem_readers);
pthread_mutex_lock(&protect_readers_count);
current_readers++;
pthread_mutex_unlock(&protect_readers_count);
if(current_readers==1)
pthread_mutex_lock(&mx);
printf("%llu\\n",data);
pthread_mutex_lock(&protect_readers_count);
current_readers--;
pthread_mutex_unlock(&protect_readers_count);
if(current_readers==0)
pthread_mutex_unlock(&mx);
sem_post(&sem_readers);
}
void* writers(void *arg)
{
pthread_mutex_lock(&protect_start);
pthread_mutex_unlock(&protect_start);
pthread_mutex_lock(&mx);
data++;
pthread_mutex_unlock(&mx);
}
int main()
{
sem_init(&sem_readers,0,100);
pthread_t *threads = (pthread_t*) malloc(sizeof(pthread_t)*(100 +100));
int i;
pthread_mutex_lock(&protect_start);
for(i=0;i<100;i++)
pthread_create(&threads[i],0,readers,0);
for(i=0;i<100;i++)
pthread_create(&threads[i+100],0,writers,0);
pthread_mutex_unlock(&protect_start);
for(i=0;i<100 +100;i++)
pthread_join(threads[i],0);
printf("data in end = %llu\\n",data);
return 0;
}
| 1
|
#include <pthread.h>
struct fade *fade_init(int samplerate, float level)
{
struct fade *s;
if (!(s = malloc(sizeof (struct fade))))
{
fprintf(stderr, "fade_init: malloc failure\\n");
exit(5);
}
s->samplerate = samplerate;
s->baselevel = level;
if (pthread_mutex_init(&s->mutex, 0))
{
fprintf(stderr, "fade_init: mutex creation failed\\n");
exit(5);
}
fade_set(s, FADE_SET_HIGH, 0.0f, FADE_IN);
return s;
}
void fade_destroy(struct fade *s)
{
pthread_mutex_destroy(&s->mutex);
free(s);
}
void fade_set(struct fade *s, enum fade_startpos sp, float t, enum fade_direction d)
{
pthread_mutex_lock(&s->mutex);
s->startpos = sp;
if (t >= 0.0f)
s->samples = floorf(s->samplerate * t);
if (d != FADE_DIRECTION_UNCHANGED)
s->newdirection = d;
s->newdata = 1;
pthread_mutex_unlock(&s->mutex);
}
float fade_get(struct fade *s)
{
if (s->newdata)
{
pthread_mutex_lock(&s->mutex);
if (s->startpos == FADE_SET_HIGH)
s->level = 1.0f;
if (s->startpos == FADE_SET_LOW)
s->level = 0.0f;
if ((s->direction = s->newdirection) == FADE_IN)
s->rate = powf(s->baselevel, -1.0f / s->samples);
else
s->rate = powf(s->baselevel, 1.0f / s->samples);
s->moving = 1;
s->newdata = 0;
pthread_mutex_unlock(&s->mutex);
}
if (s->moving)
{
if (s->direction == FADE_IN)
{
if (s->level < s->baselevel)
s->level = s->baselevel;
else
if ((s->level *= s->rate) >= 1.0f)
{
s->level = 1.0f;
s->moving = 0;
}
}
if (s->direction == FADE_OUT)
{
if (s->level > s->baselevel)
s->level *= s->rate;
else
{
s->level = 0.0f;
s->moving = 0;
}
}
}
return s->level;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.