text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
void validaParametrosInput(int argc, char *argv[], int *cantVias);
void createThreads( pthread_t **thread_id, int count);
void waitThreads(pthread_t *thread_id, int count);
void *thread_function(void *dummyPtr);
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int semID;
int main(int argc, char *argv[])
{
key_t keySem;
pthread_t *thread_id;
int cantVias = 0;
validaParametrosInput(argc, argv, &cantVias);
keySem = creo_clave(1333);
semID = sem_create(keySem, cantVias);
for(int i=0; i < cantVias; i++)
{
printf("Entro i \\n");
sem_wait(&semID,0);
}
createThreads(&thread_id, cantVias);
for(int i=0; i< cantVias; i++)
{
sem_post(&semID,0);
}
waitThreads(&thread_id, cantVias);
printf("Fin JOIN\\n");
for (int i = 0; i < cantVias; i++)
{
printf("Hola %d\\n", i);
}
return 0;
}
void validaParametrosInput(int argc, char *argv[], int *cantVias)
{
if (argc != 2)
{
printf("\\nDebe recibir el número de vias de peaje\\n\\n");
exit(1);
}
int val = atoi(argv[1]);
*cantVias = val;
if (val < 0)
{
printf("\\nEl nro de vias de peaje no cumple con los permitidos\\n\\n");
exit(1);
}
}
void createThreads(pthread_t **thread_id, int count)
{
(*thread_id) = malloc(sizeof(pthread_t)*count);
for(int i = 0; i < count; i++)
{
pthread_create( &(*thread_id)[i], 0, thread_function, 0 );
}
printf("Threads Creados\\n");
}
void waitThreads(pthread_t *thread_id, int count)
{
for(int j=0; j < count; j++)
{
pthread_join(&thread_id[j], 0);
}
}
void *thread_function(void *dummyPtr)
{
printf("Ejecuto thread number %ld\\n", pthread_self());
pthread_mutex_lock( &mutex1 );
pthread_mutex_unlock( &mutex1 );
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
int totalPorts;
int numThreads;
FILE * outputFile;
{
char *portString;
char *ipAddress;
}portArgs;
void * downloadChunk(void *arguments)
{
portArgs *args = (portArgs*)(arguments);
int port = atoi(args->portString);
char receivedBuffer[1024];
char fullChunk[1024];
char chunkString[128];
pthread_mutex_lock(&lock);
int threadNum = numThreads++;
pthread_mutex_unlock(&lock);
int chunkNum = threadNum;
while(1)
{
int con_fd = 0;
int ret = 0;
struct sockaddr_in serv_addr;
con_fd = socket(PF_INET, SOCK_STREAM, 0);
if (con_fd == -1)
{
perror("Socket Error\\n");
return -1;
}
memset(&serv_addr, 0, sizeof(struct sockaddr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = connect(con_fd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr));
if (ret < 0)
{
perror("Connect error\\n");
return -1;
}
else
{
printf("Successful connection!\\n");
}
snprintf(chunkString, 128, "%d", chunkNum);
send(con_fd, chunkString, strlen(chunkString), 0);
printf("chunkString: %s\\n", chunkString);
int length = recv(con_fd, receivedBuffer, 1024, 0);
printf("Length: %d\\n", length);
if(length <= 0)
{
close(con_fd);
break;
}
do
{
strncat(fullChunk, receivedBuffer, 1024);
length = recv(con_fd, receivedBuffer, 1024, 0);
if(length <= 0)
{
close(con_fd);
break;
}
}while((length > 0) && (strlen(fullChunk) <= 1024));
close(con_fd);
pthread_mutex_lock(&lock);
fseek(outputFile, chunkNum*1024, 0);
fputs(fullChunk, outputFile);
pthread_mutex_unlock(&lock);
chunkNum += totalPorts;
memset(fullChunk, 0, 1024);
memset(receivedBuffer, 0, 1024);
memset(chunkString, 0, 128);
}
}
int main(int argc, char **argv)
{
outputFile = fopen("output.txt", "w");
totalPorts = (argc-1)/2;
pthread_t threadList[totalPorts];
void *readCnts[totalPorts];
int i = 0;
while(1)
{
struct portArgs *newArgs = malloc(sizeof(portArgs));
newArgs->portString = argv[2+i*2];
newArgs->ipAddress = argv[1+i*2];
pthread_create(&threadList[i], 0, downloadChunk, (void*)newArgs);
i++;
if(i >= totalPorts)
{
break;
}
}
i = 0;
while(1)
{
pthread_join(threadList[i], &readCnts[i]);
i++;
if(i >= totalPorts)
{
break;
}
}
fclose(outputFile);
return 0;
}
| 0
|
#include <pthread.h>
struct to_info {
void (*to_fn)(void *);
void * to_arg;
struct timespec to_wait;
};
int
makethread(void * (*fn)(void *), void * arg, int detach)
{
int err;
int detachstate;
pthread_t tid;
pthread_attr_t attr;
if ((err = pthread_attr_init(&attr)) != 0) {
return(err);
}
if (detach != 0) {
detachstate = PTHREAD_CREATE_DETACHED;
}
else {
detachstate = PTHREAD_CREATE_JOINABLE;
}
err = pthread_attr_setdetachstate(&attr, detachstate);
if (err == 0) {
err = pthread_create(&tid, &attr, fn, arg);
}
pthread_attr_destroy(&attr);
return(err);
}
void *
timeout_helper(void * arg)
{
struct to_info * tip;
tip = (struct to_info *)arg;
nanosleep(&tip->to_wait, 0);
(*tip->to_fn)(tip->to_arg);
free(arg);
return((void *)0);
}
void
timeout(const struct timespec * when, void (*func)(void *), void * arg)
{
struct timespec now;
struct timeval tv;
struct to_info * tip;
int err;
gettimeofday(&tv, 0);
now.tv_sec = tv.tv_sec;
now.tv_nsec = tv.tv_usec * 1000;
if ((when->tv_sec > now.tv_sec) ||
(when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) {
tip = (struct to_info *)malloc(sizeof(struct to_info));
if (tip != 0) {
tip->to_fn = func;
tip->to_arg = arg;
tip->to_wait.tv_sec = when->tv_sec - now.tv_sec;
if (when->tv_nsec >= now.tv_nsec) {
tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec;
}
else {
--tip->to_wait.tv_sec;
tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec;
}
err = makethread(timeout_helper, tip, 1);
if (err == 0) {
return;
}
else {
free(tip);
}
}
}
(*func)(arg);
}
pthread_mutexattr_t attr;
pthread_mutex_t mutex;
void
retry(void * arg)
{
pthread_mutex_lock(&mutex);
printf("it is a test\\n");
pthread_mutex_unlock(&mutex);
}
void
maketimespec(struct timespec * tsp, long seconds)
{
struct timeval now;
gettimeofday(&now, 0);
tsp->tv_sec = now.tv_sec;
tsp->tv_nsec = now.tv_usec * 1000;
tsp->tv_sec += seconds;
}
int
main(void)
{
int err;
int condition;
int arg;
struct timespec when;
if ((err = pthread_mutexattr_init(&attr)) != 0) {
printf("pthread_mutexattr_init failed\\n");
return(1);
}
err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
if (err != 0) {
printf("pthread_mutexattr_settype failed\\n");
}
else if ((err = pthread_mutex_init(&mutex, &attr)) != 0) {
printf("pthread_mutex_init failed\\n");
}
pthread_mutexattr_destroy(&attr);
if (err != 0) {
return(1);
}
pthread_mutex_lock(&mutex);
condition = 1;
if (condition) {
maketimespec(&when, 5);
timeout(&when, retry, (void *)arg);
}
pthread_mutex_unlock(&mutex);
sleep(10);
exit(0);
}
| 1
|
#include <pthread.h>
struct pios_semaphore {
uint32_t magic;
pthread_mutex_t mutex;
pthread_cond_t cond;
bool given;
};
struct pios_semaphore *PIOS_Semaphore_Create(void)
{
struct pios_semaphore *s = PIOS_malloc(sizeof(*s));
if (!s) {
return 0;
}
pthread_mutexattr_t attr;
if (pthread_mutexattr_init(&attr)) {
abort();
}
pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT);
if (pthread_mutex_init(&s->mutex, &attr)) {
abort();
}
if (pthread_cond_init(&s->cond, 0)) {
abort();
}
s->given = 1;
s->magic = 0x616d6553;
return s;
}
bool PIOS_Semaphore_Take(struct pios_semaphore *sema, uint32_t timeout_ms)
{
PIOS_Assert(sema->magic == 0x616d6553);
struct timespec abstime;
if (timeout_ms != PIOS_QUEUE_TIMEOUT_MAX) {
clock_gettime(CLOCK_REALTIME, &abstime);
abstime.tv_nsec += (timeout_ms % 1000) * 1000000;
abstime.tv_sec += timeout_ms / 1000;
if (abstime.tv_nsec > 1000000000) {
abstime.tv_nsec -= 1000000000;
abstime.tv_sec += 1;
}
}
pthread_mutex_lock(&sema->mutex);
while (!sema->given) {
if (timeout_ms != PIOS_QUEUE_TIMEOUT_MAX) {
if (pthread_cond_timedwait(&sema->cond,
&sema->mutex, &abstime)) {
pthread_mutex_unlock(&sema->mutex);
return 0;
}
} else {
pthread_cond_wait(&sema->cond, &sema->mutex);
}
}
sema->given = 0;
pthread_mutex_unlock(&sema->mutex);
return 1;
}
bool PIOS_Semaphore_Give(struct pios_semaphore *sema)
{
bool old;
PIOS_Assert(sema->magic == 0x616d6553);
pthread_mutex_lock(&sema->mutex);
old = sema->given;
sema->given = 1;
pthread_cond_signal(&sema->cond);
pthread_mutex_unlock(&sema->mutex);
return !old;
}
bool PIOS_Semaphore_Take_FromISR(struct pios_semaphore *sema, bool *woken)
{
bool ret = PIOS_Semaphore_Take(sema, 0);
if (ret && woken) {
*woken = 1;
}
return ret;
}
bool PIOS_Semaphore_Give_FromISR(struct pios_semaphore *sema, bool *woken)
{
bool ret = PIOS_Semaphore_Give(sema);
if (ret && woken) {
*woken = 1;
}
return ret;
}
| 0
|
#include <pthread.h>
extern char **environ;
pthread_mutex_t env_mutex;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
static void thread_init(void)
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&env_mutex, &attr);
pthread_mutexattr_destroy(&attr);
}
int getenv_r(const char *name, char *buf, int buflen)
{
int i, len, olen;
pthread_once(&init_done, thread_init);
len = strlen(name);
pthread_mutex_lock(&env_mutex);
for (i = 0; environ[i] != 0; i++) {
if ((strncmp(name, environ[i], len) == 0) &&
environ[i][len] == '=') {
olen = strlen(&environ[i][len+1]);
if (olen > buflen) {
pthread_mutex_unlock(&env_mutex);
return(ENOSPC);
}
strcpy(buf, &environ[i][len+1]);
pthread_mutex_unlock(&env_mutex);
return 0;
}
}
pthread_mutex_unlock(&env_mutex);
return ENOENT;
}
void *thd(void *arg)
{
char buf[4096];
if (getenv_r("SHELL", buf, 4096) == 0) printf("SHELL = %s\\n", buf);
if (getenv_r("TERM_PROGRAM", buf, 4096) == 0) printf("TERM_PROGRAM = %s\\n", buf);
if (getenv_r("MANPATH", buf, 4096) == 0) printf("MANPATH = %s\\n", buf);
if (getenv_r("TERM", buf, 4096) == 0) printf("TERM = %s\\n", buf);
if (getenv_r("PWD", buf, 4096) == 0) printf("PWD = %s\\n", buf);
pthread_exit((void *)0);
}
int main(void)
{
int err;
pthread_t tid1, tid2;
pthread_attr_t thd_attr;
err = pthread_attr_init(&thd_attr);
if (err != 0)
return err;
err = pthread_attr_setdetachstate(&thd_attr, PTHREAD_CREATE_DETACHED);
if (err != 0)
return err;
err = pthread_create(&tid1, &thd_attr, thd, 0);
if (err != 0)
return err;
err = pthread_create(&tid2, &thd_attr, thd, 0);
if (err != 0)
return err;
pthread_attr_destroy(&thd_attr);
sleep(1);
return 0;
}
| 1
|
#include <pthread.h>
int number;
pthread_mutex_t mu= PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t sig_consumer= PTHREAD_COND_INITIALIZER;
pthread_cond_t sig_producer= PTHREAD_COND_INITIALIZER;
void *consumer(void *dummy)
{
int printed= 0;
" now\\"\\n", pthread_self());
while (1)
{
pthread_mutex_lock(&mu);
pthread_cond_signal(&sig_producer);
pthread_cond_wait(&sig_consumer, &mu);
pthread_mutex_unlock(&mu);
if (number == 10)
{
printf("Consumer done.. !!\\n");
break;
}
}
}
void *producer(void *dummy)
{
" now\\"\\n", pthread_self());
while (1)
{
pthread_mutex_lock(&mu);
number ++;
printf("Producer : %d\\n", number);
pthread_cond_signal(&sig_consumer);
if (number != 10)
pthread_cond_wait(&sig_producer, &mu);
pthread_mutex_unlock(&mu);
if (number == 10)
{
printf("Producer done.. !!\\n");
break;
}
}
}
void main()
{
int rc, i;
pthread_t t[2];
number= 0;
if ((rc= pthread_create(&t[0], 0, consumer, 0)))
printf("Error creating the 2nd consumer thread..\\n");
if ((rc= pthread_create(&t[0], 0, consumer, 0)))
printf("Error creating the 1st consumer thread..\\n");
if ((rc= pthread_create(&t[1], 0, producer, 0)))
printf("Error creating the producer thread..\\n");
for (i= 0; i < 2; i ++)
pthread_join(t[i], 0);
printf("Done..\\n");
}
| 0
|
#include <pthread.h>
int stoj = 0;
char rodic1, rodic2;
int pocet = 0;
int organizmySuma[3] = {0};
pthread_t organizmy[1000];
int ROZMNOZOVAT = 1;
int PARIT = 0;
int rodicia = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condRozmnozovanie = PTHREAD_COND_INITIALIZER;
pthread_cond_t condPartner = PTHREAD_COND_INITIALIZER;
void *organizmus_A();
void *organizmus_B();
void *organizmus_C();
void rozmnoz(char typ) {
if(stoj){
return;
}
pthread_mutex_lock(&mutex);
while(!ROZMNOZOVAT){
if(stoj){
return;
}
pthread_cond_wait(&condRozmnozovanie, &mutex);
}
rodicia++;
if(rodicia == 1){
rodic1 = typ;
printf("Organizmus %c: rozmnozujem sa ako rodic 1\\n", rodic1);
while(!PARIT){
if(stoj){
return;
}
pthread_cond_wait(&condPartner, &mutex);
}
} else if(rodicia == 2){
rodic2 = typ;
printf("Organizmus %c: rozmnozujem sa ako rodic 2\\n", rodic2);
ROZMNOZOVAT = 0;
PARIT = 1;
pthread_cond_signal(&condPartner);
}
rodicia--;
if(rodicia == 0){
if(rodic1 != 'A' && rodic2 != 'A'){
printf("Vytvoril sa novy organizmus A.\\n");
pthread_create(&organizmy[pocet], 0, &organizmus_A, 0);
pocet++;
organizmySuma[0]++;
}
if(rodic1 != 'B' && rodic2 != 'B'){
printf("Vytvoril sa novy organizmus B.\\n");
pthread_create(&organizmy[pocet], 0, &organizmus_B, 0);
pocet++;
organizmySuma[1]++;
}
if(rodic1 != 'C' && rodic2 != 'C'){
printf("Vytvoril sa novy organizmus C.\\n");
pthread_create(&organizmy[pocet], 0, &organizmus_C, 0);
pocet++;
organizmySuma[2]++;
}
printf("\\n");
PARIT = 0;
ROZMNOZOVAT = 1;
pthread_cond_broadcast(&condRozmnozovanie);
}
pthread_mutex_unlock(&mutex);
}
void *organizmus_A() {
while (!stoj) {
sleep(1);
rozmnoz('A');
}
return 0;
}
void *organizmus_B() {
while (!stoj) {
sleep(2);
rozmnoz('B');
}
return 0;
}
void *organizmus_C() {
while (!stoj) {
sleep(3);
rozmnoz('C');
}
return 0;
}
int main(void) {
int i;
for (i=0; i<1; i++){
pthread_create(&organizmy[pocet], 0, &organizmus_A, 0);
pocet++;
}
organizmySuma[0] = 1;
for (i=0; i<2; i++){
pthread_create(&organizmy[pocet], 0, &organizmus_B, 0);
pocet++;
}
organizmySuma[1] = 2;
for (i=0; i<3; i++){
pthread_create(&organizmy[pocet], 0, &organizmus_C, 0);
pocet++;
}
organizmySuma[2] = 3;
sleep(10);
pthread_mutex_lock(&mutex);
printf("Koniec simulacie !!!\\n");
stoj = 1;
pthread_cond_broadcast(&condRozmnozovanie);
pthread_cond_broadcast(&condPartner);
pthread_mutex_unlock(&mutex);
for (i=0; i<pocet; i++) pthread_join(organizmy[i], 0);
printf("Pocet Organimov: %d\\n", pocet);
printf("Organizmov A: %d\\n", organizmySuma[0]);
printf("Organizmov B: %d\\n", organizmySuma[1]);
printf("Organizmov C: %d\\n", organizmySuma[2]);
exit(0);
}
| 1
|
#include <pthread.h>
int shared = 0;
pthread_mutex_t lock;
pthread_cond_t cond;
int thread_num;
char buf[80];
} tinfo_t;
void*
thread1_func(void *arg)
{
tinfo_t *tmp = (tinfo_t*)arg;
printf("Thread %u - going to wait for shared data to be >= %u\\n",
tmp->thread_num, 15);
pthread_mutex_lock(&lock);
while (shared < 15) {
printf("T1: shared:%u not >= MAX:%u, waiting\\n", shared, 15);
pthread_cond_wait(&cond, &lock);
printf("T1: woken up - need to recheck condition\\n");
}
printf("T1: Woken up - condition met! Shared data now: %u\\n", shared);
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
void*
thread2_func(void *arg)
{
tinfo_t *tmp = (tinfo_t*)arg;
int done = 0;
printf("Thread %u - going to slowly inc shared data to be >= %u\\n",
tmp->thread_num, 15);
while (0 == done) {
int add = rand() % 7;
printf("T2: Adding %u to shared data\\n", add);
pthread_mutex_lock(&lock);
shared += add;
if (shared > 15) {
printf("T2: Finally, shared:%u eclipes MAX:%u, signal other thread\\n", shared, 15);
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
done = 1;
} else {
printf("T2: shared:%u does not eclipse MAX:%u, sleep 2 and keep adding\\n", shared, 15);
pthread_mutex_unlock(&lock);
sleep(2);
}
}
pthread_exit(0);
}
int main()
{
int ret = 0;
int i = 0;
printf("Shared data initially starts at %u, MAX_VAL=%u\\n",
shared, 15);
ret = pthread_mutex_init(&lock, 0);
if (0 != ret) {
printf("Mutex init failed: %u\\n", ret);
return 0;
}
ret = pthread_cond_init(&cond, 0);
if (0 != ret) {
printf("Cond var init failed: %u\\n", ret);
return 0;
}
tinfo_t thread_args[2];
for (i = 0; i < 2; i++) {
thread_args[i].thread_num = i+1;
sprintf(thread_args[i].buf, "Thread Number: %u", i);
}
pthread_t tids[2] = { 0 };
if (0 == pthread_create(&tids[0], 0, thread1_func, (void*)&thread_args[0])) {
printf("T1 created, sleeping for a couple seconds to allow it to run before creating Thread2\\n");
sleep(2);
} else {
printf("T1 create failed: ret=%u\\n", ret);
}
if (0 == pthread_create(&tids[1], 0, thread2_func, (void*)&thread_args[1])) {
printf("T2 created\\n");
} else {
printf("T2 create failed: ret=%u\\n", ret);
}
for (i = 0; i < 2; i++) {
pthread_join(tids[i], 0);
}
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t beers_lock = PTHREAD_MUTEX_INITIALIZER;
void error(char *msg)
{
fprintf(stderr, "%s, %s\\n", msg, strerror(errno));
exit(1);
}
int beers = 2000000;
void* drink_lots(void *a)
{
pthread_mutex_lock(&beers_lock);
int i;
for (i = 0; i < 100000; i++) {
beers--;
}
pthread_mutex_unlock(&beers_lock);
printf("beers = %i \\n", beers);
return 0;
}
int main()
{
pthread_t threads[20];
int t;
printf("%i bottles of beer on the wall\\n%i bottles of beer\\n", beers, beers);
for (t = 0; t < 20; t++) {
if(pthread_create(&threads[t], 0, drink_lots, 0))
error("Can't create thread");
}
void* result;
for (t = 0; t < 20; t++) {
if(pthread_join(threads[t], &result))
error("cant join thread");
}
printf("There are now %i bottels of beer on the wall\\n", beers);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
int sum = 0;
void *countgold(void *param) {
int i;
int local = 0;
for (i = 0; i < 10000000; i++)
local++;
pthread_mutex_lock(&m);
sum += local;
pthread_mutex_unlock(&m);
return 0;
}
int main(int argc, char const *argv[]) {
pthread_t tid1, tid2;
pthread_create(&tid1, 0, countgold, 0);
pthread_create(&tid2, 0, countgold, 0);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
printf("ARRRRG sum is %d\\n", sum);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void cleanup(void *p)
{
printf("\\n %s: \\n",__func__);
pthread_mutex_unlock(&mutex);
printf("Cleanup: mutex released\\n" );
}
void *thread_func1(void *ignored_argument)
{
int s;
printf("\\n %s: \\n",__func__);
pthread_cleanup_push(cleanup, 0);
pthread_mutex_lock(&mutex);
printf("Thread 1: mutex acquired\\n");
sleep(10);
pthread_mutex_unlock(&mutex);
pthread_cleanup_pop(0);
printf("Thread 1: mutex released\\n");
pthread_exit(0);
}
void *thread_func2(void *ignored_argument)
{
int s;
printf("\\n %s: \\n",__func__);
sleep(5);
pthread_mutex_lock(&mutex);
printf("Thread 2: mutex acquired \\n");
pthread_mutex_unlock(&mutex);
printf("Thread 2: mutex \\n");
return 0;
}
int main(void)
{
pthread_t thr1,thr2;
void *res;
int s;
s = pthread_create(&thr1, 0, &thread_func1, 0);
if (s != 0) {
perror("pthread_create");
exit(1);
}
s = pthread_create(&thr2, 0, &thread_func2, 0);
if (s != 0) {
perror("pthread_create");
exit(1);
}
sleep(2);
printf("\\nmain(): sending cancellation request\\n");
s = pthread_join(thr1, &res);
if (s != 0) {
perror("pthread_join");
exit(1);
}
if (res == PTHREAD_CANCELED)
printf("main(): thread was canceled\\n");
else
printf("main(): thread wasn't canceled (shouldn't happen!)\\n");
s = pthread_join(thr2, &res);
if (s != 0) {
perror("pthread_join");
exit(1);
}
return 0;
}
| 1
|
#include <pthread.h>
void process__(struct tcp_stream *a_tcp, int type);
void process_request(struct tcp_stream *a_tcp) {
struct half_stream *hlf = &a_tcp->server;
struct threads *p = 0;
if(hlf->offset==0) {
if(hlf->count <= 4) {
a_tcp->client.collect--;
a_tcp->server.collect--;
fprintf(stderr, "Drop it (too short)\\n");
return;
}
if(!(hlf->data[0]=='G' && hlf->data[1]=='E' && hlf->data[2]=='T' && hlf->data[3]==' ')) {
a_tcp->client.collect--;
a_tcp->server.collect--;
fprintf(stderr, "Drop it (not GET)\\n");
return;
}
fprintf(stderr, "Follow it\\n");
}
process__(a_tcp, 0);
}
void process_response(struct tcp_stream *a_tcp) {
process__(a_tcp, 1);
}
void process_close(struct tcp_stream *a_tcp) {
fprintf(stderr, "Close it\\n");
process__(a_tcp, 4);
}
void process__(struct tcp_stream *a_tcp, int type) {
pthread_mutex_lock(&q_mutex);
if(q_tail == 0) {
if(q_head != 0) {
fprintf(stderr, "Mistake in link list\\n");
exit(1);
}
q_tail = (struct queue *) malloc(sizeof(struct queue));
if(q_tail == 0) {
fprintf(stderr, "Cannot malloc q_head.\\n");
exit(1);
}
q_head = q_tail;
} else {
q_tail->next = (struct queue *) malloc(sizeof(struct queue));
if(q_tail->next == 0) {
fprintf(stderr, "Cannot malloc q_tail.\\n");
exit(1);
}
q_tail = q_tail->next;
}
memset(q_tail, 0, sizeof(struct queue));
q_tail->addr = a_tcp->addr;
q_tail->inout = type;
switch(type) {
case 0:
q_tail->data_length = a_tcp->server.count - a_tcp->server.offset;
memcpy(q_tail->data, a_tcp->server.data, q_tail->data_length);
break;
case 1:
q_tail->data_length = a_tcp->client.count - a_tcp->client.offset;
memcpy(q_tail->data, a_tcp->client.data, q_tail->data_length);
break;
case 2:
break;
case 3:
break;
case 4:
break;
default:
fprintf(stderr, "Unknown type code\\n");
exit(1);
}
if(q_tail->data_length > 1500) {
fprintf(stderr, "Too big packet.\\n");
exit(1);
}
pthread_cond_signal(&ctrl_cond);
pthread_mutex_unlock(&q_mutex);
}
void tcp_callback(struct tcp_stream *a_tcp, void **arg) {
char buf[1024];
strncpy((char *)&buf, (char *)adres(a_tcp->addr), 1024);
switch(a_tcp->nids_state){
case NIDS_JUST_EST:
a_tcp->client.collect++;
a_tcp->server.collect++;
fprintf(stderr, "%s established\\n", buf);
break;
case NIDS_DATA:
if(a_tcp->server.count_new){
fprintf(stderr, "Send data...\\n");
process_request(a_tcp);
break;
}
if(a_tcp->client.count_new){
fprintf(stderr, "Receive data...\\n");
process_response(a_tcp);
break;
}
fprintf(stderr, "Unknown NIDS_DATA direction.");
exit(1);
break;
case NIDS_CLOSE:
case NIDS_RESET:
case NIDS_TIMED_OUT:
fprintf(stderr, "%s closing\\n", buf);
process_close(a_tcp);
break;
case NIDS_EXITING:
fprintf(stderr,"NIDS exit\\n");
break;
default:
fprintf(stderr,"Unknown NIDS state\\n");
exit(1);
}
}
| 0
|
#include <pthread.h>
extern int makethread(void *(*)(void *), void *);
struct to_info {
void (*to_fn)(void *);
void *to_arg;
struct timespec to_wait;
};
int global = 0;
void clock_gettime(struct timespec *tsp)
{
struct timeval tv;
gettimeofday(&tv, 0);
tsp -> tv_sec = tv.tv_sec;
tsp -> tv_nsec = tv.tv_usec * 1000;
}
void *timeout_helper(void *arg)
{
struct to_info *tip;
tip = (struct to_info*)arg;
nanosleep(&tip->to_wait, 0);
(*tip->to_fn)(tip->to_arg);
free(arg);
return (void *)0;
}
void
timeout(const struct timespec *when, void (*func)(void *), void *arg)
{
struct timespec now;
struct to_info *tip;
int err;
clock_gettime(&now);
if ((when -> tv_sec > now.tv_sec) ||
(when -> tv_sec == now.tv_sec && when -> tv_nsec > now.tv_nsec)) {
tip = malloc(sizeof(struct to_info));
if (tip != 0) {
tip -> to_fn = func;
tip -> to_arg = arg;
tip -> to_wait.tv_sec = when -> tv_sec - now.tv_sec;
if (when -> tv_nsec >= now.tv_nsec) {
tip -> to_wait.tv_nsec = when -> tv_nsec - now.tv_nsec;
} else {
tip -> to_wait.tv_sec--;
tip -> to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec;
}
err = makethread(timeout_helper, (void *)tip);
if (err == 0)
return;
else
free(tip);
}
}
(*func)(arg);
}
pthread_mutexattr_t attr;
pthread_mutex_t mutex;
void retry(void *arg)
{
pthread_mutex_lock(&mutex);
global++;
pthread_mutex_unlock(&mutex);
}
int main(void)
{
int err, condition, arg;
struct timespec when;
condition = 0;
arg = 0;
if ((err = pthread_mutexattr_init(&attr)) != 0)
err_exit(err, "pthread_mutexattr_init failed");
if ((err = pthread_mutexattr_settype(&attr,
PTHREAD_MUTEX_RECURSIVE)) != 0)
err_exit(err, "pthread_mutexattr_settype failed");
if ((err = pthread_mutex_init(&mutex, &attr)) != 0)
err_exit(err, "can't create recursive mutex");
pthread_mutex_lock(&mutex);
while (condition++ < 10) {
clock_gettime(&when);
when.tv_sec += 10;
timeout(&when, retry, (void *)(unsigned long)arg++);
}
pthread_mutex_unlock(&mutex);
sleep(30);
printf("global = %d\\n", global);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gateaux_prets = PTHREAD_COND_INITIALIZER;
int gateaux = 0;
int stop = 0;
void* enfant(void *arg) {
int id = *((int*) arg);
int mange = 0;
while(1) {
pthread_mutex_lock(&mutex);
while(gateaux == 0) {
if (stop == 1) {
pthread_mutex_unlock(&mutex);
goto fin;
}
pthread_mutex_unlock(&mutex);
usleep(100000);
pthread_mutex_lock(&mutex);
}
if (gateaux > 0) {
gateaux--;
mange++;
printf("L'enfant %d a mangé un gateau\\n", id);
} else {
printf("L'enfant %d n'a pas eu de gateau\\n", id);
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
fin :
return *((void**) &mange);
}
void* parent(void *arg) {
int i;
for (i = 0; i < 4; i++) {
pthread_mutex_lock(&mutex);
gateaux += 4;
printf("Le parent a préparé des gateaux\\n");
pthread_mutex_unlock(&mutex);
sleep(2);
}
pthread_mutex_lock(&mutex);
stop = 1;
pthread_mutex_unlock(&mutex);
return 0;
}
int main() {
int i, nb[5];
void* ret[5];
pthread_t tid[5 + 1];
for (i = 0; i < 5; i++) {
nb[i] = i;
pthread_create(&tid[i], 0, enfant, (void*) &nb[i]);
}
pthread_create(&tid[i], 0, parent, 0);
for (i = 0; i < 5; i++) {
pthread_join(tid[i], &ret[i]);
printf("L'enfant %d a mangé %d gateaux\\n", i, *((int*) &ret[i]));
}
pthread_join(tid[i], 0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
static int gpio_ext_write(struct gpio_ext *gpioExt, uint16_t values) {
static pthread_mutex_t funcMutex = PTHREAD_MUTEX_INITIALIZER;
int ret;
char bytes[2] = { values & 0xFF , values >> 8 };
ret = pthread_mutex_lock(&funcMutex);
if (ret != 0) {
PRINTE("pthread_mutex_lock() failed!");
return ret;
}
ret = i2c_write(gpioExt->i2c, bytes, gpioExt->numPins / 8);
if (ret != 0) {
pthread_mutex_unlock(&funcMutex);
return ret;
}
gpioExt->values = values;
pthread_mutex_unlock(&funcMutex);
return 0;
}
static int gpio_ext_read(struct gpio_ext *gpioExt) {
static pthread_mutex_t funcMutex = PTHREAD_MUTEX_INITIALIZER;
int ret;
char bytes[2] = { 0, 0 };
uint16_t values;
int old, new;
ret = pthread_mutex_lock(&funcMutex);
if (ret != 0) {
PRINTE("pthread_mutex_lock() failed!");
return ret;
}
ret = i2c_read(gpioExt->i2c, bytes, gpioExt->numPins / 8);
if (ret != 0) {
pthread_mutex_unlock(&funcMutex);
return ret;
}
values = gpioExt->values;
gpioExt->values = ((uint16_t)bytes[1] << 8) | (uint16_t)bytes[0];
for (int i = 0; i < gpioExt->numPins; i++) {
old = values & (1 << i);
new = gpioExt->values & (1 << i);
if (gpioExt->irqList[i] && gpioExt->irqList[i]->enabled && gpioExt->irqList[i]->callback &&
gpioExt->irqList[i]->direction == GPIO_DIR_IN &&
(((old > new) && (gpioExt->irqList[i]->sensitivity == GPIO_SEN_FALLING)) ||
((old < new) && (gpioExt->irqList[i]->sensitivity == GPIO_SEN_RISING)) ||
((old != new) && (gpioExt->irqList[i]->sensitivity == GPIO_SEN_BOTH)))) {
gpioExt->irqList[i]->callback(gpioExt->irqList[i]->context);
}
}
pthread_mutex_unlock(&funcMutex);
return 0;
}
int gpio_ext_init(struct gpio_ext *gpioExt, enum pcf857x_pin_count numPins, struct i2c *i2c, int intDebounceTime) {
int ret;
PRINT("pcf857x-0x%02X: Initializing device.\\n", i2c->address);
gpioExt->values = 0xFFFF;
gpioExt->i2c = i2c;
gpioExt->numPins = numPins;
memset(gpioExt->irqList, 0, sizeof(gpioExt->irqList));
ret = gpio_ext_read(gpioExt);
if (ret != 0) {
return ret;
}
if (gpioExt->gpioPin.gpio == 0 || gpioExt->gpioPin.pin == -1) {
return 0;
}
ret = gpio_irq_init(&gpioExt->irq, &gpioExt->gpioPin, (int (*)(void *))&gpio_ext_read, gpioExt, GPIO_DIR_IN, GPIO_SEN_FALLING, intDebounceTime);
if (ret != 0) {
return ret;
}
ret = gpio_irq_enable(&gpioExt->irq, TRUE);
if (ret != 0) {
return ret;
}
return 0;
}
int gpio_ext_uninit(struct gpio_ext *gpioExt) {
int ret;
PRINT("pcf857x-0x%02X: Uninitializing device.\\n", gpioExt->i2c->address);
if (gpioExt->gpioPin.gpio != 0 && gpioExt->gpioPin.pin != -1) {
ret = gpio_irq_uninit(&gpioExt->irq);
if (ret != 0) {
return ret;
}
}
memset(gpioExt, 0, sizeof(*gpioExt));
return 0;
}
int gpio_ext_set_bit(struct gpio_ext *gpioExt, uint8_t bit, uint8_t set) {
int ret;
uint16_t values = gpioExt->values;
PRINTV("pcf857x-0x%02X: Setting bit %u to %u.\\n", gpioExt->i2c->address, bit, set);
values ^= (-set ^ values) & (1 << bit);
ret = gpio_ext_write(gpioExt, values);
return ret;
}
int gpio_ext_set_bits(struct gpio_ext *gpioExt, uint16_t bits, uint16_t value) {
int ret;
uint16_t values = gpioExt->values;
PRINTV("pcf857x-0x%02X: Setting bits 0x%08X to 0x%08X.\\n", gpioExt->i2c->address, bits, value);
values ^= (-bits ^ values) & value;
ret = gpio_ext_write(gpioExt, values);
return ret;
}
int gpio_ext_set_value(struct gpio_ext *gpioExt, uint16_t value) {
int ret;
PRINTV("pcf857x-0x%02X: Setting to 0x%08X.\\n", gpioExt->i2c->address, value);
ret = gpio_ext_write(gpioExt, value);
return ret;
}
int gpio_ext_get_bit(struct gpio_ext *gpioExt, uint8_t bit, uint8_t *set) {
*set = (gpioExt->values & (1 << bit)) ? TRUE : FALSE;
return 0;
}
int gpio_ext_get_bits(struct gpio_ext *gpioExt, uint16_t bits, uint16_t *value) {
*value = gpioExt->values & bits;
return 0;
}
int gpio_ext_get_value(struct gpio_ext *gpioExt, uint16_t *value) {
*value = gpioExt->values;
return 0;
}
int gpio_ext_irq_init(struct gpio_ext_irq *extIrq, struct gpio_ext_pin *gpioExtPin, int (*callback)(void *), void *context, int direction, int sensitivity) {
PRINT("pcf857x-0x%02X: Initializing IRQ on pin %d.\\n", gpioExtPin->gpioExt->i2c->address, gpioExtPin->pin);
extIrq->gpioExtPin = *gpioExtPin;
extIrq->callback = callback;
extIrq->context = context;
extIrq->direction = direction;
extIrq->sensitivity = sensitivity;
extIrq->enabled = FALSE;
gpioExtPin->gpioExt->irqList[gpioExtPin->pin] = extIrq;
return 0;
}
int gpio_ext_irq_uninit(struct gpio_ext_irq *extIrq) {
PRINT("pcf857x-0x%02X: Uninitializing IRQ on pin %d.\\n", extIrq->gpioExtPin.gpioExt->i2c->address, extIrq->gpioExtPin.pin);
extIrq->gpioExtPin.gpioExt->irqList[extIrq->gpioExtPin.pin] = 0;
memset(extIrq, 0, sizeof(*extIrq));
return 0;
}
int gpio_ext_irq_enable(struct gpio_ext_irq *extIrq, bool enable) {
PRINT("pcf857x-0x%02X: %s IRQ on pin %d.\\n", extIrq->gpioExtPin.gpioExt->i2c->address, enable ? "Enabling" : "Disabling", extIrq->gpioExtPin.pin);
extIrq->enabled = enable;
return 0;
}
int gpio_ext_irq_is_enabled(struct gpio_ext_irq *extIrq, bool *enabled) {
*enabled = extIrq->enabled;
return 0;
}
int gpio_ext_pin_set_value(struct gpio_ext_pin *gpioExtPin, bool value) {
int ret;
ret = gpio_ext_set_bit(gpioExtPin->gpioExt, gpioExtPin->pin, value ? 0x1 : 0x0);
return ret;
}
int gpio_ext_pin_get_value(struct gpio_ext_pin *gpioExtPin, bool *value) {
int ret;
ret = gpio_ext_get_bit(gpioExtPin->gpioExt, gpioExtPin->pin, (uint8_t *)value);
return ret;
}
| 1
|
#include <pthread.h>
void* doSomeThing(void *);
pthread_t tid[2];
int counter;
pthread_mutex_t lock;
void* doSomeThing(void *arg)
{
unsigned long i;
pthread_mutex_lock(&lock);
i = 0;
counter += 1;
printf("\\n Job %d started\\n", counter);
for (i=0; i<(0xFFFFFFFF); i++);
printf("\\n Job %d finished\\n", counter);
pthread_mutex_unlock(&lock);
return 0;
}
int main(void)
{
int i = 0;
int err;
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("\\n mutex init failed\\n");
return 1;
}
while (i < 2)
{
err = pthread_create(&(tid[i]), 0, &doSomeThing, 0);
if (err != 0)
printf("\\ncan't create thread :[%s]", strerror(err));
i++;
}
pthread_join(tid[0], 0);
pthread_join(tid[1], 0);
pthread_mutex_destroy(&lock);
return 0;
}
| 0
|
#include <pthread.h>
int p_count=10;
int queue[5];
int q_front=0;
int q_end=0;
int q_size=0;
pthread_mutex_t mutex_var,mutex_p;
pthread_cond_t cond_producer;
pthread_cond_t cond_consumer;
void *producerFunction();
void *consumerFunction();
int producer_lock();
pthread_t thread_id;
pthread_attr_t attributes;
main() {
pthread_t producerThread1,producerThread2,consumerThread;
pthread_mutex_init (&mutex_var,0);
pthread_attr_init (&attributes);
pthread_cond_init (&cond_producer,0);
pthread_cond_init (&cond_consumer,0);
pthread_create(&producerThread1,0,producerFunction,0);
pthread_create(&producerThread2,0,producerFunction,0);
pthread_create(&consumerThread,0,consumerFunction,0);
pthread_join (producerThread1,0);
pthread_join (producerThread2,0);
pthread_join (consumerThread,0);
}
int insertQueue(int data){
if(q_size<5) {
queue[q_end] = data;
q_end = (q_end+1) % 5;
q_size++;
return data;
}
else {
return -1;
}
}
int deQueue(){
int data=-1;
if(q_size > 0) {
data = queue[q_front];
q_front= (q_front+1) % 5;
q_size--;
return data;
}
else {
return -1;
}
}
void *producerFunction()
{
int get,stats;
while (p_count > 0 ) {
pthread_mutex_lock(&mutex_var);
get=producer_lock();
if (q_size == 5) {
pthread_cond_wait(&cond_producer,&mutex_var);
}
stats=insertQueue(get);
if(stats!=-1)
printf("\\n Added to queue : %d by producer thread with ID : %ld \\n",stats , (unsigned long int)pthread_self());
else
printf("\\nProducer error.");
pthread_cond_signal(&cond_consumer);
pthread_mutex_unlock(&mutex_var);
}
pthread_exit(0);
}
int producer_lock()
{
int check = -1;
pthread_mutex_lock(&mutex_p);
check = p_count--;
pthread_mutex_unlock(&mutex_p);
return check;
}
void *consumerFunction() {
int i,value;
while (p_count > 0) {
pthread_mutex_lock(&mutex_var);
if (q_size == 0) {
pthread_cond_wait(&cond_consumer,&mutex_var);
}
value = deQueue();
if(value!=-1)
printf("\\nRemoved from queue : %d by consumer thread with ID : %ld \\n",value, (unsigned long int)pthread_self());
else
printf("\\nConsumer error.");
pthread_cond_signal(&cond_producer);
pthread_mutex_unlock(&mutex_var);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int SocketLevel[5] = {0, 1, 2, 3, 4};
char ICLevelName[5][10] = {"NOLOG", "DEBUG", "INFO", "WARNING", "ERROR"};
pthread_mutex_t mutex_log = PTHREAD_MUTEX_INITIALIZER;
static int ITCAST_Error_GetCurTime(char* strTime)
{
struct tm* tmTime = 0;
size_t timeLen = 0;
time_t tTime = 0;
tTime = time(0);
tmTime = localtime(&tTime);
timeLen = strftime(strTime, 33, "%Y.%m.%d %H:%M:%S", tmTime);
return timeLen;
}
static int ITCAST_Error_OpenFile(int* pf)
{
char fileName[1024];
struct tm* tmTime = 0;
time_t tTime = 0;
char tmpfile[120] = { 0 };
char strTime[12] = { 0 };
memset(fileName, 0, sizeof(fileName));
tTime = time(0);
tmTime = localtime(&tTime);
strftime(strTime, 33, "%Y.%m.%d-", tmTime);
sprintf(tmpfile, "%s%s", strTime, "socketlib.log");
sprintf(fileName, "./%s/%s", "LOG" ,tmpfile);
mkdir("LOG", 0755);
*pf = open(fileName, O_WRONLY|O_CREAT|O_APPEND, 0666);
if(*pf < 0)
{
return -1;
}
return 0;
}
static void ITCAST_Error_Core(const char *file, int line, int level, int status, const char *fmt, va_list args)
{
char str[5120];
int strLen = 0;
char tmpStr[64];
int tmpStrLen = 0;
int pf = 0;
memset(str, 0, 5120);
memset(tmpStr, 0, 64);
tmpStrLen = ITCAST_Error_GetCurTime(tmpStr);
tmpStrLen = sprintf(str, "[%s] ", tmpStr);
strLen = tmpStrLen;
tmpStrLen = sprintf(str+strLen, "[%s] ", ICLevelName[level]);
strLen += tmpStrLen;
if (status != 0)
{
tmpStrLen = sprintf(str+strLen, "[ERRNO is %d] ", status);
}
else
{
tmpStrLen = sprintf(str+strLen, "[SUCCESS] ");
}
strLen += tmpStrLen;
tmpStrLen = vsprintf(str+strLen, fmt, args);
strLen += tmpStrLen;
tmpStrLen = sprintf(str+strLen, " [%s]", file);
strLen += tmpStrLen;
tmpStrLen = sprintf(str+strLen, " [%d]\\n", line);
strLen += tmpStrLen;
if(ITCAST_Error_OpenFile(&pf))
{
return ;
}
write(pf, str, strLen);
close(pf);
return ;
}
void Socket_Log(const char *file, int line, int level, int status, const char *fmt, ...)
{
va_list args;
pthread_mutex_lock(&mutex_log);
if(level == 0)
{
return ;
}
__builtin_va_start((args));
ITCAST_Error_Core(file, line, level, status, fmt, args);
;
pthread_mutex_unlock(&mutex_log);
pthread_mutex_destroy(&mutex_log);
return ;
}
| 0
|
#include <pthread.h>
struct Foo* gs_foo = 0;
int gs_sum = 0;
static pthread_mutex_t gs_sum_guard = PTHREAD_MUTEX_INITIALIZER;
volatile int gs_is_end;
void ReadThreadFunc()
{
struct Foo* foo = 0;
int sum = 0;
unsigned int i;
int j;
rcu_register_thread();
for (i = 0; i < LOOP_TIMES; ++i) {
for (j = 0; j < 1000; ++j) {
rcu_read_lock();
foo = rcu_dereference(gs_foo);
if (foo) {
sum += foo->a + foo->b + foo->c + foo->d;
}
rcu_read_unlock();
}
rcu_quiescent_state();
}
rcu_unregister_thread();
pthread_mutex_lock(&gs_sum_guard);
gs_sum += sum;
pthread_mutex_unlock(&gs_sum_guard);
}
void WriteThreadFunc()
{
int i;
while (!gs_is_end) {
for (i = 0; i < 1000; ++i) {
struct Foo* foo = (struct Foo*) malloc(sizeof(struct Foo));
foo->a = 2;
foo->b = 3;
foo->c = 4;
foo->d = 5;
rcu_xchg_pointer(&gs_foo, foo);
synchronize_rcu();
if (foo) {
free(foo);
}
}
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex_test = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_test = PTHREAD_COND_INITIALIZER;
void *One_Thread(void * tparam)
{
printf("One_Thread Start!\\r\\n");
pthread_mutex_lock(&mutex_test);
pthread_cond_wait(&cond_test, &mutex_test);
printf("One_Thread Receive Signal\\r\\n");
pthread_mutex_unlock(&mutex_test);
}
void *Two_Thread(void * tparam)
{
unsigned char j = 0;
printf("Two_Thread Start!\\r\\n");
for(j = 0; j < 10; ++j)
{
if(j == 5)
{
printf("Two _Thread Ready Send Signal\\r\\n");
pthread_cond_signal(&cond_test);
printf("Two_Thread Send Signal OK\\r\\n");
}
printf("Two_Thread j Value is:%d\\r\\n", j);
}
}
int main(void)
{
pthread_t one_thread;
pthread_t two_thread;
pthread_create(&one_thread, 0, One_Thread, (void *)0);
sleep(1);
pthread_create(&two_thread, 0, Two_Thread, (void *)0);
pthread_join(one_thread, 0);
pthread_join(two_thread, 0);
printf("ALL END\\r\\n");
}
| 0
|
#include <pthread.h>
void * spravca(void *);
void * kobyla(void *);
pthread_t tid[2];
sem_t semA, semB;
int kapacita = 20;
int pocet_kobyl = 10;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
main(int argc, char *argv[])
{
sem_init(&semA, 0, 0);
sem_init(&semB, 0, 20);
pthread_mutex_init(&mut,0);
pthread_create(&tid[0], 0, spravca, 0);
pthread_create(&tid[1], 0, kobyla, 0);
pthread_mutex_destroy(&mut);
pthread_join(tid[0],0);
pthread_join(tid[1],0);
}
void * spravca(void * param)
{
int i;
for (i = 0; i < 3; i++)
{
pthread_mutex_lock(&mut);
sem_wait(&semA);
printf("Spravca naplnil valov\\n");
int z;
for (z = 0; z < 20; z++)
sem_post(&semB);
pthread_mutex_unlock(&mut);
}
}
void * kobyla(void * param)
{
int j;
for (j = 0; j < 3; j++)
{
while(kapacita > 0)
{
sem_wait(&semB);
pthread_mutex_lock(&mut);
kapacita--;
printf("kobyla zozrala jedlo, kapacita ostava : %d\\n",kapacita);
pthread_mutex_unlock(&mut);
}
printf("Posledna kobyla zaerdzala\\n");
kapacita = 20;
sem_post(&semA);
}
}
| 1
|
#include <pthread.h>
pthread_t fid[1],cid[20];
pthread_mutex_t cpu=PTHREAD_MUTEX_INITIALIZER,s[20];
int num;
int time1;
int remain;
int state;
}pcb;
pcb thread[20];
int total=0;
int slice=3;
int flag=1;
int waitTime=0;
void* child(void* vargp){
int i = *(int*)vargp;
while(thread[i].remain>0){
pthread_mutex_lock(&s[i]);
pthread_mutex_lock(&cpu);
int i2=0;
sleep(1.5);
waitTime+=(total-thread[i].time1);
for(i2=0;i2<slice;i2++){
if(thread[i].remain<=0){
total++;
printf("ThreadId is:%d Round:%d Remain:%d\\n",thread[i].num,total,thread[i].remain);
}else{
printf("ThreadId is:%d Round:%d Remain:%d\\n",thread[i].num,total,thread[i].remain);
total++;
thread[i].remain--;
}
thread[i].time1=total;
}
pthread_mutex_unlock(&cpu);
pthread_mutex_unlock(&s[i]);
sleep(1);
}
}
void* father(void* vargp){
srand(time(0));
int i=0;
for(i=0;i<20;i++){
pthread_mutex_lock(&s[i]);
thread[i].num=i;
thread[i].remain=rand()%15+1;
thread[i].state=0;
thread[i].time1=0;
}
for(i=0;i<20;i++){
thread[i].state=1;
pthread_mutex_unlock(&s[i]);
}
int inum[20];
int it1=0;
for(it1=0;it1<20;it1++){
inum[it1]=it1;
}
for(it1=0;it1<20;it1++){
pthread_create(&cid[it1],0,child,(void*)(&inum[it1]));
}
for(i=0;i<20;i++){
pthread_join(cid[i],0);
}
printf("\\nAverage WaitTime = %f s\\n",waitTime*1.0/20);
}
int main(){
int i=0,j=0;
for(j=0;j<20;j++){
s[j]=cpu;
}
pthread_create(&fid[i],0,father,(void*)(&i));
pthread_join(fid[i],0);
return 0;
}
| 0
|
#include <pthread.h>
int mbox_init(struct mbox *mb, size_t size)
{
int ret;
mb->read_idx = 0;
mb->write_idx = 0;
mb->size = size;
ret = sem_init(&mb->sem_read, 0, 0);
if (ret)
goto out_err;
ret = sem_init(&mb->sem_write, 0, size);
if (ret)
goto out_err;
ret = pthread_mutex_init(&mb->mutex_read, 0);
if (ret)
goto out_err;
ret = pthread_mutex_init(&mb->mutex_write, 0);
if (ret)
goto out_err;
mb->messages = malloc(mb->size * sizeof(uint32_t));
if (!mb->messages)
goto out_err;
return 0;
out_err:
return -EIO;
}
void mbox_destroy(struct mbox *mb)
{
free(mb->messages);
sem_destroy(&mb->sem_write);
sem_destroy(&mb->sem_read);
pthread_mutex_destroy(&mb->mutex_read);
pthread_mutex_destroy(&mb->mutex_write);
}
int mbox_put(struct mbox *mb, uint32_t msg)
{
pthread_mutex_lock(&mb->mutex_write);
sem_wait(&mb->sem_write);
mb->messages[mb->write_idx] = msg;
mb->write_idx = (mb->write_idx + 1) % mb->size;
sem_post(&mb->sem_read);
pthread_mutex_unlock(&mb->mutex_write);
return 0;
}
int mbox_put_interruptible(struct mbox *mb, uint32_t msg)
{
if (pthread_mutex_lock(&mb->mutex_write) < 0) {
return -1;
}
if (sem_wait(&mb->sem_write) < 0) {
pthread_mutex_unlock(&mb->mutex_write);
return -1;
}
mb->messages[mb->write_idx] = msg;
mb->write_idx = (mb->write_idx + 1) % mb->size;
sem_post(&mb->sem_read);
pthread_mutex_unlock(&mb->mutex_write);
return 0;
}
uint32_t mbox_get(struct mbox *mb)
{
uint32_t msg;
pthread_mutex_lock(&mb->mutex_read);
sem_wait(&mb->sem_read);
msg = mb->messages[mb->read_idx];
mb->read_idx = (mb->read_idx + 1) % mb->size;
sem_post(&mb->sem_write);
pthread_mutex_unlock(&mb->mutex_read);
return msg;
}
int mbox_get_interruptible(struct mbox *mb, uint32_t *msg)
{
if (pthread_mutex_lock(&mb->mutex_read) < 0) {
return -1;
}
if (sem_wait(&mb->sem_read) < 0) {
pthread_mutex_unlock(&mb->mutex_read);
return -1;
}
*msg = mb->messages[mb->read_idx];
mb->read_idx = (mb->read_idx + 1) % mb->size;
sem_post(&mb->sem_write);
pthread_mutex_unlock(&mb->mutex_read);
return 0;
}
int mbox_tryget(struct mbox *mb, uint32_t *msg)
{
int success, fill;
pthread_mutex_lock(&mb->mutex_read);
sem_getvalue(&mb->sem_read, &fill);
if (fill <= 0) {
success = 0;
} else {
success = 1;
sem_wait(&mb->sem_read);
*msg = mb->messages[mb->read_idx];
mb->read_idx = (mb->read_idx + 1) % mb->size;
sem_post(&mb->sem_write);
}
pthread_mutex_unlock(&mb->mutex_read);
return success;
}
int mbox_tryput(struct mbox * mb, uint32_t msg)
{
int success, rem;
pthread_mutex_lock(&mb->mutex_write);
sem_getvalue(&mb->sem_write, &rem);
if (rem <= 0) {
success = 0;
} else {
success = 1;
sem_wait(&mb->sem_write);
mb->messages[mb->write_idx] = msg;
mb->write_idx = (mb->write_idx + 1) % mb->size;
sem_post(&mb->sem_read);
}
pthread_mutex_unlock(&mb->mutex_write);
return success;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex_sum = PTHREAD_MUTEX_INITIALIZER;
int *VecA, *VecB, sum = 0, dist;
void * doMyWork(int myId)
{
int counter, mySum = 0;
printf("\\n %d: I am taking the interval: %d - %d.", myId, ((myId - 1) * dist), ((myId * dist) - 1));
for (counter = ((myId - 1) * dist); counter <= ((myId * dist) - 1); counter++)
mySum += VecA[counter] * VecB[counter];
printf("\\n %d: My Local Sum: %d.", myId, mySum);
pthread_mutex_lock(&mutex_sum);
sum += mySum;
pthread_mutex_unlock(&mutex_sum);
return;
}
main(int argc, char *argv[])
{
int ret_count;
pthread_t * threads;
pthread_attr_t pta;
double time_start, time_end, diff;
struct timeval tv;
struct timezone tz;
int counter, NumThreads, VecSize;
printf("\\n\\t\\t---------------------------------------------------------------------------");
printf("\\n\\t\\t Centre for Development of Advanced Computing (C-DAC)");
printf("\\n\\t\\t Email : RarchK");
printf("\\n\\t\\t---------------------------------------------------------------------------");
printf("\\n\\t\\t Objective : Vector-Vector Multiplication");
printf("\\n\\t\\t Compute the vector-vector multiplication using block-striped partitioning ");
printf("\\n\\t\\t for uniform data distribution");
printf("\\n\\t\\t..........................................................................\\n");
if (argc != 3)
{
printf(" Missing Arguments: exe <VectorSize> <NumThreads> \\n");
return;
}
NumThreads = abs(atoi(argv[2]));
VecSize = abs(atoi(argv[1]));
if (VecSize == 0)
{
printf("\\nVector Size is assumed as 100");
VecSize = 100;
}
if (NumThreads == 0)
{
printf("\\nNumber of Threads are assumed as 4");
NumThreads =4;
}
printf("\\n Size of Vector: %d.", VecSize);
printf("\\n Number of Threads: %d.", NumThreads);
if (NumThreads > 8)
{
printf("\\n Number of threads should be less than or equal to 8. Aborting.\\n");
return ;
}
if (VecSize % NumThreads != 0)
{
printf("\\n Number of threads not a factor of vector size. Aborting.\\n");
return ;
}
VecA = (int *) malloc(sizeof(int) * VecSize);
VecB = (int *) malloc(sizeof(int) * VecSize);
pthread_attr_init(&pta);
threads = (pthread_t *) malloc(sizeof(pthread_t) * NumThreads);
dist = VecSize / NumThreads;
for (counter = 0; counter < VecSize; counter++)
{
VecA[counter] = 2;
VecB[counter] = 3;
}
gettimeofday(&tv, &tz);
time_start = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
for (counter = 0; counter < NumThreads; counter++)
{
ret_count=pthread_create(&threads[counter], &pta, (void *(*) (void *)) doMyWork, (void *) (counter + 1));
if(ret_count)
{
printf("\\n ERROR: Return code from pthread_create() function is %d",ret_count);
exit(-1);
}
}
for (counter = 0; counter < NumThreads; counter++)
{
ret_count=pthread_join(threads[counter], 0);
if(ret_count)
{
printf("\\n ERROR : Return code from pthread_join() is %d ",ret_count);
exit(-1);
}
}
gettimeofday(&tv, &tz);
time_end = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
printf("\\n The Sum is: %d.", sum);
printf("\\n Time in Seconds (T) : %lf\\n", time_end - time_start);
ret_count=pthread_attr_destroy(&pta);
if(ret_count)
{
printf("\\n ERROR : Return code from pthread_attr_destroy() is %d ",ret_count);
exit(-1);
}
return;
}
| 0
|
#include <pthread.h>
sem_t SEntrada;
pthread_mutex_t C1;
char est[24];
pthread_t th_auto[8];
int lugar;
void automovil( void *id );
int entrada( void *id ,int puerta);
void salida( void *id ,int salida,int lug);
void tiempo(int time);
void interfaz();
int main()
{
int i;
for(i=0;i<24;i++)
{
est[i]=' ';
}
sem_init( &SEntrada,0,24);
pthread_mutex_init(&C1,0);
int res;
for(i=0;i<8;i++){
pthread_create( &th_auto[i], 0,(void *) &automovil, (void *) i);
}
for(i=0;i<8;i++){
pthread_join(th_auto[i],(void *)&res);
}
return 0;
}
void automovil( void *id ){
int ent,tie,sal,i;
for(i=0;i<5;i++)
{
ent = rand()%10;
tie = rand()%5;
sal = rand()%10;
int id2 = (int) id;
int lug = entrada(id,ent);
interfaz();
tiempo(tie);
salida(id,sal,lug);
interfaz();
}
}
int entrada( void *id ,int puerta)
{
int id2 = (int) id;
char id3 = (char) (id2+48);
sem_wait(&SEntrada);
printf("%d Entro por la puerta: %d\\n",id2,puerta);
pthread_mutex_lock(&C1);
lugar = rand()%24;
while(est[lugar] != ' ')
{
lugar = (lugar+1)%24;
}
est[lugar] = id3;
pthread_mutex_unlock(&C1);
return lugar;
}
void salida( void *id ,int salida,int lug)
{
int id2 = (int) id;
char id3 = (char) (id2+48);
printf("%d Salio por la puerta: %d\\n",id2,salida);
pthread_mutex_lock(&C1);
est[lug] = ' ';
pthread_mutex_unlock(&C1);
sem_post(&SEntrada);
}
void tiempo(int time){
sleep(time);
}
void interfaz()
{
,est[0],est[1],est[2],est[3],est[4],est[5],est[6],est[7]
,est[8],est[9],est[10],est[11],est[12],est[13],est[14],est[15]
,est[16],est[17],est[18],est[19],est[20],est[21],est[22],est[23]);
}
| 1
|
#include <pthread.h>
struct rssi_table table[MAX_ENTRY];
struct timeval present;
pthread_mutex_t table_mutex=PTHREAD_MUTEX_INITIALIZER;
int initialize(){
pthread_mutex_lock(&table_mutex);
memset(&present,0,sizeof(struct timeval));
memset(table,0,sizeof(struct rssi_table)*MAX_ENTRY);
pthread_mutex_unlock(&table_mutex);
return 0;
}
int get_index(uint8_t *bssid){
int i;
for(i=0;i<50;i++){
if(table[i].used==1&&memcmp(bssid,&table[i].bssid,6)==0){
return i;
}
}
return -1;
}
int isinblocklist(uint8_t *bssid){
return 0;
}
int create(uint8_t *bssid){
int i,index;
printf("creating entry for");
for (i=0;i<5;i++){
printf("%X:",*(bssid+i));
}
printf("%X\\n",*(bssid+5));
for (i=0;i<50;i++){
if(table[i].used==0){
table[i].used=1;
memcpy(table[i].bssid,bssid,6);
return i;
}
}
printf("create entry failed!\\n");
return -1;
}
int update(uint8_t *bssid,uint8_t signal,struct timeval ts){
int index=get_index(bssid);
if(index==-1){
index=create(bssid);
}
pthread_mutex_lock(&table_mutex);
table[index].rssi[table[index].p++]=signal;
table[index].p%=10;
table[index].ts=ts;
present=ts;
pthread_mutex_unlock(&table_mutex);
return 0;
}
float get_rssi(uint8_t *bssid){
int index=get_index(bssid);
if(index==-1){return -1;}
return get_rssi_index(index);
}
float get_rssi_index(int index){
float calc=0.0;
pthread_mutex_lock(&table_mutex);
if(present.tv_sec-table[index].ts.tv_sec>VALID_INTERVAL){
return 0;
}
int i;
for(i=0;i<10;i++){
calc+=table[index].rssi[i];
}
pthread_mutex_unlock(&table_mutex);
return calc/10;
}
float get_rssi_raw(struct rssi_table* p){
pthread_mutex_lock(&table_mutex);
if(present.tv_sec-p->ts.tv_sec>VALID_INTERVAL){
return 0;
}
if(p->used==0){return -1;}
float calc=0.0;
int i;
for(i=0;i<10;i++){
calc+=p->rssi[i];
}
pthread_mutex_unlock(&table_mutex);
return calc/10;
}
| 0
|
#include <pthread.h>
pthread_mutex_t ma[6];
int a[6];
pthread_mutex_t mi;
int i = 0;
int d = 0;
void *choice()
{
int x;
for (x = 1; x < 6; x++)
{
pthread_mutex_lock(&mi);
i = x;
pthread_mutex_unlock(&mi);
}
return 0;
}
void *wa(void *arg)
{
unsigned id = (unsigned long) arg;
pthread_mutex_lock(&ma[id]);
a[id] = 1;
pthread_mutex_unlock(&ma[id]);
return 0;
}
void *ra()
{
int idx = 0;
pthread_mutex_lock(&mi);
idx = i;
pthread_mutex_unlock(&mi);
pthread_mutex_lock(&ma[idx]);
if (a[idx] == 1)
{
d++;
a[idx] = 0;
}
pthread_mutex_unlock(&ma[idx]);
return 0;
}
int main()
{
int x;
pthread_t idk;
pthread_t idr;
pthread_t idw[6];
pthread_mutex_init(&mi, 0);
for (x = 0; x < 6; x++)
{
a[x] = 0;
pthread_mutex_init(&ma[x], 0);
pthread_create(&idw[x], 0, wa, (void*) (long) x);
}
for (x = 0; x < 4; x++)
{
pthread_create(&idk, 0, choice, 0);
pthread_create(&idr, 0, ra, 0);
pthread_join(idk, 0);
pthread_join(idr, 0);
}
for (x = 0; x < 6; x++)
pthread_join(idw[x],0);
pthread_exit (0);
return 0;
}
| 1
|
#include <pthread.h>
const int READER_NUM = 10;
pthread_rwlock_t rwlock;
pthread_mutex_t mutex;
void readerFunc(void) {
int id = ((int)pthread_self()) % 10000;
printf("Reader %4d is waiting\\n", id);
pthread_rwlock_rdlock(&rwlock);
pthread_mutex_lock(&mutex);
printf(" Reader %4d start reading ...\\n", id);
sleep(rand()%11);
printf(" Reader %4d finish reading !\\n", id);
pthread_mutex_unlock(&mutex);
pthread_rwlock_unlock(&rwlock);
}
void writerFunc(void) {
int id = ((int)pthread_self()) % 10000;
int i;
for (i = 0; i < 4; i++) {
printf(" Writer %4d is waiting\\n", id);
pthread_rwlock_wrlock(&rwlock);
printf(" Writer %4d start writing ...\\n", id);
sleep(rand()%3);
printf(" Writer %4d finish writing !\\n", id);
pthread_rwlock_unlock(&rwlock);
sleep(rand()%3);
}
}
int main(void) {
pthread_t handle[READER_NUM+1];
int i;
pthread_rwlock_init(&rwlock, 0);
pthread_mutex_init(&mutex, 0);
for (i = 1; i < 2; i++) {
pthread_create(&handle[i], 0, (void*)readerFunc, 0);
}
pthread_create(&handle[0], 0, (void*)writerFunc, 0);
sleep(2);
for (; i <= READER_NUM; i++) {
pthread_create(&handle[i], 0, (void*)readerFunc, 0);
}
for (i = 0; i <= READER_NUM; i++) {
pthread_join(handle[i], 0);
}
pthread_rwlock_destroy(&rwlock);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t sum_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER;
void *functionAdd1();
void *functionAdd2();
int sum = 0;
int count=0;
int main()
{
pthread_t thread1, thread2;
pthread_create(&thread1, 0, &functionAdd1, 0);
pthread_create(&thread2, 0, &functionAdd2, 0);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
exit(0);
}
void *functionAdd1()
{
while(1)
{
pthread_mutex_lock(&condition_mutex);
while (sum >= 2 && sum <=4){
pthread_cond_wait(&condition_cond, &condition_mutex);
}
pthread_mutex_unlock(&condition_mutex);
pthread_mutex_lock(&sum_mutex);
sum++;
printf("Sum value functionAdd1: %d\\n",sum);
pthread_mutex_unlock(&sum_mutex);
if (sum >= 10) return (0);
}
}
void *functionAdd2()
{
while(1)
{
pthread_mutex_lock(&condition_mutex);
if(sum < 2 || sum > 4)
{
pthread_cond_signal(&condition_cond);
}
pthread_mutex_unlock(&condition_mutex);
pthread_mutex_lock(&sum_mutex);
sum++;
printf("Sum value functionAdd2: %d\\n",sum);
pthread_mutex_unlock(&sum_mutex);
if (sum >=10) return (0);
}
}
| 1
|
#include <pthread.h>
pthread_t Thread_set;
pthread_t Thread_get;
pthread_attr_t schedAttr_set;
pthread_attr_t schedAttr_get;
struct sched_param set_param;
struct sched_param get_param;
pthread_mutex_t mutexLock;
int test;
{
double Acc_x,Acc_y,Acc_z;
double roll;
double pitch;
double yaw;
struct timespec ts;
}NAV;
NAV *nav;
void set_XYZ(void *a)
{
pthread_mutex_lock(&mutexLock);
nav->Acc_x = rand();
nav->Acc_y = rand();
nav->Acc_z = rand();
nav->roll = rand();
nav->pitch = rand();
nav->yaw = rand();
clock_gettime(CLOCK_MONOTONIC, &(nav->ts));
pthread_mutex_unlock(&mutexLock);
}
void get_XYZ(void *a)
{
pthread_mutex_lock(&mutexLock);
printf("Acc_x= %f\\n",nav->Acc_x);
printf("Acc_y= %f\\n",nav->Acc_y);
printf("Acc_z= %f\\n",nav->Acc_z);
printf("roll= %f\\n",nav->roll);
printf("pitch= %f\\n",nav->pitch);
printf("yaw= %f\\n",nav->yaw);
printf("time: sec=%d, nsec=%d\\n",(int)nav->ts.tv_sec,(int)nav->ts.tv_nsec);
pthread_mutex_unlock(&mutexLock);
}
int main (int argc, char *argv[])
{
pthread_attr_init(&schedAttr_set);
pthread_attr_init(&schedAttr_get);
pthread_attr_setinheritsched(&schedAttr_set, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setschedpolicy(&schedAttr_set, SCHED_FIFO);
pthread_attr_setinheritsched(&schedAttr_get, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setschedpolicy(&schedAttr_get, SCHED_FIFO);
set_param.sched_priority = 4;
get_param.sched_priority = 3;
pthread_attr_setschedparam(&schedAttr_set, &set_param);
pthread_attr_setschedparam(&schedAttr_get, &get_param);
int count = 0;
nav = (NAV *) malloc(sizeof(NAV));
while(count < 2)
{
pthread_create(&Thread_set, &schedAttr_set,set_XYZ,(void*) 0);
pthread_create(&Thread_get, &schedAttr_get,get_XYZ,(void*) 0);
count++;
usleep(10000);
}
pthread_join(Thread_set,0);
pthread_join(Thread_get,0);
}
| 0
|
#include <pthread.h>
FILE *fp;
pthread_t threads[2];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void * read_file(void* tmp)
{
int i, ret;
for (i = 0; i < 3000; i++) {
if (pthread_self() == threads[1]) {
pthread_mutex_lock(&mutex);
ret = fputc('a', fp);
pthread_mutex_unlock(&mutex);
} else {
pthread_mutex_lock(&mutex);
ret = fputc('b', fp);
pthread_mutex_unlock(&mutex);
}
if (ret < 0) {
printf("Some error, closing\\n");
goto close;
}
}
if(pthread_self() == threads[1]) {
pthread_mutex_lock(&mutex);
fputc('-', fp);
pthread_mutex_unlock(&mutex);
} else {
pthread_mutex_lock(&mutex);
fputc('+', fp);
pthread_mutex_unlock(&mutex);
}
close:
return 0;
}
int main()
{
fp = fopen(("my_file.txt"), "a+");
if (!fp) {
printf("Could not open the file\\n");
return -1;
}
pthread_create(&threads[1], 0, read_file, 0);
pthread_create(&threads[2], 0, read_file, 0);
pthread_join(threads[1], 0);
pthread_join(threads[2], 0);
fclose(fp);
return 0;
}
| 1
|
#include <pthread.h>
int TEAMS1=0,TEAMS2=0,N;
pthread_cond_t y[100000],l[100000];
pthread_mutex_t mutex = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
int counter1=0,counter2=0;
int lan_que[100000],york_que[100000];
int lan_tail=-1,lan_head=0,york_head=0,york_tail=-1;
void * func1(void * arg){
int i=((int *)arg),flag=0;
pthread_mutex_lock(&mutex);
york_tail=(york_tail+1);
york_que[york_tail]=i;
printf("\\t\\t\\tyork %d entered queue\\n",i);
while(counter1==N||counter2!=0){
pthread_cond_wait(&y[i],&mutex);
}
york_head=(york_head+1);
printf("\\t\\t\\tyork %d left queue\\n",i);
counter1++;
printf("york %d entered\\n",i );
pthread_mutex_unlock(&mutex);
sleep(1);
pthread_mutex_lock(&mutex);
printf("york %d leaving \\n",i );
counter1--;
int temp=N-counter1;int yh=york_head;
while(temp>0 && yh<=york_tail){
pthread_cond_signal(&y[york_que[yh]]);
yh++;
temp--;
}
temp=N-counter2;int lh=lan_head;
while(counter1==0 && temp>0 && lh<=lan_tail){
pthread_cond_signal(&l[lan_que[lh]]);
temp--;
lh++;
}
pthread_mutex_unlock(&mutex);
return 0;
}
void * func2(void * arg){
int i=((int *)arg);
pthread_mutex_lock(&mutex);
lan_tail=(lan_tail+1);
lan_que[lan_tail]=i;
printf(" \\t\\t\\t\\t\\t\\tlan %d entered queue \\n",i);
while(counter2==N||counter1!=0)
pthread_cond_wait(&l[i],&mutex);
lan_head=(lan_head+1);
printf(" \\t\\t\\t\\t\\t\\tlan %d left queue\\n",i);
counter2++;
printf("lanchester %d entered\\n",i );
pthread_mutex_unlock(&mutex);
sleep(1);
pthread_mutex_lock(&mutex);
printf("lanchester %d leaving \\n",i );
counter2--;
int temp=N-counter1;int yh=york_head;
while(counter2==0 && temp>0 && yh<=york_tail){
pthread_cond_signal(&y[york_que[yh]]);
temp--;
yh++;
}
temp=N-counter2;int lh=lan_head;
while(temp>0 && lh<=lan_tail){
pthread_cond_signal(&l[lan_que[lh]]);
lh++;
temp--;
}
pthread_mutex_unlock(&mutex);
return 0;
}
int main(){
int i,t,tot;
pthread_t york[100000],lan[100000];
printf("enter inn size:");
scanf("%d",&N);
printf("enter number of soldiers:");
scanf("%d",&tot);
i=0;int j=0;
printf("ENTRY \\t\\t\\t YORKS QUEUE\\t\\t LANCHESTER'S QUEUE\\n");
while(tot--){
if(rand()%2==0){
y[TEAMS1++]=(pthread_cond_t)PTHREAD_COND_INITIALIZER;
t=pthread_create(&york[i],0,func1,i);
i++;
}
else{
l[TEAMS2++]=(pthread_cond_t)PTHREAD_COND_INITIALIZER;
t=pthread_create(&lan[j],0,func2,j);
j++;
}
}
for(i=0;i<TEAMS1;i++){
t=pthread_join(york[i],0);
}
for(i=0;i<TEAMS2;i++){
t=pthread_join(lan[i],0);
}
}
| 0
|
#include <pthread.h>
int amount_of_elements_in_run = 0;
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
void print_v(int v[], int n)
{
int i = 0;
while(i<n)
{
printf("%d\\t",v[i]);
i++;
}
printf("\\n");
}
void *calculate_two_elements(void *vectorptr)
{
pthread_mutex_lock(&mutex1);
int i;
int *vector = (int*)vectorptr;
while(amount_of_elements_in_run > 1)
{
vector[0] = vector[0] + vector[amount_of_elements_in_run-1];
amount_of_elements_in_run--;
}
pthread_mutex_unlock(&mutex1);
}
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
int *generate_random_vector( int n)
{
int *v;
v = (int*)malloc(sizeof(int)*n);
int i;
for(i = 0;i < n;++i)
v[i] = i;
int w ;
for(i = n - 1;i > 0;--i)
{
w = rand() % i;
swap(&v[i],&v[w]);
}
return v;
}
int calculate_sum_vector_in_main(int vector[], int n, double *spent_time)
{
struct timeval antes, depois ;
*spent_time = 0;
gettimeofday (&antes, 0) ;
int sum = 0;
int i = 0;
while(i < n)
{
sum = sum + vector[i];
i++;
}
gettimeofday (&depois, 0) ;
*spent_time = (double)( (depois.tv_sec * 1000000 + depois.tv_usec) - (antes.tv_sec * 1000000 + antes.tv_usec) );
return sum;
}
void close_threads(pthread_t threads_vector[], int amount_of_threads)
{
int index;
for(index=0;index<amount_of_threads;index++)
{
pthread_join(threads_vector[index] ,0);
}
}
void calculate_sum_vector_with_k_threads(int *vector, int n, int amount_of_threads, double *spent_time)
{
struct timeval antes, depois ;
*spent_time = 0;
gettimeofday (&antes, 0) ;
amount_of_elements_in_run = n;
pthread_t threads_vector[amount_of_threads];
int index;
for(index=0;index<amount_of_threads ;index++)
{
pthread_create(threads_vector + index,0,&calculate_two_elements,(void*)vector);
}
close_threads(threads_vector,amount_of_threads);
gettimeofday (&depois, 0) ;
*spent_time = (double)( (depois.tv_sec * 1000000 + depois.tv_usec) - (antes.tv_sec * 1000000 + antes.tv_usec) );
}
int main(int argc, char **argv)
{
if(argc == 3)
{
srand(time(0));
int n = atoi(argv[1]);
int k = atoi(argv[2]);
int *vector;
printf("* Tamanho da entrada: %d\\n",n);
printf("* Quantidade de threads: %d\\n",k);
amount_of_elements_in_run = n;
printf("\\n");
double spent_time = 0,spent_time2 = 0;
vector = generate_random_vector(n);
printf("* Soma dos elementos do vetor na Thread Main: %d\\n",calculate_sum_vector_in_main(vector,n,&spent_time));
printf("* Tempo decorrido na Thread Main (microssegundos): %lf\\n\\n",spent_time);
calculate_sum_vector_with_k_threads(vector,n,k,&spent_time2);
printf("* Soma dos elementos do vetor Com k(%d)-Threads: %d\\n",k,vector[0]);
printf("* Tempo decorrido com k(%d)-Threads (microssegundos): %lf\\n",k,spent_time2);
printf("%lf\\n",spent_time2);
} else
{
printf("* Deve-se haver três argumentos de entrada!\\n");
printf("* ./<arquivo-executavel> <tamanho do vetor> <quantidade de threads>\\n");
}
exit(0);
}
| 1
|
#include <pthread.h>
struct foo {
int f_count;
pthread_mutex_t f_lock;
int f_id;
};
struct foo *foo_alloc(int id) {
struct foo *fp;
if ((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 1;
fp->f_id = id;
if (pthread_mutex_init(&fp->f_lock, 0) !=0) {
free(fp);
return (0);
}
}
return fp;
}
void foo_hold(struct foo *fp) {
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
void foo_rele(struct foo *fp) {
pthread_mutex_lock(&fp->f_lock);
if (--fp->f_count == 0) {
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
} else {
pthread_mutex_unlock(&fp->f_lock);
}
}
| 0
|
#include <pthread.h>
int buffer[BUFFER_SIZE];
int buffer_pointer;
int buffer_length;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void produce() {
while (1) {
int value = get_random_number();
put(value);
printf("Produced: %d\\n", value);
fflush(stdout);
usleep(1000000);
}
}
void consume() {
while (1) {
int value = get();
printf("Consumed: %d\\n", value);
fflush(stdout);
usleep(1000000);
}
}
void put(int value) {
pthread_mutex_lock(&mutex);
if ( !buffer_full_p() ) {
buffer[(buffer_pointer + buffer_length) % BUFFER_SIZE] = value;
buffer_length++;
} else {
printf("Buffer full!\\n");
fflush(stdout);
}
pthread_mutex_unlock(&mutex);
}
int get() {
pthread_mutex_lock(&mutex);
if ( !buffer_empty_p() ) {
buffer_length--;
pthread_mutex_unlock(&mutex);
return buffer[buffer_pointer++ % BUFFER_SIZE];
} else {
printf("Buffer empty!\\n");
fflush(stdout);
}
pthread_mutex_unlock(&mutex);
}
int buffer_full_p() {
return buffer_length == BUFFER_SIZE;
}
int buffer_empty_p() {
return buffer_length == 0;
}
int get_random_number() {
return rand() % 100;
}
int main() {
pthread_t producer, consumer;
int i = 0;
for( i = 0; i < BUFFER_SIZE; ++i )
buffer[i] = 0;
buffer_pointer = 0;
buffer_length = 0;
pthread_create(&producer, 0, produce, (void*)0);
pthread_create(&consumer, 0, consume, (void*)0);
pthread_join(producer, 0);
pthread_join(consumer, 0);
}
| 1
|
#include <pthread.h>
void *myTh(void *arg);
char dirname[256];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main(int argc, char *argv[]){
pthread_t *th;
int n,i,fd;
char fname[256];
if(argc != 3){
return -1;
}
n = atoi(argv[1]);
chdir(argv[2]);
sprintf(dirname, "%s", argv[2]);
mkdir("tmp", 0777);
th = (pthread_t *)malloc(sizeof(pthread_t) * n);
for(i=0; i<20; i++){
sprintf(fname, "file%d", i);
fd = open(fname, O_CREAT | O_RDWR | O_TRUNC, 0777);
write(fd, fname, strlen(fname) * sizeof(char));
close(fd);
}
for(i=0; i<n; i++){
int *j = (int *)malloc(sizeof(int));
*j = i;
pthread_create(&th[i], 0, myTh, (void *)j);
}
pthread_exit(0);
}
void *myTh(void *arg){
pthread_detach(pthread_self());
int *n = (int *) arg;
int count =0;
int fd[2];
char fname[2][256];
char catName[256];
char tmpFileName[256];
char *buf[2];
int bufSize[2];
struct stat stat_buf;
DIR *dp;
struct dirent *dirp;
while(1){
pthread_mutex_lock(&mutex);
dp = opendir(".");
while((dirp = readdir(dp)) != 0 && count < 2){
lstat(dirp->d_name, &stat_buf);
switch(stat_buf.st_mode & S_IFMT){
case S_IFDIR:
break;
case S_IFREG:
sprintf(fname[count], "%s", dirp->d_name);
bufSize[count] = stat_buf.st_size;
buf[count] = (char *)malloc(bufSize[count] * sizeof(char));
fd[count] = open(fname[count], O_RDONLY, 0777);
count++;
break;
}
}
closedir(dp);
if(count < 2){
count = 0;
free(buf[count]);
pthread_mutex_unlock(&mutex);
break;
}
if(count == 2){
unlink(fname[0]);
unlink(fname[1]);
pthread_mutex_unlock(&mutex);
read(fd[0], buf[0], bufSize[0]);
read(fd[1], buf[1], bufSize[1]);
close(fd[0]);
close(fd[1]);
sprintf(catName, "%s%s", fname[0], fname[1]);
sprintf(tmpFileName, "tmp/%s", catName);
printf("Thread %d conacatenate %s %s\\n", *n, fname[0], fname[1]);
fd[0] = open(tmpFileName, O_CREAT | O_TRUNC | O_RDWR, 0777);
write(fd[0], buf[0], bufSize[0]);
write(fd[0], buf[1], bufSize[1]);
close(fd[0]);
free(buf[0]);
free(buf[1]);
link(tmpFileName, catName);
unlink(tmpFileName);
count = 0;
}
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int final_result = 0;
void *swap (void *threadarg) {
int y;
int checksum=0;
int accel_num = *((int *)threadarg);
int output[1024];
for (y=0; y<1024; y++) {
output [y] = input_array[y][accel_num];
}
for (y=0; y<1024; y++) {
checksum+= (expected_array [accel_num][y] == output [y]);
}
pthread_mutex_lock (&mutex);
final_result += checksum;
pthread_mutex_unlock (&mutex);
pthread_exit(0);
}
int main() {
int i;
int main_result=0;
pthread_t threads[6];
int data[6];
for (i=0; i<6; i++) {
data[i]=i;
pthread_create(&threads[i], 0, swap, (void *)&data[i]);
}
for (i=0; i<6; i++) {
pthread_join(threads[i], 0);
}
printf ("Result: %d\\n", final_result);
if (final_result == 6144) {
printf("RESULT: PASS\\n");
} else {
printf("RESULT: FAIL\\n");
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t condc, condp;
int element[20];
uint8_t head;
uint8_t tail;
uint8_t remaining_elements;
int waiting;
} prod_cons_queue;
prod_cons_queue *q;
int pid;
} vars;
int main(){
return 0;
}
void queue_initialize (prod_cons_queue *q){
for(int i = 0;i< 20;i++){
q -> element[i] = 0;
}
(q -> head) = (q -> tail) = 0;
q -> remaining_elements = 0;
q -> waiting = 0;
}
void queue_add( prod_cons_queue *q, int element){
if(q->remaining_elements == 20){
if(q->tail < 19){
q->element[q->tail + 1] = element;
q->tail ++;
}else{
q->element[0] = element;
q->tail = 0;
}
q->remaining_elements ++;
}
}
void queue_remove( prod_cons_queue *q){
if(q->remaining_elements != 0){
if(q->head < 19){
q->head += 1;
q->remaining_elements -= 1;
}else{
q->head = 0;
q->remaining_elements -= 1;
}
}
}
void* producer(void *ptr){
int msgs = 10;
for(int i = 0;i<msgs;i++){
pthread_mutex_lock(&mutex);
if(((vars *)ptr)->q->remaining_elements == 20){
((vars *)ptr)->q->waiting += 1;
pthread_cond_wait(&condp, &mutex);
}
((vars *)ptr)->q->waiting -= 1;
queue_add(((vars *)ptr)->q, ((vars *)ptr)->pid);
if(((vars *)ptr)->q->remaining_elements == 1)pthread_cond_signal(&condc);
pthread_mutex_unlock(&mutex);
}
}
void* consumer(void *ptr){
int msgs = 0;
if(((vars *)ptr)->q->remaining_elements == 0){
((vars *)ptr)->q->waiting += 1;
pthread_cond_wait(&condc, &mutex);
}
((vars *)ptr)->q->waiting -= 1;
int pid = ((vars *)ptr)->q->element[((vars *)ptr)->q->head];
printf("This is a message from thread %d", ((vars *)ptr)->pid);
queue_remove(((vars *)ptr)->q);
if(((vars *)ptr)->q->remaining_elements == 19) pthread_cond_signal(&condp);
}
| 0
|
#include <pthread.h>
int i;
int acount=0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condVar = PTHREAD_COND_INITIALIZER;
int accessible = 1;
void waitMySemaphor(int amountToWithdraw);
void signalMySemphor();
void *threadClientWithdrawer(void* args);
void *threadClientDeposit(void* args);
void *threadAccount();
void *threadClientWithdrawer(void* args)
{
char* name = (char*) args;
int amountToWithdraw = atoi(name);
int i;
for (i = 0; i< 10; ++i)
{
waitMySemaphor(amountToWithdraw);
if (acount >= amountToWithdraw)
{
printf("%d - %d\\n", acount, amountToWithdraw);
acount -= amountToWithdraw;
}
else
printf("%s : To little in account\\n",name);
int sleepTime = rand()%500;
usleep((sleepTime + 1250) * 1000);
signalMySemphor();
sleepTime = rand()%500;
usleep((sleepTime + 1000) * 1000);
}
printf("%s : end of thread -- acount: %d\\n",name,acount);
}
void *threadClientDeposit(void* args)
{
char* name = (char*) args;
int amountToDeposit = atoi(name);
int i;
for (i = 0; i< 110; ++i)
{
int sleepTime = rand()%500;
usleep((sleepTime + 250) * 1000);
acount += amountToDeposit;
signalMySemphor();
}
printf("%s : end of thread -- acount: %d\\n",name,acount);
}
void *threadAccount()
{
int i;
int oldAcount;
while(1)
{
if (oldAcount != acount)
{
printf("Acount amount: %d\\n",acount);
oldAcount = acount;
}
}
}
void waitMySemaphor(int amountToWithdraw)
{
pthread_mutex_lock(&mutex);
while (accessible == 0 || acount < amountToWithdraw)
{
if (acount < amountToWithdraw)
printf("waitMySemaphor %d %d\\n",acount,amountToWithdraw);
pthread_cond_wait(&condVar, &mutex);
}
accessible = 0;
pthread_mutex_unlock(&mutex);
}
void signalMySemphor()
{
pthread_mutex_lock(&mutex);
pthread_cond_signal(&condVar);
accessible = 1;
pthread_mutex_unlock(&mutex);
}
int main(int argc, char* argv[])
{
pthread_t a,b,c,d,e,f,g,h,j;
char* buff1 = (char*) malloc(15);
char* buff2 = (char*) malloc(15);
char* buff3 = (char*) malloc(15);
char* buff4 = (char*) malloc(15);
char* buff5 = (char*) malloc(15);
char* buff6 = (char*) malloc(15);
char* buff7 = (char*) malloc(15);
char* buff8 = (char*) malloc(15);
sprintf(buff1,"10");
sprintf(buff2,"20");
sprintf(buff3,"30");
sprintf(buff4,"40");
sprintf(buff5,"110");
sprintf(buff6,"220");
sprintf(buff7,"330");
sprintf(buff8,"440");
srand(time(0));
pthread_create(&a,0,threadAccount,0);
pthread_create(&b,0,threadClientDeposit,buff1);
pthread_create(&c,0,threadClientDeposit,buff2);
pthread_create(&d,0,threadClientDeposit,buff3);
pthread_create(&e,0,threadClientDeposit,buff4);
pthread_create(&f,0,threadClientWithdrawer,buff5);
pthread_create(&g,0,threadClientWithdrawer,buff6);
pthread_create(&h,0,threadClientWithdrawer,buff7);
pthread_create(&j,0,threadClientWithdrawer,buff8);
pthread_join(a,0);
pthread_join(b,0);
pthread_join(c,0);
pthread_join(d,0);
pthread_join(e,0);
pthread_join(f,0);
pthread_join(g,0);
pthread_join(h,0);
pthread_join(j,0);
}
| 1
|
#include <pthread.h>
sem_t semph[5];
pthread_mutex_t mutex;
void* philosopher(void* param);
int main(int argc, char* argv[])
{
int i;
srand(getpid());
pthread_t PhilosopherThread[5];
int phId[5];
pthread_mutex_init(&mutex, 0);
for (i=0; i<5; i++)
{
phId[i] = i;
sem_init(&semph[i], 0, 1);
pthread_create(&PhilosopherThread[i], 0, philosopher, (void*)(&phId[i]));
usleep(5000);
}
sleep(30);
return 0;
}
void* philosopher(void* param)
{
int myid;
char stateStr[128];
char mystate;
int ret;
unsigned int leftFork;
unsigned int rightFork;
myid = *((int*)(param));
printf("philosopher %d begin ....\\n", myid);
usleep(1000000);
mystate = 1;
leftFork = (myid) % 5;
rightFork = (myid + 1) % 5;
while (1)
{
switch(mystate)
{
case 1:
mystate = 2;
strcpy(stateStr, "HUNGRY");
break;
case 2:
strcpy(stateStr, "HUNGRY");
ret = sem_trywait(&semph[leftFork]);
if (ret == 0)
{
ret = sem_trywait(&semph[rightFork]);
if (ret == 0)
{
mystate = 3;
strcpy(stateStr, "DINING");
}
else
{
sem_post(&semph[leftFork]);
}
}
break;
case 3:
sem_post(&semph[leftFork]);
sem_post(&semph[rightFork]);
mystate = 1;
strcpy(stateStr, "THINKING");
break;
}
pthread_mutex_lock(&mutex);
printf("philosopher %d is : %s\\n", myid, stateStr);
pthread_mutex_unlock(&mutex);
int sleepTime;
sleepTime = 1 + (int)(5.0*rand()/(32767 +1.0));
usleep(sleepTime*100000);
}
}
| 0
|
#include <pthread.h>
int *buffer;
int count;
pthread_mutex_t mutex;
pthread_cond_t condp, condc;
int produzItem (int base) {
usleep(100);
return base;
}
int consomeItem (int item) {
usleep(100);
return item;
}
void *produtor(void *param) {
int k=1, in=0;
while ( k<=1000 ) {
pthread_mutex_lock(&mutex);
if (count == 10)
pthread_cond_wait(&condp, &mutex);
pthread_mutex_unlock(&mutex);
int item = produzItem (k);
buffer[in] = item;
in = (in + 1) % 10;
k++;
pthread_mutex_lock(&mutex);
count++;
if(count == 1)
pthread_cond_signal(&condc);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void *consumidor(void *param) {
int k=1, out=0;
double mean=0;
while (k<=1000) {
pthread_mutex_lock(&mutex);
if (count == 0)
pthread_cond_wait(&condc, &mutex);
pthread_mutex_unlock(&mutex);
int item = buffer[out];
out = (out + 1) % 10;
k++;
pthread_mutex_lock(&mutex);
count--;
if (count == 10 - 1)
pthread_cond_signal(&condp);
pthread_mutex_unlock(&mutex);
mean += consomeItem (item);
}
mean /= 1000;
printf ("Consumer: Mean value is %.1f.\\n", mean);
pthread_exit(0);
}
int main (int argc, char *argv[])
{
buffer = (int *)malloc( 10 * sizeof(int) );
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&condp, 0);
pthread_cond_init(&condc, 0);
pthread_t prod_t;
pthread_t cons_t;
pthread_create(&prod_t, 0, produtor, 0);
pthread_create(&cons_t, 0, consumidor, 0);
printf ("Main(): Launched all threads.\\n");
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int
main(int argc, char **argv)
{
int i, tnum, ramp, allcox, connum, k, cfd;
uint64_t allrps, allbps;
char *p, hbuf[256], prt[8], erbuf[256];
pthread_t tid;
struct timespec tick, tock;
struct addrinfo hints, *res, *r;
struct epoll_event ev = {.events = EPOLLIN};
if (argc < 5) {
exit(1);
}
if ( sscanf(argv[1], "%d", &tnum) < 1 ||
sscanf(argv[2], "%d", &ramp) < 1 ||
sscanf(argv[3], "%lu", &vernum) < 1) goto meh;
if (tnum < 1) {
fputs("At least 1 thread, please!\\n", stderr);
exit(1);
}
if ( (p = strstr(argv[4], "://")) != 0) hp = p + 3;
else hp = argv[4];
if ( (gp = strstr(hp, "/")) == 0) {
fputs("URL needs closing slash!\\n", stderr);
exit(1);
}
gl = strlen(gp);
if ( (p = strstr(hp, ":")) != 0 && p < gp) {
i = gp - p - 1;
memcpy(prt, p + 1, i);
prt[i] = '\\0';
*p = '\\0';
hl = p - hp;
} else {
memcpy(prt, "80\\0", 3);
hl = gp - hp;
if (hl > sizeof(hbuf) - 1) {
fputs("Hostname is too long!\\n", stderr);
exit(1);
}
memcpy(hbuf, hp, hl);
hbuf[hl] = '\\0';
hp = hbuf;
}
bzero(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ( (i = getaddrinfo(hp, prt, &hints, &res)) != 0) {
fputs("getaddrinfo: ", stderr);
fputs(gai_strerror(i), stderr);
exit(1);
}
if ( (th = calloc(tnum + 1, sizeof(struct qstat))) == 0) {
fputs("No memory!\\n", stderr);
exit(1);
}
for (i = 0; i < tnum; i++) {
if ( (th[i].efd = epoll_create(ECHUNK)) < 0) {
perror("epoll_create");
exit(1);
}
pthread_mutex_init(&th[i].mx, 0);
if ( (errno = pthread_create(&tid, 0, wkr, &th[i])) != 0) {
perror("pthread_create");
exit(1);
}
}
pthread_mutex_init(&th[tnum].mx, 0);
clock_gettime(CLOCK_MONOTONIC, &tick);
tick.tv_sec -= 1;
connum = k = 0;
for (; ;) {
allcox = allrps = allbps = 0;
if (clock_gettime(CLOCK_MONOTONIC, &tock) < 0) {
perror("clock_gettime");
exit(1);
}
for (i = 0; i <= tnum; i++) {
pthread_mutex_lock(&th[i].mx);
allcox += th[i].cox;
allrps += th[i].rps;
allbps += th[i].bps;
th[i].cox = 0;
th[i].rps = 0;
th[i].bps = 0;
pthread_mutex_unlock(&th[i].mx);
}
connum -= allcox;
tick.tv_sec = tock.tv_sec - tick.tv_sec;
if ( (tick.tv_nsec = tock.tv_nsec - tick.tv_nsec) < 0) {
tick.tv_sec--;
tick.tv_nsec += 1000000000;
}
tick.tv_sec = tick.tv_nsec / 1000000 + tick.tv_sec * 1000;
allrps = allrps * 1000 / tick.tv_sec;
allbps = allbps * 8 / tick.tv_sec;
for (i = 0; tick.tv_sec > (i * 1000 + 500) * PERIOD; i++) {
printf("%*d %*d %*d ", 8, connum, 8, (int) allrps, 8, (int) allbps);
if (scf) printf(" *SRVCLOSE*");
if (sre) {
strerror_r(sre, erbuf, sizeof(erbuf));
printf(" SND: %s", erbuf);
}
if (coe) {
strerror_r(coe, erbuf, sizeof(erbuf));
printf(" CON: %s", erbuf);
}
printf("\\n");
}
fflush(stdout);
coe = sre = scf = 0;
for (i = 0; (argc < 6 && i < ramp) || (argc == 6 && connum < ramp); i++) {
r = res;
do {
cfd = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
if (cfd < 0) continue;
if (connect(cfd, r->ai_addr, r->ai_addrlen) == 0) break;
while (close(cfd) < 0 && errno == EINTR);
} while ( (r = r->ai_next) != 0);
if (r == 0) {
coe = errno;
break;
}
connum++;
ev.data.u64 = (uint64_t) cfd;
if (epoll_ctl(th[k].efd, EPOLL_CTL_ADD, cfd, &ev) < 0) {
perror("epoll_ctl_add");
exit(1);
}
if (++k >= tnum) k = 0;
send_req(cfd, &th[tnum]);
}
memcpy(&tick, &tock, sizeof(tick));
tock.tv_sec += PERIOD;
while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &tock, 0) < 0 && errno == EINTR);
}
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t exit_code_lock = PTHREAD_MUTEX_INITIALIZER;
static uint8_t exit_code = 0;
void set_exit_code(uint8_t value)
{
pthread_mutex_lock(&exit_code_lock);
exit_code = value;
pthread_mutex_unlock(&exit_code_lock);
}
bool is_exiting()
{
bool is_exit_code_set = 0;
pthread_mutex_lock(&exit_code_lock);
if (exit_code != 0) {
is_exit_code_set = 1;
}
pthread_mutex_unlock(&exit_code_lock);
return is_exit_code_set;
}
uint8_t get_exit_code() {
return exit_code;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t sem_nfree;
int available[20] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
void *runStation(void *ptr);
void *runMachine(void *ptr);
void setup(int stations, int machines)
{
pthread_t kstation_thread[5];
sem_init(&sem_nfree, 0, 20);
int j;
int k;
for(k = 0; k < 5; k++)
{
pthread_create(&kstation_thread[k], 0, &runStation, (void *)&k);
printf("SETUP: Creating K_STATIONS thread %d\\n", k);
}
pthread_t nmachine_thread[20];
for (j = 0; j < 20; j++)
{
pthread_create(&nmachine_thread[j], 0, &runMachine, (void *)&j);
printf("SETUP: Creating N_MACHINES thread %d\\n", j);
}
sem_wait(&sem_nfree);
sem_post(&sem_nfree);
}
void *runMachine(void *ptr)
{
while(1)
{
pthread_mutex_lock(&mutex);
sleep(5);
pthread_mutex_unlock(&mutex);
}
}
int allocate()
{
int i;
sem_wait(&sem_nfree);
pthread_mutex_lock(&mutex);
for(i = 0; i < 20; i++)
{
if (available[i] != 0)
{
available[i] = 0;
pthread_mutex_lock(&mutex);
return i;
}
}
return 0;
}
void release(int machine)
{
pthread_mutex_lock(&mutex);
available[machine] = 1;
pthread_mutex_unlock(&mutex);
sem_post(&sem_nfree);
}
void *runStation(void *ptr)
{
}
int main(int argc, char **argv)
{
return 0;
}
| 0
|
#include <pthread.h>
unsigned int REG_TEST[2] = {
REG_MEMORY_A,
REG_MEMORY_B,
};
unsigned int TEST_VALUE_RW[4] = { 0x000000,
0xFFFFFF,
0x555555,
0xAAAAAA
};
int VT_mc13783_RW_setup(void) {
int rv = TFAIL;
rv = TPASS;
return rv;
}
int VT_mc13783_RW_cleanup(void) {
int rv = TFAIL;
rv = TPASS;
return rv;
}
int VT_mc13783_test_RW(void) {
int rv = TPASS, fd, i, j;
unsigned int valueW = 0, valueR = 0, reg = 0;
fd = open(MC13783_DEVICE, O_RDWR);
if (fd < 0) {
pthread_mutex_lock(&mutex);
tst_resm(TFAIL, "Unable to open %s", MC13783_DEVICE);
pthread_mutex_unlock(&mutex);
return TFAIL;
}
for (i = 0; i < 2; i++) {
reg = REG_TEST[i];
for (j = 0; j < 4; j++) {
valueW = TEST_VALUE_RW[j];
valueR = 0;
if (VT_mc13783_write(fd, reg, valueW) != TPASS) {
rv = TFAIL;
} else {
if (VT_mc13783_read(fd, reg, &valueR) !=
TPASS) {
rv = TFAIL;
}
if (valueR != valueW) {
pthread_mutex_lock(&mutex);
printf
("Test ERROR Read/Write res1=0x%X"
" val=0x%X\\n", valueW,
valueR);
pthread_mutex_unlock(&mutex);
rv = TFAIL;
}
}
}
}
if (close(fd) < 0) {
pthread_mutex_lock(&mutex);
tst_resm(TFAIL, "Unable to close file descriptor %d",
fd);
pthread_mutex_unlock(&mutex);
return TFAIL;
}
return rv;
}
| 1
|
#include <pthread.h>
int* row;
int stability;
pthread_mutex_t mutex;
}grid_t;
int counter;
int stability;
pthread_mutex_t mutex;
pthread_cond_t condition;
}barrier_t;
pthread_t thread;
barrier_t* barrier;
grid_t* grid;
int thread_id;
int numthreads;
int gridsize;
int region_stability;
int grid_stability;
int initial_cell;
int final_cell;
}tinfo_t;
void barrier_init(barrier_t* b, int numthreads) {
b->counter = numthreads;
b->stability = numthreads;
pthread_cond_init(&b->condition,0);
pthread_mutex_init(&b->mutex, 0);
}
int barrier_wait(barrier_t* barrier,int numthreads, int stability) {
pthread_mutex_lock(&barrier->mutex);
barrier->counter--;
barrier->stability -= stability;
if (barrier->counter == 0) {
pthread_cond_broadcast(&barrier->condition);
if (barrier->stability == 0) {
pthread_mutex_unlock(&barrier->mutex);
return 1;
}
barrier->counter = numthreads;
barrier->stability = numthreads;
} else {
pthread_cond_wait(&barrier->condition,&barrier->mutex);
if (barrier->stability == 0) {
pthread_mutex_unlock(&barrier->mutex);
return 1;
}
}
pthread_mutex_unlock(&barrier->mutex);
return 0;
}
void print_grid(tinfo_t* tinfo) {
for(int i = 0; i < tinfo->gridsize; i++) {
printf("\\n");
for(int j = 0; j < tinfo->gridsize; j++) {
printf("%d ",tinfo->grid[i].row[j]);
}
}
printf("\\n");
}
void lock_threads(tinfo_t* tinfo, int rownumber) {
if(rownumber == tinfo->initial_cell) {
pthread_mutex_lock(&tinfo->grid[rownumber].mutex);
}
if(rownumber - 1 <= tinfo->initial_cell && rownumber > 0) {
pthread_mutex_lock(&tinfo->grid[rownumber-1].mutex);
}
if(rownumber + 1 >= tinfo->final_cell - 1 && rownumber < tinfo->gridsize - 1) {
pthread_mutex_lock(&tinfo->grid[rownumber+1].mutex);
}
if(rownumber == tinfo->final_cell - 1) {
pthread_mutex_lock(&tinfo->grid[rownumber].mutex);
}
}
void unlock_threads(tinfo_t* tinfo, int rownumber) {
if(rownumber == tinfo->initial_cell || rownumber == tinfo->final_cell - 1) {
pthread_mutex_unlock(&tinfo->grid[rownumber].mutex);
}
if(rownumber + 1 >= tinfo->final_cell-1 && rownumber < tinfo->gridsize - 1) {
pthread_mutex_unlock(&tinfo->grid[rownumber+1].mutex);
}
if(rownumber - 1 <= tinfo->initial_cell && rownumber > 0) {
pthread_mutex_unlock(&tinfo->grid[rownumber-1].mutex);
}
}
void compute(tinfo_t* tinfo) {
tinfo->region_stability = 1;
for(int i = tinfo->initial_cell; i < tinfo->final_cell; i++) {
lock_threads(tinfo,i);
while(tinfo->grid[i].stability == 0) {
tinfo->grid[i].stability = 1;
for(int j = 0; j < tinfo->gridsize; j++) {
if(tinfo->grid[i].row[j] >= 4) {
tinfo->grid[i].row[j] -= 4;
tinfo->grid[i].stability = 0;
tinfo->region_stability = 0;
if(i-1 < tinfo->initial_cell || i+1 == tinfo->final_cell) {
tinfo->grid_stability = 0;
}
if (i > 0) {
tinfo->grid[i-1].row[j] += 1;
tinfo->grid[i-1].stability = 0;
}
if (i < tinfo->gridsize - 1) {
tinfo->grid[i+1].row[j] += 1;
tinfo->grid[i+1].stability = 0;
}
if (j > 0) {
tinfo->grid[i].row[j-1] += 1;
}
if(j < tinfo->gridsize - 1) {
tinfo->grid[i].row[j+1] += 1;
}
}
}
}
print_grid(tinfo);
unlock_threads(tinfo,i);
}
}
void sandpile_simulation(tinfo_t *tinfo) {
while(1) {
compute(tinfo);
if(tinfo->region_stability == 1) {
int stability = tinfo->grid_stability & tinfo->region_stability;
if(barrier_wait(tinfo->barrier,tinfo->numthreads,stability) == 1) {
break;
}
tinfo->grid_stability = 1;
barrier_wait(tinfo->barrier, tinfo->numthreads,stability);
}
}
}
int main(int argc, char **argv) {
clock_t initial_cell = clock();
int numthreads = atoi(argv[1]);
int gridsize = atoi(argv[2]);
int height = atoi(argv[3]);
static grid_t* grid;
grid = (grid_t*)malloc(gridsize*sizeof(grid_t));
for (int i = 0; i < gridsize; i++) {
grid[i].stability = 0;
grid[i].row = (int*)malloc(gridsize*sizeof(int));
pthread_mutex_init(&grid[i].mutex,0);
for (int j = 0; j < gridsize; j++) {
grid[i].row[j] = 0;
}
}
grid[gridsize/2].row[gridsize/2] = height;
tinfo_t tinfo[numthreads];
static barrier_t barrier;
barrier_init(&barrier,numthreads);
for(int i = 0; i < numthreads; i++) {
tinfo[i].numthreads = numthreads;
tinfo[i].thread_id = i;
tinfo[i].barrier = &barrier;
tinfo[i].grid = grid;
tinfo[i].initial_cell = (gridsize/(numthreads))*(i);
tinfo[i].final_cell = (gridsize/(numthreads))*(i+1);
tinfo[i].gridsize = gridsize;
tinfo[i].region_stability = 1;
tinfo[i].grid_stability = 1;
if(i != 0) {
pthread_create(&tinfo[i].thread, 0, (void*(*)(void*))sandpile_simulation, &tinfo[i]);
}
}
sandpile_simulation(&tinfo[0]);
print_grid(&tinfo[0]);
clock_t final_cell = clock();
double time = ((double)(final_cell - initial_cell))/ CLOCKS_PER_SEC;
printf("Time: %f secs\\n",time);
}
| 0
|
#include <pthread.h>
static void ctx_assertf2(const char *file, const char *func, int line,
const char *asserttxt, const char *fmt, va_list argptr)
{
pthread_mutex_lock(&ctx_biglock);
fflush(stdout);
fprintf(stderr, "[%s:%i] Assert Failed %s(): %s", file, line, func, asserttxt);
if(fmt != 0) {
fputs(": ", stderr);
vfprintf(stderr, fmt, argptr);
}
fprintf(stderr, "\\n");
timestampf(stderr);
fputs(" Assert Error\\n", stderr);
fflush(stderr);
pthread_mutex_unlock(&ctx_biglock);
}
void ctx_assertf_no_abort(const char *file, const char *func, int line,
const char *asserttxt, const char *fmt, ...)
{
va_list argptr;
__builtin_va_start((argptr));
ctx_assertf2(file, func, line, asserttxt, fmt, argptr);
;
}
void ctx_assertf(const char *file, const char *func, int line,
const char *asserttxt, const char *fmt, ...)
{
va_list argptr;
__builtin_va_start((argptr));
ctx_assertf2(file, func, line, asserttxt, fmt, argptr);
;
abort();
}
| 1
|
#include <pthread.h>
int cliente;
sem_t pedido;
}TVENDEDOR;
TVENDEDOR vendedores[5] = {0};
int senha = 1;
int proximo = 1;
pthread_mutex_t mutex_senha = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_proximo = PTHREAD_MUTEX_INITIALIZER;
void atende_cliente(int vendedor, int cliente){
printf("Cliente %d atendido pelo vendedor %d\\n", cliente, vendedor);
}
void faz_pedido(int i){
}
void *vendedor(void *args){
int id = *((int*)args);
while (1) {
pthread_mutex_lock(&mutex_proximo);
if(proximo > 25){
break;
}
printf("Vendedor %d chama cliente %d\\n", id+1, proximo);
vendedores[id].cliente = proximo++;
pthread_mutex_unlock(&mutex_proximo);
sem_wait(&vendedores[id].pedido);
atende_cliente(id+1, vendedores[id].cliente);
}
pthread_exit(0);
}
void *cliente(void *args){
int numero, i, atendido;
pthread_mutex_lock(&mutex_senha);
printf("Cliente chegou e pegou a senha %d\\n", senha);
numero = senha++;
pthread_mutex_unlock(&mutex_senha);
atendido = 0;
while (!atendido){
for (i = 0; i < 5; i++)
if (vendedores[i].cliente == numero) {
atendido = 1;
break;
}
}
sem_post(&vendedores[i].pedido);
faz_pedido(i);
pthread_exit(0);
}
int main(int argc, char const *argv[]){
pthread_t threads_vendedores[5], threads_clientes[25];
for(int i = 0; i < 5; i++) {
sem_init(&vendedores[i].pedido, 0, 0);
int *args = malloc(sizeof(int*));
*args = i;
int r = pthread_create(&threads_vendedores[i], 0, vendedor, (void*)args);
if(r) {
exit(1);
}
}
for(int i = 0; i < 25; i++){
int r = pthread_create(&threads_clientes[i], 0, cliente, 0);
if(r) {
exit(1);
}
}
for(int i=0; i < 5; i++) {
pthread_join(threads_vendedores[i], 0);
}
for(int i=0; i < 25; i++) {
pthread_join(threads_clientes[i], 0);
}
return 0;
}
| 0
|
#include <pthread.h>
struct Message
{
pthread_t tid;
double value;
}thr[100];
double Money ;
int number ;
int k = 0;
double Rands_number(double LeftMoney)
{
srand((unsigned)time(0));
double value= rand()/(double)(32767/LeftMoney);
int temp = value*100;
value = ((double)temp/100);
return value;
}
void *Main_thread()
{
printf("开始抢红包啦!\\t金额=%lf\\n",Money);
}
pthread_mutex_t lock;
void *thread1()
{
pthread_mutex_lock (&lock);
double value;
if(number != 1)
value = Rands_number(Money);
else
value = Money;
thr[k++].value = value;
Money -= value;
number--;
pthread_mutex_unlock(&lock);
}
int main()
{
int i ;
printf("input the number and Money:");
scanf("%d%lf",&number,&Money);
int total = number;
for(i = 0;i < total;i++)
{
if((pthread_create(&(thr[i].tid),0,thread1,0)) )
perror("thread failed");
}
for(int j = 0;j < total;j++)
{
printf("Money:%.2lf\\n",thr[j].value);
}
pthread_mutex_destroy(&lock);
return 0;
}
| 1
|
#include <pthread.h>
buffer_t buffer[10];
int buffer_index;
pthread_mutex_t buffer_lock;
pthread_cond_t full_cond, empty_cond;
void insertbuffer(buffer_t value) {
if (buffer_index < 10) {
buffer[buffer_index++] = value;
} else {
printf("Buffer overflow\\n");
}
}
buffer_t dequeuebuffer() {
if (buffer_index > 0) {
return buffer[--buffer_index];
} else {
printf("Buffer underflow\\n");
}
return 0;
}
int isempty() {
if (buffer_index == 0)
return 1;
return 0;
}
int isfull() {
if (buffer_index == 10)
return 1;
return 0;
}
void *producer(void *thread_n) {
int i = 0;
int value;
int thread_numb = *(int *)thread_n;
while (i++ < 2) {
sleep(rand() % 10);
value = rand() % 100;
pthread_mutex_lock(&buffer_lock);
while (isfull()) {
pthread_cond_wait(&full_cond, &buffer_lock);
}
if (isempty()) {
insertbuffer(value);
pthread_cond_signal(&empty_cond);
} else {
insertbuffer(value);
}
printf("Producer thread %d inserted %d\\n", thread_numb, value);
pthread_mutex_unlock(&buffer_lock);
}
pthread_exit(0);
}
void *consumer(void *thread_n) {
int i = 0;
buffer_t value;
int thread_numb = *(int *)thread_n;
while (i++ < 2) {
pthread_mutex_lock(&buffer_lock);
while(isempty()) {
pthread_cond_wait(&empty_cond, &buffer_lock);
}
if (isfull()) {
value = dequeuebuffer();
pthread_cond_signal(&full_cond);
} else {
value = dequeuebuffer();
}
printf("Consumer thread %d processed %d\\n", thread_numb, value);
pthread_mutex_unlock(&buffer_lock);
}
pthread_exit(0);
}
int main(int argc, int *argv[]) {
buffer_index = 0;
pthread_t thread[10];
int thread_num[10];
pthread_mutex_init(&buffer_lock, 0);
pthread_cond_init(&empty_cond, 0);
pthread_cond_init(&full_cond, 0);
int i = 0;
for (i = 0; i < 10; ) {
thread_num[i] = i;
pthread_create(&thread[i],
0,
producer,
&thread_num[i]);
i++;
thread_num[i] = i;
pthread_create(&thread[i],
0,
consumer,
&thread_num[i]);
i++;
}
for (i = 0; i < 10; i++)
pthread_join(thread[i], 0);
pthread_mutex_destroy(&buffer_lock);
pthread_cond_destroy(&full_cond);
pthread_cond_destroy(&empty_cond);
return 0;
}
| 0
|
#include <pthread.h>
struct foo {
int f_count;
int f_id;
pthread_mutex_t f_lock;
};
struct foo *foo_alloc(int id)
{
struct foo *fp;
if((fp = malloc(sizeof(struct foo))) != 0){
fp->f_count = 1;
fp->f_id = id;
if(pthread_mutex_init(fp->f_lock, 0) != 0){
free(fp);
return 0;
}
}
return fp;
}
void foo_hold(struct foo *fp)
{
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
void foo_rele(struct foo *fp)
{
pthread_mutex_lock(&fp->f_lock);
if(--fp->f_count == 0){
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
} else {
pthread_mutex_unlock(&fp->f_lock);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t countLock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t countCV = PTHREAD_COND_INITIALIZER;
int counter = 0;
void* worker(void* arg){
int threadID = *((int*)arg);
printf("hello im worker thread %i\\n",threadID);
for(int i=0;i<10;i++){
pthread_mutex_lock(&countLock);
printf("Worker %i aqquired mutex, incrementing counter to %i\\n",threadID,1+counter);
counter ++;
if(counter == 12){
pthread_cond_signal(&countCV);
printf("Worker %i signaling watcher and releasing MUTEX \\n",threadID);
}
pthread_mutex_unlock(&countLock);
sleep(1);
}
printf("Worker thread %i finishing\\n\\n",threadID);
pthread_exit(0);
}
void* watcher(void* arg){
int threadID = *(int*)arg;
printf("hello im watcher thread %i\\n",threadID);
pthread_mutex_lock(&countLock);
while(counter != 12){
printf("Watcher: Count != 12, sleeping..\\n");
pthread_cond_wait(&countCV, &countLock);
printf("Watcher: Awoken\\n");
}
printf("Watcher: Counter = 12, consuming the 12\\n");
counter = 0;
pthread_mutex_unlock(&countLock);
printf("Watcher: Unlocking the mutex\\n\\n");
pthread_exit(0);
}
int main(){
pthread_t threads[3];
int t0 = 0, t1 = 1, t2 = 2;
pthread_create(&threads[0],0,worker,(void*)(&t0));
pthread_create(&threads[1],0,worker,(void*)(&t1));
pthread_create(&threads[2],0,watcher,(void*)(&t2));
for(int i=0;i<3;i++){
pthread_join(threads[i],0);
}
printf("\\n\\n All threads finished: counter = %i\\n\\n",counter);
pthread_mutex_destroy(&countLock);
pthread_cond_destroy(&countCV);
return 0;
}
| 0
|
#include <pthread.h>
int
timer_delete (timerid)
timer_t timerid;
{
struct timer *kt = (struct timer *) timerid;
int res = INLINE_SYSCALL (timer_delete, 1, kt->ktimerid);
if (res == 0)
{
if (kt->sigev_notify == SIGEV_THREAD)
{
pthread_mutex_lock (&__active_timer_sigev_thread_lock);
if (__active_timer_sigev_thread == kt)
__active_timer_sigev_thread = kt->next;
else
{
struct timer *prevp = __active_timer_sigev_thread;
while (prevp->next != 0)
if (prevp->next == kt)
{
prevp->next = kt->next;
break;
}
else
prevp = prevp->next;
}
pthread_mutex_unlock (&__active_timer_sigev_thread_lock);
}
(void) free (kt);
return 0;
}
return -1;
}
| 1
|
#include <pthread.h>
uid_t procrealuid = 0;
uid_t proceffuid = 0;
int str_to_u(const char* s, unsigned* u){
char* p;
unsigned o;
errno = 0;
o = strtoul(s, &p, 0);
if(errno || *p){
return -1;
}
*u = o;
return 0;
}
int read_complete(int fd, void* buf, size_t count){
char* bufp = (char*)buf;
size_t curcount = 0;
int rval;
do{
rval = read(fd, bufp, count - curcount);
if(rval < 0){
return rval;
}else if(rval == 0){
return curcount;
}else{
bufp += rval;
curcount += rval;
}
}while(curcount < count);
return count;
}
int strerror_threadsafe(int errnum, char* buf, size_t buflen){
static pthread_mutex_t strerror_call_mutex = PTHREAD_MUTEX_INITIALIZER;
char* rval;
int rlen;
pthread_mutex_lock(&strerror_call_mutex);
rval = strerror(errnum);
rlen = strlen(rval);
if(buflen < rlen){
pthread_mutex_unlock(&strerror_call_mutex );
return -1;
}
strcpy(buf, rval);
pthread_mutex_unlock(&strerror_call_mutex);
return 0;
}
int sprintf_malloc(char** strstore, const char* format, ...){
int len;
char* newstr;
va_list ap;
__builtin_va_start((ap));
len = vsnprintf(0, 0, format, ap) + 1;
;
newstr = malloc(len);
if(newstr == 0){
return -1;
}
__builtin_va_start((ap));
len = vsnprintf(newstr, len, format, ap);
;
*strstore = newstr;
return len;
}
void checktimespec(struct timespec* arg){
long tominus;
if(arg->tv_nsec >= 1000000000){
arg->tv_sec += (arg->tv_nsec / 1000000000);
arg->tv_nsec %= 1000000000;
}else if(arg->tv_nsec < 0){
if((-(arg->tv_nsec)) % 1000000000 == 0){
arg->tv_sec -= ((-(arg->tv_nsec)) / 1000000000);
arg->tv_nsec = 0;
}else{
tominus = (((-(arg->tv_nsec)) / 1000000000) + 1);
arg->tv_sec -= tominus;
arg->tv_nsec += tominus * 1000000000;
}
}
}
void difftimespec(start, end, out)
const struct timespec* start;
const struct timespec* end;
struct timespec* out;
{
out->tv_sec = end->tv_sec - start->tv_sec;
out->tv_nsec = end->tv_nsec - start->tv_nsec;
if(out->tv_nsec < 0){
out->tv_nsec += 1000000000;
out->tv_sec--;
}
}
int comparetimespec(t1, t2)
const struct timespec* t1;
const struct timespec* t2;
{
if(t1->tv_sec < t2->tv_sec){
return -1;
}else if(t1->tv_sec > t2->tv_sec){
return 1;
}else{
if(t1->tv_nsec < t2->tv_nsec){
return -1;
}else if(t1->tv_nsec > t2->tv_nsec){
return 1;
}else{
return 0;
}
}
return 0;
}
void save_uids(void){
procrealuid = getuid();
proceffuid = geteuid();
}
void disable_setuid(void){
setreuid(proceffuid, procrealuid);
}
void enable_setuid(void){
setreuid(procrealuid, proceffuid);
}
| 0
|
#include <pthread.h>
const int SIGMA = 5;
int *array;
int array_index = -1;
pthread_mutex_t lock;
void *thread(void * arg)
{
pthread_mutex_lock(&lock);
int curidx = array_index;
array[array_index] = 1;
int cur = array[array_index];
pthread_mutex_unlock(&lock);
return 0;
}
int main()
{
int tid, sum;
pthread_t *t;
pthread_mutex_init(&lock, 0);
t = (pthread_t *)malloc(sizeof(pthread_t) * SIGMA);
array = (int *)malloc(sizeof(int) * SIGMA);
for (tid=0; tid<SIGMA; tid++) {
pthread_mutex_lock(&lock);
pthread_create(&t[tid], 0, thread, 0);
array_index++;
pthread_mutex_unlock(&lock);
}
for (tid=0; tid<SIGMA; tid++) {
pthread_join(t[tid], 0);
}
for (tid=sum=0; tid<SIGMA; tid++) {
sum += array[tid];
}
assert(sum == SIGMA);
return 0;
}
| 1
|
#include <pthread.h>
void lock_range(int begin, int end) {
for (int i = begin; i < end; ++i) {
pthread_mutex_lock(&Locks[i]);
}
}
void unlock_range(int begin, int end) {
for (int i = begin; i < end; ++i) {
pthread_mutex_unlock(&Locks[i]);
}
}
bool is_locked(int lock) {
int status = pthread_mutex_trylock(&Locks[lock]);
if (status == 0) {
pthread_mutex_unlock(&Locks[lock]);
return 0;
} else if (status == EBUSY) {
return 1;
} else {
fprintf(stderr, "Broken lock!\\n");
exit(1);
}
}
bool is_unlocked(int lock) {
return !is_locked(lock);
}
bool are_all(int begin, int end, bool (*f)(int)) {
for (int i = begin; i < end; ++i) {
if (!f(i)) {
return 0;
}
}
return 1;
}
int main() {
int philo0 = 0;
int philo2 = 2;
EXPECT_EQ(are_all(0, NUM_FORKS, is_unlocked), 1);
get_chopsticks(philo0);
EXPECT_EQ(are_all(0, 2, is_locked), 1);
EXPECT_EQ(are_all(2, NUM_FORKS, is_unlocked), 1);
put_chopsticks(philo0);
EXPECT_EQ(are_all(0, NUM_FORKS, is_unlocked), 1);
get_chopsticks(philo0);
EXPECT_EQ(are_all(0, 2, is_locked), 1);
EXPECT_EQ(are_all(2, NUM_FORKS, is_unlocked), 1);
get_chopsticks(philo2);
EXPECT_EQ(are_all(0, 4, is_locked), 1);
EXPECT_EQ(are_all(4, NUM_FORKS, is_unlocked), 1);
put_chopsticks(philo0);
put_chopsticks(philo2);
EXPECT_EQ(are_all(0, NUM_FORKS, is_unlocked), 1);
return RETURN_VALUE;
}
| 0
|
#include <pthread.h>
pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c1 = PTHREAD_COND_INITIALIZER;
int t1_is_ready = 0;
pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c2 = PTHREAD_COND_INITIALIZER;
int t2_is_ready = 0;
void* t1_work(void* arg)
{
pthread_mutex_lock(&m1);
printf("thread t1 does its work\\n");
t1_is_ready = 1;
pthread_mutex_unlock(&m1);
pthread_cond_signal(&c1);
pthread_exit(0);
}
void* t2_work(void* arg)
{
pthread_mutex_lock(&m1);
while(t1_is_ready == 0)
{
pthread_cond_wait(&c1, &m1);
}
pthread_mutex_unlock(&m1);
pthread_mutex_lock(&m2);
printf("thread t2 does its work\\n");
t2_is_ready = 1;
pthread_mutex_unlock(&m2);
pthread_cond_signal(&c2);
pthread_exit(0);
}
void* t3_work(void* arg)
{
pthread_mutex_lock(&m2);
while(t2_is_ready == 0)
{
pthread_cond_wait(&c2, &m2);
}
printf("thread t3 does its work\\n");
pthread_mutex_unlock(&m2);
pthread_exit(0);
}
int main(void)
{
pthread_t t1;
pthread_t t2;
pthread_t t3;
pthread_create(&t1, 0, t1_work, 0);
pthread_create(&t2, 0, t2_work, 0);
pthread_create(&t3, 0, t3_work, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_join(t3, 0);
return 0;
}
| 1
|
#include <pthread.h>
const char plugin_name[] = "SLURM Backfill Scheduler plugin";
const char plugin_type[] = "sched/backfill";
const uint32_t plugin_version = SLURM_VERSION_NUMBER;
static int plugin_errno = SLURM_SUCCESS;
static pthread_t backfill_thread = 0;
static pthread_mutex_t thread_flag_mutex = PTHREAD_MUTEX_INITIALIZER;
int init( void )
{
pthread_attr_t attr;
if (slurmctld_config.scheduling_disabled)
return SLURM_SUCCESS;
verbose( "sched: Backfill scheduler plugin loaded" );
pthread_mutex_lock( &thread_flag_mutex );
if ( backfill_thread ) {
debug2( "Backfill thread already running, not starting "
"another" );
pthread_mutex_unlock( &thread_flag_mutex );
return SLURM_ERROR;
}
slurm_attr_init( &attr );
if (pthread_create( &backfill_thread, &attr, backfill_agent, 0))
error("Unable to start backfill thread: %m");
pthread_mutex_unlock( &thread_flag_mutex );
slurm_attr_destroy( &attr );
return SLURM_SUCCESS;
}
void fini( void )
{
pthread_mutex_lock( &thread_flag_mutex );
if ( backfill_thread ) {
verbose( "Backfill scheduler plugin shutting down" );
stop_backfill_agent();
pthread_join(backfill_thread, 0);
backfill_thread = 0;
}
pthread_mutex_unlock( &thread_flag_mutex );
}
int slurm_sched_p_reconfig( void )
{
backfill_reconfig();
return SLURM_SUCCESS;
}
int slurm_sched_p_schedule(void)
{
return SLURM_SUCCESS;
}
int slurm_sched_p_newalloc(struct job_record *job_ptr)
{
return SLURM_SUCCESS;
}
int slurm_sched_p_freealloc(struct job_record *job_ptr)
{
return SLURM_SUCCESS;
}
uint32_t slurm_sched_p_initial_priority(uint32_t last_prio,
struct job_record *job_ptr)
{
return priority_g_set(last_prio, job_ptr);
}
void slurm_sched_p_job_is_pending( void )
{
}
void slurm_sched_p_partition_change( void )
{
}
int slurm_sched_p_get_errno( void )
{
return plugin_errno;
}
char *slurm_sched_p_strerror( int errnum )
{
return 0;
}
void slurm_sched_p_requeue( struct job_record *job_ptr, char *reason )
{
}
char *slurm_sched_p_get_conf( void )
{
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t l[5], mutex;
char name[][10] = {"XYQ", "PROF. CXQ", "TA. YPF", "TA. LHR", "TA. WCK"};
void mythread(void * arg) {
int k, o = 0;
int id = ((int)arg);
int id2 = (id + 1) % 5;
char *_name = name[id];
pthread_mutex_lock(&l[id]);
for (k = 0; k != 10000000; ++k) o ++;
pthread_mutex_lock(&mutex);
cprintf("%s pick up left fork! \\n", _name);
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&l[id2]);
pthread_mutex_lock(&mutex);
cprintf("%s pick up right fork! \\n", _name);
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&mutex);
cprintf("%s start eating! Yumyum \\n", _name);
pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&l[id]);
pthread_mutex_lock(&mutex);
cprintf("%s put down left fork! \\n", _name);
pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&l[id2]);
pthread_mutex_lock(&mutex);
cprintf("%s put down right fork! \\n", _name);
pthread_mutex_unlock(&mutex);
}
void
umain(int argc, char **argv)
{
cprintf("==================================\\n");
int i;
for (i = 0; i != 5; ++i)
pthread_mutex_init(&l[i], 0);
pthread_mutex_init(&mutex, 0);
uint32_t t[5];
for (i = 0; i != 5; ++i)
pthread_create(&t[i], mythread, (void *)i);
for (i = 0; i != 5; ++i)
pthread_join(t[i]);
cprintf("----------------------------------\\n");
cprintf("Everyone has finished eating! hahahahaha\\n");
cprintf("==================================\\n");
}
| 1
|
#include <pthread.h>
int grid[9][9];
int err_counter;
pthread_mutex_t counter_mutex;
int load_grid(char *filename) {
FILE *input_file = fopen(filename, "r");
if (input_file != 0) {
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
fscanf(input_file, "%d", &grid[i][j]);
fclose(input_file);
return 1;
}
return 0;
}
int check_row(int row_id){
int sum = 0;
for (int i = 0; i < 9; i++)
{
sum += grid[row_id][i];
}
return (sum == 45);
}
int check_column(int column_id){
int sum = 0;
for (int i = 0; i < 9; i++)
{
sum += grid[i][column_id];
}
return (sum == 45);
}
int check_region(int region_index){
int row_index = (region_index / 3) * 3;
int column_index = (region_index % 3) * 3;
int sum = 0;
for (int i = row_index; i < row_index + 3; i++)
{
for (int j = column_index; j < column_index + 3; j++)
{
sum += grid[i][j];
}
}
return (sum == 45);
}
void increment_counter(){
pthread_mutex_lock(&counter_mutex);
err_counter++;
pthread_mutex_unlock(&counter_mutex);
}
pthread_mutex_t work_mutex;
int work_map[3][9];
void* do_work(void* _index){
int index = (int)_index;
int valid = 1;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 9; j++)
{
pthread_mutex_lock(&work_mutex);
if(work_map[i][j] == 0){
pthread_mutex_unlock(&work_mutex);
continue;
}
work_map[i][j] = 0;
pthread_mutex_unlock(&work_mutex);
switch(i){
case 0:
valid = check_row(j);
if(!valid){
increment_counter();
printf("Thread %d: erro na linha %d\\n", index, j);
}
break;
case 1:
valid = check_column(j);
if(!valid){
increment_counter();
printf("Thread %d: erro na coluna %d\\n", index, j);
}
break;
case 2:
valid = check_region(j);
if(!valid){
increment_counter();
printf("Thread %d: erro na região %d\\n", index, j);
}
break;
}
}
}
}
int main(int argc, char *argv[]) {
if(argc < 2) {
printf("Erro: informe o arquivo de entrada!\\nUso: %s <arquivo de entrada>\\n\\n", argv[0]);
return 1;
}
int num_threads = 1;
if(argv[2]){
num_threads = atoi(argv[2]);
}
if(num_threads < 1){
num_threads = 1;
}
if(!load_grid(argv[1])){
printf("Erro no carregamento do quebra-cabeça\\n");
return 1;
}
pthread_mutex_init(&counter_mutex, 0);
err_counter = 0;
pthread_mutex_init(&work_mutex, 0);
memset(work_map, 1, sizeof(work_map[0][0]) * 3 * 9);
pthread_t threads[num_threads];
for (int i = 0; i < num_threads; i++)
{
pthread_create(&threads[i], 0, do_work, (void*)i);
}
for (int i = 0; i < num_threads; i++)
{
pthread_join(threads[i], 0);
}
printf("Erros encontrados: %d\\n", err_counter);
return 0;
}
| 0
|
#include <pthread.h>
void *producer(void *b);
void *consumer(void *b);
void *bufferPrinter(void *b);
pthread_t *producerThreads;
pthread_t *consumerThreads;
pthread_t bufferPrinterThread;
int PRODUCERCOUNT;
int CONSUMERCOUNT;
int BUFFERCOUNT;
int ITEM_MAX;
int item_count = 0;
int *full;
pthread_mutex_t *mutex;
pthread_mutex_t item;
pthread_mutex_t itemCount;
pthread_mutex_t printStatus;
pthread_mutex_t printerDone;
pthread_cond_t condProducer;
pthread_cond_t condConsumer;
void *producer(void *id) {
int i, busy, filled;
while(1){
busy = 1;
filled = 1;
pthread_mutex_lock(&item);
if(ITEM_MAX > 0){
pthread_mutex_unlock(&item);
for(i = 0; i < BUFFERCOUNT; i++){
if(pthread_mutex_trylock(&mutex[i]) == 0){
if(full[i] < 1024){
filled = 0;
pthread_mutex_lock(&item);
full[i] = full[i]+1;
item_count = item_count+1;
ITEM_MAX--;
if(item_count % 1000 == 0){
pthread_mutex_unlock(&printStatus);
}
else{
pthread_mutex_unlock(&item);
}
pthread_cond_broadcast(&condConsumer);
pthread_mutex_unlock(&mutex[i]);
break;
}
pthread_mutex_unlock(&mutex[i]);
}
}
if(filled){
pthread_cond_broadcast(&condConsumer);
pthread_cond_wait(&condProducer, &itemCount);
pthread_mutex_unlock(&itemCount);
}
}
else{
pthread_mutex_unlock(&item);
printf("Producer Thread %d is Finished\\n", (int) id);
ITEM_MAX--;
pthread_cond_signal(&condProducer);
pthread_exit(0);
}
}
}
void *consumer(void *id){
int i, j, emptyBuffer;
while(1){
emptyBuffer = 0;
for(i = 0; i < BUFFERCOUNT; i++){
if(pthread_mutex_trylock(&mutex[i]) == 0){
if(full[i] > 0){
full[i] = full[i] - 1;
}
else{
emptyBuffer = emptyBuffer +1;
}
pthread_mutex_unlock(&mutex[i]);
}
if(emptyBuffer == BUFFERCOUNT){
if(pthread_mutex_trylock(&printerDone) == 0){
pthread_mutex_unlock(&printerDone);
pthread_cond_broadcast(&condConsumer);
printf("Consumer Thread %d has finished.\\n", (int) id);
pthread_exit(0);
}
else{
pthread_cond_broadcast(&condProducer);
printf("Consumer Thread %d is yielding.\\n", (int) id);
pthread_cond_wait(&condConsumer, &itemCount);
pthread_mutex_unlock(&itemCount);
}
}
}
}
}
void *bufferPrinter(void *count){
int i, j;
while(1){
if(pthread_mutex_trylock(&printStatus) == 0){
printf("%d items created\\n", item_count);
for(i = 0; i < BUFFERCOUNT; i++){
printf("SharedBuffer %d has %d items.\\n", i+1, full[i]);
}
pthread_mutex_unlock(&item);
}
if(ITEM_MAX < 0){
pthread_mutex_unlock(&printerDone);
pthread_cond_signal(&condConsumer);
pthread_exit(0);
}
}
}
int main(int argc, char *argv[]) {
if (argc == 5) {
PRODUCERCOUNT = atoi(argv[1]);
CONSUMERCOUNT = atoi(argv[2]);
BUFFERCOUNT = atoi(argv[3]);
ITEM_MAX = atoi(argv[4]);
}
int i =0, j;
mutex = malloc(BUFFERCOUNT * sizeof(pthread_mutex_t));
full = malloc(BUFFERCOUNT * sizeof(int));
for (i = 0; i < BUFFERCOUNT; i++) {
pthread_mutex_init(&mutex[i], 0);
}
pthread_mutex_init(&item, 0);
pthread_mutex_init(&printStatus, 0);
pthread_mutex_init(&printerDone, 0);
pthread_mutex_lock(&printStatus);
pthread_mutex_lock(&printerDone);
pthread_cond_init(&condProducer, 0);
pthread_cond_init(&condConsumer, 0);
producerThreads = malloc(PRODUCERCOUNT * sizeof(pthread_t));
for (i = 0; i < PRODUCERCOUNT; i++) {
j = i +1;
pthread_create(&producerThreads[i], 0, (void*)&producer, (void *) j);
}
pthread_create(&bufferPrinterThread, 0, (void*)&bufferPrinter, 0);
consumerThreads = malloc(CONSUMERCOUNT * sizeof(pthread_t));
for (i = 0; i < CONSUMERCOUNT; i++) {
j = i+1;
pthread_create(&consumerThreads[i], 0, (void*)&consumer, (void *) j);
}
for (i = 0; i < PRODUCERCOUNT; i++) {
pthread_join(producerThreads[i], 0);
}
for(i = 0; i < CONSUMERCOUNT; i++){
pthread_join(consumerThreads[i], 0);
}
for(i = 0; i < BUFFERCOUNT; i++){
printf("%d items left in buffer %d\\n", full[i], i+1);
}
printf("%d items created\\n", item_count);
pthread_cond_destroy(&condProducer);
pthread_cond_destroy(&condConsumer);
for(i = 0; i < BUFFERCOUNT; i++){
pthread_mutex_destroy(&mutex[i]);
}
pthread_mutex_destroy(&item);
pthread_mutex_destroy(&itemCount);
pthread_mutex_destroy(&printStatus);
pthread_mutex_destroy(&printerDone);
free(producerThreads);
free(consumerThreads);
free(mutex);
free(full);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t condVar1;
pthread_cond_t condVar2;
int shared_integer = 0;
pthread_t tid[2];
_Bool first_time_in = 1;
double timespec_to_ms(struct timespec *ts)
{
return ts-> tv_sec *1000.0 + ts-> tv_nsec/1000000.0;
}
void* doSomeThing(void *arg);
void* doSomeThing2(void *arg);
struct timespec start_time, end_time;
int main(int argc, char *argv[]){
pthread_create(&(tid[0]), 0, &doSomeThing, 0);
pthread_create(&(tid[1]), 0, &doSomeThing2, 0);
pthread_join(tid[0], 0);
pthread_join(tid[1], 0);
printf("%fms\\n", timespec_to_ms(&end_time)-timespec_to_ms(&start_time));
return 0;
}
void* doSomeThing(void *arg)
{
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_time);
pthread_mutex_lock(&lock);
while(shared_integer == 0){
pthread_cond_wait(&condVar1, &lock);
}
if(shared_integer == 1){
shared_integer = 0;
}
else{
shared_integer = 1;
}
pthread_cond_signal(&condVar2);
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
void* doSomeThing2(void *arg)
{
pthread_mutex_lock(&lock);
while(shared_integer==1){
pthread_cond_wait(&condVar2, &lock);
}
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_time);
if(shared_integer == 1){
shared_integer = 0;
}
else{
shared_integer = 1;
}
pthread_mutex_unlock(&lock);
pthread_cond_signal(&condVar1);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
static void expandHashtable(
struct UFDBhashtable * ht )
{
unsigned int newTableSize;
unsigned int i, j;
struct UFDBhte * hte;
struct UFDBhte ** newtable;
newTableSize = ht->tableSize * 2 - 1;
newtable = ufdbCalloc( sizeof(struct UFDBhte*), newTableSize );
if (newtable == 0)
{
ht->optimalMaxEntries = (unsigned int) (ht->tableSize * 0.88);
return;
}
for (i = 0; i < ht->tableSize; i++)
{
while ((hte = ht->table[i]) != 0)
{
ht->table[i] = hte->next;
j = hte->hash % newTableSize;
hte->next = newtable[j];
newtable[j] = hte;
}
}
ht->tableSize = newTableSize;
ht->optimalMaxEntries = (unsigned int) (newTableSize * 0.68);
ufdbFree( ht->table );
ht->table = newtable;
}
struct UFDBhashtable *
UFDBcreateHashtable(
unsigned int tableSize,
unsigned int (*hashFunction) (void*),
int (*keyEqFunction) (void*,void*) )
{
struct UFDBhashtable * ht;
ht = ufdbMalloc( sizeof( struct UFDBhashtable ) );
if (ht == 0)
return 0;
if (tableSize < 23)
tableSize = 23;
ht->tableSize = tableSize;
ht->table = ufdbCalloc( sizeof(struct UFDBhte*), tableSize );
if (ht->table == 0)
return 0;
ht->nEntries = 0;
ht->optimalMaxEntries = (unsigned int) (tableSize * 0.68);
ht->hashFunction = hashFunction;
ht->keyEqFunction = keyEqFunction;
pthread_mutex_init( &(ht->mutex), 0 );
return ht;
}
void
UFDBinsertHashtable(
struct UFDBhashtable * ht,
void * key,
void * value,
int lockSetBySearch )
{
unsigned int i;
struct UFDBhte * hte;
hte = ufdbMalloc( sizeof(struct UFDBhte) );
if (hte == 0)
return;
hte->hash = ht->hashFunction( key );
hte->key = key;
hte->value = value;
if (!lockSetBySearch)
{
pthread_mutex_lock( &ht->mutex );
}
i = hte->hash % ht->tableSize;
hte->next = ht->table[i];
ht->table[i] = hte;
ht->nEntries++;
if (ht->nEntries > ht->optimalMaxEntries)
expandHashtable( ht );
pthread_mutex_unlock( &ht->mutex );
}
void UFDBunlockHashtable(
struct UFDBhashtable * ht )
{
pthread_mutex_unlock( &ht->mutex );
}
void *
UFDBsearchHashtable(
struct UFDBhashtable * ht,
void * key,
int keepLockForInsert )
{
unsigned int hash;
unsigned int i;
void * retval;
struct UFDBhte * hte;
retval = 0;
hash = ht->hashFunction( key );
pthread_mutex_lock( &ht->mutex );
i = hash % ht->tableSize;
hte = ht->table[i];
while (hte != 0)
{
if (hte->hash == hash && ht->keyEqFunction(key,hte->key))
{
retval = hte->value;
break;
}
hte = hte->next;
}
if ( !(retval == 0 && keepLockForInsert) )
{
pthread_mutex_unlock( &ht->mutex );
}
return retval;
}
void *
UFDBremoveHashtable(
struct UFDBhashtable * ht,
void * key )
{
unsigned int hash;
unsigned int i;
struct UFDBhte * hte;
struct UFDBhte ** head_hte;
void * retval;
retval = 0;
hash = ht->hashFunction( key );
pthread_mutex_lock( &ht->mutex );
i = hash % ht->tableSize;
head_hte = &( ht->table[i] );
hte = *head_hte;
while (hte != 0)
{
if (hte->hash == hash && ht->keyEqFunction(key,hte->key))
{
*head_hte = hte->next;
retval = hte->value;
ufdbFree( hte->key );
ufdbFree( hte );
ht->nEntries--;
break;
}
head_hte = &hte->next;
hte = hte->next;
}
pthread_mutex_unlock( &ht->mutex );
return retval;
}
void
UFDBdestroyHashtable(
struct UFDBhashtable * ht,
int freeValues )
{
unsigned int i;
struct UFDBhte * hte;
struct UFDBhte * next;
pthread_mutex_lock( &ht->mutex );
for (i = 0; i < ht->tableSize; i++)
{
hte = ht->table[i];
while (hte != 0)
{
next = hte->next;
ufdbFree( hte->key );
if (freeValues)
ufdbFree( hte->value );
ufdbFree( hte );
hte = next;
}
}
ufdbFree( ht->table );
pthread_mutex_unlock( &ht->mutex );
ufdbFree( ht );
}
| 1
|
#include <pthread.h>
volatile long numero = 0;
char primos[1000000];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int ehPrimo(long 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;
}
void *ExecutaTarefa (void * i) {
unsigned long int n;
while(1) {
pthread_mutex_lock(&mutex);
n = numero;
if(n == 1000000) {
pthread_mutex_unlock(&mutex);
break;
}
numero++;
pthread_mutex_unlock(&mutex);
primos[n] = ehPrimo(n);
}
pthread_exit(0);
}
int main(int argc, char *argv[]) {
pthread_t tid[2];
int t; unsigned long int i, qtde=0;
struct timeval startTime, endTime;
unsigned int totalUsecs;
gettimeofday(&startTime, 0);
for(t=0; t<2; t++) {
if (pthread_create(&tid[t], 0, ExecutaTarefa, 0)) {
printf("--ERRO: pthread_create()\\n"); exit(-1);
}
}
for (t=0; t<2; t++) {
if (pthread_join(tid[t], 0)) {
printf("--ERRO: pthread_join() \\n"); exit(-1);
}
}
gettimeofday(&endTime, 0);
totalUsecs = (unsigned long long) (endTime.tv_sec - startTime.tv_sec) * 1000000 +
(unsigned long long) (endTime.tv_usec - startTime.tv_usec);
for(i=0;i<1000000;i++) {
if(primos[i]) qtde++;
}
printf("Valor final de numero = %lu\\n", numero);
printf("Qtde de primos = %lu\\n", qtde);
printf("%s%g\\n", "Tempo = ", (double)totalUsecs);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_cond_t stable,
workshop,
santaSleeping,
elfWaiting,
santaWaitElf;
pthread_mutex_t elfAndReindeerCount,
elfwWaitingLock;
int minWait, maxWait;
int elfCount;
int reindeerCount;
int elfDoor;
void *elfThread(void *args)
{
while(1)
{
elvesHelper();
}
}
void elvesHelper()
{
pthread_mutex_lock(&elfwWaitingLock);
printf("Elf beginning work.\\n");
int amount = ((rand() % (maxWait - minWait)) + minWait) * 1000;
usleep(amount);
while (elfDoor == 1)
{
pthread_cond_wait(&elfWaiting, &elfwWaitingLock);
}
pthread_mutex_lock(&elfAndReindeerCount);
elfDoor = 1;
elfCount++;
if (elfCount == 3)
{
printf("3rd elf is waiking Santa up.\\n");
pthread_cond_signal(&santaSleeping);
pthread_cond_wait(&workshop, &elfAndReindeerCount);
}
else
{
printf("Elf waits for help from santa.\\n");
elfDoor = 0;
pthread_mutex_unlock(&elfwWaitingLock);
pthread_cond_wait(&workshop, &elfAndReindeerCount);
}
elfCount--;
if (elfCount == 0)
{
elfDoor = 0;
pthread_cond_signal(&santaWaitElf);
pthread_cond_broadcast(&elfWaiting);
pthread_mutex_unlock(&elfwWaitingLock);
printf("Last Elf done working for the moment.\\n");
}
else
{
printf("Elf done working for the moment.\\n");
}
pthread_mutex_unlock(&elfAndReindeerCount);
}
| 1
|
#include <pthread.h>
extern unsigned int num_threads;
int volatile unsigned active_threads;
pthread_mutex_t actmut;
unsigned long int *morton_codes;
unsigned long int *sorted_morton_codes;
unsigned int *permutation_vector;
unsigned int *index;
unsigned int *level_record;
int N;
int population_threshold;
int sft;
int lv;
pthread_t tid;
int child;
int father;
}radarg;
inline void swap_long(unsigned long int **x, unsigned long int **y){
unsigned long int *tmp;
tmp = x[0];
x[0] = y[0];
y[0] = tmp;
}
inline void swap(unsigned int **x, unsigned int **y){
unsigned int *tmp;
tmp = x[0];
x[0] = y[0];
y[0] = tmp;
}
void *parallel_truncated_radix_sort(void *arg)
{
radarg *p = (radarg*)arg;
int BinSizes[8] = {0};
int BinCursor[8] = {0};
unsigned int *tmp_ptr;
unsigned long int *tmp_code;
unsigned long int *morton_codes=p->morton_codes;
unsigned long int *sorted_morton_codes=p->sorted_morton_codes;
unsigned int *permutation_vector=p->permutation_vector;
unsigned int *index=p->index;
unsigned int *level_record=p->level_record;
int N=p->N;
int population_threshold=p->population_threshold;
int sft=p->sft;
int lv=p->lv;
pthread_t tid=p->tid;
int child=p->child;
int father=p->father;
if(N<=0)
{
return;
}else if(N<=population_threshold || sft < 0)
{
level_record[0] = lv;
memcpy(permutation_vector, index, N*sizeof(unsigned int));
memcpy(sorted_morton_codes, morton_codes, N*sizeof(unsigned long int));
return;
}
else
{
level_record[0] = lv;
for(int j=0; j<N; j++){
unsigned int ii = (morton_codes[j]>>sft) & 0x07;
BinSizes[ii]++;
}
int offset = 0;
for(int i=0; i<8; i++)
{
int ss = BinSizes[i];
BinCursor[i] = offset;
offset += ss;
BinSizes[i] = offset;
}
for(int j=0; j<N; j++)
{
unsigned int ii = (morton_codes[j]>>sft) & 0x07;
permutation_vector[BinCursor[ii]] = index[j];
sorted_morton_codes[BinCursor[ii]] = morton_codes[j];
BinCursor[ii]++;
}
swap(&index, &permutation_vector);
swap_long(&morton_codes, &sorted_morton_codes);
radarg *p2;
p2 = (radarg*)malloc(8*sizeof(radarg));
for(int i=0; i<8; i++)
{
int offset = (i>0) ? BinSizes[i-1] : 0;
int size = BinSizes[i] - offset;
p2[i].morton_codes=&morton_codes[offset];
p2[i].sorted_morton_codes=&sorted_morton_codes[offset];
p2[i].permutation_vector=&permutation_vector[offset];
p2[i].index=&index[offset];
p2[i].level_record=&level_record[offset];
p2[i].N=size;
p2[i].population_threshold=population_threshold;
p2[i].sft=sft-3;
p2[i].lv=lv+1;
pthread_mutex_lock(&actmut);
if (active_threads < num_threads){
pthread_t *newthread;
newthread = (pthread_t*)malloc(sizeof(pthread_t));
pthread_attr_t joinable;
pthread_attr_init(&joinable);
pthread_attr_setdetachstate(&joinable, PTHREAD_CREATE_JOINABLE);
p2[i].child = 1;
p2[i].tid = newthread;
active_threads++;
pthread_create(&newthread, &joinable, parallel_truncated_radix_sort, (void*)(p2+i));
pthread_mutex_unlock(&actmut);
father = 1;
pthread_attr_destroy(&joinable);
}else
{
pthread_mutex_unlock(&actmut);
father = 0;
p2[i].child = 0 ;
p2[i].tid = 0;
parallel_truncated_radix_sort( (void*)(p2+i) );
}
}
if (child == 1)
{
pthread_join(tid, 0);
pthread_mutex_lock(&actmut);
active_threads--;
pthread_mutex_unlock(&actmut);
}
}
}
void truncated_radix_sort(unsigned long int *morton_codes,
unsigned long int *sorted_morton_codes,
unsigned int *permutation_vector,
unsigned int *index,
unsigned int *level_record,
int N,
int population_threshold,
int sft, int lv)
{
pthread_mutex_init(&actmut, 0);
radarg *ra;
ra = (radarg*)malloc(sizeof(radarg));
ra->morton_codes=morton_codes;
ra->sorted_morton_codes=sorted_morton_codes;
ra->permutation_vector=permutation_vector;
ra->index=index;
ra->level_record=level_record;
ra->N=N;
ra->population_threshold=population_threshold;
ra->sft=sft;
ra->lv=lv;
ra->tid = 0;
ra->child = 0;
ra->father = 0;
active_threads = 1;
parallel_truncated_radix_sort( (void*)ra );
while (active_threads > 1);
pthread_mutex_destroy(&actmut);
free(ra);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex_1;
int counter;
void *child1(void *arg)
{
while(1){
pthread_mutex_lock(&mutex_1);
sleep(1);
if(counter > 25)
{
pthread_mutex_unlock(&mutex_1);
pthread_exit(0);
}
else
counter++;
pthread_mutex_unlock(&mutex_1);
printf("Child1: counter=%d\\n", counter);
}
}
int main(void)
{
pthread_t tid1;
counter = 0;
pthread_mutex_init(&mutex_1,0);
pthread_create(&tid1,0,child1,0);
do{
pthread_mutex_lock(&mutex_1);
sleep(1);
counter++;
pthread_mutex_unlock(&mutex_1);
printf("Main: counter=%d\\n", counter);
}while(1);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
{
int balance;
pthread_mutex_t mutex;
} Account;
void deposit(Account* account, int amount)
{
pthread_mutex_lock(&(account->mutex));
account->balance += amount;
pthread_mutex_unlock(&(account->mutex));
}
void transfer(Account* accountA, Account* accountB, int amount)
{
pthread_mutex_lock(&(accountA->mutex));
pthread_mutex_lock(&(accountB->mutex));
accountA->balance += amount;
accountB->balance -= amount;
pthread_mutex_unlock(&(accountB->mutex));
pthread_mutex_unlock(&(accountA->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;
pthread_mutex_init( &accountA.mutex, 0 );
accountB.balance = 1000;
pthread_mutex_init( &accountB.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(&accountA.mutex);
pthread_mutex_destroy(&accountB.mutex);
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
int count = 0;
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *inc_count(void *t)
{
int i;
long my_id = (long)t;
for (i=0; i < 10; i++) {
pthread_mutex_lock(&count_mutex);
count++;
if (count == 12) {
printf("inc_count(): thread %ld, count = %d Threshold reached. ",
my_id, count);
pthread_cond_signal(&count_threshold_cv);
printf("Just sent signal.\\n");
}
printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n",
my_id, count);
pthread_mutex_unlock(&count_mutex);
sleep(1);
}
pthread_exit(0);
}
void *watch_count(void *t)
{
long my_id = (long)t;
printf("Starting watch_count(): thread %ld\\n", my_id);
pthread_mutex_lock(&count_mutex);
while (count < 12) {
printf("watch_count(): thread %ld Count= %d. Going into wait...\\n", my_id,count);
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %ld Condition signal received. Count= %d\\n", my_id,count);
printf("watch_count(): thread %ld Updating the value of count...\\n", my_id,count);
count += 125;
printf("watch_count(): thread %ld count now = %d.\\n", my_id, count);
}
printf("watch_count(): thread %ld Unlocking mutex.\\n", my_id);
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int i, rc;
long t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, watch_count, (void *)t1);
pthread_create(&threads[1], &attr, inc_count, (void *)t2);
pthread_create(&threads[2], &attr, inc_count, (void *)t3);
for (i = 0; i < 3; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited and joined with %d threads. Final value of count = %d. Done.\\n",
3, count);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit (0);
}
| 1
|
#include <pthread.h>
const long NUM_PHILOSOPHERS = 5;
pthread_mutex_t chopstick_mutex[5];
void* grab_chopsticks(void* rank);
int main(void)
{
long i, j;
pthread_t* threads = (pthread_t*)malloc(NUM_PHILOSOPHERS * sizeof(pthread_t));
;
for(i = 0; i < NUM_PHILOSOPHERS; ++i)
{
pthread_mutex_init(&chopstick_mutex[i], 0);
printf("Philosopher %d is thinking.\\n", i);
}
for(j = 0; j < 10; ++j)
{
for(i = 0; i < NUM_PHILOSOPHERS; ++i)
{
pthread_create(&threads[i], 0, grab_chopsticks, (void*)i);
}
for(i = 0; i < NUM_PHILOSOPHERS; ++i)
{
pthread_join(threads[i], 0);
}
}
free(threads);
return 0;
}
void* grab_chopsticks(void* rank)
{
long thread_rank = (long)rank;
pthread_mutex_lock(&chopstick_mutex[thread_rank]);
printf("Philosopher %ld picked up chopstick %ld.\\n", thread_rank, thread_rank);
pthread_mutex_lock(&chopstick_mutex[(thread_rank + 1) % NUM_PHILOSOPHERS]);
printf("Philosopher %ld picked up chopstick %ld.\\n", thread_rank, (thread_rank + 1) % NUM_PHILOSOPHERS);
printf("Philosopher %ld is eating.\\n", thread_rank);
sleep(5);
pthread_mutex_unlock(&chopstick_mutex[(thread_rank + 1) % NUM_PHILOSOPHERS]);
printf("Philosopher %ld put down chopstick %ld.\\n", thread_rank, (thread_rank + 1) % NUM_PHILOSOPHERS);
pthread_mutex_unlock(&chopstick_mutex[thread_rank]);
printf("Philosopher %ld put down chopstick %ld.\\n", thread_rank, thread_rank);
printf("Philosopher %ld is thinking.\\n", thread_rank);
}
| 0
|
#include <pthread.h>
pthread_t t_s;
struct sim_time_t bc_time;
int fd;
void* bcsock () {
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,0);
int fd = TCP_Server_init(9010,"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] == 'B') {
char b[250];
memset(&b,'\\0',sizeof(b));
pthread_mutex_lock(&mutex);
int len = sizeof(pso);
printf("pso size = %d \\n",len);
memcpy(&b,&pso,sizeof(pso));
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(bc_time);
memcpy(&b,&bc_time,sizeof(bc_time));
pthread_mutex_unlock(&mutex);
r = Socket_send(s,b,len);
if (r == -1) {
close(s);
break;
}
}
}
}
close(fd);
return 0;
}
void time_tick(struct sim_time_t *time) {
time->Mls += 100;
if (time->Mls >= 1000) {
time->Second += 1;
time->Mls = 0;
if (time->Second >= 60) {
time->Second = 0;
time->Minute += 1;
if (time->Minute >= 60) {
time->Minute = 0;
time->Hour += 1;
}
}
}
}
void* bcmain() {
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,0);
pthread_create(&t_s, 0, (void *(*)(void *))bcsock, 0);
memset(&bc_time,0,sizeof(bc_time));
while(sim_stat != 0 ) {
Disp_start();
usleep(100000);
bc_disp_wait();
pthread_mutex_lock(&mutex);
if (sim_stat == 0) {
break;
}
if (bc_takt++ >= 1000) {
bc_takt = 0;
}
pso.Sn = model.Sn;
int i;
for(i = 0; i < 3; i++) {
pso.o_Omg[i] = model.o_Omg[i];
pso.S_cck[i] = model.S_cck[i];
}
time_tick(&bc_time);
pthread_mutex_unlock(&mutex);
}
close(fd);
pthread_cancel(t_s);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t no_wait, no_acc, counter;
int no_of_readers=0;
void writer(void* arg);
void read(int id);
void check_and_wait_if_busy(int id);
void write(int id);
void check_and_wait(int id);
void reader(void *arg)
{
int id=*((int*)arg);
printf("reader %d started\\n", id);
while(1)
{
sleep(rand()%4);
check_and_wait(id);
read(id);
}
}
void writer(void* arg)
{
int id=*((int*)arg);
printf("writer %d started\\n", id);
while(1)
{
sleep(rand()%5);
check_and_wait_if_busy(id);
write(id);
}
}
void check_and_wait_if_busy(int id)
{
if(pthread_mutex_trylock(&no_wait)!=0){
printf("Writer %d Waiting\\n", id);
pthread_mutex_lock(&no_wait);
}
}
void check_and_wait(int id)
{
if(pthread_mutex_trylock(&no_wait)!=0){
printf("Reader %d Waiting\\n", id);
pthread_mutex_lock(&no_wait);
}
}
void read(int id)
{
pthread_mutex_lock(&counter);
no_of_readers++;
pthread_mutex_unlock(&counter);
if(no_of_readers==1)
pthread_mutex_lock(&no_acc);
pthread_mutex_unlock(&no_wait);
printf("reader %d reading...\\n", id);
sleep(rand()%5);
printf("reader %d finished reading\\n", id);
pthread_mutex_lock(&counter);
no_of_readers--;
pthread_mutex_unlock(&counter);
if(no_of_readers==0)
pthread_mutex_unlock(&no_acc);
}
void write(int id)
{
pthread_mutex_lock(&no_acc);
pthread_mutex_unlock(&no_wait);
printf("Writer %d writing...\\n", id);
sleep(rand()%4+2);
printf("Writer %d finished writing\\n", id);
pthread_mutex_unlock(&no_acc);
}
int main(int argc, char* argv[])
{
pthread_t R[5],W[5];
int ids[5];
for(int i=0; i<5; i++)
{
ids[i]=i+1;
pthread_create(&R[i], 0, (void*)&reader, (void*)&ids[i]);
pthread_create(&W[i], 0, (void*)&writer, (void*)&ids[i]);
}
pthread_join(R[0], 0);
exit(0);
}
| 0
|
#include <pthread.h>
struct data {
int tid;
char buffer[100];
} tdata1, tdata2;
pthread_mutex_t lock1;
pthread_mutex_t lock2;
pthread_cond_t cond1;
pthread_cond_t cond2;
int mySharedCounter = 0;
int go1 = 0;
int go2 = 0;
void helper(void *tdata, pthread_mutex_t *l1, pthread_cond_t *c1, int *goP1, pthread_mutex_t *l2, pthread_cond_t *c2, int *goP2) {
struct data *d = (struct data*) tdata;
if(d->tid == 1)
{
pthread_mutex_lock(l1);
while (!(*goP1)) {
printf("thread %d sleeps until condition %lu - goP1 is set\\n", d->tid, (long)goP1);
pthread_cond_wait(c1, l1);
}
printf("helper func reached by thread %d : after waiting for c1 and l1\\n", d->tid);
sleep(1);
}
else
{
pthread_mutex_lock(l2);
while (!(*goP2)) {
printf("thread %d sleeps until condition %lu - goP2 is set \\n", d->tid, (long)goP2);
pthread_cond_wait(c2, l2);
}
printf("helper func reached by thread %d : after waiting for c2 and l2\\n", d->tid);
sleep(1);
}
mySharedCounter++;
printf("thread %d performed its critical region and exiting ..\\n", d->tid);
pthread_mutex_unlock(l2);
pthread_mutex_unlock(l1);
pthread_exit(0);
}
void *worker1(void *tdata) {
struct data *d = (struct data*) tdata;
printf("thread %d says %s\\n", d->tid, d->buffer);
helper(d, &lock1, &cond1, &go1, &lock2, &cond2, &go2);
pthread_exit(0);
}
void *worker2(void *tdata) {
struct data *d = (struct data*) tdata;
printf("thread %d says %s\\n", d->tid, d->buffer);
helper(d, &lock2, &cond2, &go2, &lock1, &cond1, &go1);
pthread_exit(0);
}
int main(char *argc[], int argv) {
int failed;
pthread_t thread1, thread2;
void *status1, *status2;
pthread_mutex_init(&lock1, 0);
pthread_mutex_init(&lock2, 0);
printf(" ************** MAIN THREAD: CREATING THREADS ! ***************\\n");
tdata1.tid = 1;
strcpy(tdata1.buffer, "hello");
failed = pthread_create(&thread1, 0, worker1, (void*)&tdata1);
if (failed) {
printf("thread_create failed!\\n");
return -1;
}
tdata2.tid = 2;
strcpy(tdata2.buffer, "world");
failed = pthread_create(&thread2, 0, worker2, (void*)&tdata2);
if (failed) {
printf("thread_create failed!\\n");
return -1;
}
printf("Main thread finished creating threads and is now sleeping\\n");
sleep(1);
printf("Main thread woke up!\\n");
pthread_mutex_lock(&lock1);
go1 = 1;
pthread_cond_broadcast(&cond1);
pthread_mutex_unlock(&lock1);
pthread_mutex_lock(&lock2);
go2 = 1;
pthread_cond_broadcast(&cond2);
pthread_mutex_unlock(&lock2);
pthread_join(thread1, &status1);
pthread_join(thread2, &status2);
printf("If you see this message, we were lucky!\\n");
printf("mySharedCounter = %d\\n", mySharedCounter);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int globalvar = 0;
int anotherglobal = 0;
pthread_mutex_t gmutex;
void * commonfunction(int local) {
int i = 0;
globalvar=local;
while (i++ < 0x2fff)
{
globalvar++;
printf("thread id : %d : globalvar : %d\\n", pthread_self(), globalvar);
}
return ((void *) 0);
}
void * depositing(void * thr_p) {
while (1)
{
pthread_mutex_lock(&gmutex);
deposit(20);
pthread_mutex_unlock(&gmutex);
}
return ((void *) 0);
}
void * withdrawal(void * thr_p) {
while (1)
{
pthread_mutex_lock(&gmutex);
withdraw(50);
pthread_mutex_unlock(&gmutex);
}
return ((void *) 0);
}
int main()
{
int retval;
pthread_t m_ThreadId;
pthread_t l_ThreadId;
pthread_attr_t atrr;
pthread_attr_init(&atrr);
pthread_attr_setscope(&atrr, PTHREAD_SCOPE_SYSTEM);
pthread_mutex_init(&gmutex, 0);
retval = pthread_create(&l_ThreadId, &atrr, startthread2, (void *)0);
if (0 != retval)
{
printf("thread creation failed\\n");
return (-1);
}
retval = pthread_create(&m_ThreadId, 0, startthread1, (void *)0);
if (0 != retval)
{
printf("thread creation failed\\n");
return (-1);
}
retval = pthread_join(l_ThreadId, 0);
if (0 != retval)
{
printf("thread join failed\\n");
return (-1);
}
retval = pthread_join(m_ThreadId, 0);
if (0 != retval)
{
printf("thread join failed\\n");
return (-1);
}
return 0;
}
| 0
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t wait = 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(&wait);
return (0);
default:
printf("unexpected signal %d\\n", signal);
exit (1);
}
}
}
int
main(void)
{
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(&wait, &lock);
pthread_mutex_unlock(&lock);
quitflag = 0;
if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0)
err_sys("SIG_SETMASK error");
exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
void hander(void *arg)
{
free(arg);
(void)pthread_mutex_unlock(&mutex);
}
void *thread1(void *arg)
{
pthread_cleanup_push(hander, &mutex);
while(1) {
printf("thread1 is running\\n");
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
printf("thread1 applied the condition\\n");
pthread_mutex_unlock(&mutex);
sleep(4);
}
pthread_cleanup_pop(0);
}
void *thread2(void *arg)
{
while(1) {
printf("thread2 is running\\n");
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
printf("thread2 applied the condition\\n");
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main()
{
pthread_t thid1, thid2;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
pthread_create(&thid1, 0, thread1, 0);
pthread_create(&thid2, 0, thread2, 0);
sleep(1);
do {
pthread_cond_signal(&cond);
sleep(5);
} while(1);
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
void fregister(FILE* fp)
{
pthread_mutex_lock(&__first_file_lock);
fp->flags |= _FILE_REGISTERED;
if ( (fp->next = __first_file) )
__first_file->prev = fp;
__first_file = fp;
pthread_mutex_unlock(&__first_file_lock);
}
| 1
|
#include <pthread.h>
pthread_t tid[2];
int counter;
pthread_mutex_t lock;
void* producer(void *arg)
{
long unsigned i;
while(1){
while(counter < 5){
counter += 1;
pthread_mutex_lock(&lock);
printf("\\n (Prodcuer) Buffer Value :%d", counter);
for(i=0; i<(0x10011111);i++);
pthread_mutex_unlock(&lock);
for(i=0; i<(0x10011111);i++);
}
}
return 0;
}
void* consumer(void *arg)
{
unsigned long i;
while(1){
while(counter != 0){
pthread_mutex_lock(&lock);
counter -= 1;
printf("\\n \\t\\t(Consumer) Buffer Value :%d", counter);
for(i=0; i<(0x10011111);i++);
pthread_mutex_unlock(&lock);
for(i=0; i<(0x10011111);i++);
}
}
return 0;
}
int main(void)
{
int i = 0;
int error;
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("\\n mutex init has failed\\n");
return 1;
}
error = pthread_create(&(tid[0]), 0, &producer,0);
error =pthread_create(&(tid[1]), 0, &consumer,0);
if(error != 0){
printf("\\nThread can't be created :[%s]",strerror(error));
}
while(1);
pthread_mutex_destroy(&lock);
return 0;
}
| 0
|
#include <pthread.h>
void warn(char *msg) {
if (msg) {
fprintf(stderr, "%s\\n", msg);
}
}
void panic(char *msg) {
endwin();
warn(msg);
exit(1);
}
int strtoi(const char *nptr, char **endptr, int base) {
long lval = strtol(nptr, endptr, base);
if (lval < INT_MIN) {
errno = ERANGE;
return INT_MIN;
}
if (lval > 32767) {
errno = ERANGE;
return 32767;
}
return (int) lval;
}
size_t anystrunplen(char *str, size_t maxlen, char ** endp) {
int len = 0;
char *last_sym = str;
while (maxlen-- && *str) {
if ((*str++ & 0xC0) != 0x80) {
len++;
last_sym = str - 1;
} else {
maxlen++;
}
}
if (++maxlen == 0 && endp != 0 && *endp != 0 && *str) {
*endp = last_sym;
}
return len;
}
size_t anystrnplen(char *str, size_t maxlen, char ** endp) {
int len = 0;
while (maxlen-- && *str) {
if ((*str++ & 0xC0) != 0x80) {
len++;
}
}
if (++maxlen == 0 && endp != 0 && *endp != 0 && *str) {
*endp = str;
}
return len;
}
size_t anystrnlen(char *str, size_t maxlen) {
return anystrnplen(str, maxlen, 0);
}
size_t anystrlen(char *str) {
return anystrnlen(str, 4294967295U);
}
int synchronized_readall(pthread_mutex_t *mutex, int fd, void *buf,
size_t size) {
if (0 == mutex) {
panic("synchronized_readall: NULL mutex provided");
}
pthread_mutex_lock(mutex);
int retval = readall(fd, buf, size);
pthread_mutex_unlock(mutex);
return retval;
}
int readall(int fd, void *buf, size_t size) {
int rc = -1;
size_t got = 0;
if (size == 0) {
return 0;
}
while (got < size) {
if ((rc = read(fd, (char *)buf + got, size - got)) > 0) {
got += rc;
} else {
break;
}
}
if (got == size) {
return size;
}
return -1;
}
void log_init() {
char *log_file = CONF_SVAL("file_server_log");
if (! *log_file) {
return;
}
if ((log_fd = open(log_file, O_WRONLY | O_APPEND | O_CREAT, 0666)) < 0) {
panicf("Unable to open %s!", log_file);
}
logger(" ======= GAME STARTED ======= ");
}
void logger(char *str) {
if (log_fd < 0) {
return;
}
char buf[8192];
struct timeval tv;
if (gettimeofday(&tv, 0) < 0) {
panic("Unable to get system time!");
}
int len = snprintf(buf, sizeof(buf), "%lu: %s\\n", tv.tv_sec, str);
if (write(log_fd, buf, len) < 0) {
panic("Unable to write log output!");
}
}
int main(int argc, char *argv[]) {
int server_only = 0;
server_started = 0;
server_connected = 0;
config_init("itmmorgue.conf");
while (*++argv) {
if (strcmp(*argv, "--server-only") == 0) {
server_only = 1;
} else if (strcmp(*argv, "-s") == 0) {
server_only = 1;
}
}
log_fd = -1;
log_init();
if (server_only == 0) {
client();
} else {
fprintf(stderr, "Starting server in headless mode...\\n");
server();
}
(void) argc;
return 0;
}
| 1
|
#include <pthread.h>
sem_t sem_stu;
sem_t sem_ta;
pthread_mutex_t mutex;
int chair[3];
int count = 0;
int next_seat = 0;
int next_teach = 0;
void rand_sleep(void);
void* stu_programming(void* stu_id);
void* ta_teaching();
int main(int argc, char **argv){
pthread_t *students;
pthread_t ta;
int* student_ids;
int student_num;
int i;
printf("How many students? ");
scanf("%d", &student_num);
students = (pthread_t*)malloc(sizeof(pthread_t) * student_num);
student_ids = (int*)malloc(sizeof(int) * student_num);
memset(student_ids, 0, student_num);
sem_init(&sem_stu,0,0);
sem_init(&sem_ta,0,1);
srand(time(0));
pthread_mutex_init(&mutex,0);
pthread_create(&ta,0,ta_teaching,0);
for(i=0; i<student_num; i++)
{
student_ids[i] = i+1;
pthread_create(&students[i], 0, stu_programming, (void*) &student_ids[i]);
}
pthread_join(ta, 0);
for(i=0; i<student_num;i++)
{
pthread_join(students[i],0);
}
return 0;
}
void* stu_programming(void* stu_id)
{
int id = *(int*)stu_id;
printf("[stu] student %d is programming\\n",id);
while(1)
{
rand_sleep();
pthread_mutex_lock(&mutex);
if(count < 3)
{
chair[next_seat] = id;
count++;
printf(" [stu] student %d is waiting\\n",id);
printf("waiting students : [1] %d [2] %d [3] %d\\n",chair[0],chair[1],chair[2]);
next_seat = (next_seat+1) % 3;
pthread_mutex_unlock(&mutex);
sem_post(&sem_stu);
sem_wait(&sem_ta);
}
else
{
pthread_mutex_unlock(&mutex);
printf("[stu] no more chairs. student %d is programming\\n",id);
}
}
}
void* ta_teaching()
{
while(1)
{
sem_wait(&sem_stu);
pthread_mutex_lock(&mutex);
printf(" [ta] TA is teaching student %d\\n",chair[next_teach]);
chair[next_teach]=0;
count--;
printf("waiting students : [1] %d [2] %d [3] %d\\n",chair[0],chair[1],chair[2]);
next_teach = (next_teach + 1) % 3;
rand_sleep();
printf(" [ta] teaching finish.\\n");
pthread_mutex_unlock(&mutex);
sem_post(&sem_ta);
}
}
void rand_sleep(void){
int time = rand() % 5 + 1;
sleep(time);
}
| 0
|
#include <pthread.h>
int cpt = 0;
pthread_mutex_t mut;
pthread_cond_t cond;
int var = 1;
struct timeval tv;
struct timespec ts;
void* increm1(void* arg){
int i = 0;
for ( i = 0; i < 4; i++){
sleep(1);
pthread_mutex_lock(&mut);
cpt++;
printf("compteur : %d\\n", cpt);
if (cpt == 3){
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mut);
}
pthread_exit(0);
}
void* increm2(void* arg){
int j = 0;
for ( j = 0; j < 4; j++){
sleep(1);
pthread_mutex_lock(&mut);
cpt++;
printf("compteur : %d\\n", cpt);
if (cpt == 3)
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mut);
}
pthread_exit(0);
}
void* attente(void* arg){
sleep(0.5);
pthread_mutex_lock(&mut);
if(var == 1){
pthread_cond_timedwait(&cond, &mut, &ts);
printf("On a atteint 3\\n");
}
pthread_mutex_unlock(&mut);
pthread_exit(0);
}
int main(){
gettimeofday(&tv, 0);
ts.tv_sec = tv.tv_sec + 4;
ts.tv_nsec = 3;
pthread_t id1, id2, id3;
pthread_mutex_init(&mut, 0);
pthread_cond_init(&cond, 0);
pthread_mutex_lock(&mut);
pthread_create(&id1, 0, increm1, 0);
pthread_create(&id2, 0, increm2, 0);
pthread_create(&id3, 0, attente, 0);
pthread_mutex_unlock(&mut);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
void*rightCounter();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int rightcounter = 0;
void*leftCounter();
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
int leftcounter = 0 ;
int right[]={1,2,2,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0};
int left[]={1,2,2,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0};
int rright[]={-1};
int lleft[]={-1};
bool L = 0;
bool R = 0;
bool flagr = 1;
bool flagl = 1;
bool FLAG = 1;
int q = 0;
int main()
{
pthread_t thread1, thread2;
int rc1, rc2;
int counter =0;
int b = 0; int c=0;
int d=0;
bool REJECT = 0;
int reject[sizeof(right)/sizeof(right[0])];
int good[2*sizeof(right)/sizeof(right[0])];
printf("size of good %lu\\n",sizeof(good)/sizeof(good[0]));
while(FLAG){
if((pthread_create(&thread1, 0, &rightCounter, 0)))
{
printf("Thread creation failed: %d\\n", rc1);
}
if((pthread_create(&thread2, 0, &leftCounter,0)))
{
printf("Thread creation failed: %d\\n",rc2);
}
printf("in comparision\\n");
pthread_join(thread1, 0);
pthread_join(thread2, 0);
if(rright[0]==lleft[0]){
good[c]=rright[0];
printf("%d added to good from right\\n",rright[0]);
c++;
good[c]=lleft[0];
printf("%d added to good from left\\n",lleft[0]);
c++;
}else{
printf("%d from right is not equal to %d from left\\n",rright[0],lleft[0]);
reject[d]=rright[0];
printf("%d added to reject from right\\n",rright[0]);
d++;
reject[d]=lleft[0];
printf("%d added to rejct from left\\n",lleft[0]);
d++;
REJECT = 1;
}
flagr=1;
flagl=1;
rright[0]=-1;
R=0;
lleft[0]=-1;
L=0;
q++;
b++;
if(b >= sizeof(right)/sizeof(right[0])){
FLAG = 0;
printf("COMPLETE\\n");
printf("Reject = %s\\n",REJECT ? "true" : "false");
}
}
}
void*rightCounter()
{
pthread_mutex_lock(&mutex1);
while(flagr){
if(rright[0] < 0 && R == 0){
rright[0]=right[q];
flagr = 0;
R=1;
}else{
flagr = 1;
}
}
pthread_mutex_unlock(&mutex1);
return 0;
}
void*leftCounter()
{
pthread_mutex_lock(&mutex1);
while(flagl){
if(lleft[0] < 0 && L == 0){
lleft[0]=left[q];
flagl = 0;
L=1;
}else{
flagl = 1;
}
}
pthread_mutex_unlock(&mutex1);
return 0;
}
| 0
|
#include <pthread.h>
static size_t used_memory = 0;
static bool tf_malloc_thread_safe = 0;
pthread_mutex_t used_memory_mutex = PTHREAD_MUTEX_INITIALIZER;
static void tf_malloc_default_oom(size_t size) {
emerg(errno, "tf_malloc: Out of memory trying to allocate %zu bytes", size);
abort();
}
static void (*tf_malloc_oom_handler)(size_t) = tf_malloc_default_oom;
void *tf_alloc(size_t size) {
void *ptr = malloc(size+(sizeof(size_t)));
if (!ptr) tf_malloc_oom_handler(size);
*((size_t*)ptr) = size;
do { size_t _n = (size+(sizeof(size_t))); if (_n&(sizeof(long)-1)) _n += sizeof(long)-(_n&(sizeof(long)-1)); if (tf_malloc_thread_safe) { do { pthread_mutex_lock(&used_memory_mutex); used_memory += (_n); pthread_mutex_unlock(&used_memory_mutex); } while(0); } else { used_memory += _n; } } while(0);
return (char*)ptr+(sizeof(size_t));
}
void *tf_calloc(size_t size) {
void *ptr = calloc(1, size+(sizeof(size_t)));
if (!ptr) tf_malloc_oom_handler(size);
*((size_t*)ptr) = size;
do { size_t _n = (size+(sizeof(size_t))); if (_n&(sizeof(long)-1)) _n += sizeof(long)-(_n&(sizeof(long)-1)); if (tf_malloc_thread_safe) { do { pthread_mutex_lock(&used_memory_mutex); used_memory += (_n); pthread_mutex_unlock(&used_memory_mutex); } while(0); } else { used_memory += _n; } } while(0);
return (char*)ptr+(sizeof(size_t));
}
size_t tf_malloc_size(void *ptr) {
void *realptr = (char*)ptr-(sizeof(size_t));
size_t size = *((size_t*)realptr);
if (size&(sizeof(long)-1)) size += sizeof(long)-(size&(sizeof(long)-1));
return size+(sizeof(size_t));
}
void *tf_realloc(void *ptr, size_t size) {
void *realptr;
size_t oldsize;
void *newptr;
if (ptr == 0) return tf_alloc(size);
realptr = (char*)ptr-(sizeof(size_t));
oldsize = *((size_t*)realptr);
newptr = realloc(realptr,size+(sizeof(size_t)));
if (!newptr) tf_malloc_oom_handler(size);
*((size_t*)newptr) = size;
do { size_t _n = (oldsize); if (_n&(sizeof(long)-1)) _n += sizeof(long)-(_n&(sizeof(long)-1)); if (tf_malloc_thread_safe) { do { pthread_mutex_lock(&used_memory_mutex); used_memory -= (_n); pthread_mutex_unlock(&used_memory_mutex); } while(0); } else { used_memory -= _n; } } while(0);
do { size_t _n = (size); if (_n&(sizeof(long)-1)) _n += sizeof(long)-(_n&(sizeof(long)-1)); if (tf_malloc_thread_safe) { do { pthread_mutex_lock(&used_memory_mutex); used_memory += (_n); pthread_mutex_unlock(&used_memory_mutex); } while(0); } else { used_memory += _n; } } while(0);
return (char*)newptr+(sizeof(size_t));
}
void tf_free(void *ptr) {
void *realptr;
size_t oldsize;
if (ptr == 0) return;
realptr = (char*)ptr-(sizeof(size_t));
oldsize = *((size_t*)realptr);
do { size_t _n = (oldsize+(sizeof(size_t))); if (_n&(sizeof(long)-1)) _n += sizeof(long)-(_n&(sizeof(long)-1)); if (tf_malloc_thread_safe) { do { pthread_mutex_lock(&used_memory_mutex); used_memory -= (_n); pthread_mutex_unlock(&used_memory_mutex); } while(0); } else { used_memory -= _n; } } while(0);
free(realptr);
}
size_t tf_malloc_used_memory(void) {
size_t um;
if (tf_malloc_thread_safe) {
pthread_mutex_lock(&used_memory_mutex);
um = used_memory;
pthread_mutex_unlock(&used_memory_mutex);
}
else {
um = used_memory;
}
return um;
}
void tf_malloc_enable_thread_safeness(void) {
tf_malloc_thread_safe = 1;
}
void *tf_memdup(const void *ptr, size_t size){
char *p = tf_alloc(size + 1);
memcpy(p, ptr, size);
p[size] = '\\0';
return p;
}
| 1
|
#include <pthread.h>
void make_water();
void reaction_init(struct reaction *reaction)
{
pthread_mutex_init(&reaction->lock_mutex,0);
pthread_cond_init(&reaction->getting_new_H,0);
pthread_cond_init(&reaction->ready_to_react,0);
reaction->number_of_H = 0;
}
void reaction_h(struct reaction *reaction)
{
pthread_mutex_lock(&reaction->lock_mutex);
reaction->number_of_H++;
pthread_cond_signal(&reaction->getting_new_H);
pthread_cond_wait(&reaction->ready_to_react,&reaction->lock_mutex);
pthread_mutex_unlock(&reaction->lock_mutex);
}
void reaction_o(struct reaction *reaction)
{
pthread_mutex_lock(&reaction->lock_mutex);
while(reaction->number_of_H < 2){
pthread_cond_wait(&reaction->getting_new_H,&reaction->lock_mutex);
}
make_water();
reaction->number_of_H -= 2;
pthread_cond_signal(&reaction->ready_to_react);
pthread_cond_signal(&reaction->ready_to_react);
pthread_mutex_unlock(&reaction->lock_mutex);
}
| 0
|
#include <pthread.h>
extern int dmeventd_debug;
static pthread_mutex_t _register_mutex = PTHREAD_MUTEX_INITIALIZER;
static int _register_count = 0;
static struct dm_pool *_mem_pool = 0;
static void *_lvm_handle = 0;
static pthread_mutex_t _event_mutex = PTHREAD_MUTEX_INITIALIZER;
static void _temporary_log_fn(int level,
const char *file ,
int line ,
int dm_errno ,
const char *message)
{
level &= ~(_LOG_STDERR | _LOG_ONCE);
switch (level) {
case _LOG_DEBUG:
if (dmeventd_debug >= 3)
syslog(LOG_DEBUG, "%s", message);
break;
case _LOG_INFO:
if (dmeventd_debug >= 2)
syslog(LOG_INFO, "%s", message);
break;
case _LOG_NOTICE:
if (dmeventd_debug >= 1)
syslog(LOG_NOTICE, "%s", message);
break;
case _LOG_WARN:
syslog(LOG_WARNING, "%s", message);
break;
case _LOG_ERR:
syslog(LOG_ERR, "%s", message);
break;
default:
syslog(LOG_CRIT, "%s", message);
}
}
void dmeventd_lvm2_lock(void)
{
if (pthread_mutex_trylock(&_event_mutex)) {
syslog(LOG_NOTICE, "Another thread is handling an event. Waiting...");
pthread_mutex_lock(&_event_mutex);
}
}
void dmeventd_lvm2_unlock(void)
{
pthread_mutex_unlock(&_event_mutex);
}
int dmeventd_lvm2_init(void)
{
int r = 0;
pthread_mutex_lock(&_register_mutex);
if (!_mem_pool && !(_mem_pool = dm_pool_create("mirror_dso", 1024)))
goto out;
if (!_lvm_handle) {
lvm2_log_fn(_temporary_log_fn);
if (!(_lvm_handle = lvm2_init())) {
dm_pool_destroy(_mem_pool);
_mem_pool = 0;
goto out;
}
lvm2_run(_lvm_handle, "_memlock_inc");
}
_register_count++;
r = 1;
out:
pthread_mutex_unlock(&_register_mutex);
return r;
}
void dmeventd_lvm2_exit(void)
{
pthread_mutex_lock(&_register_mutex);
if (!--_register_count) {
lvm2_run(_lvm_handle, "_memlock_dec");
dm_pool_destroy(_mem_pool);
_mem_pool = 0;
lvm2_exit(_lvm_handle);
_lvm_handle = 0;
}
pthread_mutex_unlock(&_register_mutex);
}
struct dm_pool *dmeventd_lvm2_pool(void)
{
return _mem_pool;
}
int dmeventd_lvm2_run(const char *cmdline)
{
return lvm2_run(_lvm_handle, cmdline);
}
| 1
|
#include <pthread.h>
void* producersFunction(void*);
void* consumersFunction(void*);
{
int head;
int tail;
int isFull;
int isEmpty;
char buffer[5];
pthread_mutex_t mtx;
pthread_cond_t condNotFull;
pthread_cond_t condNotEmpty;
}FIFO,*PFIFO;
FIFO fifo={0,0,0,1};
int main()
{
pthread_t idProducer,idConsumer;
char str[32];
pthread_mutex_init(&fifo.mtx,0);
pthread_cond_init(&fifo.condNotFull,0);
pthread_cond_init(&fifo.condNotEmpty,0);
pthread_create(&idProducer,0,producersFunction,0);
pthread_create(&idConsumer,0,consumersFunction,0);
pthread_join(idProducer,0);
pthread_join(idConsumer,0);
pthread_mutex_destroy(&fifo.mtx);
pthread_cond_destroy(&fifo.condNotFull);
pthread_cond_destroy(&fifo.condNotEmpty);
printf("type \\"Return\\" to finish\\n");
fgets(str,sizeof(str),stdin);
return 0;
}
void* producersFunction(void* arg)
{
int i=0,wasEmpty;
for(i=0;i<6;i++)
{
pthread_mutex_lock(&fifo.mtx);
while(fifo.isFull) pthread_cond_wait(&fifo.condNotFull,&fifo.mtx);
wasEmpty=fifo.isEmpty;
fifo.buffer[fifo.head]=(i+1)*15;
fifo.head=(fifo.head+1)%5;
printf("PRODUCER. head=%d tail=%d\\n",fifo.head,fifo.tail);
fifo.isEmpty=0;
fifo.isFull=(fifo.tail==fifo.head);
if(wasEmpty) pthread_cond_signal(&fifo.condNotEmpty);
pthread_mutex_unlock(&fifo.mtx);
}
return 0;
}
void* consumersFunction(void* arg)
{
int n,i,wasFull;
for(i=0;i<6;i++)
{
sleep(1);
pthread_mutex_lock(&fifo.mtx);
while(fifo.isEmpty) pthread_cond_wait(&fifo.condNotEmpty,&fifo.mtx);
wasFull=fifo.isFull;
n=fifo.buffer[fifo.tail];
fifo.tail=(fifo.tail+1)%5;
printf("%d\\n",n);
printf("CONSUMER. head=%d tail=%d\\n",fifo.head,fifo.tail);
fifo.isEmpty=(fifo.head==fifo.tail);
fifo.isFull=0;
if(wasFull) pthread_cond_broadcast(&fifo.condNotFull);
sleep(1);
pthread_mutex_unlock(&fifo.mtx);
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int index;
} syn_obj_t;
syn_obj_t syn_obj = {PTHREAD_MUTEX_INITIALIZER,
PTHREAD_COND_INITIALIZER, 0};
int flag;
} elem_t;
void* thread_routine(void* arg);
int main(int argc, char** argv)
{
elem_t elems[4];
pthread_t pds[4];
int i;
printf("syn_obj.index = %d\\n", syn_obj.index);
for (i = 0; i < 4; i++) {
elems[i].flag = i;
if ( (pthread_create(&pds[i], 0, thread_routine, &elems[i])) != 0 ) {
perror("pthread create");
exit(-1);
}
}
for (i = 0; i < 4; i++) {
pthread_join(pds[i], 0);
}
pthread_mutex_destroy(&syn_obj.mutex);
pthread_cond_destroy(&syn_obj.cond);
printf("\\nsyn_obj.index = %d\\n", syn_obj.index);
return 0;
}
void* thread_routine(void* arg)
{
elem_t *elem = (elem_t *)arg;
int i;
for (i = 0; i < 100; i++) {
pthread_mutex_lock(&syn_obj.mutex);
while ( (syn_obj.index % 4) != elem->flag ) {
pthread_cond_wait(&syn_obj.cond, &syn_obj.mutex);
}
printf("%d", elem->flag);
if ( 0 == (syn_obj.index+1) % 4 ) {
printf("\\t");
}
syn_obj.index++;
pthread_cond_broadcast(&syn_obj.cond);
pthread_mutex_unlock(&syn_obj.mutex);
}
return 0;
}
| 1
|
#include <pthread.h>
int commonCounter = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *increment_counter(void *ptr);
int main(void) {
int error = -1;
int i = 0;
pthread_t thread_ids[10];
int mainCounter[10];
for (i = 0; i < 10; i++)
mainCounter[i] = 0;
for (i = 0; i < 10; i++) {
error = pthread_create(&thread_ids[i], 0, increment_counter, &mainCounter[i]);
if (error)
fprintf(stderr, "Error: %s\\n", strerror(error));
}
for (i = 0; i < 10; i++)
pthread_join(thread_ids[i], 0);
printf("Value of common counter: %d\\n", commonCounter);
for (i = 0; i < 10; i++)
printf("Value of main counter[%d]=%d\\n", i, mainCounter[i]);
printf("Number of losses of increments from commonCounter: %d\\n", 1000000*10 - commonCounter);
exit(0);
return 0;
}
void *increment_counter(void *ptr) {
int i = 0;
while (i < 1000000) {
*(int *)ptr = *(int *)ptr + 1;
pthread_mutex_lock(&mutex);
commonCounter++;
pthread_mutex_unlock(&mutex);
i++;
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER ;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER ;
pthread_t tid1,tid2;
int uuid=0;
void *lock_add(void *arg);
void *lock_move(void *arg);
int main(int argc,char **argv)
{
void * err;
uuid = 0 ;
pthread_mutex_lock(&mutex2);
pthread_create(&tid1,0,lock_add,"abc");
pthread_create(&tid2,0,lock_move,"123");
pthread_join(tid1,0);
pthread_join(tid2,0);
pthread_mutex_unlock(&mutex2);
printf("%d\\n",uuid);
return 0;
}
void *lock_add(void *arg)
{
unsigned int ssid = 0;
ssid = (unsigned int )pthread_self();
pthread_mutex_lock(&mutex);
printf("[%u]uuid %d\\n",ssid,uuid);
uuid++ ;
printf("[%u]uuid %d\\n",ssid,uuid);
sleep(1);
pthread_mutex_unlock(&mutex);
return 0 ;
}
void *lock_move(void *arg)
{
unsigned int ssid = 0;
ssid = (unsigned int )pthread_self();
pthread_mutex_lock(&mutex);
printf("[%u]uuid %d\\n",ssid,uuid);
uuid-- ;
printf("[%u]uuid %d\\n",ssid,uuid);
pthread_mutex_unlock(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
double pi = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *work(void *arg)
{
int start;
int end;
int i;
double local_pi = 0;
start = (200000000/2) * ((int )arg) ;
end = start + 200000000/2;
for (i = start; i < end; i++) {
local_pi += 1.0/(i*4.0 + 1.0);
local_pi -= 1.0/(i*4.0 + 3.0);
}
pthread_mutex_lock(&mutex);
pi += local_pi;
pthread_mutex_unlock(&mutex);
return 0;
}
int
main(int argc, char** argv) {
int i;
pthread_t tids[2 -1];
for (i = 0; i < 2 - 1 ; i++) {
pthread_create(&tids[i], 0, work, (void *)i);
}
i = 2 -1;
work((void *)i);
for (i = 0; i < 2 - 1 ; i++) {
pthread_join(tids[i], 0);
}
pi = pi * 4.0;
printf("pi done - %f \\n", pi);
return (0);
}
| 0
|
#include <pthread.h>
int taken;
pthread_mutex_t lock;
pthread_cond_t ready;
} Chopstick;
static Chopstick chop_new() {
Chopstick chop;
chop.taken = 0;
pthread_mutex_init( &chop.lock, 0 );
pthread_cond_init( &chop.ready, 0 );
return chop;
}
static void chop_take( Chopstick chop ) {
pthread_mutex_lock( &chop.lock );
while ( chop.taken ) {
pthread_cond_wait( &chop.ready, &chop.lock );
}
chop.taken = 1;
pthread_mutex_unlock( &chop.lock );
}
static void chop_drop( Chopstick chop ) {
pthread_mutex_lock( &chop.lock );
chop.taken = 0;
pthread_mutex_unlock( &chop.lock );
pthread_cond_signal( &chop.ready );
}
Chopstick left;
Chopstick right;
int id;
} Philosopher;
static Philosopher ph_new( int id, Chopstick left, Chopstick right ) {
Philosopher ph;
ph.id = id;
ph.left = left;
ph.right = right;
return ph;
}
static void thinking() {
int s = rand() % 1133;
usleep( s );
}
static void *ph_dining( void *p ) {
Philosopher *ph = (Philosopher *) p;
thinking();
chop_take( ph->left );
chop_take( ph->right );
thinking();
chop_drop( ph->left );
chop_drop( ph->right );
return (void *) 0;
}
int main( void ) {
Chopstick chops[ 5 ];
int size = 5;
int i;
int id = 0;
for ( i = 0; i < size; i++ ) {
chops[ i ] = chop_new();
}
Philosopher phs[ 5 ];
for ( i = 0; i < size-1; i++ ) {
phs[ i ] = ph_new( ++id, chops[ i ], chops[ (i+1) ] );
}
phs[ i ] = ph_new( ++id, chops[ 0 ], chops[ i ] );
pthread_t pid[ 5 ];
for ( i = 0; i < size; i++ ) {
pthread_create( &pid[ i ], 0, ph_dining, (void *) &phs[ i ] );
}
printf( "Print 'Enter' to quit:" );
getchar();
return 0;
}
| 1
|
#include <pthread.h>
struct propset {
char *str;
int row;
int delay;
int dir;
};
pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER;
int get_msgnum(int num_items);
int setup(int nstrings, char *strings[], struct propset props[]);
int main(int ac, char *av[])
{
int c;
pthread_t thrds[10];
struct propset props[10];
void *animate();
int num_msg ;
int i;
if ( ac == 1 ){
printf("usage: tanimate string ..\\n");
exit(1);
}
num_msg = setup(ac-1,av+1,props);
for(i=0 ; i<num_msg; i++)
if ( pthread_create(&thrds[i], 0, animate, &props[i])){
fprintf(stderr,"error creating thread");
endwin();
exit(0);
}
while(1) {
c = getch();
if ( c == 'Q' ) break;
if ( c == ' ' )
for(i=0;i<num_msg;i++)
props[i].dir = -props[i].dir;
else if ( c >= '0' && c <= '9' ){
i = c - '0';
if ( i < num_msg )
props[i].dir = -props[i].dir;
}
else if ( c == 's' ){
int arg = get_msgnum(num_msg);
if ( arg >= 0 )
props[arg].delay <<= 1;
}
else if ( c == 'f' ){
int arg = get_msgnum(num_msg);
if ( arg >= 0 && props[arg].delay > 2 )
props[arg].delay >>= 1;
}
}
pthread_mutex_lock(&mx);
for (i=0; i<num_msg; i++ )
pthread_cancel(thrds[i]);
endwin();
return 0;
}
int get_msgnum(int num_items)
{
char c = getch();
if ( c >= '0' && c < '0' + num_items )
return c - '0';
return -1;
}
int setup(int nstrings, char *strings[], struct propset props[])
{
int num_msg = ( nstrings > 10 ? 10 : nstrings );
int i;
srand(getpid());
for(i=0 ; i<num_msg; i++){
props[i].str = strings[i];
props[i].row = i;
props[i].delay = 1+(rand()%15);
props[i].dir = ((rand()%2)?1:-1);
}
initscr();
crmode();
noecho();
clear();
mvprintw(LINES-1,0,"'Q' to quit, '0'..'%d' to bounce",num_msg-1);
return num_msg;
}
void *animate(void *arg)
{
struct propset *info = arg;
int len = strlen(info->str)+2;
int col = rand()%(COLS-len-3);
while( 1 )
{
usleep(info->delay*20000);
pthread_mutex_lock(&mx);
move( info->row, col );
addch(' ');
addstr( info->str );
addch(' ');
move(LINES-1,COLS-1);
refresh();
pthread_mutex_unlock(&mx);
col += info->dir;
if ( col <= 0 && info->dir == -1 )
info->dir = 1;
else if ( col+len >= COLS && info->dir == 1 )
info->dir = -1;
}
}
| 0
|
#include <pthread.h>
int total_words;
pthread_mutex_t counter_lock = PTHREAD_MUTEX_INITIALIZER;
int main(int argc, char** argv)
{
pthread_t t1, t2;
void *count_words(void *);
if(argc != 3){
printf("usage: %s file1 fil2\\n", argv[0]);
exit(1);
}
total_words = 0;
pthread_create(&t1, 0, count_words, (void *)argv[1]);
pthread_create(&t2, 0, count_words, (void *)argv[2]);
pthread_join(t1, 0);
pthread_join(t2, 0);
printf("%5d: total words\\n", total_words);
}
void *count_words(void *f)
{
char *filename = (char *)f;
FILE *fp;
int c, prevc = '\\0';
if( ( fp = fopen(filename, "r") ) != 0 ){
while( ( c = getc(fp) ) != EOF ){
if( !isalnum(c) && isalnum(prevc) ){
pthread_mutex_lock(&counter_lock);
total_words++;
pthread_mutex_unlock(&counter_lock);
}
prevc = c;
}
fclose(fp);
}else
perror(filename);
return 0;
}
| 1
|
#include <pthread.h>
pthread_t thread;
pthread_cond_t cond;
pthread_mutex_t mutex;
unsigned char flag = 1;
void * thr_fn(void * arg)
{
struct timeval now;
struct timespec outtime;
pthread_mutex_lock(&mutex);
while (flag)
{
printf("thread sleep now\\n");
gettimeofday(&now, 0);
outtime.tv_sec = now.tv_sec + 10;
outtime.tv_nsec = now.tv_usec * 1000;
pthread_cond_timedwait(&cond, &mutex, &outtime);
}
pthread_mutex_unlock(&mutex);
printf("thread exit\\n");
}
int main()
{
char c ;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
if (0 != pthread_create(&thread, 0, thr_fn, 0))
{
printf("error when create pthread,%d\\n", errno);
return 1;
}
while ((c = getchar()) != 'q');
printf("Now terminate the thread!\\n");
flag = 0;
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
printf("Wait for thread to exit\\n");
pthread_join(thread, 0);
printf("Bye\\n");
return 0;
}
| 0
|
#include <pthread.h>
sem_t *semaphore;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int finished_threads = 0;
int n;
} data;
void *mytask(void *p_data) {
data *info = p_data;
srand(time(0));
int random = rand() % 10 + 1;
printf("Thread %d, sleeping for %d\\n", info->n, random);
sleep((unsigned int) random);
pthread_mutex_lock(&mutex);
finished_threads++;
if (finished_threads == 10) {
printf("Thread %d is waking others.\\n", info->n);
for (int i = 0; i < 10 -1; i++) {
sem_post(semaphore);
}
finished_threads = 0;
pthread_mutex_unlock(&mutex);
} else {
printf("Thread %d is waiting.\\n", info->n);
pthread_mutex_unlock(&mutex);
sem_wait(semaphore);
}
return 0;
}
int main(void) {
printf("main start\\n");
sem_unlink("barrier");
semaphore = sem_open("barrier", O_CREAT|O_EXCL, 0777, 0);
if(semaphore == SEM_FAILED) {
perror("unable to create semaphore");
sem_unlink("barrier");
exit( -1 );
}
int i;
pthread_t threads[10];
data infos[10];
for (i = 0; i < 10; i++) {
infos[i].n = i;
pthread_create(&threads[i], 0, mytask, &infos[i]);
}
for (i = 0; i < 10; i++) {
pthread_join(threads[i], 0);
}
sem_close(semaphore);
sem_unlink("barrier");
printf("main end\\n");
}
| 1
|
#include <pthread.h>
static char * buffers[10] = {0};
static int consume_index = 0;
static pthread_mutex_t buffer_mutex;
static pthread_mutex_t total_chars_mutex;
static pthread_mutex_t total_words_mutex;
static pthread_cond_t cond_empty;
static pthread_cond_t cond_full;
static int stored_count = 0;
static ulong word_total = 0;
static ulong char_total = 0;
static int calculateTotalChars(const char *buffer, const int size)
{
int i=-1;
for(i=0; i<size; i++)
{
if( '\\0' == buffer[i]) break;
}
return i+1;
}
static int calculateTotalWords(const char *buffer, const char *deliminate)
{
int total_word = 0;
char *brkt = 0;
char *word = 0;
for(word = strtok_r((char *)buffer, deliminate, &brkt); word;
word = strtok_r(0, deliminate, &brkt))
{
total_word++;
}
return total_word;
}
static void *consume()
{
unsigned int total_chars = -1;
unsigned int total_wrds = -1;
bool isFinished = 0;
char *buffer_copy = 0;
while(!isFinished)
{
pthread_mutex_lock(&buffer_mutex);
while(stored_count ==0)
{
pthread_cond_wait(&cond_empty, &buffer_mutex);
}
buffer_copy = strdup(buffers[consume_index]);
free(buffers[consume_index]);
buffers[consume_index] = 0;
consume_index++;
consume_index %= 10;
stored_count--;
pthread_cond_signal(&cond_full);
pthread_mutex_unlock(&buffer_mutex);
if(0 != strcmp(buffer_copy, "<QUIT>"))
{
total_chars = calculateTotalChars(buffer_copy, 81);
total_wrds = calculateTotalWords(buffer_copy, " \\t\\n");
pthread_mutex_lock(&total_chars_mutex);
char_total += total_chars;
pthread_mutex_unlock(&total_chars_mutex);
pthread_mutex_lock(&total_words_mutex);
word_total += total_wrds;
pthread_mutex_unlock(&total_words_mutex);
}
else
{
isFinished = 1;
}
free(buffer_copy);
buffer_copy = 0;
}
pthread_exit(0);
}
static void produce(const char *buffer, const int buf_index)
{
pthread_mutex_lock(&buffer_mutex);
while(stored_count == 10)
{
pthread_cond_wait(&cond_full, &buffer_mutex);
}
buffers[buf_index] = strdup(buffer);
stored_count++;
pthread_cond_signal(&cond_empty);
pthread_mutex_unlock(&buffer_mutex);
}
int main (int argc, char * argv[])
{
pthread_t consumer_threads[10] = {0};
char line[81] = {'\\0'};
int num_threads = -1;
FILE *inputfile = 0;
if(argc < 3)
{
printf("Usage: %s num_threads <input file>\\n", argv[0]);
exit(0);
}
else
{
num_threads = atoi(argv[1]);
if(num_threads > 10)
{
printf("Usage: the program can create at most %d threads\\n", 10);
exit(0);
}
}
bool finish_reading = 0;
int thread_exit_count = 0;
int i=-1;
printf("start processing\\n");
inputfile = fopen(argv[2], "r");
if(inputfile == 0)
{
printf("Unable to open %s\\n", argv[2]);
exit(0);
}
pthread_cond_init(&cond_empty, 0);
pthread_cond_init(&cond_full, 0);
pthread_mutex_init(&buffer_mutex, 0);
pthread_mutex_init(&total_chars_mutex, 0);
pthread_mutex_init(&total_words_mutex, 0);
finish_reading = 0;
thread_exit_count = 0;
for(i=0; i<num_threads; i++)
{
pthread_create(&consumer_threads[i], 0, consume, 0);
}
i=0;
while(10 != thread_exit_count)
{
if(finish_reading)
{
produce("<QUIT>", i);
++thread_exit_count;
}
else if(!fgets(line, 81, inputfile))
{
finish_reading = 1;
printf("Done Reading File\\n");
continue;
}
else
{
produce(line, i);
memset(line, '\\0', sizeof(line));
}
i++;
i %= 10;
}
for(i=0; i<num_threads; i++)
{
pthread_join(consumer_threads[i], 0);
}
pthread_cond_destroy(&cond_empty);
pthread_cond_destroy(&cond_full);
pthread_mutex_destroy(&buffer_mutex);
pthread_mutex_destroy(&total_chars_mutex);
pthread_mutex_destroy(&total_words_mutex);
fclose(inputfile);
printf("Tatal Characters: %lu\\n", char_total);
printf("Tatal Words: %lu\\n", word_total);
char_total = 0;
word_total = 0;
stored_count =0;
consume_index = 0;
printf("End of processing\\n");
return 0;
}
| 0
|
#include <pthread.h>
static size_t ls_usedMemoryRecord = 0;
static int ls_threadSafenessFlag = 0;
pthread_mutex_t ls_usedMemoryRecordMutex = PTHREAD_MUTEX_INITIALIZER;
static void defaultOomHandler(size_t size);
static void (* ls_oomHandler)(size_t) = defaultOomHandler;
static inline void incUsedMemoryRecord(size_t n) {
__sync_add_and_fetch(&ls_usedMemoryRecord, n);
return;
}
static inline void subUsedMemoryRecord(size_t n) {
__sync_sub_and_fetch(&ls_usedMemoryRecord, n);
return;
}
static inline void updateUsedMemoryRecordWhenAlloc(size_t n) {
size_t alignSize = n;
if(alignSize & ((sizeof(long)) - 1)) {
alignSize +=
(sizeof(long)) - (alignSize & ((sizeof(long)) - 1));
}
if(ls_threadSafenessFlag) {
incUsedMemoryRecord(alignSize);
} else {
ls_usedMemoryRecord += alignSize;
}
return;
}
static inline void updateUsedMemoryRecordWhenFree(size_t n) {
size_t alignSize = n;
if(alignSize & ((sizeof(long)) - 1)) {
alignSize +=
(sizeof(long)) - (alignSize & ((sizeof(long)) - 1));
}
if(ls_threadSafenessFlag) {
subUsedMemoryRecord(alignSize);
} else {
ls_usedMemoryRecord -= alignSize;
}
return;
}
static void defaultOomHandler(size_t size) {
fprintf(stderr,
"memory management error: Out of memory trying to allocate %zu bytes\\n",
size);
fflush(stderr);
abort();
return;
}
void * MEMMAG_malloc(size_t size) {
void * ptr = malloc(size + (sizeof(size_t)));
if(!ptr) {
ls_oomHandler(size);
}
*((size_t *)ptr) = size;
updateUsedMemoryRecordWhenAlloc(size + (sizeof(size_t)));
return (char *)ptr + (sizeof(size_t));
}
void * MEMMAG_calloc(size_t size) {
void * ptr = calloc(1, size + (sizeof(size_t)));
if(!ptr) {
ls_oomHandler(size);
}
*((size_t *)ptr) = size;
updateUsedMemoryRecordWhenAlloc(size + (sizeof(size_t)));
return (char *)ptr + (sizeof(size_t));
}
void * MEMMAG_realloc(void * oldPtr, size_t newSize) {
if(!oldPtr) {
return MEMMAG_malloc(newSize);
}
void * realOldPtr = (char *)oldPtr - (sizeof(size_t));
size_t oldSize = *((size_t *)realOldPtr);
void * newPtr = realloc(realOldPtr, newSize + (sizeof(size_t)));
if(!newPtr) {
ls_oomHandler(newSize);
}
*((size_t *)newPtr) = newSize;
updateUsedMemoryRecordWhenFree(oldSize);
updateUsedMemoryRecordWhenAlloc(newSize);
return (char *)newPtr + (sizeof(size_t));
}
void MEMMAG_free(void * ptr) {
void * realPtr = (char *)ptr - (sizeof(size_t));
size_t oldSize = *((size_t *)realPtr);
updateUsedMemoryRecordWhenFree(oldSize + (sizeof(size_t)));
free(realPtr);
return;
}
size_t MEMMAG_getUsedMemoryInBytes(void) {
size_t res;
if(ls_threadSafenessFlag) {
pthread_mutex_lock(&ls_usedMemoryRecordMutex);
res = ls_usedMemoryRecord;
pthread_mutex_unlock(&ls_usedMemoryRecordMutex);
} else {
res = ls_usedMemoryRecord;
}
return res;
}
void MEMMAG_enableThreadSafeness(void) {
ls_threadSafenessFlag = 1;
return;
}
void MEMMAG_setOomHandler(void (*oomHandler)(size_t)) {
ls_oomHandler = oomHandler;
return;
}
size_t MEMMAG_sizeOf(void * ptr) {
void * realPtr = (char *)ptr - (sizeof(size_t));
size_t size = *((size_t *)realPtr);
if(size & ((sizeof(long)) - 1)) {
size += (sizeof(long)) - (size & ((sizeof(long)) - 1));
}
return size + (sizeof(size_t));
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
void *runner(void *arg)
{
char *str;
str=(char*)arg;
usleep(10);
printf("%s about to lock\\n",str);
pthread_mutex_lock (&mutex);
printf("%s says in critical section\\n",str);
pthread_mutex_unlock (&mutex);
printf("%s says in finished\\n",str);
return 0;
}
int main(int argc, char *argv[]) {
pthread_t pth;
pthread_mutex_init(&mutex, 0);
pthread_create(&pth, 0, runner, (void *) "Thread 1");
printf("Main Thread locking\\n");
pthread_mutex_lock(&mutex);
printf("Main Thread within critical section\\n");
pthread_mutex_unlock(&mutex);
printf("Main Thread joinning with thread\\n");
pthread_join(pth, 0);
printf("Main Thread finished waiting\\n");
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
pthread_t thread_id;
} params_t;
int cancel = 0;
pthread_mutex_t mutex;
int wrs, rds, max;
int *vector;
void my_signal_handler(int sig)
{
printf("sig = %d", sig);
switch(sig) {
case SIGINT:
puts("Exiting...");
cancel = 1;
default:
break;
}
}
void* thread_writers(void* arg)
{
int i;
while(!cancel) {
pthread_mutex_lock (&mutex);
for(i = 0; i < max; i++)
if(vector[i] == 0) {vector[i] = 1; break;}
pthread_mutex_unlock (&mutex);
}
return 0;
}
void* thread_readers(void* arg)
{
int i;
while(!cancel) {
pthread_mutex_lock (&mutex);
for(i = 0; i < max; i++)
if(vector[i] == 1) {vector[i] = 0; break;}
pthread_mutex_unlock (&mutex);
}
return 0;
}
int main(int argc, char** argv, char** env)
{
params_t *p_rds, *p_wrs;
int i;
if(argc < 4) {
printf("usage:\\t%s writers readers max\\n", argv[0]);
puts("writers - количество писателей");
puts("readers - количество читателей");
puts("max - максимальное количество элементов в контейнере");
return 0;
}
wrs = atoi(argv[1]);
rds = atoi(argv[2]);
max = atoi(argv[3]);
if(wrs <= 0) {
perror(argv[1]);
exit(1);
}
if(rds <= 0) {
perror(argv[2]);
exit(1);
}
if(max < 0) {
perror(argv[3]);
exit(1);
}
static struct sigaction act_s;
act_s.sa_handler = my_signal_handler;
sigaction(SIGINT, &act_s, 0);
vector = calloc(sizeof(int), max);
p_wrs = calloc(sizeof(pthread_t), wrs);
if(p_wrs == 0) {
perror("malloc wrs");
exit(1);
}
for(i = 0; i < wrs; i++) {
if(pthread_create(&p_wrs[i].thread_id, 0, &thread_writers, 0) != 0) {
perror("pthread wrs create");
exit(1);
}
}
p_rds = calloc(sizeof(pthread_t), rds);
if(p_rds == 0) {
perror("malloc rds");
exit(1);
}
for(i = 0; i < rds; i++) {
if(pthread_create(&p_rds[i].thread_id, 0, &thread_readers, 0) != 0) {
perror("pthread rds create");
exit(1);
}
}
while(!cancel) {
int num;
usleep(100000);
pthread_mutex_lock(&mutex);
for(i = 0, num = 0; i < max; i++)
if(vector[i]) num++;
printf("vector: %d\\n", num);
pthread_mutex_unlock(&mutex);
}
free(p_wrs);
free(p_rds);
free(vector);
return 0;
}
| 1
|
#include <pthread.h>
pthread_t thread1;
pthread_mutex_t mutex;
pthread_mutexattr_t mta;
int ret;
void *a_thread_func(void *)
{
ret=pthread_mutex_unlock(&mutex);
pthread_exit((void*)0);
return 0;
}
int main()
{
if(pthread_mutexattr_init(&mta) != 0)
{
perror("Error at pthread_mutexattr_init()\\n");
return PTS_UNRESOLVED;
}
if(pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_ERRORCHECK) != 0)
{
printf("Test FAILED: Error setting the attribute 'type'\\n");
return PTS_FAIL;
}
if(pthread_mutex_init(&mutex, &mta) != 0)
{
perror("Error intializing the mutex.\\n");
return PTS_UNRESOLVED;
}
if(pthread_mutex_lock(&mutex) != 0 )
{
perror("Error locking the mutex first time around.\\n");
return PTS_UNRESOLVED;
}
if(pthread_create(&thread1, 0, a_thread_func, 0) != 0)
{
perror("Error creating a thread.\\n");
return PTS_UNRESOLVED;
}
pthread_join(thread1, 0);
if(ret == 0)
{
printf("Test FAILED: Expected an error when trying to unlock a mutex that was locked by another thread. Returned 0 instead.\\n");
return PTS_FAIL;
}
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);
if(pthread_mutexattr_destroy(&mta))
{
perror("Error at pthread_mutexattr_destroy().\\n");
return PTS_UNRESOLVED;
}
printf("Test PASSED\\n");
return PTS_PASS;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.