text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
struct my_struct {
int fd;
int stop;
char *read_buf;
char *write_buf;
pthread_mutex_t RW_mutex;
};
void *read_function(void *arg)
{
int i, len;
struct my_struct *myData = (struct my_struct *)arg;
myData->read_buf = malloc(256);
for(i=0;;i++)
{
pthread_mutex_lock( &(myData->RW_mutex) );
if ((len = read(myData->fd, myData->read_buf, 256)) == -1)
{
fprintf(stdout,"ERR:on read():%s\\n",strerror(errno));
}
else
{
fprintf(stdout, "%d - read \\"%s\\" len=%d\\n", i, myData->read_buf, len);
}
pthread_mutex_unlock(&(myData->RW_mutex));
memset((void *)myData->read_buf, '\\0', 256);
sleep(1);
if(myData->stop)
{
break;
}
}
free(myData->read_buf);
return 0;
}
void *write_function(void *arg)
{
int i, wlen;
struct my_struct *myData = (struct my_struct *)arg;
wlen = strlen(myData->write_buf);
for(i=0;;i++)
{
pthread_mutex_lock(&(myData->RW_mutex));
if ((wlen = write(myData->fd, myData->write_buf, wlen)) == -1)
{
fprintf(stdout,"ERR:on write():%s\\n",strerror(errno));
}
else
{
fprintf(stdout, "%d - write count=%d\\n", i, wlen);
}
pthread_mutex_unlock(&(myData->RW_mutex));
usleep(700000);
if(myData->stop)
{
break;
}
}
return 0;
}
int main(int argc, char *argv[])
{
int i, j, status;
int file_type, file_flag;
pthread_t readThread, writeThread;
pthread_mutex_t RW_mutex = PTHREAD_MUTEX_INITIALIZER;
struct my_struct myData;
myData.write_buf = malloc(256);
memset((void *)myData.write_buf, '\\0', 256);
myData.stop = 0;
myData.RW_mutex = RW_mutex;
strcpy(myData.write_buf, "Eureka!");
file_type = O_RDWR;
file_flag = O_APPEND;
if(argc == 4)
{
switch(atoi(argv[1]))
{
case 3:
file_type = O_WRONLY;
break;
case 2:
file_type = O_RDONLY;
break;
case 1:
default:
file_type = O_RDWR;
break;
}
switch(atoi(argv[2]))
{
case 2:
file_flag = O_TRUNC;
break;
case 1:
default:
file_flag = O_APPEND;
break;
}
strcpy(myData.write_buf, argv[3]);
}
else
{
fprintf(stdout, " help menu..\\n");
fprintf(stdout, " ./CDD2 arg1 arg2 arg3\\n");
fprintf(stdout, " arg1: open file type 1-RW, 2-Read only, 3-write only\\n");
fprintf(stdout, " arg2: file write control 1-append, 2-trunc\\n");
fprintf(stdout, " arg3: string for testing, max size=132 bytes\\n");
return 0;
}
fprintf(stdout, "Open device\\n");
if((myData.fd = open("/dev/CDD2", file_type | file_flag)) == -1)
{
fprintf(stderr,"ERR:on open():%s\\n",strerror(errno));
free(myData.write_buf);
return 0;
}
fprintf(stdout, "Create read thread\\n");
if((status = pthread_create(&readThread, 0, read_function, &myData)) != 0)
{
return 1;
}
fprintf(stdout, "Create write thread\\n");
if((status = pthread_create(&writeThread, 0, write_function, &myData)) != 0)
{
return 1;
}
sleep(10);
myData.stop = 1;
fprintf(stdout, "Delete write thread\\n");
status = pthread_join(writeThread, 0);
fprintf(stdout, "Delete read thread\\n");
status = pthread_join(readThread, 0);
free(myData.write_buf);
close(myData.fd);
return 0;
}
| 1
|
#include <pthread.h>
int p;
int n;
int* list;
int counter = 0;
pthread_mutex_t mutex;
pthread_cond_t cond_var;
void *Sort(void* rank);
void Odd_even_iter(int phase, int partner, long my_rank);
void Merge(int first, int last);
int main(int argc, char** argv)
{
long thread;
pthread_t* thread_handles;
int i,j,k;
n = atoi(argv[1]);
p = atoi(argv[2]);
double start, finish;
list = malloc(n*sizeof(int));
thread_handles = malloc(p*sizeof(pthread_t));
GET_TIME(start);
srand(p);
for (i=0;i<(n/4);i++)
{
list[i] = rand()%250;
}
for (i=(n/4);i<(n/4)*2;i++)
{
list[i] = rand()%250+250;
}
for (i=(n/4)*2;i<(n/4)*3;i++)
{
list[i] = rand()%250+500;
}
for (i=(n/4)*3;i<n;i++)
{
list[i] = rand()%250+750;
}
printf("Unsorted Global: \\n");
if (n<50)
{
for (j=0;j<n;j++)
{
printf("%d ",list[j]);
}
}
else
{
for (j=0;j<50;j++)
{
printf("%d ",list[j]);
}
}
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond_var, 0);
for (thread = 0; thread < p; thread++)
{
pthread_create(&thread_handles[thread], 0, Sort, (void*) thread);
}
for (thread = 0; thread < p; thread++)
{
pthread_join(thread_handles[thread], 0);
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond_var);
printf("\\nSorted Global: \\n");
if (n<50)
{
for (k=0;k<n;k++)
{
printf("%d ",list[k]);
}
}
else
{
for (k=0;k<50;k++)
{
printf("%d ",list[k]);
}
}
free(thread_handles);
free(list);
GET_TIME(finish);
printf("\\nTotal Time = %e\\n", finish-start);
return 0;
}
void *Sort(void* rank)
{
long my_rank = (long) rank;
int phase;
int partner;
partner = my_rank+1;
if (partner == p)
{
partner = -1;
}
int start = my_rank*(n/p);
int end = start+(n/p);
int flag = 1;
int i;
for (i=start+1;i<end;i++)
{
if (list[i-1] > list[i])
{
flag = 0;
}
}
if (flag == 0)
{
int j, k;
int temp;
for (j=start+1;j<end;j++)
{
temp = list[j];
for (k = j; k > start && temp < list[k-1]; k--)
{
list[k] = list[k-1];
}
list[k] = temp;
}
}
int l;
for (phase=0;phase<p;phase++)
{
Odd_even_iter(phase, partner, my_rank);
pthread_mutex_lock(&mutex);
counter++;
if (counter == p)
{
counter = 0;
pthread_cond_broadcast(&cond_var);
}
else
{
while (pthread_cond_wait(&cond_var, &mutex) != 0);
}
pthread_mutex_unlock(&mutex);
}
}
void Odd_even_iter(int phase, int partner, long my_rank)
{
int my_first = my_rank*(n/p);
int my_last = (my_first+(n/p))-1;
int partner_first = my_last+1;
int partner_last = partner_first+(n/p);
if (phase % 2 == 0 && my_rank % 2 == 0)
{
if (partner != -1)
{
if (list[my_last]>=list[partner_first])
{
Merge(my_first,partner_last);
}
}
}
if (phase %2 != 0 && my_rank % 2 != 0)
{
if (partner != -1)
{
if (list[my_last]>=list[partner_first])
{
Merge(my_first,partner_last);
}
}
}
}
void Merge(int first, int last)
{
int i, j, temp;
for (i = first+1; i < last; i++)
{
temp = list[i];
for (j = i; j > first && temp < list[j-1]; j--)
{
list[j] = list[j-1];
}
list[j] = temp;
}
}
| 0
|
#include <pthread.h>
pthread_t *th_A , *th_B;
pthread_mutex_t mutex , mutex2;
int nThread = 1000;
int id;
char type;
} ThreadData;
ThreadData *dataA , *dataB;
sem_t *printA , *printB;
int cnt_3 = 0;
int statB = 0;
int statA = 0;
int lock = 0;
void * procA ( void *arg ){
ThreadData *d = ( ThreadData * ) arg;
sem_wait( printA );
pthread_mutex_lock ( &mutex );
printf ( "%c%d ", d->type , d->id );
statA++;
if ( statA + statB >= 3 ){
printf ( "\\n");
statA = 0;
statB = 0;
sem_post ( printB );
sem_post ( printA );
sem_post ( printB );
}
pthread_mutex_unlock ( &mutex );
}
void * procB ( void *arg ){
ThreadData *d = ( ThreadData * ) arg;
sem_wait ( printB );
pthread_mutex_lock ( &mutex );
printf ( "%c%d ", d->type , d->id );
statB++;
if ( statA + statB >= 3 ){
printf ( "\\n");
statA = 0;
statB = 0;
sem_post ( printA );
sem_post ( printB );
sem_post ( printB );
}
pthread_mutex_unlock ( &mutex );
}
int main ( int argc , char *agrv[] ){
nThread = atoi(argv[1]);
dataA = ( struct ThreadData * ) malloc ( nThread * sizeof ( struct ThreadData ) ) ;
dataB = ( struct ThreadData * ) malloc ( 2 * nThread * sizeof ( struct ThreadData ) ) ;
th_A = ( pthread_t * ) malloc ( nThread * sizeof ( pthread_t ) );
th_B = ( pthread_t * ) malloc ( 2 * nThread * sizeof ( pthread_t ) );
printA = ( sem_t * ) malloc ( sizeof ( sem_t ) );
printB = ( sem_t * ) malloc ( sizeof ( sem_t ) );
sem_init ( printA , 0 , 1 );
sem_init ( printB , 0 , 2 );
pthread_mutex_init(&mutex,0);
pthread_mutex_init(&mutex2,0);
for ( int i = 0; i < 2 * nThread; i++ ){
dataB[i].id = i;
dataB[i].type = 'B';
pthread_create (&th_B[i] , 0 , procB , ( void * ) &dataB[i] );
}
for ( int i = 0; i < nThread; i++ ){
dataA[i].id = i;
dataA[i].type = 'A';
pthread_create ( &th_A[i] , 0 , procA , ( void * ) &dataA[i] );
}
for ( int i = 0; i < nThread; i++ ){
pthread_join ( th_A[i] , 0 );
}
for ( int i = 0; i < nThread * 2; i++ ){
pthread_join ( th_B[i] , 0 );
}
printf ( "\\n");
return 0;
}
| 1
|
#include <pthread.h>
int buffer[30];
int fill_ptr = 0;
int use_ptr = 0;
int count = 0;
void put(int value) {
buffer[fill_ptr] = value;
fill_ptr = (fill_ptr + 1) % 30;
count++;
}
int get() {
int tmp = buffer[use_ptr];
use_ptr = (use_ptr + 1) % 30;
count--;
return tmp;
}
pthread_cond_t empty, fill;
pthread_mutex_t mutex;
void *producer(void *arg) {
int loops = (int) arg;
int i;
for (i = 0; i < loops; i++) {
pthread_mutex_lock(&mutex);
while (count == 30) {
pthread_cond_wait(&empty, &mutex);
}
put(i);
pthread_cond_signal(&fill);
pthread_mutex_unlock(&mutex);
}
return 0;
}
void *consumer(void *arg) {
int loops = (int) arg;
int i;
for (i = 0; i < loops; i++) {
pthread_mutex_lock(&mutex);
while (count == 0) {
pthread_cond_wait(&fill, &mutex);
}
int tmp = get();
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
printf("%d\\n", tmp);
}
return 0;
}
| 0
|
#include <pthread.h>
void *sendPhyDL(void* threadid){
char package[100];
int error;
pthread_mutex_unlock(&mutex1);
while(1){
pthread_mutex_lock(&mutex0);
printf("Mensagem: ");
__fpurge(stdin);
scanf("%s", package);
__fpurge(stdin);
memcpy(DataLink_Physical, package, 100);
pthread_mutex_unlock(&mutex1);
usleep(100);
error = errorDataLink;
if(error == -202) {
printf("Erro %d: no nao valido.\\n\\n", error*(-1));
} else if(error == -303) {
printf("Erro %d: proprio no.\\n\\n", error*(-1));
} else if(error == -404) {
printf("Erro %d: no não vizinho.\\n\\n", error*(-1));
} else if(error == -505){
printf("Erro %d: dados excedem MTU.\\n\\n", error*(-1));
} else if(error == -606){
printf("Erro %d:sendto_garbled().\\n\\n", error*(-1));
} else {
printf("Enviado com sucesso.\\n\\n");
}
fflush(stdout);
usleep(100);
}
}
void *receivePhyDL(void *threadid){
while(1){
pthread_mutex_lock(&mutex3);
printf("\\nMensagem Recebida: %s\\n", DataLink_Physical);
fflush(stdout);
memset(DataLink_Physical, 0, sizeof(DataLink_Physical));
pthread_mutex_unlock(&mutex4);
}
}
void initPhysical(){
pthread_create(&tSend, 0, sendPhyDL, (void* )1);
usleep(100);
pthread_create(&tReceive, 0, receivePhyDL, (void* )1);
usleep(100);
pthread_join(tReceive, 0);
pthread_join(tSend, 0);
}
| 1
|
#include <pthread.h>
struct {
pthread_mutex_t mutex;
int buff[10];
int nitems;
} shared = {
PTHREAD_MUTEX_INITIALIZER
};
void* produce(void* arg) {
for (;;) {
pthread_mutex_lock(&shared.mutex);
if (shared.nitems >= 100000000) {
pthread_mutex_unlock(&shared.mutex);
return 0;
}
shared.buff[*((int*) arg)]++;
shared.nitems++;
pthread_mutex_unlock(&shared.mutex);
}
}
void* consume(void* arg) {
int i;
for (i = 0; i < 10; ++i)
printf("buff[%d] = %d\\n", i, shared.buff[i]);
return 0;
}
int main() {
int i;
pthread_t produce_threads[10];
pthread_t consume_thread;
for (i = 0; i < 10; ++i)
pthread_create(&produce_threads[i], 0, produce, &i);
for (i = 0; i < 10; ++i)
pthread_join(produce_threads[i], 0);
pthread_create(&consume_thread, 0, consume, 0);
pthread_join(consume_thread, 0);
return 0;
}
| 0
|
#include <pthread.h>
struct requestinfo {
int type;
int wantipv6;
pthread_t threadhandle;
pthread_mutex_t threadeventmutex;
int threadeventobject;
char* requestvalue;
char* result;
};
void* resolvethread(void* data) {
struct requestinfo* i = data;
if (i->type == 1) {
i->result = malloc(300);
if (so_ReverseResolveBlocking(i->requestvalue, i->result, 300) != 0) {
free(i->result);i->result = 0;
}
}
if (i->type == 2) {
i->result = malloc(IPMAXLEN+1);
int iptype = IPTYPE_IPV4;
if (i->wantipv6 == 1) {iptype = IPTYPE_IPV6;}
if (so_ResolveBlocking(i->requestvalue, iptype, i->result, IPMAXLEN+1) != 0) {
free(i->result);i->result = 0;
}
}
pthread_mutex_lock(&i->threadeventmutex);
i->threadeventobject = 1;
pthread_mutex_unlock(&i->threadeventmutex);
pthread_exit(0);
return 0;
}
void* hostresolv_internal_NewRequest(int type, const char* requestvalue, int wantipv6) {
struct requestinfo i;
memset(&i,0,sizeof(i));
i.requestvalue = malloc(strlen(requestvalue)+1);
if (!i.requestvalue) {return 0;}
strcpy(i.requestvalue, requestvalue);
i.type = type;
void* entry = malloc(sizeof(i));
if (!entry) {free(i.requestvalue);return 0;}
memcpy(entry, &i, sizeof(i));
struct requestinfo* ri = entry;
ri->wantipv6 = wantipv6;
pthread_mutex_init(&ri->threadeventmutex, 0);
ri->threadeventobject = 0;
pthread_create(&ri->threadhandle, 0, resolvethread, ri);
pthread_detach(ri->threadhandle);
return entry;
}
void* hostresolv_ReverseLookupRequest(const char* ip) {
return hostresolv_internal_NewRequest(1, ip, 0);
}
void* hostresolv_LookupRequest(const char* host, int ipv6) {
return hostresolv_internal_NewRequest(2, host, ipv6);
}
int hostresolv_GetRequestStatus(void* handle) {
if (!handle) {return RESOLVSTATUS_FAILURE;}
struct requestinfo* i = handle;
pthread_mutex_lock(&i->threadeventmutex);
int u = i->threadeventobject;
pthread_mutex_unlock(&i->threadeventmutex);
if (u == 1) {
if (i->result != 0) {
return RESOLVSTATUS_SUCCESS;
}else{
return RESOLVSTATUS_FAILURE;
}
}else{
return RESOLVSTATUS_PENDING;
}
}
const char* hostresolv_GetRequestResult(void* handle) {
if (!handle) {return 0;}
if (hostresolv_GetRequestStatus(handle) == RESOLVSTATUS_PENDING) {return 0;}
struct requestinfo* i = handle;
return i->result;
}
void hostresolv_FreeRequest(void* handle) {
if (!handle) {return;}
struct requestinfo* i = handle;
free(i->requestvalue);
if (i->result) {free(i->result);}
free(handle);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
struct in_addr dest_ip;
unsigned short int min_port;
unsigned short int max_port;
}port_segment;
int do_scan(struct sockaddr_in serv_addr)
{
int fd;
int result;
fd = socket(AF_INET,SOCK_STREAM,0);
if (fd < 0){
perror("Socket Error"); return -1;
}
if ((result = connect(fd,(struct sockaddr *)&serv_addr,sizeof(struct sockaddr)) < 0)){
if (errno == ECONNREFUSED){
close(fd);
return 0;
}
else{
close(fd);
return -1;
}
}
else if (result == 0){
printf("端口%d开放\\n",ntohs(serv_addr.sin_port));
close(fd);
return 1;
}
return -1;
}
void scaner(port_segment *arg)
{
unsigned short int i;
struct sockaddr_in serv_addr;
port_segment portinfo;
pthread_mutex_lock(&mutex);
memcpy(&portinfo,arg,sizeof(struct _port_segment));
pthread_mutex_unlock(&mutex);
memset(&serv_addr,0,sizeof(struct sockaddr_in));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = portinfo.dest_ip.s_addr;
for (i = portinfo.min_port; i < portinfo.max_port; i++){
serv_addr.sin_port = htons(i);
do_scan(serv_addr);
}
}
int main(int argc,char *argv[])
{
pthread_t *pthread;
int max_port;
int thread_num;
int seg_len;
struct in_addr dest_ip;
port_segment portinfo;
int i;
if (argc != 7){
printf("参数有误!\\n");
return 1;
}
for (i = 1; i < argc; i++){
if (strcmp("-m",argv[i]) == 0){
max_port = atoi(argv[i + 1]);
if (max_port > 65535 || max_port < 0){
printf("最大端口号有误!\\n");
return 1;
}
}
else if(strcmp("-a",argv[i]) == 0){
if (inet_aton(argv[i + 1],&dest_ip) == 0){
printf("IP有误!\\n");
return 1;
}
}
else if (strcmp("-n",argv[i]) == 0){
thread_num = atoi(argv[i + 1]);
if (thread_num <= 0){
printf("线程数有误!\\n");
return 1;
}
}
}
if (max_port < thread_num){
thread_num = max_port;
}
seg_len = max_port / thread_num;
if (seg_len % thread_num != 0)
thread_num++;
pthread = (pthread_t *)malloc(sizeof(pthread_t) * thread_num);
for (i = 0; i < thread_num; i++){
pthread_mutex_lock(&mutex);
portinfo.dest_ip = dest_ip;
portinfo.min_port = i * seg_len + 1;
if (i != thread_num - 1)
portinfo.max_port = portinfo.min_port + seg_len;
else
portinfo.max_port = max_port;
pthread_mutex_unlock(&mutex);
if (pthread_create(&pthread[i],0,(void *)scaner,&portinfo) != 0){
printf("第%d个线程创建失败\\n",i);
return 1;
}
}
for (i = 0; i < thread_num; i++)
pthread_join(pthread[i],0);
printf("扫描完成!\\n");
return 0;
}
| 0
|
#include <pthread.h>
static volatile uint32_t Gen_IO_CSR_Reg = 0;
static volatile uint32_t Gen_IO_Buff_Reg = 0;
static volatile uint32_t Gen_IO_Size_Reg = 0;
static volatile uint32_t Gen_IO_Count_Reg = 0;
static volatile int IO_Q_Halt_Thread = 0;
static pthread_t IO_Q_Thread;
static pthread_cond_t IO_Q_Cond = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t IO_Q_Lock = PTHREAD_MUTEX_INITIALIZER;
static void Gen_IO_Finish();
{
uint32_t op;
uint32_t buff;
uint32_t size;
} gen_io_blk_t;
static void *gen_io_thread(void *arg);
static int32_t get_byte(int32_t id, int32_t addr)
{
Machine_Check(MC_HW_WARNING | MC_ILLEGAL_ADDR,
"timer registers are word wide");
return 0;
}
static int32_t get_word(int32_t id, int32_t addr)
{
int32_t value;
if (addr == 0)
{
value = Gen_IO_CSR_Reg;
}
else if (addr == 4)
{
value = Gen_IO_Buff_Reg;
}
else if (addr == 8)
{
value = Gen_IO_Size_Reg;
}
else if (addr == 12)
{
value = Gen_IO_Count_Reg;
}
return value;
}
static void set_byte(int32_t id, int32_t addr, int32_t value)
{
Machine_Check(MC_HW_WARNING | MC_ILLEGAL_ADDR,
"timer registers are word wide");
}
static void set_word(int32_t id, int32_t addr, int32_t value)
{
if (addr == 0)
{
Gen_IO_CSR_Reg = value;
}
else if (addr == 4)
{
Gen_IO_Buff_Reg = value;
}
else if (addr == 8)
{
Gen_IO_Size_Reg = value;
}
else if (addr == 12)
{
Gen_IO_Count_Reg = value;
}
}
static void Gen_IO_Finish()
{
IO_Q_Halt_Thread = 1;
pthread_cond_broadcast(&IO_Q_Cond);
pthread_join(IO_Q_Thread, 0);
}
int Gen_IO_Init()
{
IO_Register_Handler(0, GEN_IO_CSR, 16,
get_word, get_byte, set_word, set_byte);
pthread_create(&IO_Q_Thread, 0, gen_io_thread, 0);
atexit(Gen_IO_Finish);
return 0;
}
static void *gen_io_thread(void *arg)
{
int op;
int num;
int status;
int stackl_addr;
char *addr;
pthread_mutex_lock(&IO_Q_Lock);
while (!IO_Q_Halt_Thread)
{
while (!IO_Q_Halt_Thread && (Gen_IO_CSR_Reg & GEN_IO_CSR_DONE))
{
pthread_cond_wait(&IO_Q_Cond, &IO_Q_Lock);
}
stackl_addr = Gen_IO_Buff_Reg + Gen_IO_Count_Reg;
addr = Abs_Get_Addr(stackl_addr);
op = Gen_IO_CSR_Reg & 0xFF;
switch (op)
{
case GEN_IO_OP_PRINTS:
if (Gen_IO_Size_Reg > Gen_IO_Count_Reg)
{
pthread_mutex_unlock(&IO_Q_Lock);
usleep(100);
fputc(*addr, stdout);
fflush(stdout);
pthread_mutex_lock(&IO_Q_Lock);
Gen_IO_Count_Reg++;
}
else
{
Gen_IO_CSR_Reg |= GEN_IO_CSR_DONE;
}
break;
case GEN_IO_OP_PRINTC:
pthread_mutex_unlock(&IO_Q_Lock);
usleep(100);
fputc(*addr, stdout);
fflush(stdout);
pthread_mutex_lock(&IO_Q_Lock);
Gen_IO_Count_Reg++;
Gen_IO_CSR_Reg |= GEN_IO_CSR_DONE;
break;
case GEN_IO_OP_GETL:
if (fgets(addr, Gen_IO_Size_Reg, stdin) == 0)
{
Gen_IO_CSR_Reg |= GEN_IO_CSR_ERR;
}
Gen_IO_CSR_Reg |= GEN_IO_CSR_DONE;
break;
case GEN_IO_OP_GETI:
num = scanf("%d", (int *)addr);
if (num != 1) Gen_IO_CSR_Reg |= GEN_IO_CSR_ERR;
Gen_IO_CSR_Reg |= GEN_IO_CSR_DONE;
break;
case GEN_IO_OP_EXEC:
pthread_mutex_unlock(&IO_Q_Lock);
status = Load(addr, 0);
pthread_mutex_lock(&IO_Q_Lock);
Gen_IO_Count_Reg = status;
Gen_IO_CSR_Reg |= GEN_IO_CSR_DONE;
if (status < 0) Gen_IO_CSR_Reg |= GEN_IO_CSR_ERR;
break;
}
if ((Gen_IO_CSR_Reg & (GEN_IO_CSR_IE | GEN_IO_CSR_DONE)) == (GEN_IO_CSR_IE | GEN_IO_CSR_DONE))
{
Gen_IO_CSR_Reg |= GEN_IO_CSR_INT;
Machine_Signal_Interrupt(1, GEN_IO_VECTOR);
}
}
return 0;
}
| 1
|
#include <pthread.h>void* philoDiner(void *arg);
pthread_mutex_t chops [1000];
int phioFed = 0;
int numPhilo = 0;
int numNom = 0;
int main(int argc, char *argv[]) {
pthread_t thread[1000];
int thread_id[1000];
int id = 0;
int result;
int isLocked = 0;
numPhilo = atoi(argv[1]);
numNom = atoi(argv[2]);
for (int i = 0; i < numPhilo; i++) {
thread_id[i] = i;
result = pthread_create(&(thread[i]), 0, &philoDiner, &(thread_id[i]));
pthread_mutex_init(&chops[i], 0);
}
for (int c = 0; c < numPhilo; c++) {
result = pthread_join(thread[c], 0);
}
for (int c = 0; c < numPhilo; c++) {
result = pthread_mutex_destroy(&chops[c]);
}
return 0;
}
void* philoDiner(void *arg) {
int minId = 0;
int fatty = 0;
int id = *((int*) arg);
minId = id - 1;
if (minId == -1)
minId = numPhilo - 1;
while (fatty < numNom) {
printf("Philosopher %d Waiting...\\n", id + 1);
pthread_mutex_lock(&chops[id]);
pthread_mutex_lock(&chops[minId]);
fatty++;
sleep(1);
printf("Philosopher %d Eating....\\n", id + 1);
pthread_mutex_unlock(&chops[id]);
pthread_mutex_unlock(&chops[minId]);
printf("Philosopher %d has eaten!\\n", id + 1);
}
phioFed++;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
int shared_data = 5;
void *thread_function (void *arg)
{
pthread_mutex_lock(&mutex) ;
while ( shared_data > 0)
{
--shared_data ;
printf("Thread - Decreasing shared_data... Value:%d\\n",shared_data);
sleep(1);
}
pthread_mutex_unlock(&mutex);
printf("Thread, loop finished...\\n");
sleep(3);
return 0;
}
int main (void)
{
pthread_t thread_ID1;
void *exit_status;
pthread_mutex_init (&mutex , 0) ;
pthread_create (&thread_ID1 ,0, thread_function , 0) ;
while (1)
{
pthread_mutex_lock(&mutex );
printf("Main thread locking the mutex...\\n");
if(shared_data==0)
break;
pthread_mutex_unlock(&mutex);
}
pthread_mutex_unlock(&mutex);
printf("Main awake - Value of shared_data: %d!!!\\n", shared_data);
pthread_mutex_unlock(&mutex) ;
pthread_join( thread_ID1 , 0) ;
pthread_mutex_destroy(&mutex) ;
exit(0);
}
| 1
|
#include <pthread.h>
void (*add_func)();
} function_pointers;
pthread_mutex_t * mutex;
pthread_cond_t * work_sig;
pthread_cond_t * mon_sig;
int * shared_data;
int * work_available;
int * stop_work;
function_pointers * pointers;
int index;
} worker_data;
pthread_cond_t * work_sig;
pthread_cond_t * mon_sig;
pthread_mutex_t * mutex;
int * shared_minimum;
int * shared_data;
int * work_available;
} monitor_data;
void shared_addition(worker_data * data) {
(*(data->shared_data))++;
printf("[DATA]: The current shared variable is: %d\\n", *(data->shared_data));
}
void * do_additions(void * arg) {
worker_data * data = (worker_data *)arg;
pthread_mutex_lock(data->mutex);
for(;;) {
while(!*(data->work_available)) {
pthread_cond_wait(data->work_sig, data->mutex);
}
if (*(data->stop_work)) {
break;
}
(*data->pointers->add_func)(data);
*(data->work_available) = 0;
pthread_cond_signal(data->mon_sig);
}
pthread_mutex_unlock(data->mutex);
return 0;
}
int check_done(monitor_data * data) {
int shared = *(data->shared_data);
int minimum = *(data->shared_minimum);
if (shared < minimum) {
printf("[MONITOR]: Work to be done %d < %d.\\n", shared, minimum);
return 0;
} else {
printf("[MONITOR]: DONE!\\n");
return 1;
}
}
void * do_monitor(void * arg) {
monitor_data * data = (monitor_data * )arg;
sleep(4);
printf("[MONITOR]: Waiting for mutex.\\n");
pthread_mutex_lock(data->mutex);
printf("[MONITOR]: got mutex.\\n");
while(!*(data->work_available)) {
if (check_done(data)) {
break;
}
printf("[MONITOR]: No one is working, kick a working thread into gear.\\n");
*(data->work_available) = 1;
pthread_cond_signal(data->work_sig);
pthread_cond_wait(data->mon_sig, data->mutex);
}
pthread_mutex_unlock(data->mutex);
return 0;
}
int main(void) {
int shared_minimum = 500;
int shared_data = 0;
int num_threads = 10;
int work_available = 0;
int stop_work = 0;
pthread_mutex_t add_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t new_data_sig = PTHREAD_COND_INITIALIZER;
pthread_cond_t do_work_sig = PTHREAD_COND_INITIALIZER;
pthread_t thread_pool[num_threads];
worker_data input_data[num_threads];
pthread_t monitor_thread;
function_pointers pointers = {.add_func = shared_addition};
for (int i=0; i<num_threads; i++) {
input_data[i] = (worker_data){
.mutex = &add_mutex,
.work_sig = &do_work_sig,
.mon_sig = &new_data_sig,
.shared_data = &shared_data,
.pointers = &pointers,
.work_available = &work_available,
.index = i+1,
.stop_work = &stop_work,
};
pthread_create(&thread_pool[i], 0, do_additions, &input_data[i]);
}
monitor_data mon_data = {
.work_sig = &do_work_sig,
.mon_sig = &new_data_sig,
.mutex = &add_mutex,
.shared_minimum = &shared_minimum,
.shared_data = &shared_data,
.work_available = &work_available,
};
pthread_create(&monitor_thread, 0, do_monitor, &mon_data);
printf("[MAIN]: Created monitor thread.\\n");
printf("[MAIN]: Waiting to join monitor thread.\\n");
pthread_join(monitor_thread, 0);
printf("[MAIN]: Joined with monitor thread.\\n");
printf("[MAIN]: Setting stop_work to 1.\\n");
stop_work = 1;
work_available = 1;
printf("[MAIN]: Broadcasting to all sleeping workers.\\n");
pthread_mutex_lock(&add_mutex);
pthread_cond_broadcast(&do_work_sig);
pthread_mutex_unlock(&add_mutex);
for(int i=0; i<num_threads; i++) {
printf("[MAIN]: Joining working thread %d.\\n", i);
pthread_join(thread_pool[i], 0);
printf("[MAIN]: Done joining working thread %d.\\n", i);
}
pthread_mutex_destroy(&add_mutex);
pthread_cond_destroy(&new_data_sig);
pthread_cond_destroy(&do_work_sig);
return 0;
}
| 0
|
#include <pthread.h>
int fichier;
int nombre;
int first;
float valeur;
pthread_mutex_t mutex;
}DONNEE;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
void* min(void* arg){
DONNEE* f = (DONNEE*)arg;
char* tbuf = malloc(sizeof(char));
pthread_mutex_lock(&f->mutex);
int i=0;
read(f->fichier,tbuf,1);
if(f->first)
{
char* buf = (char*)malloc(sizeof(char));
while(*tbuf!='\\n'){
buf=strcat(buf,tbuf);
read(f->fichier,tbuf,1);
}
f->valeur=atof(buf);
read(f->fichier,tbuf,1);
free(buf);
i=1;
f->first=0;
}
while(i<f->nombre && *tbuf!='\\0')
{
char* buf = (char*)malloc(sizeof(char));
while(*tbuf!='\\n' && *tbuf!='\\0'){
buf=strcat(buf,tbuf);
read(f->fichier,tbuf,1);
}
if((f->valeur)>atof(buf))
f->valeur =atof(buf);
read(f->fichier,tbuf,1);
free(buf);
i++;
}
pthread_mutex_unlock(&f->mutex);
return 0;
}
void* max(void* arg){
DONNEE* f = (DONNEE*)arg;
char* tbuf = malloc(sizeof(char));
pthread_mutex_lock(&mutex);
int i=0;
read(f->fichier,tbuf,1);
if(f->first)
{
char* buf = (char*)malloc(sizeof(char));
while(*tbuf!='\\n'){
buf=strcat(buf,tbuf);
read(f->fichier,tbuf,1);
}
f->valeur=atof(buf);
read(f->fichier,tbuf,1);
free(buf);
i=1;
f->first=0;
}
while(i<f->nombre && *tbuf!='\\0')
{
char* buf = (char*)malloc(sizeof(char));
while(*tbuf!='\\n' && *tbuf!='\\0'){
buf=strcat(buf,tbuf);
read(f->fichier,tbuf,1);
}
if((f->valeur) < atof(buf))
f->valeur = atof(buf);
read(f->fichier,tbuf,1);
free(buf);
i++;
}
pthread_mutex_unlock(&mutex);
return 0;
}
void* sum(void* arg){
DONNEE* f = (DONNEE*)arg;
char* tbuf = malloc(sizeof(char));
pthread_mutex_lock(&mutex);
int i=0;
read(f->fichier,tbuf,1);
if(f->first)
{
char* buf = (char*)malloc(sizeof(char));
while(*tbuf!='\\n'){
buf=strcat(buf,tbuf);
read(f->fichier,tbuf,1);
}
f->valeur=atof(buf);
read(f->fichier,tbuf,1);
free(buf);
i=1;
f->first=0;
}
while(i<f->nombre && *tbuf!='\\0')
{
char* buf = (char*)malloc(sizeof(char));
while(*tbuf!='\\n' && *tbuf!='\\0'){
buf=strcat(buf,tbuf);
read(f->fichier,tbuf,1);
}
f->valeur = f->valeur + atof(buf);
read(f->fichier,tbuf,1);
free(buf);
i++;
}
pthread_mutex_unlock(&mutex);
return 0;
}
void* odd(void* arg){
DONNEE* f = (DONNEE*)arg;
char* tbuf = malloc(sizeof(char));
int compteur = 0;
pthread_mutex_lock(&mutex);
int i=0;
read(f->fichier,tbuf,1);
if(f->first)
{
char* buf = (char*)malloc(sizeof(char));
while(*tbuf!='\\n'){
buf=strcat(buf,tbuf);
read(f->fichier,tbuf,1);
}
f->valeur=atof(buf);
compteur = compteur + modulof(f->valeur);
read(f->fichier,tbuf,1);
free(buf);
i=1;
f->first=0;
}
while(i<f->nombre && *tbuf!='\\0')
{
char* buf = (char*)malloc(sizeof(char));
while(*tbuf!='\\n' && *tbuf!='\\0'){
buf=strcat(buf,tbuf);
read(f->fichier,tbuf,1);
}
compteur = compteur + modulof(atof(buf));
f->valeur = compteur;
read(f->fichier,tbuf,1);
free(buf);
i++;
}
pthread_mutex_unlock(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
static void * thread_compteur(void * inutile);
static void * thread_signaux(void * inutile);
static int compteur = 0;
static pthread_mutex_t mutex_compteur = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond_compteur = PTHREAD_COND_INITIALIZER;
static pthread_t thr_signaux;
static pthread_t thr_compteur;
int
main(void) {
pthread_create(& thr_compteur, 0, thread_compteur, 0);
pthread_create(& thr_signaux, 0, thread_signaux, 0);
pthread_exit(0);
}
static void *
thread_compteur(void * inutile) {
sigset_t masque;
sigfillset(& masque);
pthread_sigmask(SIG_BLOCK, & masque, 0);
while (1) {
pthread_mutex_lock(& mutex_compteur);
pthread_cleanup_push(pthread_mutex_unlock,
(void *) & mutex_compteur);
pthread_cond_wait(& cond_compteur,
& mutex_compteur);
fprintf(stdout, "Compteur : %d \\n", compteur);
if (compteur > 5)
break;
pthread_cleanup_pop(1);
}
pthread_cancel(thr_signaux);
return (0);
}
static void *
thread_signaux(void * inutile) {
sigset_t masque;
int numero;
sigemptyset(& masque);
sigaddset(& masque, SIGINT);
sigaddset(& masque, SIGQUIT);
while (1) {
sigwait(& masque, & numero);
pthread_mutex_lock(& mutex_compteur);
switch (numero) {
case SIGINT:
compteur++;
break;
case SIGQUIT:
compteur--;
break;
}
pthread_cond_signal(& cond_compteur);
pthread_mutex_unlock(& mutex_compteur);
}
return (0);
}
| 0
|
#include <pthread.h>
sem_t empty,full;
pthread_mutex_t m;
int buff[5];
void *producer(void *arg)
{
printf("\\nProducer thread created");
sleep(5);
int item,i=0;
while(1)
{
sem_wait(&empty);
item=random()%10;
pthread_mutex_lock(&m);
buff[i++]=item;
printf("\\n%d item is inserted at %d location\\n",item,i-1);
if(i==5)
i=0;
sleep(1);
pthread_mutex_unlock(&m);
sem_post(&full);
}
}
void *consumer(void *arg)
{
printf("\\nConsumer thread created");
sleep(5);
int key,i=0;
while(1)
{
sem_wait(&full);
pthread_mutex_lock(&m);
key=buff[i++];
printf("\\n%d key is extracted from %d location\\n",key,i-1);
if(i==5)
i=0;
sleep(1);
pthread_mutex_unlock(&m);
sem_post(&empty);
}
}
int main()
{
sem_init(&empty,0,5);
sem_init(&full,0,0);
pthread_mutex_init(&m,0);
pthread_t pid,cid;
pthread_create(&pid,0,producer,0);
sleep(1);
pthread_create(&cid,0,consumer,0);
sleep(1);
pthread_join(pid,0);
pthread_join(cid,0);
printf("\\nMain thread terminated\\n");
}
| 1
|
#include <pthread.h>
static int volatile global1;
static int volatile global2;
static pthread_mutex_t mux = PTHREAD_MUTEX_INITIALIZER;
static void *
thr_main(void *ign)
{
while (!force_quit) {
int v1;
int v2;
STOP_ANALYSIS();
pthread_mutex_lock(&mux);
v1 = global1;
pthread_mutex_unlock(&mux);
pthread_mutex_lock(&mux);
v2 = global2;
pthread_mutex_unlock(&mux);
assert(v1 == v2);
STOP_ANALYSIS();
usleep(1000);
read_cntr++;
}
return 0;
}
int
main()
{
pthread_t thr;
time_t start_time = time(0);
int forever = 0;
if (getenv("SOS22_RUN_FOREVER"))
forever = 1;
global1 = 99;
global2 = 99;
pthread_create(&thr, 0, thr_main, 0);
while (forever || time(0) < start_time + 10) {
STOP_ANALYSIS();
pthread_mutex_lock(&mux);
global1 = 5;
STOP_ANALYSIS();
global2 = 5;
pthread_mutex_unlock(&mux);
STOP_ANALYSIS();
usleep(1000);
STOP_ANALYSIS();
pthread_mutex_lock(&mux);
global1 = 7;
global2 = 7;
pthread_mutex_unlock(&mux);
STOP_ANALYSIS();
write_cntr++;
}
force_quit = 1;
pthread_join(thr, 0);
printf("Survived, %d read events and %d write events\\n", read_cntr, write_cntr);
return 0;
}
| 0
|
#include <pthread.h>
int flag;
int edge;
pthread_mutex_t lock;
struct square *next;
struct square *prev;
} square;
int generator;
int license;
} carParam;
struct square trafficCircle[5][5];
int run = 1;
pthread_t carGenerators[4];
struct carParam arr1[200];
struct carParam arr2[200];
struct carParam arr3[200];
struct carParam arr4[200];
void* car(void *arg) {
struct carParam *arr;
struct square *p;
int x, y, tmp =1;
arr = (struct carParam *) arg;
switch (arr->generator) {
case 1:
p = &(trafficCircle[0][5 - 1]);
break;
case 2:
p = &(trafficCircle[0][0]);
break;
case 3:
p = &(trafficCircle[5 - 1][0]);
break;
case 4:
p = &(trafficCircle[5 - 1][5 - 1]);
break;
}
while (run) {
if (tmp) {
pthread_mutex_lock(&(p->prev->lock));
pthread_mutex_lock(&(p->lock));
if (p->flag == 0 && p->prev->flag == 0) {
p->flag = 1;
tmp = 0;
}
pthread_mutex_unlock(&(p->lock));
pthread_mutex_unlock(&(p->prev->lock));
} else {
}
}
return 0;
}
void* Generator(void *arg) {
pthread_t cars[200];
struct carParam *arr;
int counter = 0;
int time, err, i;
arr = (struct carParam *) arg;
while (i < 200) {
arr[i++].license = -1;
arr[i++].generator = *((int*) arg);
}
while (run) {
time = (rand() % (9000000 - 8000000))
+ 8000000;
usleep(time / 1000);
arr[counter].license = counter;
err = pthread_create(&(cars[counter]), 0, &car, &(arr[counter]));
if (err != 0)
printf("\\ncan't create thread :[%s]\\n", strerror(err));
for (i = 0; i < 200; i++) {
if (arr[i].license == -1)
counter = i;
}
}
return 0;
}
int main(void) {
int i = 0, j = 0, tmp = 0;
struct square *p;
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
if (pthread_mutex_init(&(trafficCircle[i][j].lock), 0) != 0) {
printf("\\n mutex init failed\\n");
return 1;
}
trafficCircle[i][j].flag = tmp++;
switch (i) {
case 0:
if (j == 0) {
trafficCircle[i][j].next = &trafficCircle[i + 1][j];
trafficCircle[i][j].prev = &trafficCircle[i][j + 1];
} else if (j == 5 - 1) {
trafficCircle[i][j].next = &trafficCircle[i][j - 1];
trafficCircle[i][j].prev = &trafficCircle[i + 1][j];
} else {
trafficCircle[i][j].next = &trafficCircle[i][j - 1];
trafficCircle[i][j].prev = &trafficCircle[i][j + 1];
}
continue;
case 5 - 1:
if (j == 5 - 1) {
trafficCircle[i][j].next = &trafficCircle[i - 1][j];
trafficCircle[i][j].prev = &trafficCircle[i][j - 1];
} else if (j == 0) {
trafficCircle[i][j].next = &trafficCircle[i][j + 1];
trafficCircle[i][j].prev = &trafficCircle[i - 1][j];
} else {
trafficCircle[i][j].next = &trafficCircle[i][j + 1];
trafficCircle[i][j].prev = &trafficCircle[i][j - 1];
}
continue;
}
switch (j) {
case 0:
trafficCircle[i][j].next = &trafficCircle[i + 1][j];
trafficCircle[i][j].prev = &trafficCircle[i - 1][j];
continue;
case 5 - 1:
trafficCircle[i][j].next = &trafficCircle[i - 1][j];
trafficCircle[i][j].prev = &trafficCircle[i + 1][j];
continue;
}
}
}
p = &(trafficCircle[0][0]);
for (i = 0; i < 30; i++) {
if (p->prev != 0)
printf("%d %d\\n", p->flag, p->prev->flag);
else
printf("%d\\n", p->flag);
p = p->next;
}
return 0;
}
| 1
|
#include <pthread.h>
extern unsigned volatile int *lock;
FILE *fileout_sha;
FILE *fileout_rijndaelenc;
FILE *fileout_rijndaeldec;
FILE *fileout_blowfishenc;
FILE *fileout_blowfishdec;
FILE *filein_sha;
FILE *filein_rijndaelenc;
FILE *filein_rijndaeldec;
FILE *filein_blowfishenc;
FILE *filein_blowfishdec;
volatile int procCounter = 0;
volatile int barrier_in = 0;
volatile int procsFinished = 0;
extern pthread_mutex_t mutex_print;
extern pthread_mutex_t mutex_malloc;
int NSOFTWARES = 4;
void open_files();
void close_files();
int main(int argc, char *argv[])
{
register int procNumber;
AcquireGlobalLock();
procNumber = procCounter++;
ReleaseGlobalLock();
if (procNumber == 0){
printf("\\n");
printf("--------------------------------------------------------------------\\n");
printf("------------------------- MPSoCBench -----------------------------\\n");
printf("--------------------Running: multi_security ------------------------\\n");
printf("---------SHA, Rijndael Encoder, Rijndael Decoder, Blowfish----------\\n");
printf("--------------------------------------------------------------------\\n");
printf("\\n");
open_files();
pthread_mutex_init(&mutex_print,0);
pthread_mutex_init(&mutex_malloc,0);
AcquireGlobalLock();
barrier_in = 1;
ReleaseGlobalLock();
main_sha();
pthread_mutex_lock(&mutex_print);
printf("\\nSha finished.\\n");
pthread_mutex_unlock(&mutex_print);
}
else if (procNumber == 1)
{
while(barrier_in == 0);
main_rijndael_enc();
pthread_mutex_lock(&mutex_print);
printf("\\nRijndael Encoder finished.\\n");
pthread_mutex_unlock(&mutex_print);
}
else if (procNumber == 2)
{
while(barrier_in == 0);
main_rijndael_dec();
pthread_mutex_lock(&mutex_print);
printf("\\nRijndael Decoder finished.\\n");
pthread_mutex_unlock(&mutex_print);
}
else if (procNumber == 3)
{
while(barrier_in == 0);
main_blowfish("E");
pthread_mutex_lock(&mutex_print);
printf("\\nBlowfish Encoder finished.\\n");
pthread_mutex_unlock(&mutex_print);
}
else
{
printf("\\nERROR!\\n");
}
AcquireGlobalLock();
procsFinished++;
if(procsFinished == NSOFTWARES)
{
close_files();
}
ReleaseGlobalLock();
_exit(0);
return 0;
}
void close_files ()
{
fclose(fileout_sha);
fclose(fileout_rijndaelenc);
fclose(fileout_rijndaeldec);
fclose(fileout_blowfishenc);
}
void open_files ()
{
fileout_sha = fopen("output_sha","w");
if (fileout_sha == 0){
printf("Error: fopen() fileout_sha\\n");
exit(1);
}
fileout_rijndaelenc = fopen("output_encoder_rijndael","w");
if (fileout_rijndaelenc == 0){
printf("Error: fopen() fileout_rijndaelenc\\n");
exit(1);
}
fileout_rijndaeldec = fopen("output_decoder_rijndael","w");
if (fileout_rijndaeldec == 0){
printf("Error: fopen() fileout_rijndaeldec\\n");
exit(1);
}
fileout_blowfishenc = fopen("output_blowfish","w");
if (fileout_blowfishenc == 0){
printf("Error: fopen() fileout_blowfishenc\\n");
exit(1);
}
filein_sha = fopen("input_large.asc","r");
if (filein_sha == 0){
printf("Error: fopen() filein_sha\\n");
exit(1);
}
filein_rijndaelenc = fopen("inputencoder.asc","r");
if (filein_rijndaelenc == 0){
printf("Error: fopen() filein_rijndaelenc\\n");
exit(1);
}
filein_rijndaeldec = fopen("inputdecoder.enc","r");
if (filein_rijndaeldec == 0){
printf("Error: fopen() filein_rijndaeldec\\n");
exit(1);
}
filein_blowfishenc = fopen("inputencoder_large.asc","r");
if (filein_blowfishenc == 0){
printf("Error: fopen() filein_blowfishenc\\n");
exit(1);
}
}
| 0
|
#include <pthread.h>
int globl = 0;
int count = 0;
pthread_mutex_t lock;
int thread_rand(pthread_mutex_t* arg) {
pthread_mutex_lock(arg);
globl += (int) (10 * ((double) rand()) / 32767);
--count;
if(count == 0) {
pthread_mutex_unlock(&lock);
}
pthread_mutex_unlock(arg);
return 0;
}
int thread_print(void* arg) {
(void) arg;
pthread_mutex_lock(&lock);
printf("globl = %d\\n", globl);
pthread_mutex_unlock(&lock);
return 0;
}
int main(int argc, char* argv[]) {
if(argc != 2) {
printf("usage: %s THREAD_COUNT\\n", argv[0]);
exit(1);
}
int thread_count = atoi(argv[1]);
pthread_t *t = malloc(thread_count * sizeof(pthread_t));
pthread_t print;
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, 0);
pthread_mutex_init(&lock, 0);
pthread_mutex_lock(&lock);
pthread_create(&print, 0, (void* (*)(void*)) thread_print, (void*) 0);
count = thread_count;
srand(time(0));
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
for(int64_t i = 0; i < thread_count; ++i) {
pthread_create(t + i, &attr, (void* (*)(void*)) thread_rand, (void*) &mutex);
}
pthread_join(print, 0);
return 0;
}
| 1
|
#include <pthread.h>
struct ap_hash_head_t *aphead = 0;
unsigned int conflict_count = 0;
unsigned int ap_innet_cnt = 0;
unsigned int ap_reg_cnt = 0;
static unsigned int
__elfhash(char* str, unsigned int len)
{
unsigned int hash = 0;
unsigned int x = 0;
unsigned int i = 0;
for(i = 0; i < len; str++, i++)
{
hash = (hash << 4) + (*str);
if((x = hash & 0xF0000000L) != 0)
{
hash ^= (x >> 24);
}
hash &= ~x;
}
return hash;
}
static unsigned int
__hash_key(char *data, unsigned int len)
{
assert(data != 0 && len > 0);
return __elfhash(data, len) % MAX_BUCKET;
}
struct ap_hash_t *hash_ap(char *mac)
{
assert(mac != 0);
char *dest;
int key, len = 6;
struct ap_hash_head_t *head = 0;
struct ap_hash_t **pprev, *aphash = 0;
pprev = &aphash;
key = __hash_key(mac, len);
head = aphead + key;
pthread_mutex_lock(&head->lock);
aphash = &head->aphash;
dest = aphash->ap.mac;
if(aphash->key == IDLE_AP)
goto new;
while(aphash) {
pprev = &aphash;
if(!strncmp(aphash->ap.mac, mac, ETH_ALEN))
goto ret;
aphash = aphash->apnext;
conflict_count++;
}
aphash = calloc(1, sizeof(struct ap_hash_t));
if(aphash == 0) {
sys_err("Calloc failed: %s\\n",
strerror(errno));
return 0;
}
(*pprev)->apnext = aphash;
goto new;
new:
pthread_mutex_init(&aphash->lock, 0);
aphash->key = key;
aphash->ptail = &aphash->next;
memcpy(dest, mac, len);
ap_innet_cnt++;
ret:
pthread_mutex_unlock(&head->lock);
pr_hash(key, aphash, mac);
return aphash;
}
void hash_init()
{
assert(aphead == 0);
_Static_assert(MAX_BUCKET < (1ull << 32), "ap num too large\\n");
aphead = calloc(1, sizeof(struct ap_hash_head_t) * MAX_BUCKET);
if(aphead == 0) {
sys_err("Malloc hash bucket failed: %s\\n",
strerror(errno));
exit(-1);
}
sys_debug("Max support ap: %lu\\n", MAX_BUCKET);
int i;
for(i = 0; i < MAX_BUCKET; i++) {
aphead[i].aphash.key = IDLE_AP;
aphead[i].aphash.ptail = &aphead[i].aphash.next;
pthread_mutex_init(&aphead[i].lock, 0);
}
return;
}
void message_insert(struct ap_hash_t *aphash, struct message_t *msg)
{
assert(aphash != 0);
msg->next = 0;
sys_debug("message insert aphash: %p, msg: %p\\n", aphash, msg);
pthread_mutex_lock(&aphash->lock);
*(aphash->ptail) = msg;
aphash->ptail = &msg->next;
aphash->count++;
pthread_mutex_unlock(&aphash->lock);
}
static struct message_t *message_delete(struct ap_hash_t *aphash)
{
if(aphash->next == 0)
return 0;
struct message_t *msg;
pthread_mutex_lock(&aphash->lock);
msg = aphash->next;
aphash->next = msg->next;
aphash->count--;
if(&msg->next == aphash->ptail)
aphash->ptail = &aphash->next;
pthread_mutex_unlock(&aphash->lock);
sys_debug("message delete aphash: %p, msg: %p\\n", aphash, msg);
return msg;
}
static void message_free(struct message_t *msg)
{
free(msg);
}
static void *message_travel(void *arg)
{
assert(aphead != 0);
struct ap_hash_t *aphash;
struct message_t *msg;
int i;
while(1) {
sleep(argument.msgitv);
for(i = 0; i < MAX_BUCKET; i++) {
aphash = &(aphead[i].aphash);
while(aphash) {
while((msg = message_delete(aphash))) {
msg_proc(aphash,
(void *)&msg->data[0],
msg->len,
msg->proto);
message_free(msg);
}
aphash = aphash->apnext;
}
}
}
}
void message_travel_init()
{
create_pthread(message_travel, 0);
}
| 0
|
#include <pthread.h>
int buf[10];
size_t len;
pthread_mutex_t mutex;
pthread_cond_t can_produce;
pthread_cond_t can_consume;
} buffer_t;
int isPrime(int n){
int i;
if(n % 2 == 0){
return 0;
}
for(i = 3; i <= sqrt(n); i = i + 2){
if(n % i == 0){
return 0;
}
}
return 1;
}
void* producer(void *arg) {
buffer_t *buffer = (buffer_t*)arg;
while(1) {
usleep(100 * 1000);
int t = (rand() % (1000 +1-100)) + 100;
printf("Produced: %d\\n", t);
sleep(rand() % 2);
pthread_mutex_lock(&buffer->mutex);
if(buffer->len == 10) {
pthread_cond_wait(&buffer->can_produce, &buffer->mutex);
}
buffer->buf[buffer->len] = t;
++buffer->len;
int i;
for(i = 0; i < buffer->len; ++i){
printf("%d ", buffer->buf[i]);
}
printf("\\n");
pthread_cond_signal(&buffer->can_consume);
pthread_mutex_unlock(&buffer->mutex);
}
return 0;
}
void* consumer(void *arg) {
buffer_t *buffer = (buffer_t*)arg;
int work;
while(1) {
pthread_mutex_lock(&buffer->mutex);
while(buffer->len == 0) {
pthread_cond_wait(&buffer->can_consume, &buffer->mutex);
}
--buffer->len;
work = buffer->buf[buffer->len];
pthread_cond_signal(&buffer->can_produce);
pthread_mutex_unlock(&buffer->mutex);
if(isPrime(work)){
printf("Thread %ld: number <%d>, prime: YES\\n", (long)pthread_self(), work);
}
else{
printf("Thread %ld: number <%d>, prime: NO\\n", (long)pthread_self(), work);
}
sleep(rand() % 4);
}
return 0;
}
int main(int argc, char *argv[]){
buffer_t buffer = {
.len = 0,
.mutex = PTHREAD_MUTEX_INITIALIZER,
.can_produce = PTHREAD_COND_INITIALIZER,
.can_consume = PTHREAD_COND_INITIALIZER
};
pthread_t prod, cons[3];
pthread_create(&prod, 0, producer, (void*)&buffer);
pthread_create(&cons[0], 0, consumer, (void*)&buffer);
pthread_create(&cons[1], 0, consumer, (void*)&buffer);
pthread_create(&cons[2], 0, consumer, (void*)&buffer);
pthread_join(prod, 0);
pthread_join(cons[0], 0);
pthread_join(cons[1], 0);
pthread_join(cons[2], 0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t verroux = PTHREAD_MUTEX_INITIALIZER;
int nbzone=4;
int peutlancerT2=0;
pthread_cond_t condition;
int tabf[4]={0,1,2,3};
int tabZAT[3]={-1,-1,-1};
void* actionT1(void* p)
{
printf("lancement T1 \\n");
int i;
int j;
for(i=0;i<nbzone;i++)
{
pthread_mutex_lock(&verroux);
tabZAT[0]++;
pthread_cond_broadcast(&condition);
int k;
for(k=0;k<3;k++)
{
printf("thread %d: zone: %d\\n",k,tabZAT[k]);
}
pthread_mutex_unlock(&verroux);
tabf[i]++;
sleep(2);
printf("case %d T1: %d\\n",i,tabf[i]);
}
pthread_mutex_lock(&verroux);
tabZAT[0]++;
pthread_cond_broadcast(&condition);
pthread_mutex_unlock(&verroux);
}
void* actionT2(void* p)
{
printf("lancement T2 \\n");
int i;
for(i=0;i<nbzone;i++)
{
pthread_mutex_lock(&verroux);
tabZAT[1]++;
pthread_cond_broadcast(&condition);
while(i>=tabZAT[0])
{
pthread_cond_wait(&condition,&verroux);
}
int k;
for(k=0;k<3;k++)
{
printf("thread %d: zone: %d\\n",k,tabZAT[k]);
}
pthread_mutex_unlock(&verroux);
printf("T2 traite: %d\\n",i);
tabf[i]=tabf[i]*10;
sleep(2);
}
pthread_mutex_lock(&verroux);
tabZAT[1]++;
pthread_cond_broadcast(&condition);
pthread_mutex_unlock(&verroux);
}
void* actionT3(void* p){
printf("lancement T3 \\n");
int i;
for(i=0;i<nbzone;i++)
{
pthread_mutex_lock(&verroux);
tabZAT[2]++;
pthread_cond_broadcast(&condition);
while(i>=tabZAT[1])
{
pthread_cond_wait(&condition,&verroux);
}
int k;
for(k=0;k<3;k++){
printf("thread %d: zone: %d\\n",k,tabZAT[k]);
}
pthread_mutex_unlock(&verroux);
tabf[i]=tabf[i]+1000;
sleep(2);
printf("case %d T3: %d\\n",i,tabf[i]);
}
pthread_mutex_lock(&verroux);
tabZAT[2]++;
pthread_cond_broadcast(&condition);
pthread_mutex_unlock(&verroux);
}
int main(int argc, char** argv) {
pthread_t T1,T2,T3;
pthread_cond_init(&condition,0);
int k;
for(k=0;k<3;k++){
printf("thread %d: zone: %d\\n",k,tabZAT[k]);
}
pthread_create(&T1,0,actionT1,0);
pthread_create(&T2,0,actionT2,0);
pthread_create(&T3,0,actionT3,0);
pthread_join(T1,0);
pthread_join(T2,0);
pthread_join(T3,0);
return (0);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t IO_Q_Lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t IO_Q_Cond = PTHREAD_COND_INITIALIZER;
static volatile int IO_Q_Halt_Thread = 0;
static pthread_t IO_Q_Thread;
static int32_t Status;
static int32_t Command;
static int32_t Address;
static int32_t Size;
static void *terminal_device(void *arg)
{
int size;
char *buffer;
while (IO_Q_Halt_Thread == 0)
{
pthread_mutex_lock(&IO_Q_Lock);
while ( !IO_Q_Halt_Thread && (Command & DMA_T_CMD_START_READ) == 0)
{
pthread_cond_wait(&IO_Q_Cond, &IO_Q_Lock);
}
if (Command & DMA_T_CMD_START_READ)
{
Command &= ~DMA_T_CMD_START_READ;
Status &= ~(DMA_T_STATUS_READ_DONE | DMA_T_STATUS_READ_ERROR);
Status |= DMA_T_STATUS_READ_BUSY;
size = Size;
buffer = (char *)Abs_Get_Addr(Address);
if (buffer == 0)
{
Machine_Check(MC_HW_WARNING | MC_ILLEGAL_ADDR,
"DMA_T read to invalid address");
}
else
{
pthread_mutex_unlock(&IO_Q_Lock);
buffer = fgets(buffer, size, stdin);
pthread_mutex_lock(&IO_Q_Lock);
Status &= ~DMA_T_STATUS_READ_BUSY;
Status |= DMA_T_STATUS_READ_DONE | DMA_T_STATUS_ATTN;
if (buffer == 0) Status |= DMA_T_STATUS_READ_ERROR;
if (Command & DMA_T_CMD_INT_ENA)
{
Machine_Signal_Interrupt(1, DMA_T_VECTOR);
}
}
}
pthread_mutex_unlock(&IO_Q_Lock);
}
return 0;
}
static int32_t get_word(int32_t id, int32_t addr)
{
int32_t value;
pthread_mutex_lock(&IO_Q_Lock);
if (addr == 0)
{
value = Status;
Status = 0;
}
else if (addr == 4)
value = Command;
else if (addr == 8)
value = Address;
else
value = Size;
pthread_mutex_unlock(&IO_Q_Lock);
return value;
}
static int32_t get_byte(int32_t id, int32_t addr)
{
return 0xFFFFFFFF;
}
static void set_word(int32_t id, int32_t addr, int32_t value)
{
pthread_mutex_lock(&IO_Q_Lock);
if (addr == 0)
Status = 0;
else if (addr == 4)
{
Command = value;
if (Command & DMA_T_CMD_START_WRITE)
{
char *buffer = (char*)Abs_Get_Addr(Address);
if (buffer == 0)
{
Machine_Check(MC_HW_WARNING | MC_ILLEGAL_ADDR,
"DMA_T write from invalid address");
}
else
{
printf("%s", buffer);
Status &= ~(DMA_T_STATUS_WRITE_BUSY | DMA_T_STATUS_WRITE_ERROR);
Status |= DMA_T_STATUS_WRITE_DONE | DMA_T_STATUS_ATTN;
if (Command & DMA_T_CMD_INT_ENA)
{
Machine_Signal_Interrupt(0, DMA_T_VECTOR);
}
}
}
pthread_cond_signal(&IO_Q_Cond);
}
else if (addr == 8)
Address = value;
else
Size = value;
pthread_mutex_unlock(&IO_Q_Lock);
}
static void set_byte(int32_t id, int32_t addr, int32_t value)
{
}
static void DMA_T_Finish()
{
IO_Q_Halt_Thread = 1;
pthread_cond_signal(&IO_Q_Cond);
pthread_join(IO_Q_Thread, 0);
}
int DMA_T_Init()
{
IO_Q_Halt_Thread = 0;
pthread_create(&IO_Q_Thread, 0, terminal_device, 0);
IO_Register_Handler(0, DMA_T_STATUS, 16,
get_word, get_byte, set_word, set_byte);
atexit(DMA_T_Finish);
return 0;
}
| 1
|
#include <pthread.h>
enum IOCTL_CMD
{
IOCTL_UNKOWN = 0x100,
IOCTL_GET_ENV_INFO,
IOCTL_WAIT_VE,
IOCTL_RESET_VE,
IOCTL_ENABLE_VE,
IOCTL_DISABLE_VE,
IOCTL_SET_VE_FREQ,
IOCTL_CONFIG_AVS2 = 0x200,
IOCTL_GETVALUE_AVS2 ,
IOCTL_PAUSE_AVS2 ,
IOCTL_START_AVS2 ,
IOCTL_RESET_AVS2 ,
IOCTL_ADJUST_AVS2,
IOCTL_ENGINE_REQ,
IOCTL_ENGINE_REL,
IOCTL_ENGINE_CHECK_DELAY,
IOCTL_GET_IC_VER,
IOCTL_ADJUST_AVS2_ABS,
IOCTL_FLUSH_CACHE
};
struct ve_info
{
uint32_t reserved_mem;
int reserved_mem_size;
uint32_t registers;
};
struct cedarv_cache_range
{
long start;
long end;
};
struct memchunk_t
{
uint32_t phys_addr;
int size;
void *virt_addr;
struct memchunk_t *next;
};
static struct
{
int fd;
void *regs;
int version;
struct memchunk_t first_memchunk;
pthread_rwlock_t memory_lock;
pthread_mutex_t device_lock;
} ve = { .fd = -1, .memory_lock = PTHREAD_RWLOCK_INITIALIZER, .device_lock = PTHREAD_MUTEX_INITIALIZER };
int ve_open(void)
{
if (ve.fd != -1)
return 0;
struct ve_info info;
ve.fd = open("/dev/cedar_dev", O_RDWR);
if (ve.fd == -1)
return 0;
if (ioctl(ve.fd, IOCTL_GET_ENV_INFO, (void *)(&info)) == -1)
goto err;
ve.regs = mmap(0, 0x800, PROT_READ | PROT_WRITE, MAP_SHARED, ve.fd, info.registers);
if (ve.regs == MAP_FAILED)
goto err;
ve.first_memchunk.phys_addr = info.reserved_mem - (0xc0000000);
ve.first_memchunk.size = info.reserved_mem_size;
ioctl(ve.fd, IOCTL_ENGINE_REQ, 0);
ioctl(ve.fd, IOCTL_ENABLE_VE, 0);
ioctl(ve.fd, IOCTL_SET_VE_FREQ, 320);
ioctl(ve.fd, IOCTL_RESET_VE, 0);
writel(0x00130007, ve.regs + VE_CTRL);
ve.version = readl(ve.regs + VE_VERSION) >> 16;
printf("[VDPAU SUNXI] VE version 0x%04x opened.\\n", ve.version);
return 1;
err:
close(ve.fd);
ve.fd = -1;
return 0;
}
void ve_close(void)
{
if (ve.fd == -1)
return;
ioctl(ve.fd, IOCTL_DISABLE_VE, 0);
ioctl(ve.fd, IOCTL_ENGINE_REL, 0);
munmap(ve.regs, 0x800);
ve.regs = 0;
close(ve.fd);
ve.fd = -1;
}
int ve_get_version(void)
{
return ve.version;
}
int ve_wait(int timeout)
{
if (ve.fd == -1)
return 0;
return ioctl(ve.fd, IOCTL_WAIT_VE, timeout);
}
void *ve_get(int engine, uint32_t flags)
{
if (pthread_mutex_lock(&ve.device_lock))
return 0;
writel(0x00130000 | (engine & 0xf) | (flags & ~0xf), ve.regs + VE_CTRL);
return ve.regs;
}
void ve_put(void)
{
writel(0x00130007, ve.regs + VE_CTRL);
pthread_mutex_unlock(&ve.device_lock);
}
void *ve_malloc(int size)
{
if (ve.fd == -1)
return 0;
if (pthread_rwlock_wrlock(&ve.memory_lock))
return 0;
void *addr = 0;
size = (size + (4096) - 1) & ~((4096) - 1);
struct memchunk_t *c, *best_chunk = 0;
for (c = &ve.first_memchunk; c != 0; c = c->next)
{
if(c->virt_addr == 0 && c->size >= size)
{
if (best_chunk == 0 || c->size < best_chunk->size)
best_chunk = c;
if (c->size == size)
break;
}
}
if (!best_chunk)
goto out;
int left_size = best_chunk->size - size;
addr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, ve.fd, best_chunk->phys_addr + (0xc0000000));
if (addr == MAP_FAILED)
{
addr = 0;
goto out;
}
best_chunk->virt_addr = addr;
best_chunk->size = size;
if (left_size > 0)
{
c = malloc(sizeof(struct memchunk_t));
c->phys_addr = best_chunk->phys_addr + size;
c->size = left_size;
c->virt_addr = 0;
c->next = best_chunk->next;
best_chunk->next = c;
}
out:
pthread_rwlock_unlock(&ve.memory_lock);
return addr;
}
void ve_free(void *ptr)
{
if (ve.fd == -1)
return;
if (ptr == 0)
return;
if (pthread_rwlock_wrlock(&ve.memory_lock))
return;
struct memchunk_t *c;
for (c = &ve.first_memchunk; c != 0; c = c->next)
{
if (c->virt_addr == ptr)
{
munmap(ptr, c->size);
c->virt_addr = 0;
break;
}
}
for (c = &ve.first_memchunk; c != 0; c = c->next)
{
if (c->virt_addr == 0)
{
while (c->next != 0 && c->next->virt_addr == 0)
{
struct memchunk_t *n = c->next;
c->size += n->size;
c->next = n->next;
free(n);
}
}
}
pthread_rwlock_unlock(&ve.memory_lock);
}
uint32_t ve_virt2phys(void *ptr)
{
if (ve.fd == -1)
return 0;
if (pthread_rwlock_rdlock(&ve.memory_lock))
return 0;
uint32_t addr = 0;
struct memchunk_t *c;
for (c = &ve.first_memchunk; c != 0; c = c->next)
{
if (c->virt_addr == 0)
continue;
if (c->virt_addr == ptr)
{
addr = c->phys_addr;
break;
}
else if (ptr > c->virt_addr && ptr < (c->virt_addr + c->size))
{
addr = c->phys_addr + (ptr - c->virt_addr);
break;
}
}
pthread_rwlock_unlock(&ve.memory_lock);
return addr;
}
void ve_flush_cache(void *start, int len)
{
if (ve.fd == -1)
return;
struct cedarv_cache_range range =
{
.start = (int)start,
.end = (int)(start + len)
};
ioctl(ve.fd, IOCTL_FLUSH_CACHE, (void*)(&range));
}
| 0
|
#include <pthread.h>
extern char **environ;
static pthread_mutex_t env_mutex;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
static void thread_init(void);
int getenv_r(const char *name, char *buf, int buflen);
int putenv_r(const char *s);
int putenv_r(const char *s)
{
pthread_once(&init_done, thread_init);
pthread_mutex_lock(&env_mutex);
putenv(s_dup(s));
pthread_mutex_unlock(&env_mutex);
return (ENOENT);
}
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);
}
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);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutexes[3];
pthread_cond_t conditionVars[3];
int permits[3];
pthread_t tids[3];
int data = 0;
void * Philosopher(void * arg){
int i;
i = (int)arg;
pthread_mutex_lock(&mutexes[i%3]);
while (permits[i%3] == 0) {
printf("P%d : tryget F%d\\n", i, i%3);
pthread_cond_wait(&conditionVars[i%3],&mutexes[i%3]);
}
permits[i%3] = 0;
printf("P%d : get F%d\\n", i, i%3);
pthread_mutex_unlock(&mutexes[i%3]);
pthread_mutex_lock(&mutexes[(i+1)%3]);
while (permits[(i+1)%3] == 0) {
printf("P%d : tryget F%d\\n", i, (i+1)%3);
pthread_cond_wait(&conditionVars[(i+1)%3],&mutexes[(i+1)%3]);
}
permits[(i+1)%3] = 0;
printf("P%d : get F%d\\n", i, (i+1)%3);
pthread_mutex_unlock(&mutexes[(i+1)%3]);
printf("%d\\n", i);
fflush(stdout);
pthread_mutex_lock(&mutexes[(i+1)%3]);
permits[(i+1)%3] = 1;
printf("P%d : put F%d\\n", i, (i+1)%3);
pthread_cond_signal(&conditionVars[(i+1)%3]);
pthread_mutex_unlock(&mutexes[(i+1)%3]);
pthread_mutex_lock(&mutexes[i%3]);
permits[i%3] = 1;
printf("P%d : put F%d\\n", i, i%3);
pthread_cond_signal(&conditionVars[i%3]);
pthread_mutex_unlock(&mutexes[i%3]);
return 0;
}
void * OddPhilosopher(void * arg){
int i;
i = (int)arg;
pthread_mutex_lock(&mutexes[(i+1)%3]);
while (permits[(i+1)%3] == 0) {
printf("P%d : tryget F%d\\n", i, (i+1)%3);
pthread_cond_wait(&conditionVars[(i+1)%3],&mutexes[(i+1)%3]);
}
permits[(i+1)%3] = 0;
printf("P%d : get F%d \\n", i, (i+1)%3);
pthread_mutex_unlock(&mutexes[(i+1)%3]);
pthread_mutex_lock(&mutexes[i%3]);
while (permits[i%3] == 0) {
printf("P%d : tryget F%d\\n", i, i%3);
pthread_cond_wait(&conditionVars[i%3],&mutexes[i%3]);
}
permits[i%3] = 0;
printf("P%d : get F%d \\n", i, i%3);
pthread_mutex_unlock(&mutexes[i%3]);
printf("%d\\n", i);
fflush(stdout);
pthread_mutex_lock(&mutexes[i%3]);
permits[i%3] = 1;
printf("P%d : put F%d \\n", i, i%3);
pthread_cond_signal(&conditionVars[i%3]);
pthread_mutex_unlock(&mutexes[i%3]);
pthread_mutex_lock(&mutexes[(i+1)%3]);
permits[(i+1)%3] = 1;
printf("P%d : put F%d \\n", i, (i+1)%3);
pthread_cond_signal(&conditionVars[(i+1)%3]);
pthread_mutex_unlock(&mutexes[(i+1)%3]);
return 0;
}
int main(){
int i;
for (i = 0; i < 3; i++)
pthread_mutex_init(&mutexes[i], 0);
for (i = 0; i < 3; i++)
pthread_cond_init(&conditionVars[i], 0);
for (i = 0; i < 3; i++)
permits[i] = 1;
for (i = 0; i < 3 -1; i++){
pthread_create(&tids[i], 0, Philosopher, (void*)(i) );
}
pthread_create(&tids[3 -1], 0, OddPhilosopher, (void*)(3 -1) );
for (i = 0; i < 3; i++){
pthread_join(tids[i], 0);
}
for (i = 0; i < 3; i++){
pthread_mutex_destroy(&mutexes[i]);
}
for (i = 0; i < 3; i++){
pthread_cond_destroy(&conditionVars[i]);
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int final_result = 0;
struct thread_data{
int startidx;
int maxidx;
};
void *line (void *threadarg) {
int sx, sy, err, dx, dy, e2, x_pixel, y_pixel;
int sight;
int result=0;
int x0, y0;
struct thread_data* arg = (struct thread_data*) threadarg;
int y_start = arg->startidx;
int y_end = arg->maxidx;
int x1=30;
int y1=15;
for (y_pixel=y_start; y_pixel<y_end; y_pixel++) {
for (x_pixel=0; x_pixel<60; x_pixel++) {
sight=1;
x0 = x_pixel;
y0 = y_pixel;
if (x0 < x1) {
sx=1;
dx=x1-x0;
}
else {
sx=-1;
dx=x0-x1;
}
if (y0 < y1) {
sy=1;
dy=y1-y0;
}
else {
sy=-1;
dy=y0-y1;
}
err=dx-dy;
while (1) {
if ((x0==x1) && (y0==y1)) {
break;
}
if (obstacles[y0][x0] == 1) {
sight=0;
break;
}
e2=2*err;
if (e2 > -dy) {
err = err - dy;
x0 = x0+sx;
}
if (e2 < dx) {
err = err + dx;
y0 = y0 + sy;
}
}
if (sight == 1) {
output[y_pixel][x_pixel] = input[y_pixel][x_pixel];
}
else {
output[y_pixel][x_pixel] = 0;
}
}
}
for (y_pixel=y_start; y_pixel<y_end; y_pixel++) {
for (x_pixel=0; x_pixel<60; x_pixel++) {
result += (expected[y_pixel][x_pixel] == output[y_pixel][x_pixel]);
}
}
pthread_mutex_lock (&mutex);
final_result += result;
pthread_mutex_unlock (&mutex);
pthread_exit(0);
}
int result[6];
int main() {
int i,j;
int main_result=0;
pthread_t threads[6];
struct thread_data data[6];
for (i=0; i<6; i++) {
data[i].startidx = i*30/6;
data[i].maxidx = (i+1)*30/6;
pthread_create(&threads[i], 0, line, (void *)&data[i]);
}
for (i=0; i<6; i++) {
pthread_join(threads[i], 0);
}
printf ("Result: %d\\n", final_result);
if (final_result == 1800) {
printf("RESULT: PASS\\n");
} else {
printf("RESULT: FAIL\\n");
}
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t POS_Optics_Write_Lock = PTHREAD_MUTEX_INITIALIZER;
static int POS_Optical_state_Percent;
void Init_Optics(void)
{
pthread_mutex_unlock(&POS_Optics_Write_Lock);
POS_Optical_state_Percent=0;
}
void Set_Optics_Setting(int rawdata)
{
while(pthread_mutex_lock(&POS_Optics_Write_Lock) != 0)
{
usleep(34+(rawdata%16));
}
POS_Optical_state_Percent=rawdata%100;
pthread_mutex_unlock(&POS_Optics_Write_Lock);
return;
}
int Get_Optics_Setting(void)
{
if(POS_Optical_state_Percent > 0)
{
return (POS_Optical_state_Percent * OPTICS_FILTER_ARM_FORDWARD_INDEX)
+ OPTICS_FILTER_ARM_SERVO_CENTER;
}else{
return (POS_Optical_state_Percent * OPTICS_FILTER_ARM_BACKWARD_INDEX)
+OPTICS_FILTER_ARM_SERVO_CENTER;
}
return 0;
}
| 0
|
#include <pthread.h>
enum state {THINKING,HUNGRY,EATING};
enum state philState[10];
float millis;
clock_t start,end;
int timer[10];
int N;
void* philospher(void *num);
void pickup_forks(int);
void return_forks(int);
void philosopher_test(int);
pthread_mutex_t mutex;
pthread_cond_t cond_var;
int phil_num[10];
int main()
{
char ch='n';
start=clock();
printf("Enter number of Philosophers(max 10): \\n");
scanf("%d",&N);
for(int i=0;i<N;i++)
timer[i]=0;
for(int k=0;k<N;k++)
phil_num[k]=k;
do{
pthread_t thread_id[N];
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond_var,0);
for(int i=0;i<N;i++)
{
pthread_create(&thread_id[i],0,philospher,&phil_num[i]);
printf("Philosopher %d is thinking\\n",i+1);
}
for(int i=0;i<N;i++)
pthread_join(thread_id[i],0);
printf("\\nDo you wish to continue: ");
scanf("\\n%c",&ch);
}while(ch=='y' || ch=='Y');
for(int i=0;i<N;i++)
printf("Philosopher %d eating time is %d\\n",i,timer[i] );
end=clock();
millis=(end-start)/100;
printf("Elapsed Time = %f\\n",millis );
exit(0);
}
void *philospher(void *num) {
int *i = num;
pickup_forks(*i);
int eat_time=(rand()%3)+1;
sleep(eat_time);
timer[*i]=eat_time+timer[*i];
return_forks(*i);
}
void pickup_forks(int philosopher_num) {
pthread_mutex_lock(&mutex);
philState[philosopher_num] = HUNGRY;
printf("Philosopher %d is Hungry\\n",philosopher_num+1);
philosopher_test(philosopher_num);
while (philState[philosopher_num]!=EATING)
pthread_cond_wait(&cond_var, &mutex);
pthread_mutex_unlock(&mutex);
}
void return_forks(int philosopher_num) {
pthread_mutex_lock(&mutex);
philState[philosopher_num] = THINKING;
printf("Philosopher %d returned chopsticks:\\t%d and %d\\n",philosopher_num+1,(philosopher_num+(N-1))%N+1,philosopher_num+1);
printf("Philosopher %d is thinking\\n",philosopher_num+1);
philosopher_test((philosopher_num+(N-1))%N);
philosopher_test((philosopher_num+1)%N);
pthread_mutex_unlock(&mutex);
}
void philosopher_test(int philosopher_num)
{
if (philState[philosopher_num] == HUNGRY && philState[(philosopher_num+(N-1))%N] != EATING && philState[(philosopher_num+1)%N] != EATING)
{
philState[philosopher_num] = EATING;
printf("Philosopher %d picked up chopsticks:\\t%d and %d\\n",philosopher_num+1,(philosopher_num+(N-1))%N+1,philosopher_num+1);
printf("\\tPhilosopher %d is Eating\\n",philosopher_num+1);
}
pthread_cond_signal(&cond_var);
}
| 1
|
#include <pthread.h>
void *functionC();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
main()
{
int rc1, rc2;
pthread_t thread1, thread2;
if( (rc1=pthread_create( &thread1, 0, &functionC, 0)) )
{
printf("Thread creation failed: %d\\n", rc1);
}
if( (rc2=pthread_create( &thread2, 0, &functionC, 0)) )
{
printf("Thread creation failed: %d\\n", rc2);
}
pthread_join( thread1, 0);
pthread_join( thread2, 0);
exit(0);
}
void *functionC()
{
pthread_mutex_lock( &mutex1 );
counter++;
printf("Counter value: %d\\n",counter);
pthread_mutex_unlock( &mutex1 );
}
| 0
|
#include <pthread.h>
int count = 0;
int thread_ids[3] = {0,1,2};
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *inc_count(void *t) {
int i;
long my_id = (long)t;
for (i=0;i<10;i++) {
pthread_mutex_lock(&count_mutex);
count++;
if (count == 12) {
pthread_cond_signal(&count_threshold_cv);
printf("inc_count(): thread %ld, count = %d Threshold reached.\\n", my_id, count);
}
printf("inc_count(): thread %ld, count %d, unlocking mutex\\n", my_id, count);
pthread_mutex_unlock(&count_mutex);
sleep(1);
}
pthread_exit(0);
}
void *watch_count(void *t) {
long my_id = (long)t;
printf("Starting watch_count(): thread %ld\\n", my_id);
pthread_mutex_lock(&count_mutex);
while (count<12) {
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %ld Condition signal received.\\n", my_id);
count += 125;
printf("watch_count(): thread %ld count now = %d.\\n", my_id, count);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main(int argc, char *argv[]) {
int i, rc;
long t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init(&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, watch_count, (void *)t1);
pthread_create(&threads[1], &attr, inc_count, (void *)t2);
pthread_create(&threads[2], &attr, inc_count, (void *)t3);
for (i=0;i<3;i++)
pthread_join(threads[i], 0);
printf("Main(): Waited on %d threads. Done.\\n", 3);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
void aq_init(struct aq_info* paq)
{
paq->front_sig = 0;
paq->rear_sig = 0;
paq->aq_cur_size = 0;
pthread_mutex_init(&paq->tmp_mutex,0);
paq->aq_turn_num = aq_buf_max - 1;
paq->aq_full = -10000;
paq->aq_empty = -10001;
paq->aq_push_ok = -10002;
return;
}
int aq_cur_size(struct aq_info* paq)
{
int tmp;
pthread_mutex_lock(&paq->tmp_mutex);
tmp = paq->aq_cur_size;
pthread_mutex_unlock(&paq->tmp_mutex);
return tmp;
}
int aq_push(struct aq_info* paq,int N)
{
int tmp;
int D_val;
pthread_mutex_lock(&paq->tmp_mutex);
if(paq->aq_cur_size >= aq_buf_max)
{
printf("array queue has full\\n");
pthread_mutex_unlock(&paq->tmp_mutex);
return paq->aq_full;
}
D_val = paq->rear_sig + N;
if(D_val >= aq_buf_max)
{
D_val = D_val - aq_buf_max;
for(tmp = 0;paq->rear_sig <= paq->aq_turn_num;paq->rear_sig++)
{
paq->aq_buf[paq->rear_sig] = paq->AS_push[tmp];
tmp++;
}
for(paq->rear_sig = 0;paq->rear_sig < D_val;paq->rear_sig++)
{
paq->aq_buf[paq->rear_sig] = paq->AS_push[tmp];
tmp++;
}
paq->aq_cur_size = paq->aq_cur_size + N;
}
else
{
for(tmp = 0;paq->rear_sig < D_val;paq->rear_sig++)
{
paq->aq_buf[paq->rear_sig] = paq->AS_push[tmp];
tmp++;
}
paq->aq_cur_size = paq->aq_cur_size + N;;
}
pthread_mutex_unlock(&paq->tmp_mutex);
return paq->aq_push_ok;
}
int aq_pop(struct aq_info* paq)
{
int tmp;
int D_val;
int pop_count;
pthread_mutex_lock(&paq->tmp_mutex);
if(paq->aq_cur_size == 0)
{
printf("array queue is empty\\n");
pthread_mutex_unlock(&paq->tmp_mutex);
return paq->aq_empty;
}
pop_count = paq->aq_cur_size;
if(pop_count > AS_buf_max)
pop_count = AS_buf_max;
D_val = paq->front_sig + pop_count;
if(D_val >= aq_buf_max)
{
D_val = D_val - aq_buf_max;
for(tmp = 0;paq->front_sig <= paq->aq_turn_num;paq->front_sig++)
{
paq->AS_pop[tmp] = paq->aq_buf[paq->front_sig];
tmp++;
}
for(paq->front_sig = 0;paq->front_sig < D_val;paq->front_sig++)
{
paq->AS_pop[tmp] = paq->aq_buf[paq->front_sig];
tmp++;
}
paq->aq_cur_size = paq->aq_cur_size - pop_count;
}
else
{
for(tmp = 0;paq->front_sig < D_val;paq->front_sig++)
{
paq->AS_pop[tmp] = paq->aq_buf[paq->front_sig];
tmp++;
}
paq->aq_cur_size = paq->aq_cur_size - pop_count;
}
return pop_count;
}
int aq_is_empty(struct aq_info* paq)
{
int tmp;
pthread_mutex_lock(&paq->tmp_mutex);
if(paq->aq_cur_size == 0)
tmp = 1;
else
tmp = 0;
pthread_mutex_unlock(&paq->tmp_mutex);
return tmp;
}
int aq_is_full(struct aq_info* paq)
{
int tmp;
pthread_mutex_lock(&paq->tmp_mutex);
if(paq->aq_cur_size == aq_buf_max)
tmp = 1;
else
tmp = 0;
pthread_mutex_unlock(&paq->tmp_mutex);
return tmp;
}
| 0
|
#include <pthread.h>
int RANGE = 2;
long global_row;
pthread_mutex_t global_row_lock;
pthread_barrier_t barrier;
void *elimination(void* threadid) {
int norm, row, col, row_end;
float multiplier;
pthread_t self;
long tid;
tid = (long)threadid;
for (nor = 0; norm < N - 1; norm++) {
row = norm;
global_row = 0;
pthread_barrier_wait(&barrier);
while (row < N - 1) {
pthread_mutex_lock(&global_row_lock);
row = norm + 1 + global_row;
global_row += RANGE;
pthread_mutex_unlock(&global_row_lock);
row_end = (row + RANGE) > N ? (row + RANGE) : N;
for (row = row; row < row_end; row++) {
multiplier = A[row][norm] / A[norm][norm];
for (col = nomr; col < N; col++) {
A[row][col] -= A[norm][col] * multiplier;
}
B[row] -= B[norm] * multiplier;
}
}
pthread_barrier_wait(&barrier);
}
}
void gauss() {
int norm, row, col;
int i;
pthread_t threads[procs];
global_row = 0;
pthread_mutex_init(&global_row_lock, 0);
pthread_barrier_init(&barrier, 0, procs);
for (i = 0; i < procs; i++) {
pthread_create(&threads[i], 0, &elimination, (void*)i);
}
for (i = 0; i < procs; i++) {
pthread_join(threads[i], 0);
}
pthread_mutex_destroy(&global_row_lock);
pthread_barrier_destroy(&barrier);
for (row = N - 1; row >= 0; row--) {
X[row] = B[row];
for (col = N - 1; col > row; col--) {
X[row] -= A[row][col] * X[col];
}
X[row] /= A[row][row];
}
}
| 1
|
#include <pthread.h>
char proto[4];
char IPserveur[33];
char IPclient[33];
int dport;
char md5sum[32];
uint16_t opentime;
} args_iptables_struct;
static struct aes_data_t* _spa = 0;
pthread_mutex_t lock1;
pthread_mutex_t lock2;
void *changeiptables(void* args)
{
pthread_mutex_lock(&lock1);
args_iptables_struct *argums = args;
char regle[1000];
if(add_check_4_replay(argums->md5sum) == -1){
return;
}
sprintf(regle, "iptables -A FORWARD -p %s -d %s -s %s --dport %d -m state --state NEW -j ACCEPT",
argums->proto, argums->IPserveur, argums->IPclient, argums->dport);
system(regle);
pthread_mutex_unlock(&lock1);
if(argums->opentime > 0 && argums->opentime < 180)
sleep(argums->opentime);
else
sleep(30);
pthread_mutex_lock(&lock2);
sprintf(regle, "iptables -D FORWARD -p %s -d %s -s %s --dport %d -m state --state NEW -j ACCEPT",
argums->proto, argums->IPserveur, argums->IPclient, argums->dport);
system(regle);
del_check_4_replay(argums->md5sum);
free(argums);
pthread_mutex_unlock(&lock2);
}
void spa_init(){
clientry_read("server.secret");
if(pthread_mutex_init(&lock1, 0) != 0)
{
printf("\\n mutex 1 init failed\\n");
exit(-1);
}
if(pthread_mutex_init(&lock2, 0) != 0)
{
printf("\\n mutex 2 init failed\\n");
exit(-1);
}
}
int spa_parser(char* data, int size, int pkt_ip_src){
char str_ip0[16]; memset(str_ip0, '\\0', 16);
conv_ip_int_to_str(pkt_ip_src, str_ip0);
int counter = clientry_get_counter(str_ip0);
if(counter < 0){
printf("Erreur : impossible de trouver une correspondance pour cette ip (%s)\\n", str_ip0);
return -1;
}
char hotp_res[9];
memset(hotp_res, '\\0', 9);
char seed[16];
clientry_get_seed(seed, str_ip0);
hotp(seed, strlen(seed), counter, hotp_res, 9);
printf("NEW KEY : %s\\n", hotp_res);
char* decrypted_spa = decrypt(hotp_res,
data,
96);
_spa = (struct aes_data_t*)(decrypted_spa);
const int md5less = sizeof(struct aes_data_t) - sizeof(uint8_t) * 32;
char verify_md5[32];
memset(verify_md5, '\\0', 32);
md5_hash_from_string(decrypted_spa,
md5less,
verify_md5);
if((0x1 | 0x4 | 0x8) & 0x4){
if(strncmp(_spa->md5sum, verify_md5, 32) != 0){
printf("MD5 INCORRECTE\\n");
printf("md5sum(calc) : %s\\n", verify_md5);
printf("md5sum(recv) : %s\\n", _spa->md5sum);
free(decrypted_spa);
return -1;
}
else{
printf("MD5 CORRECTE\\n");
}
}
if(((0x1 | 0x4 | 0x8) & 0x1) != 0 &&
_spa->ip_src != pkt_ip_src){
printf("ERREUR : l'ip source du paquet ne correspond pas à l'ip contenu dans le paquet spa\\n");
free(decrypted_spa);
return -1;
}
int current_time = (int)time(0);
if(abs(current_time - _spa->timestamp) > 30){
printf("date pérminée\\n");
free(decrypted_spa);
return -1;
}
int i = 0;
printf("username : %s\\n", _spa->username);
printf("timestamp : %d\\n", _spa->timestamp);
char str_ip[16];
conv_ip_int_to_str(_spa->ip_src, &str_ip);
printf("ip src: %s\\n", str_ip);
conv_ip_int_to_str(_spa->ip_dst, &str_ip);
printf("ip dest: %s\\n", str_ip);
printf("port : %d\\n", _spa->port);
printf("protocol : %d (%s)\\n",
_spa->protocol,
(_spa->protocol == 0) ? "TCP" : "UDP");
printf("opentime : %d\\n", _spa->opentime);
printf("random : %s\\n", _spa->random);
clientry_inc_counter(str_ip0);
pthread_t threadIptables;
args_iptables_struct *args = malloc(sizeof *args);
if (_spa->protocol == 0)
strcpy(args->proto, "TCP");
else
strcpy(args->proto, "UDP");
conv_ip_int_to_str(_spa->ip_dst, args->IPserveur);
conv_ip_int_to_str(_spa->ip_src, args->IPclient);
args->dport = _spa->port;
args->opentime = _spa->opentime;
strncpy(args->md5sum, _spa->md5sum,32);
pthread_create (& threadIptables, 0, changeiptables, args);
free(decrypted_spa);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t max_connect_mutex = PTHREAD_MUTEX_INITIALIZER;
unsigned int uiConnectCount = 0;
void *thread(void *arg)
{
FILE * fp;
int i = 0;
int ret;
int fd = (int)arg;
char cmd_buf[128];
char pipe_buf[512];
pthread_mutex_lock(&max_connect_mutex);
uiConnectCount++;
pthread_mutex_unlock(&max_connect_mutex);
while (recv(fd, cmd_buf, sizeof(cmd_buf), 0) != -1)
{
DSTR("%s\\n", cmd_buf);
ret = strcmp(cmd_buf, "exit");
if(0 == ret)
break;
fp = popen(cmd_buf, "r");
if(0 == fp)
sprintf(pipe_buf, ": command not find%c", EOF);
else{
for(i=0; i<sizeof(pipe_buf); i++){
pipe_buf[i] = fgetc(fp);
if(EOF == pipe_buf[i])
break;
}
}
pclose(fp);
DSTR("%s\\n",pipe_buf);
ret = send(fd, pipe_buf, sizeof(pipe_buf), 0);
if(ret == -1){
fprintf(stderr, "send error, error code is %d.\\n", -errno);
break;
}
memset(cmd_buf, 0, sizeof(cmd_buf));
memset(pipe_buf, 0, sizeof(pipe_buf));
}
close(fd);
DSTR("Thread End, Close Socket:%d\\n", fd);
pthread_mutex_lock(&max_connect_mutex);
uiConnectCount--;
pthread_mutex_unlock(&max_connect_mutex);
return (void *)0;
}
int main(void)
{
int fd = 0;
int len;
int ret;
int client_sockfd;
int iConnectInvalid = 1;
struct sockaddr_in localaddr;
struct sockaddr_in remoteaddr;
pthread_t id;
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1){
fprintf(stderr, "socket error, error code is %d.\\n", -errno);
goto exit;
}
DSTR("socket %d\\n", fd);
localaddr.sin_family = AF_INET;
localaddr.sin_addr.s_addr = htonl(INADDR_ANY);
localaddr.sin_port = htons(5001);
len = sizeof(localaddr);
if(bind(fd, (struct sockaddr *)&localaddr, len) == -1)
{
fprintf(stderr, "bind error, error code is %d.\\n", -errno);
goto exit;
}
DSTR("bind successfully.\\n");
if(listen(fd, 5) == -1)
{
fprintf(stderr, "listen error, error code is %d.\\n", -errno);
goto exit;
}
DSTR("listen successfully.\\n");
while (1)
{
len = sizeof(remoteaddr);
client_sockfd = accept(fd, (struct sockaddr *)&remoteaddr, &len);
DSTR("accept successfully. Client socketfd = %d\\n", client_sockfd);
pthread_mutex_lock(&max_connect_mutex);
DVAR(uiConnectCount);
iConnectInvalid = (uiConnectCount >= 2)?0:1;
pthread_mutex_unlock(&max_connect_mutex);
if(iConnectInvalid)
{
ret = send(client_sockfd, "CONNECT_OK", strlen("CONNECT_OK"), 0);
if(ret == -1)
{
DSTR("send response err!\\n");
}
}
else
{
ret = send(client_sockfd, "CONNECT_NG", strlen("CONNECT_NG"), 0);
if(ret == -1)
{
DSTR("send response err!\\n");
}
close(client_sockfd);
continue;
}
ret = pthread_create(&id, 0, thread, (void *)client_sockfd);
}
exit:
if(fd != 0)
close(fd);
return 0;
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
extern int __VERIFIER_nondet_int();
int idx=0;
int ctr1=1, ctr2=0;
int readerprogress1=0, readerprogress2=0;
pthread_mutex_t mutex;
void __VERIFIER_atomic_use1(int myidx) {
__VERIFIER_assume(myidx <= 0 && ctr1>0);
ctr1++;
}
void __VERIFIER_atomic_use2(int myidx) {
__VERIFIER_assume(myidx >= 1 && ctr2>0);
ctr2++;
}
void __VERIFIER_atomic_use_done(int myidx) {
if (myidx <= 0) { ctr1--; }
else { ctr2--; }
}
void __VERIFIER_atomic_take_snapshot(int *readerstart1, int *readerstart2) {
*readerstart1 = readerprogress1;
*readerstart2 = readerprogress2;
}
void __VERIFIER_atomic_check_progress1(int readerstart1) {
if (__VERIFIER_nondet_int()) {
__VERIFIER_assume(readerstart1 == 1 && readerprogress1 == 1);
if (!(0)) ERROR: __VERIFIER_error();;
}
return;
}
void __VERIFIER_atomic_check_progress2(int readerstart2) {
if (__VERIFIER_nondet_int()) {
__VERIFIER_assume(readerstart2 == 1 && readerprogress2 == 1);
if (!(0)) ERROR: __VERIFIER_error();;
}
return;
}
void *qrcu_reader1() {
int
myidx;
while (1) {
myidx = idx;
if (
__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use1(myidx);
break;
} else {
if (__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use2(myidx);
break;
} else {}
}
}
readerprogress1 = 1;
readerprogress1 = 2;
__VERIFIER_atomic_use_done(myidx);
return 0;
}
void *qrcu_reader2() {
int
myidx;
while (1) {
myidx = idx;
if (
__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use1(myidx);
break;
} else {
if (__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use2(myidx);
break;
} else {}
}
}
readerprogress2 = 1;
readerprogress2 = 2;
__VERIFIER_atomic_use_done(myidx);
return 0;
}
void* qrcu_updater() {
int i;
int readerstart1, readerstart2;
int sum;
__VERIFIER_atomic_take_snapshot(&readerstart1, &readerstart2);
if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; };
if (sum <= 1) { if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; }; }
else {}
if (sum > 1) {
pthread_mutex_lock(&mutex);
if (idx <= 0) { ctr2++; idx = 1; ctr1--; }
else { ctr1++; idx = 0; ctr2--; }
if (idx <= 0) {
while (ctr1 > 0); }
else {
while (ctr2 > 0); }
pthread_mutex_unlock(&mutex);
} else {}
__VERIFIER_atomic_check_progress1(readerstart1);
__VERIFIER_atomic_check_progress2(readerstart2);
return 0;
}
int main() {
pthread_t t1, t2, t3;
pthread_mutex_init(&mutex, 0);
pthread_create(&t1, 0, qrcu_reader1, 0);
pthread_create(&t2, 0, qrcu_reader2, 0);
pthread_create(&t3, 0, qrcu_updater, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_join(t3, 0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
sem_t mysem[10000];
pthread_mutex_t mylock;
struct shared
{
int threadId;
long counter[10000];
char msg[10];
};
void* mythread_entry(void *args)
{
struct shared *SharedCounter = (struct shared*)args;
int i=0;
int resource_to_use = SharedCounter->threadId % 10000;
sem_trywait(&mysem[resource_to_use]);
pthread_mutex_lock(&mylock);
for(i=0; i<1000; i++)
{
sleep(0.001);
SharedCounter->counter[resource_to_use] += 1;
}
pthread_mutex_unlock(&mylock);
sem_post(&mysem[resource_to_use]);
pthread_exit(0);
}
int main()
{
int i, retCode;
struct shared *SharedCounter = (struct shared *)malloc(sizeof(struct shared));
for(i=0; i<10000; i++)
{
SharedCounter->counter[i] = 0;
}
for(i=0; i<10000; i++)
{
retCode = sem_init(&mysem[i], 0, 10000/10000);
if(retCode != 0) printf("mysem failed to init...\\n");
}
retCode = pthread_mutex_init(&mylock, 0);
if(retCode != 0) printf("mylock failed to init...\\n");
pthread_t mythread[10000];
for(i=0; i<10000; i++)
{
SharedCounter->threadId = i;
retCode = pthread_create(&mythread[i], 0, &mythread_entry, SharedCounter);
if(retCode == -1)
{
printf("Thread_create failed");
return -1;
}
}
for( i=0; i<10000; i++)
{
pthread_join(mythread[i], 0);
}
int finalCounter = 0;
for(i=0; i<10000; i++)
{
finalCounter = finalCounter + SharedCounter->counter[i];
}
printf("Final SharedCounter: %d\\t Expected: %d\\n", finalCounter, 10000*1000);
for(i=0; i<10000; i++)
sem_destroy(&mysem[i]);
pthread_mutex_destroy(&mylock);
free(SharedCounter);
return 0;
}
| 1
|
#include <pthread.h>
static int keep_ticks;
static void *tickTurn(void *ptr);
void messageCB(char *message);
void print_turnInfo();
static struct turn_info turnInfo;
static struct listenConfig listenConfig;
static pthread_t turnListenThread;
static char rcv_message[100];
pthread_mutex_t turnInfo_mutex = PTHREAD_MUTEX_INITIALIZER;
static int socket_type;
int main(int argc, char *argv[])
{
pthread_t turnTickThread;
if (argc != 6) {
fprintf(stderr,"usage: pumpturn iface [TCP|UDP] turnserver user pass\\n");
exit(1);
}
if( strcmp(argv[2], "UDP") == 0 ){
socket_type = SOCK_DGRAM;
}else{
socket_type = SOCK_STREAM;
}
initTurnInfo(&turnInfo);
addCredentials(&turnInfo, argv[3], argv[4], argv[5]);
listenConfig.update_inc_status = messageCB;
getRemoteTurnServerIp(&turnInfo, argv[3]);
getLocalIPaddresses(&turnInfo, socket_type, argv[1]);
TurnClient_Init(TEST_THREAD_CTX, 50, 50, 0, 0, "PumpTurn");
pthread_create( &turnTickThread, 0, tickTurn, (void*) &TEST_THREAD_CTX);
printf("Gather!!!\\n");
gatherAll(&turnInfo, &listenConfig, &print_turnInfo);
pthread_create( &turnListenThread, 0, stunListen, (void*)&listenConfig);
printf("Her er jeg\\n");
while(1)
{
getch();
}
return 0;
}
void messageCB(char *message)
{
int n = sizeof(rcv_message);
strncpy(rcv_message, message, n);
if (n > 0)
rcv_message[n - 1]= '\\0';
fprintf(stdout,"%s", rcv_message);
}
void print_turnInfo(){
char addr[SOCKADDR_MAX_STRLEN];
pthread_mutex_lock( &turnInfo_mutex );
fprintf(stdout, "RELAY addr: '%s'\\n",
sockaddr_toString((struct sockaddr *)&turnInfo.turnAlloc_44.relAddr,
addr,
sizeof(addr),
1));
pthread_mutex_unlock( &turnInfo_mutex );
}
static void *tickTurn(void *ptr){
struct timespec timer;
struct timespec remaining;
uint32_t *ctx = (uint32_t *)ptr;
timer.tv_sec = 0;
timer.tv_nsec = 50000000;
for(;;){
keep_ticks++;
nanosleep(&timer, &remaining);
TurnClient_HandleTick(*ctx);
if(keep_ticks>100){
sendKeepalive(&turnInfo);
keep_ticks = 0;
}
}
}
| 0
|
#include <pthread.h>
static const unsigned OS_TICKS_PER_SEC = 100;
{
OS_NO_ERR = 0,
OS_ERR_EVENT_TYPE = 1,
OS_ERR_PEVENT_NULL = 4,
OS_ERR_TIMEOUT = 10,
OS_ERR_PEND_ABORT = 14,
OS_ERR_PRIO_EXIST = 40,
OS_ERR_PRIO = 41,
OS_ERR_PRIO_INVALID = 42,
OS_ERR_SEM_OVF = 50,
OS_ERR_TASK_DEL = 61,
OS_ERR_TASK_NOT_EXIST = 67,
} os_err_e;
static const unsigned OS_PRIO_SELF = 0xFF;
static uint32_t os_time_offset = 0;
static void OSTimeSet(uint32_t value)
{
struct timeval tv;
if (gettimeofday(&tv, 0) < 0)
return;
uint32_t now = (tv.tv_sec * OS_TICKS_PER_SEC)
+ (tv.tv_usec / (1000000 / OS_TICKS_PER_SEC));
os_time_offset = value - now;
}
static uint32_t OSTimeGet(void)
{
struct timeval tv;
if (gettimeofday(&tv, 0) < 0)
return 0;
uint32_t now = (tv.tv_sec * OS_TICKS_PER_SEC)
+ (tv.tv_usec / (1000000 / OS_TICKS_PER_SEC));
return (now + os_time_offset);
}
static void OSTimeDly(uint16_t ticks)
{
usleep(ticks * (1000000 / OS_TICKS_PER_SEC));
}
{
void (*task)(void*);
void *param;
pthread_t thread;
} os_task_t;
static os_task_t os_task[256];
static pthread_mutex_t os_task_mutex = PTHREAD_MUTEX_INITIALIZER;
static void* os_task_start(void* param)
{
uintptr_t prio = (uintptr_t)param;
if (prio >= 256)
return 0;
os_task[prio].task(os_task[prio].param);
os_task[prio].task = 0;
return 0;
}
static uint8_t OSTaskCreate(
void (*task)(void*), void* param,
void* stack, uint8_t prio)
{
if (prio == OS_PRIO_SELF)
return OS_ERR_PRIO_INVALID;
pthread_mutex_lock(&os_task_mutex);
if (os_task[prio].task)
return OS_ERR_PRIO_EXIST;
os_task[prio].task = task;
os_task[prio].param = param;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstack(&attr, stack, PTHREAD_STACK_MIN);
unsigned long lprio = prio;
bool success = (pthread_create(
&os_task[prio].thread, &attr,
os_task_start, (void*)lprio) == 0);
pthread_attr_destroy(&attr);
pthread_mutex_unlock(&os_task_mutex);
return (success ? OS_NO_ERR : OS_ERR_PRIO);
}
static uint8_t OSTaskDel(uint8_t prio)
{
pthread_mutex_lock(&os_task_mutex);
if (!os_task[prio].task)
return OS_ERR_TASK_NOT_EXIST;
if (prio == OS_PRIO_SELF)
exit(0);
if (pthread_cancel(os_task[prio].thread) != 0)
return OS_ERR_TASK_DEL;
os_task[prio].task = 0;
pthread_mutex_unlock(&os_task_mutex);
return OS_NO_ERR;
}
static sem_t* OSSemCreate(uint16_t count)
{
sem_t* event = vaddr_to_ptr(malloc32(sizeof(sem_t)));
if (!event) return 0;
sem_init(event, 0, count);
return event;
}
static void OSSemDel(sem_t* event)
{
if (event)
{
sem_destroy(event);
free32(ptr_to_vaddr(event));
}
}
static void OSSemPend(sem_t* event, uint16_t timeout, uint8_t* err)
{
if (!event)
{
if (err) *err = OS_ERR_PEVENT_NULL;
return;
}
int status = -1;
if (timeout == 0)
{
status = sem_wait(event);
}
else
{
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
unsigned s = (timeout / OS_TICKS_PER_SEC);
unsigned ns = (timeout % OS_TICKS_PER_SEC);
ns = (ns * OS_TICKS_PER_SEC) / 1000000000;
ts.tv_sec += s;
ts.tv_nsec += ns;
if (ts.tv_nsec > 1000000000)
{
ts.tv_sec++;
ts.tv_nsec -= 1000000000;
}
status = sem_timedwait(event, &ts);
}
if (err)
{
if (status == ETIMEDOUT)
*err = OS_ERR_TIMEOUT;
else if (status < 0)
*err = OS_ERR_PEND_ABORT;
else
*err = OS_NO_ERR;
}
}
static uint8_t OSSemPost(sem_t* event)
{
if (!event)
return OS_ERR_PEVENT_NULL;
int status = sem_post(event);
if (status == EINVAL)
return OS_ERR_EVENT_TYPE;
if (status < 0)
return OS_ERR_SEM_OVF;
return OS_NO_ERR;
}
void os_ucos2_init(void)
{
IMPORT_REGISTER_NATIVE(OSTimeSet, 1, 0);
IMPORT_REGISTER_NATIVE(OSTimeGet, 0, 1);
IMPORT_REGISTER_NATIVE(OSTimeDly, 1, 0);
IMPORT_REGISTER_NATIVE(OSTaskCreate, 4, 1);
IMPORT_REGISTER_NATIVE(OSTaskDel , 1, 1);
IMPORT_REGISTER_NATIVE(OSSemCreate, 1, 1);
IMPORT_REGISTER_NATIVE(OSSemDel , 1, 0);
IMPORT_REGISTER_NATIVE(OSSemPend , 3, 0);
IMPORT_REGISTER_NATIVE(OSSemPost , 1, 1);
}
| 1
|
#include <pthread.h>
void error_handler_initialize() {
pthread_mutex_init(&elock_main, 0);
pthread_cond_init(&econd_main, 0);
eflag_main = 0;
pthread_mutex_init(&elock_i2c, 0);
pthread_cond_init(&econd_i2c, 0);
eflag_i2c = 0;
}
void esignal_main() {
pthread_mutex_lock(&elock_main);
eflag_main= 1;
syslog(LOG_ERR, "Signalled the main thread");
pthread_cond_signal(&econd_main);
pthread_mutex_unlock(&elock_main);
}
void ewait_i2c(){
pthread_mutex_lock(&elock_i2c);
while ( eflag_i2c ) pthread_cond_wait(&econd_i2c, &elock_i2c);
pthread_mutex_unlock(&elock_i2c);
}
void esignal_i2c(){
pthread_mutex_lock(&elock_i2c);
eflag_i2c = 1;
syslog(LOG_ERR, "I2C has encounted an error");
pthread_mutex_unlock(&elock_i2c);
esignal_main();
}
void error_handler_destroy() {
pthread_cond_destroy(&econd_main);
pthread_mutex_destroy(&elock_main);
pthread_cond_destroy(&econd_i2c);
pthread_mutex_destroy(&elock_i2c);
}
| 0
|
#include <pthread.h>
pthread_mutex_t semaforo1,semaforo2;
int recurso;
int numeroLectores;
void * escritor(void * limite);
void * lector(void * limite);
int main(){
srand(time(0));
pthread_t * hilos;
hilos=(pthread_t *)malloc(sizeof(hilos)*4);
recurso=5;
numeroLectores=0;
pthread_mutex_init(&semaforo1,0);
pthread_mutex_init(&semaforo2,0);
int i;
int * limiteLecturas;
int * limiteEscrituras;
limiteLecturas=(int *)malloc(sizeof(int));
limiteEscrituras=(int *)malloc(sizeof(int));
system("clear");
printf("\\nIntroduce un limite de lecturas por hilo: ");
scanf("%d",limiteLecturas);
printf("\\nIntroduce un limite de escrituras por hilo: ");
scanf("%d",limiteEscrituras);
pthread_create(&hilos[0],0,(void *)escritor,(void *)limiteEscrituras);
for(i=1;i<4;i++){
pthread_create(&hilos[i],0,(void *)lector,(void *)limiteLecturas);
}
for(i=0;i<4;i++){
pthread_join(hilos[i],0);
}
return 0;
}
void * escritor(void * limite){
int l=*(int *)limite;
while(l!=0){
pthread_mutex_lock(&semaforo2);
recurso=rand()%10;
printf("\\n\\t[+]Escritor añadiendo %d\\n",recurso);
pthread_mutex_unlock(&semaforo2);
l--;
sleep(rand()%4);
}
pthread_exit(0);
}
void * lector(void * limite){
int l=*(int *)limite;
while(l!=0){
pthread_mutex_lock(&semaforo1);
numeroLectores+=1;
if(numeroLectores==1){
pthread_mutex_lock(&semaforo2);
}
pthread_mutex_unlock(&semaforo1);
printf("\\n\\t[$]Lector leyendo %d\\n",recurso);
pthread_mutex_lock(&semaforo1);
numeroLectores-=1;
if(numeroLectores==0){
pthread_mutex_unlock(&semaforo2);
}
pthread_mutex_unlock(&semaforo1);
sleep(rand()%3);
l--;
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
{
FILE* fsync;
FILE* frestart;
int synced;
int count;
int quit;
pthread_mutex_t mutex;
pthread_t thread[32];
} cloud_state_t;
cloud_state_t* gstate = 0;
static void cloud_state_quit(int signo)
{
assert(gstate);
if(signo != SIGINT)
{
return;
}
pthread_mutex_lock(&gstate->mutex);
LOGI("[ QUIT]");
gstate->quit = 1;
pthread_mutex_unlock(&gstate->mutex);
}
static int cloud_state_isQuit(int id, const char* line)
{
LOGD("debug id=%i", id);
pthread_mutex_lock(&gstate->mutex);
int quit = gstate->quit;
if(quit)
{
LOGI("[ QUIT] id=%02i", id);
fprintf(gstate->frestart, "%s", line);
}
pthread_mutex_unlock(&gstate->mutex);
return quit;
}
static int cloud_state_next(int id, char** line, size_t* n)
{
assert(line);
assert(n);
LOGD("debug id=%i", id);
pthread_mutex_lock(&gstate->mutex);
if(gstate->quit)
{
LOGI("[ QUIT] id=%02i", id);
pthread_mutex_unlock(&gstate->mutex);
return 0;
}
if(getline(line, n, gstate->fsync) < 0)
{
LOGI("[ EOF] id=%02i", id);
pthread_mutex_unlock(&gstate->mutex);
return 0;
}
int i = 0;
char* s = *line;
while(s[i] != '\\0')
{
if((s[i] == '\\r') ||
(s[i] == '\\n'))
{
s[i] = '\\0';
}
++i;
}
pthread_mutex_unlock(&gstate->mutex);
return 1;
}
static int cloud_sync(int id, const char* line)
{
assert(line);
LOGI("[START] id=%02i: %s", id, line);
char timeout[256];
snprintf(timeout, 256, "%s", "timeout -s KILL 60");
char cmd[256];
snprintf(cmd, 256,
"%s gsutil cp -a public-read %s gs://goto/%s",
timeout, line, line);
if(system(cmd) != 0)
{
return 0;
}
pthread_mutex_lock(&gstate->mutex);
++gstate->synced;
LOGI("[ SYNC] id=%02i: %i %i %f %s",
id, gstate->synced, gstate->count,
100.0f*((float) gstate->synced)/((float) gstate->count),
line);
pthread_mutex_unlock(&gstate->mutex);
return 1;
}
static void* cloud_thread(void* arg)
{
assert(arg);
LOGD("debug");
int id = *((int*) arg);
char* line = 0;
size_t n = 0;
while(cloud_state_next(id, &line, &n))
{
while(cloud_sync(id, line) == 0)
{
if(cloud_state_isQuit(id, line))
{
free(line);
return 0;
}
LOGI("[RETRY] id=%02i: %s", id, line);
usleep(100000);
}
}
free(line);
return 0;
}
int main(int argc, char** argv)
{
if(argc != 3)
{
LOGE("usage: %s [sync.list] [restart.list]", argv[0]);
return 1;
}
const char* fname_sync = argv[1];
const char* fname_restart = argv[2];
if(access(fname_restart, F_OK) == 0)
{
LOGE("%s already exists", fname_restart);
return 1;
}
gstate = (cloud_state_t*) malloc(sizeof(cloud_state_t));
if(gstate == 0)
{
LOGE("malloc failed");
return 1;
}
gstate->fsync = fopen(fname_sync, "r");
if(gstate->fsync == 0)
{
LOGE("failed to open %s", fname_sync);
goto fail_fsync;
}
char* line = 0;
size_t n = 0;
gstate->count = 0;
gstate->synced = 0;
while(getline(&line, &n, gstate->fsync) > 0)
{
++gstate->count;
}
rewind(gstate->fsync);
free(line);
line = 0;
n = 0;
gstate->frestart = fopen(fname_restart, "w");
if(gstate->frestart == 0)
{
LOGE("failed to open %s", fname_restart);
goto fail_frestart;
}
gstate->quit = 0;
if(pthread_mutex_init(&gstate->mutex, 0) != 0)
{
LOGE("pthread_mutex_init failed");
goto fail_mutex;
}
int i;
int ids[32];
for(i = 0; i < 32; ++i)
{
ids[i] = i;
}
pthread_mutex_lock(&gstate->mutex);
for(i = 0; i < 32; ++i)
{
if(pthread_create(&gstate->thread[i], 0,
cloud_thread,
(void*) &ids[i]) != 0)
{
LOGE("pthread_create failed");
goto fail_thread;
}
}
if(signal(SIGINT, cloud_state_quit) == SIG_ERR)
{
goto fail_signal;
}
pthread_mutex_unlock(&gstate->mutex);
for(i = 0; i < 32; ++i)
{
pthread_join(gstate->thread[i], 0);
}
while(getline(&line, &n, gstate->fsync) > 0)
{
fprintf(gstate->frestart, "%s", line);
}
free(line);
fclose(gstate->frestart);
fclose(gstate->fsync);
LOGI("[ DONE]");
signal(SIGINT, SIG_DFL);
pthread_mutex_destroy(&gstate->mutex);
free(gstate);
gstate = 0;
return 0;
fail_signal:
fail_thread:
gstate->quit = 1;
pthread_mutex_unlock(&gstate->mutex);
int j;
for(j = 0; j < i; ++j)
{
pthread_join(gstate->thread[j], 0);
}
pthread_mutex_destroy(&gstate->mutex);
fail_mutex:
fclose(gstate->frestart);
fail_frestart:
fclose(gstate->fsync);
fail_fsync:
free(gstate);
gstate = 0;
return 1;
}
| 0
|
#include <pthread.h>
long circleCount = 0;
pthread_t *threads;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *monteCarloPi(void *thread_ID) {
long i;
int a = (int) thread_ID;
long incircle_thread = 0;
unsigned int rand_state = rand();
for (i = 0; i < 10000000/5; i++) {
double x = rand_r(&rand_state) / ((double)32767 + 1) * 2.0 - 1.0;
double y = rand_r(&rand_state) / ((double)32767 + 1) * 2.0 - 1.0;
if (x * x + y * y < 1) {
incircle_thread++;
}
}
float Pi = (4. * (double)incircle_thread) /
((double)10000000/5 * 1);
printf("Thread [%d] Reports Pi to be [%f]\\n" ,a,Pi);
pthread_mutex_lock(&mutex);
circleCount += incircle_thread;
pthread_mutex_unlock(&mutex);
return 0;
}
void createThreads(){
int i, s;
threads = malloc(5 * sizeof(pthread_t));
pthread_attr_t attr;
pthread_attr_init(&attr);
printf("\\n----------------------------------------\\n*Creating [%d] Threads\\n\\n", 5);
for (i = 0; i < 5; i++) {
s = pthread_create(&threads[i], &attr, monteCarloPi, (void *) i);
if (s != 0){
do { errno = s; perror("pthread_create"); exit(1); } while (0);
}
}
}
void joinThreads(){
int i,s;
for (i = 0; i < 5; i++) {
s = pthread_join(threads[i], 0);
if (s != 0){
do { errno = s; perror("pthread_join"); exit(1); } while (0);
}
}
pthread_mutex_destroy(&mutex);
printf("\\n*[%d] Threads Rejoined\\n\\n", 5);
free(threads);
}
int main() {
float Pi;
createThreads();
joinThreads();
Pi = (4. * (double)circleCount) / ((double)10000000/5 * 5);
printf("Final Estimation of Pi: %f\\n\\n----------------------------------------\\n", Pi);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t g_cp8_emu_mtx = PTHREAD_MUTEX_INITIALIZER;
struct cp8_emu_tasks_ctx {
const char *name;
cp8_emu_task task;
};
static struct termios g_oldattr;
static int cp8_help(void);
static int cp8_version(void);
void cp8_emu_init(struct cp8_ctx *cp8) {
struct termios attr;
int res;
pthread_mutexattr_t mtx_attr;
tcgetattr(STDIN_FILENO, &attr);
g_oldattr = attr;
attr.c_lflag = ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &attr);
ioctl(STDIN_FILENO, FIONREAD, &res);
setbuf(stdout, 0);
pthread_mutexattr_init(&mtx_attr);
pthread_mutexattr_settype(&mtx_attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&g_cp8_emu_mtx, &mtx_attr);
if (cp8 != 0) {
memset(cp8, 0, sizeof(struct cp8_ctx));
pthread_mutex_init(&cp8->mtx, &mtx_attr);
}
cp8_vidinit();
cp8_kbdinit();
}
int cp8_emu_exec(void) {
struct cp8_emu_tasks_ctx tasks [] = {
{ "emulate", cp8_emu_tsk_emulate },
{ "umount", cp8_emu_tsk_umount }
};
const size_t tasks_nr = sizeof(tasks) / sizeof(tasks[0]);
size_t t;
int exit_code = 0;
cp8_emu_task curr_task = 0;
if (cp8_emu_bool_option("version", 0)) {
return cp8_version();
} else if (cp8_emu_bool_option("help", 0)) {
return cp8_help();
}
for (t = 0; t < tasks_nr; t++) {
if (cp8_emu_task_option(tasks[t].name)) {
exit_code += (curr_task = tasks[t].task)();
}
}
if (curr_task == 0) {
printf("ERROR: no valid tasks were supplied.\\n");
exit_code = 1;
}
return exit_code;
}
void cp8_emu_finis(void) {
cp8_vidfinis();
tcsetattr(STDIN_FILENO, TCSANOW, &g_oldattr);
}
void cp8_emu_lock(void) {
pthread_mutex_lock(&g_cp8_emu_mtx);
}
void cp8_emu_unlock(void) {
pthread_mutex_unlock(&g_cp8_emu_mtx);
}
static int cp8_help(void) {
printf("usage: cp8 emulate | umount <options>\\n\\n"
"cp8 is Copyright (C) 2016-2017 by Rafael Santiago.\\n\\n"
"Bug reports, feedback, etc: <voidbrainvoid@gmail.com> "
"or <https://github.com/rafael-santiago/CP-8/issues>\\n");
return 0;
}
static int cp8_version(void) {
printf("cp8-%s\\n", CP8_VERSION);
return 0;
}
| 0
|
#include <pthread.h>
struct msg
{
struct msg *next;
int num;
};
struct msg *head;
struct msg *mp;
pthread_cond_t has_product=PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
void *consumer(void *p)
{
for(;;)
{
pthread_mutex_lock(&lock);
while(head==0)
{
pthread_cond_wait(&has_product,&lock);
}
mp=head;
head=mp->next;
pthread_mutex_unlock(&lock);
printf("-Consume---%d\\n",mp->num);
free(mp);
sleep(rand()%3);
}
}
void *producer(void *p)
{
for(;;)
{
mp=malloc(sizeof(struct msg));
mp->num=rand()%1000+1;
printf("-Produce-----%d\\n",mp->num);
pthread_mutex_lock(&lock);
mp->next=head;
head=mp;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&has_product);
sleep(rand()%3);
}
}
int main(int argc,char *argv[])
{
pthread_t pid,cid;
srand(time(0));
pthread_create(&pid,0,producer,0);
pthread_create(&cid,0,consumer,0);
pthread_join(pid,0);
pthread_join(cid,0);
return 0;
}
| 1
|
#include <pthread.h>
struct mt {
int num;
pthread_mutex_t mutex;
pthread_mutexattr_t mutexattr;
};
struct mt * mm;
void test(struct mt * mm)
{
for (int i=0;i<10;i++){
printf("PID:%d \\n",getpid());
pthread_mutex_lock(&mm->mutex);
mm->num += 1;
printf("PID:%d num = :%d\\n",getpid(),mm->num);
pthread_mutex_unlock(&mm->mutex);
}
}
void test2()
{
for (int i=0;i<10;i++){
printf("PID:%d \\n",getpid());
pthread_mutex_lock(&mm->mutex);
mm->num += 1;
printf("PID:%d num = :%d\\n",getpid(),mm->num);
pthread_mutex_unlock(&mm->mutex);
}
}
int main(void)
{
int fd, i;
pid_t pid;
unlink("mt_test");
fd = open("mt_test", O_CREAT | O_RDWR, 0777);
ftruncate(fd, sizeof(*mm));
mm = mmap(0, sizeof(*mm), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
memset(mm, 0, sizeof(*mm));
pthread_mutexattr_init(&mm->mutexattr);
pthread_mutexattr_setpshared(&mm->mutexattr,PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&mm->mutex, &mm->mutexattr);
pid = fork();
if (pid == 0){
test2();
}
else if (pid > 0) {
test2();
wait(0);
}
pthread_mutex_destroy(&mm->mutex);
pthread_mutexattr_destroy(&mm->mutexattr);
munmap(mm,sizeof(*mm));
unlink("mt_test");
return 0;
}
| 0
|
#include <pthread.h>
int count = 0;
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void* inc_count(void *arg)
{
int i;
int my_id = *((int*) arg);
for (i=0; i<10; i++) {
pthread_mutex_lock(&count_mutex);
count++;
if (count == 12) {
printf("inc_count(): thread %d, count = %d Threshold reached. ",
my_id, count);
pthread_cond_signal(&count_threshold_cv);
printf("Just sent signal.\\n");
}
printf("inc_count(): thread %d, count = %d, unlocking mutex\\n",
my_id, count);
pthread_mutex_unlock(&count_mutex);
sleep(1);
}
return 0;
}
void* watch_count(void *arg)
{
int my_id = *((int*) arg);
printf("Starting watch_count(): thread %d\\n", my_id);
pthread_mutex_lock(&count_mutex);
while (count < 12) {
printf("watch_count(): thread %d Count= %d. Going into wait...\\n", my_id,count);
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %d Condition signal received. Count= %d\\n", my_id,count);
}
printf("watch_count(): thread %d Updating the value of count...\\n", my_id);
count += 125;
printf("watch_count(): thread %d count now = %d.\\n", my_id, count);
printf("watch_count(): thread %d Unlocking mutex.\\n", my_id);
pthread_mutex_unlock(&count_mutex);
return 0;
}
int main(int argc, char *argv[])
{
int i, err;
int params[3];
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (i=0; i<3; i++) {
params[i] = i;
if (i==0) {
err = pthread_create(&threads[i], &attr, watch_count, (void*)&(params[i]));
}
else {
err = pthread_create(&threads[i], &attr, inc_count, (void*)&(params[i]));
}
if (err != 0) {
fprintf(stderr, "Can't create thread. Reason: '%s'", strerror(err));
exit(EX_OSERR);
}
}
for (i=0; i<3; i++) {
pthread_join(threads[i], 0);
}
printf("Main(): Waited and joined with %d threads. Final value of count = %d. Done.\\n",
3, count);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
return 0;
}
| 1
|
#include <pthread.h>
void *customerMaker();
void *barberShop();
void *waitingRoom();
void checkQueue();
pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t wait_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t sleep_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t barberSleep_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t barberWorking_cond = PTHREAD_COND_INITIALIZER;
int returnTime=5,current=0, sleeping=0, iseed;
int main(int argc, char *argv[])
{
iseed=time(0);
srand(iseed);
pthread_t barber,customerM,timer_thread;
pthread_attr_t barberAttr, timerAttr;
pthread_attr_t customerMAttr;
pthread_attr_init(&timerAttr);
pthread_attr_init(&barberAttr);
pthread_attr_init(&customerMAttr);
printf("\\n");
pthread_create(&customerM,&customerMAttr,customerMaker,0);
pthread_create(&barber,&barberAttr,barberShop,0);
pthread_join(barber,0);
pthread_join(customerM,0);
return 0;
}
void *customerMaker()
{
int i=0;
printf("*Customer Maker Created*\\n\\n");
fflush(stdout);
pthread_t customer[6 +1];
pthread_attr_t customerAttr[6 +1];
while(i<(6 +1))
{
i++;
pthread_attr_init(&customerAttr[i]);
while(rand()%2!=1)
{
sleep(1);
}
pthread_create(&customer[i],&customerAttr[i],waitingRoom,0);
}
pthread_exit(0);
}
void *waitingRoom()
{
pthread_mutex_lock(&queue_mutex);
checkQueue();
sleep(returnTime);
waitingRoom();
}
void *barberShop()
{
int loop=0;
printf("The barber has opened the store.\\n");
fflush(stdout);
while(loop==0)
{
if(current==0)
{
printf("\\tThe shop is empty, barber is sleeping.\\n");
fflush(stdout);
pthread_mutex_lock(&sleep_mutex);
sleeping=1;
pthread_cond_wait(&barberSleep_cond,&sleep_mutex);
sleeping=0;
pthread_mutex_unlock(&sleep_mutex);
printf("\\t\\t\\t\\tBarber wakes up.\\n");
fflush(stdout);
}
else
{
printf("\\t\\t\\tBarber begins cutting hair.\\n");
fflush(stdout);
sleep((rand()%20)/5);
current--;
printf("\\t\\t\\t\\tHair cut complete, customer leaving store.\\n");
pthread_cond_signal(&barberWorking_cond);
}
}
pthread_exit(0);
}
void checkQueue()
{
current++;
printf("\\tCustomer has arrived in the waiting room.\\t\\t\\t\\t\\t\\t\\t%d Customers in store.\\n",current);
fflush(stdout);
printf("\\t\\tCustomer checking chairs.\\n");
fflush(stdout);
if(current<6)
{
if(sleeping==1)
{
printf("\\t\\t\\tBarber is sleeping, customer wakes him.\\n");
fflush(stdout);
pthread_cond_signal(&barberSleep_cond);
}
printf("\\t\\tCustomer takes a seat.\\n");
fflush(stdout);
pthread_mutex_unlock(&queue_mutex);
pthread_mutex_lock(&wait_mutex);
pthread_cond_wait(&barberWorking_cond,&wait_mutex);
pthread_mutex_unlock(&wait_mutex);
return;
}
if(current>=6)
{
printf("\\t\\tAll chairs full, leaving store.\\n");
fflush(stdout);
current--;
pthread_mutex_unlock(&queue_mutex);
return;
}
}
| 0
|
#include <pthread.h>
int _mosquitto_handle_pingreq(struct mosquitto *mosq)
{
assert(mosq);
_mosquitto_log_printf(mosq, MOSQ_LOG_DEBUG, "Client %s received PINGREQ", mosq->id);
return _mosquitto_send_pingresp(mosq);
}
int _mosquitto_handle_pingresp(struct mosquitto *mosq)
{
assert(mosq);
mosq->ping_t = 0;
_mosquitto_log_printf(mosq, MOSQ_LOG_DEBUG, "Client %s received PINGRESP", mosq->id);
return MOSQ_ERR_SUCCESS;
}
int _mosquitto_handle_pubackcomp(struct mosquitto *mosq, const char *type)
{
uint16_t mid;
int rc;
assert(mosq);
rc = _mosquitto_read_uint16(&mosq->in_packet, &mid);
if(rc) return rc;
_mosquitto_log_printf(mosq, MOSQ_LOG_DEBUG, "Client %s received %s (Mid: %d)", mosq->id, type, mid);
if(!_mosquitto_message_delete(mosq, mid, mosq_md_out)){
pthread_mutex_lock(&mosq->callback_mutex);
if(mosq->on_publish){
mosq->in_callback = 1;
mosq->on_publish(mosq, mosq->userdata, mid);
mosq->in_callback = 0;
}
pthread_mutex_unlock(&mosq->callback_mutex);
}
return MOSQ_ERR_SUCCESS;
}
int _mosquitto_handle_pubrec(struct mosquitto *mosq)
{
uint16_t mid;
int rc;
assert(mosq);
rc = _mosquitto_read_uint16(&mosq->in_packet, &mid);
if(rc) return rc;
_mosquitto_log_printf(mosq, MOSQ_LOG_DEBUG, "Client %s received PUBREC (Mid: %d)", mosq->id, mid);
rc = _mosquitto_message_out_update(mosq, mid, mosq_ms_wait_for_pubcomp);
if(rc) return rc;
rc = _mosquitto_send_pubrel(mosq, mid);
if(rc) return rc;
return MOSQ_ERR_SUCCESS;
}
int _mosquitto_handle_pubrel(struct mosquitto_db *db, struct mosquitto *mosq)
{
uint16_t mid;
struct mosquitto_message_all *message = 0;
int rc;
assert(mosq);
if(mosq->protocol == mosq_p_mqtt311){
if((mosq->in_packet.command&0x0F) != 0x02){
return MOSQ_ERR_PROTOCOL;
}
}
rc = _mosquitto_read_uint16(&mosq->in_packet, &mid);
if(rc) return rc;
_mosquitto_log_printf(mosq, MOSQ_LOG_DEBUG, "Client %s received PUBREL (Mid: %d)", mosq->id, mid);
if(!_mosquitto_message_remove(mosq, mid, mosq_md_in, &message)){
pthread_mutex_lock(&mosq->callback_mutex);
if(mosq->on_message){
mosq->in_callback = 1;
mosq->on_message(mosq, mosq->userdata, &message->msg);
mosq->in_callback = 0;
}
pthread_mutex_unlock(&mosq->callback_mutex);
_mosquitto_message_cleanup(&message);
}
rc = _mosquitto_send_pubcomp(mosq, mid);
if(rc) return rc;
return MOSQ_ERR_SUCCESS;
}
int _mosquitto_handle_suback(struct mosquitto *mosq)
{
uint16_t mid;
uint8_t qos;
int *granted_qos;
int qos_count;
int i = 0;
int rc;
assert(mosq);
_mosquitto_log_printf(mosq, MOSQ_LOG_DEBUG, "Client %s received SUBACK", mosq->id);
rc = _mosquitto_read_uint16(&mosq->in_packet, &mid);
if(rc) return rc;
qos_count = mosq->in_packet.remaining_length - mosq->in_packet.pos;
granted_qos = _mosquitto_malloc(qos_count*sizeof(int));
if(!granted_qos) return MOSQ_ERR_NOMEM;
while(mosq->in_packet.pos < mosq->in_packet.remaining_length){
rc = _mosquitto_read_byte(&mosq->in_packet, &qos);
if(rc){
_mosquitto_free(granted_qos);
return rc;
}
granted_qos[i] = (int)qos;
i++;
}
pthread_mutex_lock(&mosq->callback_mutex);
if(mosq->on_subscribe){
mosq->in_callback = 1;
mosq->on_subscribe(mosq, mosq->userdata, mid, qos_count, granted_qos);
mosq->in_callback = 0;
}
pthread_mutex_unlock(&mosq->callback_mutex);
_mosquitto_free(granted_qos);
return MOSQ_ERR_SUCCESS;
}
int _mosquitto_handle_unsuback(struct mosquitto *mosq)
{
uint16_t mid;
int rc;
assert(mosq);
_mosquitto_log_printf(mosq, MOSQ_LOG_DEBUG, "Client %s received UNSUBACK", mosq->id);
rc = _mosquitto_read_uint16(&mosq->in_packet, &mid);
if(rc) return rc;
pthread_mutex_lock(&mosq->callback_mutex);
if(mosq->on_unsubscribe){
mosq->in_callback = 1;
mosq->on_unsubscribe(mosq, mosq->userdata, mid);
mosq->in_callback = 0;
}
pthread_mutex_unlock(&mosq->callback_mutex);
return MOSQ_ERR_SUCCESS;
}
| 1
|
#include <pthread.h>
pthread_mutex_t llave;
double sum = 0.0;
struct parametros {
int inicio; ;
int fin ;
int nh;
double *vector;
};
void *do_work( void *arg );
int main(int argc, char *argv[]){
double *vector;
vector = malloc(sizeof(double*)*1000000000);
for(int i = 0; i < 1000000000; i++ ){
vector[i]= i* 1.0;
}
pthread_t *thread;
thread = (pthread_t*)malloc(sizeof(pthread_t)*4);
pthread_mutex_init(&llave, 0);
int paquete = 1000000000 / 4;
int excedente = 1000000000 % 4;
int fin = 0;
int inicio = 0;
struct parametros parametros_array[4];
for(int i = 0; i<4; i++){
parametros_array[i].vector = vector;
fin = inicio + paquete;
if(excedente > 0){
fin++;
excedente--;
}
parametros_array[i].inicio = inicio;
parametros_array[i].fin = fin;
parametros_array[i].nh = i;
pthread_create ( &thread[i], 0, do_work, (void*)¶metros_array[i]);
inicio = fin;
}
for(int i = 0; i<4; i++){
pthread_join( thread[i], 0);
}
printf ("\\nDone. Sum= %lf \\n", sum);
sum=0.0;
int i = 0;
for (i=0;i<1000000000;i++){
if(i%2 == 0) sum += vector[i];
else sum -= vector[i];
}
printf("Check Sum= %lf\\n",sum);
free(thread);
pthread_mutex_destroy(&llave);
}
void *do_work(void *arg){
int i;
double mysum=0.0;
struct parametros * p;
p = ( struct parametros *) arg ;
for(int i = (p -> inicio); i < (p -> fin); i++){
if(i%2==0) mysum += (p -> vector[i]);
else mysum -= (p -> vector[i]);
}
pthread_mutex_lock(&llave);
printf("\\nLlave está cerrada");
sum += mysum;
printf("\\nValor de sum = %lf", sum);
pthread_mutex_unlock(&llave);
printf("\\nLlave está abierta\\n");
return 0;
}
| 0
|
#include <pthread.h>
struct sensorBlockTime sensorBlockArr[(32* (TURNS + 1)) + ((TURNS + 1) * 2)];
struct executionTimeSensor sensorExecutionArr[(32* (TURNS + 1)) + ((TURNS + 1) * 2)];
struct d arr[(32* (TURNS + 1)) + ((TURNS + 1) * 2)];
void *sensor(void* val) {
struct timespec start;
struct timespec end;
double result = 0.0;
double distance = 0.0;
double speed = 0.0, tmp;
int save = 0;
int countBefore= -1;
int policy;
struct sched_param param;
int co = 0;
if(pthread_getschedparam(pthread_self(), &policy, ¶m) != 0 ) {
printf("error\\n");
}
printf(" Sensor policy=%s, priority=%d\\n",
(policy == SCHED_FIFO) ? "SCHED_FIFO" :
(policy == SCHED_RR) ? "SCHED_RR" :
(policy == SCHED_OTHER) ? "SCHED_OTHER" :
"???",
param.sched_priority);
pthread_barrier_wait(&barrier);
while(abbruch == 0) {
co = count;
if(!(co == countBefore)) {
if(executionTime == 1) {
clock_gettime(CLOCK_REALTIME, &sensorExecutionArr[co].start);
}
countBefore = co;
digitalWrite(7, 1);
usleep(10);
digitalWrite(7, 0);
clock_gettime(CLOCK_REALTIME, &start);
while(digitalRead(8) == 0) {
clock_gettime(CLOCK_REALTIME, &start);
}
while(digitalRead(8) == 1) {
clock_gettime(CLOCK_REALTIME, &end);
}
if (tempSensor == 1 )
{
temperature = bmp085_GetTemperature(bmp085_ReadUT());
tmp = (double)temperature / 10;
} else {
tmp = 20.0;
}
printf("temperatur: %.2f\\n", tmp);
speed = 331.5 + (0.6 * tmp);
speed = speed * 1000;
result = diff_time(start, end);
printf("Geschwindigkeit: %f\\n", speed);
printf("zeit: %.20f\\n", result);
distance = ((result * speed) ) / 2;
printf("entfernung: %.2f\\n", distance);
if( distance >= 30.0) {
distance = 0.0;
}
printf("entfernung: %.2f\\n", distance);
save++;
if(executionTime == 1) {
clock_gettime(CLOCK_REALTIME, &sensorExecutionArr[co].end);
}
if(blockTime == 1) {
clock_gettime(CLOCK_REALTIME, &sensorBlockArr[co].start);
}
pthread_mutex_lock(&lock);
arr[co].sensor = save - 1;
arr[co].entfernung = distance;
gemessen = 1;
pthread_mutex_unlock(&lock);
if(blockTime == 1) {
clock_gettime(CLOCK_REALTIME, &sensorBlockArr[co].end);
}
}
usleep(60000);
}
printf("sensor %d\\n", save);
return 0;
}
| 1
|
#include <pthread.h>
struct to_info{
void (*to_fn)(void *);
void *to_arg;
struct timespec to_wait;
};
int makethread(void *(*fn)(void *), void *arg)
{
int err;
pthread_t tid;
pthread_attr_t attr;
err = pthread_attr_init(&attr);
if(err != 0){
return (err);
}
err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
if(err = 0){
err = pthread_create(&tid, &attr, fn, arg);
}
pthread_attr_destroy(&attr);
return (err);
}
void *timeout_helper(void *arg)
{
struct to_info *tip;
tip = (struct to_info *)arg;
nanosleep(&tip->to_wait, 0);
(*tip->to_fn)(tip->to_arg);
return (0);
}
void timeout(const struct timespec *when, void (*func)(void *), void *arg)
{
struct timespec now;
struct timeval tv;
struct to_info *tip;
int err;
gettimeofday(&tv, 0);
now.tv_sec = tv.tv_sec;
now.tv_nsec = tv.tv_usec * 1000;
if((when->tv_sec > now.tv_sec) ||
(when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)){
tip = malloc(sizeof(struct to_info));
if(tip != 0){
tip->to_fn = func;
tip->to_arg = arg;
tip->to_wait.tv_sec = when->tv_sec - now.tv_sec;
if(when->tv_nsec >= now.tv_nsec){
tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec;
} else {
tip->to_wait.tv_sec--;
tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec;
}
err = makethread(timeout_helper, (void *)tip);
if(err == 0){
return;
}
}
}
(*func)(arg);
}
pthread_mutexattr_t attr;
pthread_mutex_t mutex;
void retry(void *arg)
{
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
}
int main(void)
{
int err, condition, arg;
struct timespec when;
if((err = pthread_mutexattr_init(&attr)) != 0){
err_exit(err, "pthread_mutexattr_init failed");
}
if((err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) != 0){
err_exit(err, "can't set recursive type");
}
if((err = pthread_mutex_init(&mutex, &attr)) != 0){
err_exit(err, "can't create recursive mutex");
}
pthread_mutex_lock(&mutex);
if(condition){
timeout(&when, retry, (void *)arg);
}
pthread_mutex_unlock(&mutex);
exit(0);
}
| 0
|
#include <pthread.h>
void
print_buffer(byte *data, uint len, byte *counter, pthread_mutex_t *lock)
{
uint i;
char *buf;
buf = malloc((len * 2 ) + 1 );
for (i = 0; i < len; i++)
sprintf(buf + (i*2), "%02x", data[i] + *counter);
pthread_mutex_lock(lock);
printf("%s\\n", buf);
pthread_mutex_unlock(lock);
(*counter)++;
free(buf);
}
void *
thread_main(void *arg)
{
byte b = (byte) (intptr_t) arg;
char *buffer = malloc(sizeof("abcdefgh"));
pthread_mutex_t lock;
pthread_mutex_init(&lock, 0);
strncpy(buffer, "abcdefgh", strlen("abcdefgh"));
print_buffer(buffer, strlen("abcdefgh"), &b, &lock);
pthread_mutex_destroy(&lock);
free(buffer);
return 0;
}
int
main(int argc, char **argv)
{
int i;
void *retval;
pthread_t thread[10];
for (i = 0; i < 10; i++) {
if (pthread_create(&thread[i], 0, thread_main, (void *)(intptr_t)i)) {
exit(1);
}
}
for (i = 0; i < 10; i++) {
if (pthread_join(thread[i], &retval)) {
exit(1);
}
}
return 0;
}
| 1
|
#include <pthread.h>
sem_t ta_ready, have_stud, queue[3];
pthread_mutex_t chairs;
int nstuds, queue_head, queue_tail = -1;
static void *ta_thread(void *param)
{
for (;;) {
printf("[TA] Checking for students\\n");
sem_wait(&have_stud);
printf("[TA] Found one\\n");
pthread_mutex_lock(&chairs);
--nstuds;
sem_post(&queue[queue_head % 3]);
queue_head++;
pthread_mutex_unlock(&chairs);
printf("[TA] Helping student\\n");
sleep(1 + rand() % 3);
printf("[TA] Done helping student\\n");
sem_post(&ta_ready);
}
}
static void *stud_thread(void *param)
{
int whoami = *(int *) param;
sem_t my_sem;
for (;;) {
printf("[STUD %d] Programming\\n", whoami);
sleep(1 + rand() % 3);
printf("[STUD %d] Asking for help\\n", whoami);
pthread_mutex_lock(&chairs);
if (nstuds < 3) {
nstuds++;
pthread_mutex_unlock(&chairs);
sem_post(&have_stud);
printf("[STUD %d] Waiting\\n", whoami);
queue_tail++;
sem_init(&my_sem, 0, 0);
queue[queue_tail % 3] = my_sem;
sem_wait(&queue[queue_tail % 3]);
printf("[STUD %d] Getting help\\n", whoami);
} else {
printf("[STUD %d] No luck\\n", whoami);
pthread_mutex_unlock(&chairs);
}
}
}
static void init(pthread_attr_t *tattr)
{
pthread_attr_init(tattr);
pthread_mutex_init(&chairs, 0);
sem_init(&ta_ready, 0, 1);
sem_init(&have_stud, 0, 0);
srand(time(0));
}
int main(void)
{
pthread_t student[5 + 1];
int i, *stud[5];
pthread_attr_t tattr;
init(&tattr);
pthread_create(&student[0], &tattr, ta_thread, 0);
for (i = 1; i <= 5; i++) {
stud[i - 1] = malloc(sizeof i);
*(stud[i - 1]) = i;
pthread_create(&student[i], &tattr, stud_thread, stud[i - 1]);
}
for (i = 1; i <= 5; i++) {
pthread_join(student[i], 0);
free(stud[i - 1]);
}
return 0;
}
| 0
|
#include <pthread.h>
int b[10];
int cont = 0;
pthread_cond_t prod_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t cons_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mp = PTHREAD_MUTEX_INITIALIZER;
int prod_pos = 0;
int cons_pos = 0;
void * produtor(void * arg){
while(1){
printf("Proutor - Vai produzir\\n");
int p = (int)(drand48()*1000);
pthread_mutex_lock(&mp);
while (cont == 10) {
printf("Produtor - Dormindo\\n");
pthread_cond_wait(&prod_cond,&mp);
}
b[prod_pos]=p;
prod_pos = (prod_pos+1)%10;
printf("Produtor - produzindo\\n");
sleep(2);
printf("Produtor - Produziu\\n");
cont++;
if(cont == 1){
pthread_cond_signal(&cons_cond);
}
pthread_mutex_unlock(&mp);
}
}
void * consumidor(void * arg){
int id = (int) arg;
while(1){
printf("Consumidor %d - Quer Consumir\\n", id);
pthread_mutex_lock(&mp);
while (cont == 0) {
printf("Consumidor %d - Esperando\\n",id);
pthread_cond_wait(&cons_cond,&mp);
}
int c = b[cons_pos];
cons_pos = (cons_pos+1)%10;
cont--;
if(cont == (10 -1)){
pthread_cond_signal(&prod_cond);
}
pthread_mutex_unlock(&mp);
printf("Consumidor %d - Consumindo\\n",id);
sleep(5);
printf("Consumidor %d - Consumiu\\n",id );
}
}
int main() {
pthread_t c[10];
int i;
int *id;
srand48(time(0));
for(i = 0; i < 10; i++){
id = (int*)malloc(sizeof(int));
*id = i;
pthread_create(&c[i],0,consumidor,(void*)(id));
}
pthread_join(c[0],0);
return 0;
}
| 1
|
#include <pthread.h>
struct padded_int {
int value;
char padding[32000 - sizeof(int)];
};
struct padded_int * privateCount;
int * test_array;
int i, length, t;
int totalCount = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void * count3s(void * arg){
int id = *((int *) arg); id--;
int length_per_thread = length/t;
int start = id *length_per_thread;
for(i = start; i < start+length_per_thread; i++){
if(test_array[i] == 3){
privateCount[id].value++;
}
}
pthread_mutex_lock(&mutex);
totalCount += privateCount[id].value;
pthread_mutex_unlock(&mutex);
}
int main(int argc, char *argv[]) {
struct timespec start, end;
double cpu_time_used_iterative, cpu_time_used_threads;
int i, n_threads, array_size, debug_flag;
int counter_of_3 = 0;
if(argc > 2){
if(argc >= 3){
array_size = atoi(argv[1]);
n_threads = atoi(argv[2]);
if(argc == 4){
debug_flag = 1;
} else { debug_flag = 0; }
}
} else { fprintf(stderr, "Not enough inputs \\n"); return(1); }
length = array_size;
t = n_threads;
test_array = (int *) malloc(sizeof(int*)*array_size);
privateCount = (struct padded_int*) malloc(sizeof(struct padded_int)* n_threads);
for(i = 0; i < array_size; i++){
test_array[i] = (1 + rand() % ((5)+1 - (1)) );
if(debug_flag == 1 ){ printf("test_array[%d] = %d\\n", i, test_array[i]); }
}
clock_gettime(CLOCK_MONOTONIC, &start);
for(i = 0; i < array_size; i++){
if(test_array[i] == 3) counter_of_3++;
}
clock_gettime(CLOCK_MONOTONIC, &end);
cpu_time_used_iterative = 1e3 * (end.tv_sec - start.tv_sec) + 1e-6 * (end.tv_nsec - start.tv_nsec);
pthread_t tids[n_threads];
clock_gettime(CLOCK_MONOTONIC, &start);
for(i = 0; i < n_threads; i++){
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tids[i], &attr, count3s, &i);
}
int x;
for(x = 0; x < n_threads; x++){
pthread_join(tids[x], 0);
}
clock_gettime(CLOCK_MONOTONIC, &end);
cpu_time_used_threads = 1e3 * (end.tv_sec - start.tv_sec) + 1e-6 * (end.tv_nsec - start.tv_nsec);
printf("%f\\n", cpu_time_used_threads);
}
| 0
|
#include <pthread.h>
struct psuma {
uint16_t v1;
uint16_t v2;
uint32_t res;
};
void *suma (void *);
void *ver_cone (void *);
int leer_mensaje ( int , char * , int );
int cone;
pthread_mutex_t m;
pthread_cond_t c;
int main() {
int lon;
int sd;
int sd_cli;
struct sockaddr_in servidor;
struct sockaddr_in cliente;
pthread_t tid;
pthread_t tid_ver;
servidor.sin_family = AF_INET;
servidor.sin_port = htons (4444);
servidor.sin_addr.s_addr = INADDR_ANY;
sd = socket (PF_INET, SOCK_STREAM, 0);
if ( bind ( sd , (struct sockaddr *) &servidor , sizeof(servidor) ) < 0 ) {
perror("Error en bind\\n");
exit (-1);
}
listen ( sd , 5);
cone = 0;
pthread_mutex_init ( &m , 0);
pthread_cond_init ( &c , 0);
pthread_create ( &tid_ver, 0, ver_cone, 0 );
while (1) {
lon = sizeof(cliente);
sd_cli = accept ( sd , (struct sockaddr *) &cliente , &lon);
pthread_mutex_lock (&m);
cone++;
pthread_cond_signal (&c);
pthread_mutex_unlock (&m);
pthread_create ( &tid, 0, suma, &sd_cli );
}
close (sd);
}
void *suma ( void *arg ) {
int sdc;
int n;
char buffer[sizeof(struct psuma)];
struct psuma *suma;
suma = (struct psuma *) buffer;
sdc = *( (int *) arg);
n = 1;
while ( n != 0) {
if ( ( n = leer_mensaje ( sdc , buffer , sizeof(struct psuma) ) ) > 0 ) {
suma->res = htonl ( ntohs (suma->v1) + ntohs(suma->v2) );
printf ("Enviando: %d %d %d \\n",ntohs(suma->v1),ntohs(suma->v2),ntohl(suma->res));
send ( sdc , buffer , sizeof(struct psuma) ,0 );
}
}
close (sdc);
pthread_mutex_lock (&m);
cone--;
pthread_cond_signal (&c);
pthread_mutex_unlock (&m);
}
void *ver_cone (void * arg) {
while (1) {
pthread_mutex_lock (&m);
pthread_cond_wait(&c,&m);
printf("Conexiones %d\\n",cone);
pthread_mutex_unlock (&m);
}
}
int leer_mensaje ( int socket , char *buffer , int total ) {
int bytes, leido;
leido = 0;
bytes = 1;
while ( (leido < total) && (bytes > 0) ) {
bytes = recv ( socket , buffer + leido , total - leido , 0 );
leido = leido + bytes;
}
return (leido);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t avail;
pthread_cond_t ready;
int data_ready;
long data;
pthread_t thread;
struct stage_tag* next;
} stage_t;
pthread_mutex_t mutex;
stage_t* head;
stage_t* tail;
int stages;
int active;
} pipe_t;
int pipe_send(stage_t* stage, long data);
void* pipe_stage(void* arg);
int pipe_create(pipe_t* pipe, int stages);
int pipe_start(pipe_t* pipe, long value);
int pipe_result(pipe_t* pipe, long* result);
int main() {
pipe_t pipe;
long value, result;
char line[128];
pipe_create(&pipe, 10);
printf("Input a number or '='\\n");
while (1) {
printf("Input>> ");
if (fgets(line, sizeof(line), stdin) == 0)
exit(0);
if (strlen(line) <= 1)
continue;
if (strlen(line) <= 2 && line[0] == '=') {
if (pipe_result(&pipe, &result))
printf("The result is: %ld\\n", result);
else
printf("The pipe is empty\\n");
} else {
if (sscanf(line, "%ld", &value) < 1)
emsg("Input integer value.");
else
pipe_start(&pipe, value);
}
}
}
int pipe_send(stage_t* stage, long data) {
int s;
if ((s = pthread_mutex_lock(&stage->mutex)) != 0)
return s;
while (stage->data_ready) {
if ((s = pthread_cond_wait(&stage->ready, &stage->mutex)) != 0) {
pthread_mutex_unlock(&stage->mutex);
return s;
}
}
stage->data = data;
stage->data_ready = 1;
if ((s = pthread_cond_signal(&stage->avail)) != 0) {
pthread_mutex_unlock(&stage->mutex);
return s;
}
s = pthread_mutex_unlock(&stage->mutex);
return s;
}
void* pipe_stage(void* arg) {
stage_t* stage = (stage_t*) arg;
stage_t* next_stage = stage->next;
int s;
s = pthread_mutex_lock(&stage->mutex);
if (s != 0)
handle_err(s, "Lock pipe stage");
while (1) {
while (stage->data_ready != 1) {
s = pthread_cond_wait(&stage->avail, &stage->mutex);
if (s != 0)
handle_err(s, "Wait for previous stage");
}
pipe_send(next_stage, stage->data + 1);
stage->data_ready = 0;
s = pthread_cond_signal(&stage->ready);
if (s != 0)
handle_err(s, "Wake next stage");
}
}
int pipe_create(pipe_t* pipe, int stages) {
stage_t** link = &pipe->head;
stage_t* new_stage;
stage_t* stage;
int s;
s = pthread_mutex_init(&pipe->mutex, 0);
if (s != 0)
handle_err(s, "Init pipe mutex");
pipe->stages = stages;
pipe->active = 0;
for (int pipe_index = 0; pipe_index <= stages; pipe_index++) {
new_stage = malloc(sizeof(stage_t));
if ((s = pthread_mutex_init(&new_stage->mutex, 0)) != 0)
handle_err(s, "Init stage mutex");
if ((s = pthread_cond_init(&new_stage->avail, 0)) != 0)
handle_err(s, "Init avail cond");
if ((s = pthread_cond_init(&new_stage->ready, 0)) != 0)
handle_err(s, "Init ready cond");
new_stage->data_ready = 0;
*link = new_stage;
link = &new_stage->next;
}
*link = (stage_t*) 0;
pipe->tail = new_stage;
for (stage = pipe->head; stage->next != 0; stage = stage->next) {
if ((s = pthread_create(&stage->thread, 0, pipe_stage, (void*) stage)) != 0)
handle_err(s, "Create pipe stage");
}
return 0;
}
int pipe_start(pipe_t* pipe, long value) {
int s;
if ((s = pthread_mutex_lock(&pipe->mutex)) != 0)
handle_err(s, "Lock pipe mutex");
pipe->active++;
if ((s = pthread_mutex_unlock(&pipe->mutex)) != 0)
handle_err(s, "Unlock pipe mutex");
pipe_send(pipe->head, value);
return 0;
}
int pipe_result(pipe_t* pipe, long* result) {
stage_t* tail = pipe->tail;
int empty = 0;
int s;
if ((s = pthread_mutex_lock(&pipe->mutex)) != 0)
handle_err(s, "Lock pipe mutex");
if (pipe->active <= 0)
empty = 1;
else
pipe->active--;
if ((s = pthread_mutex_unlock(&pipe->mutex)) != 0)
handle_err(s, "Unlock pipe mutex");
if (empty)
return 0;
if ((s = pthread_mutex_lock(&tail->mutex)) != 0)
handle_err(s, "Lock tail mutex");
while (! tail->data_ready)
pthread_cond_wait(&tail->ready, &tail->mutex);
*result = tail->data;
tail->data_ready = 0;
pthread_cond_signal(&tail->ready);
pthread_mutex_unlock(&tail->mutex);
return 1;
}
| 0
|
#include <pthread.h>
pthread_key_t threadIdxxKey = 0;
pthread_key_t blockIdxxKey = 0;
pthread_key_t blockDimxKey = 0;
pthread_key_t gridDimxKey = 0;
pthread_mutex_t atom_add_mutex;
pthread_mutex_t thread_id_mutex;
pthread_mutex_t barrier_mutex;
pthread_mutex_t thread_gate_mutex;
void lock_atom_add(){
pthread_mutex_lock(&atom_add_mutex);
}
void unlock_atom_add(){
pthread_mutex_unlock(&atom_add_mutex);
}
void lock_thread_id(){
pthread_mutex_lock(&thread_id_mutex);
}
void unlock_thread_id(){
pthread_mutex_unlock(&thread_id_mutex);
}
void barrier_mutex_lock(){
pthread_mutex_lock(&barrier_mutex);
}
void barrier_mutex_unlock(){
pthread_mutex_unlock(&barrier_mutex);
}
void thread_gate_mutex_lock(){
pthread_mutex_lock(&thread_gate_mutex);
}
void thread_gate_mutex_unlock(){
pthread_mutex_unlock(&thread_gate_mutex);
}
int getThreadId(){
return getBlockIdxx() * getBlockDimx() + getThreadIdxx();
}
int getThreadIdxx(){
return (int) pthread_getspecific(threadIdxxKey);
}
int getBlockIdxx(){
return (int) pthread_getspecific(blockIdxxKey);
}
int getBlockDimx(){
return (int) pthread_getspecific(blockDimxKey);
}
int getGridDimx(){
return (int) pthread_getspecific(gridDimxKey);
}
long long java_lang_System_nanoTime(char * gc_info, int * exception){
struct timeval tm;
gettimeofday(&tm, 0);
return tm.tv_sec * 1000000 + tm.tv_usec;
}
void org_trifort_sleep(int micro_seconds){
usleep(micro_seconds);
}
| 1
|
#include <pthread.h>
char buf[100];
int fd;
pthread_mutex_t lock;
void* writeit()
{
pthread_mutex_lock(&lock);
printf("Enter data to send to server.\\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 server: %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("Server says: %s",buf);
close(fd);
}
pthread_mutex_unlock(&lock);
}
int main(int argc, char *argv[])
{
pthread_t thread1, thread2;
while(1)
{
int ret=mkfifo("datafile",0600);
fd=open("datafile",O_RDONLY);
if(fd<0)
{
printf("Failed to open file.\\n");
close(fd);
exit(0);
}
else
{
int ret1=pthread_create(&thread1,0,readit,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);
}
}
fd=open("datafile",O_WRONLY);
if(fd<0)
{
printf("Failed to open file.\\n");
exit(0);
}
else
{
int ret2=pthread_create(&thread2,0,writeit,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;
}
| 0
|
#include <pthread.h>
extern void __VERIFIER_error() ;
int __VERIFIER_nondet_int(void);
void ldv_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error();}; return; }
pthread_t t1, t2;
pthread_mutex_t mutex;
int pdev;
void ath9k_flush(void) {
pthread_mutex_lock(&mutex);
pdev = 6;
ldv_assert(pdev==6);
pthread_mutex_unlock(&mutex);
}
void *thread_ath9k(void *arg) {
while(1) {
switch(__VERIFIER_nondet_int()) {
case 1:
ath9k_flush();
break;
case 2:
goto exit_thread_ath9k;
}
}
exit_thread_ath9k:
return 0;
}
int ieee80211_register_hw(void) {
if(__VERIFIER_nondet_int()) {
pthread_create(&t2, 0, thread_ath9k, 0);
return 0;
}
return -1;
}
void ieee80211_deregister_hw(void) {
void *status;
pthread_join(t2, &status);
return;
}
static int ath_ahb_probe(void)
{
int error;
error = ieee80211_register_hw();
if (error)
goto rx_cleanup;
return 0;
rx_cleanup:
return -1;
}
void ath_ahb_disconnect() {
ieee80211_deregister_hw();
}
int ldv_usb_state;
void *thread_usb(void *arg) {
ldv_usb_state = 0;
int probe_ret;
while(1) {
switch(__VERIFIER_nondet_int()) {
case 0:
if(ldv_usb_state==0) {
probe_ret = ath_ahb_probe();
if(probe_ret!=0)
goto exit_thread_usb;
ldv_usb_state = 1;
}
break;
case 1:
if(ldv_usb_state==1) {
ath_ahb_disconnect();
ldv_usb_state=0;
pdev = 8;
ldv_assert(pdev==8);
}
break;
case 2:
if(ldv_usb_state==0) {
goto exit_thread_usb;
}
break;
}
}
exit_thread_usb:
pdev = 9;
ldv_assert(pdev==9);
return 0;
}
int module_init() {
pthread_mutex_init(&mutex, 0);
pdev = 1;
ldv_assert(pdev==1);
if(__VERIFIER_nondet_int()) {
pthread_create(&t1, 0, thread_usb, 0);
return 0;
}
pdev = 3;
ldv_assert(pdev==3);
pthread_mutex_destroy(&mutex);
return -1;
}
void module_exit() {
void *status;
pthread_join(t1, &status);
pthread_mutex_destroy(&mutex);
pdev = 5;
ldv_assert(pdev==5);
}
int main(void) {
if(module_init()!=0) goto module_exit;
module_exit();
module_exit:
return 0;
}
| 1
|
#include <pthread.h>
extern pthread_mutex_t global_data_mutex;
static int prevRainA = 0;
static int prevRainB = 0;
static int prevTime = 0;
static time_t reset_time = 0;
int open_rain_device(char * device_str)
{
int fd = -1;
assert(-1 == global_config.rain_fd);
if (0 != global_config.rain_serial && -1 == global_config.rain_fd) {
app_debug(debug, "Opening rain device: %s\\n" ,global_config.rain_serial);
fd = open_1wire_fd(global_config.rain_serial,"counters.ALL");
app_debug(debug, "rain_fd: %d\\n" ,fd);
}
return fd;
}
void update_rain_data (int rain_fd)
{
char counters[18];
int counterA;
int counterB;
int realcounters;
struct tm currtm;
time_t now;
int tm_hour, tm_min;
int read_rc;
assert(-1 != rain_fd);
memset(counters, 0, 18);
now = time(0);
if (0 == prevRainA || 0 == prevRainB)
{
app_debug(debug, "Rain: first time\\n");
sscanf(global_config.reset_tofd_str, "%2d:%2d", &tm_hour, &tm_min);
currtm = *localtime(&now);
currtm.tm_hour = tm_hour;
currtm.tm_min = tm_min;
currtm.tm_sec = 0;
reset_time = mktime(&currtm);
lseek(rain_fd, 0, 0);
read_rc = read(rain_fd, counters, 17);
if(-1 == read_rc)
{
app_debug(debug, "Rain:first time read error %d\\n", read_rc);
close(rain_fd);
global_config.rain_fd = -1;
return;
}
app_debug(debug, "Rain counters: %s\\n", counters);
sscanf(counters, "%d,%d", &counterA, &counterB);
app_debug(debug, "Rain counterA: %d\\n", counterA);
app_debug(debug, "Rain counterB: %d\\n", counterB);
prevRainA = counterA;
prevRainB = counterB;
prevTime = now;
}
lseek(rain_fd, 0, 0);
read_rc = read(rain_fd, counters, 17);
if(-1 == read_rc)
{
app_debug(debug, "Rain:read error %d\\n", read_rc);
close(rain_fd);
global_config.rain_fd = -1;
return;
}
sscanf(counters, "%d,%d", &counterA, &counterB);
app_debug(debug, "Rain counterA: %d\\n", counterA);
app_debug(debug, "Rain counterB: %d\\n", counterB);
realcounters = (counterA - prevRainA) + (counterB - prevRainB);
app_debug(debug, "Rain realcounters %d\\n", realcounters);
int diff = difftime(reset_time, now);
if(diff < 0)
{
app_debug(debug, "Rain: reset time\\n");
reset_time += 86400;
prevRainA = counterA;
prevRainB = counterB;
prevTime = now;
}
app_debug(debug, "Rain Counter:\\t%d\\n", realcounters);
if ((realcounters > 999) || (realcounters < 0))
{
app_debug(info, "Rain: Got garbage from the rain counter sensor. Rejecting\\n");
} else {
char *end;
pthread_mutex_lock(&global_data_mutex);
global_data.rain = (float)realcounters;
global_data.rain *= 0.01f;
global_data.rain *= strtof(global_config.rain_calib, &end);
app_debug(debug, "Rain Calibration:\\t%1.2f\\n", strtof(global_config.rain_calib, &end));
int part_of_hour = (int)(60/(now - prevTime + 1));
global_data.rainrate = global_data.rain * part_of_hour;
global_data.updatetime = time(0);
app_debug(debug, "Rain:\\t\\t%1.2f\\nRate:\\t\\t%1.2f\\n", global_data.rain, global_data.rainrate);
pthread_mutex_unlock(&global_data_mutex);
prevTime = now;
}
return;
}
| 0
|
#include <pthread.h>
pthread_mutex_t insertMutex;
pthread_mutex_t mutex;
pthread_cond_t mutex_cond = PTHREAD_COND_INITIALIZER;
int active = 0;
int activeDeletes = 0;
char *item;
struct list *next;
}Node;
Node *begin = 0;
Node *end = 0;
int searchThreads = 0;
int insertThreads = 0;
int deleteThreads = 0;
bool addToList(char *item){
bool success = 0;
Node *new = 0;
new = malloc(sizeof(Node));
if(new == 0){
fprintf(stderr,"insertToList : Malloc failed");
return 0;
}
char * buf = malloc(strlen(item) + 1);
if(buf == 0){
fprintf(stderr,"insertToList : Malloc failed");
return 0;
}
strcpy(buf,item);
new->item = buf;
new->next = 0;
if(begin == 0 || end == 0){
begin = new;
end = new;
return 1;
}
end->next = new;
end = end->next;
return 1;
}
void printList(){
if(begin == 0)
return;
Node *temp = begin;
printf("==============\\n");
while(temp!=0){
printf("%s\\n" , temp->item);
temp = temp->next;
}
}
bool removeFromList(char *item){
if(end == 0){
return 0;
}
Node *temp = begin;
Node *prev = 0;
while(temp != 0){
if(strcmp(temp->item,item)== 0){
if(prev == 0){
begin = begin->next;
free(temp->item);
free(temp);
return 1;
}
if(temp->next == 0){
end = prev;
}
prev->next = temp->next;
free(temp->item);
free(temp);
return 1;
}
prev = temp;
temp = temp->next;
}
return 0;
}
bool searchList(char *item){
Node * temp;
temp = begin;
if(temp == 0){
return 0;
}
while(temp != 0){
if(strcmp(temp->item,item) == 0){
return 1;
}
temp = temp->next;
}
return 0;
}
void printThreadInfo(char* operation, char* value, bool success, pthread_t tid){
int len = strlen(value);
value[len-1] = '\\0';
if(success)
printf("[%08x] Success %s [ %s ] Retrievers : %i Adders : %i Removers : %i\\n" ,tid, operation,value,searchThreads,insertThreads,deleteThreads);
else
printf("[%08x] Fail %s [ %s ] Retrievers : %i Adders : %i Removers : %i\\n" , tid , operation,value,searchThreads,insertThreads,deleteThreads);
}
void *searcher(void *args){
int k;
pthread_mutex_lock(&mutex);
active = active + 1;
searchThreads = searchThreads + 1;
pthread_mutex_unlock(&mutex);
char* temp = (char*)args;
bool success = searchList(temp);
printThreadInfo("Search" , temp , success,pthread_self());
pthread_mutex_lock(&mutex);
active = active - 1;
searchThreads = searchThreads - 1;
if(active == 0 && activeDeletes>0){
for(k=0;k<activeDeletes;k++)
pthread_cond_signal(&mutex_cond);
}
pthread_mutex_unlock(&mutex);
}
void* inserter(void *args){
pthread_mutex_lock(&insertMutex);
int k;
pthread_mutex_lock(&mutex);
active = active + 1;
insertThreads = insertThreads + 1;
pthread_mutex_unlock(&mutex);
char* temp = (char*)args;
bool success = addToList(temp);
printThreadInfo("Add" , temp , success,pthread_self());
pthread_mutex_lock(&mutex);
active = active - 1;
insertThreads = insertThreads - 1;
if(active == 0 && activeDeletes>0){
for(k=0;k<activeDeletes;k++)
pthread_cond_signal(&mutex_cond);
}
pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&insertMutex);
}
void * deleter(void *args){
pthread_mutex_lock(&mutex);
while(active != 0){
activeDeletes = activeDeletes + 1;
pthread_cond_wait(&mutex_cond,&mutex);
activeDeletes = activeDeletes-1;
}
deleteThreads = deleteThreads + 1;
char* temp = (char*)args;
bool success = removeFromList(temp);
printThreadInfo("Delete" , temp , success,pthread_self());
deleteThreads = deleteThreads - 1;
pthread_mutex_unlock(&mutex);
}
void initialize(void)
{
pthread_mutex_init(&mutex, 0);
pthread_mutex_init(&insertMutex, 0);
}
int main(int argc , char** argv){
pthread_t th[5000];
char* th_arg[5000];
int counter=0;
char c;
int l;
int j;
int len;
setbuf(stdout,0);
char filename[] = "p2_input.txt";
FILE *file = fopen ( filename, "r" );
if ( file != 0 )
{
char line [ 128 ];
while ( fgets ( line, sizeof line, file ) != 0 )
{
char *token;
token = strtok(line, " ");
c = token[0];
token = strtok(0, " ");
switch(c){
case 'A' :
th_arg[counter] = malloc(strlen(token) * sizeof(char) + 1);
strcpy(th_arg[counter],token);
pthread_create(&(th[counter]), 0, inserter, (void*)(th_arg[counter]));
counter++;
break;
case 'D' :
th_arg[counter] = malloc(strlen(token) * sizeof(char) + 1);
strcpy(th_arg[counter],token);
pthread_create(&(th[counter]), 0, deleter, (void*)(th_arg[counter]));
counter++;
break;
case 'M' :
for ( j = 0 ; j<counter ; j++ ){
if(th[j] != 0){
pthread_join(th[j], 0);
th[j] = 0;
free(th_arg[j]);
}
}
counter=0;
break;
case 'R' :
th_arg[counter] = malloc(strlen(token) * sizeof(char) + 1);
strcpy(th_arg[counter],token);
pthread_create(&(th[counter]), 0, searcher, (void*)(th_arg[counter]));
counter++;
break;
default :
printf("Input error : %c", c);
}
}
printList();
fclose ( file );
}
else
{
perror ( filename );
}
return 0;
}
| 1
|
#include <pthread.h>
int value;
pthread_cond_t* cond;
pthread_mutex_t mtx;
int status;
} SimpleChannel;
SimpleChannel createChannel(){
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
SimpleChannel ch = {
0,
0,
mtx,
0
};
return ch;
}
void send(SimpleChannel* ch, int v){
pthread_mutex_lock(&(ch->mtx));
if(ch->status==2){
ch->value = v;
ch->status = 0;
pthread_mutex_unlock(&(ch->mtx));
pthread_cond_signal(ch->cond);
return;
}
else if(ch->status==1){
return;
}
else{
ch->status = 1;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
ch->cond = &cond;
ch->value = v;
pthread_cond_wait(&cond,&(ch->mtx));
pthread_mutex_unlock(&(ch->mtx));
return;
}
}
int recieve(SimpleChannel* ch){
pthread_mutex_lock(&(ch->mtx));
int ret;
if(ch->status==1){
ch->status = 0;
ret = ch->value;
pthread_mutex_unlock(&(ch->mtx));
pthread_cond_signal(ch->cond);
return ret;
}
else if(ch->status==2){
return 0;
}
else{
ch->status = 2;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
ch->cond = &cond;
pthread_cond_wait(&cond,&(ch->mtx));
ret = ch->value;
pthread_mutex_unlock(&(ch->mtx));
return ret;
}
}
void* doSomething( void* arg ){
SimpleChannel* ch = (SimpleChannel*) arg;
int foo = recieve(ch);
printf("Recieved: %d\\n",foo);
}
int main(){
SimpleChannel ch = createChannel();
pthread_t thread;
printf("started!\\n");
pthread_create(&thread, 0, doSomething, &ch );
send(&ch,13);
send(&ch,69);
pthread_join(thread, 0);
}
| 0
|
#include <pthread.h>
int thread_flag;
pthread_cond_t thread_flag_cv ;
pthread_mutex_t thread_flag_mutex ;
void initialize_flag ()
{
pthread_mutex_init (&thread_flag_mutex, 0);
pthread_cond_init (&thread_flag_cv, 0);
thread_flag = 0;
}
void* thread_function (void* thread_arg)
{
while (1)
{
pthread_mutex_lock (&thread_flag_mutex);
while (!thread_flag)
pthread_cond_wait (&thread_flag_cv, &thread_flag_mutex);
pthread_mutex_unlock (&thread_flag_mutex);
do_work ();
}
return 0;
}
void set_thread_flag (int flag_value)
{
pthread_mutex_lock (&thread_flag_mutex);
thread_flag = flag_value;
pthread_cond_signal (&thread_flag_cv);
pthread_mutex_unlock (&thread_flag_mutex);
}
| 1
|
#include <pthread.h>
extern pthread_mutex_t mutex;
static bool accept_anyways(unsigned cur_eval, unsigned neigh_eval,
double temperature);
static unsigned update_temperature(unsigned t, unsigned TEMP_INITIAL,
unsigned T_MAX, unsigned COOLING_RATE);
struct jsp optimise(struct jsp schedule, struct jsp **current,
enum algorithm alg, unsigned T_MAX,
unsigned TEMP_INITIAL, unsigned COOLING_RATE) {
double temperature = TEMP_INITIAL;
struct jsp optimum = copy_jsp_data(schedule);
*current = &optimum;
unsigned opt_eval = eval(&optimum);
for (unsigned t = 1; t < T_MAX; ++t) {
unsigned cur_eval = eval(&schedule);
struct jsp neigh_schedule = get_neighbour(schedule);
unsigned neigh_eval = eval(&neigh_schedule);
if (neigh_eval < cur_eval) {
delete_jsp(&schedule);
schedule = neigh_schedule;
} else if ((alg == A_STOCHASTIC_HILLCLIMBING
|| alg == A_SIMULATED_ANNEALING)
&& accept_anyways(cur_eval, neigh_eval, temperature)) {
delete_jsp(&schedule);
schedule = neigh_schedule;
} else {
delete_jsp(&neigh_schedule);
}
if (cur_eval < opt_eval) {
delete_jsp(&optimum);
optimum = copy_jsp_data(schedule);
opt_eval = cur_eval;
}
if (alg == A_SIMULATED_ANNEALING) {
temperature = update_temperature(t, TEMP_INITIAL, T_MAX,
COOLING_RATE);
}
}
if (schedule.operations != 0) {
delete_jsp(&schedule);
}
pthread_mutex_lock(&mutex);
*current = 0;
pthread_mutex_unlock(&mutex);
return optimum;
}
static bool accept_anyways(unsigned cur_eval, unsigned neigh_eval,
double temperature) {
double rval = rand() / (1.0 * 32767);
double diff = 1.0 * cur_eval - neigh_eval;
return rval < exp((diff) / temperature);
}
static unsigned update_temperature(unsigned t, unsigned TEMP_INITIAL,
unsigned T_MAX, unsigned COOLING_RATE) {
double new_temp = TEMP_INITIAL * exp(-1.0 * COOLING_RATE * t / T_MAX);
return new_temp;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
int count=0;
char msg_buf[64];
void SetMsg_Func(void);
void PrintMsg_Func(void);
int main()
{
int ret;
pthread_t set_thread;
count = 4;
pthread_mutex_init(&mutex,0);
ret = pthread_create(&set_thread,0, (void *)&SetMsg_Func, 0);
if (ret != 0)
{
perror("Thread Creation Failed");
exit(1);
}
PrintMsg_Func();
ret = pthread_join(set_thread, 0);
if (ret != 0)
{
perror("Thread join failed");
exit(1);
}
printf("Finished!\\n");
pthread_mutex_destroy(&mutex);
return 0;
}
void SetMsg_Func(void)
{
while(count>0)
{
pthread_mutex_lock(&mutex);
memset(msg_buf,0,64);
sprintf(msg_buf,"count=%d.\\n",count--);
pthread_mutex_unlock(&mutex);
srand((int)time(0));
sleep(rand()%3);
}
pthread_exit(0);
}
void PrintMsg_Func(void)
{
while(count>=0)
{
pthread_mutex_lock(&mutex);
printf(msg_buf);
pthread_mutex_unlock(&mutex);
if(0==count)
break;
srand((int)time(0));
sleep(rand()%3); }
}
| 1
|
#include <pthread.h>
int shmid;
int matsize;
int *pint;
char thisStart[10];
char thisWalkno[10];
char thisMatsize[10];
char thisShmkey[10];
}arguments;
arguments tid_arg;
void *tidchild(void *child);
main(int argc, char *argv[])
{
int i, j, k, m, n, shmkey, offset;
int status = 0;
char *addr;
int walkers, walktid, next, start;
pthread_t tid;
pthread_attr_t attr;
if (argc < 3)
{
perror("Not enough parameters: basename, matsize, start");
exit(1);
}
matsize = atoi(argv[1]);
start = atoi(argv[2]);
shmkey = 75;
shmid = shmget(shmkey, 4096, 0777| IPC_CREAT);
addr = shmat(shmid,0,0);
printf("start of memory 0x%x\\n", addr);
pint = (int *)addr;
printf("loading shm \\n");
for(i=0; i < matsize; i++)
{
pint++;
*pint = 0;
}
pint = (int *)addr;
printf("verifying shm \\n");
for (i = 0; i < matsize; i++)
{
pint++;
printf("%d\\t %d\\t\\n", pint, *pint);
}
sprintf(tid_arg.thisWalkno, "%d", (m + 1));
sprintf(tid_arg.thisStart, "%d", start);
sprintf(tid_arg.thisMatsize, "%d", matsize);
sprintf(tid_arg.thisShmkey, "%d", shmkey);
int tid_child[matsize];
for(m = 0; m < matsize; ++m)
{
printf("started walker %d\\t\\n", m);
pthread_attr_init(&attr);
tid_child[m] = m;
if (pthread_create(&tid, &attr, tidchild, (void *)(tid_child + m)) != 0) {
printf("Could not execute child program\\n");
exit(1);
}
}
sleep(5);
pint=(int *)addr;
*pint=atoi(argv[2]);
printf( "Unblocking\\n");
pthread_join(tid,0);
printf("all children completed\\n");
printf("Bryan Cantos ID: %d\\n", 23023992);
}
void *tidchild(void *child) {
int* walkno = (int*)child;
int i;
char *addr;
srand(time(0));
int start, shmid, matsize, shmkey;
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, 0);
start = atoi(tid_arg.thisStart);
matsize = atoi(tid_arg.thisMatsize);
shmkey = atoi(tid_arg.thisShmkey);
printf("walkno = %d\\n", *walkno);
printf("start = %d\\n", start);
printf("matsize = %d\\n", matsize);
printf("shmkey = %d\\n", shmkey);
printf("child %d start %d size of list %d memory key %d \\n", *walkno, start, matsize,shmkey);
shmid = shmget(shmkey, 4096, 0777);
addr = shmat(shmid,0,0);
pint = (int *)addr;
while(*pint > start)
pint=(int *)addr;
pthread_mutex_lock(&mutex);
printf("Child %d acquires the mutex lock and is entering critcal section\\n", *walkno);
printf("Child %d is looking for free slot\\n", *walkno);
if(*pint != 0)
{
printf("Slot is taken, Child %d looking for a new slot\\n", *walkno);
pint++;
while(*pint != 0)
{
printf("Child %d is still looking for a free slot\\n", *walkno);
pint++;
}
}
printf("Child %d found free slot\\n", *walkno);
printf("Child %d is putting his ID in slot\\n", *walkno);
*pint = pthread_self();
printf("Child %d ID is %d\\n", *walkno, *pint);
printf("Child %d is now letting go of lock and leaving critcal section\\n", *walkno);
pthread_mutex_unlock(&mutex);
printf("Child %d is now sleeping\\n", *walkno);
sleep(rand() % 10);
printf ("Child %d is now exiting. Putting 0 in slot\\n", *walkno);
*pint = 0;
pint=(int *)addr;
printf( "child %d pint %d *pint %d\\n",*walkno, pint, *pint);
for(i= 0; i < matsize; i++)
{
pint++;
printf("%d\\t", *pint);
}
printf("\\n");
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int A[6][6];
int B[6][6];
int qtd = 0;
pthread_cond_t condVar;
pthread_mutex_t monitorLock;
int id;
int iter;
} thread_arg;
void preenche(int A[6][6], int m, int n){
int i,j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
A[i][j] = i + j + i*j;
}
void imprime(int A[6][6], int m, int n){
int i,j;
for (i = 0; i < m; i++){
for (j = 0; j < n; j++){
printf("|%d|\\t", A[i][j]);
}
printf("\\n");
}
printf("-----------------------------------------------------\\n");
}
void calculaSEQ(int X[6][6], int Y[6][6], int m, int n){
int i, j;
for(i = 0; i < m; i++){
for(j = 0; j <n; j++){
if(i == 0 || j == 0 || i == (m-1) || j == (n-1)){
Y[i][j] = X[i][j];
} else {
Y[i][j] = (X[i-1][j] + X[i+1][j] + X[i][j-1] +X[i][j+1])/1;
}
}
}
}
int barreira(){
pthread_mutex_lock(&monitorLock);
qtd++;
if(qtd < 2){
printf("CALMA %d\\n", qtd);
pthread_cond_wait(&condVar, &monitorLock);
} else {
printf("ACABOU %d\\n", qtd);
pthread_cond_broadcast(&condVar);
qtd = 0;
}
pthread_mutex_unlock(&monitorLock);
return 0;
}
void *calculaPAR(void *vargp){
thread_arg *arg = (thread_arg *) vargp;
int threadId = arg->id;
int iter = arg-> iter;
int i,j;
for (i = (threadId*(6/2)); i < ((threadId+1)*(6/2)); i++){
for (j = 0; j < 6; j++){
if(iter % 2 == 0){
if(j == 0 || i == 0 || i == (6 - 1) || j == (6 - 1)){
B[i][j] = A[i][j];
} else {
B[i][j] = (A[i-1][j] + A[i+1][j] + A[i][j-1] + A[i][j+1])/1;
}
} else {
if(j == 0 || i == 0 || i == (6 - 1) || j == (6 - 1)){
A[i][j] = B[i][j];
} else {
A[i][j] = (B[i-1][j] + B[i+1][j] + B[i][j-1] + B[i][j+1])/1;
}
}
}
barreira();
}
pthread_exit(0);
}
int main(int argc, char **argv) {
pthread_t threads[2];
pthread_attr_t atributos;
pthread_attr_init(&atributos);
pthread_attr_setdetachstate(&atributos, PTHREAD_CREATE_JOINABLE);
pthread_attr_setscope(&atributos,PTHREAD_SCOPE_SYSTEM);
pthread_mutex_init(&monitorLock, 0);
pthread_cond_init(&condVar, 0);
int a, i,flag;
preenche(A,6,6);
for (a = 0; a < 3; a++){
printf("ITERACAO => %d\\n\\n", a);
for (i = 0; i < 2; i++){
thread_arg arg[2];
arg[i].id = i;
arg[i].iter = a;
flag = pthread_create(&threads[i], &atributos, calculaPAR, (void *) &arg[i]);
}
if (flag)
exit(-1);
for (i = 0; i < 2; i++)
pthread_join(threads[i], 0);
imprime(A,6,6);
imprime(B,6,6);
}
pthread_mutex_destroy(&monitorLock);
pthread_cond_destroy(&condVar);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
int buffer;
int estado = 0;
void produtor(int id)
{
int i=0;
int item;
int aguardar;
printf("Inicio produtor %d \\n",id);
while (i < 10)
{
item = i + (id*1000);
pthread_mutex_lock(&mutex);
while (estado == 1)
{
pthread_mutex_unlock(&mutex);
pthread_yield();
pthread_mutex_lock(&mutex);
}
printf("Produtor %d inserindo item %d\\n", id, item);
buffer = item;
estado = 1;
pthread_mutex_unlock(&mutex);
i++;
sleep(1);
}
printf("Produtor %d terminado \\n", id);
}
void consumidor(int id)
{
int item;
int aguardar;
printf("Inicio consumidor %d \\n",id);
while (1)
{
pthread_mutex_lock(&mutex);
while (estado == 0)
{
pthread_mutex_unlock(&mutex);
pthread_yield();
pthread_mutex_lock(&mutex);
}
item = buffer;
estado = 0;
pthread_mutex_unlock(&mutex);
printf("Consumidor %d consumiu item %d\\n", id, item);
sleep(1);
}
printf("Consumidor %d terminado \\n", id);
}
int main()
{
pthread_t prod1;
pthread_t prod2;
pthread_t prod3;
pthread_t cons1;
pthread_t cons2;
printf("Programa Produtor-Consumidor\\n");
printf("Iniciando variaveis de sincronizacao.\\n");
pthread_mutex_init(&mutex,0);
printf("Disparando threads produtores\\n");
pthread_create(&prod1, 0, (void*) produtor,1);
pthread_create(&prod2, 0, (void*) produtor,2);
pthread_create(&prod3, 0, (void*) produtor,3);
printf("Disparando threads consumidores\\n");
pthread_create(&cons1, 0, (void*) consumidor,1);
pthread_create(&cons2, 0, (void*) consumidor,2);
pthread_join(prod1,0);
pthread_join(prod2,0);
pthread_join(prod3,0);
pthread_join(cons1,0);
pthread_join(cons2,0);
printf("Terminado processo Produtor-Consumidor.\\n\\n");
}
| 0
|
#include <pthread.h>
pthread_mutex_t m;
pthread_cond_t cond;
char str[100];
bool str_available;
void* producer(void* arg ) {
while (1) {
fgets(str, sizeof str, stdin);
pthread_mutex_lock(&m);
str_available = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&m);
}
}
void* consumer(void* arg ) {
while (1) {
pthread_mutex_lock(&m);
while (!str_available) {
pthread_cond_wait(&cond, &m);
}
char str_snapshot[sizeof str];
strncpy(str_snapshot, str, sizeof str_snapshot);
str_available = 0;
pthread_mutex_unlock(&m);
printf("Got string: %s", str_snapshot);
for (int i = 0; i < 4; i++) {
usleep(500000);
}
printf("Repeating: %s", str_snapshot);
}
}
int main(void) {
pthread_mutex_init(&m, 0);
pthread_cond_init(&cond, 0);
pthread_t id1, id2;
assert(pthread_create(&id1, 0, producer, 0) == 0);
assert(pthread_create(&id2, 0, consumer, 0) == 0);
assert(pthread_join(id1, 0) == 0);
assert(pthread_join(id2, 0) == 0);
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&m);
return 0;
}
| 1
|
#include <pthread.h>
int k = 0;
pthread_cond_t cond;
pthread_mutex_t mutex;
void* writing()
{
time_t rawtime;
struct tm *timeinfo;
int file;
int num_str = 1;
char str[100];
while(1)
{
pthread_mutex_lock(&mutex);
time(&rawtime);
timeinfo = localtime(&rawtime);
file = open("time.txt", O_CREAT|O_WRONLY|O_APPEND, 0700);
write(file, str, strlen(str));
num_str++;
k = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_exit(0);
}
void* reading()
{
int file;
int str_read = 0;
int str_write = 0;
char str[100];
while(1)
{
pthread_mutex_lock(&mutex);
while (k != 1)
pthread_cond_wait(&cond, &mutex);
file = open("time.txt", O_CREAT|O_RDONLY, 0700);
while ((str_read = read(file, str, 128)) > 0)
{
str_write = write (1, str, str_read);
}
printf("&&&&&&&&&&&&&&&&&&&&\\n");
k = 0;
pthread_mutex_unlock(&mutex);
sleep(5);
}
pthread_exit(0);
}
int main (int argc, char* argv[])
{
pthread_t writer;
pthread_t readers [10];
int i;
if(pthread_create(&writer, 0, writing, 0)<0)
{
printf("ERROR: create writer thread false\\n");
return -1;
}
for (i = 0; i<10; ++i)
{
if(pthread_create(&readers[i], 0, reading, 0)<0)
{
printf("ERROR: create reading thread %d false\\n", i);
return -1;
}
}
if(pthread_join(writer, 0)<0)
{
printf("ERROR: joining writer thread false\\n");
return -1;
}
for (i = 0; i<10; ++i)
{
if(pthread_join(readers[i], 0)<0)
{
printf("ERROR: joining reading thread %d false\\n", i);
return -1;
}
}
return 0;
}
| 0
|
#include <pthread.h>
int one=0,two=0,more=0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
void* f( void *p)
{
while(one<5 || two<5 || more<5)
{
int n = 1 + rand()%999;
printf("Valoare: %d \\n",n);
if(n/10==0)
{
pthread_mutex_lock(&m);
one++;
pthread_mutex_unlock(&m);
}
else if(n/100==0)
{
pthread_mutex_lock(&m);
two++;
pthread_mutex_unlock(&m);
}
else
{
pthread_mutex_lock(&m);
more++;
pthread_mutex_unlock(&m);
}
}
return 0;
}
int main()
{
srand(time(0));
pthread_mutex_init(&m, 0);
pthread_t T[7];
int i;
for(i=0;i<=6;i++)
pthread_create(&T[i],0,f,0);
for(i=0;i<7;i++)
pthread_join(T[i],0);
printf("One digit: %d, two digits: %d, more: %d \\n",one,two,more);
pthread_mutex_destroy(&m);
return 0;
}
| 1
|
#include <pthread.h>
static void set_realtime(void)
{
struct sched_param p;
int ret;
p.sched_priority = 1;
ret = sched_setscheduler(0, SCHED_FIFO, &p);
if (ret == -1) {
fprintf(stderr, "Failed to set scheduler to SCHED_FIFO\\n");
}
}
static void high_priority(void)
{
int ret;
ret = nice(-20);
if (ret == -1) {
fprintf(stderr, "Failed to set high priority\\n");
}
}
static void run_child(const char *filename)
{
pthread_mutex_t *mutex;
void *addr;
int ret, fd;
fd = open(filename, O_RDWR, 0600);
if (fd == -1) {
exit(1);
}
addr = mmap(0, sizeof(pthread_mutex_t), PROT_READ|PROT_WRITE,
MAP_SHARED|MAP_FILE, fd, 0);
if (addr == 0) {
exit(2);
}
mutex = (pthread_mutex_t *)addr;
again:
ret = pthread_mutex_lock(mutex);
if (ret == EOWNERDEAD) {
ret = pthread_mutex_consistent(mutex);
} else if (ret == EAGAIN) {
goto again;
}
if (ret != 0) {
fprintf(stderr, "pid %u lock failed, ret=%d\\n", getpid(), ret);
exit(3);
}
fprintf(stderr, "pid %u locked\\n", getpid());
kill(getpid(), SIGKILL);
}
int main(int argc, const char **argv)
{
pthread_mutexattr_t ma;
pthread_mutex_t *mutex;
int fd, ret, i;
pid_t pid;
void *addr;
int num_children;
int priority = 0;
if (argc < 3 || argc > 4) {
fprintf(stderr, "Usage: %s <file> <n> [0|1|2]\\n", argv[0]);
fprintf(stderr, " %s <file> debug\\n", argv[0]);
exit(1);
}
if (argc == 4) {
priority = atoi(argv[3]);
}
if (priority == 1) {
set_realtime();
} else if (priority == 2) {
high_priority();
}
fd = open(argv[1], O_CREAT|O_RDWR, 0600);
if (fd == -1) {
fprintf(stderr, "open failed\\n");
exit(1);
}
ret = lseek(fd, 0, 0);
if (ret != 0) {
fprintf(stderr, "lseek failed\\n");
exit(1);
}
ret = ftruncate(fd, sizeof(pthread_mutex_t));
if (ret != 0) {
fprintf(stderr, "ftruncate failed\\n");
exit(1);
}
addr = mmap(0, sizeof(pthread_mutex_t), PROT_READ|PROT_WRITE,
MAP_SHARED|MAP_FILE, fd, 0);
if (addr == 0) {
fprintf(stderr, "mmap failed\\n");
exit(1);
}
mutex = (pthread_mutex_t *)addr;
if (strcmp(argv[2], "debug") == 0) {
ret = pthread_mutex_trylock(mutex);
if (ret == EOWNERDEAD) {
ret = pthread_mutex_consistent(mutex);
if (ret == 0) {
pthread_mutex_unlock(mutex);
}
} else if (ret == EBUSY) {
printf("pid=%u\\n", mutex->__data.__owner);
} else if (ret == 0) {
pthread_mutex_unlock(mutex);
}
exit(0);
}
ret = pthread_mutexattr_init(&ma);
if (ret != 0) {
fprintf(stderr, "pthread_mutexattr_init failed\\n");
exit(1);
}
ret = pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_ERRORCHECK);
if (ret != 0) {
fprintf(stderr, "pthread_mutexattr_settype failed\\n");
exit(1);
}
ret = pthread_mutexattr_setpshared(&ma, PTHREAD_PROCESS_SHARED);
if (ret != 0) {
fprintf(stderr, "pthread_mutexattr_setpshared failed\\n");
exit(1);
}
ret = pthread_mutexattr_setrobust(&ma, PTHREAD_MUTEX_ROBUST);
if (ret != 0) {
fprintf(stderr, "pthread_mutexattr_setrobust failed\\n");
exit(1);
}
ret = pthread_mutex_init(mutex, &ma);
if (ret != 0) {
fprintf(stderr, "pthread_mutex_init failed\\n");
exit(1);
}
ret = pthread_mutex_lock(mutex);
if (ret != 0) {
fprintf(stderr, "pthread_mutex_lock failed\\n");
exit(1);
}
setpgid(0, 0);
fprintf(stderr, "Creating children\\n");
num_children = atoi(argv[2]);
for (i=0; i<num_children; i++) {
pid = fork();
if (pid < 0) {
fprintf(stderr, "fork() failed\\n");
exit(1);
}
if (pid == 0) {
close(fd);
run_child(argv[1]);
exit(1);
}
}
fprintf(stderr, "Waiting for children\\n");
ret = pthread_mutex_unlock(mutex);
if (ret != 0) {
fprintf(stderr, "pthread_mutex_unlock failed\\n");
exit(1);
}
for (i=0; i<num_children; i++) {
int status;
pid = waitpid(-1, &status, 0);
if (pid <= 0) {
fprintf(stderr, "waitpid() failed\\n");
}
}
close(fd);
unlink(argv[1]);
exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer[10] = {0,0,0,0,0,0,0,0,0,0};
void *producer(void *ptr)
{
int i=0;
pthread_mutex_lock(&the_mutex);
while(buffer[i]!=0 && i<10)
{
pthread_cond_wait(&condp, &the_mutex);
i++;
}
for(i=0; i<10; i++)
{
printf("procucer produce item %d\\n",i);
buffer = i;
pthread_cond_signal(&condc);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
void *consumer(void *ptr)
{
int i;
for(i=1; i<=10; i++)
{
pthread_mutex_lock(&the_mutex);
while(buffer ==0) pthread_cond_wait(&condc, &the_mutex);
printf("consumer consume item %d\\n",i);
buffer = 0;
pthread_cond_signal(&condp);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
int main(int argc, char *argv[])
{
pthread_t pro, con;
pthread_mutex_init(&the_mutex, 0);
pthread_cond_init(&condc,0);
pthread_cond_init(&condp,0);
pthread_create(&con, 0, consumer, 0);
pthread_create(&pro, 0, producer, 0);
pthread_join(pro,0);
pthread_join(con,0);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
pthread_mutex_destroy(&the_mutex);
return 0;
}
| 1
|
#include <pthread.h>
void read_from_usb_thread(void *p) {
struct device_data* dev = (struct device_data*)p;
unsigned int ret = 0, i;
unsigned char buff[4] = {0, 0, 0, 0};
unsigned long rfu_sleep_time = THREAD_SLEEP_TIME;
while(1) {
if(pCMDValue.exit_time>0 && pCMDValue.exit_time<time(0)) break;
if(ret==0) {
ret = read_obd_serial(dev->fd, (char*)dev->usb_read_tmp_buffer, 100 );
if(ret<0) ret = 0;
}
if(ret>0) {
pthread_mutex_lock(&dev->usb_read_mutex);
if(10000-dev->usb_read_buffer_length>ret ) {
memcpy(dev->usb_read_buffer+dev->usb_read_buffer_length, dev->usb_read_tmp_buffer, ret);
dev->usb_read_buffer_length +=ret;
ret=0;
rfu_sleep_time = THREAD_SLEEP_TIME;
}
pthread_mutex_unlock(&dev->usb_read_mutex);
}
if(rfu_sleep_time>THREAD_SLEEP_TIME) usleep( rfu_sleep_time );
if(rfu_sleep_time<THREAD_MAX_SLEEP_TIME) rfu_sleep_time += THREAD_SLEEP_TIME;
}
printf("exit: usb_read\\n");
pthread_exit(p);
}
| 0
|
#include <pthread.h>
char *line;
int pid;
FILE *fp;
pthread_t thread;
} Command;
int n = 0;
Command *commands = 0;
bool stop = 0;
bool shutdown_pending = 0;
pthread_mutex_t mutex;
sigset_t block_mask;
int _run_command(Command *cmd) {
int filedes[2];
if (pipe(filedes) == -1) return -1;
pid_t pid = fork();
if (pid == -1) {
close(filedes[0]);
close(filedes[1]);
return -1;
} else if (pid == 0) {
setpgrp();
dup2(filedes[1], STDOUT_FILENO);
close(filedes[1]);
close(filedes[0]);
execl("/bin/sh", "sh", "-c", cmd->line, 0);
_exit(127);
} else {
FILE *fp = fdopen(filedes[0], "r");
close(filedes[1]);
cmd->pid = pid;
cmd->fp = fp;
return 0;
}
}
int run_command(Command *cmd) {
sigset_t previous;
sigprocmask(SIG_BLOCK, &block_mask, &previous);
int rc = _run_command(cmd);
sigprocmask(SIG_SETMASK, &previous, 0);
return rc;
}
void send_signal(int signo) {
for (int i = 0; i < n; ++i) {
if (commands[i].pid) {
kill(-commands[i].pid, signo);
}
}
}
void sig_handler(int signo) {
pthread_mutex_lock(&mutex);
switch (signo) {
case SIGINT:
if (shutdown_pending) {
send_signal(SIGKILL);
} else {
send_signal(SIGTERM);
shutdown_pending = 1;
}
break;
case SIGTERM:
send_signal(SIGTERM);
break;
case SIGQUIT:
send_signal(SIGKILL);
break;
case SIGABRT:
_exit(0);
}
stop = 1;
pthread_mutex_unlock(&mutex);
}
void *watch_command(void *ptr) {
Command *cmd = (Command*)ptr;
while (1) {
pthread_mutex_lock(&mutex);
if (stop) {
cmd->pid = 0;
pthread_mutex_unlock(&mutex);
break;
}
if (run_command(cmd) == -1) {
fprintf(stderr, "overlord: cannot run command: %s\\n", strerror(errno));
cmd->pid = 0;
pthread_mutex_unlock(&mutex);
sleep(1);
continue;
}
pthread_mutex_unlock(&mutex);
char *line = 0;
ssize_t linelen;
size_t linecap = 0;
while ((linelen = getline(&line, &linecap, cmd->fp)) > 0)
fwrite(line, linelen, 1, stdout);
fclose(cmd->fp);
int pstat;
pid_t pid;
do {
pid = waitpid(cmd->pid, &pstat, 0);
} while (pid == -1 && errno == EINTR);
}
pthread_exit(0);
}
char *trim_whitespace(char *str) {
char *end;
while(isspace(*str)) str++;
if(*str == 0)
return str;
end = str + strlen(str) - 1;
while(end > str && isspace(*end)) end--;
*(end+1) = 0;
return str;
}
int main() {
char *line = 0;
ssize_t linelen;
size_t linecap = 0;
while ((linelen = getline(&line, &linecap, stdin)) > 0) {
char *trimmed = trim_whitespace(line);
if (*trimmed == '\\0') continue;
commands = realloc(commands, sizeof(Command) * ++n);
if (commands == 0) {
fprintf(stderr, "overlord: %s\\n", strerror(errno));
return 1;
}
commands[n-1].pid = 0;
commands[n-1].line = malloc(strlen(trimmed)+1);
if (commands[n-1].line == 0) {
fprintf(stderr, "overlord: %s\\n", strerror(errno));
return 2;
}
strcpy(commands[n-1].line, trimmed);
}
pthread_mutex_init(&mutex, 0);
sigemptyset(&block_mask);
sigaddset(&block_mask, SIGINT);
sigaddset(&block_mask, SIGTERM);
sigaddset(&block_mask, SIGQUIT);
sigaddset(&block_mask, SIGABRT);
struct sigaction act;
act.sa_handler = sig_handler;
act.sa_mask = block_mask;
act.sa_flags = 0;
sigaction(SIGINT, &act, 0);
sigaction(SIGTERM, &act, 0);
sigaction(SIGQUIT, &act, 0);
sigaction(SIGABRT, &act, 0);
for (int i = 0; i < n; ++i) {
if (pthread_create(&commands[i].thread, 0, watch_command, (void*)&commands[i]) != 0) {
fprintf(stderr, "overlord: cannot create thread");
pthread_mutex_lock(&mutex);
send_signal(SIGKILL);
stop = 1;
pthread_mutex_unlock(&mutex);
return 3;
}
}
for (int i = 0; i < n; ++i)
pthread_join(commands[i].thread, 0);
return 0;
}
| 1
|
#include <pthread.h>
int last_threadID;
int successes;
int count = 1;
pthread_mutex_t lock;
void *function(void *threadid)
{
int tid = (int)threadid;
pthread_mutex_lock(&lock);
int difference = tid-last_threadID;
if(difference != 1) {
}
else {
printf("%d - %d\\n",difference,tid);
successes = successes++;
last_threadID = tid;
if(last_threadID == 5) {
count++;
last_threadID = 0;
if(count<51){
}
}
if(successes >= 250) {
printf("Finished. Total prints: %d \\n", successes);
exit(0);
pthread_exit(0);
}
}
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
int main() {
while(1){
pthread_t threads[5];
last_threadID = 0;
successes = 0;
int rc;
int i;
int k;
while(successes != 250) {
for(i = 0; i<5; i++){
rc = pthread_create(&threads[i], 0, function, (void *)(i+1));
}
}
pthread_exit(0);
}
}
| 0
|
#include <pthread.h>
long n = 1000000000;
pthread_mutex_t mutex;
long thread_count;
double sum = 0;
void* Thread_sum(void* rank)
{
long my_rank = (long)rank;
double factor;
long my_n = n / thread_count;
long my_first_i = my_n * my_rank;
long my_last_i = my_n * (my_rank + 1) - 1;
double my_sum = 0.0;
if (my_first_i % 2 == 0)
factor = 1.0;
else
factor = -1.0;
for (long i = my_first_i; i <= my_last_i; i++, factor *= -1)
my_sum += factor / (2 * i + 1);
pthread_mutex_lock(&mutex);
sum += my_sum;
pthread_mutex_unlock(&mutex);
return 0;
}
int main(int argc, char* argv[])
{
thread_count = strtol(argv[1], 0, 10);
pthread_mutex_init(&mutex, 0);
pthread_t* thread_handles;
thread_handles = malloc(thread_count * sizeof(pthread_t));
for (long thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread],
0,
Thread_sum,
(void*)thread);
for (long thread = 0; thread < thread_count; thread++)
pthread_join(thread_handles[thread], 0);
printf("PI = %lf\\n", 4 * sum);
return 0;
}
| 1
|
#include <pthread.h>
static int cb_cnt, finished, target;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cv = PTHREAD_COND_INITIALIZER;
static void
signal_finished(void)
{
pthread_mutex_lock(&lock);
finished = 1;
pthread_cond_signal(&cv);
pthread_mutex_unlock(&lock);
}
static int
wait_for_finish(int wait)
{
struct timespec ts[1];
struct timeval tv[1];
int r = -1;
gettimeofday(tv, 0);
ts->tv_sec = tv->tv_sec + wait;
ts->tv_nsec = tv->tv_usec * 1000;
pthread_mutex_lock(&lock);
while (!finished) {
if (pthread_cond_timedwait(&cv, &lock, ts) == ETIMEDOUT) {
printf("timed out\\n");
goto done;
}
}
r = 0;
done:
finished = 0;
pthread_mutex_unlock(&lock);
return (r);
}
static void
cnt_cb(void *a)
{
int *c = a;
(*c)++;
if (*c == target) {
signal_finished();
}
}
static void
excl_cb(void *a)
{
int c = cb_cnt;
fprintf(stderr, "before sleeping: %d\\n", cb_cnt);
sleep(1);
fprintf(stderr, "after sleeping: %d\\n", cb_cnt);
if (cb_cnt != c) {
fprintf(stderr, "!=\\n");
exit(1);
}
}
static void
excl(int cnt, int tgt, int wait)
{
int i;
fprintf(stderr, "%d excl\\n", cnt);
target = tgt;
for (i = 0; i < cnt; i++) {
thrpool_req_excl(cnt_cb, &cb_cnt, 0);
}
if (!wait) {
return;
}
if (wait_for_finish(wait) < 0) {
exit(1);
}
if (cb_cnt != target) {
printf("cnt is %d, should be %d\\n", cb_cnt, target);
exit(1);
}
}
static void
norm(int cnt, int tgt, int wait)
{
int i;
fprintf(stderr, "%d norm\\n", cnt);
target = tgt;
for (i = 0; i < cnt; i++) {
thrpool_req(cnt_cb, &cb_cnt, 0, 0);
}
if (!wait) {
return;
}
if (wait_for_finish(wait) < 0) {
exit(1);
}
if (cb_cnt != target) {
printf("cnt is %d, should be %d\\n", cb_cnt, target);
exit(1);
}
}
int
main()
{
if (applog_open(L_STDERR, "test") < 0) {
exit(1);
}
applog_addlevel(log_all_on);
excl(1, 1, 1);
cb_cnt = 0;
excl(5, 5, 1);
cb_cnt = 0;
excl(1, 1, 1);
cb_cnt = 0;
sleep(1);
excl(5, 5, 1);
cb_cnt = 0;
sleep(1);
excl(1, 1, 1);
norm(10, 10, 1);
cb_cnt = 0;
excl(1, 1, 1);
cb_cnt = 0;
norm(10, 10, 1);
cb_cnt = 0;
norm(5, 5, 0);
excl(1, 6, 0);
norm(5, 11, 1);
sleep(1);
cb_cnt = 0;
fprintf(stderr, "excl is excl test\\n");
norm(3, 3, 0);
fprintf(stderr, "adding excl task 1\\n");
thrpool_req_excl(excl_cb, 0, 0);
norm(3, 6, 2);
sleep(1);
fprintf(stderr, "adding excl task 2\\n");
thrpool_req_excl(excl_cb, 0, 0);
norm(3, 9, 2);
printf("*** PASSED ***\\n");
exit(0);
}
| 0
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER;
void *thr_fn(void *arg)
{
int err, signo;
for(;;) {
err = sigwait(&mask, &signo);
if (err != 0)
err_exit(err, "sigwait failed");
switch(signo) {
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&waitloc);
return(0);
default:
printf("unexpected signal %d\\n", signo);
}
}
}
int main(void)
{
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0)
err_exit(err, "SIG_BLOCK error");
err = pthread_create(&tid, 0, thr_fn, 0);
if (err != 0)
err_exit(err, "Can't create thread");
pthread_mutex_lock(&lock);
while (quitflag == 0)
pthread_cond_wait(&waitloc, &lock);
pthread_mutex_unlock(&lock);
quitflag = 0;
if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0)
err_sys("SIG_SETMASK error");
exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
void fun(int signum)
{
printf("解锁一次......\\n");
if (pthread_mutex_unlock(&mutex) != 0)
{
printf("解锁失败...\\n");
}
}
int main(void)
{
int ret = -1;
int i = 0;
ret = pthread_mutex_init(&mutex, 0);
if (0 != ret)
{
printf("第一次初始化互斥量失败....\\n");
}
signal(SIGINT, fun);
for (i = 0; i < 5; i++)
{
if (pthread_mutex_lock(&mutex) != 0)
{
printf("第%d次加锁失败\\n", i);
}
printf("第%d次加锁.....\\n", i);
}
if (pthread_mutex_trylock(&mutex) != 0)
{
printf("尝试加锁失败...\\n");
}
pthread_mutex_unlock(&mutex);
if (0 != pthread_mutex_destroy(&mutex))
{
printf("第一次销毁互斥量失败...\\n");
}
return 0;
}
| 0
|
#include <pthread.h>
void die( const char* format, ... ) {
va_list args;
__builtin_va_start((args));
vfprintf( stderr, format, args );
fprintf( stderr, "\\n" );
;
assert( 0 );
exit( 1 );
}
void true_or_die( int is_ok, const char* format, ... ) {
if( !is_ok ) {
va_list args;
__builtin_va_start((args));
vfprintf( stderr, format, args );
fprintf( stderr, "\\n" );
;
assert( 0 );
exit( 1 );
}
}
void ip_to_string( char* buf, uint32_t ip ) {
uint8_t* bytes;
if( ip == (htonl(0xE0000005)) ) {
snprintf( buf, STRLEN_IP, "ROUTER-OSPF-IP" );
return;
}
bytes = (uint8_t*)&ip;
snprintf( buf, STRLEN_IP, "%u.%u.%u.%u",
bytes[0],
bytes[1],
bytes[2],
bytes[3] );
}
void mac_to_string( char* buf, uint8_t* mac ) {
snprintf( buf, STRLEN_MAC, "%X%X:%X%X:%X%X:%X%X:%X%X:%X%X",
mac[0] >> 4, 0x0F & mac[0],
mac[1] >> 4, 0x0F & mac[1],
mac[2] >> 4, 0x0F & mac[2],
mac[3] >> 4, 0x0F & mac[3],
mac[4] >> 4, 0x0F & mac[4],
mac[5] >> 4, 0x0F & mac[5] );
}
uint32_t ones( register uint32_t x ) {
x -= ((x >> 1) & 0x55555555);
x = (((x >> 2) & 0x33333333) + (x & 0x33333333));
x = (((x >> 4) + x) & 0x0f0f0f0f);
x += (x >> 8);
x += (x >> 16);
return( x & 0x0000003f );
}
void subnet_to_string( char* buf, uint32_t subnet, uint32_t mask ) {
unsigned num_ones;
uint8_t* bytes;
num_ones = ones(mask);
bytes = (uint8_t*)&subnet;
if( num_ones == 0 && subnet == 0 )
snprintf( buf, STRLEN_SUBNET, "<catch-all>" );
else if( num_ones <= 8 )
snprintf( buf, STRLEN_SUBNET, "%u/%u",
bytes[0], num_ones );
else if( num_ones <= 16 )
snprintf( buf, STRLEN_SUBNET, "%u.%u/%u",
bytes[0], bytes[1], num_ones );
else if( num_ones <= 24 )
snprintf( buf, STRLEN_SUBNET, "%u.%u.%u/%u",
bytes[0], bytes[1], bytes[2], num_ones );
else
snprintf( buf, STRLEN_SUBNET, "%u.%u.%u.%u/%u",
bytes[0], bytes[1], bytes[2], bytes[3], num_ones );
}
void time_to_string( char* buf, unsigned sec ) {
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
time_t t = sec;
pthread_mutex_lock( &lock );
strncpy( buf, ctime(&t), STRLEN_TIME );
pthread_mutex_unlock( &lock );
}
const char* quick_ip_to_string( uint32_t ip ) {
static char str_ip[STRLEN_IP];
ip_to_string( str_ip, ip );
return str_ip;
}
const char* quick_mac_to_string( uint8_t* mac ) {
static char str_mac[STRLEN_MAC];
mac_to_string( str_mac, mac );
return str_mac;
}
void* malloc_or_die( unsigned size ) {
void* ret;
ret = malloc( size );
true_or_die( ret!=0, "Error: malloc failed" );
return ret;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
long long *create_vector1(int);
long long *create_vector2(int);
void do_work(void);
void produto_interno(int, int);
int threads, vector_size, val;
long long prod_int, *vector_a, *vector_b;
int round_div(int dividend, int divisor) {
return (dividend + (divisor / 2)) / divisor;
}
void *fazThread(void *void_counter_ptr) {
int *i_ptr = (int *)void_counter_ptr;
int minval;
int maxval;
if(*i_ptr==threads-1) {
int rest = vector_size % threads;
minval = (*i_ptr)*val;
maxval = minval + val + rest;
} else {
minval = (*i_ptr)*val;
maxval = minval+val;
}
produto_interno(minval,maxval);
}
int main(int argc, char *argv[]) {
vector_size = atoi(argv[1]);
threads = atoi(argv[2]);
vector_a = create_vector1(vector_size);
vector_b = create_vector2(vector_size);
do_work();
val = round_div(vector_size,threads);
int i = 0;
pthread_t * thread = malloc(sizeof(pthread_t)*threads);
for (i = 0; i < threads; i++) {
if(pthread_create(&thread[i], 0, fazThread, &i)){
perror("error");
exit(1);
}
}
for (i = 0; i < threads; i++) {
if(pthread_join(thread[i], 0)){
perror("error");
exit(1);
}
}
return 0;
}
long long *create_vector1(int size) {
int i;
long long *vector;
vector = (long long *) malloc(size * sizeof(long long));
for (i = 0; i < size; i++)
vector[i] = i;
return vector;
}
long long *create_vector2(int size) {
int i;
long long *vector;
vector = (long long *) malloc(size * sizeof(long long));
for (i = 0; i < size; i++)
vector[i] = size-i-1;
return vector;
}
void do_work(void) {
prod_int = 0;
produto_interno(0, vector_size);
printf("Produto Interno = %lld\\n", prod_int);
return;
}
void produto_interno(int start, int end) {
int i;
for (i = start; i < end; i++) {
pthread_mutex_lock(&mutex);
prod_int += vector_a[i] * vector_b[i];
pthread_mutex_unlock(&mutex);
}
return;
}
| 0
|
#include <pthread.h>
pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER;
char var[20];
void* child1(void *p)
{
int k=0;
pthread_mutex_lock(&m1);
printf("\\nENTER U MESSAGE:");
gets(var);
k=strlen(var);
printf("\\nUR MESSAGE HAS BEEN SENT BY CHILD 1\\n");
pthread_mutex_unlock(&m1);
pthread_mutex_lock(&m2);
printf("\\n MESSAGE HAS BEEN RECEIVED BY CHILD 1\\n");
if(atoi(var)==k)
printf("\\nPROG WORKING WELL:NO OF CHARATERS SENT AND RECEIVED ARE SAME: %d\\n",k);
else
{
printf("\\nNO OF CHARATERS SENT BY CHILD1: %d",k);
printf("\\nNO OF CHARACTERS RECEIVED BY CHILD 2 : %d",atoi(var));
printf("\\nNo of characters sent != No of characters received!!! \\n");
}
pthread_mutex_unlock(&m2);
exit(0);
}
void* child2(void *p)
{
pthread_mutex_lock(&m2);
pthread_mutex_lock(&m1);
printf("\\nMESSAGE RECEIVED BY CHILD 2\\n");
sprintf(var,"%d",(int)strlen(var));
printf("\\nMESSAGE SENT BY CHILD 2\\n");
pthread_mutex_unlock(&m1);
pthread_mutex_unlock(&m2);
}
int main()
{
pthread_t p1, p2;
int ir1 = pthread_create(&p1, 0, child1, 0);
wait(1);
int ir2 = pthread_create(&p2, 0, child2, 0);
while(1){}
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_read = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_write = PTHREAD_COND_INITIALIZER;
bool done = 0;
int reading_to = 1;
int writing_from = 1;
char buffer_1[16*1024*1024];
char buffer_2[16*1024*1024];
int buffer_1_dat = 0;
int buffer_2_dat = 0;
void *read_to_buff(void *data){
int readed;
while(1){
pthread_mutex_lock(&lock);
switch (reading_to){
case 1 :{
while (buffer_1_dat > 0 ) {
pthread_cond_wait(&cond_read, &lock);
}
readed = read(0, buffer_1 , 16*1024*1024);
buffer_1_dat +=readed;
reading_to = 2;
if (readed == 0){
done = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond_write);
pthread_exit(0);
}
pthread_cond_signal(&cond_write);
break;
}
case 2 : {
while (buffer_2_dat > 0 ){
pthread_cond_wait(&cond_read, &lock);
}
readed = read(0,buffer_2,16*1024*1024);
buffer_2_dat +=readed;
reading_to = 1;
if (readed == 0){
done = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond_write);
pthread_exit(0);
}
pthread_cond_signal(&cond_write);
break;
}
}
pthread_mutex_unlock(&lock);
if (readed== -1 ){
printf("Error reading\\n" );
}
}
}
void *print_from_buff(void *data){
int wrote;
int add;
while(1){
pthread_mutex_lock(&lock);
switch (writing_from){
case 1:{
while ( buffer_1_dat == 0 && done == 0){
pthread_cond_wait(&cond_write, &lock);
}
wrote = write(1, buffer_1, buffer_1_dat);
if (wrote == -1){ printf("Error printing\\n" ); }
while (buffer_1_dat != wrote){
add= write(1, &buffer_1[wrote], buffer_1_dat-wrote);
if (add== -1){ printf("Error printing\\n" ); break; }
wrote+=add;
}
buffer_1_dat = 0;
writing_from = 2;
pthread_cond_signal(&cond_read);
break;
}
case 2:{
while( buffer_2_dat == 0 && done == 0){
pthread_cond_wait(&cond_write, &lock);
}
wrote = write(1, buffer_2, buffer_2_dat);
if (wrote == -1){ printf("Error printing\\n" ); }
while (buffer_2_dat != wrote){
add = write(1, &buffer_2[wrote], buffer_2_dat-wrote);
if (add == -1){ printf("Error printing\\n" ); break;}
wrote+=add;
}
buffer_2_dat = 0;
writing_from = 1;
pthread_cond_signal(&cond_read);
break;
}
}
if (done == 1){
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
pthread_mutex_unlock(&lock);
if (wrote == -1 ){
printf("Error printing \\n" );
}
}
}
int main(int argc, char** argv) {
pthread_mutex_init(&lock, 0);
pthread_t reader;
pthread_t printer;
int create_read_stat = pthread_create(&reader, 0, read_to_buff, 0);
if (create_read_stat != 0) {
printf("Error creating reading thread, error code: %d \\n",create_read_stat );
}
int create_printer_stat = pthread_create(&printer, 0, print_from_buff, 0);
if (create_printer_stat != 0) {
printf("Error creating printing thread, error code: %d \\n",create_printer_stat );
}
int end_status_reader = pthread_join(reader, 0);
if (end_status_reader != 0) {
printf("Reader error, error code: %d \\n",end_status_reader );
}
int end_status_printer = pthread_join(printer, 0);
if (end_status_printer != 0) {
printf("Printer error, error code: %d \\n",end_status_printer );
}
int mutex_status = pthread_mutex_destroy( &lock);
if (mutex_status != 0) {
printf("Mutex not destroyed, error code: %d \\n",mutex_status );
}
return 0;
}
| 0
|
#include <pthread.h>
int thread_flag,ret;
pthread_cond_t flag1,flag2;
pthread_mutex_t mut,mutx;
pthread_t print_wait;
void initialize_flag ()
{
pthread_mutex_init (&mut, 0);
pthread_cond_init (&flag1, 0);
pthread_mutex_init (&mutx, 0);
pthread_cond_init (&flag2, 0);
thread_flag = 0;
}
void* thread_2_fun(void* arg)
{
while(1)
{
printf("\\nThe Thread Ended the Command with the return :%d\\n",ret);
pthread_cond_wait(&flag2,&mutx);
}return 0;
}
void* print_dot(void* arg)
{
while(1)printf(".");
return 0;
}
void* thread_function(void* arg)
{
char* value = (char*)arg;
while(1)
{
pthread_mutex_lock(&mut);
while(!thread_flag)
{
pthread_cond_wait(&flag1,&mut);
pthread_mutex_unlock(&mut);
ret = system(value);
pthread_cancel(print_wait);
printf("i canceled th print_wait thrad now.\\n");
pthread_cond_signal(&flag2);
}
return 0;
}
}
int main()
{
printf("Hello world!\\n");
pthread_t thread1,thread2;
initialize_flag();
printf("I am going to get the output of command :ls -l \\n");
pthread_create(&print_wait,0,&print_dot,0);
pthread_create(&thread2,0,&thread_2_fun,0);
pthread_create(&thread1,0,&thread_function,(void*)"ls -l");
pthread_join(thread1,0);
pthread_join(thread2,0);
return 0;
}
| 1
|
#include <pthread.h>
struct list_node_s
{
int data;
struct list_node_s* next;
};
int Member(int value);
int Insert(int value);
int Delete(int value);
void extractArgs(int argc,char* argv[]);
void populatelinkedlist();
void initializearray();
void shufflearray();
void* doOperations(void* id);
struct list_node_s* head_p;
int n=0;
int m=0;
double percMember=0;
double percInsert=0;
double percDelete=0;
int m_member=0;
int m_insert=0;
int m_delete=0;
int* op_array;
int sample_size=150;
double mean=0;
double std_deviation;
pthread_mutex_t mutex;
int th_count;
volatile int th_completed=0;
int main(int argc, char* argv[])
{
double array_timetaken[sample_size];
double total_time=0,std_error=0;
extractArgs(argc,argv);
int arr[m];
op_array=arr;
initializearray();
for(int i=0;i<sample_size;i++){
double start,end,time_taken;
long th_id;
pthread_t* thread_handles;
populatelinkedlist();
shufflearray();
thread_handles = (pthread_t*) malloc (th_count*sizeof(pthread_t));
pthread_mutex_init(&mutex, 0);
start=clock();
for (th_id = 0; th_id < th_count; th_id++)
{
pthread_create(&thread_handles[th_id], 0, doOperations , (void*)th_id);
}
for (th_id = 0; th_id < th_count; th_id++)
{
pthread_join(thread_handles[th_id], 0);
}
pthread_mutex_destroy(&mutex);
end=clock();
time_taken=(end-start)/CLOCKS_PER_SEC;
array_timetaken[i]=time_taken;
total_time+=time_taken;
head_p=0;
}
mean= total_time/sample_size;
for(int i=0;i<sample_size;i++){
std_error+=pow(array_timetaken[i] - mean, 2);
}
std_deviation=sqrt(std_error/sample_size);
printf("Mean :%.5f\\nStd deviation:%.5f\\n",mean,std_deviation);
}
void extractArgs(int argc,char* argv[])
{
if(argc ==7)
{
n=atoi(argv[1]);
m=atoi(argv[2]);
percMember=atof(argv[3]);
percInsert=atof(argv[4]);
percDelete=atof(argv[5]);
th_count= atoi(argv[6]);
if(percInsert+percMember+percDelete != 1.0){
printf("Please check percentages again\\n");
exit(0);
}else if(n<0 || m<0){
printf("Please check n and m values again\\n");
exit(0);
}
}else{
printf("%s","Please insert arguments in order <numberOfNodes> <numberOfOperations> <percentageOfMember> <percentageOfInsert> <percentageOfDelete>\\n");
exit(0);
}
m_member= m * percMember;
m_insert=m*percInsert;
m_delete=m*percDelete;
}
void populatelinkedlist(){
for(int i=0;i<n;i++){
int r=rand()%65536;
int result=Insert(r);
if(!result){
i--;
}
}
}
void initializearray(){
int i=0;
for(;i<m_delete;i++)
op_array[i]=1;
for(;i<m_delete+m_insert;i++)
op_array[i]=2;
for(;i<m;i++)
op_array[i]=3;
}
void shufflearray(){
int i=0;
for (i = 0; i <m-2; i++) {
int j=rand()%m;
while(j<i){
j=rand()%m;
}
int tmp = op_array[j];
op_array[j] = op_array[i];
op_array[i] = tmp;
}
}
void* doOperations(void* id){
pthread_mutex_lock(&mutex);
while(th_completed<m){
int i=th_completed;
printf("%ld thread:%i\\n",(long)id,th_completed);
th_completed++;
if(op_array[i]==1){
Delete(rand()%65536);
}else if(op_array[i]==2){
int res=Insert(rand()%65536);
while(!res){
res=Insert(rand()%65536);
}
}else if(op_array[i]==3){
Member(rand()%65536);
}
}
pthread_mutex_unlock(&mutex);
}
int Member(int value)
{
struct list_node_s* curr_p =head_p;
while(curr_p != 0 && curr_p ->data <value)
curr_p= curr_p ->next;
if(curr_p == 0 || curr_p -> data > value){
return 0;
}else{
return 1;
}
}
int Insert(int value)
{
struct list_node_s* curr_p = *&head_p;
struct list_node_s* pred_p = 0;
struct list_node_s* temp_p = 0;
while(curr_p != 0 && curr_p -> data <value){
pred_p =curr_p;
curr_p =curr_p ->next;
}
if(curr_p == 0 || curr_p ->data >value){
temp_p = malloc(sizeof( struct list_node_s));
temp_p -> data =value;
temp_p ->next = curr_p;
if(pred_p == 0)
head_p= temp_p;
else
pred_p -> next =temp_p;
return 1;
}else{
return 0;
}
}
int Delete(int value)
{
struct list_node_s* curr_p =*&head_p;
struct list_node_s* pred_p = 0;
while(curr_p != 0 && curr_p -> data <value){
pred_p =curr_p;
curr_p =curr_p ->next;
}
if(curr_p != 0 && curr_p -> data == value){
if(pred_p == 0){
*&head_p=curr_p->next;
free(curr_p);
}else{
pred_p->next =curr_p->next;
free(curr_p);
}
return 1;
}else{
return 0;
}
}
| 0
|
#include <pthread.h>
struct foo {
int f_count;
pthread_mutex_t f_lock;
};
struct foo *
foo_alloc(void)
{
struct foo *fp;
if ((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 1;
if (pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return 0;
}
}
return fp;
}
void
foo_hold(struct foo *fp)
{
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
void foo_rele(struct foo *fp)
{
pthread_mutex_lock(&fp->f_lock);
if (--fp->f_count == 0) {
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
} else {
pthread_mutex_unlock(&fp->f_lock);
}
}
| 1
|
#include <pthread.h>
void create_threads(int records_num);
void *start_thread(void *records_num) ;
void join_threads();
int find_text(char *text);
void cancel_threads_async();
int read_data(int records_num) ;
void destructor(void *data) ;
int read_records(char **data) ;
int id;
char text[RECORD_SIZE - sizeof(int)];
} record_str;
pthread_t **threads;
pthread_key_t record_buffer_data_key;
int threads_num;
int records_num;
int fd;
char *text_key;
pthread_mutex_t file_mutex = PTHREAD_MUTEX_INITIALIZER;
int main(int argc, char *argv[]) {
threads_num = parseUnsignedIntArg(argc, argv, 1, "number of threads");
char *filename = parseTextArg(argc, argv, 2, "file name");
records_num = parseUnsignedIntArg(argc, argv, 3, "number of records");
text_key = parseTextArg(argc, argv, 4, "text key to find");
fd = open_file(filename);
pthread_key_create(&record_buffer_data_key, destructor);
create_threads(records_num);
join_threads();
pthread_mutex_destroy(&file_mutex);
pthread_key_delete(record_buffer_data_key);
close(fd);
return 0;
}
void destructor(void *data) {
char **records = (char **) data;
for (int i = 0; i < records_num && records[i] != 0; ++i) {
free(records[i]);
}
free(data);
}
void create_threads(int records_num) {
threads = calloc((size_t) threads_num, sizeof(*threads));
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (int i = 0; i < threads_num; ++i) {
pthread_t *thread = malloc(sizeof(*thread));
int *records = calloc(1, sizeof(*records));
*records = records_num;
int error_num;
if ((error_num = pthread_create(thread, &attr, start_thread, records)) != 0) {
fprintf(stderr, "Error creating thread: %s\\n", strerror(error_num));
exit(1);
}
threads[i] = thread;
}
pthread_attr_destroy(&attr);
}
void join_threads() {
for (int i = 0; i < threads_num; ++i) {
void *ret;
int error_num;
if ((error_num = pthread_join(*threads[i], &ret)) != 0) {
fprintf(stderr, "Error joining thread: %s\\n", strerror(error_num));
exit(1);
}
}
}
void *start_thread(void *records_num) {
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
int read_records;
while ((read_records = read_data(*(int *) records_num)) != 0) {
char **data = pthread_getspecific(record_buffer_data_key);
for (int i = 0; i < read_records; ++i) {
record_str *record = (record_str *) data[i];
if (find_text(record->text) == 1) {
printf("Key found in record %d by thread with id %ld\\n", record->id, get_thread_id());
pthread_mutex_lock(&file_mutex);
cancel_threads_async();
pthread_mutex_unlock(&file_mutex);
pthread_exit((void *) 0);
}
}
}
return (void *) 0;
}
int read_data(int records_num) {
char **data = pthread_getspecific(record_buffer_data_key);
if (data == 0) {
data = calloc((size_t) records_num, sizeof(*data));
pthread_setspecific(record_buffer_data_key, data);
}
pthread_mutex_lock(&file_mutex);
int records = read_records(data);
pthread_mutex_unlock(&file_mutex);
return records;
}
int read_records(char **data) {
ssize_t read_result;
int record_num = 0;
for (record_num = 0; record_num < records_num; ++record_num) {
data[record_num] = calloc(RECORD_SIZE, sizeof(*data[record_num]));
if ((read_result = read(fd, data[record_num], RECORD_SIZE * sizeof(*data[record_num]))) == -1) {
fprintf(stderr, "Error while reading from file in thread %ld\\n", get_thread_id());
pthread_mutex_unlock(&file_mutex);
pthread_exit((void *) 1);
}
if (read_result == 0) {
break;
}
}
return record_num;
}
void cancel_threads_async() {
for (int i = 0; i < threads_num; ++i) {
if (threads[i] != 0 && pthread_equal(*threads[i], pthread_self()) == 0) {
pthread_cancel(*threads[i]);
}
}
}
int find_text(char *text) {
size_t key_len = strlen(text_key);
int record_len = RECORD_SIZE - sizeof(int);
int key_index;
for (int i = 0; i < record_len; ++i) {
for (key_index = 0; key_index < key_len && i + key_index < record_len; ++key_index) {
if (text[i + key_index] != text_key[key_index]) {
break;
}
}
if (key_index == key_len) {
return 1;
}
}
return 0;
}
| 0
|
#include <pthread.h>
struct input {
int num;
int cT;
};
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int curThread = 0;
int timecount = 0;
void *createThread(void *input) {
struct input *in = input;
int actual = in->cT;
printf("Hello from thread No. %d!\\n", actual);
int tcount = 0;
timecount += in->num;
pthread_t p1, p2;
sleep(in->num);
while(tcount < 2) {
pthread_mutex_lock(&mutex);
if(curThread < 10) {
curThread++;
if (tcount == 0){
struct input first;
first.num = (int) rand()%10;
first.cT = curThread;
pthread_create(&p1, 0, createThread, &first);
}
else {
struct input sec;
sec.num = (int) rand()%10;
sec.cT = curThread;
pthread_create(&p2, 0, createThread, &sec);
}
}
pthread_mutex_unlock(&mutex);
tcount++;
}
pthread_join(p1, 0);
pthread_join(p2, 0);
printf("Bye from thread No. %d!\\n", actual);
}
int main() {
struct input start;
start.num = 3;
start.cT = curThread;
createThread(&start);
printf("Die Threads haben zusammen %d Sekunden gewartet.\\n", timecount);
}
| 1
|
#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()
{
pthread_t tid1,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(5);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mux;
unsigned int counter;
void * thread_code(void *arg){
unsigned int start;
unsigned int end;
unsigned int priv_count = 0;
int thread_indx =(int) arg;
if (thread_indx == 0){
start = 0;
}else{
start = 4294967295U/4 * thread_indx +1;
}
if (thread_indx == 4 -1){
end = 4294967295U;
}else{
end = 4294967295U/4 * (thread_indx +1) ;
}
printf("thread %d \\t start (%u) \\t end %u \\t thread_id %ul\\n", thread_indx, start, end, pthread_self());
for (unsigned int i = start; i < end; i++){
pthread_mutex_lock(&mux);
counter ++;
pthread_mutex_unlock(&mux);
}
printf("thread end %ul %u\\n", pthread_self(), priv_count);
}
void error_and_die(const char *msg) {
perror(msg);
exit(1);
}
int main(){
counter = 0;
pthread_t thread_id[20];
if(0 != pthread_mutex_init(&mux, 0)){
printf("mutex creation error\\n");
exit(-1);
}
for (int i = 0 ; i < 4; i++){
pthread_create(&thread_id[i],
0,
thread_code,
(void *) i);
}
for (int i = 0; i < 4; i++){
pthread_join(thread_id[i], 0);
}
printf("resultado %u\\n", counter);
pthread_mutex_destroy(&mux);
}
| 1
|
#include <pthread.h>
char name[2];
int data;
pthread_t thread;
pthread_mutex_t lock;
pthread_cond_t cond;
long int waits;
} PROC;
void _exec_and_wait(void* args) {
static struct timespec time_to_wait = {0, 0};
PROC *proc = (PROC*) args;
while(proc->data < 10) {
time_to_wait.tv_sec = time(0) + proc->waits;
pthread_mutex_lock(&proc->lock);
pthread_cond_timedwait(&proc->cond, &proc->lock, &time_to_wait);
proc->data++;
printf("increase proc[%s] data to [%d]\\n", proc->name, proc->data);
pthread_mutex_unlock(&proc->lock);
}
}
int _init_proc(PROC *proc, void *(*routine) (void *)) {
pthread_attr_t attr;
printf("try to init proc [%s]\\n", proc->name);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_mutex_init(&proc->lock, 0);
pthread_cond_init(&proc->cond, 0);
pthread_create(&proc->thread, &attr, routine, (void*) proc);
pthread_attr_destroy(&attr);
return 1;
}
int main(int argc, char** argv)
{
int result_a = 0, result_b = 0;
PROC proc_a, proc_b;
strcpy(proc_a.name, "A\\0");
proc_a.data = 0;
proc_a.waits = 2L;
strcpy(proc_b.name, "B\\0");
proc_b.data = 0;
proc_b.waits = 1L;
if (!_init_proc(&proc_a, _exec_and_wait))
printf("Fail to init proc [%s]\\n", proc_a.name);
if (!_init_proc(&proc_b, _exec_and_wait))
printf("Fail to init proc [%s]\\n", proc_b.name);
pthread_join(proc_a.thread, (void*) &result_a);
pthread_join(proc_b.thread, (void*) &result_b);
return (0);
}
| 0
|
#include <pthread.h>
int q[4];
int qsiz;
pthread_mutex_t mq;
void queue_init ()
{
pthread_mutex_init (&mq, 0);
qsiz = 0;
}
void queue_insert (int x)
{
int done = 0;
printf ("prod: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz < 4)
{
done = 1;
q[qsiz] = x;
qsiz++;
}
pthread_mutex_unlock (&mq);
}
}
int queue_extract ()
{
int done = 0;
int x = -1, i = 0;
printf ("consumer: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz > 0)
{
done = 1;
x = q[0];
qsiz--;
for (i = 0; i < qsiz; i++) q[i] = q[i+1];
__VERIFIER_assert (qsiz < 4);
q[qsiz] = 0;
}
pthread_mutex_unlock (&mq);
}
return x;
}
void swap (int *t, int i, int j)
{
int aux;
aux = t[i];
t[i] = t[j];
t[j] = aux;
}
int findmaxidx (int *t, int count)
{
int i, mx;
mx = 0;
for (i = 1; i < count; i++)
{
if (t[i] > t[mx]) mx = i;
}
__VERIFIER_assert (mx >= 0);
__VERIFIER_assert (mx < count);
t[mx] = -t[mx];
return mx;
}
int source[5];
int sorted[5];
void producer ()
{
int i, idx;
for (i = 0; i < 5; i++)
{
idx = findmaxidx (source, 5);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 5);
queue_insert (idx);
}
}
void consumer ()
{
int i, idx;
for (i = 0; i < 5; i++)
{
idx = queue_extract ();
sorted[i] = idx;
printf ("m: i %d sorted = %d\\n", i, sorted[i]);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 5);
}
}
void *thread (void * arg)
{
(void) arg;
producer ();
return 0;
}
int main ()
{
pthread_t t;
int i;
__libc_init_poet ();
for (i = 0; i < 5; i++)
{
source[i] = __VERIFIER_nondet_int(0,20);
printf ("m: init i %d source = %d\\n", i, source[i]);
__VERIFIER_assert (source[i] >= 0);
}
queue_init ();
pthread_create (&t, 0, thread, 0);
consumer ();
pthread_join (t, 0);
return 0;
}
| 1
|
#include <pthread.h>
unsigned int generate_CRC32(unsigned char * data_buf, unsigned int len, unsigned int oldcrc32)
{
unsigned int t;
while (len > 0) {
t = (oldcrc32 ^ *data_buf) & 0xff;
oldcrc32 = (oldcrc32 >> 8) ^ crc_32_file_tab[t];
len--;
data_buf++;
}
return oldcrc32;
}
unsigned int basedata_crc(const char *basedata_path)
{
FILE *fp = 0;
int fread_num = 0;
char buf[120];
unsigned int oldcrc32 = 0;
fp = fopen(basedata_path, "r");
if (fp == 0) {
perror("fopen");
return 0;
}
fread_num = fread(buf, 1, 4, fp);
if (fread_num < 4) {
return 0;
}
while (1) {
fread_num = fread(buf, 1, 100, fp);
if (fread_num <= 0)
return oldcrc32;
else
oldcrc32 = generate_CRC32(buf, fread_num, oldcrc32);
}
}
unsigned int get_file_crc(const char *basedata_path)
{
FILE *fp = 0;
int fread_num = 0;
char buf[10];
unsigned int oldcrc32 = 0;
fp = fopen(basedata_path, "r");
if (fp == 0) {
perror("fopen");
return 0xffffffff;;
}
fread_num = fread(buf, 1, 4, fp);
if (fread_num < 4) {
return 0xffffffff;
} else {
oldcrc32 = (unsigned int)buf[0] | (unsigned int)buf[1] << 8 | (unsigned int)buf[2] << 16 | (unsigned int)buf[3] << 24;
return oldcrc32;
}
}
int check_file(void)
{
unsigned int file_crc = 0;
unsigned int base_crc = 0;
base_crc = basedata_crc("/sbin/route_data/basedata.dat");
file_crc = get_file_crc("/sbin/route_data/basedata.dat");
opt_log_info("basedata crc %x, file crc %x\\n", base_crc, file_crc);
return (base_crc == file_crc) ? 1 : -1;
}
static int get_base_data_version_local ()
{
FILE *fp;
char buf[16] = {0};
int tempt;
fp = fopen("/sbin/route_data/basedata.dat", "r");
if (fp == 0) {
return -1;
}
fread(buf, sizeof(char), 16, fp);
fclose(fp);
tempt = (((int)buf[15]) << 24) |
((((int)buf[14]) << 16) & 0x00ff0000) |
((((int)buf[13]) << 8) & 0x00ff00) |
(((int)buf[12]) & 0x00ff);
pthread_mutex_lock(&bd_version_local_s.mutex_s_bdvl);
bd_version_local_s.bd_version_local = tempt;
pthread_mutex_unlock(&bd_version_local_s.mutex_s_bdvl);
}
| 0
|
#include <pthread.h>
struct list_node_s{
int data;
struct list_node_s* next;
};
int Member(int value, struct list_node_s* head_p){
struct list_node_s* curr_p = head_p;
while(curr_p != 0 && curr_p->data < value)
curr_p = curr_p->next;
if(curr_p == 0 || curr_p->data > value)
return 0;
else
return 1;
}
int Insert(int value, struct list_node_s** head_p){
struct list_node_s* curr_p = *head_p;
struct list_node_s* pred_p = 0;
struct list_node_s* temp_p;
while(curr_p != 0 && curr_p->data < value){
pred_p = curr_p;
curr_p = curr_p->next;
}
if(curr_p == 0 || curr_p->data > value){
temp_p = malloc(sizeof(struct list_node_s));
temp_p->data = value;
temp_p->next = curr_p;
if(pred_p == 0)
*head_p = temp_p;
else pred_p->next = temp_p;
return 1;
}
else return 0;
}
int Delete(int value, struct list_node_s** head_p){
struct list_node_s* curr_p = *head_p;
struct list_node_s* pred_p = 0;
while(curr_p != 0 && curr_p->data < value){
pred_p = curr_p;
curr_p = curr_p->next;
}
if(curr_p != 0 && curr_p->data == value){
if(pred_p == 0){
*head_p = curr_p->next;
free(curr_p);
}
else{
pred_p->next = curr_p->next;
free(curr_p);
}
return 1;
}
else
return 0;
}
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct list_node_s* list;
void* Tabla(void* rank){
long my_rank = (long) rank;
int i;
srand(time(0));
for(i = 0; i < 80000; i++) {
pthread_mutex_lock(&mutex);
Insert(rand()%100,&list);
pthread_mutex_unlock(&mutex);
}
for(i = 0; i < 10000; i++) {
pthread_mutex_lock(&mutex);
Member(rand()%100,list);
pthread_mutex_unlock(&mutex);
}
for(i = 0; i < 10000; i++) {
pthread_mutex_lock(&mutex);
Delete(rand()%100,&list);
pthread_mutex_unlock(&mutex);
}
return 0;
}
int main(int argc, char* argv[]){
long thread;
double thread_count;
pthread_t *thread_handles;
clock_t time;
struct list_node_s* list = 0;
pthread_rwlock_init(&mutex,0);
thread_count = strtol(argv[1],0,10);
thread_handles = malloc(thread_count* sizeof(pthread_t));
time = clock();
for(thread=0;thread<thread_count;thread++)
pthread_create(&thread_handles[thread],0,
Tabla,(void*)thread);
for(thread=0;thread<thread_count;thread++)
pthread_join(thread_handles[thread],0);
time = clock() - time;
printf("Tiempo:%lf\\n", (((float)time)/CLOCKS_PER_SEC));
return 0;
}
| 1
|
#include <pthread.h>
static int terminate_env_thread = 0;
static void env_thread_finish(struct ezcfg_socket_agent *agent)
{
pthread_mutex_lock(&(agent->env_thread_mutex));
pthread_mutex_lock(&(agent->sub_agent_thread_list_mutex));
if (agent->sub_agent_thread_list != 0) {
ezcfg_linked_list_del(agent->sub_agent_thread_list);
agent->sub_agent_thread_list = 0;
}
pthread_mutex_unlock(&(agent->sub_agent_thread_list_mutex));
agent->env_thread_stop = 1;
pthread_mutex_unlock(&(agent->env_thread_mutex));
}
static void sigusr1_handler(int sig, siginfo_t *si, void *unused)
{
EZDBG("Got SIGUSR1 at address: 0x%lx\\n", (long) si->si_addr);
EZDBG("Got SIGUSR1 from pid: %d\\n", (int)si->si_pid);
EZDBG("Got SIGUSR1 si_signo: %d\\n", (int)si->si_signo);
EZDBG("Got SIGUSR1 si_code: %d\\n", (int)si->si_code);
EZDBG("Got SIGUSR1 si_status: %d\\n", (int)si->si_status);
terminate_env_thread = 1;
}
void *local_socket_agent_env_thread_routine(void *arg)
{
struct ezcfg *ezcfg = 0;
struct ezcfg_socket_agent *agent = 0;
struct ezcfg_thread *env_thread = 0;
struct timespec req;
struct timespec rem;
struct sigaction sa;
sigset_t set;
int ret;
ASSERT(arg != 0);
agent = (struct ezcfg_socket_agent *)arg;
ezcfg = agent->ezcfg;
ASSERT(agent->env_thread != 0);
env_thread = agent->env_thread;
sa.sa_flags = SA_SIGINFO;
sigemptyset(&sa.sa_mask);
sa.sa_sigaction = sigusr1_handler;
if (sigaction(SIGUSR1, &sa, 0) == -1) {
EZDBG("%s(%d)\\n", __func__, 110);
err(ezcfg, "sigaction(USR1).");
return arg;
}
sigfillset(&set);
sigdelset(&set, SIGUSR1);
ret = pthread_sigmask(SIG_SETMASK, &set, 0);
if (ret != 0) {
EZDBG("%s(%d) errno=[%d]\\n", __func__, 120, errno);
return arg;
}
while (ezcfg_thread_state_is_running(env_thread) == EZCFG_RET_OK) {
EZDBG("%s(%d)\\n", __func__, 125);
req.tv_sec = EZCFG_AGENT_ENVIRONMENT_WAIT_TIME;
req.tv_nsec = 0;
if (nanosleep(&req, &rem) == -1) {
EZDBG("%s(%d) errno=[%d]\\n", __func__, 129, errno);
EZDBG("%s(%d) rem.tv_sec=[%ld]\\n", __func__, 130, (long)rem.tv_sec);
EZDBG("%s(%d) rem.tv_nsec=[%ld]\\n", __func__, 131, rem.tv_nsec);
}
EZDBG("%s(%d)\\n", __func__, 133);
}
env_thread_finish(agent);
return arg;
}
int local_socket_agent_env_thread_arg_del(void *arg)
{
return EZCFG_RET_OK;
}
int local_socket_agent_env_thread_stop(void *arg)
{
struct ezcfg_socket_agent *agent = 0;
struct ezcfg_thread *env_thread = 0;
struct timespec req;
struct timespec rem;
ASSERT(arg != 0);
EZDBG("%s(%d)\\n", __func__, 162);
agent = (struct ezcfg_socket_agent *)arg;
env_thread = agent->env_thread;
EZDBG("%s(%d)\\n", __func__, 166);
while (agent->env_thread_stop == 0) {
EZDBG("%s(%d)\\n", __func__, 168);
req.tv_sec = EZCFG_AGENT_ENVIRONMENT_WAIT_TIME;
req.tv_nsec = 0;
if (nanosleep(&req, &rem) == -1) {
EZDBG("%s(%d) errno=[%d]\\n", __func__, 172, errno);
EZDBG("%s(%d) rem.tv_sec=[%ld]\\n", __func__, 173, (long)rem.tv_sec);
EZDBG("%s(%d) rem.tv_nsec=[%ld]\\n", __func__, 174, rem.tv_nsec);
}
EZDBG("%s(%d)\\n", __func__, 176);
}
EZDBG("%s(%d)\\n", __func__, 179);
ezcfg_thread_set_arg(env_thread, 0);
EZDBG("%s(%d)\\n", __func__, 184);
return EZCFG_RET_OK;
}
| 0
|
#include <pthread.h>
static int n = 0;
void* controller_thread(void *arg) {
fprintf(stderr, "Controller thread %u start.\\n", (unsigned int)pthread_self());
pthread_mutex_lock(&q_mutex);
while(1) {
fprintf(stderr, "Controller: check queue.\\n");
struct queue *p = q_head, *prev_q = q_head;
bool new_thread = 0;
while(p != 0) {
static struct queue tmp_q;
bool delete = 0;
memcpy(&tmp_q, p, sizeof(struct queue));
pthread_mutex_unlock(&q_mutex);
pthread_mutex_lock(&t_mutex);
struct threads *q = t_head, *prev_t;
while(q != 0) {
if(memcmp(&q->addr, &tmp_q.addr, sizeof(struct tuple4))==0)
break;
prev_t = q;
q = q->next;
}
if(q == 0 && tmp_q.inout < 2) {
new_thread = 1;
q = (struct threads *) malloc(sizeof(struct threads));
if(q == 0) {
fprintf(stderr, "Controller: Cannot alloc queue item\\n");
exit(1);
}
if(t_head==0)
t_head = q;
else
prev_t->next = q;
memset(q, 0, sizeof(struct threads));
q->addr = tmp_q.addr;
sprintf((char *)&q->conn.tmp_name, "%d", n++);
pthread_mutex_init(&q->mutex, 0);
pthread_mutex_init(&q->wait_mutex, 0);
pthread_cond_init(&q->cond, 0);
q->inout = tmp_q.inout;
memcpy(q->data, &tmp_q.data, tmp_q.data_length);
q->data_length = tmp_q.data_length;
q->consumed = 0;
if(pthread_create((pthread_t *)&q->tid, 0, process_thread, q)!=0) {
fprintf(stderr, "Controller: Cannot create thread\\n");
exit(1);
}
delete = 1;
fprintf(stderr, "Controller: Thread %u is ok.\\n", (unsigned int)q->tid);
}
pthread_mutex_unlock(&t_mutex);
if(q != 0 && !new_thread){
if(pthread_mutex_trylock(&q->mutex)==0) {
if(q->consumed) {
fprintf(stderr, "Controller: Thread %u locked. Give it data.\\n", (unsigned int)q->tid);
q->inout = tmp_q.inout;
memcpy(q->data, &tmp_q.data, tmp_q.data_length);
q->data_length = tmp_q.data_length;
q->consumed = 0;
pthread_cond_signal(&q->cond);
pthread_mutex_unlock(&q->mutex);
fprintf(stderr, "Controller: Thread %u unlocked. It should wake.\\n", (unsigned int)q->tid);
delete = 1;
} else {
fprintf(stderr, "Controller: Thread %u hasn't consumed data. Wait it.\\n", (unsigned int)q->tid);
pthread_mutex_unlock(&q->mutex);
}
} else {
fprintf(stderr, "Controller: Cannot lock thread %u, may be busy.\\n", (unsigned int)q->tid);
}
}
if(q==0 && tmp_q.inout >=2) {
fprintf(stderr, "Controller: Ignore closing connection without thread.\\n");
delete = 1;
}
pthread_mutex_lock(&q_mutex);
if(delete) {
if(p == q_head) {
q_head = q_head->next;
free(prev_q);
prev_q = q_head;
}
else {
prev_q->next = p->next;
free(p);
p = prev_q;
}
if (q_head==0)
q_tail = 0;
}
p = p->next;
}
if (q_head==0) {
pthread_mutex_lock(&ctrl_mutex);
if(ctrl_exit)
break;
pthread_mutex_unlock(&ctrl_mutex);
pthread_cond_wait(&ctrl_cond, &q_mutex);
}
}
pthread_mutex_unlock(&q_mutex);
pthread_mutex_unlock(&ctrl_mutex);
fprintf(stderr, "Controller thread %u exit\\n", (unsigned int)pthread_self());
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t flaglock;
pthread_cond_t mycond;
int flag = 1;
void *hello(void *p)
{
while(1)
{
pthread_mutex_lock(&flaglock);
while(1 != flag)
{
pthread_cond_wait(&mycond, &flaglock);
}
pthread_mutex_unlock(&flaglock);
printf("hello\\n");
pthread_mutex_lock(&flaglock);
flag = 2;
pthread_mutex_unlock(&flaglock);
pthread_cond_broadcast(&mycond);
}
}
void *the(void *p)
{
while(1)
{
pthread_mutex_lock(&flaglock);
while(2 != flag)
{
pthread_cond_wait(&mycond, &flaglock);
}
pthread_mutex_unlock(&flaglock);
printf("the\\n");
pthread_mutex_lock(&flaglock);
flag = 3;
pthread_mutex_unlock(&flaglock);
pthread_cond_broadcast(&mycond);
}
}
void *word(void *p)
{
while(1)
{
pthread_mutex_lock(&flaglock);
while(3 != flag)
{
pthread_cond_wait(&mycond, &flaglock);
}
pthread_mutex_unlock(&flaglock);
printf("word\\n");
pthread_mutex_lock(&flaglock);
flag = 1;
pthread_mutex_unlock(&flaglock);
pthread_cond_broadcast(&mycond);
}
}
int main()
{
pthread_mutex_init(&flaglock, 0);
pthread_cond_init(&mycond, 0);
pthread_t t1, t2, t3;
pthread_create(&t1, 0, hello, 0);
pthread_create(&t2, 0, word, 0);
pthread_create(&t3, 0, the, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_join(t3, 0);
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.