text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
uint32_t abort_signal;
pthread_mutex_t mutex;
pthread_cond_t cond;
int32_t synchronized_data = 0;
void * test_func1(void * param)
{
FUNC_ENTRY;
int32_t ret;
LOG_LOW("Locking mutex");
ret = pthread_mutex_lock(&mutex);
if (ret != 0)
{
LOG_ERROR("Could not thread attrs");
pthread_exit(0);
}
else
{
LOG_LOW("Waiting on condition");
ret = pthread_cond_wait(&cond, &mutex);
if (ret != 0)
{
LOG_ERROR("Could not wait for condition %s", strerror(ret));
pthread_exit(0);
}
LOG_LOW("Received condition");
LOG_LOW("Sleeping for 5 seconds");
usleep(5000000);
synchronized_data++;
LOG_LOW("Unlocking mutex");
ret = pthread_mutex_unlock(&mutex);
if (ret != 0)
{
LOG_ERROR("Could not lock mutex %s", strerror(ret));
pthread_exit(0);
}
}
pthread_exit(0);
}
void * test_func(void * param)
{
FUNC_ENTRY;
int32_t ret;
size_t stacksize;
void * stackaddr;
pthread_attr_t attr;
pthread_t self = pthread_self();
ret = pthread_getattr_np(self, &attr);
if (ret != 0)
{
LOG_ERROR("Could not thread attrs");
return 0;
}
ret = pthread_attr_getstack(&attr, &stackaddr, &stacksize);
if (ret != 0)
{
LOG_ERROR("Could not get stack info");
return 0;
}
LOG_HIGH("Stack address %p Stack size %zu", stackaddr, stacksize);
LOG_LOW("Sleeping for 2 seconds");
usleep(2000000);
LOG_LOW("Locking mutex");
ret = pthread_mutex_lock(&mutex);
if (ret == 0)
{
LOG_LOW("Signaling condition");
ret = pthread_cond_signal(&cond);
if (ret != 0)
{
LOG_ERROR("%s", strerror(ret));
}
LOG_LOW("Unlocking mutex");
ret = pthread_mutex_unlock(&mutex);
if (ret != 0)
{
LOG_ERROR("Could not lock mutex");
pthread_exit(0);
}
usleep(500000);
ret = pthread_mutex_trylock(&mutex);
if (ret != 0)
{
LOG_ERROR("Could not lock mutex (expected)");
}
LOG_LOW("synchronized_data on trylock %d", synchronized_data);
ret = pthread_mutex_lock(&mutex);
if (ret != 0)
{
LOG_ERROR("Could not lock mutex (unexpected)");
pthread_exit(0);
}
LOG_LOW("synchronized_data on lock %d", synchronized_data);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main()
{
int32_t ret;
pthread_t test_thread;
pthread_t test_thread1;
pthread_attr_t test_attr;
log_init();
FUNC_ENTRY;
ret = pthread_cond_init(&cond, 0);
if (ret != 0)
{
LOG_ERROR("Could not init condition");
return 1;
}
else
{
LOG_LOW("Initialized condition");
}
ret = pthread_mutex_init(&mutex, 0);
if (ret != 0)
{
LOG_ERROR("Could not init mutex");
return 1;
}
else
{
LOG_LOW("Initialized mutex");
}
ret = pthread_attr_init(&test_attr);
if (ret != 0)
{
LOG_ERROR("Could not init attr");
return 1;
}
else
{
LOG_LOW("Initialized thread attributes");
}
ret = pthread_attr_setstacksize(&test_attr, (65536));
if (ret != 0)
{
LOG_ERROR("Could not set stack size");
return 1;
}
else
{
LOG_LOW("Initialized thread stack size to %d", (65536));
}
ret = pthread_attr_setguardsize(&test_attr, (4096));
if (ret != 0)
{
LOG_ERROR("Could not set guard size");
return 1;
}
else
{
LOG_LOW("Initialized thread guard size to %d", (4096));
}
ret = pthread_create(&test_thread, &test_attr, test_func, 0);
if (ret != 0)
{
LOG_ERROR("Could not set create pthread %s", strerror(ret));
return 1;
}
else
{
LOG_LOW("Created thread");
}
ret = pthread_create(&test_thread1, &test_attr, test_func1, 0);
if (ret != 0)
{
LOG_ERROR("Could not set create pthread %s", strerror(ret));
return 1;
}
else
{
LOG_LOW("Created thread");
}
LOG_HIGH("Waiting for threads to join");
pthread_join(test_thread, 0);
pthread_join(test_thread1, 0);
LOG_HIGH("Threads joined");
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&mutex);
pthread_attr_destroy(&test_attr);
log_destroy();
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t m;
pthread_cond_t c;
int x;
static void my_cleanup(void *arg) {
printf("my_cleanup\\n");
pthread_mutex_unlock((pthread_mutex_t*)arg);
}
void *thr1(void *p) {
pthread_mutex_lock(&m);
pthread_cleanup_push(my_cleanup, &m);
barrier_wait(&barrier);
while (x == 0)
pthread_cond_wait(&c, &m);
pthread_cleanup_pop(1);
return 0;
}
int main() {
barrier_init(&barrier, 2);
pthread_t th;
pthread_mutex_init(&m, 0);
pthread_cond_init(&c, 0);
pthread_create(&th, 0, thr1, 0);
barrier_wait(&barrier);
sleep(1);
pthread_cancel(th);
pthread_join(th, 0);
pthread_mutex_lock(&m);
pthread_mutex_unlock(&m);
fprintf(stderr, "OK\\n");
}
| 0
|
#include <pthread.h>
int g_signaled = 0;
pthread_mutex_t g_lock;
pthread_cond_t g_cond;
void *wait(void *data) {
pthread_mutex_lock(&g_lock);
while (g_signaled == 0) {
printf("%lu wait cond\\n", pthread_self());
pthread_cond_wait(&g_cond, &g_lock);
}
pthread_mutex_unlock(&g_lock);
printf("%lu bang!\\n", pthread_self());
return 0;
}
void *signal(void *data) {
pthread_mutex_lock(&g_lock);
g_signaled = 1;
pthread_mutex_unlock(&g_lock);
printf("send out signal!\\n");
pthread_cond_signal(&g_cond);
sleep(1);
pthread_cond_signal(&g_cond);
sleep(1);
pthread_cond_signal(&g_cond);
sleep(1);
pthread_cond_signal(&g_cond);
sleep(1);
pthread_cond_signal(&g_cond);
return 0;
}
int main(int argc, char **argv) {
pthread_mutex_init(&g_lock, 0);
pthread_cond_init(&g_cond, 0);
const int nThreads = 5;
pthread_t workers[nThreads];
int i;
pthread_create(&workers[0], 0, wait, 0);
pthread_create(&workers[1], 0, wait, 0);
pthread_create(&workers[2], 0, wait, 0);
pthread_create(&workers[3], 0, wait, 0);
pthread_create(&workers[4], 0, signal, 0);
qthread_hibernate_thread(0);
for (i = 0; i < nThreads; i++)
pthread_join(workers[i], 0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER;
void
dcethread__default_log_callback (const char* file, unsigned int line, int level, const char* str, void* data)
{
const char* level_name = 0;
switch (level)
{
case DCETHREAD_DEBUG_ERROR:
level_name = "ERROR";
break;
case DCETHREAD_DEBUG_WARNING:
level_name = "WARNING";
break;
case DCETHREAD_DEBUG_INFO:
level_name = "INFO";
break;
case DCETHREAD_DEBUG_VERBOSE:
level_name = "VERBOSE";
break;
case DCETHREAD_DEBUG_TRACE:
level_name = "TRACE";
break;
default:
level_name = "UNKNOWN";
break;
}
pthread_mutex_lock(&log_lock);
fprintf(stderr, "dcethread-%s %s:%i: %s\\n", level_name, file, line, str);
if (level == DCETHREAD_DEBUG_ERROR)
abort();
pthread_mutex_unlock(&log_lock);
}
static void (*log_callback) (const char* file, unsigned int line, int level, const char* str, void* data) = 0;
static void *log_callback_data = 0;
void
dcethread__debug_set_callback(void (*cb) (const char*, unsigned int, int, const char*, void* data), void* data)
{
log_callback = cb;
log_callback_data = data;
}
static char *
my_vasprintf(const char* format, va_list args)
{
char *smallBuffer;
unsigned int bufsize;
int requiredLength;
unsigned int newRequiredLength;
char* outputString = 0;
va_list args2;
va_copy(args2, args);
bufsize = 4;
do
{
smallBuffer = malloc(bufsize);
if (!smallBuffer)
{
return 0;
}
requiredLength = vsnprintf(smallBuffer, bufsize, format, args);
if (requiredLength < 0)
{
bufsize *= 2;
}
free(smallBuffer);
} while (requiredLength < 0);
if (requiredLength >= (0xFFFFFFFF - 1))
{
return 0;
}
outputString = malloc(requiredLength + 2);
if (!outputString)
{
return 0;
}
newRequiredLength = vsnprintf(outputString, requiredLength + 1, format, args2);
if (newRequiredLength < 0)
{
free(outputString);
return 0;
}
;
return outputString;
}
void
dcethread__debug_printf(const char* file, unsigned int line, int level, const char* fmt, ...)
{
va_list ap;
char* str;
if (!log_callback)
return;
__builtin_va_start((ap));
str = my_vasprintf(fmt, ap);
if (str)
{
log_callback(file, line, level, str, log_callback_data);
free(str);
}
;
}
| 0
|
#include <pthread.h>
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
void *compute(void *arg)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
return 0;
}
void wakeup_thread()
{
pthread_mutex_lock(&mutex);
counter ++;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
int main(int argc, char *argv[])
{
int i;
int number = atoi(argv[1]);
pthread_t tids[number];
for (i = 0; i < number; i++){
pthread_create(&tids[i], 0, compute, 0);
}
sleep(1);
printf("Start to wakeup the thread which with pthread_cond_wait()\\n");
printf("Using wakeup_thread\\n");
for(i = 0; i< number; i++){
wakeup_thread();
}
printf("counter: %d\\n", counter);
return 0;
}
| 1
|
#include <pthread.h>
int data1;
int data2;
pthread_mutex_t A;
pthread_mutex_t B;
void * thread_routine_1(void * arg)
{
int tmp;
pthread_mutex_lock(&A);
printf("thread 1 : lock (A)\\n");
tmp = data1;
data2 = tmp+1;
pthread_mutex_unlock(&A);
printf("thread 1 : unlock (A)\\n");
return 0;
}
void * thread_routine_2(void * arg)
{
int tmp;
pthread_mutex_lock(&B);
printf("thread 2 : lock (B)\\n");
tmp = data2;
pthread_mutex_lock(&A);
printf("thread 2 : lock (A)\\n");
data1 = tmp-1;
pthread_mutex_unlock(&A);
printf("thread 2 : unlock (A)\\n");
pthread_mutex_unlock(&B);
printf("thread 2 : unlock (B)\\n");
return 0;
}
int main()
{
pthread_t t1, t2;
pthread_mutex_init(&A, 0);
pthread_mutex_init(&B, 0);
pthread_create(&t1, 0, thread_routine_1, 0);
pthread_create(&t2, 0, thread_routine_2, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_mutex_destroy(&A);
pthread_mutex_destroy(&B);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
{
int _data;
struct node_list *_next;
}node, *node_p, **node_pp;
node_p head;
static node_p alloc_node(int data)
{
node_p newNode = (node_p)malloc(sizeof(node));
if(newNode == 0)
{
perror("malloc");
exit(1);
}
newNode->_next = 0;
newNode->_data = data;
return newNode;
}
static void free_node(node_p del)
{
if(del)
{
free(del);
del = 0;
}
}
void initList(node_pp h)
{
*h = alloc_node(0);
}
void pushHead(node_p h, int data)
{
node_p newNode = alloc_node(data);
newNode->_next = h->_next;
h->_next = newNode;
}
int IsEmpty(node_p h)
{
return h->_next == 0 ? 1 : 0;
}
void popHead(node_p h, int *data)
{
if(!IsEmpty(h))
{
node_p del = h->_next;
h->_next = del->_next;
*data = del->_data;
free_node(del);
}
}
void showList(node_p h)
{
node_p cur = h->_next;
while(cur)
{
printf("%d ", cur->_data);
cur = cur->_next;
}
printf("\\n");
}
void DestoryList(node_p h)
{
int data = 0;
if(IsEmpty(h))
{
popHead(h, &data);
}
free_node(h);
}
void *product_run(void *arg)
{
int data = 0;
node_p h = (node_p)arg;
while(1)
{
usleep(1000000);
data = rand()%1000;
pthread_mutex_lock(&lock);
pushHead(h, data);
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
printf("product is done ..\\n");
}
}
void *consumer_run(void *arg)
{
int data = 0;
node_p h = (node_p)arg;
while(1)
{
pthread_mutex_lock(&lock);
if(IsEmpty(h))
{
pthread_cond_wait(&cond, &lock);
}
popHead(h, &data);
pthread_mutex_unlock(&lock);
printf("consumer is done, data is %d\\n", data);
}
}
int main()
{
initList(&head);
pthread_t product;
pthread_t consumer;
pthread_create(&product, 0, product_run, (void*)head);
pthread_create(&consumer, 0, consumer_run, (void*)head);
pthread_join(product, 0);
pthread_join(consumer, 0);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
int buffer[2];
int buf_first=0;
int buf_last=0;
int buf_count=0;
void produce(int val)
{
pthread_mutex_lock(&mutex);
while(buf_count == 2){
pthread_cond_wait(&cond1, &mutex);
}
buffer[buf_first] = val;
buf_count++;
buf_first = (buf_first + 1) % 2;
printf("\\t producing value %d\\n",val);
pthread_cond_broadcast(&cond1);
pthread_mutex_unlock(&mutex);
}
int consume(void)
{
int val = -1;
pthread_mutex_lock(&mutex);
while(buf_count == 0){
pthread_cond_wait(&cond2, &mutex);
}
val = buffer[buf_last];
buf_count--;
buf_last = (buf_last + 1) % 2;
printf("\\t\\t consuming value %d\\n",val);
pthread_cond_broadcast(&cond2);
pthread_mutex_unlock(&mutex);
return val;
}
void* producer(void* arg)
{
int i = 0;
int new_value = 0;
for(i=0; i<20; i++){
new_value = rand()%10;
produce(new_value);
}
return 0;
}
void* consumer(void* arg)
{
int i = 0;
int value = 0;
for(i=0; i<20; i++){
value = consume();
}
return 0;
}
int main(void)
{
pthread_t tids[4];
int i=0;
struct timespec tt;
clock_gettime(CLOCK_MONOTONIC, &tt);
srand(tt.tv_sec);
for(i=0; i< 4; i++){
if(i%2 == 0){
if(pthread_create (&tids[i], 0, producer, 0) != 0){
fprintf(stderr,"Failed to create the using thread\\n");
return 1;
}
}
else{
if(pthread_create (&tids[i], 0, consumer, 0) != 0){
fprintf(stderr,"Failed to create the generating thread\\n");
return 1;
}
}
}
for (i = 0; i < 4; i++){
pthread_join (tids[i], 0) ;
}
return 0;
}
| 0
|
#include <pthread.h>
struct node {
struct msg msg;
struct node *next;
};
int N = 0;
struct node *head = 0;
struct node *back = 0;
sem_t sem_got;
sem_t sem_left;
pthread_mutex_t mutex;
pthread_mutexattr_t mutattr;
void myqueue_init(const int max_count)
{
pthread_mutexattr_init(& mutattr);
pthread_mutexattr_settype(& mutattr, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(& mutex, 0);
N = max_count;
sem_init(& sem_got, 0, 0);
sem_init(& sem_left, 0, N);
}
const int myqueue_max_count() {
return N;
}
const int myqueue_count()
{
pthread_mutex_lock(& mutex);
int sval;
sem_getvalue(& sem_got, & sval);
pthread_mutex_unlock(& mutex);
return sval;
}
void myqueue_clear() {
pthread_mutex_lock(& mutex);
while (myqueue_count() != 0)
myqueue_pop();
pthread_mutex_unlock(& mutex);
}
void myqueue_destroy()
{
myqueue_clear();
sem_destroy(& sem_left);
sem_destroy(& sem_got);
pthread_mutexattr_destroy(& mutattr);
pthread_mutex_destroy(& mutex);
}
void myqueue_push(const struct msg *src)
{
sem_wait(& sem_left);
pthread_mutex_lock(& mutex);
struct node *np = (struct node*) malloc(sizeof(struct node));
memcpy(& np->msg, src, sizeof(struct msg));
char *p = (char *) malloc(np->msg.len * sizeof(char));
memcpy(p, src->data, np->msg.len);
np->msg.data = p;
np->next = 0;
if (back != 0) {
back->next = np;
back = back->next;
} else {
back = np;
head = np;
}
sem_post(& sem_got);
pthread_mutex_unlock(& mutex);
return;
}
void myqueue_front(struct msg *dest)
{
sem_wait(& sem_got);
pthread_mutex_lock(& mutex);
sem_post(& sem_got);
dest->T = head->msg.T;
dest->len = head->msg.len;
memcpy(dest->data, head->msg.data, dest->len * sizeof(char));
pthread_mutex_unlock(& mutex);
}
void myqueue_pop()
{
sem_wait(& sem_got);
pthread_mutex_lock(& mutex);
if (head == back)
back = 0;
struct node *pt = head;
head = head->next;
free(pt->msg.data);
free(pt);
sem_post(& sem_left);
pthread_mutex_unlock(& mutex);
}
| 1
|
#include <pthread.h>
struct PKW
{
int PSL;
int PIS;
int PO;
int SLD;
int OTH;
int OKW_PSL[20];
int OKW_PIS[20];
int OKW_PO[20];
int OKW_SLD[20];
int OKW_OTH[20];
pthread_barrier_t barrier;
pthread_mutex_t mutex;
};
struct PKW *shared;
void init_shared()
{
int i;
for(i = 0; i < 20; i++)
{
shared->OKW_PSL[i] = 0;
shared->OKW_PIS[i] = 0;
shared->OKW_PO[i] = 0;
shared->OKW_SLD[i] = 0;
}
shared->PSL = 0;
shared->PIS = 0;
shared->PO = 0;
shared->SLD = 0;
shared->OTH = 0;
pthread_barrierattr_t attr;
pthread_barrierattr_init(&attr);
pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
pthread_barrier_init(&shared->barrier, &attr, 20);
pthread_mutexattr_t mutexat;
pthread_mutexattr_init(&mutexat);
pthread_mutexattr_setpshared(&mutexat, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&shared->mutex, &mutexat);
}
int randomVote()
{
float choice = drand48();
if(choice < 0.2368) return 0;
else if(choice < 0.5053) return 1;
else if(choice < 0.7689) return 2;
else if(choice < 0.8567) return 3;
else return 4;
}
void Voting(int committeId)
{
int i = 0;
int psl = 0, pis = 0, po = 0, sld = 0, oth = 0;
srand48(getpid() * time(0));
for (i = 0; i < 1000000; i++)
{
switch(randomVote())
{
case 0: psl = psl+1; break;
case 1: pis = pis+1; break;
case 2: po = po+1; break;
case 3: sld = sld+1; break;
case 4: oth = oth+1; break;
}
}
shared->OKW_PSL[committeId] = psl;
shared->OKW_PIS[committeId] = pis;
shared->OKW_PO[committeId] = po;
shared->OKW_SLD[committeId] = sld;
shared->OKW_OTH[committeId] = oth;
pthread_mutex_lock(&shared->mutex);
shared->PSL = shared->PSL + psl;
shared->PIS = shared->PIS + pis;
shared->PO = shared->PO + po;
shared->SLD = shared->SLD + sld;
shared->OTH = shared->OTH + oth;
pthread_mutex_unlock(&shared->mutex);
}
void showResults()
{
float percent = 1000000 * 20 /100;
printf("Global results :\\n");
printf("PSL = %d (%f %%)\\n", shared->PSL, shared->PSL/percent);
printf("PO = %d (%f %%)\\n", shared->PO, shared->PO/percent);
printf("PiS = %d (%f %%)\\n", shared->PIS, shared->PIS/percent);
printf("SLD = %d (%f %%)\\n", shared->SLD, shared->SLD/percent);
printf("OTH = %d (%f %%)\\n", shared->OTH, shared->OTH/percent);
}
void verify()
{
int sum = shared->PSL + shared->PO + shared->PIS + shared->SLD + shared->OTH;
int valid_votes = 1000000 * 20;
if(sum == valid_votes) printf("Number of votes is correct\\n");
else printf("PKW syndrome - we forgot how to math\\n(should be %d, but %d exists\\n)", valid_votes, sum);
int psl =0, po =0, pis =0, sld =0, oth =0;
int i;
for(i = 0; i < 20; i++)
{
psl = psl + shared->OKW_PSL[i];
po = po + shared->OKW_PO[i];
pis = pis + shared->OKW_PIS[i];
sld = sld + shared->OKW_SLD[i];
oth = oth + shared->OKW_OTH[i];
}
printf("From local data, results :\\n");
printf("PSL = %d \\n", psl);
printf("PO = %d \\n", po);
printf("PiS = %d \\n", pis);
printf("SLD = %d \\n", sld);
printf("OTH = %d\\n", oth);
}
int main(int argc, char** argv)
{
int Committe[20];
int i = 0, j = 0, shmid = 0, status = 0;
shmid = shmget(((key_t) 123919L), sizeof(struct PKW), IPC_CREAT | 0666);
if (shmid < 0)
{
perror("shmget");
return(1);
}
shared = shmat(shmid, 0, 0);
if (shared == 0)
{
perror("shmat");
return(1);
}
init_shared();
for(i = 0; i<20; i++)
{
Committe[i] = fork();
if(Committe[i]==0)
{
pthread_barrier_wait(&shared->barrier);
Voting(i);
exit(0);
}
}
for(j = 0; j < 20; j++)
{
wait(&status);
}
showResults();
verify();
shmdt(shared);
shmctl(shmid, IPC_RMID, 0);
return 0;
}
| 0
|
#include <pthread.h>
enum Error {
NoTarget = 1,
AddrInfo,
SocketInit,
};
pthread_t net_speed;
pthread_mutex_t net_speed_update;
int deltabytes = 0;
void *callback(void *arg)
{
int timeout = (int)arg;
while (1) {
if (deltabytes > 0) {
printf("Attack vector running at %d Mbps\\n", (deltabytes / timeout) * 8 / 1000 / 1000);
pthread_mutex_lock(&net_speed_update);
deltabytes = 0;
pthread_mutex_unlock(&net_speed_update);
}
sleep(timeout);
}
return 0;
}
int main(int argc, char *argv[])
{
int socket_fd;
struct addrinfo hints, *ll_server_info;
char ip4[INET_ADDRSTRLEN];
struct sockaddr_in *sin;
char payload[(1500 - 60 - 8)];
pthread_mutex_init(&net_speed_update, 0);
if (argc < 2) {
printf("No target specified\\n");
return NoTarget;
}
else {
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
if ((getaddrinfo(argv[1], "8888", &hints, &ll_server_info)) != 0) {
fprintf(stderr, "Unable to retrive target data %s\\n", gai_strerror(socket_fd));
return AddrInfo;
}
if ((socket_fd = socket(ll_server_info->ai_family, ll_server_info->ai_socktype, ll_server_info->ai_protocol)) < 0) {
printf("Unable to create the socket\\n");
return SocketInit;
}
else {
sin = (struct sockaddr_in *) ll_server_info->ai_addr;
inet_ntop(AF_INET, &(sin->sin_addr), ip4, INET_ADDRSTRLEN);
printf("Attack vector ready for %s:%d\\n", ip4, (int) ntohs(sin->sin_port));
}
pthread_create(&net_speed, 0, callback, (void*)1);
memset(&payload, 1, (1500 - 60 - 8));
for (;;) {
int sent;
if ((sent = sendto(socket_fd, payload, (1500 - 60 - 8), 0, ll_server_info->ai_addr, ll_server_info->ai_addrlen)) > 0) {
pthread_mutex_lock(&net_speed_update);
deltabytes += sent;
pthread_mutex_unlock(&net_speed_update);
}
else {
printf("Unable to send packet.\\n");
freeaddrinfo(ll_server_info);
close(socket_fd);
pthread_kill(net_speed, SIGTERM);
break;
}
}
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex_lock;
sem_t students_sem;
sem_t ta_sem;
int waiting_students;
void rand_sleep(void);
void* student_programming(void* stu_id);
void* ta_teaching();
int main(int argc, char **argv){
printf("CS149 SleepingTA from Muchuan Gong\\n");
pthread_t students[4];
pthread_t ta;
int studentid[4]={0};
sem_init(&students_sem,0,0);
sem_init(&ta_sem,0,1);
srand(time(0));
pthread_mutex_init(&mutex_lock,0);
pthread_create(&ta,0,ta_teaching,0);
for(int i=0; i<4; i++)
{
studentid[i] = i+1;
pthread_create(&students[i], 0, student_programming, (void*) &studentid[i]);
}
pthread_join(ta, 0);
return 0;
}
void* student_programming(void* stu_id)
{
int id = *(int*)stu_id;
int helpcount = 0;
while(1)
{
printf(" Student %d programming for 3 seconds\\n",
id);
rand_sleep();
pthread_mutex_lock(&mutex_lock);
if(waiting_students<2)
{
waiting_students++;
id,waiting_students);
sem_post(&students_sem);
pthread_mutex_unlock(&mutex_lock);
sem_wait(&ta_sem);
printf("Student %d revceiving help\\n",id);
helpcount++;
}
else
{
printf(" student %d will try later\\n"
,id);
pthread_mutex_unlock(&mutex_lock);
}
if(helpcount >= 2){
pthread_mutex_unlock(&mutex_lock);
pthread_exit(0);
}
}
}
void* ta_teaching()
{
int helpcount = 0;
while(1)
{
sem_wait(&students_sem);
pthread_mutex_lock(&mutex_lock);
printf("Helping a student for 3 second,");
helpcount++;
waiting_students--;
,waiting_students);
sem_post(&ta_sem);
pthread_mutex_unlock(&mutex_lock);
if(helpcount==2*4){
pthread_exit(0);
}
rand_sleep();
}
}
void rand_sleep(void){
time_t seed;
time(&seed);
int time = rand_r(&seed) % 3 + 1;
sleep(time);
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error() ;
int block;
int busy;
int inode;
pthread_mutex_t m_inode;
pthread_mutex_t m_busy;
void *allocator(){
pthread_mutex_lock(&m_inode);
if(inode == 0){
pthread_mutex_lock(&m_busy);
busy = 1;
pthread_mutex_unlock(&m_busy);
inode = 1;
}
block = 1;
if (!(block == 1)) ERROR: __VERIFIER_error();;
pthread_mutex_unlock(&m_inode);
return 0;
}
void *de_allocator(){
pthread_mutex_lock(&m_busy);
if(busy == 0){
block = 0;
if (!(block == 0)) ERROR: __VERIFIER_error();;
}
pthread_mutex_unlock(&m_busy);
return ((void *)0);
}
int main() {
pthread_t t1, t2;
__VERIFIER_assume(inode == busy);
pthread_mutex_init(&m_inode, 0);
pthread_mutex_init(&m_busy, 0);
pthread_create(&t1, 0, allocator, 0);
pthread_create(&t2, 0, de_allocator, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_mutex_destroy(&m_inode);
pthread_mutex_destroy(&m_busy);
return 0;
}
| 1
|
#include <pthread.h>
struct Request;
struct Msg;
struct Request
{
int pid;
};
struct Msg
{
int pid;
char data[512];
};
char *servername = "server2";
char *famfifo = "server2";
int ffd;
int semid;
int numclients = 0;
int ifd,ofd;
int cfd[10][2];
struct pollfd pfd[10];
pthread_t tid;
pthread_mutex_t mut;
inline int semGet(int numsem)
{
int semkey = ftok("/home",2048);
int semid = semget(2048,numsem,IPC_CREAT|0666);
assert(semid != -1);
return semid;
}
void genearteFifo(int pid)
{
int ret;
char buff[512];
sprintf(buff,"%d.out",pid);
ret = mkfifo(buff,0666);
assert(ret != -1);
ofd = open(buff,O_RDWR);
assert(ofd != -1);
sprintf(buff,"%d.in",pid);
ret = mkfifo(buff,0666);
assert(ret != -1);
ifd = open(buff,O_RDWR);
assert(ifd != -1);
return;
}
void* pollFifo(void *args)
{
setbuf(stdout, 0);
int i,j;
struct Msg msg;
while(1)
{
pthread_mutex_lock(&mut);
int status = poll(pfd,numclients,0);
if(status > 0)
{
for(i=0;i<numclients;i++)
{
if(pfd[i].revents == POLLIN)
{
read(cfd[i][1],&msg,(sizeof(struct Msg)));
printf("MSG received from client (%d): %s\\n",msg.pid,msg.data);
for(j=0;j<numclients;j++)
{
if(j!=i)
{
write(cfd[j][0],&msg,(sizeof(struct Msg)));
}
}
}
}
}
pthread_mutex_unlock(&mut);
}
}
int main(int argc, char const *argv[])
{
setbuf(stdout, 0);
printf("%s created============\\n",servername);
semid = semGet(2);
printf("semid: %d\\n",semid);
unsigned short arr[] = {1,0};
semInit(semid,arr,2);
unlink(famfifo);
int ret = mkfifo(famfifo,0666);
assert(ret != -1);
ffd = open(famfifo,O_RDWR);
assert(ffd != -1);
assert(pthread_mutex_init(&mut,0) == 0);
assert(pthread_create(&tid,0,pollFifo,0) == 0);
struct Request req;
int i;
while(1)
{
semWait(semid,1);
read(ffd,&req,(sizeof(struct Request)));
printf("Request received from: %d\\n",req.pid);
genearteFifo(req.pid);
cfd[numclients][1] = ifd;
cfd[numclients][0] = ofd;
pfd[numclients].fd = ifd;
pfd[numclients].events = POLLIN;
pfd[numclients].revents = 0;
pthread_mutex_lock(&mut);
numclients++;
printf("numclients %d\\n",numclients);
pthread_mutex_unlock(&mut);
semSignal(semid,1);
}
return 0;
}
| 0
|
#include <pthread.h>
long long int N;
pthread_mutex_t bastao;
int nThreads;
int ehPrimo (long long int n) {
int i;
if (n<=1) return 0;
if (n==2) return 1;
if (n%2==0) return 0;
for (i=3; i<sqrt(n)+1; i+=2)
if(n%i==0) return 0;
return 1;
}
int contaPrimosSeq () {
int qPrimos = 0;
for ( ; N > 1; N--) {
if (ehPrimo(N)) { qPrimos++; }
}
return qPrimos;
}
void * contaPrimosConc (void * tid) {
int id = * (int *) tid;
int qPrimos, *retorno;
long long int i;
qPrimos = 0;
if ((retorno = malloc(sizeof(int))) == 0)
printf("--ERRO: malloc()\\n"); exit(-1);
while (N > 1) {
pthread_mutex_lock(&bastao);
N--;
pthread_mutex_unlock(&bastao);
if (ehPrimo(N)) { qPrimos++; }
}
free(tid);
*retorno = qPrimos;
pthread_exit((void *) retorno);
}
int main(int argc, char const *argv[]) {
double ini, fi, inicio, final, procSeq, procConc, speedup;
int *id, *retorno, i, qPrimosSeq = 0, qPrimosConc = 0;
pthread_t *tid_sistema;
GET_TIME(ini);
if (argc < 3) { printf("Use: %s <N> <numero de threads>\\n", argv[0]); exit(-1); }
N = atoll(argv[1]);
nThreads = atoi(argv[2]);
if (nThreads < 1) { printf("--ERRO: numero de threads menor que 1\\n"); exit(-1); }
printf("Quantidade de numeros de 1 a %lld (inclusive): ", N);
GET_TIME(fi);
inicio = fi - ini;
GET_TIME(ini);
qPrimos = contaPrimosSeq();
GET_TIME(fi);
procSeq = fi - ini;
GET_TIME(ini);
pthread_mutex_init(&bastao, 0);
for (i = 0; i < nThreads; ++i) {
if ((id = malloc(sizeof(int))) == 0) {
printf("--ERRO: malloc()\\n"); exit(-1);
}
*id = i;
if (pthread_create(&tid_sistema, 0, contaPrimosConc, (void *)id)) {
printf("--ERRO: pthread_create()\\n"); exit(-1);
}
}
for (i = 0; i < nThreads; ++i) {
}
GET_TIME(fi);
procConc = fi - ini;
GET_TIME(ini);
printf("%d\\n", qPrimos);
GET_TIME(fi);
final = fi - ini;
procSeq += (inicio + final);
procConc += (inicio + final);
speedup = procSeq/procConc;
printf("Tempo Sequencial: %f\\n", procSeq);
printf("Tempo Concorrente: %f\\n", procConc);
printf("Speedup: %f\\n", speedup);
return 0;
}
| 1
|
#include <pthread.h>
int _pid;
int _pv;
unsigned short _cote;
Magicien magiciens[4];
int ig_magiciens;
pthread_mutex_t lock;
} Game;
key_t key = (int) 1205;
int shm;
Game *game;
void creerXmagiciens();
int sommeDigitsPid(int pid);
void initialisation();
int rand_a_b(int a, int b);
void attendreAleatoirement();
void jeterSort();
void receptionSort(int sig);
void enterrement();
void magicien();
int main(void)
{
if((shm = shmget(key, sizeof(Game), 0666 | IPC_CREAT)) == -1)
{
perror("Erreur création de la SHM\\n");
exit(1);
}
if((game = shmat(shm,0,0))<0)
{
perror("Erreur attachement de la zone mémoire !\\n");
exit(1);
}
pthread_mutex_init(&game->lock, 0);
game->ig_magiciens = 0;
creerXmagiciens();
printf("début du jeu, il y a %d magiciens \\n\\n\\n", game->ig_magiciens);
return 0;
}
void creerXmagiciens()
{
int pid=0, i;
for(i=1;i<(4);i++)
{
switch(pid=fork())
{
case -1:
perror("Erreur lors du fork() \\n");
exit(1);
break;
case 0:
magicien();
exit(0);
break;
default:
break;
}
}
magicien();
}
int sommeDigitsPid(int pid)
{
if(pid == 0)
return 0;
else
return (pid % 10) + sommeDigitsPid(pid/10);
}
void initialisation()
{
struct sigaction action;
srand(time(0));
_pid = getpid();
_cote = (sommeDigitsPid(_pid) % 2 ? 1 : 0);
_pv = 10;
sigset_t sig_mask;
if(sigfillset(&sig_mask) != 0)
{
perror("Erreur sigfillset \\n");
exit(1);
}
if(sigdelset(&sig_mask, SIGUSR1) != 0)
{
perror("Erreur ajout SIGUSR1 \\n");
exit(1);
}
if(sigdelset(&sig_mask, SIGUSR2) != 0)
{
perror("Erreur ajout SIGUSR2 \\n");
exit(1);
}
if(sigprocmask(SIG_SETMASK, &sig_mask, 0) != 0)
{
perror("Erreur sigprocmask \\n");
exit(1);
}
action.sa_handler = receptionSort;
action.sa_flags=0;
if(sigaction(SIGUSR1, &action, 0) != 0)
{
perror("Erreur attachement handler SIGUSR1\\n");
exit(1);
}
action.sa_handler = receptionSort;
action.sa_flags = 0;
if(sigaction(SIGUSR2, &action, 0) != 0)
{
perror("Erreur attachement handler SIGUSR2 \\n");
exit(1);
}
pthread_mutex_lock(&game->lock);
game->magiciens[game->ig_magiciens] = _pid;
game->ig_magiciens++;
pthread_mutex_unlock(&game->lock);
}
int rand_a_b(int a, int b)
{
return rand()%(b-a) +a;
}
void attendreAleatoirement()
{
int delay = rand_a_b(1,5);
sleep(delay);
}
void jeterSort()
{
int opponent = rand_a_b(0,4 -1);
if(_cote)
{
printf("[%d] je jettre un mauvais sort sur %d\\n", _pid, game->magiciens[opponent]);
kill(game->magiciens[opponent], SIGUSR2);
}
else
{
printf("[%d] je jette un bon sort sur %d\\n", _pid, game->magiciens[opponent]);
kill(game->magiciens[opponent], SIGUSR1);
}
}
void receptionSort(int sig)
{
switch(sig)
{
case SIGUSR1:
_pv++;
printf("[%d] J'ai pris un bon sort : mes pv %d\\n", _pid, _pv);
break;
case SIGUSR2:
_pv-=2;
printf("[%d] J'ai pris un mauvais sort : mes pv %d\\n", _pid, _pv);
break;
default:
fprintf(stderr, "Signal reçu inconnu !\\n");
exit(1);
}
}
void enterrement()
{
printf("[%d] Je suis mort !!\\n", _pid);
pthread_mutex_lock(&game->lock);
game->ig_magiciens--;
pthread_mutex_unlock(&game->lock);
}
void magicien()
{
initialisation();
printf("Je suis le magicien %d du côté %d\\n", _pid, _cote);
sleep(1);
while(_pv > 0)
{
attendreAleatoirement();
jeterSort();
}
enterrement();
}
| 0
|
#include <pthread.h>
static pthread_mutex_t lock;
static pthread_barrier_t barrier;
int* counterArray;
int nthreads;
int ncounters;
void* chain(void* arglist)
{
int i, j, summation;
long tid = (long) arglist;
for (i = 0; i < nthreads; i++) {
pthread_mutex_lock(&lock);
if (tid == nthreads-1) {
for (j = 0; j < ncounters; j++)
counterArray[j*16]++;
} else {
for (j = 0; j < ncounters; j++)
summation += counterArray[j*16];
}
pthread_mutex_unlock(&lock);
pthread_barrier_wait(&barrier);
}
return 0;
}
int main(int argc, const char** const argv)
{
if (argc != 3) {
printf("Usage: ./microbench1 <nthreads> <ncounters>\\n");
exit(1);
}
nthreads = atoi(argv[1]);
ncounters = atoi(argv[2]);
if (nthreads < 2 || ncounters < 1) {
printf("This test requires at least 2 CPUs, 1 counter variable\\n");
exit(1);
}
long i;
pthread_t pth[nthreads];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
pthread_mutex_init(&lock, 0);
printf("Init done\\n");
pthread_barrier_init(&barrier, 0, nthreads);
counterArray = (int*) calloc(ncounters*16, sizeof(int));
for (i = 0; i < nthreads; i++) {
pthread_create(&pth[i], &attr, chain, (void*) i);
}
for (i = 0; i < nthreads; i++) {
pthread_join(pth[i], 0);
}
printf("Val: %d\\n", counterArray[0]);
printf("PASSED :-)\\n");
return 0;
}
| 1
|
#include <pthread.h>
void async_alarm(void);
void insert(char *);
void delete(void);
pthread_mutex_t mutex;
pthread_cond_t cond1;
pthread_cond_t cond2;
struct alarm **head;
} my_struct_t;
struct alarm {
char message[128];
int seconds;
struct alarm *link;
};
struct alarm *start = 0, *temp, *t, *fnode;
my_struct_t data = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER, &start};
int main (void)
{
char line[128];
pthread_t t1;
if(0 != (pthread_create(&t1, 0, (void*)&async_alarm, 0))) {
err_abort(errno, "Thread creation failed\\n");
exit(1);
}
while(1) {
printf("Alarm> ");
if (fgets (line, sizeof (line), stdin) == 0) {
exit(0);
}
if (strlen (line) <= 1)
continue;
pthread_mutex_lock(&(data.mutex));
insert(line);
}
return 0;
}
void insert(char *line)
{
int seconds;
char message[128];
temp = (struct alarm *)malloc(sizeof(struct alarm));
if (sscanf (line, "%d %64[^\\n]", &seconds, message ) < 2) {
fprintf (stderr, "Bad command\\n");
return;
}
temp -> seconds = time(0) + seconds;
strcpy(temp -> message, message);
if(start == 0) {
temp -> link = 0;
start = temp;
pthread_mutex_unlock(&(data.mutex));
pthread_cond_signal(&(data.cond1));
} else {
t = start;
if(t -> seconds > temp -> seconds) {
temp -> link = start;
start = temp;
pthread_mutex_unlock(&(data.mutex));
pthread_cond_signal(&(data.cond2));
} else {
while(t -> link != 0 && (t -> link -> seconds) < temp -> seconds) {
t = t -> link;
}
temp -> link = t -> link;
t -> link = temp;
pthread_mutex_unlock(&(data.mutex));
}
}
return;
}
void delete(void)
{
struct alarm *t;
t = start;
start = t -> link;
free(t);
}
void async_alarm(void)
{
struct timespec abs;
int status;
while(1) {
pthread_mutex_lock(&(data.mutex));
if (start == 0) {
pthread_cond_wait(&(data.cond1), &(data.mutex));
}
abs.tv_sec = start -> seconds;
abs.tv_nsec = 0;
status = pthread_cond_timedwait(&(data.cond2), &(data.mutex), &abs);
if(ETIMEDOUT == status) {
printf(" (%d) %s\\n", start -> seconds, start -> message);
delete();
}
pthread_mutex_unlock(&(data.mutex));
}
}
| 0
|
#include <pthread.h>
pthread_cond_t cond;
pthread_mutex_t mutex;
int count = 0;
int task[3];
void *consumer(void *arg)
{
for (;;)
{
int num;
pthread_mutex_lock(&mutex);
while (count <= 0)
pthread_cond_wait(&cond, &mutex);
count--;
num = task[count];
printf("Consumer processed item: %d\\n", num);
pthread_mutex_unlock(&mutex);
if (num == 3) break;
}
return 0 ;
}
void *producer(void *arg)
{
unsigned short int xsubi[3] = { 3, 7, 11 };
int num = 0;
for (;;)
{
double sleep_time = 1.0 + erand48(xsubi);
usleep(1000000 * sleep_time);
pthread_mutex_lock(&mutex);
task[count] = num;
count++;
printf("Producer slept for %lf seconds created item: %d\\n", sleep_time, num);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
if (num == 3) break ;
num++;
}
return 0 ;
}
int main()
{
pthread_t prod, cons;
pthread_cond_init(&cond, 0 );
pthread_mutex_init(&mutex, 0 );
pthread_create(&cons, 0, &consumer, 0 );
pthread_create(&prod, 0, &producer, 0 );
pthread_join(prod, 0 );
pthread_join(cons, 0 );
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
int val;
struct element* next;
int isDummy;
} element;
element* head;
element* tail;
} queue;
void init_queue(queue *q) {
element *e = (element*)malloc(sizeof(element));
e->isDummy = 1;
e->next = 0;
e->val=0;
q->head = e;
q->tail = e;
}
void enqueue(queue *q, int inputValue){
pthread_mutex_lock(&mut);
element *new = (element*)malloc(sizeof(element));
new->isDummy = 0;
new->val = inputValue;
new->next = 0;
q->tail->next = new;
q->tail = new;
pthread_mutex_unlock(&mut);
}
int dequeue(queue *q, int* extractedVal) {
pthread_mutex_lock(&mut);
if(q->head->next == 0) return 1;
element *second = q->head->next;
second->isDummy = 1;
q->head = second;
*extractedVal = second->val;
free(q->head);
pthread_mutex_unlock(&mut);
return 0;
}
void main(void){
pthread_mutex_init(&mut,0);
pthread_mutex_destroy(&mut);
}
| 0
|
#include <pthread.h>
double *_vector;
double _final_sum;
int *_ranges;
pthread_mutex_t _mutex;
double sum(double* vector, int a, int b) {
double sum = 0.0;
int i = 0;
for (i=a; i<b; i++)
sum += vector[i];
return sum;
}
void* sum_and_add(void* arg) {
int *range_a = (int*) arg;
double range_sum = sum(_vector, range_a[0], range_a[1]);
pthread_mutex_lock(&_mutex);
printf("Dodaję %g\\n", range_sum);
_final_sum += range_sum;
pthread_mutex_unlock(&_mutex);
}
int read_vector_from_file(char *file_name) {
int n = 0;
FILE* f = fopen(file_name, "r");
char buffer[80 +1];
fgets(buffer, 80, f);
n = atoi(buffer);
if(n == 0) {
perror("Nie udało się pobrać liczby elementów wektora\\n");
exit(1);
}
printf("Wektor ma %d elementów\\n", n);
prepare_vector(n);
int i;
for(i=0; i<n; i++) {
fgets(buffer, 80, f);
_vector[i] = atof(buffer);
}
fclose(f);
return n;
}
int prepare_vector(int n) {
size_t size = sizeof(double) * n;
_vector = (double*) malloc(size);
if (!_vector) {
perror("malloc in vector");
exit(1);
}
return 0;
}
int prepare_ranges(int n){
size_t size = sizeof(int) * (5 + 1);
_ranges = (int*)malloc(size);
if(!_ranges) {
perror("malloc in ranges");
return 1;
}
int i;
int dn = n/5;
for(i=0; i<5; i++) {
_ranges[i] = i*dn;
}
_ranges[5] = n;
return 0;
}
void clean() {
free(_vector);
free(_ranges);
}
int main(int argc, char **argv) {
int i, n;
_mutex = PTHREAD_MUTEX_INITIALIZER;
_final_sum = 0;
pthread_t threads[5];
n = read_vector_from_file("vector.dat");
prepare_ranges(n);
printf("Suma początkowa: %g\\n", _final_sum);
for (i = 0; i < 5; i++) {
if(pthread_create(&threads[i], 0, &sum_and_add, &_ranges[i]) != 0) {
clean();
perror("Blad podczas tworzenia watku!\\n");
exit(1);
}
}
for (i = 0; i < 5; i++) {
if(pthread_join(threads[i], 0) != 0) {
clean();
printf("Blad podczas czekania na watek %d!\\n", i);
exit(1);
}
}
clean();
printf("Suma końcowa: %g\\n", _final_sum);
return 0;
}
| 1
|
#include <pthread.h>
int fd;
int flag=0;
pthread_mutex_t lock;
pthread_t even_thd,odd_thd;
pthread_cond_t cond;
void handler(int arg)
{
printf("got sinal unpaused\\n");
}
void attr_func(pthread_attr_t *attr)
{
int ret=pthread_attr_init(attr);
if(ret!=0)
perror("pthread_attr_init");
ret=pthread_attr_setdetachstate(attr,PTHREAD_CREATE_JOINABLE);
if(ret!=0)
perror("pthread_attr_setdeatchstate");
}
void * even( )
{
char a='A';
int i=0;
while(i<10)
{
pthread_mutex_lock(&lock);
if(i%2==0)
printf("even:%d\\n",i);
i++;
pthread_mutex_unlock(&lock);
kill(odd_thd,SIGALRM);
printf("killed\\n");
}
}
void * odd( )
{
char a='0';
int i=0,s=2;
signal(SIGALRM,handler);
while(i<10)
{
printf("odd_waiting\\n");
pause();
printf("odd_unpaused\\n");
pthread_mutex_lock(&lock);
if(i%2!=0)
printf("odd:%d\\n",i);
i++;
pthread_mutex_unlock(&lock);
}
}
int main()
{
pthread_attr_t attr;
if(pthread_mutex_init(&lock,0)!=0)
{
perror("init");
exit(0);
}
pthread_cond_init (&cond , 0);
printf("%s_Thread_running\\n",__func__);
fd=open("even_oddfile",O_CREAT|O_RDWR|O_TRUNC);
if(fd==-1)
{
perror("open");
exit(1);
}
attr_func(&attr);
pthread_create(&even_thd,&attr,even,0);
pthread_create(&odd_thd,&attr,odd,0);
pthread_join(even_thd,0);
pthread_join(odd_thd,0);
printf("%s_Thread_exiting\\n",__func__);
return 0;
}
| 0
|
#include <pthread.h>
static void* thread_loop(void* arg)
{
struct thread_state *ts = arg;
struct ds_pcm_data pcm;
pthread_mutex_init(&ts->thread_mutex, 0);
pthread_cond_init(&ts->thread_cond, 0);
bool loop = 1;
while (loop) {
switch (ts->state) {
case PAUSE:
pthread_mutex_lock(&ts->thread_mutex);
pthread_cond_wait(&ts->thread_cond, &ts->thread_mutex);
pthread_mutex_unlock(&ts->thread_mutex);
break;
case PLAY: {
int rc = despotify_get_pcm(ts->session, &pcm);
if (rc == 0)
audio_play_pcm(ts->audio_device, &pcm);
else {
exit(-1);
}
break;
}
case EXIT:
loop = 0;
break;
}
}
pthread_cond_destroy(&ts->thread_cond);
pthread_mutex_destroy(&ts->thread_mutex);
return 0;
}
void thread_play(struct thread_state* ts)
{
pthread_mutex_lock(&ts->thread_mutex);
ts->state = PLAY;
pthread_cond_signal(&ts->thread_cond);
pthread_mutex_unlock(&ts->thread_mutex);
}
void thread_pause(struct thread_state* ts)
{
pthread_mutex_lock(&ts->thread_mutex);
ts->state = PAUSE;
pthread_mutex_unlock(&ts->thread_mutex);
}
void thread_exit(struct thread_state* ts)
{
pthread_mutex_lock(&ts->thread_mutex);
ts->state = EXIT;
pthread_cond_signal(&ts->thread_cond);
pthread_mutex_unlock(&ts->thread_mutex);
pthread_join(ts->thread, 0);
}
struct thread_state* thread_init(struct despotify_session* session)
{
struct thread_state* ts = malloc(sizeof(struct thread_state));
memset(ts, 0, sizeof(struct thread_state));
ts->audio_device = audio_init();
ts->session = session;
ts->state = PAUSE;
pthread_create(&ts->thread, 0, &thread_loop, ts);
return ts;
}
| 1
|
#include <pthread.h>
int numberOfSeats = 6;
int timeToReturn = 5;
int atPresent = 0;
int napping = 0;
int seedInteger;
void *createCustomer();
void *haircutStore();
void *sittingArea();
void assessLineup();
pthread_mutex_t lineupMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t sittingMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t nappingMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t nappingCheck = PTHREAD_COND_INITIALIZER;
pthread_cond_t workingCheck = PTHREAD_COND_INITIALIZER;
int main(int argc, char *argv[])
{
seedInteger = time(0);
srand(seedInteger);
pthread_t haircutter;
pthread_t makeCustomer;
pthread_t threadForTimer;
pthread_attr_t haircutterAttribute;
pthread_attr_t timerAttribute;
pthread_attr_t makecustomerAttributeibute;
pthread_attr_init(&timerAttribute);
pthread_attr_init(&haircutterAttribute);
pthread_attr_init(&makecustomerAttributeibute);
printf("\\n");
pthread_create(&makeCustomer,&makecustomerAttributeibute,createCustomer,0);
pthread_create(&haircutter,&haircutterAttribute,haircutStore,0);
pthread_join(haircutter,0);
pthread_join(makeCustomer,0);
return 0;
}
void *createCustomer()
{
int counter = 0;
printf("Function createCustomer was initialized\\n\\n");
fflush(stdout);
pthread_t customerComesIn[numberOfSeats+1];
pthread_attr_t customerAttribute[numberOfSeats+1];
while ( counter < ( numberOfSeats + 1 ) )
{
counter++;
pthread_attr_init(&customerAttribute[counter]);
while ( rand() % 2 != 1 )
{
sleep(1);
}
pthread_create(&customerComesIn[counter],&customerAttribute[counter],sittingArea,0);
}
pthread_exit(0);
}
void *sittingArea()
{
pthread_mutex_lock(&lineupMutex);
assessLineup();
sleep(timeToReturn);
sittingArea();
}
void *haircutStore()
{
int counter = 0;
printf("Haircutter has just opened up shop.\\n");
fflush(stdout);
while ( counter == 0 )
{
if ( atPresent == 0 )
{
printf("Store is currently empty, haircutter is currently sleeping.\\n");
fflush(stdout);
pthread_mutex_lock(&nappingMutex);
napping = 1;
pthread_cond_wait(&nappingCheck,&nappingMutex);
napping = 0;
pthread_mutex_unlock(&nappingMutex);
printf("The haircutter has awakened.\\n");
fflush(stdout);
}
else
{
printf("Haircutter has started cutting the hair.\\n");
fflush(stdout);
sleep((rand()%20)/5);
atPresent--;
printf("The haircut has finished, the customer has left the shop.\\n");
pthread_cond_signal(&workingCheck);
}
}
pthread_exit(0);
}
void assessLineup()
{
atPresent++;
printf("The customer has just ingressed the sitting area.\\t%d\\tThere are customers in the shop.\\n",atPresent);
fflush(stdout);
printf("The customer assesses the seats that are available.\\n");
fflush(stdout);
if ( atPresent < numberOfSeats )
{
if ( napping == 1 )
{
printf("The haircutter is sleeping, the customer has interrupted.\\n");
fflush(stdout);
pthread_cond_signal(&nappingCheck);
}
printf("The customer sits in the chair.\\n");
fflush(stdout);
pthread_mutex_unlock(&lineupMutex);
pthread_mutex_lock(&sittingMutex);
pthread_cond_wait(&workingCheck,&sittingMutex);
pthread_mutex_unlock(&sittingMutex);
return;
}
if ( atPresent >= numberOfSeats )
{
printf("All the seats have been taken, the customer is egressing the shop.\\n");
fflush(stdout);
atPresent--;
pthread_mutex_unlock(&lineupMutex);
return;
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex_count = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_condition = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_condition = PTHREAD_COND_INITIALIZER;
void* function_count1(void*);
void* function_count2(void*);
int count = 0;
int main(int argc, char** argv)
{
pthread_t thread1, thread2;
if(0 != pthread_create(&thread1, 0, function_count1, 0)){
perror("1. pthread_create() failed");
exit(1);
}
if(0 != pthread_create(&thread2, 0, function_count2, 0)){
perror("2. pthread_create() failed");
exit(1);
}
pthread_join(thread1, 0);
pthread_join(thread2, 0);
pthread_exit(0);
}
void* function_count1(void* dummy)
{
while(1){
pthread_mutex_lock( &mutex_condition);
while( (count >= 3) && (count <= 6)){
pthread_cond_wait( &cond_condition, &mutex_condition);
}
pthread_mutex_unlock(&mutex_condition);
pthread_mutex_lock(&mutex_count);
++count;
printf("function 1 - counter value function_count1(): %d\\n", count);
pthread_mutex_unlock( &mutex_count);
if(count >= 1000) pthread_exit(0);
}
}
void* function_count2(void* dummy)
{
while(1){
pthread_mutex_lock( &mutex_condition);
if( (count < 3) || (count > 6)){
pthread_cond_signal( &cond_condition);
}
pthread_mutex_unlock(&mutex_condition);
pthread_mutex_lock(&mutex_count);
++count;
printf("function 2 - counter value function_count2(): %d\\n", count);
pthread_mutex_unlock(&mutex_count);
if(count >= 1000) pthread_exit(0);
}
}
| 1
|
#include <pthread.h>
{
int balance;
} Account;
pthread_mutex_t mutex;
void deposit(Account* account, int amount)
{
pthread_mutex_lock(&mutex);
account->balance += amount;
pthread_mutex_unlock(&mutex);
}
void transfer(Account* accountA, Account* accountB, int amount)
{
pthread_mutex_lock(&mutex);
accountA->balance += amount;
accountB->balance -= amount;
pthread_mutex_unlock(&mutex);
}
Account accountA;
Account accountB;
void *thread_start()
{
int i;
for ( i = 0 ; i < 1000000 ; i++)
{
transfer( &accountA, &accountB, 10 );
transfer( &accountB, &accountA, 10 );
}
pthread_exit(0);
}
int main(int argc, char** argv)
{
accountA.balance = 1000;
accountB.balance = 1000;
pthread_mutex_init( &mutex, 0 );
pthread_t threads[2];
int i;
for( i = 0 ; i < 2 ; i++ )
{
int res = pthread_create( &threads[i], 0, thread_start, 0 );
if (res)
{
printf("Error: pthread_create() failed with error code %d\\n", res);
exit(-1);
}
}
for( i = 0 ; i < 2 ; i++ )
{
int res = pthread_join(threads[i], 0);
if (res)
{
printf("Error: pthread_join() failed with error code %d\\n", res);
exit(-1);
}
}
printf("Final balance on account A is %d\\n", accountA.balance );
printf("Final balance on account B is %d\\n", accountB.balance );
pthread_mutex_destroy(&mutex);
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_t thread1, thread2;
pthread_attr_t attr;
pthread_mutex_t impresor=PTHREAD_MUTEX_INITIALIZER;
void *imprimir (void *arg)
{
char a[12];
pthread_mutex_lock (&impresor);
strcpy(a, (char*)arg);
printf("%s ",a);
pthread_mutex_unlock (&impresor);
pthread_exit (0);
}
int main (void)
{
char cadena_hola[]="Hola ";
char cadena_mundo[]="mundo \\n";
int i;
pthread_attr_init (&attr);
for (i=1; i<=3; i++) {
pthread_create(&thread1, &attr, imprimir, (void *)cadena_hola);
pthread_create(&thread2, &attr, imprimir, (void *)cadena_mundo);
}
pthread_exit (0);
}
| 1
|
#include <pthread.h>
MESSAGE_TYPE_INFO,
MESSAGE_TYPE_ERROR,
MESSAGE_TYPE_FATAL,
MESSAGE_TYPE_MAX_VALUE,
} message_type_t;
static char* message_prefixes[MESSAGE_TYPE_MAX_VALUE] = {
[MESSAGE_TYPE_INFO] = "MEMKIND_INFO",
[MESSAGE_TYPE_ERROR] = "MEMKIND_ERROR",
[MESSAGE_TYPE_FATAL] = "MEMKIND_FATAL",
};
static bool log_enabled;
static pthread_once_t init_once = PTHREAD_ONCE_INIT;
static void log_init_once(void)
{
char *memkind_debug_env= getenv("MEMKIND_DEBUG");
if (memkind_debug_env) {
if(strcmp(memkind_debug_env, "1") == 0) {
log_enabled = 1;
}
else {
fprintf(stderr, "MEMKIND_WARNING: debug option \\"%s\\" unknown; Try man memkind for available options.\\n", memkind_debug_env);
}
}
}
static pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER;
static void log_generic(message_type_t type, const char * format, va_list args)
{
pthread_once(&init_once, log_init_once);
if(log_enabled || (type == MESSAGE_TYPE_FATAL))
{
pthread_mutex_lock(&log_lock);
fprintf(stderr, "%s: ", message_prefixes[type]);
vfprintf(stderr, format, args);
fprintf(stderr, "\\n");
pthread_mutex_unlock(&log_lock);
}
}
void log_info(const char * format, ...)
{
va_list args;
__builtin_va_start((args));
log_generic(MESSAGE_TYPE_INFO, format, args);
;
}
void log_err(const char * format, ...)
{
va_list args;
__builtin_va_start((args));
log_generic(MESSAGE_TYPE_ERROR, format, args);
;
}
void log_fatal(const char * format, ...)
{
va_list args;
__builtin_va_start((args));
log_generic(MESSAGE_TYPE_FATAL, format, args);
;
}
| 0
|
#include <pthread.h>
volatile int val;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* ThreadEntry( ){
int i =0;
while(i<30){
sleep(3);
pthread_mutex_lock( &mutex );
printf("\\x1b[32m" "New customer comes into the barber shop.\\n" "\\x1b[0m");
if(val < 1){
val ++;
if(val <= 0){
printf("\\x1b[32m" "\\nCustomer wakes up the barber.\\n""\\x1b[0m");
pthread_cond_signal( &cond);
}
}
pthread_mutex_unlock( & mutex );
i++;
}
return 0;
}
int main( int argc, char** argv ){
puts("\\x1b[36m" "Program begins" "\\x1b[0m");
int i =0,res;
pthread_t thread;
res = pthread_create( &thread, 0, ThreadEntry, 0);
if(res){
printf("Error with thread creation\\n");
exit(1);
}
while(i<30){
pthread_mutex_lock( &mutex );
val --;
if(val < 0){
printf("\\x1b[31m" "\\nThe barber is sleeping. \\n" "\\x1b[0m");
pthread_cond_wait( & cond, & mutex );
}
puts("\\x1b[31m" "Barber takes the next customer." "\\x1b[0m");
pthread_mutex_unlock( & mutex );
printf( "\\x1b[31m" "Barber know takes care of the customer\\n" "\\x1b[0m");
sleep(2);
printf("\\x1b[31m" "Barber know is finishing with the customer\\n" "\\x1b[0m");
i++;
}
res = pthread_join(thread, 0);
if(res){
printf("Error with thread join\\n");
exit(1);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t forks[5];
pthread_t phils[5];
void *philosopher (void *id);
int food_on_table ();
void get_fork (int, int, char *);
void down_forks (int, int);
pthread_mutex_t foodlock;
pthread_cond_t cond;
pthread_mutex_t forks_all;
int sleep_seconds = 0;
int main (int argn, char **argv){
int i;
if (argn == 2){
sleep_seconds = atoi (argv[1]);
}
pthread_cond_init(&cond, 0);
pthread_mutex_init (&foodlock, 0);
pthread_mutex_init (&forks_all, 0);
for (i = 0; i < 5; i++){
pthread_mutex_init (&forks[i], 0);
}
for (i = 0; i < 5; i++){
pthread_create (&phils[i], 0, philosopher, (void *)i);
}
for (i = 0; i < 5; i++){
pthread_join (phils[i], 0);
}
pthread_mutex_destroy(&foodlock);
return 0;
}
void *philosopher (void *num){
int id;
int left_fork, right_fork, f;
int is_exit = 0;
id = (int)num;
printf ("Philosopher %d sitting down to dinner.\\n", id);
right_fork = id;
left_fork = id + 1;
if (left_fork == 5)
left_fork = 0;
while (f = food_on_table ()) {
sleep (sleep_seconds);
printf ("Philosopher %d: get dish %d.\\n", id, f);
while(1){
get_fork (id, left_fork, "left ");
pthread_mutex_lock (&forks_all);
if(pthread_mutex_trylock(&forks[right_fork])){
pthread_cond_broadcast(&cond);
pthread_mutex_unlock (&forks[left_fork]);
printf ("Philosopher %d: let go %s fork %d\\n", id, "left", left_fork);
pthread_cond_wait(&cond, &forks_all);
pthread_mutex_unlock (&forks_all);
} else {
printf ("Philosopher %d: got %s fork %d\\n", id, "right", right_fork);
pthread_mutex_unlock (&forks_all);
break;
}
}
printf ("Philosopher %d: eating.\\n", id);
usleep (30000 * (50 - f + 1));
down_forks (left_fork, right_fork);
}
printf ("Philosopher %d is done eating.\\n", id);
return (0);
}
int food_on_table (){
static int food = 50;
int myfood;
pthread_mutex_lock (&foodlock);
if (food > 0) {
food--;
}
myfood = food;
pthread_mutex_unlock (&foodlock);
return myfood;
}
void get_fork (int phil, int fork, char *hand)
{
pthread_mutex_lock (&forks[fork]);
printf ("Philosopher %d: got %s fork %d\\n", phil, hand, fork);
}
void down_forks (int f1, int f2)
{
pthread_mutex_unlock (&forks[f1]);
pthread_mutex_unlock (&forks[f2]);
pthread_cond_broadcast(&cond);
}
| 0
|
#include <pthread.h>
struct timeval start, end;
long mtime, seconds, useconds;
int id;
double balance;
bool bInUse;
pthread_mutex_t mutex;
pthread_cond_t freeAcc;
} Account;
Account bank[4];
void deposit(Account* acc, double amount) {
pthread_mutex_lock(&acc->mutex);
while(acc->bInUse)pthread_cond_wait(&acc->freeAcc,&acc->mutex);
acc->bInUse = 1;
pthread_mutex_unlock(&acc->mutex);
usleep(10);
acc->balance += amount;
acc->bInUse = 0;
pthread_cond_signal(&acc->freeAcc);
}
double bankInit() {
int i;
double sum = 0;
for(i=0;i<4;i++) {
bank[i].id = i;
bank[i].balance = 0;
bank[i].bInUse = 0;
sum += bank[i].balance;
if (pthread_mutex_init(&bank[i].mutex, 0) != 0) { printf("mutex error\\n"); }
if (pthread_cond_init(&bank[i].freeAcc, 0) != 0) { printf("error initializing condition\\n"); }
}
return sum;
}
void* depositThread( void* param ) {
int to = -1;
int iter = 10000;
while(iter--) {
to = rand()%4;
deposit(&bank[to], 1);
}
return 0;
}
int main(int argc, char *argv[])
{
int i;
double sum = bankInit();
printf("Initial bank capital: %f\\n",sum);
gettimeofday(&start, 0);
pthread_t* tid;
tid = malloc(100 * sizeof(pthread_t));
for(i=0;i<100;i++) {
printf("%d ",i);
pthread_create(&tid[i], 0, depositThread, 0);
}
printf("\\n");
printf("Main waiting for threads...\\n");
for(i=0;i<100;i++) pthread_join(tid[i], 0);
double sumEnd = 0;
for(i=0;i<4;i++) {
printf("Account %d balance : %f\\n",i,bank[i].balance);
sumEnd += bank[i].balance;
}
printf("Final bank sum: %f\\n",sumEnd);
if(sumEnd != 100*10000) printf("ERROR : ******** CORRUPT BANK!!!!!! *******");
gettimeofday(&end, 0);
seconds = end.tv_sec - start.tv_sec;
useconds = end.tv_usec - start.tv_usec;
mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;
printf("Elapsed time: %ld milliseconds\\n", mtime);
return 0;
}
| 1
|
#include <pthread.h>
int main(int argc, char* argv[]){
pthread_t Les_Threads[2];
int delai[2];
void Une_Tache (void *arg);
if (argc != 3) {
printf("Utilisation : %s delai_1 delai_2 !\\n", argv[0]);
return 1;
}
delai[0] = atoi(argv[1]);
delai[1] = atoi(argv[2]);
pthread_create(&Les_Threads[0],
0, (void *(*)(void *))Une_Tache, &delai[0]);
pthread_create(&Les_Threads[1],
0, (void *(*)(void *))Une_Tache, &delai[1]);
int i = 0;
for (i = 0 ; i < 2 ; i++){
pthread_join(Les_Threads[i], 0);
printf("main (tid %d) fin de tid %d\\n", (int)pthread_self(), (int)Les_Threads[i]);
}
return 0;
}
void Une_Tache (void *arg) {
int *Ptr;
int compteur, delai;
pthread_cond_t var_cond;
pthread_mutex_t verrou;
struct timespec time;
Ptr = (int *)arg;
delai = *Ptr;
pthread_cond_init(&var_cond, 0);
pthread_mutex_init(&verrou, 0);
compteur = 0;
while (compteur < 10){
pthread_mutex_lock(&verrou);
clock_gettime (CLOCK_REALTIME, &time);
time.tv_sec += delai ;
compteur = compteur + 1;
printf("tid %d : date (s.ns) : %d.%d, compteur %d, delai %d\\n",
(int)pthread_self(), (int)time.tv_sec, (int)time.tv_nsec, compteur, delai);
pthread_cond_timedwait(&var_cond, &verrou, &time);
pthread_mutex_unlock(&verrou);
}
}
| 0
|
#include <pthread.h>
pthread_t processos[300];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int SALDO = 0;
int procId;
int valor;
int tipo;
} PROC;
PROC procs[300];
void initStruct(){
int i = 0;
while (i < 300) {
procs[i].procId = 0;
procs[i].valor = 0;
procs[i].tipo = 0;
i++;
}
}
void showStruct(){
int i = 0;
while (i < 300) {
printf("\\nO struct na posicão %d tem os valores de: id = %d valor = %d e tipo = %d", i, procs[i].procId, procs[i].valor, procs[i].tipo);
i++;
}
printf("\\n");
}
void lerArquivo(FILE *fp){
int i = 0;
char proc_s[10];
char tipo[10];
while ( i < 300 && (!feof(fp))) {
fscanf(fp, "%s %d %s %d ", proc_s, &procs[i].procId, tipo, &procs[i].valor);
if ( (strcmp(tipo, "consulta")) == 0 ){
procs[i].tipo = 3;
}
if ( (strcmp(tipo, "deposito")) == 0 ){
procs[i].tipo = 1;
}
if ( (strcmp(tipo, "saque")) == 0 ){
procs[i].tipo = 2;
}
i++;
}
}
void *consultaConta(void *arg){
long offset = (long)arg;
sleep(1);
printf("Processo %ld de consulta criado\\n", (offset+1));
printf("Processo %ld de consulta. Saldo atual é de: %d\\n", (offset+1), SALDO);
pthread_exit((void*) 0);
}
void *saqueConta(void *arg){
long offset = (long)arg;
int used = 0;
while( used == 0 ) {
sleep(1);
if ( pthread_mutex_trylock(&mutex) != 0 ) {
printf("Processo %ld de saque criado. Saque (%d)\\n", (offset+1), procs[offset].valor);
SALDO = SALDO - (int)procs[offset].valor;
printf("Processo %ld de saque acessa região crítica - saca (%d)\\n", (offset+1), procs[offset].valor);
pthread_mutex_unlock(&mutex);
used += 1;
}
else {
printf("Processo %ld de saque bloqueado.\\n", (offset+1));
}
}
printf("Processo %ld de saque sai da região crítica.\\n", (offset+1));
pthread_exit((void*) 0);
}
void *depositoConta(void *arg){
long offset = (long)arg;
int used = 0;
while( used == 0 ) {
sleep(1);
if ( pthread_mutex_trylock(&mutex) != 0 ) {
printf("Processo %ld de deposito criado. deposito (%d)\\n", (offset+1), procs[offset].valor);
SALDO = SALDO + (int)procs[offset].valor;
printf("Processo %ld de deposito acessou região crítica - deposita (%d)\\n", (offset+1), procs[offset].valor);
pthread_mutex_unlock(&mutex);
used += 1;
}
else {
printf("Processo %ld de deposito bloqueado.\\n", (offset+1));
}
}
printf("Processo %ld de deposito sai da região crítica.\\n", (offset+1));
pthread_exit((void*) 0);
}
int main(){
FILE *in;
int j;
void *status;
if ( (in = fopen("in.txt", "r")) == 0 ) {
printf("\\nArquivo de entrada inexistente! \\nTente novamente!\\n\\n");
exit(1);
}
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
initStruct();
lerArquivo(in);
for(j = 0; (j<300 && (procs[j].tipo != 0)); j++){
if ( procs[j].tipo == 1 ) {
pthread_create(&processos[j], &attr, depositoConta, (void *)j);
}
else {
if ( procs[j].tipo == 2 ) {
pthread_create(&processos[j], &attr, saqueConta, (void *)j);
}
else {
pthread_create(&processos[j], &attr, consultaConta, (void *)j);
}
}
}
pthread_attr_destroy(&attr);
for(j = 0; (j<300 && (procs[j].tipo != 0)); j++){
pthread_join(processos[j], &status);
}
printf("\\n\\n|| *** || O saldo é : %d || *** ||\\n", SALDO);
pthread_mutex_destroy(&mutexsum);
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
void **generateMat();
void printMat(int **mat);
int way1Sort(int **mat);
void maxAndSwap(int **mat, int col);
void *paraMax(void *arg);
int maxVal = 0;
int maxRow = 0;
int **mat;
int N;
int power;
uint64_t timer = 0;
pthread_t thr_id[8];
pthread_mutex_t maxLock;
pthread_mutex_t maxRowLock;
struct ptArg{
int start;
int col;
int size;
};
struct ptArg thread_data_array[8];
void **generateMat() {
int i, j;
mat = (int **)malloc(N * sizeof(int*));
srand(2);
for (i = 0; i < N; i++){
mat[i] = (int *)malloc(N * sizeof(int));
for (j = 0; j < N; j++){
mat[i][j] = rand()%1000;
}
}
}
int way1Sort(int **mat){
int i;
int j;
for (i = 0; i < N; i++){
maxAndSwap(mat, i);
}
return 0;
}
void maxAndSwap(int **mat, int col){
uint64_t diff;
struct timespec start, end;
int rc, ntime, stime;
int i;
int j;
int stepSize;
int colLength = N - col;
int numThreads;
void *status;
pthread_attr_t attr;
pthread_mutex_init (&maxLock, 0);
pthread_mutex_init (&maxRowLock, 0);
pthread_attr_init (&attr);
pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_JOINABLE);
clock_gettime(CLOCK_REALTIME, &start);
maxVal = mat[col][col];
maxRow = col;
if (colLength > 8 * 2){
numThreads = 8;
stepSize = colLength/numThreads;
}else{
numThreads = colLength/2;
stepSize = 2;
}
for (i = 0; i < numThreads - 1; i++){
thread_data_array[i].start = col + i*stepSize;
thread_data_array[i].size = stepSize;
thread_data_array[i].col = col;
}
thread_data_array[numThreads - 1].start = col + (numThreads - 1)*stepSize;
thread_data_array[numThreads - 1].size = colLength - (numThreads - 1)*stepSize;
thread_data_array[numThreads - 1].col = col;
clock_gettime(CLOCK_MONOTONIC, &start);
for (i = 0; i < numThreads; i++){
rc = pthread_create(&thr_id[i], &attr, paraMax, (void *)&thread_data_array[i]);
}
pthread_attr_destroy(&attr);
for (i = 0; i < numThreads; i++){
pthread_join(thr_id[i], &status);
}
clock_gettime(CLOCK_MONOTONIC, &end);
diff = 1000000000L * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec;
timer += diff;
pthread_mutex_destroy(&maxLock);
pthread_mutex_destroy(&maxRowLock);
int *temp = mat[col];
mat[col] = mat[maxRow];
mat[maxRow] = temp;
}
void *paraMax(void *arg){
struct ptArg *myArg;
myArg = (struct ptArg *) arg;
int start = myArg->start;
int col = myArg->col;
int size = myArg->size;
int i;
int localMax = mat[start][col];
int localRowMax = myArg->start;
for (i = start; i < start + size; i++){
if (abs(mat[i][col]) > localMax){
localMax = abs(mat[i][col]);
localRowMax = i;
}
}
pthread_mutex_lock (&maxLock);
pthread_mutex_lock (&maxRowLock);
if (localMax > maxVal){
maxVal = localMax;
maxRow = localRowMax;
}
pthread_mutex_unlock (&maxLock);
pthread_mutex_unlock (&maxRowLock);
pthread_exit(0);
}
void printMat(int **mat){
int i;
int j;
for (i = 0; i < N; i++){
for (j = 0; j < N; j++){
printf("%d ", mat[i][j]);
}
printf("\\n");
}
}
int main(int argc, char **argv){
FILE *fp;
fp=fopen("way1Para.csv","w+");
for (power = 4; power < 12; power++){
N = pow(2, power);
timer = 0;
generateMat();
way1Sort(mat);
free(mat);
printf("For 2^%d size, time = %llu nanoseconds\\n", power, (long long unsigned int) timer);
fprintf(fp, "%d, %llu\\n", power, (long long unsigned int) timer);
}
fclose(fp);
exit(0);
}
| 0
|
#include <pthread.h>
time_t t;
struct tm tm;
char **ssid;
struct timeval startwtime;
pthread_mutex_t *mut;
pthread_cond_t *notFull, *notEmpty;
} ssid_info;
void delete_ssid_info(ssid_info *wifi_info);
ssid_info * ssid_info_init();
void *wifi_writer(void* arg);
void *wifi_scanner(void* arg);
pthread_cond_t *wakeupA,*wakeupB;
pthread_mutex_t *threadA,*threadB;
int main(int argc,char *argv[])
{
if(argc!=2){
printf("Missing number of seconds ! \\n");
exit(1);
}
threadA=(pthread_mutex_t *) malloc (sizeof (pthread_mutex_t));
pthread_mutex_init (threadA, 0);
threadB=(pthread_mutex_t *) malloc (sizeof (pthread_mutex_t));
pthread_mutex_init (threadB, 0);
wakeupA=(pthread_cond_t *) malloc (sizeof (pthread_cond_t));
pthread_cond_init(wakeupA,0);
wakeupB=(pthread_cond_t *) malloc (sizeof (pthread_cond_t));
pthread_cond_init(wakeupB,0);
int sleepTime=atoi(argv[1]);
ssid_info *wifi_info;
wifi_info=ssid_info_init();
if (ssid_info_init()==0){
fprintf (stderr, "main: Wifi Info Init failed.\\n");
exit (1);
}
pthread_t scanner, writer;
int flag;
flag=pthread_create (&scanner, 0, wifi_scanner, wifi_info);
if(flag){
printf("Error: pthread_create returned code: %d\\n", flag);
exit(1);
}
flag=pthread_create (&writer, 0, wifi_writer, wifi_info);
if(flag){
printf("Error: pthread_create returned code: %d\\n", flag);
exit(1);
}
struct timeval startwtime,endwtime;
clock_t start_t,end_t;
double t2,time;
double mean=0;
int realprt= (int) sleepTime;
double fract;
fract= sleepTime - realprt;
fract=fract*pow(10,9);
struct timespec delay={realprt,fract};
delay.tv_sec=realprt;
delay.tv_nsec=fract;
t2=sleepTime;
gettimeofday(&startwtime,0);
for(;;){
start_t = clock();
clock_nanosleep(CLOCK_REALTIME,0,&delay,0);
gettimeofday(&endwtime,0);
time=(double)((endwtime.tv_usec - startwtime.tv_usec)
/1.0e6 + endwtime.tv_sec - startwtime.tv_sec);
mean=sleepTime-time;
t2=t2+mean;
realprt=(int)t2;
fract=(t2-realprt)*1000000000;
delay.tv_sec=realprt;
delay.tv_nsec=fract;
pthread_cond_signal(wakeupA);
pthread_cond_signal(wakeupB);
end_t=clock();
cpu_usage(start_t,end_t);
startwtime=endwtime;
}
pthread_join (scanner, 0);
pthread_join (writer, 0);
}
void *wifi_writer(void* q){
ssid_info *wifi_info=(ssid_info *) q;
pthread_mutex_lock(threadA);
int i;
for(;;){
pthread_mutex_lock (wifi_info->mut);
if(wifi_info->ssid == 0){
pthread_cond_wait (wifi_info->notEmpty, wifi_info->mut);
}
struct tm t;
t=wifi_info->tm;
int fl=get_in_file(wifi_info->ssid,t,wifi_info->startwtime);
if(fl!=0) printf("Error! %d\\n",fl);
wifi_info->ssid=0;
pthread_mutex_unlock (wifi_info->mut);
pthread_cond_signal (wifi_info->notFull);
pthread_cond_wait (wakeupA,threadA);
}
}
void *wifi_scanner(void* q){
ssid_info *wifi_info;
wifi_info=(ssid_info *) q;
pthread_mutex_lock(threadB);
for(;;){
pthread_mutex_lock (wifi_info->mut);
if( wifi_info->ssid !=0){
pthread_cond_wait (wifi_info->notFull, wifi_info->mut);
}
wifi_info->t= time(0);
wifi_info->ssid=read_ssid();
wifi_info->tm= *localtime(&wifi_info->t);
gettimeofday(&wifi_info->startwtime,0);
pthread_mutex_unlock (wifi_info->mut);
pthread_cond_signal (wifi_info->notEmpty);
pthread_cond_wait (wakeupB,threadB);
}
}
void delete_ssid_info(ssid_info *wifi_info){
free(wifi_info->ssid);
pthread_mutex_destroy(wifi_info->mut);
free(wifi_info->mut);
pthread_cond_destroy(wifi_info->notFull);
free(wifi_info->notFull);
pthread_cond_destroy(wifi_info->notEmpty);
free(wifi_info->notEmpty);
free(wifi_info);
}
ssid_info * ssid_info_init(){
ssid_info *wifi_info;
wifi_info=(ssid_info*)malloc(sizeof(ssid_info));
if (wifi_info==0) return 0;
wifi_info->ssid=0;
wifi_info->mut = (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t));
pthread_mutex_init (wifi_info->mut, 0);
wifi_info->notFull = (pthread_cond_t *) malloc (sizeof (pthread_cond_t));
pthread_cond_init (wifi_info->notFull, 0);
wifi_info->notEmpty = (pthread_cond_t *) malloc (sizeof (pthread_cond_t));
pthread_cond_init (wifi_info->notEmpty, 0);
return (wifi_info);
}
| 1
|
#include <pthread.h>
struct thread_info {
pthread_t thread_id;
int thread_num;
int consumer;
int qty_actions;
};
struct magic_account
{
double min_amount;
double max_amount;
double actual_amount;
pthread_mutex_t acc_lock;
} * conta_magica;
int QTD_ACTIONS = 100;
sem_t mutex_cons;
sem_t mutex_prod;
static void * change_balance(void *arg){
struct thread_info *tinfo = arg;
for(int i = 0; i < tinfo->qty_actions; i++){
if( tinfo->consumer ){
while( conta_magica->actual_amount <= conta_magica->min_amount ){
printf("Esbarrou no limite minimo\\n");
sem_wait (&mutex_cons);
}
pthread_mutex_lock(&conta_magica->acc_lock);
conta_magica->actual_amount--;
pthread_mutex_unlock(&conta_magica->acc_lock);
sem_post(&mutex_prod);
}else{
while( conta_magica->actual_amount >= conta_magica->max_amount ){
printf("Esbarrou no limite maximo\\n");
sem_wait (&mutex_prod);
}
pthread_mutex_lock(&conta_magica->acc_lock);
conta_magica->actual_amount++;
pthread_mutex_unlock(&conta_magica->acc_lock);
sem_post(&mutex_cons);
}
}
return 0;
}
int main(int argc, char* argv[]){
pthread_attr_t attr;
struct thread_info *tinfo_prod;
struct thread_info *tinfo_cons;
void *res;
int ret;
if(argc < 3){
printf("Falta argumento \\n");
return 1;
}
sem_init(&mutex_cons, 0, 1);
sem_init(&mutex_prod, 0, 1);
int qtd_prod = atoi(argv[1]);
int qtd_cons = atoi(argv[2]);
printf("Quantidade de produtores: %d \\n", qtd_prod);
printf("Quantidade de consumidores: %d \\n", qtd_cons);
conta_magica = calloc(1, sizeof(struct magic_account));
conta_magica->min_amount = 0;
conta_magica->max_amount = 1000;
printf("Escroto humano");
conta_magica->actual_amount = conta_magica->max_amount / 2;
if( pthread_mutex_init(&conta_magica->acc_lock, 0) != 0 ){
printf("\\n não foi possível inicializar a conta.");
return 1;
}
tinfo_prod = calloc(qtd_prod, sizeof(struct thread_info));
if (tinfo_prod == 0){
printf("Erro calloc tinfo_prod\\n");
return 1;
}
tinfo_cons = calloc(qtd_cons, sizeof(struct thread_info));
if (tinfo_cons == 0){
printf("Erro calloc tinfo_cons\\n");
return 1;
}
ret = pthread_attr_init(&attr);
if (ret != 0){
printf("Erro pthread_attr_init\\n");
}
int inicio = 0;
for(int i=0; i < qtd_prod; i++){
tinfo_prod[i].thread_num = i + 1;
tinfo_prod[i].consumer = 0;
tinfo_prod[i].qty_actions = QTD_ACTIONS;
ret = pthread_create(&tinfo_prod[i].thread_id, &attr, &change_balance, (void *)&tinfo_prod[i]);
if (ret != 0)
printf("Erro pthread_create\\n");
}
for(int i=0; i < qtd_cons; i++){
tinfo_cons[i].thread_num = i + 1;
tinfo_cons[i].consumer = 1;
tinfo_cons[i].qty_actions = QTD_ACTIONS;
ret = pthread_create(&tinfo_cons[i].thread_id, &attr, &change_balance, (void *)&tinfo_cons[i]);
if (ret != 0)
printf("Erro pthread_create\\n");
}
for (int tnum = 0; tnum < qtd_prod; tnum++) {
ret = pthread_join(tinfo_prod[tnum].thread_id, &res);
if (ret != 0)
printf("Erro pthread_join\\n");
printf("Thread %d finalizada\\n", tinfo_prod[tnum].thread_num);
}
for (int tnum = 0; tnum < qtd_cons; tnum++) {
ret = pthread_join(tinfo_cons[tnum].thread_id, &res);
if (ret != 0)
printf("Erro pthread_join\\n");
printf("Thread %d finalizada\\n", tinfo_cons[tnum].thread_num);
}
printf("Balanco final da conta: %5f", conta_magica->actual_amount);
return 0;
}
| 0
|
#include <pthread.h>
struct _thread_data_t {
int tid;
unsigned long long floor;
unsigned long long ceiling;
unsigned long long thread_sum;
};
unsigned long long sum;
pthread_mutex_t lock_sum;
void error( char * msg )
{
perror( msg );
exit( 1 );
}
void * thr_func( void * arg )
{
thread_data_t * data = (thread_data_t *) arg;
for( data->floor; data->floor <= data->ceiling; ++(data->floor) )
data->thread_sum = data->floor * data->thread_sum;
pthread_mutex_lock( &lock_sum );
sum = data->thread_sum * sum;
pthread_mutex_unlock( &lock_sum );
pthread_exit( 0 );
}
void init_longs( unsigned long long to_factorialize, unsigned long long * half, unsigned long long * three_fourths, unsigned long long * seven_eighths )
{
unsigned long long two, three, four, seven, eight;
two = 2;
three = 3;
four = 4;
seven = 7;
eight = 8;
*half = to_factorialize / two;
*three_fourths = (to_factorialize * three) / four;
*seven_eighths = (to_factorialize * seven) / eight;
}
int main( int argc, char *argv[] )
{
pthread_t threads[4];
thread_data_t thr_data[4];
unsigned long long to_factorialize;
unsigned long long half, three_fourths, seven_eighths;
int i, thr_status;
sum = 1;
pthread_mutex_init( &lock_sum, 0 );
to_factorialize = strtoull( argv[1], 0, 10 );
if( errno )
error( "Converting to ull failed" );
if( to_factorialize < 1 || to_factorialize > 20 )
error( "Invalide range: Can only accept numbers from [1,20]" );
init_longs( to_factorialize, &half, &three_fourths, &seven_eighths );
for( i = 0; i < 4; ++i )
{
thr_data[i].tid = i;
thr_data[i].thread_sum = 1;
}
thr_data[0].floor = 1;
thr_data[0].ceiling = half;
thr_data[1].floor = half + 1;
thr_data[1].ceiling = three_fourths;
thr_data[2].floor = three_fourths + 1;
thr_data[2].ceiling = seven_eighths;
thr_data[3].floor = seven_eighths + 1;
thr_data[3].ceiling = to_factorialize;
for( i = 0; i < 4; ++i )
{
thr_status = pthread_create( &threads[i], 0, thr_func, &thr_data[i] );
if( thr_status < 0 )
error( "Creating thread failed" );
}
for( i = 0; i < 4; ++i )
pthread_join( threads[i], 0 );
printf( "%llu\\n", sum );
return 0;
}
| 1
|
#include <pthread.h>
extern void io_output(int * arg);
struct _erl_async* next;
struct _erl_async* prev;
long async_id;
void* async_data;
void (*async_invoke)(void*);
void (*async_free)(void*);
} ErlAsync;
pthread_mutex_t mtx;
pthread_cond_t cv;
pthread_t thr;
int len;
ErlAsync* head;
ErlAsync* tail;
} AsyncQueue;
int key;
int value;
} AsyncData;
static AsyncQueue* async_q;
static long async_id = 0;
static void* async_main(void*);
static void async_add(ErlAsync*, AsyncQueue*);
int init_async() {
AsyncQueue* q;
int i;
int max_threads = 3;
async_q = q = (AsyncQueue*) malloc(max_threads * sizeof (AsyncQueue));
for (i = 0; i < max_threads; i++) {
q->head = 0;
q->tail = 0;
q->len = 0;
pthread_mutex_init(&q->mtx, 0);
pthread_cond_init(&q->cv, 0);
pthread_create(&q->thr, 0, async_main, (void*) q);
q++;
}
return 0;
}
static void async_add(ErlAsync* a, AsyncQueue* q) {
pthread_mutex_lock(&q->mtx);
if (q->len == 0) {
q->head = a;
q->tail = a;
q->len = 1;
pthread_cond_signal(&q->cv);
} else {
a->next = q->head;
q->head->prev = a;
q->head = a;
q->len++;
}
pthread_mutex_unlock(&q->mtx);
}
static ErlAsync* async_get(AsyncQueue* q) {
ErlAsync* a;
pthread_mutex_lock(&q->mtx);
while ((a = q->tail) == 0) {
pthread_cond_wait(&q->cv, &q->mtx);
}
if (q->head == q->tail) {
q->head = q->tail = 0;
q->len = 0;
} else {
q->tail->prev->next = 0;
q->tail = q->tail->prev;
q->len--;
}
pthread_mutex_unlock(&q->mtx);
return a;
}
static void* async_main(void* arg) {
AsyncQueue* q = (AsyncQueue*) arg;
pthread_t main_thread = pthread_self();
printf("the main_thread1111111 === %p \\n", &main_thread);
while (1) {
ErlAsync* a = async_get(q);
printf("the qlen==== %d \\n", q->len);
(*a->async_invoke)(a->async_data);
free(a);
}
return 0;
}
long driver_async(unsigned int* key,
void (*async_invoke)(void*), void* async_data,
void (*async_free)(void*)) {
ErlAsync* a = (ErlAsync*) malloc(sizeof (ErlAsync));
long id;
unsigned int qix;
a->next = 0;
a->prev = 0;
a->async_data = async_data;
a->async_invoke = async_invoke;
a->async_free = async_free;
async_id = (async_id + 1) & 0x7fffffff;
if (async_id == 0)
async_id++;
id = async_id;
a->async_id = id;
if (key == 0) {
qix = (id % 3);
} else {
qix = (*key % 3);
}
async_add(a, &async_q[qix]);
return id;
}
void io_test(void * arg) {
AsyncData* d = (AsyncData*) arg;
pthread_t main_thread = pthread_self();
printf("the main_thread2222222 === %p \\n", &main_thread);
printf("the key : %d", d->key);
io_output(&d->key);
free(d);
}
int main() {
int i;
init_async();
for (i = 0; i < 30; i++) {
AsyncData* d = (AsyncData*) malloc(sizeof (AsyncData));
d->key = i;
d->value = i;
int c = i;
driver_async((unsigned int*) & c, io_test, d, 0);
}
printf("the result\\n");
pthread_t main_thread = pthread_self();
pthread_exit(&main_thread);
return 0;
}
| 0
|
#include <pthread.h>
int g_val = 0;
pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t g_cond = PTHREAD_COND_INITIALIZER;
void do_prime(int s)
{
ull_t i;
int flag = 0;
for (i = 2; i < s + 300000000; i++)
{
if ((s + 300000000) % i == 0)
{
flag = 1;
break;
}
}
if (1 == flag)
printf("\\n%llu is not a prime!\\n", (ull_t)(s + 300000000));
else
printf("\\n%llu is a prime!\\n", (ull_t)(s + 300000000));
}
void * thread_handler(void * arg)
{
while (1)
{
pthread_mutex_lock(&g_lock);
pthread_cond_wait(&g_cond, &g_lock);
do_prime(g_val);
pthread_mutex_unlock(&g_lock);
}
}
int main(void)
{
int k, ret;
pthread_t tid;
ret = pthread_create(&tid, 0, thread_handler, 0);
if (ret)
{
fprintf(stderr, "pthread:%s\\n", strerror(ret));
exit(1);
}
sleep(1);
while (1)
{
printf("输入数据: ");
fflush(stdout);
pthread_mutex_lock(&g_lock);
scanf("%d", &g_val);
pthread_mutex_unlock(&g_lock);
pthread_cond_signal(&g_cond);
}
return 0;
}
| 1
|
#include <pthread.h>
void reception_task(int tab[]){
int i;
for(i = 0; i<180;i++){
tab[i]=(rand()%180);
}
}
void computation_task(int *tab1, int *tab2){
int i;
for(i=0; i<180;i++){
if (tab1[i]>7){
tab2[i] = tab1[i];
} else{
tab2[i] = 0;
}
}
}
void print_task(int *tab){
int i;
char result[180];
for(i=0;i<180;i++){
result[i]=(tab[i]!=0)?' ':'*';
}
}
void* reception_pthread(void);
void* computation_pthread(void);
void* print_pthread(void);
pthread_t reception, computation, print_data;
pthread_mutex_t data_tab, obst_tab;
pthread_cond_t new_data, to_print;
int running=1;
int data_old=0;
int data[180];
int obstacle[180];
void* reception_pthread(void){
while(running){
pthread_mutex_lock(&data_tab);
printf("reception task \\n");
reception_task(data);
data_old=0;
pthread_mutex_unlock(&data_tab);
pthread_cond_signal(&new_data);
usleep(100000);
}
}
void* computation_pthread(void){
while(running){
pthread_mutex_lock(&data_tab);
pthread_mutex_lock(&obst_tab);
if(data_old==1){
printf("... waiting ... tab has no new data\\n");
pthread_cond_wait(&new_data, &data_tab);
}
printf("computation task\\n");
computation_task(data, obstacle);
data_old=1;
pthread_mutex_unlock(&data_tab);
pthread_mutex_unlock(&obst_tab);
pthread_cond_signal(&to_print);
usleep(250000);
}
}
void* print_pthread(void){
while(running){
pthread_mutex_lock(&obst_tab);
pthread_cond_wait(&to_print, &obst_tab);
printf("print task\\n");
print_task(obstacle);
pthread_mutex_unlock(&obst_tab);
}
}
int main(int argc, char* argv[]){
if (argc<2){
printf("arguments not found - usage : exec <tps in sec>\\n");
return 1;
}
printf("beginning main Thread.\\n");
int temp = atoi(argv[1]);
time_t today_time = 1397131000;
srand(today_time);
if ((pthread_mutex_init(&data_tab, 0) != 0) &&( pthread_mutex_init(&obst_tab, 0) != 0) ){
printf("\\n mutex init failed.\\n");
return 1;
}
if((pthread_cond_init(&new_data, 0) != 0) || (pthread_cond_init(&to_print, 0))){
printf("\\n initialisation of condition failed.\\n");
}
pthread_create(&reception, 0, &reception_pthread, 0);
pthread_create(&computation, 0, &computation_pthread, 0);
pthread_create(&print_data, 0, &print_pthread, 0);
printf("sleeping %ds ...\\n", temp);
sleep(temp);
printf("...stopping threads !\\n");
running=0;
pthread_join(reception, 0);
pthread_join(computation, 0);
pthread_join(print_data, 0);
pthread_mutex_destroy(&data_tab);
pthread_mutex_destroy(&obst_tab);
printf("end of the main Thread\\n");
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t mymutex;
static int th_cnt;
static void *body(void *arg)
{
int j;
fprintf(stderr, "Thread %d: %s\\n", th_cnt++, (char *)arg);
pthread_mutex_lock(&mymutex);
for (j=0; j<20; j++) {
usleep(500000);
fprintf(stderr,(char *)arg);
}
pthread_mutex_unlock(&mymutex);
return 0;
}
int main(int argc, char *argv[])
{
pthread_t t1, t2, t3;
int err;
pthread_mutexattr_t mymutexattr;
pthread_mutexattr_init(&mymutexattr);
pthread_mutex_init(&mymutex, &mymutexattr);
pthread_mutexattr_destroy(&mymutexattr);
err = pthread_create(&t1, 0, body, (void *)".");
err = pthread_create(&t3, 0, body, (void *)"o");
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_join(t3, 0);
printf("\\n");
return 0;
}
| 1
|
#include <pthread.h>
struct node_t
{
char pcm[4096];
struct node_t * next;
};
struct fifo_t
{
struct node_t * head;
struct node_t * tail;
pthread_mutex_t lock;
};
int __init_fifo(int fifo_size)
{
static struct node_t nodes[16];
int i;
static struct fifo_t fifo;
pthread_mutex_init(&fifo.lock , 0);
for(i = 0 ; i < 16 - 1 ; i++)
{
nodes[i].pcm[0]= i+6;
nodes[i].next = &nodes[i+1];
}
nodes[i].next = 0;
fifo.head = &nodes[0];
fifo.head = &nodes[16 - 1];
}
int traverse(struct fifo_t * pfifo)
{
struct node_t * p = 0;
p = pfifo->head;
while(p != 0)
{
printf("p->pcm[0] : %x , head : %p, tail : %p \\n",p->pcm[0] , pfifo->head , pfifo->tail);
p = p->next;
}
}
int in_fifo(struct fifo_t * pfifo , struct node_t * pnode)
{
struct node_t * p ;
if(pfifo == 0 || pnode == 0)
return -1;
pthread_mutex_lock(&pfifo->lock);
p = pfifo->tail;
if(p == 0)
pfifo->head = pfifo->tail = pnode;
else
{
p->next = pnode;
pfifo->tail = pnode;
}
pnode->next = 0;
pthread_mutex_unlock(&pfifo->lock);
return 0;
}
struct node_t * out_fifo(struct fifo_t * pfifo)
{
struct node_t * p ;
if(pfifo == 0)
return 0;
pthread_mutex_lock(&pfifo->lock);
p = pfifo->head;
if(p == 0)
{
pthread_mutex_unlock(&pfifo->lock);
return 0;
}
else
pfifo->head = p->next;
pthread_mutex_unlock(&pfifo->lock);
return p;
}
struct node_t * must_out(struct fifo_t * pfifo_mem , struct fifo_t * pfifo_data)
{
struct node_t * p ;
p = out_fifo(pfifo_mem);
if(p == 0)
p = out_fifo(pfifo_data);
return p;
}
int main()
{
struct fifo_t * pfifo;
struct node_t * p;
struct node_t * a[3];
int i = 0;
int ret;
do{ static struct node_t nodes[3]; static struct fifo_t fifo; int i; pthread_mutex_init(&fifo.lock , 0); for(i = 0 ; i < 3 - 1 ; i++) { nodes[i].next = &nodes[i+1]; } nodes[i].next = 0; fifo.head = &nodes[0]; fifo.tail = &nodes[3 - 1]; *&pfifo = &fifo;}while(0);
while(1)
{
printf("----------------\\n");
traverse(pfifo);
a[i] = out_fifo(pfifo);
if(0 == a[i])
break;
i++;
}
for(i = 2 ; 0 <= i ; i--)
{
printf("+++++++++++++++++++\\n");
ret = in_fifo(pfifo,a[i]);
traverse(pfifo);
}
while((p = out_fifo(pfifo)) != 0)
printf("p->buf[0] : %x\\n",p->pcm[0]);
return 0;
}
| 0
|
#include <pthread.h>
int aa(int b)
{
if(b < 40)
printf("aaaaaaaaaaaaa00000\\n");
else
printf("aaaaaaaaaaaa111111\\n");
}
void *hi(void *ptr)
{
int a = *(int *)ptr;
int b;
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&mutex1);
if(b > 100)
if(a > 20)
printf("int hi00000\\n");
else
printf("int hi111111\\n");
else
aa(a);
pthread_mutex_unlock(&mutex1);
}
int main(int argc, char **argv) {
int c ;
int d;
kain();
klee_make_symbolic(&c, sizeof(c), "inputccccccc");
pthread_t thread1;
pthread_create(&thread1,0,hi,(void *)&c);
if(d > 100)
if(c > 0)
printf("c main hi\\n");
else
printf("c main cry\\n");
pthread_join(thread1, 0);
}
| 1
|
#include <pthread.h>
static int tc_gc_sleep;
static pthread_mutex_t gc_mutex;
static pthread_cond_t gc_cond;
static pthread_t gc_thread;
int tc_gc_init(int gc_sleep)
{
if ((tc_gc_sleep = gc_sleep) <= 0) {
debug("init_tc_gc: gc_sleep must be above 0 seconds");
return 0;
}
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
if (gc_sleep < 0) {
debug("init_tc_gc: gc_sleep must be above zero");
return 0;
}
if (pthread_mutex_init(&gc_mutex, 0) != 0) {
debug("init_tc_gc: can't init mutex gc_mutex");
return 0;
}
if (pthread_cond_init(&gc_cond, 0) != 0) {
debug("init_tc_gc: can't init condition gc_cond");
return 0;
}
if (pthread_create(&gc_thread, 0, (void *)tc_gc, 0) != 0) {
debug("init_tc_gc: failed to create gc thread");
return 0;
}
return 1;
}
int tc_gc_destroy(void)
{
debug("tc_gc_destroy: killing gc");
if (pthread_cancel(gc_thread) != 0) {
error("tc_gc_destroy: failed to cancel gc_thread");
return 0;
}
debug("tc_gc_destroy: joining gc thread");
if (pthread_join(gc_thread, 0) != 0) {
error("tc_gc_destroy: failed to join gc thread");
return 0;
}
else
debug("tc_gc_destroy: gc thread joined");
return 1;
}
int tc_gc_wake_up(void)
{
debug("STARVING MARVIN!!!");
if (pthread_mutex_lock(&gc_mutex) != 0)
return 0;
if (pthread_cond_signal(&gc_cond) != 0)
return 0;
pthread_mutex_unlock(&gc_mutex);
return 1;
}
void tc_gc(void *data)
{
struct timespec ts;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
while (1) {
if (pthread_mutex_lock(&gc_mutex) != 0)
continue;
pthread_cond_timedwait(&gc_cond, &gc_mutex, future_time(&ts, tc_gc_sleep));
debug("tc_gc: ENTER THE COLLECTOR!!");
metadata_free_unused_tc_dir();
pthread_mutex_unlock(&gc_mutex);
pthread_testcancel();
}
debug("gc loop exited");
}
| 0
|
#include <pthread.h>
int hybrid_lock_init(struct hybrid_lock *lock)
{
lock->g_count = 0;
if(pthread_mutex_init(&lock->mLock, 0)!=0){
printf("init error\\n");
return -1;
}
return 0;
}
int hybrid_lock_destroy(struct hybrid_lock *lock)
{
if(pthread_mutex_destroy(&lock->mLock)!=0){
printf("destroy error\\n");
return -1;
}
return 0;
}
int hybrid_lock_lock(struct hybrid_lock *lock)
{
printf("lock\\n");
struct timeval start2, end2;
gettimeofday(&start2,0);
gettimeofday(&end2, 0);
while(!(end2.tv_usec > start2.tv_usec && start2.tv_sec < end2.tv_sec)){
if(pthread_mutex_trylock(&lock-> mLock) == 0){
pthread_mutex_unlock(&lock-> mLock);
usleep(100);
if(pthread_mutex_trylock(&lock-> mLock) == 0){
return 0;
}
}
gettimeofday(&end2,0);
}
printf("%ld:%ld\\n",end2.tv_sec - start2.tv_sec, end2.tv_usec - start2.tv_usec);
pthread_mutex_lock(&lock->mLock);
return 0;
}
int hybrid_lock_unlock(struct hybrid_lock *lock)
{
if(pthread_mutex_unlock(&lock->mLock)!=0){
printf("unlock error\\n");
return -1;
}
return 0;
}
| 1
|
#include <pthread.h>
enum Colour
{
blue = 0,
red = 1,
yellow = 2,
Invalid = 3
};
const char* ColourName[] = {"blue", "red", "yellow"};
const int STACK_SIZE = 32*1024;
const BOOL TRUE = 1;
const BOOL FALSE = 0;
int CreatureID = 0;
enum Colour doCompliment(enum Colour c1, enum Colour c2)
{
switch (c1)
{
case blue:
switch (c2)
{
case blue:
return blue;
case red:
return yellow;
case yellow:
return red;
default:
goto errlb;
}
case red:
switch (c2)
{
case blue:
return yellow;
case red:
return red;
case yellow:
return blue;
default:
goto errlb;
}
case yellow:
switch (c2)
{
case blue:
return red;
case red:
return blue;
case yellow:
return yellow;
default:
goto errlb;
}
default:
break;
}
errlb:
printf("Invalid colour\\n");
exit( 1 );
}
char* formatNumber(int n, char* outbuf)
{
int ochar = 0, ichar = 0;
int i;
char tmp[64];
const char* NUMBERS[] =
{
"zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine"
};
ichar = sprintf(tmp, "%d", n);
for (i = 0; i < ichar; i++)
ochar += sprintf( outbuf + ochar, " %s", NUMBERS[ tmp[i] - '0' ] );
return outbuf;
}
struct MeetingPlace
{
pthread_mutex_t mutex;
int meetingsLeft;
struct Creature* firstCreature;
};
struct Creature
{
pthread_t ht;
pthread_attr_t stack_att;
struct MeetingPlace* place;
int count;
int sameCount;
enum Colour colour;
int id;
BOOL two_met;
BOOL sameid;
};
void MeetingPlace_Init(struct MeetingPlace* m, int meetings )
{
pthread_mutex_init( &m->mutex, 0 );
m->meetingsLeft = meetings;
m->firstCreature = 0;
}
BOOL Meet( struct Creature* cr)
{
BOOL retval = TRUE;
struct MeetingPlace* mp = cr->place;
pthread_mutex_lock( &(mp->mutex) );
if ( mp->meetingsLeft > 0 )
{
if ( mp->firstCreature == 0 )
{
cr->two_met = FALSE;
mp->firstCreature = cr;
}
else
{
struct Creature* first;
enum Colour newColour;
first = mp->firstCreature;
newColour = doCompliment( cr->colour, first->colour );
cr->sameid = cr->id == first->id;
cr->colour = newColour;
cr->two_met = TRUE;
first->sameid = cr->sameid;
first->colour = newColour;
first->two_met = TRUE;
mp->firstCreature = 0;
mp->meetingsLeft--;
}
}
else
retval = FALSE;
pthread_mutex_unlock( &(mp->mutex) );
return retval;
}
void* CreatureThreadRun(void* param)
{
struct Creature* cr = (struct Creature*)param;
while (TRUE)
{
if ( Meet(cr) )
{
while (cr->two_met == FALSE)
sched_yield();
if (cr->sameid)
cr->sameCount++;
cr->count++;
}
else
break;
}
return 0;
}
void Creature_Init( struct Creature *cr, struct MeetingPlace* place, enum Colour colour )
{
cr->place = place;
cr->count = cr->sameCount = 0;
cr->id = ++CreatureID;
cr->colour = colour;
cr->two_met = FALSE;
pthread_attr_init( &cr->stack_att );
pthread_attr_setstacksize( &cr->stack_att, STACK_SIZE );
pthread_create( &cr->ht, &cr->stack_att, &CreatureThreadRun, (void*)(cr) );
}
char* Creature_getResult(struct Creature* cr, char* str)
{
char numstr[256];
formatNumber(cr->sameCount, numstr);
sprintf( str, "%u%s", cr->count, numstr );
return str;
}
void runGame( int n_meeting, int ncolor, const enum Colour* colours )
{
int i;
int total = 0;
char str[256];
struct MeetingPlace place;
struct Creature *creatures = (struct Creature*) calloc( ncolor, sizeof(struct Creature) );
MeetingPlace_Init( &place, n_meeting );
for (i = 0; i < ncolor; i++)
{
printf( "%s ", ColourName[ colours[i] ] );
Creature_Init( &(creatures[i]), &place, colours[i] );
}
printf("\\n");
for (i = 0; i < ncolor; i++)
pthread_join( creatures[i].ht, 0 );
for (i = 0; i < ncolor; i++)
{
printf( "%s\\n", Creature_getResult(&(creatures[i]), str) );
total += creatures[i].count;
}
printf( "%s\\n\\n", formatNumber(total, str) );
pthread_mutex_destroy( &place.mutex );
free( creatures );
}
void printColours( enum Colour c1, enum Colour c2 )
{
printf( "%s + %s -> %s\\n",
ColourName[c1],
ColourName[c2],
ColourName[doCompliment(c1, c2)] );
}
void printColoursTable(void)
{
printColours(blue, blue);
printColours(blue, red);
printColours(blue, yellow);
printColours(red, blue);
printColours(red, red);
printColours(red, yellow);
printColours(yellow, blue);
printColours(yellow, red);
printColours(yellow, yellow);
}
int main(int argc, char** argv)
{
int n = (argc == 2) ? atoi(argv[1]) : 600;
printColoursTable();
printf("\\n");
const enum Colour r1[] = { blue, red, yellow };
const enum Colour r2[] = { blue, red, yellow,
red, yellow, blue,
red, yellow, red, blue };
runGame( n, sizeof(r1) / sizeof(r1[0]), r1 );
runGame( n, sizeof(r2) / sizeof(r2[0]), r2 );
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *thread1(void *);
void *thread2(void *);
int i=1;
int main(void)
{
pthread_t t_a;
pthread_t t_b;
pthread_create(&t_a,0,thread1,(void *)0);
pthread_create(&t_b,0,thread2,(void *)0);
pthread_join(t_a, 0);
pthread_join(t_b, 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
exit(0);
}
void *thread1(void *junk)
{
for(i=1;i<=6;i++)
{
pthread_mutex_lock(&mutex);
printf("thread1: lock %d\\n", 27);
if(i%3==0){
printf("thread1:signal 1 %d\\n", 29);
pthread_cond_signal(&cond);
printf("thread1:signal 2 %d\\n", 31);
sleep(1);
}
pthread_mutex_unlock(&mutex);
printf("thread1: unlock %d\\n\\n", 35);
sleep(1);
}
}
void *thread2(void *junk)
{
while(i<6)
{
pthread_mutex_lock(&mutex);
printf("thread2: lock %d\\n", 44);
if(i%3!=0){
printf("thread2: wait 1 %d\\n", 46);
pthread_cond_wait(&cond,&mutex);
printf("thread2: wait 2 %d\\n", 48);
}
pthread_mutex_unlock(&mutex);
printf("thread2: unlock %d\\n\\n", 51);
sleep(1);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t* mutex;
int pid;
char birth[25];
char clientString[10];
int elapsed_sec;
double elapsed_msec;
} stats_t;
void exit_handler(int sig) {
pthread_mutex_lock(mutex);
pthread_mutex_unlock(mutex);
exit(0);
}
int main(int argc, char *argv[]) {
char SHM_NAME[18] = "reichhoff_steffan";
char *clientString = argv[1];
int fd = shm_open(SHM_NAME, O_RDWR);
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = exit_handler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, 0);
sigaction(SIGTERM, &sigIntHandler, 0);
if( fd == -1) {
exit(1);
}
pthread_mutex_lock(mutex);
pthread_mutex_unlock(mutex);
while (1) {
sleep(1);
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_t ntid;
struct foo {
int f_count;
pthread_mutex_t f_clock;
int m_m;
};
struct foo*
foo_alloc(void)
{
struct foo *fp;
if ((fp=malloc(sizeof(struct foo)))!=0) {
fp->f_count=1;
fp->m_m=5;
if (pthread_mutex_init(&fp->f_clock, 0)!=0) {
free(fp);
return (0);
}
}
return fp;
}
void
foo_hold(struct foo *fp)
{
pthread_mutex_lock(&fp->f_clock);
fp->f_count++;
fp->m_m++;
pthread_mutex_unlock(&fp->f_clock);
}
void
foo_rele(struct foo *fp)
{
pthread_mutex_lock(&fp->f_clock);
fp->m_m--;
if (--fp->f_count == 0)
{
pthread_mutex_unlock(&fp->f_clock);
pthread_mutex_destroy(&fp->f_clock);
free(fp);
} else {
pthread_mutex_unlock(&fp->f_clock);
}
}
void Print(struct foo *fp)
{
printf(" fp->f_count = %d; m_m = %d\\n", fp->f_count,fp->m_m);
}
void *
thr1_fn(void *arg)
{
struct foo *ftemp=(struct foo *)arg;
while (ftemp && (ftemp->f_count)<10) {
foo_hold(ftemp);
pthread_t tid;
tid=pthread_self();
printf("thread1: %u : ",(unsigned int)tid);
Print(ftemp);
sleep(1);}
return ((void *)0);
}
void *
thr2_fn(void *arg)
{
struct foo *ftemp=(struct foo*)arg;
while(ftemp ) {
foo_rele(ftemp);
pthread_t tid;
tid=pthread_self();
printf("thread2: %u : ", (unsigned int)tid);
Print(ftemp);
sleep(2);}
return ((void*)0);
}
int main(void)
{
int err;
struct foo *sfm;
sfm=foo_alloc();
Print(sfm);
err = pthread_create(&ntid,0,thr1_fn,(void*)sfm);
if (err!=0)
err_quit("can't create thread: %s\\n",strerror(err));
err = pthread_create(&ntid, 0, thr2_fn, (void*)sfm);
if (err!=0)
err_quit("can't create thread: %s\\n", strerror(err));
sleep(20);
exit(0);
}
| 1
|
#include <pthread.h>
int id;
char *name;
int n_execs;
} thread_info_t;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *thread_hello(void *thread_info) {
thread_info_t *thread_info_p = (thread_info_t *) thread_info;
int i = 0;
pthread_mutex_lock(&mutex);
for(i = 0; i < thread_info_p->n_execs; i++) {
printf("\\nThread info:\\n");
printf("id: %d\\n", thread_info_p->id);
printf("name: %s\\n", thread_info_p->name);
printf("system id: %d", (int)pthread_self());
}
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main() {
pthread_t threads[2];
thread_info_t threads_info[2] = {
{1, "First Thread", 1},
{2, "Second Thread", 2}
};
int i = 0;
for(i = 0; i < 2; i++) {
pthread_create(&threads[i], 0, thread_hello, (void *)&threads_info[i]);
}
for(i = 0; i < 2; i++) {
pthread_join(threads[i], 0);
}
}
| 0
|
#include <pthread.h>
static int fb_index = 0;
static struct frame_buf *fbarray[FRAME_BUF_NUM];
static struct frame_buf fbpool[FRAME_BUF_NUM];
static pthread_mutex_t g_fb_mtx = PTHREAD_MUTEX_INITIALIZER;
void
VPU_framebuf_init()
{
int i;
for (i = 0; i < FRAME_BUF_NUM; i++)
{
fbarray[i] = &fbpool[i];
}
}
static struct frame_buf *
get_framebuf()
{
struct frame_buf *fb;
pthread_mutex_lock(&g_fb_mtx);
fb = fbarray[fb_index];
fbarray[fb_index] = 0;
++fb_index;
fb_index &= (FRAME_BUF_NUM - 1);
pthread_mutex_unlock(&g_fb_mtx);
return fb;
}
static void
put_framebuf(struct frame_buf *fb)
{
pthread_mutex_lock(&g_fb_mtx);
--fb_index;
fb_index &= (FRAME_BUF_NUM - 1);
fbarray[fb_index] = fb;
pthread_mutex_unlock(&g_fb_mtx);
}
struct frame_buf *
vpu_framebuf_alloc(int strideY, int height)
{
struct frame_buf *fb;
int size;
fb = get_framebuf();
if (fb == 0)
return 0;
size = strideY * height;
memset(&(fb->desc), 0, sizeof(vpu_mem_desc));
fb->desc.size = (size * 3 / 2);
if (IOGetPhyMem(&fb->desc))
{
DBG("--- Frame buffer allocation failed ---\\n");
memset(&(fb->desc), 0, sizeof(vpu_mem_desc));
return 0;
}
fb->addrY = fb->desc.phy_addr;
fb->addrCb = fb->addrY + size;
fb->addrCr = fb->addrCb + (size>>2);
fb->desc.virt_uaddr = IOGetVirtMem(&(fb->desc));
if (fb->desc.virt_uaddr <= 0)
{
IOFreePhyMem(&fb->desc);
memset(&(fb->desc), 0, sizeof(vpu_mem_desc));
return 0;
}
return fb;
}
void
vpu_framebuf_free(struct frame_buf *fb)
{
if (fb->desc.virt_uaddr)
{
IOFreeVirtMem(&fb->desc);
}
if (fb->desc.phy_addr)
{
IOFreePhyMem(&fb->desc);
}
memset(&(fb->desc), 0, sizeof(vpu_mem_desc));
put_framebuf(fb);
}
| 1
|
#include <pthread.h>
int _mosquitto_packet_handle(struct mosquitto *mosq)
{
assert(mosq);
switch((mosq->in_packet.command)&0xF0){
case PINGREQ:
return _mosquitto_handle_pingreq(mosq);
case PINGRESP:
return _mosquitto_handle_pingresp(mosq);
case PUBACK:
return _mosquitto_handle_pubackcomp(mosq, "PUBACK");
case PUBCOMP:
return _mosquitto_handle_pubackcomp(mosq, "PUBCOMP");
case PUBLISH:
return _mosquitto_handle_publish(mosq);
case PUBREC:
return _mosquitto_handle_pubrec(mosq);
case PUBREL:
return _mosquitto_handle_pubrel(0, mosq);
case CONNACK:
return _mosquitto_handle_connack(mosq);
case SUBACK:
return _mosquitto_handle_suback(mosq);
case UNSUBACK:
return _mosquitto_handle_unsuback(mosq);
default:
_mosquitto_log_printf(mosq, MOSQ_LOG_ERR, "Error: Unrecognised command %d\\n", (mosq->in_packet.command)&0xF0);
return MOSQ_ERR_PROTOCOL;
}
}
int _mosquitto_handle_publish(struct mosquitto *mosq)
{
uint8_t header;
struct mosquitto_message_all *message;
int rc = 0;
uint16_t mid;
assert(mosq);
message = _mosquitto_calloc(1, sizeof(struct mosquitto_message_all));
if(!message) return MOSQ_ERR_NOMEM;
header = mosq->in_packet.command;
message->dup = (header & 0x08)>>3;
message->msg.qos = (header & 0x06)>>1;
message->msg.retain = (header & 0x01);
rc = _mosquitto_read_string(&mosq->in_packet, &message->msg.topic);
if(rc){
_mosquitto_message_cleanup(&message);
return rc;
}
if(!strlen(message->msg.topic)){
_mosquitto_message_cleanup(&message);
return MOSQ_ERR_PROTOCOL;
}
if(message->msg.qos > 0){
rc = _mosquitto_read_uint16(&mosq->in_packet, &mid);
if(rc){
_mosquitto_message_cleanup(&message);
return rc;
}
message->msg.mid = (int)mid;
}
message->msg.payloadlen = mosq->in_packet.remaining_length - mosq->in_packet.pos;
if(message->msg.payloadlen){
message->msg.payload = _mosquitto_calloc(message->msg.payloadlen+1, sizeof(uint8_t));
if(!message->msg.payload){
_mosquitto_message_cleanup(&message);
return MOSQ_ERR_NOMEM;
}
rc = _mosquitto_read_bytes(&mosq->in_packet, message->msg.payload, message->msg.payloadlen);
if(rc){
_mosquitto_message_cleanup(&message);
return rc;
}
}
_mosquitto_log_printf(mosq, MOSQ_LOG_DEBUG,
"Client %s received PUBLISH (d%d, q%d, r%d, m%d, '%s', ... (%ld bytes))",
mosq->id, message->dup, message->msg.qos, message->msg.retain,
message->msg.mid, message->msg.topic,
(long)message->msg.payloadlen);
message->timestamp = mosquitto_time();
switch(message->msg.qos){
case 0:
pthread_mutex_lock(&mosq->callback_mutex);
if(mosq->on_message){
mosq->in_callback = 1;
mosq->on_message(mosq, mosq->userdata, &message->msg);
mosq->in_callback = 0;
}
pthread_mutex_unlock(&mosq->callback_mutex);
_mosquitto_message_cleanup(&message);
return MOSQ_ERR_SUCCESS;
case 1:
rc = _mosquitto_send_puback(mosq, message->msg.mid);
pthread_mutex_lock(&mosq->callback_mutex);
if(mosq->on_message){
mosq->in_callback = 1;
mosq->on_message(mosq, mosq->userdata, &message->msg);
mosq->in_callback = 0;
}
pthread_mutex_unlock(&mosq->callback_mutex);
_mosquitto_message_cleanup(&message);
return rc;
case 2:
rc = _mosquitto_send_pubrec(mosq, message->msg.mid);
pthread_mutex_lock(&mosq->in_message_mutex);
message->state = mosq_ms_wait_for_pubrel;
_mosquitto_message_queue(mosq, message, mosq_md_in);
pthread_mutex_unlock(&mosq->in_message_mutex);
return rc;
default:
_mosquitto_message_cleanup(&message);
return MOSQ_ERR_PROTOCOL;
}
}
| 0
|
#include <pthread.h>
volatile char running[MAX_CLIENTS];
volatile int sockets[MAX_CLIENTS];
pthread_t threads[MAX_CLIENTS];
pthread_mutex_t meta_lock = PTHREAD_MUTEX_INITIALIZER;
inline void startup_accounting( )
{
int i;
pthread_mutex_lock( &meta_lock );
for( i=0; i<MAX_CLIENTS; i++ )
running[i] = 0;
pthread_mutex_unlock( &meta_lock );
}
inline void write_client( const int sock, const char* msg )
{
if( write( sock, msg, strlen(msg)+1 ) <= 0 )
perror( "Failed to write to socket" );
}
inline void new_client( const int sock )
{
int i;
int packed[2];
pthread_mutex_lock( &meta_lock );
for( i=0; i<MAX_CLIENTS; i++ )
{
if( !running[i] )
break;
}
pthread_mutex_unlock( &meta_lock );
if( i == MAX_CLIENTS )
{
perror( "Ran out of client slots." );
pthread_exit( 0 );
exit( 3 );
}
packed[0] = i;
packed[1] = sock;
pthread_mutex_lock( &meta_lock );
sockets[i] = packed[1];
if( pthread_create( &threads[i], 0, handleClient, (void *)packed ) )
{
printf( "Thread creation failure.\\n" );
pthread_mutex_unlock( &meta_lock );
exit( 2 );
}
else
running[i] = 1;
pthread_mutex_unlock( &meta_lock );
}
inline void dispatch( const int source, const char* msg )
{
int i;
pthread_mutex_lock( &meta_lock );
for( i=0; i<MAX_CLIENTS; i++ )
{
if( running[i] && i != source )
{
printf( "Writing \\"%s\\" to %i's socket (%i)\\n", msg, i, sockets[i] );
write_client( sockets[i], msg );
}
}
pthread_mutex_unlock( &meta_lock );
}
inline void client_quit( const int clientNum )
{
pthread_mutex_lock( &meta_lock );
running[clientNum] = 0;
pthread_mutex_unlock( &meta_lock );
}
void signalhandler( const int sig )
{
printf( "\\nExiting in 10 seconds\\n" );
dispatch( -1, "SHUTDOWN: The server will shutdown in 10 seconds!" );
pthread_mutex_lock( &meta_lock );
sleep( 10 );
for( int i=0; i<MAX_CLIENTS; i++ )
{
if( running[i] )
{
pthread_mutex_unlock( &meta_lock );
client_quit( i );
pthread_mutex_lock( &meta_lock );
write_client( sockets[i], "/disconnected" );
pthread_cancel( threads[i] );
}
}
pthread_mutex_unlock( &meta_lock );
closeSocket( );
exit(0);
}
| 1
|
#include <pthread.h>
long animals;
long food;
long hunters;
long cooks;
pthread_mutex_t anim_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t food_mutex = PTHREAD_MUTEX_INITIALIZER;
int throw()
{
return (rand() % 6 + 1);
}
int change_food_state(int action)
{
int res = 0;
pthread_mutex_lock(&food_mutex);
if (action == -1) printf("Osadnik idzie cos zjesc ^^ (zostalo tylko %ld porcji!)\\n", food);
food+=action;
if (food < 0)
{
res = 1;
food = 0;
}
pthread_mutex_unlock(&food_mutex);
return res;
}
void change_anim_state(int action)
{
pthread_mutex_lock(&anim_mutex);
if (action)
{
animals++;
printf("Mysliwy upolowal jakies?? zwierze\\n");
}
else
{
if (animals > 0)
{
int temp = throw();
change_food_state(temp);
animals--;
printf("Ktos wlasnie gotuje... %d jedzonka, zostalo %ld zwierzyny\\n", temp, animals);
}
}
pthread_mutex_unlock(&anim_mutex);
}
void hunt()
{
if (throw() > throw()) change_anim_state(1);
}
void* hunter_day( void *arg )
{
int i;
for (i=0; i < 365; i++)
{
hunt();
if (change_food_state(-1))
{
hunters--;
printf("Mysliwy opuscil osade %d dnia\\n", i);
i = 365;
break;
}
usleep(10000);
}
pthread_exit(0);
}
void* cook_day( void *arg )
{
int i;
for (i=0; i < 365; i++)
{
change_anim_state(0);
if (change_food_state(-1))
{
cooks--;
printf("Kucharz opuscil osade %d dnia\\n", i);
i = 365;
break;
}
usleep(10000);
}
pthread_exit(0);
}
int main(int argc, char** argv)
{
srand(time(0));
hunters = strtol(argv[1], 0, 10);
cooks = strtol(argv[2], 0, 10);
animals = strtol(argv[3], 0, 10);
food = strtol(argv[4], 0, 10);
long temp_hunters = hunters;
long temp_cooks = cooks;
printf("l. mysliwych: %ld\\n", hunters);
printf("l. kucharzy: %ld\\n\\n", cooks);
pthread_t hunt_threads[hunters];
pthread_t cook_threads[cooks];
int i;
for (i=0; i < temp_hunters; i++)
if (pthread_create (&hunt_threads[i], 0, hunter_day, 0) )
{
printf("Blad przy tworeniu hunt_thread%d\\n", i);
return 1;
}
for (i=0; i < temp_cooks; i++)
if (pthread_create (&cook_threads[i], 0, cook_day, 0) )
{
printf("Blad przy tworeniu cook_thread%d\\n", i);
return 1;
}
for (i=0; i < temp_hunters; i++)
if (pthread_join (hunt_threads[i], 0) )
{
printf("Blad przy konczeniu hunt_thread%d\\n", i);
return 1;
}
for (i=0; i < temp_cooks; i++)
if (pthread_join (cook_threads[i], 0) )
{
printf("Blad przy konczeniu cook_thread%d\\n", i);
return 1;
}
printf("\\nMinal rok, a w wiosce pozostalo %ld kucharzy oraz %ld mysliwych\\n", cooks, hunters);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
struct my_semaphore {
pthread_mutex_t m;
int count;
};
struct my_semaphore sema;
void my_semaphore_init(struct my_semaphore *s, int count) {
pthread_mutex_init(&(s->m), 0);
pthread_mutex_lock(&(s->m));
s->count = count;
}
void my_down(struct my_semaphore *s) {
pthread_mutex_lock(&mutex);
--s->count;
pthread_mutex_unlock(&mutex);
if (s->count < 0) pthread_mutex_lock(&(s->m));
}
void my_up(struct my_semaphore *s) {
pthread_mutex_lock(&mutex);
if (s->count < 0) pthread_mutex_unlock(&(s->m));
++s->count;
pthread_mutex_unlock(&mutex);
}
handler_t *Signal(int signum, handler_t *handler) {
struct sigaction action, old_action;
action.sa_handler = handler;
sigemptyset(&action.sa_mask);
action.sa_flags = SA_RESTART;
if (sigaction(signum, &action, &old_action) < 0)
printf("Signal: error.\\n");
return (old_action.sa_handler);
}
void sigtstp_handler(int sig) {
my_up(&sema);
}
void *thread(void *arg) {
my_down(&sema);
printf("I'm requesting a count.\\n");
return 0;
}
int main() {
Signal(SIGTSTP, sigtstp_handler);
pthread_mutex_init(&mutex, 0);
my_semaphore_init(&sema, 1);
my_up(&sema);
my_down(&sema);
printf("This point can be reached.\\n");
my_down(&sema);
printf("This point can be reached.\\n");
my_down(&sema);
printf("This point can not be reached until I press ctrl-z!\\n");
printf("Now here is multithread test.\\n");
pthread_t tids[2];
pthread_create(&tids[0], 0, &thread, 0);
pthread_create(&tids[1], 0, &thread, 0);
pthread_join(tids[0], 0);
pthread_join(tids[1], 0);
}
| 1
|
#include <pthread.h>
{
int buf[5];
int in;
int out;
sem_t full;
sem_t empty;
pthread_mutex_t mutex;
} sbuf_t;
sbuf_t shared;
void *Producer(void *arg)
{
int i, item, index;
index = (int)arg;
for (i=0; i < 4; i++)
{
item = i;
sem_wait(&shared.empty);
pthread_mutex_lock(&shared.mutex);
shared.buf[shared.in] = item;
shared.in = (shared.in+1)%5;
printf("[P%d] Producing %d ...\\n", index, item);
fflush(stdout);
pthread_mutex_unlock(&shared.mutex);
sem_post(&shared.full);
if (i % 2 == 1) sleep(1);
}
return 0;
}
void *Consumer(void *arg)
{
int i, item, index;
index = (int)arg;
for (i=4; i > 0; i--) {
sem_wait(&shared.full);
pthread_mutex_lock(&shared.mutex);
item=i;
item=shared.buf[shared.out];
shared.out = (shared.out+1)%5;
printf("[C%d] Consuming %d ...\\n", index, item);
fflush(stdout);
pthread_mutex_unlock(&shared.mutex);
sem_post(&shared.empty);
if (i % 2 == 1) sleep(1);
}
return 0;
}
int main()
{
pthread_t idP, idC;
int index;
sem_init(&shared.full, 0, 0);
sem_init(&shared.empty, 0, 5);
pthread_mutex_init(&shared.mutex, 0);
for (index = 0; index < 3; index++)
{
pthread_create(&idP, 0, Producer, (void*)index);
}
for(index=0; index<3; index++)
{
pthread_create(&idC, 0, Consumer, (void*)index);
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
struct node{
int number;
struct node *next;
}*head=0;
void cleanup(void *arg){
printf("Cleanup handler of consumer thread\\n");
free(arg);
pthread_mutex_unlock(&mutex);
}
void *func(void *arg){
struct node *p=0;
pthread_cleanup_push(cleanup,p);
pthread_mutex_lock(&mutex);
while(1){
while(head==0){
printf("-->wait-unlock to product\\n");
pthread_cond_wait(&cond,&mutex);
printf("-->wait-lock to consume\\n");
}
sleep(2);
p=head;
head=head->next;
printf("-->Got %d from front of queue\\n",p->number);
free(p);
}
pthread_mutex_unlock(&mutex);
pthread_cleanup_pop(0);
}
int main(){
pthread_t pthid;
int i;
struct node *p;
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond,0);
pthread_create(&pthid,0,func,0);
sleep(1);
for(i=1;i<10;++i){
p=(struct node*)malloc(sizeof(struct node));
p->number=i;
printf("product:%d\\n",p->number);
pthread_mutex_lock(&mutex);
p->next=head;
head=p;
pthread_cond_signal(&cond);
sleep(2);
printf("unlock before signal to wait-lock\\n");
sleep(2);
pthread_mutex_unlock(&mutex);
sleep(1);
}
while(head!=0);
sleep(2);
printf("Oh,NO!\\nproducer(main thread) wanna kill the consumer.\\n");
pthread_cancel(pthid);
pthread_join(pthid,0);
printf("All done.\\n");
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
short value;
char* stuff;
}SharedInt;
sem_t sem;
SharedInt* sip;
void *functionWithCriticalSection(short v) {
pthread_mutex_lock(&(sip->lock));
printf("Crit %i executed by %u.\\n", 1, getpid());
sip->value = sip->value + v;
pthread_mutex_unlock(&(sip->lock));
sem_post(&sem);
}
void *function2WithCriticalSection(int* v2) {
int pul = 1337;
char* ollon = 0;
short v3 = *v2;
pthread_mutex_lock(&(sip->lock));
printf("Crit %i executed by %u.\\n", 2, getpid());
for (int i = 0; i < v3; i++) {
strcat(sip->stuff, " ");
}
pthread_mutex_unlock(&(sip->lock));
sem_post(&sem);
}
int main() {
int limit = 16;
sem_init(&sem, 0, 0);
SharedInt si;
si.stuff = malloc(80000*sizeof(char));
sip = &si;
sip->value = 0;
int v2 = 1;
pthread_mutex_init(&(sip->lock), 0);
for(int i = 0; i < limit; i++) {
pthread_t thread1;
pthread_t thread2;
pthread_create (&thread1,0,functionWithCriticalSection,v2);
pthread_create (&thread2,0,function2WithCriticalSection,&v2);
}
for(int i = 0; i < 2*limit; i++) {
sem_wait(&sem);
}
pthread_mutex_destroy(&(sip->lock));
sem_destroy(&sem);
int stringlength = strlen(si.stuff);
free(si.stuff);
printf("%d\\n", sip->value-stringlength);
return sip->value-stringlength;
}
| 0
|
#include <pthread.h>
static void dump_memory(const void * loc, size_t size);
static void dump_transaction(unsigned long buffer, unsigned long offset, unsigned long write_size);
static int initialized = 0;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static int (*old_ioctl)(int, unsigned long, void*);
static void init()
{
if (__sync_bool_compare_and_swap(&initialized, 0, 1)) {
old_ioctl = dlsym(RTLD_NEXT, "ioctl");
}
}
int ioctl(int fd, unsigned long request, void * arg)
{
init();
while (!initialized);
int ret = 0;
struct binder_write_read * p_bwr = (struct binder_write_read *)arg;
if (request != BINDER_WRITE_READ)
goto out;
pthread_mutex_lock(&mutex);
printf("=== tid=%d bwr.write_size = %ld, bwr.write_consumed = %ld ===\\n",
gettid(), p_bwr->write_size, p_bwr->write_consumed);
if (p_bwr->write_size)
dump_memory((const unsigned char *)p_bwr->write_buffer, p_bwr->write_size);
printf ("====\\n");
dump_transaction(p_bwr->write_buffer, p_bwr->write_consumed, p_bwr->write_size);
pthread_mutex_unlock(&mutex);
out:
ret = old_ioctl(fd, request, arg);
pthread_mutex_lock(&mutex);
if (request == BINDER_WRITE_READ) {
printf ("tid=%d === bwr.read_consumed=%lx === \\n", gettid(), p_bwr->read_consumed);
dump_memory((const unsigned char *)p_bwr->read_buffer, p_bwr->read_consumed);
dump_transaction(p_bwr->read_buffer, 0, p_bwr->read_consumed);
printf ("====\\n");
}
pthread_mutex_unlock(&mutex);
return ret;
}
static void dump_memory(const void * loc, size_t size)
{
size_t i;
for (i = 1; i <= (size + 3) / 4; ++i) {
printf("%08x ", ((const unsigned int*)loc)[i - 1]);
if (i % 4 == 0)
printf("\\n");
}
printf("\\n");
}
static void dump_transaction(unsigned long buffer, unsigned long offset, unsigned long size)
{
unsigned int * p_cmd;
for (p_cmd = (unsigned int *)(buffer + offset); p_cmd < (unsigned int *)(buffer + size); ++p_cmd) {
if (*p_cmd != BC_TRANSACTION && *p_cmd != BR_REPLY)
continue;
struct binder_transaction_data * tr = (struct binder_transaction_data*)(p_cmd + 1);
printf("== tr->data->buffer, size = %d == \\n", tr->data_size);
dump_memory(tr->data.ptr.buffer, tr->data_size);
printf("== tr->data->offset, size = %d == \\n", tr->offsets_size);
dump_memory(tr->data.ptr.offsets, tr->offsets_size);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t lck = PTHREAD_MUTEX_INITIALIZER;
void *threadFunc(void *id){
int num = *((int*)id);
pthread_mutex_lock(&lck);
printf("\\nThread %d has acquired the lock\\n",num);
for(int i=1; i<6; i++){
int random = (rand() %100);
printf("[%d]:%d\\n",num,random);
}
pthread_mutex_unlock(&lck);
}
int main(){
pthread_t tid[10];
srand((unsigned) time(0));
int thread_num[10 +1];
for ( int i=0; i<10; i++) {
thread_num[i] = i+1;
pthread_create(&tid[i], 0, threadFunc, &thread_num[i]);
}
for ( int i=0; i<10; i++) {
pthread_join(tid[i], 0);
}
exit(0);
}
| 0
|
#include <pthread.h>
struct protoent_data _protoent_data;
void
setprotoent(int f)
{
pthread_mutex_lock(&_protoent_mutex);
setprotoent_r(f, &_protoent_data);
pthread_mutex_unlock(&_protoent_mutex);
}
void
endprotoent(void)
{
pthread_mutex_lock(&_protoent_mutex);
endprotoent_r(&_protoent_data);
pthread_mutex_unlock(&_protoent_mutex);
}
struct protoent *
getprotoent(void)
{
struct protoent *p;
pthread_mutex_lock(&_protoent_mutex);
p = getprotoent_r(&_protoent_data.proto, &_protoent_data);
pthread_mutex_unlock(&_protoent_mutex);
return (p);
}
| 1
|
#include <pthread.h>
pthread_t t_sM;
struct sim_time_t rt_time;
int fd;
void* rtsock () {
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,0);
int fd = TCP_Server_init(9000,"127.0.0.1");
while (sim_stat != 0) {
int s = Socket_accept(fd);
while (1) {
char buf[2];
memset(&buf,'0',sizeof(buf));
int r;
usleep(50000);
r = Socket_recv(s,buf,1);
if (r == -1) {
close(s);
break;
}
if (buf[0] == 'M') {
char b[250];
memset(&b,'0',sizeof(b));
pthread_mutex_lock(&mutex);
int len = sizeof(model);
memcpy(&b,&model,sizeof(model));
pthread_mutex_unlock(&mutex);
r = Socket_send(s,b,len);
if (r == -1) {
close(s);
break;
}
memset(&b,'0',sizeof(b));
pthread_mutex_lock(&mutex);
len = sizeof(rt_time);
memcpy(&b,&rt_time,sizeof(rt_time));
pthread_mutex_unlock(&mutex);
r = Socket_send(s,b,len);
if (r == -1) {
close(s);
break;
}
}
}
}
close(fd);
return 0;
}
void* rtmain() {
int i=0;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,0);
pthread_create(&t_sM, 0, (void *(*)(void *))rtsock, 0);
while(sim_stat != 0 ) {
rt_disp_start();
usleep(100000);
rt_disp_wait();
pthread_mutex_lock(&mutex);
if (sim_stat == 0) {
break;
}
if (rt_takt++ >= 1000) {
rt_takt = 0;
}
for(i = 0; i < 8; i++) {
model.o_P[i] = pso.o_P[i];
}
time_tick(&rt_time);
pthread_mutex_unlock(&mutex);
}
close(fd);
pthread_cancel(t_sM);
return 0;
}
| 0
|
#include <pthread.h>
extern int idx, sink;
extern double dsink;
extern void *psink;
void bit_shift_main (void);
void dynamic_buffer_overrun_main (void);
void dynamic_buffer_underrun_main (void);
void cmp_funcadr_main (void);
void conflicting_cond_main (void);
void data_lost_main (void);
void data_overflow_main (void);
void data_underflow_main (void);
void dead_code_main (void);
void dead_lock_main (void);
void deletion_of_data_structure_sentinel_main (void);
void double_free_main (void);
void double_lock_main (void);
void double_release_main (void);
void endless_loop_main (void);
void free_nondynamic_allocated_memory_main (void);
void free_null_pointer_main (void);
void func_pointer_main (void);
void function_return_value_unchecked_main (void);
void improper_termination_of_block_main (void);
void insign_code_main (void);
void invalid_extern_main (void);
void invalid_memory_access_main (void);
void littlemem_st_main (void);
void livelock_main (void);
void lock_never_unlock_main (void);
void memory_allocation_failure_main(void);
void memory_leak_main (void);
void not_return_main (void);
void null_pointer_main (void);
void overrun_st_main (void);
void ow_memcpy_main (void);
void pow_related_errors_main (void);
void ptr_subtraction_main (void);
void race_condition_main (void);
void redundant_cond_main (void);
void return_local_main (void);
void sign_conv_main (void);
void sleep_lock_main (void);
void st_cross_thread_access_main (void);
void st_overflow_main (void);
void st_underrun_main (void);
void underrun_st_main (void);
void uninit_memory_access_main (void);
void uninit_pointer_main (void);
void uninit_var_main (void);
void unlock_without_lock_main (void);
void unused_var_main (void);
void wrong_arguments_func_pointer_main (void);
void zero_division_main (void);
pthread_mutex_t sleep_lock_001_glb_mutex_;
pthread_mutex_t *sleep_lock_001_glb_mutex = &sleep_lock_001_glb_mutex_;
void sleep_lock_001_glb_mutex_lock () {}
void sleep_lock_001_glb_mutex_unlock () {}
int sleep_lock_001_glb_data = 0;
void* sleep_lock_001_tsk_001 (void *pram)
{
pthread_mutex_lock(sleep_lock_001_glb_mutex);
sleep_lock_001_glb_data = (sleep_lock_001_glb_data % 100) + 1;
pthread_mutex_unlock(sleep_lock_001_glb_mutex);
return 0;
}
void sleep_lock_001 ()
{
pthread_t tid1;
pthread_mutex_init(sleep_lock_001_glb_mutex, 0);
pthread_create(&tid1, 0, sleep_lock_001_tsk_001, 0);
pthread_join(tid1, 0);
pthread_mutex_destroy(sleep_lock_001_glb_mutex);
}
int sleep_lock_002_glb_data = 0;
pthread_mutex_t sleep_lock_002_glb_mutex_;
pthread_mutex_t *sleep_lock_002_glb_mutex = &sleep_lock_002_glb_mutex_;
void* sleep_lock_002_tsk_001 (void *pram)
{
pthread_mutex_lock(sleep_lock_002_glb_mutex);
sleep_lock_002_glb_data = (sleep_lock_002_glb_data % 100) + 1;
pthread_mutex_unlock(sleep_lock_002_glb_mutex);
return 0;
}
void sleep_lock_002 ()
{
pthread_t tid1;
pthread_mutex_init(sleep_lock_002_glb_mutex, 0);
pthread_create(&tid1, 0, sleep_lock_002_tsk_001, 0);
pthread_join(tid1, 0);
pthread_mutex_destroy(sleep_lock_002_glb_mutex);
}
pthread_mutex_t sleep_lock_003_glb_mutex_;
pthread_mutex_t *sleep_lock_003_glb_mutex = &sleep_lock_003_glb_mutex_;
int sleep_lock_003_glb_data = 0;
void sleep_lock_003_func_001 ()
{
}
void* sleep_lock_003_tsk_001 (void *pram)
{
pthread_mutex_lock(sleep_lock_003_glb_mutex);
sleep_lock_003_glb_data = (sleep_lock_003_glb_data % 100) + 1;
sleep_lock_003_func_001();
pthread_mutex_unlock(sleep_lock_003_glb_mutex);
return 0;
}
void sleep_lock_003 ()
{
pthread_t tid1;
pthread_mutex_init(sleep_lock_003_glb_mutex, 0);
pthread_create(&tid1, 0, sleep_lock_003_tsk_001, 0);
pthread_join(tid1, 0);
pthread_mutex_destroy(sleep_lock_003_glb_mutex);
}
extern volatile int vflag;
void sleep_lock_main ()
{
if (vflag == 1 || vflag ==888)
{
sleep_lock_001();
}
if (vflag == 2 || vflag ==888)
{
sleep_lock_002();
}
if (vflag == 3 || vflag ==888)
{
sleep_lock_003();
}
}
| 1
|
#include <pthread.h>
static pthread_mutex_t mut_num = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static int num = 0;
static void * thr_func(void *p)
{
int i,j,mark;
while(1)
{
pthread_mutex_lock(&mut_num);
while(num == 0)
pthread_cond_wait(&cond,&mut_num);
if(num == -1)
{
pthread_mutex_unlock(&mut_num);
break;
}
i = num;
num = 0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mut_num);
mark = 1;
for(j = 2 ; j < i/2 ; j++)
{
if(i % j == 0)
{
mark = 0;
break;
}
}
if(mark)
printf("[%d] %d is primer\\n",(int)p,i);
}
pthread_exit(0);
}
int main()
{
int i,err;
pthread_t tid[4];
for(i = 0 ; i < 4 ;i++)
{
err = pthread_create(tid+i,0,thr_func,(void *)i);
if(err)
{
fprintf(stderr,"pthread_create failed %s\\n",strerror(err));
exit(1);
}
}
for(i = 30000000 ; i <= 30000200 ; i++)
{
pthread_mutex_lock(&mut_num);
while(num != 0)
pthread_cond_wait(&cond,&mut_num);
num = i;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mut_num);
}
pthread_mutex_lock(&mut_num);
while(num != 0)
pthread_cond_wait(&cond,&mut_num);
num = -1;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mut_num);
for(i = 0 ; i < 4 ;i++)
{
pthread_join(tid[i],0);
}
pthread_mutex_destroy(&mut_num);
pthread_cond_destroy(&cond);
exit(0);
}
| 0
|
#include <pthread.h>
int pocetVedier = 0;
int vedra[10] = {0};
int stoj = 0;
int ODDYCHOVAT = 1, POSLEDNY_VNUTRI = 0;
int count = 0;
pthread_mutex_t mutexVedra = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutexSynchronizacia = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condVsetci = PTHREAD_COND_INITIALIZER;
pthread_cond_t condVnutri = PTHREAD_COND_INITIALIZER;
void maluj(void) {
sleep(2);
}
void ber(int maliar) {
printf("Tu je maliar %d. a VEDRO: %d \\n", maliar, vedra[maliar]);
if(vedra[maliar] % 4 == 0 && vedra[maliar] > 0){
pthread_mutex_lock(&mutexSynchronizacia);
while(!ODDYCHOVAT){
if(stoj){
return;
}
pthread_cond_wait(&condVsetci, &mutexSynchronizacia);
}
count++;
printf("Tu je maliar %d. a idem oddychovat ako %d \\n", maliar, count);
if(count == 3){
printf("Tu je 3. maliar podme oddychovat \\n");
POSLEDNY_VNUTRI = 1;
ODDYCHOVAT = 0;
pthread_cond_broadcast(&condVnutri);
} else {
while(!POSLEDNY_VNUTRI){
if(stoj){
return;
}
pthread_cond_wait(&condVnutri, &mutexSynchronizacia);
}
}
pthread_mutex_unlock(&mutexSynchronizacia);
pthread_mutex_lock(&mutexSynchronizacia);
count--;
printf("Tu je maliar %d. a odchadzam ako %d \\n", maliar, 3-count);
if(count == 0) {
printf("Tu je 3. maliar ODCHADZAME \\n");
POSLEDNY_VNUTRI = 0;
ODDYCHOVAT = 1;
pthread_cond_broadcast(&condVsetci);
} else {
while(POSLEDNY_VNUTRI) {
if(stoj){
return;
}
pthread_cond_wait(&condVsetci, &mutexSynchronizacia);
}
}
pthread_mutex_unlock(&mutexSynchronizacia);
sleep(2);
}
sleep(1);
pthread_mutex_lock(&mutexVedra);
vedra[maliar]++;
pocetVedier++;
pthread_mutex_unlock(&mutexVedra);
}
void *maliar( void *ptr ) {
int maliarov_index = (int) ptr;
while(!stoj) {
maluj();
ber(maliarov_index);
}
return 0;
}
int main(void) {
int i;
pthread_t maliari[10];
for (i=0;i<10;i++) pthread_create(&maliari[i], 0, &maliar, (void *)i);
sleep(30);
pthread_mutex_lock(&mutexSynchronizacia);
stoj = 1;
pthread_cond_broadcast(&condVsetci);
pthread_cond_broadcast(&condVnutri);
pthread_mutex_unlock(&mutexSynchronizacia);
for (i=0;i<10;i++) pthread_join(maliari[i], 0);
printf("Celkovy pocet: %d\\n", pocetVedier);
for (i=0;i<10;i++) printf("Maliar %d spravil %d vedier\\n", i, vedra[i]);
exit(0);
}
| 1
|
#include <pthread.h>
void *find_words(void*);
int map_reduce(int number_threads, char *string, struct list *list);
int main(void) {
char *string;
int cur_time, i, j;
struct list *list;
struct stat *buf;
buf = (struct stat *) malloc(sizeof(struct stat));
stat("./Don_Quixote.txt", buf);
int fd = open("./Don_Quixote.txt", O_RDONLY);
string = (char *)malloc(sizeof(char) * buf->st_size);
read(fd, string, buf->st_size);
list = (struct list *)malloc(sizeof(struct list));
for(j = 2; j < 4; ++j) {
list_init(list);
cur_time = clock();
map_reduce(j, string, list);
cur_time = clock() - cur_time;
printf("%d\\n\\n", cur_time);
for(i = 0; i < list->current_length; ++i)
free(list->head[i]);
list_destroy(list);
}
free(string);
free(list);
exit(0);
}
int is_separator(char *simbol, char *separators) {
while(*separators != 0) {
if(*simbol == *separators)
return 1;
++separators;
}
return 0;
}
void *find_words(void *arg) {
struct list *list;
char *begin, *end;
char *new_begin, *new_str;
int i, is_unique;
void **pointer;
pointer = (void **)arg;
list = (struct list *)(pointer[0]);
begin = (char *)(pointer[1]);
end = (char *)(pointer[2]);
while(begin != end) {
while(begin <= end && is_separator(begin, " ,.?!"))
++begin;
if(begin > end)
return 0;
new_begin = begin;
while(new_begin <= end && !is_separator(new_begin, " ,.?!"))
++new_begin;
--new_begin;
pthread_mutex_lock(list->mutex);
is_unique = 0;
for(i = 0; i < list->current_length; ++i) {
if(strncmp(list->head[i], begin, new_begin - begin + 1) == 0) {
is_unique = 1;
break;
}
}
if(is_unique == 0) {
new_str = (char *)malloc(sizeof(char) * (new_begin - begin + 2));
memcpy(new_str, begin, new_begin - begin + 1);
new_str[new_begin - begin + 1] = '\\0';
list_add(list, new_str);
}
pthread_mutex_unlock(list->mutex);
usleep(1000);
begin = new_begin + 1;
}
pthread_exit(0);
}
int map_reduce(int number_threads, char *string, struct list *list) {
int length, delta_length, i, begin_offset, end_offset, cur_pthread;
void ***arg;
pthread_t *pthreads;
pthreads = (pthread_t *)malloc(sizeof(pthread_t)*number_threads);
arg = (void ***)malloc(sizeof(void *) * number_threads);
length = strlen(string);
delta_length = length / number_threads;
begin_offset = 0;
cur_pthread = 0;
for(i = 0; i < number_threads; ++i) {
if(i == number_threads - 1)
end_offset = length;
else {
end_offset = delta_length * (i + 1);
while(end_offset >= begin_offset && !is_separator(string + end_offset, " ,.?!"))
--end_offset;
}
if(end_offset >= begin_offset) {
arg[cur_pthread] = (void **)malloc(sizeof(void *) * 3);
arg[cur_pthread][0] = list;
arg[cur_pthread][1] = string + begin_offset;
arg[cur_pthread][2] = string + end_offset - 1;
pthread_create((pthreads + cur_pthread), 0, find_words, (void*)(arg[cur_pthread]));
++cur_pthread;
}
begin_offset = end_offset;
}
for(i = 0; i < cur_pthread; ++i) {
pthread_join(pthreads[i], 0);
free(arg[i]);
}
free(pthreads);
free(arg);
return 0;
}
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
static void *lock_unlock(void *arg)
{
while (! isend) {
pthread_mutex_lock(&m);
count ++;
pthread_mutex_unlock(&m);
}
return arg;
}
static void test_exec(void)
{
int i;
pthread_t *t;
count = 0;
t = malloc(sizeof(*t) * nproc);
for (i = 0; i < nproc; i++)
pthread_create(&t[i], 0, lock_unlock, 0);
for (i = 0; i < nproc; i++)
pthread_join(t[i], 0);
free(t);
}
static void test_print_results(int sig)
{
isend = 1;
print_results();
}
| 0
|
#include <pthread.h>
static struct keyleds_ctl
{
int console_fd;
pthread_t th_num, th_cap, th_scr;
pthread_mutex_t cs_mutex;
volatile int t_keyled[8];
} ledctl;
static void *keyled_pulse(void *arg)
{
unsigned int keyleds, iled = (unsigned int)(arg);
int t = 0;
for ( ; ; t++)
{
if (t > ledctl.t_keyled[iled] && ledctl.t_keyled[iled] != 0)
{
pthread_mutex_lock(&ledctl.cs_mutex);
if (ledctl.t_keyled[iled] != 0)
{
keyleds = get_keyboard_leds(ledctl.console_fd);
set_keyboard_leds(ledctl.console_fd,
(keyleds & iled)?
(keyleds & (~iled)): (keyleds | iled));
}
t = 0;
pthread_mutex_unlock(&ledctl.cs_mutex);
}
usleep(10000);
}
return 0;
}
void init_netraf_leds_ctl(void)
{
ledctl.console_fd = open_console_fd("/dev/console");
ledctl.t_keyled[LED_NUM] = 0;
ledctl.t_keyled[LED_CAP] = 0;
ledctl.t_keyled[LED_SCR] = 0;
pthread_mutex_init(&ledctl.cs_mutex, 0);
}
void startup_netraf_leds(void)
{
pthread_create(&ledctl.th_num, 0, keyled_pulse, (void*)LED_NUM);
pthread_create(&ledctl.th_cap, 0, keyled_pulse, (void*)LED_CAP);
pthread_create(&ledctl.th_scr, 0, keyled_pulse, (void*)LED_SCR);
}
void set_keyled_pulse_period(unsigned int iled, unsigned int period)
{
ledctl.t_keyled[iled] = period;
}
void keyleds_off(void)
{
pthread_mutex_lock(&ledctl.cs_mutex);
set_keyboard_leds(ledctl.console_fd, 0);
pthread_mutex_unlock(&ledctl.cs_mutex);
}
| 1
|
#include <pthread.h>
static pthread_once_t paymax_init = PTHREAD_ONCE_INIT;
static pthread_mutex_t paymax_mutex = PTHREAD_MUTEX_INITIALIZER;
static int uart_fd;
void init_global_var(void)
{
pthread_mutex_init(&paymax_mutex, 0);
}
static int close_paymax(struct paymax_device_t *dev){
close(uart_fd);
if (dev) {
free(dev);
}
return 0;
}
int open_uart(void){
int fd = -1;
struct termios options;
fd = open("/dev/ttyHSL1",O_RDWR | O_NOCTTY);
if(-1 == fd){
ALOGE("Could not open uart port \\n");
return(-1);
}
if(tcflush(fd, TCIOFLUSH) < 0){
ALOGE("Could not flush uart port");
close(fd);
return(-1);
}
if(tcgetattr(fd, &options) < 0){
ALOGE("Can't get port settings \\n");
close(fd);
return(-1);
}
options.c_cc[VTIME] = 0;
options.c_cc[VMIN] = 0;
options.c_cflag &= ~(CSIZE | CRTSCTS);
options.c_cflag |= (CS8 | CLOCAL | CREAD);
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0;
cfsetospeed(&options, B115200);
cfsetispeed(&options, B115200);
if(tcsetattr(fd, TCSANOW, &options) < 0){
ALOGE("Can't set port setting \\n");
close(fd);
return(-1);
}
return fd;
}
static void writeCmdToMax(struct paymax_device_t *dev, const char* cmd_buf,unsigned int cmd_len){
write(uart_fd,cmd_buf,cmd_len);
}
static unsigned int readDataFromMax(struct paymax_device_t *dev, char* read_buf, unsigned int read_len, unsigned int timeout){
unsigned int size = 0;
char buf[2048] = { 0 };
unsigned int cycle=0;
pthread_mutex_lock(&paymax_mutex);
size = read(uart_fd,buf,read_len);
while(size<=3){
usleep(1000);
size = read(uart_fd,buf,read_len);
if (cycle++ > timeout)
goto read_failed;
}
ALOGE("read_data cycle .used.(%d) timeout.(%d)",cycle,timeout);
memcpy((void*)read_buf,(void*)buf,size);
pthread_mutex_unlock(&paymax_mutex);
return size;
read_failed:
ALOGE("read_failed cycle .used.(%d) timeout.(%d)",cycle,timeout);
pthread_mutex_unlock(&paymax_mutex);
return size;
}
static int open_paymax(const struct hw_module_t* module, char const* name,
struct hw_device_t** device)
{
pthread_once(&paymax_init, init_global_var);
struct paymax_device_t *dev = malloc(sizeof(struct paymax_device_t));
if(!dev)
return -ENOMEM;
memset(dev, 0, sizeof(*dev));
dev->common.tag = HARDWARE_DEVICE_TAG;
dev->common.version = 0;
dev->common.module = (struct hw_module_t*)module;
dev->common.close = (int (*)(struct hw_device_t*))close_paymax;
dev->writeCmdToMax = writeCmdToMax;
dev->readDataFromMax = readDataFromMax;
if((uart_fd=open_uart())<0)
return -1;
*device = (struct hw_device_t*)dev;
return 0;
}
static struct hw_module_methods_t paymax_module_methods = {
.open = open_paymax,
};
struct hw_module_t HAL_MODULE_INFO_SYM = {
.tag = HARDWARE_MODULE_TAG,
.version_major = 1,
.version_minor = 0,
.id = PAYMAX_HARDWARE_MODULE_ID,
.name = "paymax Module",
.author = "SDTM, Inc.",
.methods = &paymax_module_methods,
};
| 0
|
#include <pthread.h>
struct PAQueue *plib_aqueue_new(void)
{
struct PAQueue *new = malloc(sizeof(struct PAQueue));
new->qlock = malloc(sizeof(pthread_mutex_t));
new->q = plib_queue_new();
pthread_mutex_init(new->qlock, 0);
return new;
}
void plib_aqueue_push(struct PAQueue *aq, void *data)
{
pthread_mutex_lock(aq->qlock);
plib_queue_push(aq->q, data);
pthread_mutex_unlock(aq->qlock);
}
void *plib_aqueue_pop(struct PAQueue *aq)
{
void *data;
pthread_mutex_lock(aq->qlock);
data = plib_queue_pop(aq->q);
pthread_mutex_unlock(aq->qlock);
return data;
}
size_t plib_aqueue_size(struct PAQueue *aq)
{
size_t size;
pthread_mutex_lock(aq->qlock);
size = aq->q->size;
pthread_mutex_unlock(aq->qlock);
return size;
}
void plib_aqueue_delete(struct PAQueue *aq)
{
pthread_mutex_lock(aq->qlock);
plib_queue_delete(aq->q);
pthread_mutex_unlock(aq->qlock);
pthread_mutex_destroy(aq->qlock);
free(aq->qlock);
free(aq);
}
| 1
|
#include <pthread.h>
int w, h;
v2df zero = { 0.0, 0.0 };
v2df four = { 4.0, 4.0 };
v2df nzero;
double inverse_w;
double inverse_h;
char *whole_data;
int y_pick;
pthread_mutex_t y_mutex = PTHREAD_MUTEX_INITIALIZER;
static void * worker(void *_args) {
char *data;
double x, y;
int bit_num;
char byte_acc = 0;
for (;;) {
pthread_mutex_lock(&y_mutex);
y = y_pick;
y_pick++;
pthread_mutex_unlock(&y_mutex);
if (y >= h)
return 0;
data = &whole_data[(w >> 3) * (int)y];
for(bit_num=0,x=0;x<w;x+=2)
{
v2df Crv = { (x+1.0)*inverse_w-1.5, (x)*inverse_w-1.5 };
v2df Civ = { y*inverse_h-1.0, y*inverse_h-1.0 };
v2df Zrv = { 0.0, 0.0 };
v2df Ziv = { 0.0, 0.0 };
v2df Trv = { 0.0, 0.0 };
v2df Tiv = { 0.0, 0.0 };
int i = 0;
int mask;
do {
Ziv = (Zrv*Ziv) + (Zrv*Ziv) + Civ;
Zrv = Trv - Tiv + Crv;
Trv = Zrv * Zrv;
Tiv = Ziv * Ziv;
v2df delta = (v2df)__builtin_ia32_cmplepd( (Trv + Tiv), four );
mask = __builtin_ia32_movmskpd(delta);
} while (++i < 50 && (mask));
byte_acc <<= 2;
byte_acc |= mask;
bit_num+=2;
if(!(bit_num&7)) {
data[(bit_num>>3) - 1] = byte_acc;
byte_acc = 0;
}
}
if(bit_num&7) {
byte_acc <<= (8-w%8);
bit_num += 8;
data[bit_num>>3] = byte_acc;
byte_acc = 0;
}
}
}
int main (int argc, char **argv)
{
pthread_t ids[8];
int i;
nzero = -zero;
w = h = atoi(argv[1]);
inverse_w = 2.0 / w;
inverse_h = 2.0 / h;
y_pick = 0;
whole_data = malloc(w * (w >> 3));
for (i = 0; i < 8; i++)
pthread_create(&ids[i], 0, worker, 0);
for (i = 0; i < 8; i++)
pthread_join(ids[i], 0);
pthread_mutex_destroy(&y_mutex);
printf("P4\\n%d %d\\n",w,h);
fwrite(whole_data, h, w >> 3, stdout);
free(whole_data);
return 0;
}
| 0
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER;
void * thr_fn(void *arg) {
int err, signo;
for (;;) {
err = sigwait(&mask, &signo);
if (err != 0) {
err_exit(err, "sigwait failed");
}
switch (signo) {
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&waitloc);
return(0);
default:
printf("unexpected signal %d\\n", signo);
exit(1);
}
}
}
int main(int argc, char const* argv[])
{
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) {
err_exit(err, "SIG_BLOCK error");
}
err = pthread_create(&tid, 0, thr_fn, 0);
if (err != 0)
err_exit(err, "can't create thread");
pthread_mutex_lock(&lock);
while (quitflag == 0)
pthread_cond_wait(&waitloc, &lock);
pthread_mutex_unlock(&lock);
quitflag = 0;
if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) {
err_sys("SIG_SETMASK error");
}
exit(0);
return 0;
}
| 1
|
#include <pthread.h>
static void die_with_error(char *message)
{
perror(message);
exit(1);
}
static void radix_tree_init(struct radix_tree *tree, int bits, int radix)
{
if (radix < 1) {
perror("Invalid radix\\n");
return;
}
if (bits < 1) {
perror("Invalid number of bits\\n");
return;
}
unsigned long n_slots = 1L << radix;
tree->radix = radix;
tree->max_height = (((bits) + (radix) - 1) / (radix));
tree->node = calloc(sizeof(struct radix_node) +
(n_slots * sizeof(void *)), 1);
if (!tree->node)
die_with_error("failed to create new node.\\n");
else
pthread_mutex_init(&(tree->node->lock), 0);
}
static int find_slot_index(unsigned long key, int levels_left, int radix)
{
return key >> ((levels_left - 1) * radix) & ((1 << radix) - 1);
}
static void *radix_tree_find_alloc(struct radix_tree *tree, unsigned long key,
void *(*create)(unsigned long))
{
int levels_left = tree->max_height;
int radix = tree->radix;
int n_slots = 1 << radix;
int index;
struct radix_node *current_node = tree->node;
void **next_slot = 0;
void *slot;
pthread_mutex_t *lock;
while (levels_left) {
index = find_slot_index(key, levels_left, radix);
lock = &(current_node->lock);
pthread_mutex_lock(lock);
next_slot = ¤t_node->slots[index];
slot = *next_slot;
if (slot) {
current_node = slot;
} else if (create) {
void *new;
if (levels_left != 1)
new = calloc(sizeof(struct radix_node) +
(n_slots * sizeof(void *)), 1);
else
new = create(key);
if (!new)
die_with_error("failed to create new node.\\n");
*next_slot = new;
current_node = new;
if (levels_left != 1)
pthread_mutex_init(&(current_node->lock),
0);
} else {
pthread_mutex_unlock(lock);
return 0;
}
pthread_mutex_unlock(lock);
levels_left--;
}
return current_node;
}
static void *radix_tree_find(struct radix_tree *tree, unsigned long key)
{
return radix_tree_find_alloc(tree, key, 0);
}
struct radix_tree_desc lock_node_desc = {
.name = "lock_node",
.init = radix_tree_init,
.find_alloc = radix_tree_find_alloc,
.find = radix_tree_find,
};
| 0
|
#include <pthread.h>
think,
hungry,
eat,
} Phil;
int phil_left(int ph_id);
int phil_right(int ph_id);
void *phil_action(void *ph);
int print_table();
Phil *phils;
pthread_mutex_t table;
int main(){
pthread_t *thread;
phils = (Phil *) calloc(5, sizeof(Phil));
if(phils == 0){
printf("\\nErro ao alocar filosofos!\\n");
return -1;
}
thread = (pthread_t *) calloc(5, sizeof(pthread_t));
if(thread == 0){
printf("\\nErro ao alocar threads!\\n");
return -1;
}
pthread_mutex_init(&table, 0);
int i;
for(i=0; i<5; i++){
phils[i] = think;
pthread_create(&thread[i], 0, phil_action, (void *) i);
}
for(i=0; i<5; i++){
pthread_join(thread[i], 0);
}
return 0;
}
int phil_left(int ph_id){
return (ph_id + 5 - 1) % 5;
}
int phil_right(int ph_id){
return (ph_id + 1) % 5;
}
void *phil_action(void *ph){
int ph_id = (int) ph;
while(1){
pthread_mutex_lock(&table);
switch(phils[ph_id]){
case think:
phils[ph_id] = hungry;
print_table();
pthread_mutex_unlock(&table);
srand (time(0));
sleep(rand() % 10 + 1);
break;
case eat:
phils[ph_id] = think;
print_table();
pthread_mutex_unlock(&table);
srand (time(0));
sleep(rand() % 10 + 1);
break;
case hungry:
if(phils[phil_left(ph_id)] != eat && phils[phil_right(ph_id)] != eat){
phils[ph_id] = eat;
print_table();
}
pthread_mutex_unlock(&table);
srand (time(0));
sleep(rand() % 10 + 1);
break;
}
}
}
int print_table(){
printf("\\nTABLE: ");
int i;
for(i=0; i<5; i++){
if(phils[i] == eat){
printf("->[ E ]<-");
}else if(phils[i] == think){
printf(" .T. ");
}else if(phils[i] == hungry){
printf(" [ H ] ");
}else{
printf(" [ ] ");
}
}
}
| 1
|
#include <pthread.h>
static void to_thinking(int n)
{
mod_status(n, THINKING);
}
static void get_sticks(int n)
{
int one;
int first;
int second;
one = 0;
first = (!(n % 2)) ? ((n + 1) % nb_philos) : (n);
second = (!(n % 2)) ? (n) : ((n + 1) % nb_philos);
while (check_status(first) == THINKING)
usleep(1000);
while (sem_trywait(&(sticks[first])))
pthread_cond_signal(&(conds[first]));
while (sem_trywait(&(sticks[second])))
{
if (!one && (one = 1))
to_thinking(n);
pthread_cond_signal(&(conds[second]));
}
}
static void release_sticks(int n)
{
sem_post(&(sticks[n]));
sem_post(&(sticks[(n + 1) % nb_philos]));
}
static void wait_eating(int n)
{
pthread_mutex_t unused;
struct timespec time_to_wait;
struct timeval now;
pthread_mutex_init(&unused, (const pthread_mutexattr_t*)0);
pthread_mutex_lock(&unused);
if (!gettimeofday(&now, (struct timezone*)0))
{
time_to_wait.tv_sec = now.tv_sec + time_waiting;
time_to_wait.tv_nsec = now.tv_usec * 1000;
pthread_cond_timedwait(&(conds[n]), &unused, &time_to_wait);
}
else
pthread_cond_wait(&(conds[n]), &unused);
pthread_mutex_unlock(&unused);
pthread_mutex_destroy(&unused);
}
void philo_run(int *number)
{
int rice;
int n;
rice = nb_rices;
n = *number;
while (rice)
{
get_sticks(n);
mod_status(n, EATING);
wait_eating(n);
rice -= 1;
mod_status(n, RESTING);
release_sticks(n);
if (rice)
sleep(1);
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t happy_mutex;
void *worker(void *varg)
{
long *counter = (long *)varg;
printf("thread 0x%0lx starting\\n", (long)pthread_self());
int i = 0;
for (; i < 100000; i += 1) {
pthread_mutex_lock(&happy_mutex);
*counter += 1;
pthread_mutex_unlock(&happy_mutex);
}
printf("thread 0x%0lx ending with counter %ld\\n", (long)pthread_self(), *counter);
return 0;
}
int
main(int argc, char **argv)
{
pthread_t thread_a, thread_b;
long *counter = malloc(sizeof(long));
*counter = 0UL;
pthread_mutex_init(&happy_mutex, 0);
pthread_create(&thread_a, 0, worker, counter);
pthread_create(&thread_b, 0, worker, counter);
pthread_join(thread_a, 0);
pthread_join(thread_b, 0);
printf("end counter value (main thread): %ld\\n", *counter);
pthread_mutex_destroy(&happy_mutex);
free(counter);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutexid;
pthread_mutex_t mutexres;
int idcount = 0;
pthread_mutex_t joinmutex[5];
int join[5];
int result[5];
int target;
int sequence[(5 * 30)];
void *thread (void *arg)
{
int id, i, from, count, l_target;
pthread_mutex_lock (&mutexid);
l_target = target;
id = idcount;
idcount++;
pthread_mutex_unlock (&mutexid);
__VERIFIER_assert (id >= 0);
__VERIFIER_assert (id <= 5);
from = id * 30;
count = 0;
for (i = 0; i < 30; i++)
{
if (sequence[from + i] == l_target)
{
count++;
}
if (count > 30)
{
count = 30;
}
}
printf ("t: id %d from %d count %d\\n", id, from, count);
pthread_mutex_lock (&mutexres);
result[id] = count;
pthread_mutex_unlock (&mutexres);
pthread_mutex_lock (&joinmutex[id]);
join[id] = 1;
pthread_mutex_unlock (&joinmutex[id]);
return 0;
}
int main ()
{
int i;
pthread_t t[5];
int count;
i = __VERIFIER_nondet_int (0, (5 * 30)-1);
sequence[i] = __VERIFIER_nondet_int (0, 3);
target = __VERIFIER_nondet_int (0, 3);
printf ("m: target %d\\n", target);
pthread_mutex_init (&mutexid, 0);
pthread_mutex_init (&mutexres, 0);
for (i = 0; i < 5; i++)
{
pthread_mutex_init (&joinmutex[i], 0);
result[i] = 0;
join[i] = 0;
}
i = 0;
pthread_create (&t[i], 0, thread, 0); i++;
pthread_create (&t[i], 0, thread, 0); i++;
pthread_create (&t[i], 0, thread, 0); i++;
pthread_create (&t[i], 0, thread, 0); i++;
pthread_create (&t[i], 0, thread, 0); i++;
__VERIFIER_assert (i == 5);
int j;
i = 0;
pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; }
pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; }
pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; }
pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; }
pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; }
if (i != 5)
{
return 0;
}
__VERIFIER_assert (i == 5);
count = 0;
for (i = 0; i < 5; i++)
{
count += result[i];
printf ("m: i %d result %d count %d\\n", i, result[i], count);
}
printf ("m: final count %d\\n", count);
__VERIFIER_assert (count >= 0);
__VERIFIER_assert (count <= (5 * 30));
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
void clean_mutex(void * data) {
pthread_mutex_unlock(&mutex);
printf("Thread %d a libéré le mutex\\n", (int) pthread_self());
}
void clean_buffer(void * data) {
int * buffer = (int*) data;
free(buffer);
printf("Thread %d a libéré la mémoire allouée\\n", (int) pthread_self());
}
void* th0(void* p) {
int * buffer = malloc(1024 * sizeof(int));
printf("Thread %d a alloué de la mémoire et attend le mutex\\n", (int) pthread_self());
pthread_cleanup_push(clean_buffer, buffer);
pthread_mutex_lock(&mutex);
printf("Thread %d a bloqué le mutex\\n", (int) pthread_self());
sleep(6);
pthread_mutex_unlock(&mutex);
printf("Thread %d se termine normalement après avoir libéré le mutex\\n", (int) pthread_self());
pthread_cleanup_pop(1);
pthread_exit((void*)3);
return 0;
}
void* th1(void* p) {
pthread_cleanup_push(clean_mutex, 0);
printf("Thread %d attend le mutex\\n", (int) pthread_self());
pthread_mutex_lock(&mutex);
printf("Thread %d a bloqué le mutex\\n", (int) pthread_self());
pthread_mutex_unlock(&mutex);
printf("Thread %d se termine normalement après avoir libéré le mutex\\n", (int) pthread_self());
pthread_cleanup_pop(1);
pthread_exit((void*)3);
return 0;
}
int main(void) {
pthread_t pth[3];
void* ret;
pthread_mutex_init(&mutex, 0);
pthread_create(&pth[0], 0, th0, 0);
pthread_create(&pth[1], 0, th0, 0);
sleep(1);
pthread_create(&pth[2], 0, th1, 0);
printf("Attend 10 secondes et stoppe les threads\\n");
sleep(10);
pthread_cancel(pth[0]);
pthread_cancel(pth[1]);
printf("Les threads ont été priés de s'arrêter\\n");
pthread_join(pth[0], (void**)&ret);
printf("retour du thread %d : %d\\n", (int) pth[0], *((int*) &ret));
pthread_join(pth[1], (void**)&ret);
printf("retour du thread %d : %d\\n", (int) pth[1], *((int*) &ret));
pthread_join(pth[2], (void**)&ret);
printf("retour du thread %d : %d\\n", (int) pth[2], *((int*) &ret));
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
int inn,inn_size;
int rl,fl,ry,fy,type;
pthread_mutex_t mutex;
sem_t yorks;
sem_t lancs;
int l,y;
pthread_t tid[20];
pthread_attr_t attr;
void initializeData() {
pthread_mutex_init(&mutex, 0);
pthread_attr_init(&attr);
int i;
inn_size = 1;
inn=0;
rl=fl=ry=fy=0;
type=rand()%2;
if(type==0){
sem_init(&lancs, 0,inn_size);
sem_init(&yorks, 0,0);
}
else{
sem_init(&lancs, 0,0);
sem_init(&yorks, 0,inn_size);
}
l=y=0;
}
void *Yorks(void *param) {
int id=param;
int i;
pthread_mutex_lock(&mutex);
y++;
pthread_mutex_unlock(&mutex);
sem_wait(&yorks);
pthread_mutex_lock(&mutex);
inn++;
printf("%d:York entered\\n",id);
pthread_mutex_unlock(&mutex);
sleep(5);
pthread_mutex_lock(&mutex);
y--;
printf("%d:York exited\\n",id);
if(y==0){
type^=1;
for(i=0;i<inn_size;++i)
sem_post(&lancs);
}
else
sem_post(&yorks);
pthread_mutex_unlock(&mutex);
sem_post(&yorks);
}
void *Lancs(void *param) {
int id=param;
int i;
pthread_mutex_lock(&mutex);
l++;
pthread_mutex_unlock(&mutex);
sem_wait(&lancs);
pthread_mutex_lock(&mutex);
inn++;
printf("%d:Lacannaster entered\\n",id);
pthread_mutex_unlock(&mutex);
sleep(5);
pthread_mutex_lock(&mutex);
l--;
printf("%d:Lacannaster exited\\n",id);
if(l==0){
type^=1;
for(i=0;i<inn_size;++i)
sem_post(&yorks);
}
else
sem_post(&lancs);
pthread_mutex_unlock(&mutex);
sem_post(&lancs);
}
int main() {
int i;
int *arg = malloc(sizeof(*arg));
initializeData();
int n=10;
int clan;
for(i = 0; i < n; i++) {
arg=i;
clan=rand()%2;
if(clan)
pthread_create(&tid[i],&attr,Lancs,arg);
else
pthread_create(&tid[i],&attr,Yorks,arg);
}
for(i = 0; i < n; i++) {
pthread_join(tid[i], 0);
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER;
int isGreen1 (int s) {
return s == 0;
}
int isGreen2 (int s) {
return s == 0;
}
void * signal1(void* d) {
int status = 0;
b1:
printf("1 -> GREEN\\n");
sleep(2);
status = 1;
printf("1 -> ORANGE\\n");
sleep(1);
status = 2;
printf("1 -> RED\\n");
pthread_mutex_unlock(&m1);
pthread_mutex_lock(&m2);
status = 0;
printf("1 -> GREEN\\n");
sleep(2);
status = 1;
printf("1 -> ORANGE\\n");
sleep(1);
status = 2;
printf("1 -> RED\\n");
pthread_mutex_unlock(&m1);
e1:
pthread_exit(0);
}
void * signal2(void* d) {
int status = 2;
b2:
pthread_mutex_lock(&m1);
status = 0;
printf("2 -> GREEN\\n");
sleep(2);
status = 1;
printf("2 -> ORANGE\\n");
sleep(1);
status = 2;
printf("2 -> RED\\n");
pthread_mutex_unlock(&m2);
e2:
pthread_exit(0);
}
int main() {
pthread_t t1, t2;
printf("Start\\n");
pthread_mutex_lock(&m1);
pthread_mutex_lock(&m2);
printf("Create\\n");
pthread_create(&t1, 0, signal1, 0);
pthread_create(&t2, 0, signal2, 0);
printf("Join\\n");
pthread_join(t1, 0);
pthread_join(t2, 0);
printf("End\\n");
return 0;
}
| 1
|
#include <pthread.h>
int q[5];
int qsiz;
pthread_mutex_t mq;
void queue_init ()
{
pthread_mutex_init (&mq, 0);
qsiz = 0;
}
void queue_insert (int x)
{
int done = 0;
int i = 0;
printf2 ("prod: trying\\n");
while (done == 0)
{
i++;
pthread_mutex_lock (&mq);
if (qsiz < 5)
{
printf2 ("prod: got it! x %d qsiz %d i %d\\n", x, qsiz, i);
done = 1;
q[qsiz] = x;
qsiz++;
}
pthread_mutex_unlock (&mq);
}
}
int queue_extract ()
{
int done = 0;
int x, i = 0;
printf2 ("consumer: trying\\n");
while (done == 0)
{
i++;
pthread_mutex_lock (&mq);
if (qsiz > 0)
{
done = 1;
x = q[0];
printf2 ("consumer: got it! x %d qsiz %d i %d\\n", x, qsiz, i);
qsiz--;
for (i = 0; i < qsiz; i++) q[i] = q[i+1];
}
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 findmax (int *t, int count)
{
int i, mx;
mx = 0;
for (i = 1; i < count; i++)
{
if (t[i] > t[mx]) mx = i;
}
swap (t, mx, count-1);
return t[count-1];
}
int source[7];
int sorted[7];
void producer ()
{
int i, max;
for (i = 0; i < 7; i++)
{
max = findmax (source, 7 - i);
queue_insert (max);
}
}
void consumer ()
{
int i, max;
for (i = 0; i < 7; i++)
{
max = queue_extract ();
sorted[i] = max;
}
}
void *thread (void * arg)
{
(void) arg;
producer ();
return 0;
}
int main ()
{
pthread_t t;
__libc_init_poet ();
unsigned seed = (unsigned) time (0);
int i;
srand (seed);
printf ("Using seed %u\\n", seed);
for (i = 0; i < 7; i++)
{
source[i] = random() % 20;
assert (source[i] >= 0);
printf2 ("source[%d] = %d\\n", i, source[i]);
}
printf2 ("==============\\n");
queue_init ();
pthread_create (&t, 0, thread, 0);
consumer ();
pthread_join (t, 0);
printf2 ("==============\\n");
for (i = 0; i < 7; i++)
printf2 ("sorted[%d] = %d\\n", i, sorted[i]);
return 0;
}
| 0
|
#include <pthread.h>
struct foo
{
int f_count;
int f_addtimes;
pthread_mutex_t f_mutex;
};
struct foo * foo_alloc()
{
struct foo* fp;
fp = (struct foo*)malloc(sizeof(struct foo));
if(fp != 0)
{
fp->f_count = 0;
fp->f_addtimes = 0;
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&fp->f_mutex,&attr);
}
return fp;
}
void foo_addtimes(struct foo *fp)
{
pthread_mutex_lock(&fp->f_mutex);
fp->f_addtimes++;
pthread_mutex_unlock(&fp->f_mutex);
}
void foo_add(struct foo *fp)
{
pthread_mutex_lock(&fp->f_mutex);
fp->f_count++;
foo_addtimes(fp);
pthread_mutex_unlock(&fp->f_mutex);
}
void * thread_func1(void *arg)
{
struct foo *fp = (struct foo*)arg;
printf("thread 1 start.\\n");
foo_add(fp);
printf("in thread 1 count = %d\\n",fp->f_count);
printf("thread 1 exit.\\n");
pthread_exit((void*)1);
}
void * thread_func2(void *arg)
{
struct foo *fp = (struct foo*)arg;
printf("thread 2 start.\\n");
foo_add(fp);
printf("in thread 2 count = %d\\n",fp->f_count);
printf("thread 2 exit.\\n");
pthread_exit((void*)2);
}
int main()
{
pthread_t pid1,pid2;
int err;
void *pret;
struct foo *fobj;
fobj = foo_alloc();
pthread_create(&pid1,0,thread_func1,(void*)fobj);
pthread_create(&pid2,0,thread_func2,(void*)fobj);
pthread_join(pid1,&pret);
printf("thread 1 exit code is: %d\\n",(int)pret);
pthread_join(pid2,&pret);
printf("thread 2 exit code is: %d\\n",(int)pret);
exit(0);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t s_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t s_cond = PTHREAD_COND_INITIALIZER;
static pthread_cond_t s_cond_monotonic = PTHREAD_COND_INITIALIZER;
void timespec_diff(struct timespec *start,
struct timespec *end,
struct timespec *result)
{
if ((end->tv_nsec - start->tv_nsec) < 0)
{
result->tv_sec = end->tv_sec - start->tv_sec - 1;
result->tv_nsec = end->tv_nsec - start->tv_nsec + 1000000000;
}
else
{
result->tv_sec = end->tv_sec - start->tv_sec;
result->tv_nsec = end->tv_nsec - start->tv_nsec;
}
}
void print_timedwait_result(int id, int result,
struct timespec* start,
struct timespec* end)
{
struct timespec diff;
timespec_diff(start, end, &diff);
if (result == ETIMEDOUT)
{
printf("t%d timeout: %ld.%06ld (%ld.%06ld => %ld.%06ld)\\n",
id, diff.tv_sec, diff.tv_nsec,
start->tv_sec, start->tv_nsec, end->tv_sec, end->tv_nsec);
}
else
{
printf("t%d success: %ld.%06ld (%ld.%06ld => %ld.%06ld)\\n",
id, diff.tv_sec, diff.tv_nsec,
start->tv_sec, start->tv_nsec, end->tv_sec, end->tv_nsec);
}
}
void* timedwait(void* arg)
{
int id = *((int*)arg);
pthread_mutex_lock(&s_mutex);
{
struct timespec start;
struct timespec timeout;
clock_gettime(CLOCK_REALTIME, &start);
timeout.tv_sec = start.tv_sec + 5;
timeout.tv_nsec = start.tv_nsec;
int ret = pthread_cond_timedwait(&s_cond, &s_mutex, &timeout);
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
print_timedwait_result(id, ret, &start, &now);
}
pthread_mutex_unlock(&s_mutex);
}
void* timedwait_monotonic(void* arg)
{
int id = *((int*)arg);
pthread_mutex_lock(&s_mutex);
{
struct timespec start;
struct timespec timeout;
clock_gettime(CLOCK_MONOTONIC, &start);
timeout.tv_sec = start.tv_sec + 5;
timeout.tv_nsec = start.tv_nsec;
int ret = pthread_cond_timedwait(&s_cond_monotonic, &s_mutex, &timeout);
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
print_timedwait_result(id, ret, &start, &now);
}
pthread_mutex_unlock(&s_mutex);
}
int main()
{
pthread_t t1, t2;
int id1 = 1, id2 = 2;
pthread_condattr_t attr;
pthread_condattr_init(&attr);
pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
pthread_cond_init(&s_cond_monotonic, &attr);
pthread_create(&t1, 0, timedwait, (void*)&id1);
pthread_create(&t2, 0, timedwait_monotonic, (void*)&id2);
sleep(1);
{
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
now.tv_sec += 60;
int ret = clock_settime(CLOCK_REALTIME, &now);
assert(ret == 0);
}
pthread_join(t1, 0);
pthread_join(t2, 0);
}
| 0
|
#include <pthread.h>
char fileName[256];
long int fileSize;
int fileMode;
struct fileStruct *next;
} fileStruct;
void switchMemory(int *currentMemory, void **writeMemory, void *memory1,
void *memory2, pthread_mutex_t *m1lockw, pthread_mutex_t *m1lockr, pthread_mutex_t *m2lockw, pthread_mutex_t *m2lockr)
{
*currentMemory = -(*currentMemory);
switch (*currentMemory)
{
case -1:
pthread_mutex_unlock(m2lockr);
pthread_mutex_unlock(m2lockw);
pthread_mutex_lock(m1lockr);
*writeMemory = memory1 + sizeof(int);
break;
case 1:
pthread_mutex_unlock(m1lockr);
pthread_mutex_unlock(m1lockw);
pthread_mutex_lock(m2lockr);
*writeMemory = memory2 + sizeof(int);
break;
default:
fprintf(stderr, "switch mem error");
exit(1);
break;
}
}
int mkpath(char* file_path, mode_t mode) {
assert(file_path && *file_path);
char* p;
for (p=strchr(file_path+1, '/'); p; p=strchr(p+1, '/')) {
*p='\\0';
if (mkdir(file_path, mode)==-1) {
if (errno!=EEXIST) { *p='/'; return -1; }
}
*p='/';
}
return 0;
}
void WriteFile(void *memory1, void *memory2, int bufSize, pthread_mutex_t *m1lockw, pthread_mutex_t *m1lockr, pthread_mutex_t *m2lockw, pthread_mutex_t *m2lockr)
{
bufSize -= sizeof(int);
long int remainMemory = bufSize;
int currentMemory = -1;
void *writeMemory = memory1 + sizeof(int);
void *p = writeMemory;
pthread_mutex_lock(m1lockr);
while (*(int*)memory1 == 0) { pthread_mutex_unlock(m1lockr); usleep(100); pthread_mutex_lock(m1lockr); }
while (1) {
if (remainMemory < sizeof(fileStruct)) {
switchMemory(¤tMemory, &p, memory1, memory2, m1lockw, m1lockr, m2lockw, m2lockr);
remainMemory = bufSize;
}
fileStruct * nowfile = (fileStruct *) p;
char filename[256]="";
strcpy(filename,nowfile->fileName);
printf("will write %s",filename);
mkpath(filename,0755);
int fd = open(filename , O_CREAT, nowfile->fileMode);
if(!fd){
printf("create file error");
exit(1);
}
close(fd);
int f=open(filename,O_WRONLY);
printf("size:%dmode:%d",nowfile->fileSize,nowfile->fileMode);
fileStruct * endWrite = nowfile->next;
remainMemory -= sizeof(fileStruct);
if (nowfile->fileSize < remainMemory) {
write(f, nowfile + 1, nowfile->fileSize);
remainMemory -= nowfile->fileSize;
p += sizeof(fileStruct);
p += nowfile->fileSize;
close(f);
}
else if (nowfile->fileSize == remainMemory) {
write(f, nowfile + 1, nowfile->fileSize);
remainMemory = bufSize;
switchMemory(¤tMemory, &p, memory1, memory2, m1lockw, m1lockr, m2lockw, m2lockr);
close(f);
}
else if (nowfile->fileSize > remainMemory) {
write(f, nowfile + 1, remainMemory);
int fileSize = nowfile->fileSize;
switchMemory(¤tMemory, &p, memory1, memory2, m1lockw, m1lockr, m2lockw, m2lockr);
int writeTimes = ceil((nowfile->fileSize - remainMemory) / (float)bufSize);
int i = 1;
for (i = 1; i < writeTimes;i++)
{
write(f, p, bufSize);
switchMemory(¤tMemory, &p, memory1,
memory2, m1lockw, m1lockr, m2lockw, m2lockr);
}
int lastSize =
fileSize - remainMemory - (writeTimes -
1) * bufSize;
write(f, p, lastSize);
p += lastSize;
remainMemory = bufSize - lastSize;
if (!remainMemory) {
remainMemory = bufSize;
switchMemory(¤tMemory, &p, memory1,
memory2, m1lockw, m1lockr, m2lockw, m2lockr);
}
close(f);
}
if (!endWrite)
break;
}
if (currentMemory == -1) { pthread_mutex_unlock(m1lockr); pthread_mutex_unlock(m1lockw); }
else { pthread_mutex_unlock(m2lockr); pthread_mutex_unlock(m2lockw);}
}
| 1
|
#include <pthread.h>
int log_to_stderr = 1;
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER;
void *thr_fn(void *arg)
{
int err, signo;
for ( ;; )
{
err = sigwait(&mask, &signo);
if ( err != 0 )
err_exit(err, "sigwait failed");
switch ( signo )
{
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&waitloc);
return 0;
default:
printf("unexpected signal %d\\n", signo);
exit(1);
}
}
}
int main()
{
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if ( ( err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0 )
err_exit(err, "SIG_BLOCK error");
err = pthread_create(&tid, 0, thr_fn, 0);
if ( err != 0 )
err_exit(err, "can't create thread");
pthread_mutex_lock(&lock);
while ( quitflag == 0 )
pthread_cond_wait(&waitloc, &lock);
pthread_mutex_unlock(&lock);
quitflag = 0;
if ( sigprocmask(SIG_SETMASK, &oldmask, 0) < 0 )
err_sys("SIG_SETMASK error");
exit(0);
}
| 0
|
#include <pthread.h>
static char running = 1;
static long long counter = 0;
pthread_mutex_t c_mutex;
void *process (void *arg)
{
while (running) {
pthread_mutex_lock (&c_mutex);
counter++;
pthread_mutex_unlock (&c_mutex);
}
pthread_exit (0);
}
int main (int argc, char **argv)
{
int i;
pthread_t threadId;
void *retval;
pthread_mutex_init (&c_mutex, 0);
if (pthread_create (&threadId, 0, process, "0"))
{ perror("pthread_create"); exit(errno); };
for (i = 0; i < 10; i++) {
sleep (1);
pthread_mutex_lock (&c_mutex);
printf ("%lld\\n", counter);
pthread_mutex_unlock (&c_mutex);
}
running = 0;
if (pthread_join (threadId, &retval))
{ perror("pthread_join"); exit(errno); };
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t m_go = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t c_go = PTHREAD_COND_INITIALIZER;
static pthread_cond_t c_running = PTHREAD_COND_INITIALIZER;
static volatile int alive, running;
static int spin;
static int rep_nop;
static void *spinner(void *v)
{
pthread_mutex_lock(&m_go);
while(!alive)
pthread_cond_wait(&c_go, &m_go);
running++;
pthread_cond_signal(&c_running);
pthread_mutex_unlock(&m_go);
while(alive)
spin++;
return 0;
}
static void *rep_nopper(void *v)
{
pthread_mutex_lock(&m_go);
while(!alive)
pthread_cond_wait(&c_go, &m_go);
running++;
pthread_cond_signal(&c_running);
pthread_mutex_unlock(&m_go);
while(alive) {
rep_nop++;
}
return 0;
}
int main()
{
pthread_t a, b;
pthread_create(&a, 0, spinner, 0);
pthread_create(&b, 0, rep_nopper, 0);
pthread_mutex_lock(&m_go);
alive = 1;
pthread_cond_broadcast(&c_go);
while(running < 2)
pthread_cond_wait(&c_running, &m_go);
pthread_mutex_unlock(&m_go);
sleep(2);
alive = 0;
pthread_join(a, 0);
pthread_join(b, 0);
if (0)
printf("spin=%d rep_nop=%d rep_nop:spin ratio: %g\\n",
spin, rep_nop, (float)rep_nop / spin);
if (spin > rep_nop)
printf("PASS\\n");
else
printf("FAIL spin=%d rep_nop=%d rep_nop:spin ratio: %g\\n",
spin, rep_nop, (float)rep_nop / spin);
return 0;
}
| 0
|
#include <pthread.h>
struct p_lease_v {
int lease;
int pos;
int value;
};
int array[5];
void put(int value, int pos, int lease) {
int i;
array[pos] = value;
}
int get(int pos) {
return array[pos];
}
void clean() {
int i;
for (i = 0; i < 5; ++i) {
if (array[i] != -101) {
array[i] = -101;
}
}
}
pthread_mutex_t mutex;
pthread_cond_t cond;
void read(void* pos) {
int p = (int) pos;
pthread_mutex_lock(&mutex);
int res = 0;
while ((res = get(p)) == -101) {
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
printf("questo è il valore in posizione %d: %d\\n", p, res);
}
void prod(void* pos_lease_v) {
struct p_lease_v* plv = (struct p_lease_v*) pos_lease_v;
int lease = plv->lease;
int p = plv->pos;
int value = plv->value;
free(plv);
pthread_mutex_lock(&mutex);
while (array[p] != -101) {
pthread_cond_wait(&cond, &mutex);
}
put(value, p, lease);
pthread_mutex_unlock(&mutex);
}
void garbage(void* time_cont) {
unsigned int t = (unsigned int) time_cont;
while (1) {
pthread_mutex_lock(&mutex);
clean();
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
}
int main() {
int i;
pthread_t* prods;
prods = (pthread_t*) malloc(10 * sizeof(pthread_t));
pthread_t* cons;
pthread_t garb;
cons = (pthread_t*) malloc(10 * sizeof(pthread_t));
pthread_cond_init(&cond, 0);
for (i = 0; i < 5; ++i) {
array[i] = -101;
}
pthread_mutex_init(&mutex, 0);
struct p_lease_v *plv;
for (i = 1; i <= 10; ++i) {
plv = (struct p_lease_v *) malloc(sizeof(struct p_lease_v));
plv->lease = i;
plv->pos = (i < 5) ? i : 5;
plv->value = i;
pthread_create(&prods[i], 0, prod, (void*) plv);
}
for (i = 1; i <= 10; ++i) {
pthread_create(&cons[i], 0, read, (void*) i);
}
pthread_create(&garb, 0, garbage, (void*) 2);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t escaped = PTHREAD_MUTEX_INITIALIZER;
void initSaucer(struct saucer *ship, int row, int delay) {
strncpy(ship->message, SAUCER, SAUCER_LEN);
ship->length = SAUCER_LEN;
ship->row = row;
ship->col = 0;
ship->delay = delay;
ship->hit = 0;
ship->isAlive = 1;
}
void *animateSaucer(void *arg) {
struct saucer *ship = arg;
int len = ship->length+2;
while (1) {
usleep(ship->delay*20000);
pthread_mutex_lock(&mx);
move(ship->row, ship->col);
addch(' ');
addstr(ship->message);
addch(' ');
move(LINES-1, COLS-1);
refresh();
pthread_mutex_unlock(&mx);
ship->col += 1;
if (ship->col + len >= COLS) {
ship->message[len-1] = '\\0';
len = len-1;
}
if (ship->hit) {
pthread_mutex_lock(&mx);
move(ship->row, ship->col-1);
addch(' ');
addch(' ');
addch(' ');
addch(' ');
addch(' ');
addch(' ');
move(LINES-1, COLS-1);
refresh();
pthread_mutex_unlock(&mx);
break;
}
if (ship->col >= COLS) {
pthread_mutex_lock(&escaped);
noEscaped++;
pthread_mutex_unlock(&escaped);
displayInfo();
break;
}
}
ship->isAlive = 0;
pthread_exit(0);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t free_avc_surface_lock = PTHREAD_MUTEX_INITIALIZER;
void
gen_free_avc_surface(void **data)
{
GenAvcSurface *avc_surface;
pthread_mutex_lock(&free_avc_surface_lock);
avc_surface = *data;
if (!avc_surface) {
pthread_mutex_unlock(&free_avc_surface_lock);
return;
}
dri_bo_unreference(avc_surface->dmv_top);
avc_surface->dmv_top = 0;
dri_bo_unreference(avc_surface->dmv_bottom);
avc_surface->dmv_bottom = 0;
free(avc_surface);
*data = 0;
pthread_mutex_unlock(&free_avc_surface_lock);
}
int intel_format_convert(float src, int out_int_bits, int out_frac_bits,int out_sign_flag)
{
unsigned char negative_flag = (src < 0.0) ? 1 : 0;
float src_1 = (!negative_flag)? src: -src ;
unsigned int factor = 1 << out_frac_bits;
int output_value = 0;
unsigned int integer_part = floorf(src_1);
unsigned int fraction_part = ((int)((src_1 - integer_part) * factor)) & (factor - 1) ;
output_value = (integer_part << out_frac_bits) | fraction_part;
if(negative_flag)
output_value = (~output_value + 1) & ((1 <<(out_int_bits + out_frac_bits)) -1);
if(out_sign_flag == 1 && negative_flag)
{
output_value |= negative_flag <<(out_int_bits + out_frac_bits);
}
return output_value;
}
static pthread_mutex_t free_hevc_surface_lock = PTHREAD_MUTEX_INITIALIZER;
void
gen_free_hevc_surface(void **data)
{
GenHevcSurface *hevc_surface;
pthread_mutex_lock(&free_hevc_surface_lock);
hevc_surface = *data;
if (!hevc_surface) {
pthread_mutex_unlock(&free_hevc_surface_lock);
return;
}
dri_bo_unreference(hevc_surface->motion_vector_temporal_bo);
hevc_surface->motion_vector_temporal_bo = 0;
free(hevc_surface);
*data = 0;
pthread_mutex_unlock(&free_hevc_surface_lock);
}
| 1
|
#include <pthread.h>
unsigned int __VERIFIER_nondet_uint();
static int top=0;
static unsigned int arr[(5)];
pthread_mutex_t m;
_Bool flag=(0);
void error(void)
{
ERROR: ;
goto ERROR;
return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
(top==0) ? (1) : (0);
}
int push(unsigned int *stack, int x)
{
if (top==(5))
{
printf("stack overflow\\n");
return (-1);
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (get_top()==0)
{
printf("stack underflow\\n");
return (-2);
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for(i=0; i<(5); i++)
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint()%(5);
if (push(arr,tmp)==(-1))
error();
flag=(1);
pthread_mutex_unlock(&m);
}
}
void *t2(void *arg)
{
int i;
for(i=0; i<(5); i++)
{
pthread_mutex_lock(&m);
if (flag)
{
if (!(pop(arr)!=(-2)))
error();
}
pthread_mutex_unlock(&m);
}
}
int main(void)
{
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 0
|
#include <pthread.h>
struct prodcons
{
int *buffer;
pthread_mutex_t lock;
int readpos;
int writepos;
pthread_cond_t notempty;
pthread_cond_t notfull;
};
struct prodcons buffer;
void prodcons_init(struct prodcons *buf)
{
pthread_mutex_init(&buf->lock, 0);
pthread_cond_init(&buf->notempty, 0);
pthread_cond_init(&buf->notfull, 0);
buf->buffer = (int *)malloc(sizeof(int) * 16);
buf->readpos = 0;
buf->writepos = 0;
}
void put_dataunit(struct prodcons *buf, int data)
{
pthread_mutex_lock(&buf->lock);
if ((buf->writepos + 1) % 16 == buf->readpos)
{
pthread_cond_wait(&buf->notfull, &buf->lock);
}
buf->buffer[buf->writepos] = data;
buf->writepos++;
if (buf->writepos >= 16)
buf->writepos = 0;
pthread_cond_signal(&buf->notempty);
pthread_mutex_unlock(&buf->lock);
}
int get_dataunit(struct prodcons *buf)
{
int data;
pthread_mutex_lock(&buf->lock);
if (buf->writepos == buf->readpos)
{
pthread_cond_wait(&buf->notempty, &buf->lock);
}
data = buf->buffer[buf->readpos];
buf->readpos++;
if (buf->readpos >= 16)
buf->readpos = 0;
pthread_cond_signal(&buf->notfull);
pthread_mutex_unlock(&buf->lock);
return data;
}
void *producer(void *data)
{
int n;
for (n = 0; n < 10000; n++)
{
printf("%d --->\\n", n);
put_dataunit(&buffer, n);
} put_dataunit(&buffer, (- 1));
return 0;
}
void *consumer(void *data)
{
int d;
while (1)
{
d = get_dataunit(&buffer);
if (d == (- 1))
break;
printf("--->%d \\n", d);
}
return 0;
}
int main(int argc, char *argv[])
{
pthread_t th_a, th_b;
void *retval;
prodcons_init(&buffer);
pthread_create(&th_a, 0, producer, 0);
pthread_create(&th_b, 0, consumer, 0);
pthread_join(th_a, &retval);
pthread_join(th_b, &retval);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_mutex_t wrt;
int readcount = 0;
int shared_val;
void *pthread_reader(void *thread_num);
void *pthread_writer(void *thread_num);
void init();
void sleeping();
void msg_waiting (int thread_type, int thread_num);
void msg_num_of_readers (int thread_num, int num_of_readers);
void msg_complete (int thread_type, int thread_num, int written_data);
int main(void) {
pthread_t writer[3], reader[10];
void *writer_ret[3], *reader_ret[10];
int i;
init();
for(i=0;i<3;i++) {
int *num = (int *)malloc(1 * sizeof(int));
*num = i;
pthread_create(&writer[i], 0, pthread_writer, num);
}
for(i=0;i<10;i++) {
int *num = (int *)malloc(1 * sizeof(int));
*num = i;
pthread_create(&reader[i], 0, pthread_reader, num);
}
for(i=0;i<3;i++) pthread_join(writer[i], &writer_ret[i]);
for(i=0;i<10;i++) pthread_join(reader[i], &reader_ret[i]);
pthread_mutex_destroy(&mutex);
pthread_mutex_destroy(&wrt);
}
void *pthread_reader(void *thread_num) {
int reader_num = *(int *)thread_num;
free((int *)thread_num);
sleeping();
msg_waiting(1, reader_num);
pthread_mutex_lock(&mutex);
readcount++;
msg_num_of_readers(reader_num, readcount);
if(readcount ==1) pthread_mutex_lock(&wrt);
pthread_mutex_unlock(&mutex);
msg_complete(1, reader_num, shared_val);
pthread_mutex_lock(&mutex);
readcount--;
msg_num_of_readers(reader_num, readcount);
if(readcount == 0) pthread_mutex_unlock(&wrt);
pthread_mutex_unlock(&mutex);
}
void *pthread_writer(void *thread_num) {
int writer_num = *(int *)thread_num;
free((int *)thread_num);
sleeping();
msg_waiting(0, writer_num);
pthread_mutex_lock(&wrt);
shared_val= rand();
msg_complete(0, writer_num, shared_val);
pthread_mutex_unlock(&wrt);
}
void init() {
struct timespec current_time;
if(pthread_mutex_init(&mutex, 0)) {
printf("mutex init error!\\n");
exit(1);
}
if(pthread_mutex_init(&wrt, 0)) {
printf("mutex init error!\\n");
exit(1);
}
clock_gettime(CLOCK_REALTIME, ¤t_time);
srand(current_time.tv_nsec);
shared_val = 0;
}
void sleeping() {
sleep(1 + rand() % 2);
}
void msg_waiting(int thread_type, int thread_num) {
if(thread_type == 1)
printf("[Reader %02d] --------------------- Waiting\\n", thread_num);
else
printf("[Writer %02d] --------------------- Waiting\\n", thread_num);
}
void msg_num_of_readers(int thread_num, int num_of_readers) {
thread_num, num_of_readers);
}
void msg_complete(int thread_type, int thread_num, int written_data) {
if(thread_type == 1)
printf("[Reader %02d] Read : %d\\n", thread_num, written_data);
else
printf("[Writer %02d] Written : %d\\n", thread_num, written_data);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mon = PTHREAD_MUTEX_INITIALIZER;
int *rList;
int *tList;
pthread_cond_t *cond;
char **threads;
char **resources;
int tsize;
int rsize;
void initDetector( char tName[][ NAME_LIMIT + 1 ], int tCount,
char rName[][ NAME_LIMIT + 1 ], int rCount ){
tsize = tCount;
rsize = rCount;
threads = (char **)malloc( tCount * sizeof(char *) );
for( int i = 0; i < tCount; i++ ){
threads[i] = (char *)malloc( 21 * sizeof(char) );
strcpy( threads[i], tName[i] );
}
resources = (char **)malloc( rCount * sizeof(char *) );
for( int i = 0; i < rCount; i++ ){
resources[i] = (char *)malloc( 21 * sizeof(char) );
strcpy( resources[i],rName[i] );
}
rList = malloc( rCount * sizeof( int ) );
for( int i = 0; i < rCount; i++ ){
rList[i] = -1;
}
tList = malloc( tCount * sizeof( int ) );
for( int i = 0; i < tCount; i++ ){
tList[i] = -1;
}
cond = malloc( rCount * sizeof( pthread_cond_t ) );
for( int i = 0; i < rCount; i++ ){
pthread_cond_init( &cond[i], 0 );
}
}
void destroyDetector(){
free(rList);
free(cond);
for( int i = 0; i < tsize; i++ ){
free(threads[i]);
}
free(threads);
for( int i = 0; i < rsize; i++ ){
free(resources[i]);
}
free(resources);
}
void detect( int tdex, int rdex ){
int isDeadlock = 0;
int running = 1;
int owner;
int reqR;
int rdexTemp = rdex;
owner = rList[rdex];
while( running ){
reqR = tList[owner];
if( reqR == -1 ){
break;
}
owner = rList[reqR];
if( owner == -1 ){
break;
}
if( owner == tdex ){
isDeadlock = 1;
break;
}
}
if( isDeadlock == 1 ){
printf( "%s%s%s", threads[tdex],"->",resources[rdexTemp]);
owner = rList[rdexTemp];
while( owner != tdex ){
printf( "%s%s%s", "->",threads[owner], "->");
reqR = tList[owner];
printf( "%s",resources[reqR]);
owner = rList[reqR];
}
printf("\\n");
printf("Killing %s\\n", threads[tdex]);
for( int i = 0; i < rsize; i++ ){
if( rList[i] == tdex ){
rList[i] = -1;
pthread_cond_signal( &cond[i] );
}
}
pthread_mutex_unlock( &mon );
pthread_exit(0);
} else {
return;
}
}
void acquire( int tdex, int rdex ){
pthread_mutex_lock( &mon );
while( rList[rdex] != -1 ){
detect( tdex, rdex );
tList[tdex] = rdex;
pthread_cond_wait( &cond[rdex], &mon );
}
rList[rdex] = tdex;
tList[tdex] = -1;
pthread_mutex_unlock( &mon );
}
void release( int tdex, int rdex ){
rList[rdex] = -1;
pthread_cond_signal( &cond[rdex] );
}
| 1
|
#include <pthread.h>
int q[3];
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 < 3)
{
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 < 3);
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[3];
int sorted[3];
void producer ()
{
int i, idx;
for (i = 0; i < 3; i++)
{
idx = findmaxidx (source, 3);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 3);
queue_insert (idx);
}
}
void consumer ()
{
int i, idx;
for (i = 0; i < 3; i++)
{
idx = queue_extract ();
sorted[i] = idx;
printf ("m: i %d sorted = %d\\n", i, sorted[i]);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 3);
}
}
void *thread (void * arg)
{
(void) arg;
producer ();
return 0;
}
int main ()
{
pthread_t t;
int i;
__libc_init_poet ();
for (i = 0; i < 3; 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;
}
| 0
|
#include <pthread.h>
long is_in = 0;
long ipert;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* archer(void* arg)
{
int i;
int j = 0;
double x,y;
unsigned int seed = time(0);
for(i = 0; i < ipert; i++)
{
x = ((double)rand_r(&seed)/(32767));
y = ((double)rand_r(&seed)/ (32767));
if(x*x + y*y <= (double)1)
j++;
}
pthread_mutex_lock(&mutex);
is_in = is_in + j;
pthread_mutex_unlock(&mutex);
}
int main(int argc, char *argv[])
{
double Pi;
long val_i,val_t;
val_i = atol(argv[1]);
val_t = atol(argv[2]);
ipert = val_i/val_t;
pthread_t threads[val_t - 1];
int i;
for (i = 0; i < val_t; i++)
{
pthread_create(&threads[i], 0, archer, 0);
}
for (i = 0; i < val_t; i++)
{
pthread_join(threads[i], 0);
}
pthread_mutex_destroy(&mutex);
Pi = 4*((double)is_in/val_i);
printf("\\nPi: %lf\\n",Pi);
return 0;
}
| 1
|
#include <pthread.h>
int arr[1024];
pthread_mutex_t semaphore = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t can_read = PTHREAD_COND_INITIALIZER;
pthread_cond_t can_write = PTHREAD_COND_INITIALIZER;
int n_reading = 0, n_writing = 0;
void *escritor(void *arg){
int i;
int num = *((int *)arg);
for (;;) {
sleep(random() % 3);
pthread_mutex_lock(&semaphore);
while(n_reading)
pthread_cond_wait(&can_write, &semaphore);
n_writing = 1;
for (i = 0; i < 1024; i++) {
arr[i] = num;
}
n_writing = 0;
pthread_cond_broadcast(&can_read);
pthread_mutex_unlock(&semaphore);
}
return 0;
}
void *lector(void *arg)
{
int v, i, err;
int num = *((int *)arg);
for (;;) {
sleep(random() % 3);
pthread_mutex_lock(&semaphore);
while(n_writing)
pthread_cond_wait(&can_read, &semaphore);
n_reading++;
pthread_mutex_unlock(&semaphore);
err = 0;
v = arr[0];
for (i = 1; i < 1024; i++) {
if (arr[i] != v) {
err = 1;
break;
}
}
if (err) printf("Lector %d, error de can_read\\n", num);
else printf("Lector %d, dato %d\\n", num, v);
pthread_mutex_lock(&semaphore);
if(!(--n_reading))
pthread_cond_signal(&can_write);
pthread_mutex_unlock(&semaphore);
}
return 0;
}
int main(){
int i;
pthread_t readers[2], writers[2];
int arg[2];
for (i = 0; i < 1024; i++){
arr[i] = -1;
}
for (i = 0; i < 2; i++){
arg[i] = i;
pthread_create(&readers[i], 0, lector, (void *)&arg[i]);
pthread_create(&writers[i], 0, escritor, (void *)&arg[i]);
}
pthread_join(readers[0], 0);
return 0;
}
| 0
|
#include <pthread.h>
void threadSignalNew(struct ThreadSignal* threadSignal)
{
pthread_mutex_init(&threadSignal->Mutex, 0);
pthread_cond_init(&threadSignal->Condition, 0);
};
void threadSignalDelete(struct ThreadSignal* threadSignal)
{
pthread_cond_destroy(&threadSignal->Condition);
pthread_mutex_destroy(&threadSignal->Mutex);
};
void threadSignalLock(struct ThreadSignal* threadSignal)
{
pthread_mutex_lock(&threadSignal->Mutex);
}
void threadSignalUnlock(struct ThreadSignal* threadSignal)
{
pthread_mutex_unlock(&threadSignal->Mutex);
}
void threadSignalFire(struct ThreadSignal* threadSignal)
{
pthread_cond_signal(&threadSignal->Condition);
}
void threadSignalWait(struct ThreadSignal* threadSignal)
{
pthread_cond_wait(&threadSignal->Condition, &threadSignal->Mutex);
}
| 1
|
#include <pthread.h>
struct stresser_priv {
void *fnpriv;
int fnrc;
int wait;
pthread_cond_t *cond;
pthread_mutex_t *mutex;
pthread_t thread;
struct stresser_unit *u;
int *count;
};
static void *_stresser_unit(void *p)
{
struct stresser_priv *priv = p;
int rc;
if (priv->wait) {
pthread_mutex_lock(priv->mutex);
*priv->count = *priv->count + 1;
rc = pthread_cond_wait(priv->cond, priv->mutex);
pthread_mutex_unlock(priv->mutex);
if (rc)
return (void *)1;
}
priv->fnrc = priv->u->fn(priv->fnpriv);
return 0;
}
int stresser(struct stresser_config *cfg, struct stresser_unit *set,
int n_unit, void *fnpriv)
{
struct stresser_priv *priv;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int threads = 0, i, u, highest, rc = 0, count = 0, tries;
if (n_unit == 0)
return EINVAL;
switch (cfg->distribution) {
case STRESSD_RANDOM:
srand(time(0));
threads = cfg->threads;
break;
case STRESSD_FIXED:
threads = 0;
for (i = 0; i < n_unit; i++) {
threads += set[i].d.number;
set[i]._reserved = set[i].d.number;
}
break;
case STRESSD_PROP:
for (i = 0; i < n_unit; i++) {
set[i]._reserved = (set[i].d.proportion * 100) / (cfg->threads * 100);
threads += set[i]._reserved;
}
if (threads < cfg->threads)
set[0]._reserved += (cfg->threads - threads);
break;
}
if (threads == 0)
return EINVAL;
priv = calloc(sizeof(*priv), threads);
if (priv == 0)
return ENOMEM;
for (i = 0; i < threads; i++) {
priv[i].fnpriv = fnpriv;
priv[i].count = &count;
if (cfg->stress_type == STRESST_HORDE) {
priv[i].cond = &cond;
priv[i].mutex = &mutex;
priv[i].wait = 1;
}
switch (cfg->distribution) {
case STRESSD_RANDOM:
highest = -1;
for (tries = 50; tries; tries--) {
int r;
r = rand();
for (u = 0; (u < n_unit); u++) {
if (!(r % (11 - set[u].d.chance))) {
if (highest == -1)
highest = u;
else if (set[u].d.chance > set[highest].d.chance)
highest = u;
}
}
if (highest != -1)
break;
}
if (!tries)
highest = 0;
priv[i].u = &set[highest];
break;
case STRESSD_FIXED:
case STRESSD_PROP:
for (u = 0; u < n_unit; u++)
if (set[u]._reserved)
break;
if (u == n_unit) {
fprintf(stderr, "Internal error: %s:%i\\n",
"stresser.c", 144);
exit(1);
}
priv[i].u = &set[u];
set[u]._reserved--;
break;
}
if (priv[i].u->fnpriv)
priv[i].fnpriv = priv[i].u->fnpriv;
}
for (i = 0; i < threads; i++) {
if (pthread_create(&priv[i].thread, 0, _stresser_unit,
&priv[i])) {
int e = errno;
while (--i >= 0)
pthread_cancel(priv[i].thread);
return e;
}
}
if (cfg->stress_type == STRESST_HORDE) {
while (1) {
pthread_mutex_lock(&mutex);
if (count == threads) {
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
break;
}
pthread_mutex_unlock(&mutex);
pthread_yield();
}
}
for (i = 0; i < threads; i++) {
if (!pthread_join(priv[i].thread, 0))
if (priv[i].fnrc) {
fprintf(stderr, "Thread %i returned error "
"(%i, %s)\\n", i, priv[i].fnrc,
strerror(priv[i].fnrc));
rc = 1;
}
}
return rc;
}
| 0
|
#include <pthread.h>
struct Buffer_Circ {
int buffer[BUFSIZE];
int bufIN, bufOUT;
int contador;
};
void initbuffer( struct Buffer_Circ *buff) {
pthread_mutex_lock(&buffer_lock);
int i;
for(i=0; i<BUFSIZE; i++){
(*buff).buffer[i] = -1;
}
(*buff).bufIN = 0;
(*buff).bufOUT = 0;
(*buff).contador = 0;
pthread_mutex_unlock(&buffer_lock);
}
int get_item(int* x, struct Buffer_Circ *buff) {
int nxtOUT = (*buff).bufOUT % BUFSIZE;
pthread_mutex_lock(&buffer_lock);
if( (*buff).contador > 0){
*x = (*buff).buffer[nxtOUT];
(*buff).bufOUT = (nxtOUT + 1) % BUFSIZE;
(*buff).contador = (*buff).contador - 1;
pthread_mutex_unlock(&buffer_lock);
return 0;
}
else {
pthread_mutex_unlock(&buffer_lock);
return -1;
}
}
int put_item(int x, struct Buffer_Circ *buff) {
int nxtIN = (*buff).bufIN % BUFSIZE;
pthread_mutex_lock(&buffer_lock);
if( (*buff).contador < BUFSIZE ){
(*buff).buffer[nxtIN] = x;
(*buff).bufIN = (nxtIN + 1) % BUFSIZE;
(*buff).contador = (*buff).contador + 1;
pthread_mutex_unlock(&buffer_lock);
return 0;
}
else {
pthread_mutex_unlock(&buffer_lock);
return -1;
}
}
bool bc_vacio(struct Buffer_Circ *buff){
pthread_mutex_lock(&buffer_lock);
if( (*buff).contador == 0 ) {
pthread_mutex_unlock(&buffer_lock);
return 1;
}
else {
pthread_mutex_unlock(&buffer_lock);
return 0;
}
}
bool bc_lleno(struct Buffer_Circ *buff){
pthread_mutex_lock(&buffer_lock);
if( (*buff).contador == BUFSIZE ) {
pthread_mutex_unlock(&buffer_lock);
return 1;
}
else {
pthread_mutex_unlock(&buffer_lock);
return 0;
}
}
void print (struct Buffer_Circ *buff){
pthread_mutex_lock(&buffer_lock);
printf("bufIN = %d\\n", (*buff).bufIN );
printf("bufOUT = %d\\n", (*buff).bufOUT );
printf("contador = %d\\n", (*buff).contador );
int i;
for(i=0; i<BUFSIZE; i++){
printf("Posicion %d valor: %d\\n", i, (*buff).buffer[i] );
}
printf("------------------------------------------------------------\\n");
pthread_mutex_unlock(&buffer_lock);
}
int num_elementos (struct Buffer_Circ *buff){
pthread_mutex_lock(&buffer_lock);
pthread_mutex_unlock(&buffer_lock);
return buff->contador;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condc, condp = PTHREAD_COND_INITIALIZER;
struct cArray {
unsigned int *array;
int offset;
int size;
};
struct object {
int thread;
int n;
struct cArray *arr;
};
void* produce(void *p){
srand(time(0));
struct object *oPtr = p;
int n = oPtr->n;
int thread = oPtr->thread;
unsigned int total = 0;
int i = 0;
for (i = 0; i < n; i++){
pthread_mutex_lock(&mutex);
while (oPtr->arr->size == 5){
pthread_cond_wait(&condp, &mutex);
}
unsigned int r = rand() % 100;
oPtr->arr->array[oPtr->arr->offset] = r;
oPtr->arr->offset++;
if (oPtr->arr->offset == 5){
oPtr->arr->offset = 0;
}
oPtr->arr->size++;
pthread_cond_signal(&condc);
pthread_mutex_unlock(&mutex);
printf("Producer thread %i produced a %u\\n", thread, r);
sleep(rand()%2);
total += r;
}
printf("Total produced by producer thread %i = %u\\n", thread, total);
pthread_exit((void*)0);
}
void* consume(void *c){
struct object *oPtr = c;
int n = oPtr->n;
int thread = oPtr->thread;
unsigned int total = 0;
int i = 0;
for (i = 0; i < n; i++){
pthread_mutex_lock(&mutex);
unsigned int c;
while (oPtr->arr->size == 0){
pthread_cond_wait(&condc, &mutex);
}
if (oPtr->arr->offset == 0){
c = oPtr->arr->array[4];
oPtr->arr->offset = 4;
}
else {
oPtr->arr->offset--;
c = oPtr->arr->array[oPtr->arr->offset];
}
oPtr->arr->size--;
pthread_cond_signal(&condp);
pthread_mutex_unlock(&mutex);
printf("Consumer thread %i consumed a %u\\n", thread, c);
sleep(rand()%2);
total += c;
}
printf("Total consumed by consumer thread %i = %u\\n", thread, total);
pthread_exit((void*)0);
}
int main(int argc, char *argv[])
{
int n;
if (argc == 2)
n = atoi(argv[1]);
else
n = 10;
struct cArray cArr;
cArr.array = (unsigned int*)malloc((sizeof(unsigned int))*5);
cArr.offset = 0;
cArr.size = 0;
struct object o1;
struct object o2;
struct object o3;
struct object o4;
o1.thread = 1;
o2.thread = 2;
o3.thread = 3;
o4.thread = 4;
if (n%2 != 0)
o1.n = n/2 + 1;
else
o1.n = n/2;
o2.n = n/2;
if (n%2 != 0)
o3.n = n/2 + 1;
else
o3.n = n/2;
o4.n = n/2;
o1.arr = &cArr;
o2.arr = &cArr;
o3.arr = &cArr;
o4.arr = &cArr;
void* return1;
void* return2;
void* return3;
void* return4;
pthread_t thread1;
pthread_t thread2;
pthread_t thread3;
pthread_t thread4;
pthread_create(&thread1, 0, produce, (void *)&o1);
pthread_create(&thread2, 0, produce, (void *)&o2);
pthread_create(&thread3, 0, consume, (void *)&o3);
pthread_create(&thread4, 0, consume, (void *)&o4);
pthread_join(thread1, &return1);
pthread_join(thread2, &return2);
pthread_join(thread3, &return3);
pthread_join(thread4, &return4);
free(cArr.array);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
pthread_exit((void*)0);
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.