text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
int balanco=10000;
pthread_t threads[3];
pthread_mutex_t mutex_balanco;
void *deposita(void *valor)
{
int *a= (int *) valor;
pthread_mutex_lock(&mutex_balanco);
balanco += *a;
pthread_mutex_unlock(&mutex_balanco);
pthread_exit(0);
}
void *levanta(void *valor)
{
int *b= (int *) valor;
pthread_mutex_lock(&mutex_balanco);
balanco -= *b;
pthread_mutex_unlock(&mutex_balanco);
pthread_exit(0);
}
void main()
{
int i,s,estado,depositar=6000,levantar=5000;
pthread_mutex_init(&mutex_balanco, 0);
pthread_create(&threads[0],0,deposita,(void *)&depositar);
pthread_create(&threads[1],0,levanta,(void *)&levantar);
pthread_create(&threads[2],0,levanta,(void *)&levantar);
for(i=0; i<3; i++){
s=pthread_join(threads[i], (void **) &estado);
if (s)
{
perror("Erro no join");
exit(-1);
}
printf("O thread %d terminou com o estado %d\\n",i,estado);
}
printf("O balanço é = %d\\n",balanco);
pthread_mutex_destroy(&mutex_balanco);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
extern pthread_mutex_t global_data_mutex;
void init_wsi(int mem_fd) {
char memory[MEMSIZE];
int i;
read(mem_fd,memory,MEMSIZE);
memory[0x80] = READ_DATA_CMD;
memory[0x81] = READ_DATA_CMD;
memory[0x82] = DATA_END_BYTE;
lseek(mem_fd,0,0);
i = write(mem_fd,memory,MEMSIZE);
app_debug(debug, "init_wsi: Wrote %i bytes to device\\n",i);
}
void update_wsi_data (int mem_fd, int temp_fd) {
unsigned char memory[MEMSIZE];
char temp[6];
int dir;
float speed;
float realtemp;
lseek(mem_fd,0,0);
read(mem_fd,memory,MEMSIZE);
read(temp_fd,temp,6);
speed = (float)memory[0x89] * 2.453 * 1.069 * 1000 / 3600;
dir = (int)memory[0x8a];
realtemp = atof(temp);
app_debug(debug, "\\nBEGIN WS603 READ\\n");
if ((speed == (float)255) || (dir > 16))
{
app_debug(info, "Got garbage from the wind system. Rejecting\\n");
} else {
app_debug(debug, "Wind Speed: %2.1f m/s\\n",speed);
app_debug(debug, "Wind Dir: %i\\n",dir);
app_debug(debug, "Light: %2.1f\\n",(float)memory[0x8c]);
pthread_mutex_lock(&global_data_mutex);
global_data.wind_dir = dir;
global_data.wind_speed = speed;
global_data.updatetime = time(0);
pthread_mutex_unlock(&global_data_mutex);
}
if (global_config.ignore_wsi_temp == 0) {
if ((realtemp > (long)150) || (realtemp == (long)0.000))
{
app_debug(info, "WSI: Got garbage from the WSI603 temp sensor. Rejecting\\n");
} else {
app_debug(debug, "Temp: %2.1f\\n",realtemp);
pthread_mutex_lock(&global_data_mutex);
global_data.temp = realtemp;
global_data.updatetime = time(0);
pthread_mutex_unlock(&global_data_mutex);
}
}
app_debug(debug, "END WSI603 READ\\n\\n");
}
void wsi_set_leds (int mem_fd, int blueLevel, int redLevel) {
char memory[MEMSIZE];
lseek(mem_fd,0,0);
read(mem_fd,memory,MEMSIZE);
app_debug(debug, "LED Control: Blue %i Red: %i\\n",blueLevel, redLevel);
memory[0x80] = LED_CNTRL_CMD;
memory[0x81] = 0x00;
memory[0x82] = (0x80 | (redLevel << 4) | blueLevel);
memory[0x83] = 0x00;
memory[0x84] = 0x00;
memory[0x85] = memory[0x80] + memory[0x81] + memory[0x82] + memory[0x83] + memory[0x84];
memory[0x86] = LED_END_BYTE;
lseek(mem_fd,0,0);
write(mem_fd,memory,MEMSIZE);
lseek(mem_fd,0,0);
write(mem_fd,memory,MEMSIZE);
init_wsi(mem_fd);
}
| 0
|
#include <pthread.h>
int nitems=0;
unsigned int crcTable[256];
int BUFF_SIZE=0;
sem_t producer, consumer;
pthread_mutex_t mutex;
void *pro(void*);
void *con(void*);
unsigned int crc_computation(char*, int);
void crc_init(void);
int main(int argc, char *argv[]){
BUFF_SIZE=atoi(argv[1]);
pthread_t id1,id2;
if(argc!=3)
{
exit(1);
}
if(pthread_mutex_init(&mutex,0)<0){
perror("pthread_mutex_init");
exit(1);
}
if(sem_init(&producer,0,1)<0){
perror("sem_init");
exit(1);
}
if(sem_init(&consumer,0,1)<0){
perror("sem_init");
exit(1);
}
nitems=atoi(argv[2]);
if(nitems<0){
perror("Must Enter an integer 0 or greater!");
exit(1);
}
if(BUFF_SIZE>64000){
perror("Memory size is 64K");
exit(1);
}
if(pthread_create(&id2,0,&con,0)!=0){
perror("pthread_create");
exit(1);
}
if(pthread_create(&id1,0,&pro,0)!=0){
perror("pthread_create");
exit(1);
}
(void)pthread_join(id1,0);
(void)pthread_join(id2,0);
(void)sem_destroy(&producer);
(void)pthread_mutex_destroy(&mutex);
exit(0);
return 0;
}
void crc_init(void){
int i,j;
unsigned int crc;
for(i=0; i<256; i++){
crc=i;
for(j=8;j>0;j--){
if((crc&1)==1){
crc=(crc>>1)^0XEDB88320;
}
else{
crc=crc>>1;
}
}
crcTable[i]=crc;
printf("CRC:%d\\n ",crcTable[i]);
}
}
unsigned int crc_computation(char *buff, int nbytes){
unsigned int crc;
unsigned int n1,n2;
crc=0XFFFFFFFF;
while(nbytes!=0){
n1=crc>>8;
n2=crcTable[(crc ^ *buff) & 0xff];
crc=n1^n2;
buff++;
nbytes--;
}
return(crc);
}
void *pro(void *para){
unsigned int i;
int buff[BUFF_SIZE];
for(i=0;i<nitems;i++){
sem_wait(&consumer);
pthread_mutex_lock(&mutex);
sched_yield();
buff[i%BUFF_SIZE]=i;
printf("Produced: buff[%d]=%d \\n",i,buff[i%BUFF_SIZE]);
pthread_mutex_unlock(&mutex);
sem_post(&producer);
}
if(i==(nitems/2))
return(0);
}
void *con(void *para){
int i;
int buff[BUFF_SIZE];
for(i=0;i<nitems;i++){
sem_wait(&producer);
pthread_mutex_lock(&mutex);
sched_yield();
if(i!=buff[i%BUFF_SIZE])
printf("Consumed: buff[%d] = %d \\n",i,buff[i%BUFF_SIZE]);
else{
printf("buff[%d] = %d \\n ", i, buff[i % BUFF_SIZE]);
crc_init();
printf("CRC Computation:%d\\n",crc_computation(buff[i%BUFF_SIZE],i));
}
pthread_mutex_unlock(&mutex);
sem_post(&consumer);
}
return(0);
}
| 1
|
#include <pthread.h>
struct fork_t {
int num;
pthread_mutex_t mutex;
} fork_t;
fork_t fork_array[5] = {
{0, PTHREAD_MUTEX_INITIALIZER},
{1, PTHREAD_MUTEX_INITIALIZER},
{2, PTHREAD_MUTEX_INITIALIZER},
{3, PTHREAD_MUTEX_INITIALIZER},
{4, PTHREAD_MUTEX_INITIALIZER}
};
int eat_count[5];
void *thread_func(void *args)
{
int num = (int)args;
for (eat_count[num] = 0; eat_count[num] < 4; eat_count[num]++) {
if (num & 1) {
pthread_mutex_lock(&(fork_array[num].mutex));
pthread_mutex_lock(&(fork_array[(num+1)%5].mutex));
printf("%d 号哲学家拿到了 %d 和 %d 号叉子开始第 %d 次吃饭。\\n",
num, fork_array[num].num, fork_array[(num+1)%5].num, eat_count[num]+1);
usleep(20000);
pthread_mutex_unlock(&(fork_array[num].mutex));
pthread_mutex_unlock(&(fork_array[(num+1)%5].mutex));
} else {
pthread_mutex_lock(&(fork_array[(num+1)%5].mutex));
pthread_mutex_lock(&(fork_array[num].mutex));
printf("%d 号哲学家拿到了 %d 和 %d 号叉子开始第 %d 次吃饭。\\n",
num, fork_array[num].num, fork_array[(num+1)%5].num, eat_count[num]+1);
usleep(20000);
pthread_mutex_unlock(&(fork_array[(num+1)%5].mutex));
pthread_mutex_unlock(&(fork_array[num].mutex));
}
}
printf("%d 号哲学家吃饱了...\\n");
}
int main(int argc, char *argv[])
{
pthread_t thread[5];
int i;
for (i = 0; i < 5; i++) {
pthread_create(&thread[i], 0, thread_func, (void *)i);
}
for (i = 0; i < 5; i++) {
pthread_join(thread[i], 0);
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex3 = PTHREAD_MUTEX_INITIALIZER;
void* thread_worker(void*);
void critical_section(int thread_num , int i);
int main(int argc , char* argv[]){
pthread_t pthread_id = 0;
if(pthread_create(&pthread_id , 0 , thread_worker , 0)){
printf("create error");
return -1;
};
for (int i = 0; i < 10000; ++i) {
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2);
critical_section(1 , i);
pthread_mutex_unlock(&mutex1);
pthread_mutex_unlock(&mutex2);
}
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
pthread_mutex_destroy(&mutex3);
return 0;
}
void* thread_worker(void* p){
for (int i = 0; i < 10000; ++i) {
pthread_mutex_lock(&mutex2);
pthread_mutex_lock(&mutex2);
critical_section(2 , i);
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
}
return 0;
}
void critical_section(int thread_num , int i){
printf("Thread%d:%d\\n" , thread_num , i);
}
| 1
|
#include <pthread.h>
int chopsticks[5];
int eat_time[5];
int think_time[5];
int block_time[5];
int block_start[5];
int stop;
unsigned int seed;
pthread_mutex_t aux_mutex;
void Init();
void Close();
void Philosopher(int);
void Think(int);
void Eat(int);
unsigned int random_time(void) {
return 1 + (rand_r(&seed)/(32767/3));
}
void testError(int rc, int line, char* file) {
if (rc == 0) return;
printf("Error %s (0x%X) on line %d in file\\n%s\\n", strerror(rc), rc, line, file);
exit(1);
}
void Pickup(int phil) {
if (chopsticks[phil] == phil) { printf("Left chopstick already picked up by this philosopher\\n"); exit(1); }
if (chopsticks[phil] != -1) { printf("Left chopstick already picked up by some philosopher\\n"); exit(1); }
chopsticks[phil] = phil;
if (chopsticks[(phil+1)%5] == phil) { printf("Right chopstick already picked up by this philosopher\\n"); exit(1); }
if (chopsticks[(phil+1)%5] != -1) { printf("Right chopstick already picked up by some philosopher\\n"); exit(1); }
chopsticks[(phil+1)%5] = phil;
}
void Pickdown(int phil) {
if (chopsticks[phil] != phil) { printf("Left chopstick hasn't been picked up by this philosopher\\n"); exit(1); }
chopsticks[phil] = -1;
if (chopsticks[(phil+1)%5] != phil) { printf("Right chopstick hasn't been picked up by this philosopher\\n"); exit(1); }
chopsticks[(phil+1)%5] = -1;
}
void Eat(int phil) {
testError(pthread_mutex_lock(&aux_mutex), 66, "dphil_leftie.c");
block_time[phil] += time(0) - block_start[phil];
int eat_len = random_time();
eat_time[phil] += eat_len;
Pickup(phil);
printf("Philosopher %d is eating for %d s\\n", phil, eat_len);
testError(pthread_mutex_unlock(&aux_mutex), 72, "dphil_leftie.c");
sleep(eat_len);
testError(pthread_mutex_lock(&aux_mutex), 74, "dphil_leftie.c");
printf("Philosopher %d stopped eating\\n", phil);
Pickdown(phil);
testError(pthread_mutex_unlock(&aux_mutex), 77, "dphil_leftie.c");
}
void Think(int phil) {
testError(pthread_mutex_lock(&aux_mutex), 81, "dphil_leftie.c");
int think_len = random_time();
think_time[phil] += think_len;
printf("Philosopher %d is thinking for %d s\\n", phil, think_len);
testError(pthread_mutex_unlock(&aux_mutex), 85, "dphil_leftie.c");
sleep(think_len);
testError(pthread_mutex_lock(&aux_mutex), 87, "dphil_leftie.c");
printf("Philosopher %d stopped thinking\\n", phil);
block_start[phil] = time(0);
testError(pthread_mutex_unlock(&aux_mutex), 90, "dphil_leftie.c");
}
void* philosopher_wrapper(void* param) {
int phil;
phil = (int)(param);
while(!stop) {
Philosopher(phil);
}
pthread_exit(0);
return 0;
}
int main(void) {
int i;
stop = 0;
seed = 0;
srand(time(0));
pthread_t threads[5];
int start_time;
int total_time;
for (i=0; i<5; i++) {
chopsticks[i] = -1;
eat_time[i] = 0;
think_time[i] = 0;
block_time[i] = 0;
}
testError(pthread_mutex_init(&aux_mutex, 0), 123, "dphil_leftie.c");
Init();
start_time = time(0);
for (i=0; i<5; i++)
testError(pthread_create( &threads[i], 0, &philosopher_wrapper, (void*) i), 129, "dphil_leftie.c");
sleep(100);
stop = 1;
for (i=0; i<5; i++)
testError(pthread_join( threads[i], 0), 135, "dphil_leftie.c");
total_time = time(0) - start_time;
Close();
for (i=0; i<5; i++) {
printf("Philosopher %d: eat_time=%d%%, think_time=%d%%, block_time=%d%%\\n", i, eat_time[i]*100/total_time, think_time[i]*100/total_time, block_time[i]*100/total_time);
}
pthread_mutex_destroy(&aux_mutex);
exit(0);
}
pthread_mutex_t chopstick_mutexes[5];
void Init(void) {
int i;
for (i=0;i<5;i++)
pthread_mutex_init(&chopstick_mutexes[i], 0);
}
void Close(void) {
int i;
for (i=0;i<5;i++)
pthread_mutex_destroy(&chopstick_mutexes[i]);
}
void Philosopher(int phil) {
Think(phil);
int first = (phil != 0 ? phil : (phil+1)%5);
int second = (phil != 0 ? (phil+1)%5 : phil);
pthread_mutex_lock(&chopstick_mutexes[first]);
pthread_mutex_lock(&chopstick_mutexes[second]);
Eat(phil);
pthread_mutex_unlock(&chopstick_mutexes[first]);
pthread_mutex_unlock(&chopstick_mutexes[second]);
}
| 0
|
#include <pthread.h>
FILE *arq, *arqSaida;
int nThreads;
char* Buffer[5];
int count = 0, out = 0;
int fimDeArquivo = 0;
pthread_mutex_t mutex;
pthread_cond_t cond_cons, cond_prod;
void insereCaracteres(long int* cnt, char* s);
void merge(long int* a, long int* b);
void print(long int* c, FILE* arqSaida);
void insereBuffer(char* aux);
char* retiraBuffer(int n);
void* ProduzBloco(void* arg)
{
size_t n = 0;
double readStart, readEnd;
GET_TIME(readStart);
while(!feof(arq))
{
char* aux = (char*) malloc(sizeof(char) * (1048575 + 1));
n = fread((void *)aux, sizeof(char), 1048575, arq);
if(n < 1048575) aux[n] = '\\0';
insereBuffer(aux);
}
GET_TIME(readEnd);
printf("Tempo de leitura: %lf\\n", readEnd - readStart);
pthread_mutex_lock(&mutex);
fimDeArquivo = 1;
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void insereBuffer(char* aux)
{
static int in = 0;
pthread_mutex_lock(&mutex);
while(count == 5) {
if(0) printf("Produtora vai se bloquear\\n");
pthread_cond_wait(&cond_prod, &mutex);
if(0) printf("Produtora se livrou de suas amarras\\n");
}
count++;
Buffer[in] = aux;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond_cons);
in = (in + 1) % 5;
}
void* ConsomeBloco(void* arg)
{
long int *temp_l = (long int*) malloc(sizeof(long int) * 127);
int i, tid = *(int *)arg; free(arg);
for(i = 0; i < 127; i++) temp_l[i] = 0;
char* bloco;
pthread_mutex_lock(&mutex);
int fda = fimDeArquivo;
int count_local = count;
pthread_mutex_unlock(&mutex);
while(!fda || count_local != 0)
{
bloco = retiraBuffer(tid);
if(bloco != 0)
{
insereCaracteres(temp_l, bloco);
free(bloco);
}
pthread_mutex_lock(&mutex);
fda = fimDeArquivo;
count_local = count;
pthread_mutex_unlock(&mutex);
}
pthread_cond_broadcast(&cond_cons);
pthread_exit((void *)temp_l);
}
char* retiraBuffer(int n)
{
pthread_mutex_lock(&mutex);
while(count == 0)
{
if(fimDeArquivo)
{
if(0) printf("Consumidora %d retornou NULL\\n", n);
pthread_cond_broadcast(&cond_cons);
pthread_mutex_unlock(&mutex);
return 0;
}
if(0) printf("Consumidora %d vai se bloquear\\n", n);
pthread_cond_wait(&cond_cons, &mutex);
if(0) printf("Consumidora %d se livrou das amarras\\n", n);
}
if(0) printf("Consumi %d\\n", n);
count--;
char* bloco = Buffer[out];
out = (out + 1) % 5;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond_prod);
return bloco;
}
int main(int argc, char** argv)
{
int i;
int *arg;
pthread_t* system_id;
long int charCount[127];
double start, end;
double procStart, procEnd;
double printStart, printEnd;
GET_TIME(start);
for (i = 0; i < 127; i++) charCount[i] = 0;
if(argc < 4)
{
printf("Entrada deve ser da forma <arquivo de entrada>.txt <arquivo de saida>.txt <numero de consumidores>\\n");
exit(-1);
}
arq = fopen(argv[1], "r");
if(arq == 0) {
fprintf(stderr, "Erro ao abrir o arquivo de entrada.\\n");
exit(-1);
}
arqSaida = fopen(argv[2], "w");
if(arqSaida == 0) {
fprintf(stderr, "Erro ao abrir o arquivo de saida.\\n");
exit(-1);
}
nThreads = atoi(argv[3]) + 1;
system_id = malloc(sizeof(pthread_t) * nThreads);
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond_prod, 0);
pthread_cond_init(&cond_cons, 0);
if(pthread_create(&system_id[0], 0, ProduzBloco, 0))
{ printf("Erro pthread_create"); exit(-1);}
GET_TIME(procStart);
for(i = 1; i < nThreads; i++)
{
arg = malloc(sizeof(int));
*arg = i;
if(pthread_create(&system_id[i], 0, ConsomeBloco, (void*)arg))
{ printf("Erro pthread_create"); exit(-1);}
}
if(pthread_join(system_id[0], 0))
{ printf("Erro pthread_join"); exit(-1);}
if(0) printf("dei join (produtora)\\n");
long int* ret;
for(i = 1; i < nThreads; i++)
{
if(pthread_join(system_id[i], (void**) &ret))
{ printf("Erro pthread_join"); exit(-1);}
merge(charCount, ret);
}
GET_TIME(procEnd);
printf("Tempo de processamento: %lf\\n", procEnd - procStart);
if(0) printf("dei join (consumidoras)\\n");
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond_cons);
pthread_cond_destroy(&cond_prod);
GET_TIME(printStart);
fprintf(arqSaida ,"Caractere, Qtde\\n");
print(charCount, arqSaida);
GET_TIME(printEnd);
printf("Tempo de escrita: %lf\\n", printEnd - printStart);
fclose(arq);
fclose(arqSaida);
GET_TIME(end);
printf("Tempo total decorrido: %lf\\n", end - start);
pthread_exit(0);
}
void insereCaracteres(long int* cnt, char* s)
{
int i;
for (i = 0; i < 1048575; i++)
{
if(s[i] == '\\0') break;
if(s[i] >= 0 && s[i] < 127) cnt[s[i]]++;
}
}
void merge(long int* a, long int* b)
{
int i;
for(i = 0; i < 127; i++)
a[i] += b[i];
}
int checkChar(char c)
{
if(c >= 'A' && c <= 'Z') return 1;
if(c >= 'a' && c <= 'z') return 1;
if(c >= '0' && c <= '9') return 1;
if(c == '?' || c == '!'
|| c == '.' || c == ';'
|| c == ':' || c == '_'
|| c == '-' || c == '('
|| c == ')' || c == '@'
|| c == '%' || c == '&'
return 1;
return 0;
}
void print(long int* c, FILE* arq)
{
int i;
for (i = 0; i < 127; i++)
{
if(checkChar(i) && c[i] > 0) fprintf(arq, "%c, %ld\\n", i, c[i]);
}
}
| 1
|
#include <pthread.h>
int array[4];
int array_index = 0;
pthread_mutex_t mutex;
void *thread(void * arg)
{
pthread_mutex_lock(&mutex);
array[array_index] = 1;
pthread_mutex_unlock(&mutex);
return 0;
}
int main()
{
int i, sum;
pthread_t t[4];
pthread_mutex_init(&mutex, 0);
i = 0;
pthread_create(&t[i], 0, thread, 0);
pthread_mutex_lock(&mutex); array_index++; pthread_mutex_unlock(&mutex); i++;
pthread_create(&t[i], 0, thread, 0);
pthread_mutex_lock(&mutex); array_index++; pthread_mutex_unlock(&mutex); i++;
pthread_create(&t[i], 0, thread, 0);
pthread_mutex_lock(&mutex); array_index++; pthread_mutex_unlock(&mutex); i++;
pthread_create(&t[i], 0, thread, 0);
pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); i++;
__VERIFIER_assert (i == 4);
__VERIFIER_assert (array_index < 4);
i = 0;
pthread_join (t[i], 0); i++;
pthread_join (t[i], 0); i++;
pthread_join (t[i], 0); i++;
pthread_join (t[i], 0); i++;
__VERIFIER_assert (i == 4);
sum = 0;
i = 0;
sum += array[i]; i++;
sum += array[i]; i++;
sum += array[i]; i++;
sum += array[i]; i++;
__VERIFIER_assert (i == 4);
printf ("m: sum %d SIGMA %d\\n", sum, 4);
__VERIFIER_assert (sum == 4);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t threadExclusion, dataExclusion;
int n, v[100 +5];
void *computeThread(void *arg) {
int nr = *(int *) arg;
printf("Thread started. Nr: %d \\n", nr);
while(n < 100) {
printf("while\\n");
sleep(nr);
pthread_mutex_lock(&threadExclusion);
pthread_mutex_unlock(&threadExclusion);
int nr = rand() % 100 + 1;
printf("Thread inserting number: %d\\n", nr);
}
free(arg);
}
int main(int argc, char *argv[]) {
pthread_t threads[105];
srand(time(0));
if(pthread_mutex_init(&threadExclusion, 0) != 0 || pthread_mutex_init(&dataExclusion, 0) != 0) {
perror("Error creating mutex");
exit(1);
}
n = 1;
int i;
pthread_mutex_lock(&threadExclusion);
for(i = 1; i < argc; i++) {
int nr = atoi(argv[i]);
int *toSend = malloc(sizeof(int));
*toSend = nr;
pthread_create(&threads[i], 0, computeThread, toSend);
}
pthread_mutex_unlock(&threadExclusion);
for(i = 1; i < argc; i++) {
pthread_join(threads[i], 0);
}
if(pthread_mutex_destroy(&threadExclusion) != 0 || pthread_mutex_destroy(&dataExclusion) != 0) {
perror("Error destroing mutex");
exit(1);
}
printf("Daa\\n");
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
void *work(void *arg) {
pthread_mutex_unlock(&lock);
pthread_mutex_lock(&lock);
return arg;
}
int main() {
int ret;
pthread_t thread1, thread2;
ret = pthread_mutex_init(&lock, 0);
if (ret) {
fprintf(stderr, "pthread_mutex_init, error: %d\\n", ret);
return ret;
}
ret = pthread_create(&thread1, 0, work, 0);
if (ret) {
fprintf(stderr, "pthread_create, error: %d\\n", ret);
return ret;
}
ret = pthread_create(&thread2, 0, work, 0);
if (ret) {
fprintf(stderr, "pthread_create, error: %d\\n", ret);
return ret;
}
ret = pthread_join(thread1, 0);
if (ret) {
fprintf(stderr, "pthread_join, error: %d\\n", ret);
return ret;
}
ret = pthread_join(thread2, 0);
if (ret) {
fprintf(stderr, "pthread_join, error: %d\\n", ret);
return ret;
}
ret = pthread_mutex_destroy(&lock);
if (ret) {
fprintf(stderr, "pthread_mutex_destroy, error: %d\\n", ret);
return ret;
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t *mutex_init( void ) {
pthread_mutex_t *mutex = (pthread_mutex_t *) myalloc( sizeof(pthread_mutex_t) );
if( pthread_mutex_init( mutex, 0) != 0 )
fail( "pthread_mutex_init() failed." );
return mutex;
}
void mutex_destroy( pthread_mutex_t *mutex ) {
if( mutex != 0 ) {
pthread_mutex_destroy( mutex );
myfree( mutex );
}
}
void mutex_block( pthread_mutex_t *mutex ) {
pthread_mutex_lock( mutex );
}
void mutex_unblock( pthread_mutex_t *mutex ) {
pthread_mutex_unlock( mutex );
}
| 1
|
#include <pthread.h>
static int glob = 0;
static pthread_mutex_t mtx1 = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t mtx2 = PTHREAD_MUTEX_INITIALIZER;
void incr1(){
pthread_mutex_lock(&mtx2);
glob += 1;
printf("in t1 glob = %d\\n", glob);
pthread_mutex_unlock(&mtx2);
}
void incr2(){
pthread_mutex_lock(&mtx1);
glob += 1;
printf("in t2 glob = %d\\n", glob);
pthread_mutex_unlock(&mtx1);
}
static void *
threadFunc1(void *arg)
{
pthread_mutex_lock(&mtx1);
incr1();
pthread_mutex_unlock(&mtx1);
return 0;
}
static void *
threadFunc2(void *arg)
{
pthread_mutex_lock(&mtx2);
incr2();
pthread_mutex_unlock(&mtx2);
return 0;
}
int
main(int argc, char *argv[])
{
pthread_t t1, t2;
int s;
s = pthread_create(&t1, 0, threadFunc1, 0);
s = pthread_create(&t2, 0, threadFunc2, 0);
s = pthread_join(t1, 0);
s = pthread_join(t2, 0);
printf("glob = %d\\n", glob);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t write;
FILE* fp;
void* write_1()
{
int i=0;
for(i=0;i<=1000;i++) {
pthread_mutex_lock(&write);
fprintf(fp,"$%d \\n", i);
pthread_mutex_unlock(&write);
}
printf("write_1 performed \\n");
}
void* write_2()
{
int i = 0;
for(i=0;i<=1000;i++) {
pthread_mutex_lock(&write);
pthread_mutex_unlock(&write);
}
printf("write_2 performed \\n");
}
main()
{
pthread_t tid1,tid2;
fp = fopen("temp", "w");
if(fp == 0) {
printf("file can't be open");
}
pthread_create(&tid1,0,&write_1,0);
printf("tid1 created \\n");
pthread_create(&tid2,0,&write_2,0);
printf("tid2 created \\n");
pthread_join(tid1,0);
pthread_join(tid2,0);
fclose(fp);
}
| 1
|
#include <pthread.h>
unsigned int cnt = 0;
unsigned int NUM_ITERS;
pthread_mutex_t cnt_lock;
void *count(void *arg)
{
int i;
for(i = 0; i < NUM_ITERS; i++)
{
pthread_mutex_lock(&cnt_lock);
cnt++;
pthread_mutex_unlock(&cnt_lock);
}
return 0;
}
int main(int argc, char *argv[])
{
pthread_t tid1, tid2;
if((argc > 2) && isdigit(*argv[1]))
NUM_ITERS = atoi(argv[1]);
else{
const int LINE_SIZE = 16;
char line[LINE_SIZE];
do
{
printf("How many iterations shall each thread do? ");
fgets(line, LINE_SIZE, stdin);
}
while (!isdigit(line[0]));
NUM_ITERS = atoi(line);
}
pthread_mutex_init(&cnt_lock, 0);
pthread_create(&tid1, 0, count, 0);
pthread_create(&tid2, 0, count, 0);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
pthread_mutex_destroy(&cnt_lock);
printf("Should be %d is %d\\n", NUM_ITERS*2, cnt);
return 0;
}
| 0
|
#include <pthread.h>
const int NHASH=29;
pthread_mutex_t hashlock=PTHREAD_MUTEX_INITIALIZER;
struct foo{
int f_count;
pthread_mutex_t f_lock;
int f_id;
struct foo* f_next;
};
struct foo* fh[NHASH];
struct foo* foo_alloc(int id){
struct foo* fp;
int idx;
if((fp=(struct foo*)malloc(sizeof(struct foo)))!=0){
fp->f_count=1;
fp->f_id=id;
if(pthread_mutex_init(&fp->f_lock,0)!=0){
free(fp);
return 0;
}
idx=(((unsigned long)id)%NHASH);
pthread_mutex_lock(&hashlock);
fp->f_next=fh[idx];
fh[idx]=fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
}
return fp;
}
void foo_hold(struct foo* fp){
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
struct foo* foo_find(int id){
struct foo* fp;
pthread_mutex_lock(&hashlock);
for(fp=fh[(((unsigned long)id)%NHASH)];fp!=0;fp=fp->f_next){
if(fp->f_id==id){
fp->f_count++;
break;
}
}
pthread_mutex_unlock(&hashlock);
return fp;
}
void foo_rele(struct foo* fp){
struct foo* tfp;
int idx;
pthread_mutex_lock(&fp->f_lock);
if(fp->f_count==1){
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_lock(&hashlock);
pthread_mutex_lock(&fp->f_lock);
if(fp->f_count!=1){
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
return;
}else{
idx=(((unsigned long)fp->f_id)%NHASH);
tfp=fh[idx];
if(tfp==fp){
fh[idx]=fp->f_next;
}else{
while(tfp->f_next!=fp)
tfp=tfp->f_next;
tfp->f_next=fp->f_next;
}
}
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_destory(&fp->f_lock);
free(fp);
}else{
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
}
}
void foo_rele2(struct foo* fp){
struct foo* tfp;
int idx;
pthread_mutex_lock(&hashlock);
if(--fp->f_count==0){
idx=(((unsigned long)fp->f_id)%NHASH);
tfp=fh[idx];
if(tfp==fp){
fh[idx]=fp->f_next;
}else{
while(tfp->f_next!=fp)
tfp=tfp->f_next;
tfp->f_next=fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_destory(&fp->f_lock);
free(fp);
}else
pthread_mutex_unlock(&hashlock);
}
| 1
|
#include <pthread.h>
char n[1024];
pthread_mutex_t lock= PTHREAD_MUTEX_INITIALIZER;
int string_read=0;
pthread_cond_t cond;
void * read1()
{
while(1){
while(string_read);
pthread_mutex_lock(&lock);
printf("Enter a string: ");
scanf("%s",n);
string_read=1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
}
}
void * write1()
{
while(1){
pthread_mutex_lock(&lock);
while(!string_read)
pthread_cond_wait(&cond,&lock);
printf("The string entered is %s\\n",n);
string_read=0;
pthread_mutex_unlock(&lock);
}
}
int main()
{
int status;
pthread_t tr, tw;
pthread_create(&tr,0,read1,0);
pthread_create(&tw,0,write1,0);
pthread_join(tr,0);
pthread_join(tw,0);
return 0;
}
| 0
|
#include <pthread.h>
int const N_THR = 10;
double Ns = 0;
double Zs = 0;
double const e = 0.0001;
int const N = 100;
pthread_mutex_t lock ;
pthread_cond_t pogoj ;
int piFound = 0;
void *funkcija_niti(void *arg)
{
int n = 0;
int z = 0;
double piP = 0;
while (1)
{
int i;
for ( i = 0; i < N; ++i)
{
double x = ((double) rand()) / 32767;
double y = ((double) rand()) / 32767;
if ((pow(x, 2) + pow(y, 2)) <= 1)
z++;
n++;
}
pthread_mutex_lock(&lock);
if (piFound == 1)
{
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
Ns += n;
Zs += z;
piP = (4 * Zs) / Ns;
if ( piFound == 0 && fabs(M_PI - piP) <= e)
{
piFound = 1;
printf("Pi found \\n");
fflush(0);
pthread_cond_signal(&pogoj);
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
pthread_mutex_unlock(&lock);
}
pthread_exit(0);
}
void *funkcija_B(void *arg)
{
pthread_mutex_lock(&lock);
pthread_cond_wait(&pogoj, &lock);
printf("B wakes up \\n");
printf("%f\\n", (4 * Zs) / Ns);
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
int main(int argc, char const *argv[])
{
srand(time(0));
pthread_mutex_init(&lock, 0);
pthread_cond_init(&pogoj, 0);
pthread_t A[N_THR];
pthread_t B;
int i;
int ret;
ret = pthread_create(&B, 0, funkcija_B, (void *)0);
if (ret)
{
printf("Napaka (%d)\\n", ret);
exit(1);
}
for ( i = 0; i < N_THR; i++)
{
ret = pthread_create(&A[i], 0, funkcija_niti, (void *)i);
if (ret)
{
printf("Napaka (%d)\\n", ret);
exit(1);
}
}
ret = pthread_create(&B, 0, funkcija_B, (void *)0);
if (ret)
{
printf("Napaka (%d)\\n", ret);
exit(1);
}
pthread_join(B, 0);
printf("Thread B returned \\n");
for ( i = 0; i < N_THR; ++i)
{
pthread_join(A[i], 0);
printf("Thread A[%i] returned \\n", i);
fflush(0);
}
pthread_join(B, 0);
printf("Thread B returned \\n");
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&pogoj);
}
| 1
|
#include <pthread.h>
pthread_t thread1, thread2;
static pthread_mutex_t verrou1, verrou2;
int var=5, N=10, i=1,j=1;
void *lire(void *nom_du_thread)
{
pthread_mutex_lock(&verrou1);
printf(" lire variable = %d\\n",var);
for (i=0;i<N-1;i++)
{
pthread_mutex_unlock(&verrou2);
pthread_mutex_lock(&verrou1);
printf(" lire variable = %d\\n",var);
}
pthread_exit(0);
}
void *ecrire(void *nom_du_thread)
{
for( j=0;j<N-1;j++){
printf("ecriture %d dans variable \\n",var);
sleep(1);
pthread_mutex_unlock(&verrou1);
pthread_mutex_lock(&verrou2);
var=var+1;
}
printf("ecriture %d dans variable \\n",var);
pthread_mutex_unlock(&verrou1);
pthread_exit(0);
}
int main()
{
pthread_mutex_init(&verrou1,0);
pthread_mutex_init(&verrou2,0);
pthread_mutex_lock(&verrou1);
pthread_mutex_lock(&verrou2);
pthread_create(&thread1,0,lire,0);
pthread_create(&thread2,0,ecrire,0);
pthread_join(thread1,0);
pthread_join(thread2,0);
}
| 0
|
#include <pthread.h>
static volatile bool running_flag = 0;
static int pipe_input[2];
static int pipe_output[2];
static char server_dir[PATH_MAX];
static char server_cmd[PATH_MAX];
static int server_pid = -1;
static pthread_mutex_t fd_mutex;
static pthread_t wait_thread_id;
static int run_server();
static void exec_command(char* cmd);
static void set_privilege(char* path);
static void* wait_thread(void* args);
bool game_init()
{
if(pipe(pipe_input) == -1) {
return 0;
}
if(pipe(pipe_output) == -1) {
close(pipe_input[0]);
close(pipe_input[1]);
return 0;
}
pthread_mutex_init(&fd_mutex, 0);
return 1;
}
void game_destroy()
{
game_stop();
pthread_mutex_destroy(&fd_mutex);
close(pipe_input[0]);
close(pipe_input[1]);
close(pipe_output[0]);
close(pipe_output[1]);
return;
}
bool game_start()
{
pthread_mutex_lock(&fd_mutex);
if(!running_flag) {
cfg_get_mcserver_dir(server_dir, PATH_MAX);
cfg_get_mcserver_cmd_line(server_cmd, PATH_MAX);
running_flag = 1;
if(pthread_create(&wait_thread_id, 0, wait_thread, 0) != 0) {
running_flag = 0;
pthread_mutex_unlock(&fd_mutex);
return 0;
}
}
pthread_mutex_unlock(&fd_mutex);
return 1;
}
void game_stop()
{
void* p_null;
pthread_mutex_lock(&fd_mutex);
if(running_flag) {
running_flag = 0;
write(pipe_input[1], "\\n", 1);
sleep(1);
write(pipe_input[1], "stop\\n", 5);
pthread_join(wait_thread_id, &p_null);
}
pthread_mutex_unlock(&fd_mutex);
return;
}
bool game_is_running()
{
return running_flag;
}
size_t game_read(char* buf, size_t buf_size)
{
ssize_t ret;
char* log_buf;
ret = read(pipe_output[0], buf, buf_size);
if(ret > 0) {
log_buf = malloc(ret + 1);
memcpy(log_buf, buf, ret);
*(log_buf + ret) = '\\0';
printlog(LOG_SERVER, "%s", log_buf);
free(log_buf);
return ret;
} else {
return 0;
}
return 0;
}
size_t game_write(char* buf, size_t size)
{
ssize_t ret;
if(running_flag) {
ret = write(pipe_input[1], buf, size);
if(ret > 0) {
return ret;
} else {
return 0;
}
}
return 0;
}
int run_server()
{
pid_t pid;
pid = fork();
if(pid == -1) {
return -1;
} else if(pid != 0) {
return pid;
}
if(dup2(pipe_input[0], STDIN_FILENO) == -1) {
exit(-1);
}
if(dup2(pipe_output[1], STDOUT_FILENO) == -1) {
exit(-1);
}
if(dup2(pipe_output[1], STDERR_FILENO) == -1) {
exit(-1);
}
if(chdir(server_dir) != 0) {
exit(-1);
}
exec_command(server_cmd);
exit(-1);
return -1;
}
void exec_command(char* cmd)
{
bool quote_flag;
char** args;
int arg_num;
char* buf;
char* p;
char** p_args;
char* server_path;
size_t len;
buf = malloc(strlen(cmd) + 1);
strcpy(buf, cmd);
for(quote_flag = 0, arg_num = 1, p = buf;
*p != '\\0';
p++) {
if(*p == '\\"' || *p == '\\'') {
quote_flag = !quote_flag;
} else if(*p == ' ' && !quote_flag) {
arg_num++;
}
}
args = malloc(sizeof(char*) * (arg_num + 1));
*args = buf;
for(p_args = args + 1, quote_flag = 0, p = buf;
*p != '\\0';
p++) {
if(*p == '\\"' || *p == '\\'') {
quote_flag = !quote_flag;
} else if(*p == ' ' && !quote_flag) {
*p = '\\0';
p++;
*p_args = p;
p_args++;
}
}
*p_args = 0;
len = cfg_get_mcserver_path(0, 0);
server_path = malloc(len);
cfg_get_mcserver_path(server_path, len);
set_privilege(server_path);
free(server_path);
execvp(buf, args);
return;
}
void set_privilege(char* path)
{
struct stat result;
if(stat(path, &result) != 0) {
return;
}
setgid(result.st_gid);
setgroups(1, &(result.st_gid));
setuid(result.st_uid);
return;
}
void* wait_thread(void* args)
{
int status;
while(running_flag) {
pthread_mutex_lock(&fd_mutex);
server_pid = run_server();
if(server_pid == -1) {
pthread_mutex_unlock(&fd_mutex);
printlog(LOG_SERVER, "Failed to run server!\\n");
continue;
}
pthread_mutex_unlock(&fd_mutex);
printlog(LOG_SERVER, "Server started.\\n");
waitpid(server_pid, &status, 0);
}
UNREFERRED_PARAMETER(args);
return 0;
}
| 1
|
#include <pthread.h>
static void* thread_func(void* thread_arg);
static pthread_mutex_t s_mutex;
static pthread_cond_t s_cond;
static int s_use_mutex = 0;
static void set_thread_name(const char* const name)
{
int res;
VALGRIND_DO_CLIENT_REQUEST(res, 0, VG_USERREQ__SET_THREAD_NAME,
"%s", name, 0, 0, 0);
}
int main(int argc, char** argv)
{
int optchar;
pthread_t threadid;
set_thread_name("main");
while ((optchar = getopt(argc, argv, "m")) != EOF)
{
switch (optchar)
{
case 'm':
s_use_mutex = 1;
break;
default:
assert(0);
}
}
pthread_cond_init(&s_cond, 0);
pthread_mutex_init(&s_mutex, 0);
pthread_mutex_lock(&s_mutex);
pthread_create(&threadid, 0, thread_func, 0);
pthread_cond_wait(&s_cond, &s_mutex);
pthread_mutex_unlock(&s_mutex);
pthread_join(threadid, 0);
pthread_mutex_destroy(&s_mutex);
pthread_cond_destroy(&s_cond);
return 0;
}
static void* thread_func(void* thread_arg)
{
set_thread_name("thread_func");
pthread_mutex_lock(&s_mutex);
pthread_mutex_unlock(&s_mutex);
if (s_use_mutex) pthread_mutex_lock(&s_mutex);
pthread_cond_signal(&s_cond);
if (s_use_mutex) pthread_mutex_unlock(&s_mutex);
return 0;
}
| 0
|
#include <pthread.h>
struct MuxerList * MuxerListInit(int maxLen)
{
struct MuxerList * list = (struct MuxerList*)malloc(sizeof(struct MuxerList));
memset(list, 0, sizeof(struct MuxerList));
list->listMaxLen = maxLen;
return list;
}
void MuxerListPutData(struct MuxerList * list, char * data, int dataLen)
{
if(0 == data)
{
return;
}
if(list->isOver == 1){
free(data);
return;
}
pthread_mutex_lock(&(list->mutex));
while(list->listLen == list->listMaxLen)
{
pthread_cond_wait(&(list->condFull), &(list->mutex));
if(list->isOver == 1){
break;
}
}
if(list->isOver == 1){
free(data);
}else{
int curlen = list->listLen;
struct MuxerListNode * node = (struct MuxerListNode*)malloc(sizeof(struct MuxerListNode));
node->dataLen = dataLen;
node->data = data;
node->next = 0;
if(curlen == 0){
list->tail = node;
list->head = node;
}else{
list->tail->next = node;
list->tail = node;
}
list->listLen++;
if(curlen == 0){
pthread_cond_broadcast(&(list->condEmpty));
}
}
pthread_mutex_unlock(&(list->mutex));
}
char * MuxerListGetData(struct MuxerList * list, int * dataLen)
{
pthread_mutex_lock(&(list->mutex));
if(list->isOver == 1 && list->listLen == 0){
*dataLen = 0;
pthread_mutex_unlock(&(list->mutex));
return 0;
}
while(list->listLen == 0)
{
pthread_cond_wait(&(list->condEmpty), &(list->mutex));
if(list->isOver == 1){
break;
}
}
char *ret = 0;
if(list->isOver == 1 && list->listLen == 0){
*dataLen = 0;
}else{
int curlen = list->listLen;
struct MuxerListNode * node = list->head;
*dataLen = node->dataLen;
ret = node->data;
free(node);
list->head = list->head->next;
list->listLen--;
if(curlen == list->listMaxLen){
pthread_cond_broadcast(&(list->condFull));
}
}
pthread_mutex_unlock(&(list->mutex));
return ret;
}
void MuxerListDestory(struct MuxerList * list)
{
pthread_mutex_lock(&(list->mutex));
list->isOver = 1;
pthread_cond_broadcast(&(list->condFull));
pthread_cond_broadcast(&(list->condEmpty));
while(list->listLen > 0){
struct MuxerListNode * node = list->head;
list->head = list->head->next;
if(node->data != 0){
free(node->data);
}
list->listLen--;
}
pthread_mutex_unlock(&(list->mutex));
}
| 1
|
#include <pthread.h>
void *fetch_player_orders(void *args)
{
char line[LINE_SIZE];
struct ARGS *arg = args;
fgets(line, LINE_SIZE, arg->P->in);
while (strcmp(line, "go\\n") != 0) {
struct fleet *f = malloc(sizeof(*f));
fgets(line, LINE_SIZE, arg->P->in);
sscanf(line, "%d %d %d", &f->src, &f->dst, &f->nb_ships);
pthread_mutex_lock(arg->mutex);
if (*(arg->stop)) {
pthread_mutex_unlock(arg->mutex);
free(f);
pthread_exit((void*) 1);
}
nqueue_push(arg->order_queue, f);
pthread_mutex_unlock(arg->mutex);
}
pthread_mutex_lock(arg->mutex);
(*(arg->count))++;
if (*(arg->count) >= arg->nb_players)
pthread_cond_signal(arg->cond);
pthread_mutex_unlock(arg->mutex);
pthread_exit((void*) 0);
}
void wait_fetching_or_timer_end(
struct timespec *time, int *stop,
pthread_mutex_t *mutex, pthread_cond_t *cond)
{
pthread_mutex_lock(mutex);
int rc = pthread_cond_timedwait(cond, mutex, time);
if (rc == ETIMEDOUT)
*stop = 1;
pthread_mutex_unlock(mutex);
}
void launch_threads(int nb_players, pthread_t threads[],
pthread_attr_t *attr, struct ARGS *args)
{
for (int i = 0; i < nb_players; ++i) {
pthread_create(&threads[i], attr, fetch_player_orders, &args[i]);
}
}
struct thread_data* init_threads_data(int nb_players, struct Player P[])
{
struct thread_data *td = malloc(sizeof(*td));
td->order_queue = nqueue_create();
td->args = malloc(sizeof(*td->args) * nb_players);
td->threads = malloc(sizeof(*td->threads) * nb_players);
td->latecomers = malloc(sizeof(*td->latecomers) * nb_players);
pthread_attr_init(&td->attr);
for (int i = 0; i < nb_players; i++) {
td->args[i].P = &P[i];
td->args[i].stop = &td->stop;
td->args[i].count = &td->count;
td->args[i].nb_players = nb_players;
td->args[i].mutex = &td->mutex;
td->args[i].cond = &td->cond;
td->args[i].order_queue = td->order_queue;
}
return td;
}
void free_threads_data(struct thread_data *td)
{
nqueue_destroy(td->order_queue);
free(td->args);
free(td->threads);
free(td->latecomers);
free(td);
}
void set_timeout(struct timespec *time, long max_turn_time)
{
time->tv_sec = max_turn_time / 1000;
time->tv_nsec = 1000000 * (max_turn_time % 1000);
}
void join_threads(int nb_players, pthread_t *threads, int latecomers[])
{
for (int i = 0; i < nb_players; i++) {
void *res;
pthread_join(threads[i], &res);
latecomers[i] = (int)(long) res;
}
}
void kick_latecomers(int nb_player, struct Player P[], int latecomers[])
{
for (int i = 0; i < nb_player; i++) {
if (latecomers[i]) {
player_destroy(&P[i]);
fprintf(stderr, "Player %u timed out", P[i].id);
}
}
}
void check_orders(struct thread_data *td, struct Map *map)
{
}
void add_fleets(struct thread_data *td, struct Map *map)
{
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock1;
int coins = 10;
struct Node {
int value, guard;
struct Node *left, *center, *right;
};
struct Node *root = 0;
struct Node* newNode(int value) {
struct Node* temp = (struct Node*) malloc(sizeof( struct Node ));
temp->value = value;
temp->guard = 2;
temp->left = temp->center = temp->right = 0;
return temp;
}
void build(struct Node* *node) {
if ((*node)->value - 1 > 0) {
(*node)->left = newNode((*node)->value - 1);
pthread_t worker;
pthread_create(&worker, 0, build, &( (*node)->left ));
pthread_join(worker, 0);
}
if ((*node)->value - 2 > 0) {
(*node)->center = newNode((*node)->value - 2);
build(&( (*node)->center ));
pthread_t worker;
pthread_create(&worker, 0, build, &( (*node)->center ));
pthread_join(worker, 0);
}
if ((*node)->value - 3 > 0) {
(*node)->right = newNode((*node)->value - 3);
build(&( (*node)->right ));
pthread_t worker;
pthread_create(&worker, 0, build, &( (*node)->right ));
pthread_join(worker, 0);
}
}
void fillGuards(struct Node* *node, bool max) {
int guards = 0;
if ((*node)->left) {
if (max) {
fillGuards((&( (*node)->left )), 0);
} else {
fillGuards((&( (*node)->left )), 1);
}
guards += ((*node)->left)->guard;
}
if ((*node)->center) {
if (max) {
fillGuards((&( (*node)->center )), 0);
} else {
fillGuards((&( (*node)->center )), 1);
}
guards += ((*node)->center)->guard;
}
if ((*node)->right) {
if (max) {
fillGuards((&( (*node)->right )), 0);
} else {
fillGuards((&( (*node)->right )), 1);
}
guards += ((*node)->right)->guard;
}
(*node)->guard = guards;
if (!((*node)->left) && !((*node)->center) && !((*node)->right)) {
if (max) {
(*node)->guard = 1;
} else {
(*node)->guard = -1;
}
}
}
int bestMove(bool max) {
int guard1, guard2, guard3 = 0;
if ((root)->left)
guard1 = ((root)->left)->guard;
if ((root)->center)
guard2 = ((root)->center)->guard;
if ((root)->right)
guard3 = ((root)->right)->guard;
if (max) {
if (guard1 > guard2 && guard1 > guard3)
return (root)->value - ((root)->left)->value;
if (guard2 > guard1 && guard2 > guard3)
return (root)->value - ((root)->center)->value;
if (guard3 > guard1 && guard3 > guard2)
return (root)->value - ((root)->right)->value;
if (guard1 == guard2 && guard1 > guard3)
return (root)->value - ((root)->left)->value;
if (guard1 == guard3 && guard1 > guard2)
return (root)->value - ((root)->left)->value;
if (guard2 == guard3 && guard2 > guard1)
return (root)->value - ((root)->center)->value;
} else {
if (guard1 < guard2 && guard1 < guard3)
return (root)->value - ((root)->left)->value;
if (guard2 < guard1 && guard2 < guard3)
return (root)->value - ((root)->center)->value;
if (guard3 < guard1 && guard3 < guard2)
return (root)->value - ((root)->right)->value;
if (guard1 == guard2 && guard1 < guard3)
return (root)->value - ((root)->left)->value;
if (guard1 == guard3 && guard1 < guard2)
return (root)->value - ((root)->left)->value;
if (guard2 == guard3 && guard2 < guard1)
return (root)->value - ((root)->center)->value;
}
}
void *updateRoot() {
pthread_mutex_lock(&lock1);
free(root);
root = newNode(coins);
build(&root);
fillGuards(&root, 1);
pthread_mutex_unlock(&lock1);
pthread_exit(0);
}
int game () {
if(coins == 1) {
printf("Coins on the table: %i\\n", coins);
printf("Thanks for playing!\\n");
exit(0);
}
int move = 0;
printf("Coins on the table: %i\\n", coins);
printf("Remove: ");
scanf("%i", &move);
if (move > 4) {
printf("You can't remove that much!\\n");
game();
}
if (move > 0 && move < 4) {
coins -= move;
if (coins == 1) {
printf("You beat me!\\n");
exit(0);
}
pthread_t worker;
pthread_create(&worker, 0, updateRoot, 0);
pthread_join(worker, 0);
int computerMove = bestMove(0);
printf("Computer removed %i coins\\n", computerMove);
coins -= computerMove;
pthread_t worker2;
pthread_create(&worker2, 0, updateRoot, 0);
pthread_join(worker2, 0);
game();
}
return 0;
}
int main(void) {
root = newNode(coins);
printf("Welcome to NIM. The game starts with imaginary 5 coins on the table.\\n");
printf("You can type 1, 2 or 3 for removing the coins. Your main objective is\\n");
printf("to leave the computer with just one coin. Can you? Let's play!\\n");
game();
return 0;
}
| 1
|
#include <pthread.h>
int gnum = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void * print(void * arg)
{
pthread_mutex_lock(&mutex);
while (gnum < 5)
{
pthread_cond_wait(&cond, &mutex);
}
printf("gnum is ready: %d\\n", gnum);
pthread_mutex_unlock(&mutex);
return ((void *)0);
}
void * add(void * arg)
{
int i = 0;
for (i=0;i<10;i++)
{
sleep(1);
pthread_mutex_lock(&mutex);
gnum ++;
printf ("%d\\n", gnum);
if (gnum == 5)
{
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
}
return((void *)0);
}
int main()
{
pthread_t pt_1, pt_2;
int ret = 0;
ret = pthread_create (&pt_1, 0, print, 0);
if (ret != 0)
{
perror("pthread 1 create error");
}
ret = pthread_create (&pt_2, 0, add, 0);
if (ret != 0)
{
perror("pthread 2 create error");
}
pthread_join(pt_1, 0);
pthread_join(pt_2, 0);
printf("Main thread exits !\\n");
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
struct node
{
int n_number;
struct node*n_next;
}*head=0;
static void cleanup_handler(void*arg)
{
printf("Cleanuphandlerofsecondthread.\\n");
free(arg);
(void)pthread_mutex_unlock(&mtx);
}
static void*thread_func(void*arg)
{
struct node*p=0;
pthread_cleanup_push(cleanup_handler,p);
while(1)
{
pthread_mutex_lock(&mtx);
while(1)
{
while(head==0)
{
pthread_cond_wait(&cond,&mtx);
}
p=head;
head=head->n_next;
printf("Got %d fromfrontofqueue\\n",p->n_number);
free(p);
}
pthread_mutex_unlock(&mtx);
}
pthread_cleanup_pop(0);
return 0;
}
int main(void)
{
pthread_t tid;
int i;
struct node*p;
pthread_create(&tid, 0, thread_func,0);
for(i=0;i<10;i++)
{
p=(struct node*)malloc(sizeof(struct node));
p->n_number=i;
pthread_mutex_lock(&mtx);
p->n_next=head;
head=p;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mtx);
sleep(1);
}
printf("thread1wannaendthecancelthread2.\\n");
pthread_cancel(tid);
pthread_join(tid,0);
printf("Alldone--exiting\\n");
return 0;
}
| 1
|
#include <pthread.h>
int init_pc_buffer(struct in_packet_buffer ** b) {
(*b) = (struct in_packet_buffer*) malloc(sizeof (struct in_packet_buffer));
if(*b == 0) {
fprintf(stderr, "Problem to allouate buffer memory\\n");
return 1;
}
(*b)->buffer = (struct wrapper* ) malloc(9999*sizeof(struct wrapper));
if((*b)->buffer == 0) {
fprintf(stderr, "Problem to allouate buffer memory\\n");
free(*b);
*b = 0;
return 1;
}
if(pthread_mutex_init( &(*b)->mutex, 0)) {
perror("Mutex init");
free((*b)->buffer);
(*b)->buffer = 0;
free(*b);
*b = 0;
return 1;
}
if(sem_init(&(*b)->empty, 0, 9999 -1)) {
perror("Sem init");
free((*b)->buffer);
(*b)->buffer = 0;
pthread_mutex_destroy(&(*b)->mutex);
free(*b);
*b = 0;
return 1;
}
if(sem_init(&(*b)->full, 0, 0 )) {
perror("Sem init");
free((*b)->buffer);
(*b)->buffer = 0;
pthread_mutex_destroy(&(*b)->mutex);
sem_destroy(&(*b)->empty);
free(*b);
*b = 0;
return 1;
}
(*b)->readpos = 0;
(*b)->writepos = 0;
(*b)->in = 0;
return 0;
}
int notEmpty(struct in_packet_buffer * b) {
return b->in != 0;
}
void free_pc_buffer(struct in_packet_buffer * b) {
if(b != 0) {
if(b->buffer != 0) {
free(b->buffer);
b->buffer = 0;
}
if( sem_destroy(&b->empty))
perror("Sem destroy");
if( sem_destroy(&b->full))
perror("Sem destroy");
if(pthread_mutex_destroy(&(b->mutex)))
perror("Mutex destroy");
free(b);
b=0;
}
}
void advance_wr_pos(struct in_packet_buffer *b) {
b->writepos++;
if (b->writepos >= 9999)
b->writepos = 0;
b->in++;
}
void advance_rd_pos(struct in_packet_buffer *b) {
b->readpos++;
if (b->readpos >= 9999)
b->readpos = 0;
b->in--;
}
void producer_pc_wait(struct in_packet_buffer *b) {
sem_wait(&(b->empty));
pthread_mutex_lock(&(b->mutex));
}
void producer_pc_post(struct in_packet_buffer *b) {
pthread_mutex_unlock(&(b->mutex));
sem_post(&(b->full));
}
void consumer_pc_wait(struct in_packet_buffer *b) {
sem_wait(&(b->full));
pthread_mutex_lock(&(b->mutex));
}
void consumer_pc_post(struct in_packet_buffer *b) {
pthread_mutex_unlock(&(b->mutex));
sem_post(&(b->empty));
}
void push_ps_finish(struct in_packet_buffer *b) {
sem_post(&b->full);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
void *mouseListener();
void *tableRotator();
void makeStep(char *ws);
int mouseStateFlag=0;
int ret1, ret2;
int main() {
pthread_t mouseThread, tableThread;
int mouseThreadError, tableThreadError;
int *ptr[2];
if ( !bcm2835_init() ) {
return 1;
}
mouseThreadError = pthread_create(&mouseThread, 0, mouseListener, 0);
if( mouseThreadError ) {
printf("Error - pthread_create() return code: %d\\n", mouseThreadError);
exit(1);
} else {
printf("MouseThread created\\n");
}
tableThreadError = pthread_create(&tableThread, 0, tableRotator, 0);
if( tableThreadError ) {
printf("Error - pthread_create() return code: %d\\n", tableThreadError);
exit(1);
} else {
printf("TableThread created\\n");
}
pthread_join( mouseThread, (void**)&(ptr[0]));
pthread_join( tableThread, (void**)&(ptr[1]));
bcm2835_close();
return 0;
}
void *mouseListener() {
int fd;
struct input_event ie;
if((fd = open("/dev/input/event0", O_RDONLY)) == -1) {
perror("opening device");
exit(1);
}
while(read(fd, &ie, sizeof(struct input_event))) {
printf("time %ld.%06ld\\ttype %d\\tcode %d\\tvalue %d\\n",
ie.time.tv_sec, ie.time.tv_usec, ie.type, ie.code, ie.value);
if ( ie.code == 272 || ie.code == 273 ) {
printf("type %d\\tcode %d\\tvalue %d\\n", ie.type, ie.code, ie.value);
pthread_mutex_lock(&mutex1);
mouseStateFlag = ie.type;
pthread_mutex_unlock(&mutex1);
pthread_mutex_lock(&mutex1);
mouseStateFlag = ie.code;
printf("We catch mouse %d\\n", mouseStateFlag);
pthread_mutex_unlock(&mutex1);
} else if (ie.code == 274) {
ret1 = 0;
pthread_exit(&ret1);
}
}
return 0;
}
void *tableRotator() {
int i;
char* steps4[4];
char *blankString = "0 0 0 0";
steps4[0] = "1 0 0 1";
steps4[1] = "0 1 0 1";
steps4[2] = "0 1 1 0";
steps4[3] = "1 0 1 0";
bcm2835_gpio_fsel(RPI_V2_GPIO_P1_12, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_fsel(RPI_V2_GPIO_P1_16, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_fsel(RPI_V2_GPIO_P1_18, BCM2835_GPIO_FSEL_OUTP);
bcm2835_gpio_fsel(RPI_V2_GPIO_P1_22, BCM2835_GPIO_FSEL_OUTP);
while ( mouseStateFlag != 274 ) {
if (mouseStateFlag == 272 || mouseStateFlag == 273 ) {
makeStep(blankString);
for (int i = 0; i < 4; i++ ) {
makeStep(steps4[i]);
}
makeStep(blankString);
}
pthread_mutex_lock(&mutex1);
mouseStateFlag = 0;
pthread_mutex_unlock(&mutex1);
}
ret2 = 0;
pthread_exit(&ret2);
}
void makeStep(char *ws) {
int a[4];
for ( int i = 0; i < 4 && *ws != '\\0'; ) {
if ( *ws != ' ' ) {
a[i] = *ws - '0';
i++;
ws++;
} else {
ws++;
}
}
bcm2835_gpio_write(RPI_V2_GPIO_P1_12, a[0]);
bcm2835_gpio_write(RPI_V2_GPIO_P1_16, a[1]);
bcm2835_gpio_write(RPI_V2_GPIO_P1_18, a[2]);
bcm2835_gpio_write(RPI_V2_GPIO_P1_22, a[3]);
bcm2835_delay(50);
}
| 1
|
#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);
}
| 0
|
#include <pthread.h>
int thread_count;
int barrier_thread_count = 0;
pthread_mutex_t barrier_mutex;
pthread_cond_t ok_to_proceed;
void Usage(char* prog_name);
void *Thread_work(void* rank);
int main(int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
double start, finish;
if (argc != 2) Usage(argv[0]);
thread_count = strtol(argv[1], 0, 10);
thread_handles = malloc (thread_count*sizeof(pthread_t));
pthread_mutex_init(&barrier_mutex, 0);
pthread_cond_init(&ok_to_proceed, 0);
GET_TIME(start);
for (thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread], (pthread_attr_t*) 0,
Thread_work, (void*) thread);
for (thread = 0; thread < thread_count; thread++)
pthread_join(thread_handles[thread], 0);
GET_TIME(finish);
printf("Elapsed time = %e seconds\\n", finish - start);
pthread_mutex_destroy(&barrier_mutex);
pthread_cond_destroy(&ok_to_proceed);
free(thread_handles);
return 0;
}
void Usage(char* prog_name) {
fprintf(stderr, "usage: %s <number of threads>\\n", prog_name);
exit(0);
}
void *Thread_work(void* rank) {
long my_rank = (long) rank;
int i;
for (i = 0; i < 10; i++) {
pthread_mutex_lock(&barrier_mutex);
barrier_thread_count++;
printf("At iteration %d, thread %ld arrives\\n", i, my_rank);
if (barrier_thread_count == thread_count) {
barrier_thread_count = 0;
pthread_cond_broadcast(&ok_to_proceed);
} else {
while (pthread_cond_wait(&ok_to_proceed,
&barrier_mutex) != 0);
}
pthread_mutex_unlock(&barrier_mutex);
}
return 0;
}
| 1
|
#include <pthread.h>
int * a;
pthread_mutex_t * mutexs;
pthread_t * threads;
pthread_barrier_t * barrera;
void * hebra(void * input) {
int tid = input;
int myVal;
int ptid = (tid == 0) ? 40 -1 : tid-1;
int minTid = (tid == 0) ? tid : ptid
,maxTid = (tid == 0) ? ptid : tid;
myVal = a[tid];
pthread_barrier_wait(barrera);
while(1) {
pthread_mutex_lock(&mutexs[minTid]);
pthread_mutex_lock(&mutexs[maxTid]);
if(a[ptid] > myVal) {
a[tid] = a[ptid];
} else if(a[ptid] == myVal) {
printf("El mayor es %d\\n", myVal);
exit(0);
}
pthread_mutex_unlock(&mutexs[maxTid]);
pthread_mutex_unlock(&mutexs[minTid]);
}
printf("Hebra %d launched a[%d] = %d\\n", tid, tid, a[tid]);
}
int main(int argc, char * argv[]) {
srand(time(0));
int i;
a = (int *) malloc(sizeof(int) * 40);
threads = (pthread_t *) malloc(sizeof(pthread_t) * 40);
mutexs = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t) * 40);
barrera = (pthread_barrier_t *) malloc(sizeof(pthread_barrier_t));
pthread_barrier_init(barrera, 0, 40);
for(i = 0; i < 40; i++) {
a[i] = i+1;
pthread_mutex_init(&mutexs[i], 0);
}
for(i = 0; i < 40; i++) {
pthread_create(&threads[i], 0, hebra, i);
}
for(i = 0; i < 40; i++)
pthread_join(threads[i], 0);
printf("Programa terminado!\\n");
return 0;
}
| 0
|
#include <pthread.h>
int p1=0;
int p2=0;
int n=0;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
pthread_mutex_t mVar=PTHREAD_MUTEX_INITIALIZER;
void *referee(void *arg);
void *player1(void *arg);
void *player2(void *arg);
int vcheck();
int dcheck();
void mprint();
int test=0;
int game_finish=0;
int a[6][7];
int main()
{
int i,j;
printf("Player 1-RED");
printf("Player 2-YELLOW");
for(i=0;i<6;i++)
{
for(j=0;j<7;j++)
{
a[i][j] = 0;
}
}
printf("Player 1-RED\\n");
printf("Player 2-YELLOW\\n");
mprint();
pthread_t rtid,p1tid,p2tid;
pthread_create(&p2tid,0,player2,0);
pthread_create(&p1tid,0,player1,0);
pthread_create(&rtid,0,referee,0);
pthread_join(p2tid,0);
pthread_join(p1tid,0);
pthread_join(rtid,0);
return 0;
}
void *referee(void *arg)
{
int tie = 1;
int i,j;
for(;;)
{
pthread_mutex_lock(&mVar);
while(test==1)
{
pthread_cond_wait(&cond,&mVar);
}
test=1;
vcheck();
dcheck();
if(p1==1)
{
game_finish = 1;
printf("\\n PLAYER 1-RED WON \\n");
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mVar);
return 0;
}
if(p2==1)
{
game_finish = 1;
printf("\\n PLAYER 2-YELLOW WON\\n");
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mVar);
return 0;
}
if ( tcheck() == 0)
{
printf("\\n There is tie\\n");
game_finish = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mVar);
return 0;
}
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mVar);
}
}
int tcheck()
{
int i,j;
for(i=0;i<6;i++)
{
for(j=0;j<7;j++)
{
if(a[i][j]==0)
{
return(1);
}
}
}
return(0);
}
int vcheck()
{
int i,j;
for(i=0;i<6;i++)
{
for(j=0;j<7;j++)
{
if(a[i][j]==a[i+1][j] && a[i][j]==a[i+2][j] && a[i][j]==a[i+3][j] && a[i][j]==1 && (i+1)<6 && (i+2)<6 && (i+3)<6)
{
p1=1;
return 0;
}
if(a[i][j]==a[i+1][j] && a[i][j]==a[i+2][j] && a[i][j]==a[i+3][j] && a[i][j]==2 && (i+1)<6 && (i+2)<6 && (i+3)<6)
{
p2=1;
return 0;
}
}
}
return(1);
}
int dcheck()
{
int i,j;
for(i=0;i<6;i++)
{
for(j=0;j<7;j++)
{
if(a[i][j]==a[i+1][j+1] && a[i][j]==a[i+2][j+2] && a[i][j]==a[i+3][j+3] && a[i][j]==1 && (i+1)<6 && (i+2)<6 && (i+3)<6 && (j+1)<7 && (j+2)<7 && (j+3)<7)
{
p1=1;
return 0;
}
if(a[i][j]==a[i+1][j-1] && a[i][j]==a[i+2][j-2] && a[i][j]==a[i+3][j-3] && a[i][j]==1 && (i+1)<6 && (i+2)<6 && (i+3)<6 && (j-1)>-1 && (j-2)>-1 && (j-3)>-1)
{
p1=1;
return 0;
}
if(a[i][j]==a[i+1][j+1] && a[i][j]==a[i+2][j+2] && a[i][j]==a[i+3][j+3] && a[i][j]==2 && (i+1)<6 && (i+2)<6 && (i+3)<6 && (j+1)<7 && (j+2)<7 && (j+3)<7)
{
p2=2;
return 0;
}
if(a[i][j]==a[i+1][j-1] && a[i][j]==a[i+2][j-2] && a[i][j]==a[i+3][j-3] && a[i][j]==2 && (i+1)<6 && (i+2)<6 && (i+3)<6 && (j-1)>-1 && (j-2)>-1 && (j-3)>-1)
{
p2=2;
return 0;
}
}
}
return(1);
}
void *player1(void *arg)
{
int row_cal,i,j;
for(;;)
{
pthread_mutex_lock(&mVar);
while(test==0)
pthread_cond_wait(&cond,&mVar);
if(game_finish==1)
{
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mVar);
return 0;
}
row_cal=-1;
srand(time(0));
while(row_cal==-1)
{
sleep(1);
j=rand()%7;
printf("Player1-RED is playing\\n");
printf("Coloumn selected:%d\\n\\n",j+1);
for(i=5;i>-1;i--)
{
if(a[i][j]==0)
{
row_cal=i;
break;
}
}
}
a[row_cal][j]=1;
mprint();
test=0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mVar);
}
return 0;
}
void *player2(void *arg)
{
int row_cal,i,j;
for(;;)
{
pthread_mutex_lock(&mVar);
while(test==0)
{
pthread_cond_wait(&cond,&mVar);
}
if(game_finish==1)
{
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mVar);
return 0;
}
row_cal=-1;
srand(time(0));
while(row_cal==-1)
{
sleep(1);
j=rand()%7;
printf("Player2-YELLOW is playing\\n");
printf("Coloumn Selected:%d\\n\\n",j+1);
for(i=5;i>-1;i--)
{
if(a[i][j]==0)
{
row_cal=i;
break;
}
}
}
a[row_cal][j]=2;
mprint();
test=0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mVar);
}
return 0;
}
void mprint()
{
int i,j;
printf("\\n");
for(i=0;i<6;i++)
{
for(j=0;j<7;j++)
{
printf("%d ",a[i][j]);
}
printf("\\n");
}
}
| 1
|
#include <pthread.h>
struct foo *queue[(29)];
static pthread_mutex_t global_lock = PTHREAD_MUTEX_INITIALIZER;
struct foo
{
int f_count;
void *f_data;
pthread_mutex_t f_lock;
struct foo *f_next;
};
static int resource_queue_init(int id)
{
int index = ((id) % (29));
struct foo *foo = malloc(sizeof(*foo));
assert(foo);
foo->f_count = 1;
foo->f_data = 0;
pthread_mutex_init(&foo->f_lock, 0);
foo->f_next = 0;
pthread_mutex_lock(&global_lock);
foo->f_next = queue[index];
queue[index] = foo;
pthread_mutex_lock(&foo->f_lock);
pthread_mutex_unlock(&global_lock);
foo->f_data = malloc(1024);
pthread_mutex_unlock(&foo->f_lock);
return 0;
}
static int resource_addcount(struct foo *foo)
{
int retcode = 1;
pthread_mutex_lock(&foo->f_lock);
if (foo->f_count != 0)
{
foo->f_count += 1;
retcode = 0;
}
pthread_mutex_unlock(&foo->f_lock);
return retcode;
}
static int resource_subcount(struct foo *foo)
{
struct foo *tmp = 0;
pthread_mutex_lock(&foo->f_lock);
if (--foo->count == 0)
{
pthread_mutex_unlock(&foo->f_lock);
pthread_mutex_lock(&global_lock);
pthread_mutex_lock(&foo->f_lock);
if (foo->count != 0)
{
pthread_mutex_unlock(&foo->f_lock);
pthread_mutex_unlock(&global_lock);
}
for (tmp = queue[0]; tmp != 0; tmp = tmp->f_next)
{
}
pthread_mutex_unlock(&foo->f_lock);
pthread_mutex_unlock(&global_lock);
}
else
{
pthread_mutex_unlock(&foo->f_lock);
}
return 0;
}
int main(int argc, char *argv[])
{
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t chopstick[5];
void *philosophy(void *arg);
void pickup(int me);
void drop(int me);
int main(int argc, const char *argv[])
{
pthread_t tid[5];
int i, p[5];
srand(time(0));
for (i = 0; i < 5; i++)
{
pthread_mutex_init(&chopstick[i], 0);
}
for (i = 0; i < 5; i++)
{
p[i] = i;
}
for (i = 0; i < 5 -1; i++)
{
pthread_create(&tid[i], 0, philosophy, (void *)p[i]);
}
philosophy((void *)(5 -1));
for (i = 0; i < 5 -1; i++)
{
pthread_join(tid[i], 0);
}
for (i = 0; i < 5 - 1; i++)
{
pthread_mutex_destroy(&chopstick[i]);
}
return 0;
}
void pickup(int me)
{
if (me % 5 == 0)
{
pthread_mutex_lock(&chopstick[(((me) + 1) % 5)]);
pthread_mutex_lock(&chopstick[(me)]);
}
else
{
pthread_mutex_lock(&chopstick[(me)]);
pthread_mutex_lock(&chopstick[(((me) + 1) % 5)]);
}
}
void drop(int me)
{
pthread_mutex_unlock(&chopstick[(me)]);
pthread_mutex_unlock(&chopstick[(((me) + 1) % 5)]);
}
void *philosophy(void *arg)
{
int me = (int)arg;
while (1)
{
printf("%d is thinking....\\n", me);
usleep(rand() % 10);
pickup(me);
printf("%d is eating....\\n", me);
usleep(rand() % 10);
drop(me);
}
}
| 1
|
#include <pthread.h>
int asc_code;
int ocorrencias;
}Caracter;
long buffleng;
int nthreads;
char *buffer;
Caracter *lista_asc;
pthread_mutex_t mutex;
int hashCode(int key) {
return ( key + 61) % 94;
}
int search(int key) {
int hashIndex = hashCode(key);
if(key == lista_asc[hashIndex].asc_code ){
lista_asc[hashIndex].ocorrencias++;
return 1;
}
else
return 0;
}
Caracter* preenche_asc(){
int i;
Caracter *vetor = (Caracter*) malloc(94*sizeof(Caracter));
for(i = 0; i < 94; i++){
vetor[i].asc_code = i + 33;
vetor[i].ocorrencias = 0;
}
return vetor;
}
char* gera_buffer(FILE* arq_entrada ){
fseek(arq_entrada, 0 , 2);
buffleng = ftell(arq_entrada);
rewind(arq_entrada);
char *buffer = (char*) malloc((buffleng )*sizeof(char));
return buffer;
}
void* conta_caracteres(void* id){
long posicao = 0, comeco, fim, bloco = buffleng/nthreads; int tid = *(int*) id;
comeco = tid*bloco;
if(tid < nthreads - 1)
fim = comeco + bloco;
else
fim = buffleng;
pthread_mutex_lock(&mutex);
for(posicao = comeco; posicao < fim; posicao++)
search(buffer[posicao]);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void escreve_saida(FILE* arq_saida){
int i;
fprintf(arq_saida, "Simbolo | Ocorrencias\\n");
for( i = 0; i < 94;i++){
if(lista_asc[i].ocorrencias != 0)
fprintf(arq_saida, " %c, %d\\n", lista_asc[i].asc_code, lista_asc[i].ocorrencias);
}
fclose(arq_saida);
}
int main(int argc, char* argv[]){
if(argc < 4 ){
printf("passe %s <arquivo de texto a ser lido> <nome do arquivo de saida> <número de threads>\\n",argv[0]);
exit(1);
}
FILE* arq_entrada = fopen(argv[1], "rb");
FILE* arq_saida = fopen( argv[2], "w");
buffer = gera_buffer(arq_entrada);
lista_asc = preenche_asc();
printf("CARREGANDO BUFFER...\\n");
fread(buffer, buffleng, 1, arq_entrada);
printf("CONTANDO CARACTERES DO TEXTO...\\n");
nthreads = atoi(argv[3]);
pthread_t thread[nthreads];
int t; double inicio, fim , tempo;
int *tid;
pthread_mutex_init(&mutex, 0);
GET_TIME(inicio);
for( t=0; t<nthreads; t++){
printf("for cri thread nthreads: %d\\n", nthreads);
tid = (int*) malloc(sizeof(int));if(tid==0) { printf("--ERRO: malloc()\\n"); exit(-1); }
*tid = t;
pthread_create(&thread[t], 0, conta_caracteres,(void*) tid);
}
for (t = 0; t < nthreads; t++)
pthread_join(thread[t], 0);
GET_TIME(fim);
tempo = fim - inicio;
fclose(arq_entrada);
escreve_saida(arq_saida);
printf("TEMPO EM MINUTOS COM %d threads: %.8f minutos.\\n", nthreads,tempo/60);
pthread_mutex_destroy(&mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
const int beatup_iterations = 10000;
const int num_threads = 30;
const int max_keys = 500;
struct key_list {
struct key_list *next;
pthread_key_t key;
};
struct key_list *key_list;
pthread_mutex_t key_lock = PTHREAD_MUTEX_INITIALIZER;
static void
beat_up(void)
{
struct key_list *new = malloc(sizeof *new);
struct key_list **iter, *old_key = 0;
int key_count = 0;
if (new == 0) {
fprintf(stderr, "malloc failed\\n");
abort();
}
new->next = 0;
if (pthread_key_create(&new->key, 0) != 0) {
fprintf(stderr, "pthread_key_create failed\\n");
abort();
}
if (pthread_getspecific(new->key) != 0) {
fprintf(stderr, "new pthread_key_t resolves to non-null value\\n");
abort();
}
pthread_setspecific(new->key, (void *) 1);
pthread_mutex_lock(&key_lock);
for (iter = &key_list; *iter != 0; iter = &(*iter)->next)
key_count++;
*iter = new;
if (key_count > max_keys) {
old_key = key_list;
key_list = key_list->next;
}
pthread_mutex_unlock(&key_lock);
if (old_key != 0) {
pthread_key_delete(old_key->key);
}
}
static void *
thread(void *arg)
{
int i;
for (i = 0; i < beatup_iterations; i++)
beat_up();
return 0;
}
int
main(void)
{
int i;
pthread_attr_t detached_thread;
pthread_attr_init(&detached_thread);
pthread_attr_setdetachstate(&detached_thread, PTHREAD_CREATE_DETACHED);
for (i = 0; i < num_threads; i++) {
pthread_t thread_id;
while (pthread_create(&thread_id, &detached_thread, thread, 0) == EAGAIN) {
sleep(1);
}
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int value;
pthread_cond_t rc, wc;
pthread_mutex_t rm, wm;
int r_wait, w_wait;
}Storage;
void setValue(Storage *s, int value) {
s->value = value;
}
int getValue(Storage *s) {
return s->value;
}
void *set_th(void *arg) {
Storage *s = (Storage *)arg;
for (int i = 1; i < 100; i++) {
setValue(s, i + 100);
printf("0x%lx write data: %d\\n", pthread_self(), i);
pthread_mutex_lock(&s->rm);
while (!s->r_wait) {
pthread_mutex_unlock(&s->rm);
sleep(1);
pthread_mutex_lock(&s->rm);
}
s->r_wait = 0;
pthread_mutex_unlock(&s->rm);
pthread_cond_broadcast(&s->rc);
pthread_mutex_lock(&s->wm);
s->w_wait = 1;
pthread_cond_wait(&s->wc, &s->wm);
pthread_mutex_unlock(&s->wm);
}
return (void *)0;
}
void *get_th(void *arg) {
Storage *s = (Storage *)arg;
for (int i = 1; i < 100; i++) {
pthread_mutex_lock(&s->rm);
s->r_wait = 1;
pthread_cond_wait(&s->rc, &s->rm);
pthread_mutex_unlock(&s->rm);
int value = getValue(s);
printf("0x%lx(%-5d) read data:%d\\n", pthread_self(), i, value);
pthread_mutex_lock(&s->wm);
while (!s->w_wait) {
pthread_mutex_unlock(&s->wm);
sleep(1);
pthread_mutex_lock(&s->wm);
}
s->w_wait = 0;
pthread_mutex_unlock(&s->wm);
pthread_cond_broadcast(&s->wc);
}
return (void *)0;
}
int main () {
int err;
pthread_t rth, wth;
Storage s;
s.r_wait = 0;
s.w_wait = 0;
pthread_mutex_init(&s.rm, 0);
pthread_mutex_init(&s.wm, 0);
pthread_cond_init(&s.rc, 0);
pthread_cond_init(&s.wc, 0);
if ((err = pthread_create(&rth, 0, get_th, (void *)&s)) != 0) {
perror("thread create error!");
}
if ((err = pthread_create(&wth, 0, set_th, (void *)&s)) != 0) {
perror("thread create error!");
}
pthread_join(rth, 0);
pthread_join(wth, 0);
pthread_mutex_destroy(&s.rm);
pthread_mutex_destroy(&s.wm);
pthread_cond_destroy(&s.rc);
pthread_cond_destroy(&s.wc);
return 0;
}
| 0
|
#include <pthread.h>
char** argtab;
int next_file = 1;
int nbfiles;
pthread_mutex_t next_file_mutex = PTHREAD_MUTEX_INITIALIZER;
void convert_file(char* file_name)
{
FILE *fp1, *fp2;
int c = 1;
fp1= fopen (file_name, "r");
fp2= fopen (file_name, "r+");
if ((fp1== 0) || (fp2== 0)) {
perror ("fopen");
exit (1);
}
while (c != EOF) {
c=fgetc(fp1);
if (c!=EOF)
fputc(toupper(c),fp2);
}
fclose (fp1);
fclose (fp2);
}
void *thread_convert(void* arg)
{
char *file;
while(1){
pthread_mutex_lock(&next_file_mutex);
if ( next_file > nbfiles ){
pthread_mutex_unlock(&next_file_mutex);
break;
}
file = (char *)(argtab[next_file]);
next_file++;
pthread_mutex_unlock(&next_file_mutex);
convert_file(file);
}
return 0;
}
int main (int argc, char** argv)
{
argtab = argv;
nbfiles = argc-1;
pthread_t tid[2];
int i=-1;
while ( ++i < 2 ){
if ( pthread_create(&tid[i], 0, thread_convert, (void *)&argv) ){
perror("error : pthread_create\\n");
exit(1);
}
}
i = -1;
while ( ++i < 2 ){
if ( pthread_join(tid[i], 0) ){
perror("error : pthread_join\\n");
exit(1);
}
}
return 0;
}
| 1
|
#include <pthread.h>
int whoseTurn(){
int turn;
if ((tobacco == 0) && (matches == 0) && (paper == 0)){
turn = 0;
}
if ((tobacco == 0) && (matches == 1) && (paper == 1)){
turn = 1;
}
if ((tobacco == 1) && (matches == 0) && (paper == 1)){
turn = 2;
}
if ((tobacco == 1) && (matches == 1) && (paper == 0)){
turn = 3;
}
return turn;
}
void canThreadContinue(int id){
int turn;
pthread_mutex_lock(&TABLE);
turn = whoseTurn();
while( turn != id){
switch(id){
case 1:
printf("smoker %d (that is tobacco) darn, the goods on the table are not for me, i have to wait\\n",id);
break;
case 2:
printf("smoker %d (that is matches) darn, the goods on the table are not for me, i have to wait\\n",id);
break;
case 3:
printf("smoker %d (that is paper) darn, the goods on the table are not for me, i have to wait\\n",id);
break;
}
pthread_cond_wait(&self, &TABLE);
turn = whoseTurn();
}
pthread_mutex_unlock(&TABLE);
return;
}
void smoker(int * id){
while(1){
sleep(1);
canThreadContinue(*id);
switch(*id){
case 1:
printf("smoker %d (that is tobacco) Yippe it is for me, time to smoke\\n",*id);
break;
case 2:
printf("smoker %d (that is matches) Yippe it is for me, time to smoke\\n",*id);
break;
case 3:
printf("smoker %d (that is paper) Yippe it is for me, time to smoke\\n",*id);
break;
}
tobacco = 0; matches = 0; paper= 0;
pthread_cond_broadcast(&self);
sleep(1);
}
}
void agent(int * times){
int rn,x=0;
while(x < *times){
canThreadContinue(0);
rn=rand()%3 + 1;
switch (rn){
case 1:
printf("agent placed matches and paper on table\\n");
tobacco = 0; matches = 1; paper= 1;
break;
case 2:
printf("agent placed tobacco and paper on table\\n");
tobacco = 1; matches = 0; paper= 1;
break;
case 3:
printf("agent placed matches and tobacco on table\\n");
tobacco = 1; matches = 1; paper= 0;
break;
}
sleep(1);
pthread_cond_broadcast(&self);
x++;
}
printf("agent done\\n");
pthread_exit(0);
}
| 0
|
#include <pthread.h>
struct node_struct* next;
char* data;
pthread_mutex_t mtx;
} node;
pthread_mutex_t head_mtx;
node* head;
node* push_front(node* p, char* buf) {
int len = strlen (buf);
node* q = (node*) malloc (sizeof (node));
pthread_mutex_init (&(q -> mtx), 0);
q -> data = (char*) malloc (len);
strncpy (q->data,buf,len);
q -> data [len] = 0;
pthread_mutex_lock(&head_mtx);
q -> next = p;
head = q;
pthread_mutex_unlock(&head_mtx);
}
void destroy (node* p) {
node* q;
while (p) {
q = p;
p = p -> next;
pthread_mutex_destroy(&q -> mtx);
free (q->data);
free (q);
}
}
void print_all (node* p) {
fprintf (stderr, "Curr elements:\\n");
while (p) {
pthread_mutex_lock(&(p -> mtx));
printf ("- %s\\n", p->data);
node* q = p;
p = p -> next;
pthread_mutex_unlock(&(q -> mtx));
}
}
void sort (node* p) {
node* i;
node* j;
char* tmp_str;
for (i = p; i; i = i -> next)
for (j = i -> next; j; j = j -> next)
if( strcmp(i->data,j->data) > 0) {
pthread_mutex_lock(&(i -> mtx));
pthread_mutex_lock(&(j -> mtx));
tmp_str = i -> data;
i -> data = j -> data;
j -> data = tmp_str;
pthread_mutex_unlock(&(i -> mtx));
pthread_mutex_unlock(&(j -> mtx));
sleep(1);
}
}
void* sorter (void* ptr) {
while (1) {
sleep (5);
sort (head);
}
}
int main () {
int input_size;
char buf [80];
pthread_t thread;
pthread_mutex_init(&head_mtx, 0);
pthread_create (&thread, 0, sorter, 0);
while ((input_size = read (0, buf, 80)) > 0) {
buf [input_size - 1] = 0;
if (input_size == 1)
print_all (head);
else
push_front (head, buf);
}
pthread_cancel(thread);
pthread_join(thread, 0);
pthread_mutex_destroy (&head_mtx);
destroy (head);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
int g_key = 0x3333;
void TestFunc(int loopnum)
{
printf("loopnum:%d\\n", loopnum);
int ncount = 0;
int ret = 0;
int shmhdl = 0;
int *addr = 0;
int semid = 0;
sem_open(g_key, &semid);
sem_p(semid);
ret = IPC_CreatShm(".", 0, &shmhdl);
ret =IPC_MapShm(shmhdl, (void **)&addr);
*((int *)addr) = *((int *)addr) + 1;
ncount = *((int *)addr);
printf("ncount:%d\\n", ncount);
ret =IPC_UnMapShm(addr);
sem_v(semid);
printf("进程正常退出:%d\\n", getpid());
}
void TestFunc_threadMutex(int loopnum)
{
printf("loopnum:%d\\n", loopnum);
int ncount = 0;
int ret = 0;
int shmhdl = 0;
int *addr = 0;
int semid = 0;
sem_open(g_key, &semid);
pthread_mutex_lock(&mymutex);
ret = IPC_CreatShm(".", 0, &shmhdl);
ret =IPC_MapShm(shmhdl, (void **)&addr);
*((int *)addr) = *((int *)addr) + 1;
ncount = *((int *)addr);
printf("ncount:%d\\n", ncount);
ret =IPC_UnMapShm(addr);
pthread_mutex_unlock(&mymutex);
printf("进程正常退出:%d\\n", getpid());
}
void *thread_routine(void* arg)
{
printf("thread_routine start\\n");
TestFunc_threadMutex(1);
pthread_exit(0);
}
int main(void )
{
int res;
int procnum=10;
int loopnum = 100;
pthread_t tidArray[1024*10];
int i=0,j = 0;
printf("请输入要创建子进程的个数 : \\n");
scanf("%d", &procnum);
printf("请输入让每个子进程测试多少次 :\\n");
scanf("%d", &loopnum);
int ret = 0;
int shmhdl = 0;
ret = IPC_CreatShm(".", sizeof(int), &shmhdl);
if (ret != 0)
{
printf("func IPC_CreatShm() err:%d \\n", ret);
return ret;
}
int semid = 0;
ret = sem_creat(g_key, &semid);
if (ret != 0)
{
printf("func sem_creat() err:%d,重新按照open打开信号量 \\n", ret);
if (ret == SEMERR_EEXIST)
{
ret = sem_open(g_key, &semid);
if (ret != 0)
{
printf("按照打开的方式,重新获取sem失败:%d \\n", ret);
return ret;
}
}
else
{
return ret;
}
}
int val = 0;
ret = sem_getval(semid, &val);
if (ret != 0 )
{
printf("func sem_getval() err:%d \\n", ret);
return ret;
}
printf("sem val:%d\\n", val);
getchar();
for (i=0; i<procnum; i++)
{
pthread_create(&tidArray[i], 0, thread_routine, 0);
}
for (i=0; i<procnum; i++)
{
pthread_join(tidArray[i], 0);
}
printf("父进程退出 hello...\\n");
return 0;
}
| 0
|
#include <pthread.h>
int make_listen(int port);
void handle_connection(FILE* fin, FILE* fout);
int remove_trailing_whitespace(char* buf);
static pthread_mutex_t mutex;
static pthread_cond_t condvar;
static int n_connection_threads;
void* connection_thread(void* arg) {
FILE* f = (FILE*) arg;
pthread_mutex_lock(&mutex);
++n_connection_threads;
pthread_mutex_unlock(&mutex);
pthread_detach(pthread_self());
handle_connection(f, f);
fclose(f);
pthread_mutex_lock(&mutex);
--n_connection_threads;
pthread_cond_signal(&condvar);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main(int argc, char** argv) {
int port = 6168;
if (argc >= 2) {
port = strtol(argv[1], 0, 0);
assert(port > 0 && port <= 65535);
}
int fd = make_listen(port);
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&condvar, 0);
while (1) {
int cfd = accept(fd, 0, 0);
if (cfd < 0) {
perror("accept");
exit(1);
}
while (n_connection_threads > 100) {
pthread_mutex_lock(&mutex);
if (n_connection_threads > 100)
pthread_cond_wait(&condvar, &mutex);
pthread_mutex_unlock(&mutex);
}
pthread_t t;
FILE* f = fdopen(cfd, "a+");
setvbuf(f, 0, _IONBF, 0);
int r = pthread_create(&t, 0, connection_thread, (void*) f);
if (r != 0) {
perror("pthread_create");
exit(1);
}
}
}
void handle_connection(FILE* fin, FILE* fout) {
char buf[1024];
while (fgets(buf, 1024, fin))
if (remove_trailing_whitespace(buf)) {
struct servent* service = getservbyname(buf, "tcp");
int port = service ? ntohs(service->s_port) : 0;
fprintf(fout, "%s,%d\\n", buf, port);
}
if (ferror(fin))
perror("read");
}
int make_listen(int port) {
int fd = socket(AF_INET, SOCK_STREAM, 0);
assert(fd >= 0);
int r = fcntl(fd, F_SETFD, FD_CLOEXEC);
assert(r >= 0);
int yes = 1;
r = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
assert(r >= 0);
struct sockaddr_in address;
memset(&address, 0, sizeof(address));
address.sin_family = AF_INET;
address.sin_port = htons(port);
address.sin_addr.s_addr = INADDR_ANY;
r = bind(fd, (struct sockaddr*) &address, sizeof(address));
assert(r >= 0);
r = listen(fd, 100);
assert(r >= 0);
return fd;
}
int remove_trailing_whitespace(char* buf) {
int len = strlen(buf);
while (len > 0 && isspace((unsigned char) buf[len - 1])) {
--len;
buf[len] = 0;
}
return len;
}
| 1
|
#include <pthread.h>
int numReaders = 0;
int numWriters = 0;
int resourceFlag =0;
int sharedVariable = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c_read = PTHREAD_COND_INITIALIZER;
pthread_cond_t c_write = PTHREAD_COND_INITIALIZER;
void * Reader_thread(void * param);
void * Writer_thread(void * param);
int main()
{
pthread_t readThread[5];
pthread_t writeThread[5];
int i;
for (i = 0; i < 5 ; i++)
{
if (pthread_create(&readThread[i], 0, Reader_thread, 0) != 0)
{
fprintf(stderr, "Unable to create reader thread\\n");
exit(1);
}
if (pthread_create(&writeThread[i], 0, Writer_thread, 0) != 0)
{
fprintf(stderr, "Unable to create writer thread\\n");
exit(1);
}
pthread_join (readThread[i], 0);
printf ("Reader thread %d: Joined.\\n",i);
pthread_join (writeThread[i], 0);
printf("Writer thread %d: Joined\\n", i);
}
printf("Parent exiting\\n");
return 0;
}
void * Reader_thread(void * param)
{
pthread_mutex_lock (&m);
while (resourceFlag < 0) pthread_cond_wait (&c_read, &m);
resourceFlag ++ ;
numReaders ++ ;
pthread_mutex_unlock(&m);
printf("The value of Shared variable X = %d\\n", sharedVariable);
printf("The number of readers reading Shared Variable X is %d\\n", numReaders);
pthread_mutex_lock (&m);
resourceFlag -- ;
numReaders -- ;
if (numReaders == 0)
pthread_cond_signal (&c_write);
pthread_mutex_unlock(&m);
}
void * Writer_thread(void * param)
{
pthread_mutex_lock (&m);
while (resourceFlag > 0) pthread_cond_wait (&c_write, &m);
resourceFlag ++ ;
numWriters ++;
pthread_mutex_unlock(&m);
sharedVariable += 10;
printf("The value of Shared variable X = %d\\n", sharedVariable);
printf("The number of readers reading Shared Variable X is %d\\n", numReaders);
pthread_mutex_lock (&m);
resourceFlag -- ;
numWriters -- ;
if (numWriters == 0)
pthread_cond_signal (&c_read);
pthread_mutex_unlock(&m);
}
| 0
|
#include <pthread.h>
static int balance = 0;
static pthread_mutex_t lock;
void report_and_die(const char* msg) {
perror(msg);
exit(0);
}
void* deposit(void* n) {
int* ptr = (int*) n;
int limit = *ptr, i;
for (i = 0; i < limit; i++) {
if (pthread_mutex_lock(&lock) == 0) {
balance++;
pthread_mutex_unlock(&lock);
}
else
report_and_die("pthread_mutex_lock (deposit)");
}
return 0;
}
void* withdraw(void* n) {
int* ptr = (int*) n;
int limit = *ptr, i;
for (i = 0; i < limit; i++) {
if (pthread_mutex_lock(&lock) == 0) {
balance--;
pthread_mutex_unlock(&lock);
}
else
report_and_die("pthread_mute_lock (withdraw)");
}
return 0;
}
int main(int argc, char* argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: 06-a-deposit-withdraw-without-race <number of operations apiece>\\n");
return 0;
}
int n = atoi(argv[1]);
pthread_t depositer, withdrawer;
pthread_mutex_init(&lock, 0);
if (pthread_create(&depositer, 0, deposit, &n) < 0)
report_and_die("pthread_create: depositer");
if (pthread_create(&withdrawer, 0, withdraw, &n) < 0)
report_and_die("pthread_create: withdrawer");
pthread_join(depositer, 0);
pthread_join(withdrawer, 0);
pthread_mutex_destroy(&lock);
printf("The final balance is: %i\\n", balance);
return 0;
}
| 1
|
#include <pthread.h>
void error(char *msg,int i)
{
fprintf(stderr, "%s %i: %s\\n", msg,i, strerror(errno));
exit(1);
}
int beers = 200000000;
pthread_mutex_t beers_lock = PTHREAD_MUTEX_INITIALIZER;
void* drink_lots(void* a)
{
int i;
pthread_mutex_lock(&beers_lock);
for(i=0; i<10000000; 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 beers on the wall\\n%i bootles of beer\\n", beers, beers);
for(t=0; t<20; t++)
{
if(pthread_create(&threads[t],0,drink_lots,0)==-1)
error("Cannot make threads", t);
}
void* result;
for(t=0;t<20;t++)
{
if(pthread_join(threads[t],&result)==-1)
error("Cannot join thread",t);
}
printf("There are now %i bottles of beer on the wall\\n",beers);
return 0;
}
| 0
|
#include <pthread.h>
int sqrtN,N,NThreads;
int mysum;
pthread_attr_t attr;
pthread_mutex_t mutexsum;
void * Factorize(void *arg)
{
int i;
long tid;
tid = (long) arg;
for(i=tid+2;i<=sqrtN;i=i+NThreads)
{
if((N%i)==0)
{
pthread_mutex_lock (&mutexsum);
mysum += i+N/i;
pthread_mutex_unlock (&mutexsum);
printf(" %d %d ",i,N/i);
}
}
pthread_exit((void*) 0);
}
int main(int argc,char **arv)
{
int rc;
long i;
void *status;
printf("Enter an integer and total number of threads you want to use\\n");
scanf("%d %d",&N,&NThreads);
while(N<2)
{
printf("Error !! Enter a number greater than 1\\n");
scanf("%d",&N);
}
sqrtN = sqrt(N);
if(NThreads>=sqrtN||NThreads<=0)
{
NThreads = sqrtN-1;
printf("Warning!! Excess/Insufficient number of threads, modifying number of threads to %d\\n",NThreads);
}
pthread_t threads[NThreads];
pthread_attr_init(&attr);
pthread_mutex_init(&mutexsum,0);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
mysum = 1;
printf("Factors of number %d are %d %d ",N,1,N);
for(i=0; i<NThreads; i++)
{
rc = pthread_create(&threads[i], &attr, Factorize, (void *)i);
if (rc)
{
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
pthread_attr_destroy(&attr);
for(i=0; i<NThreads; i++)
{
pthread_join(threads[i], &status);
}
if(mysum==N)
{
printf ("\\nCongratulations !! Number %d is a perfect number\\n", N);
}
else
{
printf ("\\nSorry !! Number %d is NOT a perfect number\\n", N);
}
pthread_mutex_destroy(&mutexsum);
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t getprotoby_mutex = PTHREAD_MUTEX_INITIALIZER;
static int
convert (struct protoent *ret, struct protoent *result,
char *buf, int buflen)
{
int len, i;
if (!buf) return -1;
*result = *ret;
result->p_name = (char *) buf;
len = strlen (ret->p_name) + 1;
if (len > buflen) return -1;
buflen -= len;
buf += len;
strcpy (result->p_name, ret->p_name);
for (len = sizeof (char *), i = 0; ret->p_aliases [i]; i++)
{
len += strlen (ret->p_aliases [i]) + 1 + sizeof (char *);
}
if (len > buflen) return -1;
result->p_aliases = (char **) buf;
buf += (i + 1) * sizeof (char *);
for (i = 0; ret->p_aliases [i]; i++)
{
result->p_aliases [i] = (char *) buf;
strcpy (result->p_aliases [i], ret->p_aliases [i]);
buf += strlen (ret->p_aliases [i]) + 1;
}
result->p_aliases [i] = 0;
return 0;
}
struct protoent *
getprotobynumber_r (int proto,
struct protoent *result, char *buffer, int buflen)
{
struct protoent *ret;
pthread_mutex_lock (&getprotoby_mutex);
ret = getprotobynumber (proto);
if (!ret ||
convert (ret, result, buffer, buflen) != 0)
{
result = 0;
}
pthread_mutex_unlock (&getprotoby_mutex);
return result;
}
struct protoent *
getprotobyname_r (const char *name,
struct protoent *result, char *buffer, int buflen)
{
struct protoent *ret;
pthread_mutex_lock (&getprotoby_mutex);
ret = getprotobyname (name);
if (!ret ||
convert (ret, result, buffer, buflen) != 0)
{
result = 0;
}
pthread_mutex_unlock (&getprotoby_mutex);
return result;
}
struct protoent *
getprotoent_r (struct protoent *result, char *buffer, int buflen)
{
struct protoent *ret;
pthread_mutex_lock (&getprotoby_mutex);
ret = getprotoent ();
if (!ret ||
convert (ret, result, buffer, buflen) != 0)
{
result = 0;
}
pthread_mutex_unlock (&getprotoby_mutex);
return result;
}
| 0
|
#include <pthread.h>
void* nokta(void*);
void help(char*);
unsigned int seed;
long total = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main(int argc, char *argv[])
{
if (argc != 3)
{
help(argv[0]);
}
int i, thread_say = atoi(argv[2]);
int *errCode;
double pi;
errCode = (int*)malloc(sizeof(int)*thread_say);
pthread_t *threads;
pthread_attr_t attr;
seed = time(0);
long iterasyon = atol(argv[1])/(long)thread_say;
threads = (pthread_t*)malloc(sizeof(pthread_t)*thread_say);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
for (i=0; i < thread_say; i++)
{
if (((errCode[i] = pthread_create(&threads[i], &attr, &nokta, (void*)&iterasyon)) != 0))
printf("ERROR creating thread %d, error=%d\\n",i,errCode[i]);
}
pthread_attr_destroy(&attr);
for (i=0; i < thread_say; i++)
{
if (errCode[i]==0)
{
errCode[i] = pthread_join(threads[i], 0);
if(errCode[i]!=0)
printf("error joining thread %d, error=%d",i,errCode[i]);
}
}
pthread_mutex_destroy(&mutex);
pi = 4*(double)total/atol(argv[1]);
printf("pi: %.10f\\n",pi);
free(threads);
free(errCode);
return 0;
}
void help(char* arg)
{
printf("Kullanim: %s <iterasyon sayisi> <thread sayisi>\\n" , arg);
exit(1);
}
void* nokta(void* iter)
{
double x, y;
long i,local=0;
for (i = 0; i < *(long *)iter; i++)
{
y = (double)rand_r(&seed)/32767;
x = (double)rand_r(&seed)/32767;
if (((x*x)+(y*y))<= 1.0)
local += 1;
}
pthread_mutex_lock(&mutex);
total += local;
pthread_mutex_unlock(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
int start;
int end;
} args_struct;
int min;
int max;
pthread_mutex_t mutex;
pthread_cond_t condition;
} result_struct;
static result_struct results = {
.mutex = PTHREAD_MUTEX_INITIALIZER
};
int myArray[(int) 1e8];
struct timeval begin, end;
void * search_min(void* args) {
args_struct *arguments = (struct args_struct *) args;
pthread_mutex_lock(&results.mutex);
for(int i=arguments->start;i<arguments->end;i++) {
if(results.min > myArray[i]) {
results.min = myArray[i];
}
}
pthread_mutex_unlock(&results.mutex);
return 0;
}
void * search_max(void* args) {
args_struct *arguments = (struct args_struct *) args;
pthread_mutex_lock(&results.mutex);
for(int i=arguments->start;i<arguments->end;i++) {
if(results.max < myArray[i]) {
results.max = myArray[i];
}
}
pthread_mutex_unlock(&results.mutex);
return 0;
}
int createThreads(int nbThreads, void *(fct) (void *)) {
pthread_t threads[nbThreads];
args_struct args[nbThreads];
int sizeThread = (int) 1e8 / nbThreads;
int rest = (int) 1e8 % nbThreads;
for(int i = 0; i < nbThreads; i++) {
args[i].start = sizeThread*i;
args[i].end = args[i].start + sizeThread;
if(i == nbThreads - 1 && rest > 0) {
args[i].end += 1;
}
}
gettimeofday (&begin, 0);
for(int i = 0; i < nbThreads; i++) {
if (pthread_create(&threads[i], 0, fct, (void *) &args[i])) {
return 1;
}
}
for(int i = 0; i < nbThreads; i++) {
if(pthread_join(threads[i], 0)) {
return 1;
}
}
gettimeofday (&end, 0);
printf("search process time (%d threads): %fs\\n", nbThreads, (end.tv_sec - begin.tv_sec) + ((end.tv_usec - begin.tv_usec)/1000000.0));
return 0;
}
void initThreads(int nbThreads, void *(fct) (void *)) {
results.min = (int) 1e9;
results.max = 0;
if(nbThreads > 0) {
createThreads(nbThreads, fct);
} else {
args_struct args;
args.start = 0;
args.end = (int) 1e8;
gettimeofday (&begin, 0);
search_min((void *) &args);
gettimeofday (&end, 0);
printf("search process time (%d threads): %fs\\n", nbThreads, (end.tv_sec - begin.tv_sec) + ((end.tv_usec - begin.tv_usec)/1000000.0));
gettimeofday (&begin, 0);
search_max((void *) &args);
gettimeofday (&end, 0);
printf("search process time (%d threads): %fs\\n", nbThreads, (end.tv_sec - begin.tv_sec) + ((end.tv_usec - begin.tv_usec)/1000000.0));
}
}
int main(){
srand(time(0));
for(int i=0;i < (int) 1e8; i++) {
myArray[i] = rand() % (int) 1e9;
}
initThreads(0, 0);
printf("--------------------\\n");
initThreads(2, search_min);
initThreads(2, search_max);
printf("--------------------\\n");
initThreads(4, search_min);
initThreads(4, search_max);
printf("--------------------\\n");
initThreads(8, search_min);
initThreads(8, search_max);
return 0;
}
| 0
|
#include <pthread.h>
void *trabajador(void *arg);
int vector[1024];
struct b_s {
int n;
pthread_mutex_t m;
pthread_cond_t ll;
} b;
int main(void) {
pthread_t hilo[10];
int i;
b.n = 0;
pthread_mutex_init(&b.m, 0);
pthread_cond_init(&b.ll, 0);
par=0; impar=1;
for(i=0; i<10; i++)
pthread_create(&hilo[i],
0, trabajador,
(void *)&i);
for(i=0; i<10; i++)
pthread_join(hilo[i], 0);
pthread_cond_destroy(&b.ll);
pthread_mutex_destroy(&b.m);
return 0;
}
void *trabajador(void *arg) {
int inicio=0, fin=0, i;
id = *(int *)arg;
inicio =(id)*(1024/10);
fin = (id+1)*(1024/10);
for(i=inicio; i<fin; i++) {
vector[i] = id;
}
pthread_mutex_lock(&b.m);
b.n++;
if (10<=b.n) { pthread_cond_broadcast(&b.ll);
} else {
pthread_cond_wait(&b.ll, &b.m);
}
pthread_mutex_unlock(&b.m);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex_1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_2 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_3 = PTHREAD_MUTEX_INITIALIZER;
int elementos[3] = {1,2,3};
int fumado;
int elemento = 0;
int elemento1;
int elemento2;
int elemento3;
void* fumador1(void* arg)
{
elemento = 1;
if(elemento < elemento2 && elemento < elemento3)
{
pthread_mutex_lock(&mutex_1);
sleep(5);
fumado = 1;
pthread_mutex_unlock(&mutex_1);
}
else
{
fumado = 0;
}
pthread_exit(0);
}
void* fumador2(void* arg)
{
elemento = 2;
if(elemento < elemento3 && elemento < elemento1)
{
pthread_mutex_lock(&mutex_2);
sleep(5);
fumado = 1;
pthread_mutex_unlock(&mutex_2);
}
else
{
fumado = 0;
}
pthread_exit(0);
}
void* fumador3(void* arg)
{
elemento = 3;
if(elemento > elemento2 && elemento > elemento1)
{
pthread_mutex_lock(&mutex_1);
sleep(5);
fumado = 1;
pthread_mutex_unlock(&mutex_1);
}
else
{
fumado = 0;
}
pthread_exit(0);
}
void* agente(void* arg)
{
int i;
for(i = 0; i < 100; ++i)
{
elemento1 = rand()%3;
elemento2 = rand()%3;
while (pthread_mutex_trylock(&mutex_1))
{
pthread_mutex_unlock(&mutex_1);
pthread_mutex_lock(&mutex_1);
}
while (pthread_mutex_trylock(&mutex_2))
{
pthread_mutex_unlock(&mutex_2);
pthread_mutex_lock(&mutex_2);
}
while (pthread_mutex_trylock(&mutex_3))
{
pthread_mutex_unlock(&mutex_3);
pthread_mutex_lock(&mutex_3);
}
}
pthread_exit(0);
}
int main(int argc, char* arvg[])
{
srand(time(0));
pthread_t * tid;
int nhilos;
int i;
nhilos = 4;
tid = malloc(nhilos * sizeof(pthread_t));
printf("Creando hilos ...\\n");
pthread_create(tid, 0, agente, (void *)0);
pthread_create(tid+1, 0, fumador1, (void *)1);
pthread_create(tid+2, 0, fumador2, (void *)2);
pthread_create(tid+3, 0, fumador3, (void *)3);
for (i = 0; i < nhilos; ++i) {
pthread_join(*(tid+i), 0);
printf("TID = %d...\\n", *(tid+i));
}
free(tid);
return 0;
}
| 0
|
#include <pthread.h>
int a;
pthread_mutex_t mutex;
int thread_index;
} thread_param;
void *Thread_Fn(void *arg) {
thread_param *param = (thread_param *) arg;
int k;
for (k=0; k < 10; k++) {
pthread_mutex_lock(&mutex);
a++;
printf("%d says: a is %d now\\n", param->thread_index, a);
pthread_mutex_unlock(&mutex);
}
}
int main(void) {
a = 0;
int i;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_mutex_init(&mutex, 0);
pthread_t *threads = (pthread_t *) malloc(sizeof(pthread_t *) * 5);
thread_param *params = (thread_param *) malloc(sizeof(thread_param *) * 5);
for (i = 0; i < 5; i++) {
params[i].thread_index = i;
if (pthread_create(&threads[i], &attr, Thread_Fn, (void *) ¶ms[i]) != 0) {
printf("creating thread failed\\n");
}
}
pthread_attr_destroy(&attr);
for (i = 0; i < 5; i++) {
if (pthread_join(threads[i], 0) != 0) {
printf("joing thread failed\\n");
}
}
pthread_mutex_destroy(&mutex);
free(threads);
free(params);
return 0;
}
| 1
|
#include <pthread.h>
size_t alloc_len;
size_t len;
size_t elem_size;
void *elems;
pthread_mutex_t lock;
} queue;
queue *queue_new (size_t elem_size) {
queue *q = malloc(sizeof(queue));
q->alloc_len = 1024;
q->elem_size = elem_size;
q->elems = malloc(q->alloc_len * elem_size);
q->len = 0;
pthread_mutex_init(&q->lock, 0);
return q;
}
void queue_push (queue *q, void *elem) {
pthread_mutex_lock(&q->lock);
memcpy(q->elems + (q->len * q->elem_size), elem, q->elem_size);
q->len++;
if (q->len == q->alloc_len) {
q->alloc_len *= 2;
q->elems = realloc(q->elems, q->alloc_len * q->elem_size);
};
pthread_mutex_unlock(&q->lock);
}
queue *queue_transfer(queue *orig_q) {
queue *q = malloc(sizeof(queue));
pthread_mutex_lock(&orig_q->lock);
memcpy(q, orig_q, sizeof(queue));
orig_q->len = 0;
orig_q->alloc_len = 1024;
orig_q->elems = malloc(orig_q->alloc_len * orig_q->elem_size);
pthread_mutex_unlock(&orig_q->lock);
return q;
}
void *queue_get(queue *q, size_t pos) {
assert(pos < q->len);
return q->elems + (pos * q->elem_size);
}
size_t queue_len(queue *q) {
return q->len;
}
void queue_free(queue *q) {
free(q->elems);
free(q);
}
| 0
|
#include <pthread.h>
int stack[5];
int stptr = 0;
pthread_mutex_t mutex;
pthread_cond_t condv;
void
stack_push(int xx)
{
pthread_mutex_lock(&mutex);
while (stptr >= 5) {
pthread_cond_wait(&condv, &mutex);
}
stack[++stptr] = xx;
pthread_cond_broadcast(&condv);
pthread_mutex_unlock(&mutex);
}
int
stack_pop()
{
pthread_mutex_lock(&mutex);
while (stptr <= 0) {
pthread_cond_wait(&condv, &mutex);
}
int yy = stack[stptr--];
pthread_cond_broadcast(&condv);
pthread_mutex_unlock(&mutex);
return yy;
}
void*
producer_thread(void* arg)
{
int nn = *((int*) arg);
free(arg);
for (int ii = 0; ii < nn; ++ii) {
stack_push(ii);
}
}
int
main(int _ac, char* _av[])
{
pthread_t threads[2];
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&condv, 0);
for (int ii = 0; ii < 2; ++ii) {
int* nn = malloc(sizeof(int));
*nn = 1000;
int rv = pthread_create(&(threads[ii]), 0, producer_thread, nn);
assert(rv == 0);
}
while (1) {
int yy = stack_pop();
printf("%d\\n", yy);
usleep(10000);
}
return 0;
}
| 1
|
#include <pthread.h>
static void
*adz_player_entry(void *arg)
{
long n;
void *result;
char id = *(char *)arg;
n = start_adz(id , STDOUT_FILENO);
result = (void *)n;
return result;
}
int
main(int argc, char *argv[])
{
char id;
char *message = 0;
char name[] = "?.bookz";
int fd, n;
long ads_displayed;
pthread_t adz_thread;
void *result;
if (argc > 1)
{
id = argv[1][0];
name[0] = id;
fd = open(name, O_RDONLY);
if (fd >= 0)
{
pthread_create(&adz_thread, 0, adz_player_entry, (void *)&id);
display_all(fd, STDOUT_FILENO);
close(fd);
pthread_mutex_lock(&bookz_mutex);
bookz_done = 1;
pthread_mutex_unlock(&bookz_mutex);
pthread_join(adz_thread, &result);
ads_displayed = (long)result;
n = 7 + ((int)log10(lines_read)) + 1
+ 7 + ((int)log10(ads_displayed)) + 1
+ 2;
message = (char *)malloc(n * sizeof(char));
sprintf(message, "Lines: %d, Ads: %ld\\n", lines_read, ads_displayed);
write(STDOUT_FILENO, message, n);
free(message);
return 0;
}
}
return 1;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t priv_pid_mutex;
static unsigned long priv_pid_pool=0;
static void * priv_pid_data[MAX_PLAYER_THREADS];
static unsigned long priv_pid_used[MAX_PLAYER_THREADS];
int player_id_pool_init(void)
{
priv_pid_pool=0;
MEMSET(priv_pid_data,0,sizeof(priv_pid_data));
MEMSET(priv_pid_used,0,sizeof(priv_pid_used));
pthread_mutex_init(&priv_pid_mutex,0);
return 0;
}
int player_request_pid(void)
{
int i;
int pid=-1;
static int last = 0;
pthread_mutex_lock(&priv_pid_mutex);
log_debug1("[player_request_pid:%d]last=%d\\n",43,last);
for(i=last;i<MAX_PLAYER_THREADS;i++)
{
if(!(priv_pid_pool&(1<<i)))
{
priv_pid_pool|=(1<<i);
priv_pid_data[i]=0;
priv_pid_used[i]=0;
pid= i;
log_debug1("[player_request_pid:%d]last=%d pid=%d\\n",52,last,pid);
last = i+1;
if(last == (MAX_PLAYER_THREADS -1))
last = 0;
break;
}
}
pthread_mutex_unlock(&priv_pid_mutex);
return pid;
}
int player_release_pid(int pid)
{
int ret=PLAYER_NOT_VALID_PID;
pthread_mutex_lock(&priv_pid_mutex);
if((pid>=0 && pid<32 && (priv_pid_pool &(1 <<pid))))
{
if(priv_pid_used[pid]!=0)
log_print(":WARING!%s:PID is in using!,pid=%d,used=%ld\\n",__FUNCTION__,pid,priv_pid_used[pid]);
priv_pid_used[pid]=0;
priv_pid_data[pid]=0;
priv_pid_pool&=~(1<<pid);
log_print("[player_release_pid:%d]release pid=%d\\n",73, pid);
ret=PLAYER_SUCCESS;
}
else
{
log_print("%s:pid is not valid,pid=%d,priv_pid_pool=%lx\\n",__FUNCTION__,pid,priv_pid_pool);
}
pthread_mutex_unlock(&priv_pid_mutex);
return ret;
}
int player_init_pid_data(int pid,void * data)
{
int ret;
pthread_mutex_lock(&priv_pid_mutex);
if((pid>=0 && pid<32 && (priv_pid_pool &(1 <<pid))))
{
priv_pid_data[pid]=data;
ret=PLAYER_SUCCESS;
}
else
ret=PLAYER_NOT_VALID_PID;
pthread_mutex_unlock(&priv_pid_mutex);
return ret;
}
void * player_open_pid_data(int pid)
{
void * pid_data;
pthread_mutex_lock(&priv_pid_mutex);
if((pid>=0 && pid<32 && (priv_pid_pool &(1 <<pid))))
{
pid_data=priv_pid_data[pid];
priv_pid_used[pid]++;
}
else
{
pid_data=0;
}
pthread_mutex_unlock(&priv_pid_mutex);
return pid_data;
}
int player_close_pid_data(int pid)
{
int ret=PLAYER_NOT_VALID_PID;
pthread_mutex_lock(&priv_pid_mutex);
if((pid>=0 && pid<32 && (priv_pid_pool &(1 <<pid))))
{
if(priv_pid_used[pid]>0)
{
priv_pid_used[pid]--;
ret=PLAYER_SUCCESS;
}
else
log_print("PID data release too much time:pid=%d!\\n", pid);
}
else
log_print("%s:pid is not valid,pid=%d,priv_pid_pool=%lx\\n",__FUNCTION__,pid,priv_pid_pool);
pthread_mutex_unlock(&priv_pid_mutex);
return ret;
}
int player_list_pid(char id[],int size)
{
int i,ids;
ids=0;
for(i=0;i<MAX_PLAYER_THREADS && i <size;i++)
{
if(priv_pid_pool & (1<<i))
id[ids++]=i;
}
return ids;
}
int check_pid_valid(int pid)
{
return (pid>=0 && pid<32 && (priv_pid_pool &(1 <<pid)));
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
long acc = 0;
int nque = 1;
struct mymesg {
long mtype;
char mtext[512];
};
int thread_id[16];
int msgid[16];
pthread_t tid[16];
void *thread_fn(void *arg) {
int n = *((int *)arg);
struct mymesg sbuf, rbuf;
pthread_mutex_lock(&lock);
printf("thread %d wait %d queue\\n", n, msgid[n]);
pthread_mutex_unlock(&lock);
while (msgrcv(msgid[n], &rbuf, 512, 1, 0) != 0) {
pthread_mutex_lock(&lock);
printf("%d queue thread rcv %s\\n", n, rbuf.mtext);
acc += atol(rbuf.mtext);
sbuf.mtype = 2;
sprintf(sbuf.mtext, "acc = %ld", acc);
if (msgsnd(msgid[n], &sbuf, strlen(sbuf.mtext)+1, 0) < 0) {
printf("send message");
exit(1);
}
pthread_mutex_unlock(&lock);
}
pthread_exit(0);
}
int main (int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, "q:")) != -1) {
switch(opt) {
case 'q':
nque = atoi(optarg);
default:
break;
}
}
printf("queue num = %d\\n", nque);
key_t key = 4587;
for (int i = 0; i < nque; i++) {
if ((msgid[i] = msgget(key+i, IPC_CREAT | 0666)) < 0) {
printf("msgget");
exit(1);
}
thread_id[i] = i;
pthread_create(&tid[i], 0, thread_fn, &thread_id[i]);
}
for (int i = 0; i < nque; i++) {
printf("queue %d id = %d\\n", i, msgid[i]);
}
for (int i = 0; i < nque; i++) {
pthread_join(tid[i], 0);
}
printf("acc = %ld\\n", acc);
return 0;
}
| 0
|
#include <pthread.h>
unsigned int sum = 0;
pthread_mutex_t m;
int counter;
void *incr(){
unsigned int i;
counter += 1;
printf("\\n Lock\\n");
for(i=0;i<=10;i++){
pthread_mutex_lock(&m);
sum += 1;
printf("\\n Job %d started\\n", i);
fflush(stdout);
pthread_mutex_unlock(&m);
}
printf("\\n Unlock\\n");
return 0;
}
int main(){
pthread_t thread1;
pthread_t thread2;
pthread_mutex_init(&m, 0);
int i = 0;
int err;
if(pthread_create(&thread1, 0, incr, 0)) {
fprintf(stderr, "Error creating thread\\n");
return 1;
}
if(pthread_create(&thread2, 0, incr, 0)) {
fprintf(stderr, "Error creating thread\\n");
return 1;
}
if(pthread_join(thread1, 0)) {
fprintf(stderr, "Error joining thread\\n");
return 2;
}
if(pthread_join(thread2, 0)) {
fprintf(stderr, "Error joining thread\\n");
return 2;
}
printf("SUM: %d\\n", sum);
pthread_mutex_destroy(&m);
return 0;
}
| 1
|
#include <pthread.h>
void* declare_init_files(void* rank)
{
long my_rank = rank;
pthread_mutex_t mutex;
int check = pthread_mutex_init(&mutex, 0);
if (my_rank == 0)
{
pthread_mutex_lock(&mutex);
firingcoherenceid = fopen("FiringCoherenceVaryingDs(100,8) (0.9; 0.6).txt", "w");
pthread_mutex_unlock(&mutex);
}
if (my_rank == 1)
{
pthread_mutex_lock(&mutex);
fcdegreeid = fopen("FCDegreeVaryingD(100,8) (0.9; 0.6).txt", "w");
pthread_mutex_unlock(&mutex);
}
if (my_rank == 2)
{
pthread_mutex_lock(&mutex);
fisiid = fopen("ISI_no_connections(100,8) (0.9; 0.6).txt", "w");
pthread_mutex_unlock(&mutex);
}
if(my_rank == 3)
{
pthread_mutex_lock(&mutex);
fmeanisiid = fopen("MeanISI(100,8) (0.9; 0.6).txt", "w");
pthread_mutex_unlock(&mutex);
}
check = pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
void *thread1(void *arg) {
pthread_cleanup_push (pthread_mutex_unlock,&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(int argc, char *argv[]) {
pthread_t tid1;
pthread_t tid2;
printf("condition variable study!\\n");
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond,0);
pthread_create(&tid1,0,(void *)thread1,0);
pthread_create(&tid2,0,(void *)thread2,0);
do {
pthread_cond_signal(&cond);
} while(1);
sleep(50);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t wait;
int vagas;
} semaforo;
void error(char *msg) {
fprintf(stderr, "%s: %s\\n", msg, strerror(errno));
exit(1);
}
void init(semaforo *s, int vagas) {
if (vagas <= 0) {
error("O valor de vagas tem que ser maior que 0!");
}
s->vagas = vagas;
if (pthread_cond_init(&(s->wait), 0) == -1) {
error("Erro ao inicializar a condição");
}
if (pthread_mutex_init(&(s->lock), 0) == -1) {
error("Erro ao inicializar o mutext");
}
return;
}
void p(semaforo *s) {
pthread_mutex_lock(&(s->lock));
s->vagas--;
if (s->vagas < 0) {
printf("Não existem vagas disponiveis, aguarde...\\n");
pthread_cond_wait(&(s->wait), &(s->lock));
printf("Vaga liberada!\\n");
}
printf("Um carro esta passando, %d vagas disponiveis.\\n", s->vagas);
pthread_mutex_unlock(&(s->lock));
return;
}
void v(semaforo *s) {
pthread_mutex_lock(&(s->lock));
s->vagas++;
if (s->vagas <= 0) {
pthread_cond_signal(&(s->wait));
}
printf("Uma vaga liberada. %d vagas disponiveis.\\n", s->vagas);
pthread_mutex_unlock(&(s->lock));
return;
}
void* entrando_carro(void* void_s) {
semaforo *s = void_s;
for (int i = 0; i < 20;i++) {
p(s);
sleep(1);
}
return 0;
}
void* saida_carro(void* void_s) {
semaforo *s = void_s;
for (int i = 0; i < 15;i++) {
v(s);
sleep(3);
}
return 0;
}
int main() {
semaforo s;
init(&s, 10);
pthread_t t_saida_carros;
pthread_t t_entrando_carros;
if (pthread_create(&t_entrando_carros, 0, entrando_carro, &s) == -1) {
error("Erro ao criar a thread 't_entrando_carros'!");
}
if (pthread_create(&t_saida_carros, 0, saida_carro, &s) == -1) {
error("Erro ao criar a thread 't_saida_carros'!");
}
if (pthread_join(t_entrando_carros, (void *) &s) == -1) {
error("Erro ao realizar o join da thread 't_entrando_carros'!");
}
if (pthread_join(t_saida_carros, (void *) &s) == -1) {
error("Erro ao realizar o join da thread 't_saida_carros'!");
}
return 0;
}
| 0
|
#include <pthread.h>
void*recv_t(void*in)
{
struct t_args*args=(struct t_args*)in;
char*buffer=(char*)malloc(256);
int i;
while(*(args->sig))
{
memset(buffer,0,256);
pthread_mutex_lock(args->mutex);
if(recv(*(args->sock),buffer,256,0)>0)
{
printf("\\r");fflush(stdout);
for(i=0;i<strlen(*(args->buffer));i++)
{
printf(" ");
fflush(stdout);
}
printf("\\r%s\\n%s",buffer,*(args->buffer));
fflush(stdout);
}
pthread_mutex_unlock(args->mutex);
}
free(buffer);
return in;
}
void*send_t(void*in)
{
struct t_args*args=(struct t_args*)in;
char*input=*(args->buffer);
char c;
int len;
memset(input,0,256);
while(*(args->sig))
{
len=0;
while((c=getchar())!='\\n')
*(input+len++)=c;
pthread_mutex_lock(args->mutex);
if(send(*(args->sock),input,len,0)<0)
{
printf("Error sending data\\n");
fflush(stdout);
}
memset(input,0,256);
pthread_mutex_unlock(args->mutex);
}
return in;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mut;
pthread_t thread[2];
int number=0,i;
void
*thread1 ()
{
printf("thread1: I'am thread 1\\n");
for(i=0;i<10;i++)
{
printf("thread1:number=%d\\n",number);
pthread_mutex_lock(&mut);
number++;
pthread_mutex_unlock(&mut);
sleep(2);
}
printf("thread1:主函数在等我完成任务吗?\\n");
pthread_exit(0);
}
void
*thread2 ()
{
printf("thread2:I'am thread2\\n");
for(i=0;i<10;i++)
{
printf("thread2:number=%d\\n",number);
pthread_mutex_lock(&mut);
number++;
pthread_mutex_unlock(&mut);
sleep(3);
}
printf("thread2:主函数在等我完成任务吗?\\n");
pthread_exit(0);
}
void
pthreadCreate ( void )
{
memset(&thread,0,sizeof(thread));
if(pthread_create(&thread[0],0,thread1,0)!=0)
printf("创建线程1失败!\\n");
else
printf("创建线程1成功!\\n");
if(pthread_create(&thread[1],0,thread2,0)!=0)
printf("创建线程2失败!\\n");
else
printf("创建线程2成功!\\n");
}
void
pthreadWait ( )
{
if(thread[0]!=0)
{
pthread_join(thread[0],0);
printf("线程1已经结束\\n");
}
if(thread[1]!=0)
{
pthread_join(thread[1],0);
printf("线程2已经结束\\n");
}
}
int
main ( int argc, char *argv[] )
{
pthread_mutexattr_t *mutexattr;
int type;
if(pthread_mutexattr_settype(mutexattr,PTHREAD_MUTEX_ERRORCHECK)!=0)
printf("set error\\n");
pthread_mutex_init(&mut,0);
if(pthread_mutexattr_gettype(mutexattr,&type)!=0)
printf("get error\\n");
printf("%d\\n",type);
printf("我是主函数,我正在创建线程\\n");
pthreadCreate();
printf("我是主函数,我正在等待线程完成任务\\n");
pthreadWait();
return 0;
}
| 0
|
#include <pthread.h>extern int __VERIFIER_nondet_int(void);
extern void __VERIFIER_error() ;
int element[(800)];
int head;
int tail;
int amount;
} QType;
pthread_mutex_t m;
int __VERIFIER_nondet_int();
int stored_elements[(800)];
_Bool enqueue_flag, dequeue_flag;
QType queue;
int init(QType *q)
{
q->head=0;
q->tail=0;
q->amount=0;
}
int empty(QType * q)
{
if (q->head == q->tail)
{
printf("queue is empty\\n");
return (-1);
}
else
return 0;
}
int full(QType * q)
{
if (q->amount == (800))
{
printf("queue is full\\n");
return (-2);
}
else
return 0;
}
int enqueue(QType *q, int x)
{
q->element[q->tail] = x;
q->amount++;
if (q->tail == (800))
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == (800))
{
q->head = 1;
}
else
q->head++;
return x;
}
void *t1(void *arg)
{
int value, i;
pthread_mutex_lock(&m);
value = __VERIFIER_nondet_int();
if (enqueue(&queue,value)) {
goto ERROR;
}
stored_elements[0]=value;
if (empty(&queue)) {
goto ERROR;
}
pthread_mutex_unlock(&m);
for(i=0; i<((800)-1); i++)
{
pthread_mutex_lock(&m);
if (enqueue_flag)
{
value = __VERIFIER_nondet_int();
enqueue(&queue,value);
stored_elements[i+1]=value;
enqueue_flag=(0);
dequeue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
ERROR:__VERIFIER_error();
}
void *t2(void *arg)
{
int i;
for(i=0; i<(800); i++)
{
pthread_mutex_lock(&m);
if (dequeue_flag)
{
if (!dequeue(&queue)==stored_elements[i]) {
ERROR:__VERIFIER_error();
}
dequeue_flag=(0);
enqueue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
}
int main(void)
{
pthread_t id1, id2;
enqueue_flag=(1);
dequeue_flag=(0);
init(&queue);
if (!empty(&queue)==(-1)) {
ERROR:__VERIFIER_error();
}
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, &queue);
pthread_create(&id2, 0, t2, &queue);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 1
|
#include <pthread.h>
sem_t sem_agent;
sem_t sem_tobacco;
sem_t sem_paper;
sem_t sem_match;
sem_t tobacco;
sem_t match;
sem_t paper;
sem_t sem_mutex;
bool tobFree = 0;
bool paperFree = 0;
bool matchesFree = 0;
void *agentA(void *);
void *agentB(void *);
void *agentC(void *);
void *pusherA(void *);
void *pusherB(void *);
void *pusherC(void *);
void *smoker1(void *);
void *smoker2(void *);
void *smoker3(void *);
pthread_mutex_t print_mutex;
int main( int argc, char *argv[] ) {
pthread_t a1, a2, a3, p1, p2, p3, s1, s2, s3;
sem_init(&sem_agent, 0, 1);
sem_init(&sem_tobacco, 0, 0);
sem_init(&sem_paper, 0, 0);
sem_init(&sem_match, 0, 0);
sem_init(&tobacco, 0, 0);
sem_init(&paper, 0, 0);
sem_init(&match, 0, 0);
sem_init(&sem_mutex, 0, 1);
pthread_mutex_init(&print_mutex, 0);
pthread_create(&a1, 0, agentA, 0);
pthread_create(&a2, 0, agentB, 0);
pthread_create(&a3, 0, agentC, 0);
pthread_create(&s1, 0, smoker1, 0);
pthread_create(&s2, 0, smoker2, 0);
pthread_create(&s3, 0, smoker3, 0);
pthread_create(&p1, 0, pusherA, 0);
pthread_create(&p2, 0, pusherB, 0);
pthread_create(&p3, 0, pusherC, 0);
while(1){
}
}
void *agentA(void *a){
while(1){
sem_wait(&sem_agent);
sem_post(&sem_tobacco);
sem_post(&sem_paper);
}
}
void *agentB(void *b){
while(1){
sem_wait(&sem_agent);
sem_post(&sem_tobacco);
sem_post(&sem_match);
}
}
void *agentC(void *c){
while(1){
sem_wait(&sem_agent);
sem_post(&sem_paper);
sem_post(&sem_match);
}
}
void *smoker1(void *a){
while(1){
pthread_mutex_lock(&print_mutex);
printf("S1 needs tobacco\\n");
pthread_mutex_unlock(&print_mutex);
sem_wait(&tobacco);
pthread_mutex_lock(&print_mutex);
printf("S1 gets tobacco, roll cig\\n");
pthread_mutex_unlock(&print_mutex);
sem_post(&sem_agent);
pthread_mutex_lock(&print_mutex);
printf("S1 rolls one and drops the tabacco\\n" );
pthread_mutex_unlock(&print_mutex);
sleep(4);
}
}
void *smoker2(void *b){
while(1){
pthread_mutex_lock(&print_mutex);
printf("S2 needs Paper\\n");
pthread_mutex_unlock(&print_mutex);
sem_wait(&paper);
pthread_mutex_lock(&print_mutex);
printf("S2 gets paper, roll cig\\n");
pthread_mutex_unlock(&print_mutex);
sem_post(&sem_agent);
pthread_mutex_lock(&print_mutex);
printf("S2 rolls one and drops papers\\n" );
pthread_mutex_unlock(&print_mutex);
sleep(4);
}
}
void *smoker3(void *c){
while(1){
pthread_mutex_lock(&print_mutex);
printf("S3 needs matches\\n");
pthread_mutex_unlock(&print_mutex);
sem_wait(&match);
pthread_mutex_lock(&print_mutex);
printf("S3 gets matches, roll cig\\n");
pthread_mutex_unlock(&print_mutex);
sem_post(&sem_agent);
pthread_mutex_lock(&print_mutex);
printf("S3 rolls one and drops matches\\n" );
pthread_mutex_unlock(&print_mutex);
sleep(4);
}
}
void *pusherA(void *a){
while(1){
sem_wait(&sem_tobacco);
pthread_mutex_lock(&print_mutex);
printf("Tobacco is on the table.\\n");
pthread_mutex_unlock(&print_mutex);
sem_wait(&sem_mutex);
if(paperFree){
paperFree = 0;
sem_post(&paper);
}else if(matchesFree){
matchesFree = 0;
sem_post(&match);
}else{
tobFree = 1;
}
sem_post(&sem_mutex);
}
}
void *pusherB(void *b){
while(1){
sem_wait(&sem_match);
pthread_mutex_lock(&print_mutex);
printf("Matches are on the table.\\n");
pthread_mutex_unlock(&print_mutex);
sem_wait(&sem_mutex);
if(paperFree){
paperFree = 0;
sem_post(&match);
}else if(tobFree){
tobFree = 0;
sem_post(&tobacco);
}else{
matchesFree = 1;
}
sem_post(&sem_mutex);
}
}
void *pusherC(void *c){
while(1){
sem_wait(&sem_paper);
pthread_mutex_lock(&print_mutex);
printf("Paper is on the table.\\n");
pthread_mutex_unlock(&print_mutex);
sem_wait(&sem_mutex);
if(tobFree){
tobFree = 0;
sem_post(&tobacco);
}else if(matchesFree){
matchesFree = 0;
sem_post(&match);
}else{
paperFree = 1;
}
sem_post(&sem_mutex);
}
}
| 0
|
#include <pthread.h>
{
double think_time;
double eat_time;
int left_fork;
int right_fork;
long thread_id;
time_t total_thinking_time;
time_t total_eating_time;
time_t total_starvation_time;
long spagetti;
} philosoph_t;
static pthread_mutex_t forks[ 5 ];
static philosoph_t ph[ 5 ];
time_t
think( double think_time, long thread_id )
{
time_t timer = time( 0 );
usleep( think_time );
return time( 0 ) - timer;
}
time_t
eat( double eat_time, long thread_id, long i )
{
time_t timer = time( 0 );
usleep( eat_time );
return time( 0 ) - timer;
}
void*
dining( void* input )
{
time_t timer = 0;
philosoph_t* ph = ( philosoph_t* )input;
unsigned int think_seed = time( 0 ) + ph->thread_id;
unsigned int eat_seed = time( 0 ) + ph->thread_id + 1;
ph->think_time = 1000000 * ( double )rand_r( &think_seed ) / ( double )32767;
ph->eat_time = 1000000 * ( double )rand_r( &eat_seed ) / ( double )32767;
while ( ph->spagetti != 0 )
{
bool two_forks_avail = 0;
do
{
if ( pthread_mutex_lock( &forks[ ph->left_fork ] ) != 0 )
{
printf( "ERROR: Left lock can not be locked\\n" );
}
int right_fork_result;
right_fork_result = pthread_mutex_trylock( &forks[ ph->right_fork ] );
switch ( right_fork_result )
{
case 0:
two_forks_avail = 1;
break;
case EBUSY:
timer = time( 0 );
pthread_mutex_unlock( &forks[ ph->left_fork ] );
two_forks_avail = 0;
break;
default:
printf( "Right lock can not be locked!\\n" );
}
}
while ( !two_forks_avail );
if ( time( 0 ) > timer && timer != 0 )
{
ph->total_starvation_time += time( 0 ) - timer;
timer = 0;
}
ph->spagetti = ph->spagetti - 1;
ph->total_eating_time += eat( ph->eat_time, ph->thread_id, ph->spagetti );
pthread_mutex_unlock( &forks[ ph->right_fork ] );
pthread_mutex_unlock( &forks[ ph->left_fork ] );
ph->total_thinking_time += think( ph->think_time, ph->thread_id );
}
printf( "Philosopher %ld total eating time: %ld total thinking time: %ld "
"starvation: %ld\\n", ph->thread_id, ph->total_eating_time,
ph->total_thinking_time, ph->total_starvation_time );
return 0;
}
int
main( int argc, const char* argv[] )
{
int i;
pthread_t t[ 5 ];
for ( i = 0; i < 5; i++ )
{
if ( ( pthread_mutex_init( &forks[ i ], 0 ) ) != 0 )
{
printf( "ERROR: pthread_mutex_init failed\\n" );
}
}
for ( i = 0; i < 5; i++ )
{
ph[ i ].think_time = 0.0;
ph[ i ].eat_time = 0.0;
ph[ i ].left_fork = i;
ph[ i ].right_fork = i + 1;
ph[ i ].thread_id = i;
ph[ i ].total_thinking_time = 0;
ph[ i ].total_eating_time = 0;
ph[ i ].total_starvation_time = 0;
ph[ i ].spagetti = 10;
}
ph[ 5 - 1 ].right_fork = 0;
for ( i = 0; i < 5; i++ )
{
if ( ( pthread_create( &t[ i ], 0, dining, ( void* )&ph[ i ] ) ) != 0 )
{
printf( "ERROR: pthread_create failed\\n" );
}
}
for ( i = 0; i < 5; i++ )
{
if ( ( pthread_join( t[ i ], 0 ) ) != 0 )
{
printf( "ERROR: pthread_join failed\\n" );
}
}
return 0;
}
| 1
|
#include <pthread.h>
int count = 0;
pthread_mutex_t mutex1;
void *low_pri_thread(){
int i=0;
for (i=0;i<20;i++){
printf("Executing the low priority thread: %d\\n",pthread_self());fflush(stdout);
pthread_mutex_lock(&mutex1);
count++;
pthread_mutex_unlock(&mutex1);
}
}
void *hi_pri_thread(){
pthread_t tid1;
for (int j=0; j<5;j++){
printf("Before: Executing the parent priority thread: %d\\n",pthread_self());fflush(stdout);
}
int r1 = pthread_create(&tid1,0,low_pri_thread,0);
for (int j=0; j<15;j++){
printf("After: Executing the parent priority thread: %d\\n",pthread_self());fflush(stdout);
}
pthread_join(tid1,0);
if(count == 20){
printf("-------Execution of parent priority thread complete %d------------\\n",pthread_self());fflush(stdout);
}
}
int main(){
pthread_t tid2;
int r2 = pthread_create(&tid2,0,hi_pri_thread,0);
pthread_join(tid2,0);
return 0;
}
| 0
|
#include <pthread.h>
static pthread_t thread[256];
static pthread_mutex_t mutex[256];
static pthread_cond_t cond[256];
static volatile int full[256];
static volatile int data[256];
static int cycles;
static int tokens;
static void send_to (int i, int d)
{
pthread_mutex_lock (&(mutex[i]));
while (full[i])
pthread_cond_wait (&(cond[i]), &(mutex[i]));
full[i] = 1;
data[i] = d;
pthread_cond_signal (&(cond[i]));
pthread_mutex_unlock (&(mutex[i]));
}
static int recv_from (int i)
{
int d;
pthread_mutex_lock (&(mutex[i]));
while (!full[i])
pthread_cond_wait (&(cond[i]), &(mutex[i]));
full[i] = 0;
d = data[i];
pthread_cond_signal (&(cond[i]));
pthread_mutex_unlock (&(mutex[i]));
return d;
}
static void *root (void *n)
{
int this = (int) n;
int next = (this + 1) % 256;
int i, sum, token;
send_to (next, 1);
token = recv_from (this);
fprintf (stdout, "start\\n");
fflush (stdout);
for (i = 0; i < tokens; ++i)
send_to (next, i + 1);
while (cycles > 0) {
for (i = 0; i < tokens; ++i) {
token = recv_from (this);
send_to (next, token + 1);
}
cycles--;
}
sum = 0;
for (i = 0; i < tokens; ++i)
sum += recv_from (this);
fprintf (stdout, "end\\n");
fflush (stdout);
fprintf (stdout, "%d\\n", sum);
send_to (next, 0);
token = recv_from (this);
return 0;
}
static void *element (void *n)
{
int this = (int) n;
int next = (this + 1) % 256;
int token;
do {
token = recv_from (this);
send_to (next, token > 0 ? token + 1 : token);
} while (token);
return 0;
}
int main (int argc, char *argv[])
{
int i;
if (argc >= 2)
cycles = atoi (argv[1]);
else
cycles = 0;
if (argc >= 3)
tokens = atoi (argv[2]);
else
tokens = 1;
for (i = 0; i < 256; ++i)
full[i] = data[i] = 0;
for (i = 256 - 1; i >= 0; --i) {
pthread_mutex_init (&(mutex[i]), 0);
pthread_cond_init (&(cond[i]), 0);
if (i == 0)
pthread_create (&(thread[i]), 0, root, (void *)i);
else
pthread_create (&(thread[i]), 0, element, (void *)i);
}
pthread_join (thread[0], 0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_cond_t condicao_cheio, condicao_vazio;
pthread_mutex_t mutex_contador;
pthread_t threadProdutora, threadConsumidora;
int contador;
void * produtor (void* );
void * consumidor (void *);
void produzir(void);
void consumir(void);
int main(){
pthread_mutex_init(&mutex_contador, 0);
pthread_cond_init(&condicao_vazio,0);
pthread_cond_init(&condicao_cheio,0);
pthread_create(&threadProdutora,0,&produtor,0);
pthread_create(&threadConsumidora,0,&consumidor,0);
pthread_join(threadProdutora, 0);
pthread_join(threadConsumidora, 0);
return 0;
}
void * produtor(void *arg){
while(1){
produzir();
}
}
void * consumidor(void *arg){
while(1){
consumir();
}
}
void produzir(void){
pthread_mutex_lock(&mutex_contador);
if(contador==100){
printf("Vai esperar o cheio\\n");
pthread_cond_wait(&condicao_cheio, &mutex_contador);
}
contador++;
printf("contador: %d\\n", contador);
if(contador==1){
printf("Vai sinalizar para o vazio\\n");
pthread_cond_signal(&condicao_vazio);
}
pthread_mutex_unlock(&mutex_contador);
}
void consumir(void){
pthread_mutex_lock(&mutex_contador);
if(contador==0){
printf("Vai esperar para o vazio\\n");
pthread_cond_wait(&condicao_vazio, &mutex_contador);
}
contador--;
printf("contador: %d\\n", contador);
if(contador==100 -1){
printf("Vai sinalizar para o cheio\\n");
pthread_cond_signal(&condicao_cheio);
}
pthread_mutex_unlock(&mutex_contador);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
void *thread_1(void *arg)
{
pthread_mutex_lock(&mutex);
DPRINTF(stdout,"Thread 1 locked the mutex\\n");
pthread_exit(0);
return 0;
}
void *thread_2(void *arg)
{
int rc;
pthread_t self = pthread_self();
int policy = SCHED_FIFO;
struct sched_param param;
memset(¶m, 0, sizeof(param));
param.sched_priority = sched_get_priority_min(policy);
rc = pthread_setschedparam(self, policy, ¶m);
if (rc != 0) {
EPRINTF("UNRESOLVED: pthread_setschedparam %d %s",
rc, strerror(rc));
exit(UNRESOLVED);
}
rc = pthread_mutex_lock(&mutex);
if (rc != EOWNERDEAD) {
EPRINTF("FAIL: pthread_mutex_lock didn't return EOWNERDEAD");
exit(FAIL);
}
DPRINTF(stdout,"Thread 2 lock the mutex and return EOWNERDEAD\\n");
pthread_mutex_unlock(&mutex);
rc = pthread_mutex_lock(&mutex);
if (rc != EOWNERDEAD) {
EPRINTF("FAIL:The mutex shall remain the state EOWNERDEAD "
"after unlocking in x-mode");
pthread_mutex_unlock(&mutex);
exit(FAIL);
}
pthread_exit(0);
return 0;
}
int main()
{
pthread_mutexattr_t attr;
pthread_t threads[2];
pthread_attr_t threadattr;
int rc;
rc = pthread_mutexattr_init(&attr);
if (rc != 0) {
EPRINTF("UNRESOLVED: pthread_mutexattr_init %d %s",
rc, strerror(rc));
return UNRESOLVED;
}
rc = pthread_mutexattr_setrobust_np(&attr,
PTHREAD_MUTEX_ROBUST_NP);
if (rc != 0) {
EPRINTF("UNRESOLVED: pthread_mutexattr_setrobust_np %d %s",
rc, strerror(rc));
return UNRESOLVED;
}
rc = pthread_mutex_init(&mutex, &attr);
if (rc != 0) {
EPRINTF("UNRESOLVED: pthread_mutex_init %d %s",
rc, strerror(rc));
return UNRESOLVED;
}
rc = pthread_attr_init(&threadattr);
if (rc != 0) {
EPRINTF("UNRESOLVED: pthread_attr_init %d %s",
rc, strerror(rc));
return UNRESOLVED;
}
rc = pthread_create(&threads[0], &threadattr, thread_1, 0);
if (rc != 0) {
EPRINTF("UNRESOLVED: pthread_create %d %s",
rc, strerror(rc));
return UNRESOLVED;
}
pthread_join(threads[0], 0);
DPRINTF(stdout,"Thread 1 exited without unlocking...\\n");
rc = pthread_create(&threads[1], &threadattr, thread_2, 0);
if (rc != 0) {
EPRINTF("UNRESOLVED: pthread_create %d %s",
rc, strerror(rc));
return UNRESOLVED;
}
pthread_join(threads[1], 0);
DPRINTF(stdout,"Thread 2 exited ...\\n");
DPRINTF(stdout,"Test PASSED\\n");
return PASS;
}
| 1
|
#include <pthread.h>
int reader_count = 0;
int writer = 0;
pthread_mutex_t rw_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t rw_cond = PTHREAD_COND_INITIALIZER;
void start_read(void) {
pthread_mutex_lock(&rw_mutex);
reader_count = reader_count + 1;
while(writer == 1) {
pthread_cond_wait(&rw_cond, &rw_mutex);
}
pthread_mutex_unlock(&rw_mutex);
}
void end_read(void) {
pthread_mutex_lock(&rw_mutex);
reader_count = reader_count - 1;
pthread_cond_broadcast(&rw_cond);
pthread_mutex_unlock(&rw_mutex);
}
void start_write(void) {
pthread_mutex_lock(&rw_mutex);
while((reader_count > 0) || (writer == 1)) {
pthread_cond_wait(&rw_cond, &rw_mutex);
}
writer = 1;
pthread_mutex_unlock(&rw_mutex);
}
void end_write(void) {
pthread_mutex_lock(&rw_mutex);
writer = 0;
pthread_cond_broadcast(&rw_cond);
pthread_mutex_unlock(&rw_mutex);
}
static char** split_string(char* str, int* nb_found)
{
int count=0;
int start=0;
int i=0;
char **result=0;
for(i=0; i< strlen(str); i++){
if(!strncmp(&str[i], BABBLE_DELIMITER, 1)){
if(i-start > 0){
count++;
result = realloc(result, sizeof(char*)*count);
char* new_item = malloc(sizeof(char*) * BABBLE_BUFFER_SIZE);
bzero(new_item, BABBLE_BUFFER_SIZE);
strncpy(new_item, &str[start], i-start);
result[count-1]=new_item;
}
start = i+1;
}
}
if(strlen(str)-start > 0){
count++;
result = realloc(result, sizeof(char*)*count);
char* new_item = malloc(sizeof(char*) * BABBLE_BUFFER_SIZE);
bzero(new_item, BABBLE_BUFFER_SIZE);
strncpy(new_item, &str[start], strlen(str)-start);
result[count-1]=new_item;
}
*nb_found = count;
return result;
}
static void free_split_array(char** array, int size)
{
int i=0;
for(i=0; i<size; i++){
free(array[i]);
}
free(array);
}
unsigned long hash(char *str){
unsigned long hash = 5381;
int c;
while ((c = *str++) != 0){
hash = ((hash << 5) + hash) + c;
}
return hash;
}
int str_to_command(char* str, int* ack_req)
{
int nb_items=0;
char** items=split_string(str, &nb_items);
int cid_index=0;
if(nb_items == 0){
fprintf(stderr,"Error -- invalid request -> %s\\n", str);
return -1;
}
if(strlen(items[0]) == 1 && items[0][0] == 'S'){
*ack_req=0;
cid_index=1;
}
else{
*ack_req=1;
}
if(strlen(items[cid_index]) == 1){
int res = atoi(items[cid_index]);
if( res < LOGIN || res > RDV){
fprintf(stderr,"Error -- invalid request -> %s\\n", str);
free_split_array(items, nb_items);
return -1;
}
if(res == LOGIN || res == TIMELINE || res == FOLLOW_COUNT || res == RDV){
if(*ack_req == 0){
fprintf(stderr,"Error -- invalid request -> %s\\n", str);
free_split_array(items, nb_items);
return -1;
}
}
free_split_array(items, nb_items);
return res;
}
if(!strcmp(items[cid_index], "LOGIN")){
free_split_array(items, nb_items);
if(*ack_req == 0){
fprintf(stderr,"Error -- invalid request -> %s\\n", str);
return -1;
}
return LOGIN;
}
if(!strcmp(items[cid_index], "PUBLISH")){
free_split_array(items, nb_items);
return PUBLISH;
}
if(!strcmp(items[cid_index], "FOLLOW")){
free_split_array(items, nb_items);
return FOLLOW;
}
if(!strcmp(items[cid_index], "TIMELINE")){
free_split_array(items, nb_items);
if(*ack_req == 0){
fprintf(stderr,"Error -- invalid request -> %s\\n", str);
return -1;
}
return TIMELINE;
}
if(!strcmp(items[cid_index], "FOLLOW_COUNT")){
free_split_array(items, nb_items);
if(*ack_req == 0){
fprintf(stderr,"Error -- invalid request -> %s\\n", str);
return -1;
}
return FOLLOW_COUNT;
}
if(!strcmp(items[cid_index], "RDV")){
free_split_array(items, nb_items);
return RDV;
}
free_split_array(items, nb_items);
return -1;
}
int str_to_payload(char* input, char* output, int size)
{
int nb_items=0;
char **items=split_string(input, &nb_items);
int p_index=1;
if(strlen(items[0]) == 1 && items[0][0] == 'S'){
p_index=2;
}
if(nb_items <= p_index){
fprintf(stderr,"Error -- invalid payload -> %s\\n", input);
free_split_array(items, nb_items);
return -1;
}
int payload_size = strlen(items[p_index]);
if(payload_size > size){
payload_size = size;
fprintf(stderr," Warning -- truncated msg");
}
bzero(output, size);
strncpy(output, items[p_index], payload_size);
free_split_array(items, nb_items);
return 0;
}
void str_clean(char* str)
{
char* found= strstr(str, "\\r");
if(found){
*found='\\0';
}
found= strstr(str, "\\n");
if(found){
*found='\\0';
}
}
unsigned long parse_login_ack(char* ack_msg)
{
char* key_part=strstr(ack_msg, "key");
unsigned long key=0;
if(key_part==0){
return 0;
}
sscanf(key_part,"key %lu\\n", &key);
return key;
}
int parse_fcount_ack(char* ack)
{
char* part=strstr(ack, "has");
int nb_followers=0;
if(part==0){
return -1;
}
sscanf(part,"has %d followers\\n", &nb_followers);
return nb_followers;
}
| 0
|
#include <pthread.h>
int word_len;
long start,end;
double cost_time;
void *count(void *m);
void *total(void *m);
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int main(int argc,char *argv[])
{
start = clock();
if(argc<3){
printf("error \\n");
return 0;
}
pthread_t tid1,tid2,tid3;
pthread_create(&tid1,0,count,argv[1]);
pthread_create(&tid2,0,count,argv[2]);
pthread_join(tid1,0);
pthread_join(tid2,0);
end = clock();
cost_time = (double)(end - start)/CLOCKS_PER_SEC;
printf("cose time is : %lf\\n",cost_time);
}
void *count(void *m)
{
char * string=m;
int i = 0;
int chars = 0;
pthread_mutex_lock(&lock);
printf("This is the thread1 : %s\\n",string);
while(isalnum(string[i])){
printf("%c\\n",string[i]);
i++;
}
word_len = i;
pthread_mutex_unlock(&lock);
total(0);
pthread_exit(0);
}
void *total(void *m)
{
printf("word_len = %d\\n",word_len);
if(word_len > 7)
printf("The word is too long\\n");
else if(word_len < 4)
printf("word is too short\\n");
else
printf("lenth is normal\\n");
}
| 1
|
#include <pthread.h>
sem_t sem;
struct msgs{
long msgtype;
char msg_text[512];
};
static int num = 2;
struct prodcons
{
char buf[512];
pthread_mutex_t lock;
int readpos, writepos;
pthread_cond_t notempty;
pthread_cond_t notfull;
};
struct prodcons buffer;
void init(struct prodcons * b)
{
pthread_mutex_init(&b->lock,0);
pthread_cond_init(&b->notempty,0);
pthread_cond_init(&b->notfull, 0);
b->readpos = 0;
b->writepos = 0;
}
void put(struct prodcons *p,void * message)
{
char date[512];
memset(date, 0x00, 512);
memcpy(date,(char *)message, sizeof(message));
pthread_mutex_lock(&p->lock);
if((p->writepos-1) == p->readpos)
{
pthread_cond_wait(&p->notfull,&p->lock);
}
memcpy(&p->buf[p->writepos] , (char *)message, strlen((char *)message));
printf("message is put : %s \\n",&p->buf[p->writepos]);
p->writepos++;
if(p->writepos >= 1)
p->writepos = 0;
pthread_cond_signal(&p->notempty);
pthread_mutex_unlock(&p->lock);
}
void * get(struct prodcons *b )
{
char date[512];
memset(date, 0x00, 512);
memset(date, 0x00, 512);
pthread_mutex_lock(&b->lock);
if(b->writepos == b->readpos)
{
pthread_cond_wait(&b->notempty,&b->lock);
}
strcpy(date, &(b->buf[b->readpos]));
printf("message is get : %s \\n",(char *)date);
b->readpos++;
if(b->readpos >=1)
b->readpos = 0;
pthread_cond_signal(&b->notfull);
pthread_mutex_unlock(&b->lock);
}
void * product(void * arg)
{
sem_wait(&sem);
while(1)
{
printf("message is product : %s \\n",(char *)arg);
put(&buffer,arg);
sem_wait(&sem);
}
}
void *consumer()
{
while(1)
{
get(&buffer);
}
}
int main()
{
pthread_t pthread_id[num];
int ret;
int i;
struct msgs msg;
key_t key;
ret = sem_init(&sem, 0, 0);
if(ret == -1)
{
perror("semaphore intitialization failed\\n");
exit(1);
}
int pid;
init(&buffer);
for(i = 0; i < num; i++)
{
ret = pthread_create(&pthread_id[i], 0, (void*)product,(void *)msg.msg_text);
if(ret != 0 )
{
printf("pthread_create error\\n");
return -1;
}
}
for(i = 0; i < num ;i++)
{
ret = pthread_create(&pthread_id[i], 0, (void*)consumer,0);
if(ret != 0 )
{
printf("pthread_create error\\n");
return -1;
}
}
while(1)
{
pid = msgget(1024,IPC_CREAT | 0666);
if(msgrcv(pid,(void *)&msg, 512,0,0) < 0)
{
printf(" msg failed,errno=%d[%s]\\n",errno,strerror(errno));
}
sem_post(&sem);
}
return 0;
}
| 0
|
#include <pthread.h>
int ITERS = 6;
int SLOWNESS = 30000;
int NUM_R = 7;
int NUM_W = 3;
char BUFFER[35 + 1];
pthread_mutex_t r_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t rw_lock = PTHREAD_MUTEX_INITIALIZER;
int read_count = 0;
void rest() {
usleep(SLOWNESS * (rand() % (NUM_R + NUM_W)));
}
void* reader(void *arg) {
char buff[35 + 1];
buff[35] = '\\0';
srand( (unsigned int) (intptr_t) &arg);
int i, j;
for (i = 0; i < ITERS; i++) {
rest();
pthread_mutex_lock(&r_lock);
read_count++;
if (read_count == 1) pthread_mutex_lock(&rw_lock);
pthread_mutex_unlock(&r_lock);
for (j = 0; j < 35; j++) {
buff[j] = BUFFER[j];
usleep(SLOWNESS / 35);
}
printf("[R%ld] got: %s\\n", (intptr_t) arg, buff);
pthread_mutex_lock(&r_lock);
read_count--;
if (read_count == 0) pthread_mutex_unlock(&rw_lock);
pthread_mutex_unlock(&r_lock);
}
return 0;
}
void *writer(void *arg) {
srand( (unsigned int)(intptr_t) &arg);
int i, j;
for (i = 0; i < ITERS; i++) {
rest();
pthread_mutex_lock(&rw_lock);
for (j = 0; j < 35; j++) {
BUFFER[j] = 'a' + i;
usleep(1);
}
printf("[W%ld] put: %s\\n", (intptr_t) arg, BUFFER);
pthread_mutex_unlock(&rw_lock);
}
return 0;
}
int main(int argc, char **argv) {
void *result;
pthread_t readers[NUM_R], writers[NUM_W];
memset(BUFFER, 'X', sizeof BUFFER);
BUFFER[35] = '\\0';
int i = 0;
while (i < NUM_R) {
if (pthread_create(readers + i, 0, reader, (void *) (intptr_t) i) != 0) {
perror("pthread create");
exit(-1);
}
i++;
}
i = 0;
while (i < NUM_W) {
if (pthread_create(writers + i, 0, writer, (void *) (intptr_t) i) != 0) {
perror("pthread create");
exit(-1);
}
i++;
}
i = 0;
while (i < NUM_W) {
pthread_join(writers[i], &result);
printf("Joined %d with status: %ld\\n", i, (intptr_t) result);
i++;
}
i = 0;
while (i < NUM_R) {
pthread_join(readers[i], &result);
printf("Joined %d with status: %ld\\n", i, (intptr_t) result);
i++;
}
return 0;
}
| 1
|
#include <pthread.h>
struct msg{
struct msg *next;
int num;
};
struct msg *head;
struct msg *mp;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *con(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
while (head == 0)
{
pthread_cond_wait(&cond, &mutex);
}
mp = head;
head = mp->next;
pthread_mutex_unlock(&mutex);
printf("consume --- %d\\n", mp->num);
free(mp);
sleep(rand() % 5);
}
}
void *pro(void *arg)
{
while(1)
{
mp = malloc(sizeof(struct msg));
mp->num = rand() % 1000 + 1;
printf("product --- %d\\n", mp->num);
pthread_mutex_lock(&mutex);
mp->next = head;
head = mp;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
sleep(rand() % 5);
}
}
int main()
{
pthread_t ptid, ctid;
pthread_create(&ptid, 0, pro, 0);
pthread_create(&ctid, 0, con, 0);
pthread_join(ptid, 0);
pthread_join(ctid, 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
| 0
|
#include <pthread.h>
int clnt_cnt = 0;
int clnt_socks[256];
pthread_mutex_t mutx;
void send_msg(char *msg, int len) {
int i;
pthread_mutex_lock(&mutx);
for (i = 0; i < clnt_cnt; i++) {
write(clnt_socks[i], msg, len);
}
pthread_mutex_unlock(&mutx);
}
void *handle_clnt(void *arg) {
int clnt_sock = *((int *)arg);
int str_len = 0, i;
char msg[100];
while ((str_len = read(clnt_sock, msg, sizeof(msg))) != 0 ) {
send_msg(msg, str_len);
}
pthread_mutex_lock(&mutx);
for (i = 0; i < clnt_cnt; i++) {
if (clnt_sock == clnt_socks[i]) {
while (i++ < clnt_cnt - 1) {
clnt_socks[i] = clnt_socks[i + 1];
}
break;
}
}
clnt_cnt--;
pthread_mutex_unlock(&mutx);
close(clnt_sock);
return 0;
}
void error_handling(char *msg) {
fputs(msg, stderr);
fputc('\\n', stderr);
exit(1);
}
int main(int argc, char **argv) {
int serv_sock, clnt_sock;
struct sockaddr_in serv_addr, clnt_addr;
int clnt_addr_sz;
pthread_t t_id;
if (argc != 2) {
printf("Usage : %s <port>\\n", argv[0]);
exit(1);
}
pthread_mutex_init(&mutx, 0);
serv_sock = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(atoi(argv[1]));
if (bind(serv_sock, (struct sockaddr *) &serv_addr, sizeof (serv_addr)) == -1) {
error_handling("bind() error");
}
if (listen(serv_sock, 5) == -1) {
error_handling("listen() error");
}
while (1) {
clnt_addr_sz = sizeof(clnt_addr);
clnt_sock = accept(serv_sock, (struct sockaddr *) &clnt_addr, &clnt_addr_sz);
pthread_mutex_lock(&mutx);
clnt_socks[clnt_cnt++] = clnt_sock;
pthread_mutex_unlock(&mutx);
pthread_create(&t_id, 0, handle_clnt, (void *) &clnt_sock);
pthread_detach(t_id);
printf("Connected client IP: %s\\n", inet_ntoa(clnt_addr.sin_addr));
}
close(serv_sock);
return 0;
}
| 1
|
#include <pthread.h>
unsigned int textureID;
float vertices[] =
{0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f};
float texture[] =
{0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f};
unsigned char indices[] =
{0, 1, 3, 0, 3, 2};
int texWidth, texHeight, stupidTegra;
void glInit()
{
glShadeModel(GL_FLAT);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glEnable(GL_TEXTURE_2D);
glDisable(GL_DEPTH_TEST);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
texWidth = 1;
texHeight = 1;
while((texWidth = texWidth << 1) < (screenWidth-screenWidth%zoomFactor));
while((texHeight = texHeight << 1) < (screenHeight-screenHeight%zoomFactor));
char* emptyPixels = malloc(3 * texWidth*texHeight * sizeof(char));
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texWidth, texHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, emptyPixels);
free(emptyPixels);
glVertexPointer(2, GL_FLOAT, 0, vertices);
glTexCoordPointer(2, GL_FLOAT, 0, texture);
}
void glRender()
{
if(dimensionsChanged)
{
__android_log_write( ANDROID_LOG_INFO, "TheElements", "dimensions changed" );
vertices[2] = (float) screenWidth;
vertices[5] = (float) screenHeight;
vertices[6] = (float) screenWidth;
vertices[7] = (float) screenHeight;
texture[2] = (float) workWidth/texWidth;
texture[5] = (float) workHeight/texHeight;
texture[6] = (float) workWidth/texWidth;
texture[7] = (float) workHeight/texHeight;
dimensionsChanged = FALSE;
zoomChanged = FALSE;
}
else if(zoomChanged)
{
texture[2] = (float) workWidth/texWidth;
texture[5] = (float) workHeight/texHeight;
texture[6] = (float) workWidth/texWidth;
texture[7] = (float) workHeight/texHeight;
zoomChanged = FALSE;
}
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float modViewWidth = viewWidth/2 * zoomScale;
float modViewHeight = viewHeight/2 * zoomScale;
float left = centerX - modViewWidth;
float right = centerX + modViewWidth;
float top = centerY - modViewHeight;
float bottom = centerY + modViewHeight;
if (!flipped)
{
glOrthof(left, right, bottom, top, -1.0f, 1.0f);
}
else
{
glOrthof(left, right, bottom, -1*top, -1.0f, 1.0f);
}
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(1,1,1,1);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, stupidTegra, workHeight, GL_RGB, GL_UNSIGNED_BYTE, colorsFrameBuffer);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, indices);
}
void glRenderThreaded()
{
pthread_mutex_lock(&frame_ready_mutex);
while (!frameReady)
{
pthread_cond_wait(&frame_ready_cond, &frame_ready_mutex);
}
frameReady = FALSE;
pthread_mutex_unlock(&frame_ready_mutex);
glRender();
pthread_mutex_lock(&buffer_free_mutex);
if (!bufferFree)
{
bufferFree = TRUE;
pthread_cond_signal(&buffer_free_cond);
}
pthread_mutex_unlock(&buffer_free_mutex);
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
void
prepare(void)
{
printf("preparing locks...\\n");
pthread_mutex_lock(&lock1);
pthread_mutex_lock(&lock2);
}
void
parent(void)
{
printf("parent unlocking locks...\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void
child(void)
{
printf("child unlocking locks...\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void *
thr_fn(void *arg)
{
printf("thread started...\\n");
pause();
return(0);
}
int
main(void)
{
int err;
pid_t pid;
pthread_t tid;
if ((err = pthread_atfork(prepare, parent, child)) != 0) {
printf("can't install fork handlers");
exit(0);
}
err = pthread_create(&tid, 0, thr_fn, 0);
if (err != 0) {
printf("can't create thread");
exit(0);
}
sleep(2);
printf("parent about to fork...\\n");
if ((pid = fork()) < 0) {
printf("fork failed\\n");
exit(0);
} else if (pid == 0) {
printf("child returned from fork\\n");
} else {
printf("parent returned from fork\\n");
}
}
| 1
|
#include <pthread.h>
char _buffer[50][30];
int _nbmess = 0;
pthread_cond_t _full_buff = PTHREAD_COND_INITIALIZER;
pthread_cond_t _empty_buff = PTHREAD_COND_INITIALIZER;
pthread_mutex_t _mut = PTHREAD_MUTEX_INITIALIZER;
void * Ecriture(void * arg)
{
int index_ecriture = 0;
while(1)
{
pthread_mutex_lock(&_mut);
while(_nbmess == 50)
{
pthread_cond_wait(&_full_buff, &_mut);
}
sprintf(_buffer[index_ecriture],"il y a %d voitures",index_ecriture);
_nbmess ++;
index_ecriture = (index_ecriture+1)%50;
pthread_cond_signal(&_empty_buff);
pthread_mutex_unlock(&_mut);
sleep(1);
}
}
void * Lecture(void * arg)
{
int index_lecture = 0;
while(1)
{
pthread_mutex_lock(&_mut);
while(_nbmess == 0)
{
pthread_cond_wait(&_empty_buff, &_mut);
}
printf("%s\\n",_buffer[index_lecture]);
index_lecture = (index_lecture+1)%50;
_nbmess --;
pthread_cond_signal(&_full_buff);
pthread_mutex_unlock(&_mut);
sleep(1);
}
}
int main(void)
{
pthread_t threadEcriture, threadLecture;
if(pthread_create(&threadEcriture,0,Ecriture,0)!=0)
{
perror("creation thread entrée");
exit(1);
}
if(pthread_create(&threadLecture,0,Lecture,0)!=0)
{
perror("creation thread entrée");
exit(1);
}
pthread_join(threadEcriture,0);
pthread_join(threadLecture,0);
printf("fin main\\n");
return 0;
}
| 0
|
#include <pthread.h>
int ticks = 0;
pthread_t thread[1];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t wakeupsig = PTHREAD_COND_INITIALIZER;
void* time_triggered_thread(){
char buff[100];
time_t now = time (0);
pthread_mutex_lock(&mutex);
while(1){
pthread_cond_wait(&wakeupsig, &mutex);
now = time(0);
strftime (buff, 100, "%Y-%m-%d %H:%M:%S.000", localtime (&now));
printf ("%s\\n", buff);
}
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void alarm_handler(int sino)
{
pthread_mutex_lock(&mutex);
ticks ++;
if(ticks%100 == 0){
ticks = 0;
pthread_cond_signal(&wakeupsig);
}
pthread_mutex_unlock(&mutex);
signal(SIGALRM, alarm_handler);
}
int main (int argc, char * argv[]){
printf("%d\\n", 46);
signal(SIGALRM, alarm_handler);
printf("%d\\n", 48);
struct itimerval delay;
int rc;
int ret;
delay.it_value.tv_sec = 0;
delay.it_value.tv_usec = 10000;
delay.it_interval.tv_sec= 0;
delay.it_interval.tv_usec = 10000;
rc = pthread_create(&thread[0], 0, time_triggered_thread, 0);
ret = setitimer(ITIMER_REAL, &delay, 0);
while(1)
{
pause();
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t gMutex;
static long num_steps=10000000;
double step, pi,sum = 0.0;
void *Pi(void* arg)
{
int* p = (int*)arg;
int parametro = *p, i;
double x;
for (i=parametro; i< num_steps; i=i+2)
{
x = (i+0.5)*step;
pthread_mutex_lock( &gMutex );
sum = sum + 4.0/(1.0 + x*x);
pthread_mutex_unlock( &gMutex );
}
return 0;
}
int main()
{
time_t t1,t2;
t1=0,t2=0;
t1=clock();
int i,numero[2];
pthread_t tid[2];
step = 1.0/(double) num_steps;
pthread_mutex_init( &gMutex, 0 );
for(i=0;i<2;i++)
{
numero[i]=i;
pthread_create(&tid[i], 0, Pi, &numero[i]);
}
for(i=0;i<2;i++)
{
pthread_join(tid[i], 0);
}
pi = step * sum;
printf("Pi = %.13f\\n",pi);
t2=clock();
float total = (t2-t1)/(double) CLOCKS_PER_SEC;
printf("tiempo: %f\\n", total);
system("PAUSE");
exit(0);
return 1;
}
| 0
|
#include <pthread.h>
int cliente;
sem_t pedido;
}TVENDEDOR;
TVENDEDOR vendedores[4] = {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){
printf("Pedido Feito\\n");
}
void *vendedor(void *args){
int id = *((int*)args);
while (1) {
pthread_mutex_lock(&mutex_proximo);
if(proximo > 17){
break;
}
if ((proximo % 4) == (id)) {
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 < 4; 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[]){
int i;
pthread_t threads_vendedores[4], threads_clientes[17];
for(i = 0; i < 4; 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(i = 0; i < 17; i++){
int r = pthread_create(&threads_clientes[i], 0, cliente, 0);
if(r) {
exit(1);
}
}
for(i=0; i < 4; i++) {
pthread_join(threads_vendedores[i], 0);
}
for(i=0; i < 17; i++) {
pthread_join(threads_clientes[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
char chDbgBuf[8192];
static FILE *pFile = 0;
static pthread_mutex_t tDebuggerMutex = PTHREAD_MUTEX_INITIALIZER;
void StartDebugger()
{
pFile = fopen("debug.log","w");
}
void OutputDebugString(char *pcString)
{
pthread_mutex_lock( &tDebuggerMutex );
if (pFile == 0)
{
pFile = fopen("debug.log","w");
}
if (pFile != 0)
{
fprintf(pFile, pcString);
fprintf(pFile, "\\n");
fflush(pFile);
}
pthread_mutex_unlock( &tDebuggerMutex );
}
void StopDebugger()
{
pthread_mutex_lock( &tDebuggerMutex );
if (pFile != 0)
{
fflush(pFile);
fclose(pFile);
pFile = 0;
}
pthread_mutex_unlock( &tDebuggerMutex );
pthread_mutex_destroy( &tDebuggerMutex );
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock;
int fd;
char buf[100];
void* writeit()
{
pthread_mutex_lock(&lock);
printf("Enter data to send to client.\\n");
fgets(buf,100,stdin);
int wret=write(fd,buf,100);
if(wret<0)
{
printf("Failed to Write.\\n");
close(fd);
pthread_mutex_unlock(&lock);
exit(0);
}
else
{
printf("Sent data to client: %s",buf);
close(fd);
}
pthread_mutex_unlock(&lock);
}
void* readit()
{
pthread_mutex_lock(&lock);
int rret=read(fd,buf,100);
if(rret<0)
{
printf("Failed to Read.\\n");
close(fd);
unlink("datafile");
pthread_mutex_unlock(&lock);
exit(0);
}
else
{
printf("Client says: %s",buf);
close(fd);
}
pthread_mutex_unlock(&lock);
}
int main(int argc, char *argv[])
{
pthread_t thread1, thread2;
while(1)
{
fd=open("datafile",O_WRONLY);
if(fd<0)
{
printf("Failed to open file.\\n");
close(fd);
exit(0);
}
else
{
int ret1=pthread_create(&thread1,0,writeit,0);
if(ret1<0)
{
printf("Failed to create threads.\\n");
exit(0);
}
int retj1=pthread_join(thread1,0);
if(retj1<0)
{
printf("Failed to join threads.\\n");
exit(0);
}
}
int ret=mkfifo("datafile",0600);
fd=open("datafile",O_RDONLY);
if(fd<0)
{
printf("Failed to open file.\\n");
exit(0);
}
else
{
int ret2=pthread_create(&thread2,0,readit,0);
if(ret2<0)
{
printf("Failed to create threads.\\n");
exit(0);
}
int retj2=pthread_join(thread2,0);
if(retj2<0)
{
printf("Failed to join threads.\\n");
exit(0);
}
}
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_t philosopher[20];
pthread_mutex_t forks[20];
sem_t s;
unsigned int randr (unsigned int min, unsigned int max)
{
double scaled = (double)rand()/32767;
return scaled*(max - min + 1) + min;
}
void *func(void *id){
long n = (long)id;
while(1){
printf("\\nPhilosopher %ld is thinking ",n);
sleep(randr(1,4));
sem_wait(&s);
pthread_mutex_lock(&forks[n]);
pthread_mutex_lock(&forks[(n+1)%20]);
printf("\\nPhilosopher %ld is eating ",n);
sleep(randr(1,4));
pthread_mutex_unlock(&forks[n]);
pthread_mutex_unlock(&forks[(n+1)%20]);
sem_post(&s);
printf("\\nPhilosopher %ld Finished eating ",n);
}
}
int main(){
sem_init(&s,0,20 -1);
long i,k;
void *msg;
srand(time(0));
for(i=1;i<=20;i++)
{
k=pthread_mutex_init(&forks[i],0);
if(k==-1) {
printf("\\n Mutex initialization failed");
exit(1);
}
}
for(i=1;i<=20;i++){
k=pthread_create(&philosopher[i],0,(void *)func,(void *)i);
if(k!=0){
printf("\\n Thread creation error \\n");
exit(1);
}
}
for(i=1;i<=20;i++){
k=pthread_join(philosopher[i],&msg);
if(k!=0){
printf("\\n Thread join failed \\n");
exit(1);
}
}
for(i=1;i<=20;i++){
k=pthread_mutex_destroy(&forks[i]);
if(k!=0){
printf("\\n Mutex Destroyed \\n");
exit(1);
}
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t cnt_mutex;
sem_t sem_write;
sem_t pre;
int reader_count = 0;
int content = 1;
pthread_t readers[10];
void * writer_func()
{
printf("writer start\\n");
while (1)
{
sem_wait(&pre);
sem_wait(&sem_write);
content++;
printf("writer: %d\\n", content);
sem_post(&sem_write);
sem_post(&pre);
}
pthread_exit(0);
}
void * reader_func(void * n)
{
printf("reader start\\n");
while (1)
{
sem_wait(&pre);
pthread_mutex_lock(&cnt_mutex);
if (reader_count == 0)
sem_wait(&sem_write);
reader_count++;
pthread_mutex_unlock(&cnt_mutex);
sem_post(&pre);
printf("cur reader count:%d read_v:%d\\n", reader_count, content);
pthread_mutex_lock(&cnt_mutex);
reader_count--;
if (reader_count == 0)
sem_post(&sem_write);
pthread_mutex_unlock(&cnt_mutex);
}
pthread_exit(0);
}
int main(int argc, char const* argv[])
{
pthread_t writer;
pthread_t reader;
sem_init(&sem_write, 0, 1);
sem_init(&pre, 0, 1);
pthread_create(&writer, 0, writer_func, 0);
pthread_create(&reader, 0, reader_func, 0);
pthread_join(writer, 0);
pthread_join(reader, 0);
printf("process exit\\n");
return 0;
}
| 1
|
#include <pthread.h>
static bool isFimglibInit = 0;
static pthread_mutex_t instanceLock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t sharedLock;
static int g2dFd;
static unsigned char *g2dVirtualAddress;
static unsigned int g2dSize;
static unsigned char *g2dDestinationVirtualAddress;
static unsigned int g2dDestinationSize;
static struct pollfd g2dPollFd;
static unsigned char *sourceVirtualAddress;
static unsigned int sourceSize;
static bool createContext()
{
if (g2dFd != 0)
{
printf("%s(): m_g2dFd is non-zero\\n", __func__);
return 0;
}
g2dFd = open("/dev/fimg2d", O_RDWR);
if (g2dFd < 0)
{
printf("%s(): open(%s) fail(%s)\\n", __func__, "/dev/fimg2d", strerror(errno));
g2dFd = 0;
return 0;
}
memset(&g2dPollFd, 0, sizeof(g2dPollFd));
g2dPollFd.fd = g2dFd;
g2dPollFd.events = POLLOUT | POLLERR;
return 1;
}
static bool destroyContext(void)
{
if (g2dVirtualAddress != 0)
{
munmap(g2dVirtualAddress, g2dSize);
g2dVirtualAddress = 0;
g2dSize = 0;
}
if (0 < g2dFd)
close(g2dFd);
g2dFd = 0;
return 1;
}
static bool executeIoctl(struct fimg2d_blit *cmd)
{
if (ioctl(g2dFd, FIMG2D_BITBLT_BLIT, cmd) < 0)
return 0;
return 1;
}
inline static bool pollG2D(struct pollfd * events)
{
int ret;
ret = poll(events, 1, 1000);
if (ret < 0)
{
printf("%s(): G2D poll failed\\n", __func__);
return 0;
}
else if (ret == 0)
{
printf("%s(): no data in %d milliseconds\\n", __func__, 1000);
return 0;
}
return 1;
}
bool fimg_init()
{
bool ret = 0;
pthread_mutex_lock(&instanceLock);
if (isFimglibInit)
return 1;
g2dFd = 0;
sourceVirtualAddress = 0;
sourceSize = 0;
g2dDestinationVirtualAddress = 0;
g2dVirtualAddress = 0;
g2dSize = 0;
g2dDestinationSize = 0;
memset(&(g2dPollFd), 0, sizeof(struct pollfd));
pthread_mutexattr_t psharedm;
pthread_mutexattr_init(&psharedm);
pthread_mutexattr_setpshared(&psharedm, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&sharedLock, &psharedm);
pthread_mutex_lock(&sharedLock);
if (createContext() == 0)
{
printf("%s::m_CreateG2D() fail \\n", __func__);
if (destroyContext() == 0)
printf("%s::m_DestroyG2D() fail \\n", __func__);
}
else
{
ret = 1;
isFimglibInit = 1;
}
pthread_mutex_unlock(&sharedLock);
pthread_mutex_unlock(&instanceLock);
return ret;
}
void fimg_deinit()
{
pthread_mutex_lock(&instanceLock);
pthread_mutex_destroy(&sharedLock);
isFimglibInit = 0;
pthread_mutex_unlock(&instanceLock);
printf("%s() complete\\n", __func__);
}
int fimg_stretch_internal(struct fimg2d_blit *cmd)
{
if (!isFimglibInit)
{
printf("%s: fimg not initialized\\n", __func__);
return 0;
}
bool ret = 0;
pthread_mutex_lock(&sharedLock);
if (executeIoctl(cmd))
{
ret = 1;
}
pthread_mutex_unlock(&sharedLock);
return ret;
}
bool fimg_sync(void)
{
if (!isFimglibInit)
{
printf("%s: fimg not initialized\\n", __func__);
return 0;
}
if (pollG2D(&g2dPollFd) == 0)
{
printf("%s::m_PollG2D() fail\\n", __func__);
return 0;
}
return 1;
}
| 0
|
#include <pthread.h>
int hungers[8];
int produced[8];
int indices[8];
int produced_total = 0;
int goods_in_shop = 0;
pthread_mutex_t produce_mutex, shop_mutex, consume_mutex;
pthread_cond_t place_in_shop, anything_in_shop;
void random_delay() {
struct timespec wait_time;
wait_time.tv_sec = 0;
wait_time.tv_nsec = rand() % 10;
nanosleep(&wait_time, 0);
}
void *producer(void *producer_index_ptr) {
int i = *((int *) producer_index_ptr);
int should_produce = 1;
while(should_produce) {
random_delay();
pthread_mutex_lock(&produce_mutex);
while(goods_in_shop >= 128) {
pthread_cond_wait(&place_in_shop, &produce_mutex);
}
if(produced_total >= 100000) {
should_produce = 0;
}
else {
pthread_mutex_lock(&shop_mutex);
produced[i]++;
produced_total++;
goods_in_shop++;
pthread_cond_signal(&anything_in_shop);
if(goods_in_shop > 128) printf("!too mouch goods in shop!\\n");
pthread_mutex_unlock(&shop_mutex);
}
pthread_mutex_unlock(&produce_mutex);
}
return 0;
}
void *consumer(void *consumer_index_ptr) {
int i = *((int *) consumer_index_ptr);
while(hungers[i] > 0) {
random_delay();
pthread_mutex_lock(&consume_mutex);
while(goods_in_shop <= 0) {
pthread_cond_wait(&anything_in_shop, &produce_mutex);
}
pthread_mutex_lock(&shop_mutex);
hungers[i]--;
goods_in_shop--;
pthread_cond_signal(&place_in_shop);
if(goods_in_shop < 0) printf("! less than 0 goods in shop!\\n");
pthread_mutex_unlock(&shop_mutex);
pthread_mutex_unlock(&consume_mutex);
}
return 0;
}
int main() {
srand(time(0));
if(pthread_mutex_init(&produce_mutex, 0)) {
{ fprintf(stderr, "%s: %s\\n", "Mutex initialization failed", strerror(errno)); exit(1); };
}
if(pthread_mutex_init(&consume_mutex, 0)) {
{ fprintf(stderr, "%s: %s\\n", "Mutex initialization failed", strerror(errno)); exit(1); };
}
if(pthread_mutex_init(&shop_mutex, 0)) {
{ fprintf(stderr, "%s: %s\\n", "Mutex initialization failed", strerror(errno)); exit(1); };
}
if(pthread_cond_init(&place_in_shop, 0)) {
{ fprintf(stderr, "%s: %s\\n", "Pthread_cond initialization failed", strerror(errno)); exit(1); };
}
if(pthread_cond_init(&anything_in_shop, 0)) {
{ fprintf(stderr, "%s: %s\\n", "Pthread_cond initialization failed", strerror(errno)); exit(1); };
}
pthread_t threads[16];
int hunger_left = 100000;
for(int i = 0; i < 8; i++) {
if(pthread_create(&threads[i], 0, producer, &indices[i])) {
{ fprintf(stderr, "%s: %s\\n", "Failed to create thread", strerror(errno)); exit(1); };
}
if(i == 7) {
hungers[i] = hunger_left;
}
else {
int v = (100000 / 48);
int h = rand() % (2*v) + (100000 / 8) - v;
hungers[i] = h;
hunger_left -= h;
}
indices[i] = i;
produced[i] = 0;
if(pthread_create(&threads[i+8], 0, consumer, &indices[i])) {
{ fprintf(stderr, "%s: %s\\n", "Failed to create thread", strerror(errno)); exit(1); };
}
}
for(int i = 0; i < 16; i++) {
if(pthread_join(threads[i], 0)) {
{ fprintf(stderr, "%s: %s\\n", "Failed to join thread", strerror(errno)); exit(1); };
}
}
pthread_mutex_destroy(&produce_mutex);
pthread_mutex_destroy(&consume_mutex);
pthread_mutex_destroy(&shop_mutex);
pthread_cond_destroy(&place_in_shop);
pthread_cond_destroy(&anything_in_shop);
printf("Total production: %d goods.\\n", produced_total);
printf("Left in shop: %d goods.\\n", goods_in_shop);
return 0;
}
| 1
|
#include <pthread.h>
int main(int argc, char **argv)
{
if (argc != 2 )
{
printf("Passing arguments does not match with the iPDC inputs! Try Again?\\n");
exit(0);
}
int id,i,port,ret;
char *ptr1,buff[20];
char *l1,*d1,*d2,*d3,*d4;
FILE *fp;
size_t l2=0;
ssize_t result;
id = atoi(argv[1]);
ptr1 = malloc(30*sizeof(char));
memset(ptr1, '\\0', 30);
strcat(ptr1, "iPDC");
sprintf(buff,"%d",id);
strcat(ptr1,buff);
strcat(ptr1, ".csv");
fp = fopen (ptr1,"r");
if (fp != 0)
{
getdelim (&l1, &l2, ('\\n'), fp);
if ((result = getdelim (&l1, &l2, ('\\n'), fp)) >0)
{
d1 = strtok (l1,",");
d1 = strtok (0,",");
PDC_IDCODE = atoi(d1);
d1 = strtok (0,",");
UDPPORT = atoi(d1);
d1 = strtok (0,",");
TCPPORT = atoi(d1);
d1 = strtok (0,",");
memset(dbserver_ip, '\\0', 20);
strcpy(dbserver_ip, (char *)d1);
d1 = strtok (0,",");
surcCount = atoi(d1);
d1 = strtok (0,",");
destCount = atoi(d1);
d1 = strtok (0,",");
int waitTime = atoi(d1);
d1 = strtok (0,",");
if(!strncmp(d1,"YES",3))
{
IamSPDC = 1;
printf("I am SPDC\\n");
d1 = strtok (0,",");
if(!strncmp(d1,"DDS3",4))
buildAppHashTables();
} else {
IamLPDC = 1;
printf("I am LPDC\\n");
}
pthread_mutex_lock(&mutex_Analysis);
first_arrival_lpdc = 9999999;
Min_pmutolpdc = 9999999;
Min_pmutolpdcdelay_sum = 0;
count_patial_computation = 0;
computation_time_sum = 0;
appComputeTime = 0;
dataFrameCreateTime = 0;
flagApps = 0;
VSappTime = 0, SEappTime = 0, CMappTime = 0;
pthread_mutex_unlock(&mutex_Analysis);
setup();
if (surcCount > 0)
{
getdelim (&l1, &l2, ('\\n'), fp);
getdelim (&l1, &l2, ('\\n'), fp);
for (i=0; i<surcCount; i++)
{
if ((result = getdelim (&l1, &l2, ('\\n'), fp)) >0)
{
if(i == 0)
{
d1 = strtok (l1,",");
d1 = strtok (0,",");
}
else
d1 = strtok (l1,",");
d2 = strtok (0,",");
d3 = strtok (0,",");
d4 = strtok (0,",");
ret = add_PMU(d1,d2,d3,d4);
}
}
}
else
{
}
if (destCount > 0)
{
getdelim (&l1, &l2, ('\\n'), fp);
getdelim (&l1, &l2, ('\\n'), fp);
for (i=0; i<destCount; i++)
{
if ((result = getdelim (&l1, &l2, ('\\n'), fp)) >0)
{
if(i == 0)
{
d1 = strtok (l1,",");
d1 = strtok (0,",");
}
else
d1 = strtok (l1,",");
d2 = strtok (0,",");
ret = add_PDC(d1,d2);
}
}
}
else
{
}
}
else
exit(1);
fclose(fp);
}
else
{
}
pthread_join(UDP_thread, 0);
pthread_join(TCP_thread, 0);
pthread_join(p_thread, 0);
close(UL_UDP_sockfd);
close(UL_TCP_sockfd);
return 0;
}
| 0
|
#include <pthread.h>
char buf[10];
int occupied;
int nextin;
int nextout;
pthread_mutex_t mutex;
pthread_cond_t more;
pthread_cond_t less;
} buffer_t;
buffer_t buffer;
void producer(buffer_t *b, char item)
{
pthread_mutex_lock(&b->mutex);
while (b->occupied >= 10)
pthread_cond_wait(&b->less, &b->mutex);
assert(b->occupied < 10);
b->buf[b->nextin++] = item;
b->nextin %= 10;
b->occupied++;
pthread_cond_signal(&b->more);
pthread_mutex_unlock(&b->mutex);
}
char consumer(buffer_t *b)
{
char item;
pthread_mutex_lock(&b->mutex);
while(b->occupied <= 0)
pthread_cond_wait(&b->more, &b->mutex);
assert(b->occupied > 0);
item = b->buf[b->nextout++];
b->nextout %= 10;
b->occupied--;
pthread_cond_signal(&b->less);
pthread_mutex_unlock(&b->mutex);
return(item);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
int sum = 0;
void print_vector(char name, int *v, int size) {
printf("%c = ", name);
int i;
for (i = 0; i < size; i++) {
printf("%i", v[i]);
if (i == size - 1) {
printf(" \\n");
} else {
printf(", ");
}
}
}
int* slice(int offset, int size, int *v) {
int *slice = (int*)malloc(sizeof(int) * size);
int i;
for (i = 0; i < size; i++) {
slice[i] = v[offset + i];
}
return slice;
}
int* vec1;
int* vec2;
int vec_size;
int thread_number;
int offset;
} vec_tpl;
void *calc(void *arg) {
vec_tpl *vecs = (vec_tpl*)arg;
int i;
int partial = 0;
for (i = 0; i < vecs->vec_size; i++) {
partial += vecs->vec1[i] * vecs->vec2[i];
}
pthread_mutex_lock(&mutex);
sum += partial;
pthread_mutex_unlock(&mutex);
printf("Thread %i calculou de %i a %i: produto escalar parcial = %i\\n",
vecs->thread_number,
vecs->offset,
vecs->offset + vecs->vec_size,
partial);
pthread_exit(0);
}
int main(int argc, char const *argv[]) {
if(argv[1]==0 || argv[2]==0){
printf("ERRO: Utilize o formato <nome_do_programa> <vector_size> <num_threads>\\n");
return 1;
}
pthread_mutex_init(&mutex, 0);
int VECSIZE = atoi(argv[1]);
int NTHREADS = atoi(argv[2]);
int vector1[VECSIZE];
int vector2[VECSIZE];
srand(time(0));
int i;
for (i = 0; i < VECSIZE; i++) {
vector1[i] = rand() % 10;
vector2[i] = rand() % 10;
}
print_vector('A', vector1, VECSIZE);
print_vector('B', vector2, VECSIZE);
if (NTHREADS > VECSIZE) {
NTHREADS = VECSIZE;
}
int chunk_size = VECSIZE / NTHREADS;
int rest = VECSIZE % NTHREADS;
vec_tpl subvectors[NTHREADS];
int pos = 0;
for (i = 0; i < NTHREADS; i++) {
int range = chunk_size;
if(rest>0 && i < rest){
range++;
}
subvectors[i].vec1 = slice(pos, range, vector1);
subvectors[i].vec2 = slice(pos, range, vector2);
subvectors[i].vec_size = range;
subvectors[i].thread_number = i+1;
subvectors[i].offset = pos;
pos += range;
}
pthread_t threads[NTHREADS];
for (i = 0; i < NTHREADS; i++) {
pthread_create(&threads[i], 0, calc, (void*)(&subvectors[i]));
}
for (i = 0; i < NTHREADS; i++) {
pthread_join(threads[i], 0);
}
printf("Produto escalar = %i\\n", sum);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
pthread_t thread[3];
pthread_mutex_t mut;
int k = 1;
int *a;
void thread1(void* arg){
int num = *(int*)arg;
for(; k<11; k){
pthread_mutex_lock(&mut);
if( k<11 ) printf("thread %d: k = %-2d\\t\\tthread id: %lu\\n", num, k++, pthread_self());
pthread_mutex_unlock(&mut);
Sleep(1000);
}
printf("thread %d end\\n", num);
pthread_exit(arg);
}
void thread_create(int len){
int temp, i=0;
memset(&thread, 0, sizeof(thread));
for(;i<len;i++){
if((temp = pthread_create(&thread[i], 0, (void *)thread1, (void*)a+(i)*sizeof(int))) != 0){
printf("create thread %d failed\\n", i);
}
}
}
void thread_wait(int len){
int i=0;
char* ret;
for(;i<len;){
if( pthread_join(thread[i], (void**)&ret) == 0 ){
printf("thread %d done\\n", *(int*)ret);
i++;
}
}
}
int* init(int *a, int len){
int i=0;
for(; i<len; i++){
*(a+i) = i+1;
}
return a;
}
int main(int argc, char** argv){
printf("Run in %s, %d\\n", "trd.c", 67);
int len = argc==1 ? 2 : atoi(argv[1]);
a = (int *)calloc(len, sizeof(int));
a = init(a, len);
pthread_mutex_init(&mut, 0);
printf("Prc createing threads...\\n");
thread_create(len);
printf("Prc waiting for threads done...\\n");
thread_wait(len);
pthread_mutex_destroy(&mut);
free(a);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t scan_ready = PTHREAD_COND_INITIALIZER;
void *read_serial(void * arg)
{
int serial_fd = open("/dev/ttyAMA0", O_RDONLY);
struct read_serial_out * out = (struct read_serial_out *)arg;
int16_t * ranges = out->ranges;
double * points = out->points;
char buff[22];
char packet[22];
int read_ahead = 1;
int packet_index = 0;
while(serial_fd)
{
memset(buff, 0, sizeof(buff));
int count = read(serial_fd, buff, read_ahead);
read_ahead -= count;
memcpy(&packet[packet_index], buff, count);
int z;
for (z = 0; z < count; z++)
{
}
for (z = 0; z < 22; z++)
{
}
packet_index += count;
if (buff[0] == 0xfa)
{
read_ahead = 22 - count;
packet_index = count;
}
if (packet_index == 22)
{
int j;
for (j = 0; j < 22; j++)
{
}
if (packet[1] == 0xf9)
{
pthread_mutex_lock(&mutex);
pthread_cond_signal(&scan_ready);
pthread_mutex_unlock(&mutex);
}
pthread_mutex_lock(&mutex);
decode_packet(ranges, points, out->map, packet);
if (packet[1] == 0xf9)
{
pthread_cond_signal(&scan_ready);
}
pthread_mutex_unlock(&mutex);
read_ahead = 22;
packet_index = 0;
}
if (read_ahead == 0)
{
read_ahead = 1;
}
}
printf("failed to open serial port\\n");
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock;
static int asmMutex = 1;
int g = 0;
int correct = 0;
int violations = 0;
int number_threads = 10;
int number_access = 10;
int is_locked = 0;
int is_assembly = 0;
void do_something_clever(int i);
void test_lock(void * i);
void compare_result(int expected_result);
int parse_command_line (int argc, char **argv);
void show_help(void);
int main (int argc, char *argv[]) {
int err;
int i;
int * attr = (int *)malloc((number_threads+1) * sizeof(int));
pthread_t * threads = malloc(sizeof(pthread_t)*number_threads);
parse_command_line(argc, argv);
printf("Number of threads: %d, number od access: %d, with-protection: %d, with assembly: %d\\n", number_threads,number_access, is_locked, is_assembly);
for (i = 0; i < number_threads; i++) {
*(attr++) = i;
err = pthread_create(&threads[i], 0, (void* (*)(void*))test_lock, (void *)attr);
if (err != 0)
printf("I can't create thread :[%d]\\n", err);
}
for (i = 0; i < number_threads; i++) {
pthread_join(threads[i], 0);
}
compare_result(number_threads * number_access);
free(attr - number_threads);
free(threads);
return 0;
}
void do_something_clever(int i){
printf("Thread %d/%d running.\\n", i+1, number_threads);
int j;
for (j = 0; j < number_access; j++) {
int myg;
myg = g;
sleep(0);
g += i;
sleep(0);
g -= i;
if (myg == g) {
correct++;
}
else {
violations++;
}
}
printf("Thread %d/%d ending.\\n", i+1, number_threads);
}
void assembly_lock() {
asm("spin: lock btr $0, asmMutex");
asm("jnc spin");
}
void assembly_unlock() {
asm("bts $0, asmMutex");
}
void test_lock(void * i) {
int x = *((int*) i);
if (is_assembly) {
assembly_lock();
do_something_clever(x);
assembly_unlock();
}
else if (is_locked) {
pthread_mutex_lock(&lock);
do_something_clever(x);
pthread_mutex_unlock(&lock);
}
else {
do_something_clever(x);
}
}
void compare_result(int expected_result) {
printf("Number of correct: %d (should be %d), number of violations: %d \\n", correct, expected_result, violations);
if (expected_result == correct) {
printf("OK\\n");
}
else printf("FAIL\\n");
}
void show_help(void) {
printf("Usage: protect [--threads NUMBER_OF_THREADS] [--access NUMBER_OF_ACCESS] [--with-protection] [--without-protection] [--assembly]\\n\\n");
printf("Optional arguments:\\n--help\\tshow this help message and exit\\n");
printf("--threads\\tNumber of threads\\n");
printf("--accesses\\tNumber of accesses\\n");
printf("--with-protection\\tWith lock for threads...\\n");
printf("--without-protection\\tWithout lock for threads...\\n");
printf("--assembly\\tWith assembly lock for threads...\\n");
}
int parse_command_line (int argc, char **argv){
static struct option long_options[] = {
{"threads", required_argument, 0, 't'},
{"accesses", required_argument, 0, 'a'},
{"with-protection", no_argument, 0, 'w'},
{"without-protection", no_argument, 0, 'o'},
{"assembly", no_argument, 0, 's'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
char ch;
while ((ch = getopt_long(argc, argv, "t:a:wosh", long_options, 0)) != -1) {
switch (ch)
{
case 't':
number_threads = atoi(optarg);
break;
case 'a':
number_access = atoi(optarg);
break;
case 'w':
is_locked = 1;
break;
case 'o':
is_locked = 0;
break;
case 's':
is_assembly = 1;
break;
case 'h':
show_help();
exit(0);
break;
}
}
return 0;
}
| 1
|
#include <pthread.h>
enum Colour
{
blue = 0,
red = 1,
yellow = 2,
Invalid = 3
};
const char* ColourName[] = {"blue", "red", "yellow"};
const int STACK_SIZE = 32*1024;
const BOOL TRUE = 1;
const BOOL FALSE = 0;
int CreatureID = 0;
enum Colour doCompliment(enum Colour c1, enum Colour c2)
{
switch (c1)
{
case blue:
switch (c2)
{
case blue:
return blue;
case red:
return yellow;
case yellow:
return red;
default:
goto errlb;
}
case red:
switch (c2)
{
case blue:
return yellow;
case red:
return red;
case yellow:
return blue;
default:
goto errlb;
}
case yellow:
switch (c2)
{
case blue:
return red;
case red:
return blue;
case yellow:
return yellow;
default:
goto errlb;
}
default:
break;
}
errlb:
printf("Invalid colour\\n");
exit( 1 );
}
char* formatNumber(int n, char* outbuf)
{
int ochar = 0, ichar = 0;
int i;
char tmp[64];
const char* NUMBERS[] =
{
"zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine"
};
ichar = sprintf(tmp, "%d", n);
for (i = 0; i < ichar; i++)
ochar += sprintf( outbuf + ochar, " %s", NUMBERS[ tmp[i] - '0' ] );
return outbuf;
}
struct MeetingPlace
{
pthread_mutex_t mutex;
int meetingsLeft;
struct Creature* firstCreature;
};
struct Creature
{
pthread_t ht;
pthread_attr_t stack_att;
struct MeetingPlace* place;
int count;
int sameCount;
enum Colour colour;
int id;
BOOL two_met;
BOOL sameid;
};
void MeetingPlace_Init(struct MeetingPlace* m, int meetings )
{
pthread_mutex_init( &m->mutex, 0 );
m->meetingsLeft = meetings;
m->firstCreature = 0;
}
BOOL Meet( struct Creature* cr)
{
BOOL retval = TRUE;
struct MeetingPlace* mp = cr->place;
pthread_mutex_lock( &(mp->mutex) );
if ( mp->meetingsLeft > 0 )
{
if ( mp->firstCreature == 0 )
{
cr->two_met = FALSE;
mp->firstCreature = cr;
}
else
{
struct Creature* first;
enum Colour newColour;
first = mp->firstCreature;
newColour = doCompliment( cr->colour, first->colour );
cr->sameid = cr->id == first->id;
cr->colour = newColour;
cr->two_met = TRUE;
first->sameid = cr->sameid;
first->colour = newColour;
first->two_met = TRUE;
mp->firstCreature = 0;
mp->meetingsLeft--;
}
}
else
retval = FALSE;
pthread_mutex_unlock( &(mp->mutex) );
return retval;
}
void* CreatureThreadRun(void* param)
{
struct Creature* cr = (struct Creature*)param;
while (TRUE)
{
if ( Meet(cr) )
{
while (cr->two_met == FALSE)
sched_yield();
if (cr->sameid)
cr->sameCount++;
cr->count++;
}
else
break;
}
return 0;
}
void Creature_Init( struct Creature *cr, struct MeetingPlace* place, enum Colour colour )
{
cr->place = place;
cr->count = cr->sameCount = 0;
cr->id = ++CreatureID;
cr->colour = colour;
cr->two_met = FALSE;
pthread_attr_init( &cr->stack_att );
pthread_attr_setstacksize( &cr->stack_att, STACK_SIZE );
pthread_create( &cr->ht, &cr->stack_att, &CreatureThreadRun, (void*)(cr) );
}
char* Creature_getResult(struct Creature* cr, char* str)
{
char numstr[256];
formatNumber(cr->sameCount, numstr);
sprintf( str, "%u%s", cr->count, numstr );
return str;
}
void runGame( int n_meeting, int ncolor, const enum Colour* colours )
{
int i;
int total = 0;
char str[256];
struct MeetingPlace place;
struct Creature *creatures = (struct Creature*) calloc( ncolor, sizeof(struct Creature) );
MeetingPlace_Init( &place, n_meeting );
for (i = 0; i < ncolor; i++)
{
printf( "%s ", ColourName[ colours[i] ] );
Creature_Init( &(creatures[i]), &place, colours[i] );
}
printf("\\n");
for (i = 0; i < ncolor; i++)
pthread_join( creatures[i].ht, 0 );
for (i = 0; i < ncolor; i++)
{
printf( "%s\\n", Creature_getResult(&(creatures[i]), str) );
total += creatures[i].count;
}
printf( "%s\\n\\n", formatNumber(total, str) );
pthread_mutex_destroy( &place.mutex );
free( creatures );
}
void printColours( enum Colour c1, enum Colour c2 )
{
printf( "%s + %s -> %s\\n",
ColourName[c1],
ColourName[c2],
ColourName[doCompliment(c1, c2)] );
}
void printColoursTable(void)
{
printColours(blue, blue);
printColours(blue, red);
printColours(blue, yellow);
printColours(red, blue);
printColours(red, red);
printColours(red, yellow);
printColours(yellow, blue);
printColours(yellow, red);
printColours(yellow, yellow);
}
int main(int argc, char** argv)
{
int n = (argc == 2) ? atoi(argv[1]) : 600;
printColoursTable();
printf("\\n");
const enum Colour r1[] = { blue, red, yellow };
const enum Colour r2[] = { blue, red, yellow,
red, yellow, blue,
red, yellow, red, blue };
runGame( n, sizeof(r1) / sizeof(r1[0]), r1 );
runGame( n, sizeof(r2) / sizeof(r2[0]), r2 );
return 0;
}
| 0
|
#include <pthread.h>
int sum = 0;
int count = 0;
int rcv_count = 0;
pthread_mutex_t mutex;
key_t key = 4567;
int queue[100];
struct msgbuf {
long mtype;
int mnum;
};
void *tfn(void)
{
pthread_mutex_lock(&mutex);
int msgid;
if ((msgid=msgget(key+count, IPC_CREAT|0666))<0) {
printf("msgget");
exit(1);
}
queue[count] = msgid;
printf("queue ID %d is %d, (0x%lx)\\n", count, msgid, (long unsigned)msgid);
count ++;
pthread_mutex_unlock(&mutex);
}
int Usage(char *argv0)
{
fprintf(stderr,"Usage: %s [-q num]\\n",argv0);
exit(-1);
}
int main(int argc, char *argv[])
{
int opt;
int q = 1;
pthread_t tid;
pthread_mutex_init(&mutex, 0);
if ((argc != 1) && (argc != 3))
{
Usage(argv[0]);
exit(-1);
}
if (argc == 3)
{
while ((opt = getopt(argc, argv, "q:")) != -1)
{
switch(opt)
{
case 'q':
q = atoi(optarg);
break;
default:
Usage(argv[0]);
break;
}
}
}
for(int i = 0; i < q; i++){
pthread_create(&tid, 0, tfn, 0);
}
struct msgbuf rbuf;
while(1){
for (int i = 0; i < q; i++){
if (msgrcv(queue[i], &rbuf, 128, 1, 0) >= 0){
rcv_count++;
sum = rbuf.mnum + sum;
printf("sum is %d\\n", sum);
}
}
if((rcv_count == q) && (count == q) && (pthread_mutex_trylock(&mutex) == 0)){
pthread_mutex_unlock(&mutex);
break;
}
}
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
int num=0;
pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
void* thread_func(void *arg)
{
int i = (int)arg;
int ret;
sleep(5-i);
pthread_mutex_lock(&mylock);
while(i != num)
{
printf("thread %d warting\\n",i);
ret = pthread_cond_wait(&qready, &mylock);
if(0 == ret)
{
printf("thread %d wait success\\n",i);
}
else
{
printf("thread %d wait fail\\n",i);
}
}
printf("thread %d is running\\n",i);
num++;
pthread_mutex_unlock(&mylock);
pthread_cond_broadcast(&qready);
return (void *)0;
}
int main(int argc, char** argv)
{
int i=0,err;
pthread_t tid[4];
void *tret;
for(i=0;i<4;i++)
{
err = pthread_create(&tid[i], 0, thread_func, (void *)i);
if(0 != err)
{
printf("pthread_create error:%s\\n",strerror(err));
exit(-1);
}
}
for(i=0;i<4;i++)
{
err = pthread_join(tid[i], &tret);
if(0 != err)
{
printf("can not join with thread :%d\\n",i,strerror(err));
exit(-1);
}
}
return 0;
}
| 0
|
#include <pthread.h>
char y, x;
} pos_t;
char fim, humano, num;
int tempo;
} player_t;
int max_y, max_x;
pos_t ele[4] = { {3, 10}, {15,15}, {12,40}, {19,45}};
pthread_mutex_t key;
void* move_jogador( void *dados){
player_t *j;
int ch;
pos_t d;
j = (player_t*) dados;
do {
if (!j->humano) {
ch = rand() % 4;
d.y = 0;
d.x = 0;
switch (ch) {
case 1:
d.y--;
break;
case 2:
d.x++;
break;
case 3:
d.x--;
break;
case 4:
d.x++;
break;
}
if (j-> num >= 0 && j->num < 4) {
pthread_mutex_lock(&key);
mvaddch(ele[j->num].y, ele[j->num].x , ' ');
ele[j->num].y += d.y;
ele[j->num].x += d.x;
mvaddch(ele[j->num].y, ele[j->num].x, '0'+ j->num);
refresh();
}
pthread_mutex_unlock(&key);
}
usleep( j->tempo);
} while( !j->fim);
pthread_exit(0);
}
int main(int argc, char const *argv[]) {
int ch,num;
pos_t d;
player_t j[4] = { {0,0,0,100000}, {0,0,1,300000}, {0,0,2,500000}, {0,0,3,700000} };
pthread_t tarefa[4];
initscr();
noecho();
cbreak();
keypad (stdscr, TRUE);
curs_set(0);
getmaxyx(stdscr, max_y, max_x);
pthread_mutex_init(&key, 0);
clear();
for (size_t i = 0; i < 4; i++)
mvaddch(ele[i].y, ele[i].x, '0'+i);
refresh();
for (size_t i = 0; i < 4; i++)
pthread_create( &tarefa[i], 0, &move_jogador, (void*) &j[i]);
while ( (ch = getch()) != 'q' ) {
d.y = 0;
d.x = 0;
switch (ch) {
case '0' :
num = 0;
j[0].humano = 1;
break;
case '1' :
num = 1;
j[1].humano = 1;
break;
case '2' :
num = 2;
j[2].humano = 1;
break;
case '3' :
num = 3;
j[3].humano = 1;
break;
case 'd' :
num = -1;
for (size_t i = 0; i < 4; i++) {
j[i].humano = 0;
}
case KEY_UP:
d.y--;
break;
case KEY_DOWN:
d.y++;
break;
case KEY_RIGHT:
d.x++;
break;
case KEY_LEFT:
d.x--;
break;
}
if (num >= 0 && num < 4) {
pthread_mutex_lock(&key);
mvaddch(ele[num].y, ele[num].x , ' ');
ele[num].y += d.y;
ele[num].x += d.x;
mvaddch(ele[num].y, ele[num].x, '0'+ num);
refresh();
pthread_mutex_unlock(&key);
}
}
for (size_t i = 0; i < 4; i++) {
j[i]. fim = 1;
pthread_join(tarefa[i], 0);
}
pthread_mutex_destroy(&key);
endwin();
return 0;
}
| 1
|
#include <pthread.h>
void* robotRetrait(void* arg)
{
char MessageAfficher[200];
struct convoyeur* myConvoyeur = arg;
sprintf(MessageAfficher,"[Robot de Retrait] : Prêt");
affichageConsole(LigneRobotRetrait,MessageAfficher);
while(1)
{
pthread_mutex_lock(&mutex_RobotRetrait);
if(nbPieceFini>=1)
{
sprintf(MessageAfficher,"[Robot de Retrait] : Retire pièce du convoyeur : pièce en transit");
affichageConsole(LigneRobotRetrait,MessageAfficher);
struct maillon* maillon;
maillon = retire_convoyeur(myConvoyeur,-1,0);
sprintf(MessageAfficher,"[Robot de Retrait] : Création du rapport de la pièce [%d]", maillon->obj.identifiant);
affichageConsole(LigneRobotRetrait,MessageAfficher);
sprintf(MessageAfficher,"Pièce [%d] de type : %d Temps d'usinage : %d\\n",maillon->obj.identifiant,maillon->obj.typePiece,maillon->obj.tempsUsinage);
EcrireRapport(MessageAfficher);
nbPieceFini--;
sprintf(MessageAfficher,"[Robot de Retrait] : Prêt");
affichageConsole(LigneRobotRetrait,MessageAfficher);
}
else
{
pthread_cond_wait(&attendre_RobotRetrait,&mutex_RobotRetrait);
}
pthread_mutex_unlock(&mutex_RobotRetrait);
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
void prepare(void)
{
printf("preparing locks...\\n");
pthread_mutex_lock(&lock1);
pthread_mutex_lock(&lock2);
}
void parent(void)
{
printf("parent unlocking locks...\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void child(void)
{
printf("child unlocking locks...\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void *thr_fn(void *arg)
{
printf("thread started...\\n");
pause();
return(0);
}
int main(int argc, char **argv)
{
int err;
pid_t pid;
pthread_t tid;
if ((err = pthread_atfork(prepare, parent, child)) != 0)
err_exit(err, "cat not install fork handlers");
if ((err = pthread_create(&tid, 0, thr_fn, 0)) != 0)
err_exit(err, "cat not create thread");
sleep(2);
printf("parent about to fork...\\n");
if ((pid = fork()) < 0)
err_quit("fork error");
else if (pid == 0)
printf("child returned from fork\\n");
else
printf("parent returned from fork\\n");
exit(0);
}
| 1
|
#include <pthread.h>
static unsigned long mt[624];
static int mti=624 +1;
pthread_mutex_t bowl;
struct philo_Struct {
pthread_cond_t condp;
int state;
int blocktime;
} people[5];
void init_genrand(unsigned long s)
{
mt[0]= s & 0xffffffffUL;
for (mti=1; mti<624; mti++) {
mt[mti] =
(1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
mt[mti] &= 0xffffffffUL;
}
}
unsigned long genrand_int32(void)
{
unsigned long y;
static unsigned long mag01[2]={0x0UL, 0x9908b0dfUL};
if (mti >= 624) {
int kk;
if (mti == 624 +1)
init_genrand(5489UL);
for (kk=0;kk<624 -397;kk++) {
y = (mt[kk]&0x80000000UL)|(mt[kk+1]&0x7fffffffUL);
mt[kk] = mt[kk+397] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
for (;kk<624 -1;kk++) {
y = (mt[kk]&0x80000000UL)|(mt[kk+1]&0x7fffffffUL);
mt[kk] = mt[kk+(397 -624)] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
y = (mt[624 -1]&0x80000000UL)|(mt[0]&0x7fffffffUL);
mt[624 -1] = mt[397 -1] ^ (y >> 1) ^ mag01[y & 0x1UL];
mti = 0;
}
y = mt[mti++];
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680UL;
y ^= (y << 15) & 0xefc60000UL;
y ^= (y >> 18);
return y;
}
int genrand(){
int ifRdrand = 0;
int smallRand;
if( ifRdrand == 0 ){
unsigned int randNum = genrand_int32();
smallRand = randNum & 32767;
}
return smallRand;
}
int abletoEat(int id) {
int t;
if(people[(id+4) % 5].state == 2 || people[(id+1) % 5].state == 2) {
return 0;
}
t = time(0);
if(people[(id+4) % 5].state == 1 && people[(id+4) % 5].blocktime < people[id].blocktime && (t - people[(id+4) % 5].blocktime) >= 5) {
return 0;
}
if(people[(id+1) % 5].state == 1 && people[(id+1) % 5].blocktime < people[id].blocktime && (t - people[(id+1) % 5].blocktime) >= 5) {
return 0;
}
else {
return 1;
}
}
void getforks(int id) {
pthread_mutex_lock(&bowl);
people[id].state = 1;
people[id].blocktime = time(0);
while(!abletoEat(id)) {
pthread_cond_wait(&people[id].condp, &bowl);
}
people[id].state = 2;
printf("Philosopher %d PICKS UP forks: %d and %d\\n", id, id, ((id+4) % 5));
pthread_mutex_unlock(&bowl);
}
void put_forks(int id) {
pthread_mutex_lock(&bowl);
printf("Philosopher %d PUTS DOWN forks: %d and %d\\n", id, id, ((id+4) % 5));
people[id].state = 0;
if(people[(id+4) % 5].state == 1) {
pthread_cond_signal(&people[(id+4) % 5].condp);
}
if(people[(id+1) % 5].state == 1) {
pthread_cond_signal(&people[(id+1) % 5].condp);
}
pthread_mutex_unlock(&bowl);
}
void think(int id) {
int thinkingtime = (genrand() % 19) + 1;
printf("Philosopher %d is THINKING\\n", id);
sleep(thinkingtime);
}
void eat(int id) {
int eatingtime = (genrand() % 7) + 2;
printf("Philosopher %d is EATING\\n", id );
sleep(eatingtime);
}
void* philosopher(void *num){
int id = *((int *) num);
while( 1 ){
think(id);
getforks(id);
eat(id);
put_forks(id);
}
}
int main( int argc, char *argv[] ) {
pthread_t philo[5];
pthread_mutex_init(&bowl, 0);
int i = 0;
int id[5] = {0,1,2,3,4};
for(i = 0; i < 5; i++) {
pthread_cond_init(&people[i].condp, 0);
people[i].state = 0;
people[i].blocktime = 0;
}
for( i = 0; i < 5; i++ ){
pthread_create( &philo[i], 0, philosopher, (void *)(id + i));
}
for( i = 0; i < 5; i++ ){
pthread_join( philo[i], 0 );
}
pthread_mutex_destroy( &bowl );
for( i = 0; i < 5; i++ ){
pthread_cond_destroy( &people[i].condp );
}
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.