text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
volatile long work_counter;
int req_count;
pthread_mutex_t q_lock;
void grab_lock() {
pthread_mutex_lock(&q_lock);
}
void ungrab_lock() {
pthread_mutex_unlock(&q_lock);
}
void do_work() {
for (int i = 0; i < 50000; ++i)
++work_counter;
}
void * request_processor(void *dummy) {
printf("[*] Request processor initialized.\\n");
while (1) {
grab_lock();
do_work();
ungrab_lock();
}
return 0;
}
void flush_work() {
usleep(10000);
}
void * backend_handler(void *dummy) {
printf("[*] Backend handler initialized.\\n");
while (1) {
grab_lock();
++req_count;
if (req_count % 1000 == 0) {
printf("[-] Handled %d requests.\\n", req_count);
}
if (req_count % 37 == 0) {
flush_work();
}
ungrab_lock();
}
return 0;
}
int main() {
pthread_t req_processors[2];
pthread_t backend;
pthread_mutex_init(&q_lock, 0);
for (int i = 0; i < 2; ++i) {
pthread_create(&req_processors[i], 0, request_processor, 0);
}
pthread_create(&backend, 0, backend_handler, 0);
printf("[*] Ready to process requests.\\n");
pthread_join(backend, 0);
printf("[*] Exiting.\\n");
return 0;
}
| 1
|
#include <pthread.h>
int counter = 0;
pthread_mutex_t lock1;
pthread_mutex_t lock2;
void* thr_main1(void* arg) {
puts("thread 1 start\\n");
pthread_mutex_lock(&lock1);
sleep(1);
pthread_mutex_lock(&lock2);
counter++;
sleep(1);
pthread_mutex_unlock(&lock2);
pthread_mutex_unlock(&lock1);
return ((void*)1);
}
void* thr_main2(void* arg) {
puts("thread 2 start\\n");
pthread_mutex_lock(&lock2);
sleep(1);
pthread_mutex_lock(&lock1);
counter++;
sleep(1);
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
return ((void*)1);
}
int main (void) {
int err, i;
pthread_t tid[2];
void *tret;
err = pthread_create(&tid[0], 0, thr_main1, 0);
if (err != 0) exit(1);
err = pthread_create(&tid[1], 0, thr_main2, 0);
if (err != 0) exit(1);
for (i=0; i<2; i++) {
if (pthread_join(tid[i], &tret)) exit(2);
}
printf("done %d!\\n", counter);
return 0;
}
| 0
|
#include <pthread.h>
int npos;
pthread_mutex_t mut=PTHREAD_MUTEX_INITIALIZER;
int buf[10000000], pos=0, val=0;
void *fill(void *nr)
{
while (1) {
pthread_mutex_lock(&mut);
if (pos >= npos) {
pthread_mutex_unlock(&mut);
return 0;
}
buf[pos] = val;
pos++; val++;
pthread_mutex_unlock(&mut);
*(int *)nr += 1;
}
}
void *verify(void *arg)
{
int k;
for (k=0; k<npos; k++)
if (buf[k] != k)
printf("ERROR: buf[%d] = %d\\n", k, buf[k]);
return 0;
}
int main(int argc, char *argv[])
{
int k, nthr, count[100];
pthread_t tidf[100], tidv;
int total;
if (argc != 3) {
printf("Usage: %s <nr_pos> <nr_thrs>\\n",argv[0]);
return 1;
}
npos = (atoi(argv[1]))<(10000000)?(atoi(argv[1])):(10000000);
nthr = (atoi(argv[2]))<(100)?(atoi(argv[2])):(100);
for (k=0; k<nthr; k++) {
count[k] = 0;
pthread_create(&tidf[k], 0, fill, &count[k]);
}
total=0;
for (k=0; k<nthr; k++) {
pthread_join(tidf[k], 0);
printf("count[%d] = %d\\n", k, count[k]);
total += count[k];
}
printf("total count = %d\\n",total);
pthread_create(&tidv, 0, verify, 0);
pthread_join(tidv, 0);
return 0;
}
| 1
|
#include <pthread.h>
int r1 = 0, r2 = 0, counter = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void do_one_thing() {
pthread_mutex_lock(&mutex);
counter++;
printf("job %d started\\n", counter);
for (int i = 0; i < 4; i++) {
printf(" doing one thing\\n");
for (int j = 0; j < 4000; j++) { }
}
printf("job %d finished\\n", counter);
pthread_mutex_unlock(&mutex);
}
int main(int argc, const char * argv[]) {
pthread_t thread1, thread2;
pthread_create(& thread1,
0,
(void *) do_one_thing,
(void *) &r1);
pthread_create(& thread2,
0,
(void *) do_one_thing,
(void *) &r2);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mtx;
pthread_cond_t espera;
int tenedores[5];
pthread_mutex_t mtxIndice;
pthread_cond_t esperaIndice;
int hiloespera=1;
void *filosofo(void *indice) {
int i,j,tenedor1,tenedor2;
srandom ((unsigned)pthread_self());
pthread_mutex_lock(&mtxIndice);
hiloespera=0;
i=*((int *) indice);
pthread_cond_signal(&esperaIndice);
pthread_mutex_unlock(&mtxIndice);
tenedor1= i;
tenedor2= i+1;
if (tenedor2 == 5) tenedor2=0;
for(j=0; j <= 5; j++ ) {
pthread_mutex_lock(&mtx);
while (tenedores[tenedor1]==1 || tenedores[tenedor2]==1)
pthread_cond_wait(&espera, &mtx);
tenedores[tenedor1]=1;
tenedores[tenedor2]=1;
printf("Filosofo %d va a comer\\n",i);
pthread_mutex_unlock(&mtx);
sleep (1+ random()%2);
printf("Filosofo %d deja de comer\\n",i);
pthread_mutex_lock(&mtx);
tenedores[tenedor1]=0;
tenedores[tenedor2]=0;
pthread_cond_broadcast(&espera);
pthread_mutex_unlock(&mtx);
sleep ( random()%3);
}
printf ("FIN filosofo %d\\n",i);
pthread_exit(0);
}
int main(int argc, char *argv[]){
pthread_t th[5];
int i;
pthread_mutex_init(&mtx, 0);
pthread_cond_init(&espera, 0);
pthread_mutex_init(&mtxIndice, 0);
pthread_cond_init(&esperaIndice, 0);
for (i=0; i<5; i++)
tenedores[i]=0;
for (i=0; i<5; i++){
pthread_mutex_lock(&mtxIndice);
pthread_create(&th[i], 0, filosofo, &i);
while (hiloespera==1)
pthread_cond_wait(&esperaIndice, &mtxIndice );
hiloespera=1;
pthread_mutex_unlock(&mtxIndice);
}
for (i=0; i<5; i++)
pthread_join(th[i], 0);
pthread_mutex_destroy(&mtx);
pthread_mutex_destroy(&mtxIndice);
pthread_cond_destroy(&espera);
pthread_cond_destroy(&esperaIndice);
exit(0);
}
| 1
|
#include <pthread.h>
int MaxLoop = 50000;
int NumProcs;
pthread_barrier_t barrier;
unsigned sig[33] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32 };
union {
char b[64];
int value;
} m[64];
pthread_mutex_t locks[8];
void lockItem(unsigned index) {
pthread_mutex_lock(&locks[index % 8]);
}
void unlockItem(unsigned index) {
pthread_mutex_unlock(&locks[index % 8]);
}
unsigned mix(unsigned i, unsigned j) {
return (i + j * 103995407) % 103072243;
}
void* ThreadBody(void* tid)
{
int threadId = *(int *) tid;
int i;
for(i=0; i<0x07ffffff; i++) {};
pthread_barrier_wait(&barrier);
for(i = 0 ; i < MaxLoop; i++) {
unsigned num = sig[threadId];
unsigned index1 = num%64;
unsigned index2;
{
lockItem(index1);
num = mix(num, m[index1].value);
unlockItem(index1);
}
index2 = num%64;
{
lockItem(index2);
num = mix(num, m[index2].value);
m[index2].value = num;
unlockItem(index2);
}
sig[threadId] = num;
}
return 0;
}
int
main(int argc, char* argv[])
{
pthread_t* threads;
int* tids;
pthread_attr_t attr;
int ret;
int mix_sig, i;
if(argc < 2) {
fprintf(stderr, "%s <numProcesors> <maxLoop>\\n", argv[0]);
exit(1);
}
NumProcs = atoi(argv[1]);
assert(NumProcs > 0 && NumProcs <= 32);
if (argc >= 3) {
MaxLoop = atoi(argv[2]);
assert(MaxLoop > 0);
}
for(i = 0; i < 64; i++) {
m[i].value = mix(i,i);
}
threads = (pthread_t *) malloc(sizeof(pthread_t) * NumProcs);
assert(threads != 0);
tids = (int *) malloc(sizeof (int) * NumProcs);
assert(tids != 0);
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
ret = pthread_barrier_init(&barrier, 0, NumProcs);
assert(ret == 0);
for(i=0; i < 8; ++i) {
ret = pthread_mutex_init(&locks[i], 0);
assert(ret == 0);
}
for(i=0; i < NumProcs; i++) {
tids[i] = i+1;
ret = pthread_create(&threads[i], &attr, ThreadBody, &tids[i]);
assert(ret == 0);
}
for(i=0; i < NumProcs; i++) {
ret = pthread_join(threads[i], 0);
assert(ret == 0);
}
mix_sig = sig[0];
for(i = 1; i < NumProcs ; i++) {
mix_sig = mix(sig[i], mix_sig);
}
printf("\\n\\nShort signature: %08x @ %p @ %p\\n\\n\\n",
mix_sig, &mix_sig, (void*)malloc((1 << 10)/5));
fflush(stdout);
usleep(5);
pthread_attr_destroy(&attr);
pthread_barrier_destroy(&barrier);
for(i=0; i < 8; ++i)
pthread_mutex_destroy(&locks[i]);
return 0;
}
| 0
|
#include <pthread.h>
void *producter_f(void *arg);
void *consumer_f(void *arg);
int buffer_has_item = 0;
pthread_mutex_t mutex;
int running = 1;
int main(int argc,char* argv[])
{
pthread_t consumer_t;
pthread_t producter_t;
pthread_mutex_init(&mutex,0);
pthread_create(&producter_t,0,(void*)producter_f,0);
pthread_create(&consumer_t,0,(void*)consumer_f,0);
usleep(1);
pthread_join(consumer_t,0);
pthread_join(producter_t,0);
pthread_mutex_destroy(&mutex);
return 0;
}
void *producter_f(void *arg)
{
while(running)
{
pthread_mutex_lock(&mutex);
buffer_has_item++;
printf("生产,总数量:%d\\n",buffer_has_item);
if(buffer_has_item>10000)
{
running = 0;
}
pthread_mutex_unlock(&mutex);
}
}
void *consumer_f(void *arg)
{
while(running)
{
pthread_mutex_lock(&mutex);
buffer_has_item--;
printf("消费,总数量:%d\\n",buffer_has_item);
pthread_mutex_unlock(&mutex);
}
}
| 1
|
#include <pthread.h>
int total=0;
pthread_mutex_t zain = PTHREAD_MUTEX_INITIALIZER;
void hilo(void* arg)
{
FILE * fp;
char * line = 0;
size_t len = 0;
ssize_t read;
int num=0;
int suma=0;
int kuz= 100000/1000;
kuz=8;
int start =0;
int end =0;
int cont=0;
fp = fopen("./nums", "r");
if (fp == 0)
exit(1);
start = (int)arg * (100000/kuz);
end = start + (100000/kuz);
cont= start;
printf("start %d,fin %d\\n",start,end);
while ((read = getline(&line, &len, fp)) != -1) {
++cont;
if (cont < start) { continue; }
if (cont > end) { break; }
num = (atoi(line));
suma+=num;
}
printf("sume %d\\n",suma);
pthread_mutex_lock(&zain);
total+=suma;
pthread_mutex_unlock(&zain);
pthread_exit(0);
}
int main()
{
int nhilos = 100000/1000;
nhilos=8;
pthread_t* tids= (pthread_t*)malloc((nhilos)*sizeof(pthread_t));
pthread_t* aux=tids;
clock_t start, end;
double cpu_time_used;
int index=0;
start=clock();
for(;aux<(tids+nhilos);++aux)
{
pthread_create((aux),0,hilo,index++);
}
for(aux=tids;aux<(tids+nhilos);++aux)
{
pthread_join(*(aux),0);
}
end=clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("tarde %d\\n",cpu_time_used);
printf("TOTAL: %d\\n",total);
return 0;
}
| 0
|
#include <pthread.h>
void *sending();
char achData[1000];
char *achEXE[1];
int iConnectionDis;
pthread_t serverThread;
pthread_mutex_t mutexLock;
int main()
{
int iIndex;
int iSocketDis;
int iLenght;
struct sockaddr_in serv_addr;
int i;
iSocketDis=socket(AF_INET,SOCK_STREAM,0);
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
serv_addr.sin_port=htons(3002);
if(bind(iSocketDis,(struct sockaddr*) &serv_addr,sizeof(serv_addr))<0)
{
printf("Error\\n");
perror("Bind");
}
if(listen(iSocketDis,8)<0)
{
printf("Error\\n");
perror("Listen");
}
iLenght=sizeof(serv_addr);
for (iIndex = 0; iIndex < 100; iIndex++)
{
iConnectionDis = accept(iSocketDis,(struct sockaddr*) &serv_addr,&iLenght);
if (iConnectionDis < 0)
{
printf("connection not accepted\\n");
return 1;
}
pthread_create(&serverThread,0,sending,0);
pthread_join(serverThread,0);
}
close(iSocketDis);
}
void *sending()
{
FILE *fptr;
char achTemp[1024];
pthread_mutex_lock(&mutexLock);
if((read(iConnectionDis,achData,1000)) < 0){
printf("not read from socket\\n");
exit(0);
}
printf("\\n\\tDATA:%s\\n",achData);
fptr = popen(achData,"r");
memset(achData,0,sizeof(achData));
while((fgets(achTemp,sizeof(achTemp),fptr)) != 0 ){
strcat(achData,achTemp);
}
write(iConnectionDis,achData,1000);
memset(achData,0,sizeof(achData));
pthread_mutex_unlock(&mutexLock);
}
| 1
|
#include <pthread.h>
char* buffer[BUFFER_SIZE][NAME_SIZE];
int bufferpropos=0;
int bufferconspos=0;
pthread_mutex_t esctrin;
pthread_mutex_t lertrin;
sem_t escsem;
sem_t lesem;
bool pipeclosed=1;
long int reader() {
char* file_to_open=malloc(sizeof(char)*NAME_SIZE);
while(pipeclosed) {
bool cons=1;
sem_wait(&lesem);
if(pipeclosed==0)
break;
pthread_mutex_lock(&lertrin);
file_to_open=(char*)buffer[bufferconspos];
bufferconspos=(bufferconspos+1) % BUFFER_SIZE;
pthread_mutex_unlock(&lertrin);
sem_post(&escsem);
int fd;
fd = open (file_to_open, O_RDONLY);
if (fd == -1) {
perror ("Error opening file");
} else {
char string_to_read[STRING_SZ];
char first_string[STRING_SZ];
int i;
if (flock(fd, LOCK_SH | LOCK_NB) < 0) {
if (errno == EWOULDBLOCK)
perror ("Wait unlock");
else {
perror ("Error locking file");
}
}
if (flock(fd, LOCK_SH) < 0) {
perror ("Error locking file");
}
if (read (fd, first_string, STRING_SZ) != 10) {
perror ("Error reading file");
}
for (i=0; i<NB_ENTRIES-1; i++) {
if (read (fd, string_to_read, STRING_SZ) != 10) {
fprintf (stderr,"Error reading file: %s\\n", file_to_open);
break;
}
if (strncmp(string_to_read, first_string, STRING_SZ)) {
cons=0;
break;
}
}
if (read (fd, string_to_read, STRING_SZ) != 0) {
cons=0;
}
if(cons)
printf("File %s is Consistent\\n",file_to_open);
else
fprintf (stderr, "Inconsistent file: %s\\n", file_to_open);
if (flock(fd, LOCK_UN) < 0) {
perror ("Error unlocking file");
}
if (close (fd) == -1) {
perror ("Error closing file");
}
}
}
return 0;
}
void* reader_wrapper(void* ptr) {
return (void*) reader();
}
char* readInput() {
char* input[INPUT_MAX];
int temp;
int i;
temp=read(STDIN_FILENO,input,INPUT_MAX);
if(temp==0) {
pipeclosed=0;
printf("Pipe Closed monitor-leitor Stopping \\n");
for(i=0; i<NUM_CHILDREN_READER; i++)
sem_post(&lesem);
}
if(temp<INPUT_MAX) {
input[temp]='\\0';
} else {
input[INPUT_MAX]='\\0';
}
return input;
}
void inputParser(char* input) {
char* temp= strtok(input," ");
while(temp!=0) {
strncpy((char*)buffer[bufferpropos],temp,NAME_SIZE);
sem_post(&lesem);
bufferpropos=(bufferpropos+1)%BUFFER_SIZE;
temp=strtok(0," ");
}
}
void* receberInput() {
char* filename=malloc(sizeof(char)*2048);
while(pipeclosed) {
sem_wait(&escsem);
filename=readInput();
inputParser(filename);
}
exit(0);
}
int main (int argc, char** argv) {
srandom ((unsigned) time(0));
pthread_t tid[NUM_CHILDREN_READER];
pthread_t input;
int runningChildren;
long int retVals[NUM_CHILDREN_READER];
if(sem_init(&escsem,0,BUFFER_SIZE)!=0) {
perror("Failed Initializing of escsem");
exit(-1);
}
if(sem_init(&lesem,0,0)!=0) {
perror("Failed Initializing of lesem");
exit(-1);
}
if(pthread_mutex_init(&lertrin,0)!=0) {
perror("Failed Initializing of lebuffer");
exit(-1);
}
if(pthread_mutex_init(&esctrin,0)!=0) {
perror("Failed Initializing of escbuffer");
exit(-1);
}
if(pthread_create(&input,0,receberInput,(void*)1)!=0) {
perror("Erro creating thread Input");
return -1;
}
for (runningChildren = 0; runningChildren < NUM_CHILDREN_READER; runningChildren++) {
if (pthread_create(&tid[runningChildren], 0, reader_wrapper,(void*)1 ) != 0) {
printf("Error creating thread %d", runningChildren);
return -1;
}
}
for (runningChildren = 0; runningChildren < NUM_CHILDREN_READER; runningChildren++) {
pthread_join(tid[runningChildren], (void**)&retVals[runningChildren]);
printf("Leitor Thread Finished\\n");
}
long int retVal;
pthread_join(input, (void**)&retVal);
write(STDOUT_FILENO,"Input Thread Finished\\n",22);
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER;
void output_init()
{
return;
}
void output( char * string, ... )
{
va_list ap;
char *ts="[??:??:??]";
struct tm * now;
time_t nw;
pthread_mutex_lock(&m_trace);
nw = time(0);
now = localtime(&nw);
if (now == 0)
printf(ts);
else
printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec);
__builtin_va_start((ap));
vprintf(string, ap);
;
pthread_mutex_unlock(&m_trace);
}
void output_fini()
{
return;
}
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
int controls[ 3 ] = {0, 0, 0};
void prepare( void )
{
controls[ 0 ] ++;
}
void parent( void )
{
controls[ 1 ] ++;
}
void child( void )
{
controls[ 2 ] ++;
}
void * threaded( void * arg )
{
int ret, status;
pid_t child, ctl;
ret = pthread_mutex_lock( &mtx );
if ( ret != 0 )
{
UNRESOLVED( ret, "Failed to lock mutex" );
}
ret = pthread_mutex_unlock( &mtx );
if ( ret != 0 )
{
UNRESOLVED( ret, "Failed to unlock mutex" );
}
child = fork();
if ( child == ( pid_t ) - 1 )
{
UNRESOLVED( errno, "Failed to fork" );
}
if ( child == ( pid_t ) 0 )
{
if ( controls[ 0 ] != 100 )
{
FAILED( "prepare handler skipped some rounds" );
}
if ( controls[ 2 ] != 100 )
{
FAILED( "child handler skipped some rounds" );
}
exit( PTS_PASS );
}
if ( controls[ 0 ] != 100 )
{
FAILED( "prepare handler skipped some rounds" );
}
if ( controls[ 1 ] != 100 )
{
FAILED( "parent handler skipped some rounds" );
}
ctl = waitpid( child, &status, 0 );
if ( ctl != child )
{
UNRESOLVED( errno, "Waitpid returned the wrong PID" );
}
if ( ( !WIFEXITED( status ) ) || ( WEXITSTATUS( status ) != PTS_PASS ) )
{
FAILED( "Child exited abnormally" );
}
return 0;
}
int main( int argc, char * argv[] )
{
int ret, i;
pthread_t ch;
output_init();
ret = pthread_mutex_lock( &mtx );
if ( ret != 0 )
{
UNRESOLVED( ret, "Failed to lock mutex" );
}
ret = pthread_create( &ch, 0, threaded, 0 );
if ( ret != 0 )
{
UNRESOLVED( ret, "Failed to create a thread" );
}
for ( i = 0; i < 100; i++ )
{
ret = pthread_atfork( prepare, parent, child );
if ( ret == ENOMEM )
{
output( "ENOMEM returned after %i iterations\\n", i );
break;
}
if ( ret != 0 )
{
UNRESOLVED( ret, "Failed to register the atfork handlers" );
}
}
if ( ret == 0 )
{
ret = pthread_mutex_unlock( &mtx );
if ( ret != 0 )
{
UNRESOLVED( ret, "Failed to unlock mutex" );
}
ret = pthread_join( ch, 0 );
if ( ret != 0 )
{
UNRESOLVED( ret, "Failed to join the thread" );
}
}
output( "Test passed\\n" );
PASSED;
}
| 1
|
#include <pthread.h>
extern int makethread(void *(*)(void *), void *);
struct to_info {
void (*to_fn)(void *);
void *to_arg;
struct timespec to_wait;
};
void clock_gettime(int id, struct timespec *tsp)
{
struct timeval tv;
gettimeofday(&tv, 0);
tsp->tv_sec = tv.tv_sec;
tsp->tv_nsec = tv.tv_usec * 1000;
}
void *timeout_helper(void *arg)
{
printf("timeout_helper\\n");
struct to_info *tip;
tip = (struct to_info *)arg;
printf("tip->to_wait.tv_sec = %ld\\n"
"tip->to_wait.tv_nsec = %ld\\n",
tip->to_wait.tv_sec, tip->to_wait.tv_nsec);
nanosleep((&tip->to_wait), (0));
(*tip->to_fn)(tip->to_arg);
free(arg);
return(0);
}
void timeout(const struct timespec *when, void (*func)(void *), void *arg)
{
printf("timeout\\n");
struct timespec now;
struct to_info *tip;
int err;
clock_gettime(0, &now);
printf("when->tv_sec = %ld\\nwhen->tv_nsec = %ld\\n",
when->tv_sec, when->tv_nsec);
printf("now.tv_sec = %ld\\nnow.tv_nsec = %ld\\n",
now.tv_sec, now.tv_nsec);
if ((when->tv_sec > now.tv_sec) ||
(when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) {
tip = (struct to_info*)malloc(sizeof(struct to_info));
if (tip != 0) {
tip->to_fn = func;
tip->to_arg = arg;
tip->to_wait.tv_sec = when->tv_sec - now.tv_sec;
if (when->tv_nsec >= now.tv_nsec) {
tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec;
} else {
tip->to_wait.tv_sec--;
tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec +
when->tv_nsec;
}
printf("tip->to_wait.tv_sec = %ld\\n"
"tip->to_wait.tv_nsec = %ld\\n",
tip->to_wait.tv_sec, tip->to_wait.tv_nsec);
err = makethread(timeout_helper, (void *)tip);
if (err == 0)
return;
else
{
free(tip);
printf("free(tip)\\n");
}
}
}
(*func)(arg);
}
pthread_mutexattr_t attr;
pthread_mutex_t mutex;
void retry(void *arg)
{
pthread_mutex_lock(&mutex);
printf("5 seconds have passed\\n");
pthread_mutex_unlock(&mutex);
}
int main(void)
{
int err, condition, arg;
struct timespec when;
condition = 1;
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) {
clock_gettime(0, &when);
when.tv_sec += 5;
timeout(&when, retry, (void *)((unsigned long)arg));
}
pthread_mutex_unlock(&mutex);
sleep(10);
printf("main end\\n");
exit(0);
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error();
static int iTThreads = 2;
static int iRThreads = 1;
static int data1Value = 0;
static int data2Value = 0;
pthread_mutex_t *data1Lock;
pthread_mutex_t *data2Lock;
void lock(pthread_mutex_t *);
void unlock(pthread_mutex_t *);
void *funcA(void *param)
{
pthread_mutex_lock(data1Lock);
data1Value = 1;
pthread_mutex_unlock(data1Lock);
pthread_mutex_lock(data2Lock);
data2Value = data1Value + 1;
pthread_mutex_unlock(data2Lock);
return 0;
}
void *funcB(void *param)
{
int t1 = -1;
int t2 = -1;
pthread_mutex_lock(data1Lock);
if (data1Value == 0)
{
pthread_mutex_unlock(data1Lock);
return 0;
}
t1 = data1Value;
pthread_mutex_unlock(data1Lock);
pthread_mutex_lock(data2Lock);
t2 = data2Value;
pthread_mutex_unlock(data2Lock);
if (t2 != (t1 + 1))
{
fprintf(stderr, "Bug found!\\n");
ERROR:
__VERIFIER_error();
;
}
return 0;
}
int main(int argc, char *argv[])
{
int i;
int err;
if (argc != 1)
{
if (argc != 3)
{
fprintf(stderr, "./twostage <param1> <param2>\\n");
exit(-1);
}
else
{
sscanf(argv[1], "%d", &iTThreads);
sscanf(argv[2], "%d", &iRThreads);
}
}
data1Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
data2Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
if (0 != (err = pthread_mutex_init(data1Lock, 0)))
{
fprintf(stderr, "pthread_mutex_init error: %d\\n", err);
exit(-1);
}
if (0 != (err = pthread_mutex_init(data2Lock, 0)))
{
fprintf(stderr, "pthread_mutex_init error: %d\\n", err);
exit(-1);
}
pthread_t tPool[iTThreads];
pthread_t rPool[iRThreads];
for (i = 0; i < iTThreads; i++)
{
__CPROVER_assume((((3 - argc) >= 0) && (i >= 0)) && (((-1) + argc) >= 0));
{
if (0 != (err = pthread_create(&tPool[i], 0, &funcA, 0)))
{
fprintf(stderr, "Error [%d] found creating 2stage thread.\\n", err);
exit(-1);
}
}
}
for (i = 0; i < iRThreads; i++)
{
__CPROVER_assume((((3 - argc) >= 0) && (i >= 0)) && (((-1) + argc) >= 0));
{
if (0 != (err = pthread_create(&rPool[i], 0, &funcB, 0)))
{
fprintf(stderr, "Error [%d] found creating read thread.\\n", err);
exit(-1);
}
}
}
for (i = 0; i < iTThreads; i++)
{
__CPROVER_assume((((3 - argc) >= 0) && (i >= 0)) && (((-1) + argc) >= 0));
{
if (0 != (err = pthread_join(tPool[i], 0)))
{
fprintf(stderr, "pthread join error: %d\\n", err);
exit(-1);
}
}
}
for (i = 0; i < iRThreads; i++)
{
__CPROVER_assume((((3 - argc) >= 0) && (i >= 0)) && (((-1) + argc) >= 0));
{
if (0 != (err = pthread_join(rPool[i], 0)))
{
fprintf(stderr, "pthread join error: %d\\n", err);
exit(-1);
}
}
}
return 0;
}
void lock(pthread_mutex_t *lock)
{
int err;
if (0 != (err = pthread_mutex_lock(lock)))
{
fprintf(stderr, "Got error %d from pthread_mutex_lock.\\n", err);
exit(-1);
}
}
void unlock(pthread_mutex_t *lock)
{
int err;
if (0 != (err = pthread_mutex_unlock(lock)))
{
fprintf(stderr, "Got error %d from pthread_mutex_unlock.\\n", err);
exit(-1);
}
}
| 1
|
#include <pthread.h>
int flag = 0;
int counter =0;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t threshold = PTHREAD_COND_INITIALIZER;
void *tf(void *param){
int i;
while (1) {
pthread_mutex_lock(&mutex);
if(counter == 5000000){
do { } while (0);
pthread_cond_signal(&threshold);
pthread_mutex_unlock(&mutex);
break;
}
counter++;
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main(void) {
int i;
flag = 1;
pthread_t ti_arr[5];
pthread_mutex_init(&mutex, 0);
pthread_cond_init (&threshold, 0);
for (i = 0 ; i < 5 ; i++) {
if (pthread_create(ti_arr+i, 0, tf, 0) != 0) {
printf("Error in creating a thread %d\\n", i);
exit (0);
}
}
do { } while (0);
pthread_mutex_lock(&mutex);
do { } while (0);
pthread_cond_wait(&threshold, &mutex);
do { } while (0);
printf("Counter is after the while loop %d\\n", counter);
pthread_mutex_unlock(&mutex);
for ( i = 0 ; i < 5 ; i++) {
pthread_join(ti_arr[i], 0);
}
printf("Counter is when all sub threads have finnished %d\\n", counter);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t sync_mutex;
int count = 0;
int totals[10];
void* increment_count() {
FILE* fout = 0;
fout = fopen("inc_out.txt", "w");
if(0 == fout) {
printf("Error opening inc file\\n");
exit(1);
}
for(int i = 0; i < 10; ++i) {
++count;
if(i > 0) {
totals[i] = totals[i-1] + count;
} else {
totals[0] = count;
}
}
for(int i = 0; i < 10; ++i) {
if(i > 0) {
fprintf(fout, "%d %d\\n", totals[i], (totals[i] > totals[i-1]));
} else {
fprintf(fout, "%d 1\\n", totals[i]);
}
}
fclose(fout);
pthread_mutex_unlock(&sync_mutex);
pthread_exit(0);
}
void* increment_count2() {
FILE* fout = 0;
fout = fopen("inc2_out.txt", "w");
if(0 == fout) {
printf("Error opening inc file\\n");
exit(1);
}
for(int i = 0; i < 10; ++i) {
++count;
if(i > 0) {
totals[i] = totals[i-1] + count;
} else {
totals[0] = count;
}
}
for(int i = 0; i < 10; ++i) {
if(i > 0) {
fprintf(fout, "%d %d\\n", totals[i], (totals[i] > totals[i-1]));
} else {
fprintf(fout, "%d 1\\n", totals[i]);
}
}
fclose(fout);
pthread_exit(0);
}
int main(int argc, char** argv) {
pthread_t threads[2];
int err;
FILE* fout = 0;
if(argc < 2) {
printf("Please supply input\\n");
exit(1);
}
count = atoi(argv[1]);
pthread_mutex_init(&sync_mutex, 0);
fout = fopen("output.txt", "w");
if(0 == fout) {
printf("Error opening output file\\n");
exit(1);
}
pthread_mutex_lock(&sync_mutex);
err = pthread_create(&threads[0], 0, &increment_count, 0);
if(err) {
printf("ERROR: return code for pthread_create() is %d\\n", err);
exit(1);
}
err = pthread_create(&threads[1], 0, &increment_count2, 0);
if(err) {
printf("ERROR: return code for pthread_create() is %d\\n", err);
exit(1);
}
pthread_mutex_lock(&sync_mutex);
for(int i = 0; i < 10; ++i) {
printf("%d\\n", totals[i]);
fprintf(fout, "%d\\n", totals[i]);
}
pthread_mutex_unlock(&sync_mutex);
fclose(fout);
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
void func(void *arg) {
struct timespec tm = {
.tv_sec = 100000,
.tv_nsec = 0,
};
int msg = pthread_mutex_timedlock(&mtx, &tm);
if (msg != 0) {
printf("msg = %d\\n", msg);
errno = msg;
perror("pthread_mutex_timedlock\\n");
}
pthread_exit(0);
}
int main(int argc, char *argv[]) {
pthread_t thrd;
pthread_mutex_lock(&mtx);
pthread_create(&thrd, 0, (void *) &func, 0);
int msg = pthread_join(thrd, 0);
if (msg != 0) {
printf("msg = %d\\n", msg);
errno = msg;
perror("pthread_join\\n");
}
pthread_mutex_unlock(&mtx);
return 0;
}
| 0
|
#include <pthread.h>
int qtde = 0;
pthread_mutex_t mut;
sem_t msg, prupru;
void *pombo(void)
{
while(1)
{
sem_wait(&prupru);
pthread_mutex_lock(&mut);
puts("^(0.0)^ Levando mensagens ^(0.0)^");
int i;
for(i = 0; i < 20; i++) sem_post(&msg);
qtde = 0;
pthread_mutex_unlock(&mut);
sleep(15);
puts("^(0.0)^ Voltando ao sono ZzZzZzZzZ ^(0.0)^");
}
}
void* postit(void* x)
{
int i = (int)x;
while(1)
{
sem_wait(&msg);
pthread_mutex_lock(&mut);
if(qtde == 19)
{
sem_post(&prupru);
}
qtde++;
int asd = rand() % 10;
printf("Colando mensagem, qtde: %d TID: %d, vou dormir por %d\\n", qtde, i, asd);
pthread_mutex_unlock(&mut);
sleep(asd);
}
}
int main(int argc, char *argv[])
{
int x = atoi(argv[1]),i;
pthread_t tid[x+1], p;
pthread_mutex_init(&mut, 0);
sem_init(&msg, 0 ,20);
sem_init(&prupru, 0 ,0);
pthread_create(&p, 0, pombo, (void*)0);
for(i = 0; i < x; i++) pthread_create(&tid[i], 0, postit, (void*)i);
for(;;);
}
| 1
|
#include <pthread.h>
pthread_mutex_t gm;
struct bar{
int a;
char c[15000];
};
struct foo{
int id;
struct bar b;
};
struct thread_data {
int tid;
struct foo *local_data;
};
void *t(void *args){
struct thread_data *data = (struct thread_data*)args;
int tid = data->tid;
struct foo *tmp = data->local_data;
pthread_mutex_lock(&gm);
tmp->b.c[97+tid] = 97+tid;
printf("tid %d wrote %c at f->b.c[%d]\\n", tid, tmp->b.c[97+tid], 97+tid);
tmp->b.c[10000] = '!'+tid;
if (tid == 0) {
tmp->b.c[13000] = '@';
printf("tid %d wrote %c at f->b.c[13000]\\n", tid, tmp->b.c[13000]);
}
printf("tid %d wrote %c at f->b.c[10000]\\n", tid, tmp->b.c[10000]);
pthread_mutex_unlock(&gm);
free(args);
pthread_exit(0);
}
int main(){
pthread_mutex_init(&gm, 0);
pthread_t tid[3];
printf("Checking crash status\\n");
if ( isCrashed() ) {
printf("I need to recover!\\n");
struct foo *f = (struct foo*)nvmalloc(sizeof(struct foo), (char*)"f");
nvrecover(f, sizeof(struct foo), (char *)"f");
printf("f->b.c[97] = %c\\n", f->b.c[97]);
printf("f->b.c[98] = %c\\n", f->b.c[98]);
printf("f->b.c[99] = %c\\n", f->b.c[99]);
printf("f->b.c[10000] = %c\\n", f->b.c[10000]);
printf("f->b.c[13000] = %c\\n", f->b.c[13000]);
printf("f->id = %d\\n", f->id);
free(f);
}
else{
printf("Program did not crash before, continue normal execution.\\n");
struct foo *f = (struct foo*)nvmalloc(sizeof(struct foo), (char*)"f");
memset(f->b.c, 0, sizeof(struct foo));
printf("finish writing to values\\n");
int i;
for (i = 0; i < 3; i++) {
struct thread_data *tmp = (struct thread_data*)malloc(sizeof(struct thread_data));
tmp->tid = i;
tmp->local_data = f;
pthread_create(&tid[i], 0, t, (void*)tmp);
}
pthread_mutex_lock(&gm);
f->id = 12345;
f->b.c[10000] = '$';
printf("main wrote $ to f->b.c[10000]\\n");
pthread_mutex_unlock(&gm);
pthread_mutex_lock(&gm);
f->b.c[10000] = '$';
printf("main wrote $ to f->b.c[10000] again\\n");
pthread_mutex_unlock(&gm);
for (i = 0; i < 3; i++) {
pthread_join(tid[i], 0);
}
printf("f->b.c[97] = %c\\n", f->b.c[97]);
printf("f->b.c[98] = %c\\n", f->b.c[98]);
printf("f->b.c[99] = %c\\n", f->b.c[99]);
printf("f->b.c[10000] = %c\\n", f->b.c[10000]);
printf("f->b.c[13000] = %c\\n", f->b.c[13000]);
printf("f->id = %d\\n", f->id);
printf("internally abort!\\n");
abort();
}
printf("-------------main exits-------------------\\n");
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t condVar;
void Start()
{
printf("new thread here: %u\\n", (unsigned)pthread_self());
while(1)
{
pthread_mutex_lock(&mutex);
printf("\\tthread signal %u\\n", (unsigned)pthread_self());
pthread_cond_signal(&condVar);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main()
{
pthread_t t1, t2, t3;
if(pthread_cond_init(&condVar, 0) != 0)
{
printf("CondVar init failed\\n");
return -1;
}
if(pthread_mutex_init(&mutex, 0) != 0)
{
printf("mutex init failed\\n");
return -1;
}
if((pthread_create(&t1, 0, (void *)Start, 0)) != 0)
{
printf("clrThread thread init failed, exit\\n");
return -1;
}
if((pthread_create(&t2, 0, (void *)Start, 0)) != 0)
{
printf("clrThread thread init failed, exit\\n");
return -1;
}
if((pthread_create(&t3, 0, (void *)Start, 0)) != 0)
{
printf("clrThread thread init failed, exit\\n");
return -1;
}
while(1)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&condVar, &mutex);
printf("got signal\\n");
pthread_mutex_unlock(&mutex);
}
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_join(t3, 0);
return 0;
}
| 1
|
#include <pthread.h>
struct s {
int datum;
struct s *next;
};
struct s *new(int x) {
struct s *p = malloc(sizeof(struct s));
p->datum = x;
p->next = 0;
return p;
}
void list_add(struct s *node, struct s *list) {
struct s *temp = list->next;
list->next = node;
node->next = temp;
}
pthread_mutex_t mutex[10];
struct s *slot[10];
void *t_fun(void *arg) {
int i;
pthread_mutex_lock(&mutex[i]);
list_add(new(3), slot[i]);
pthread_mutex_unlock(&mutex[i]);
return 0;
}
int main () {
int j, k;
struct s *p;
pthread_t t1;
slot[j] = new(1);
list_add(new(2), slot[j]);
slot[k] = new(1);
list_add(new(2), slot[k]);
p = new(3);
list_add(p, slot[j]);
list_add(p, slot[k]);
pthread_create(&t1, 0, t_fun, 0);
pthread_mutex_lock(&mutex[j]);
p = slot[j]->next;
printf("%d\\n", p->datum);
pthread_mutex_unlock(&mutex[j]);
return 0;
}
| 0
|
#include <pthread.h>
void* wheelTimer(void *data) {
printf("Poll thread is running...\\n");
struct hallThreadData* threadData;
threadData = (struct hallThreadData*)data;
int pollReturn, readReturn;
char* buffer[64];
struct timeval systemTime;
struct pollfd gpioDescriptor;
unsigned long int lastTime, currentTime;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
while (1) {
memset ((void*)&gpioDescriptor, 0, sizeof(gpioDescriptor));
gpioDescriptor.fd = threadData->pinFileDescriptor;
gpioDescriptor.events = POLLPRI;
pollReturn = poll (&gpioDescriptor, 1, 250);
if (pollReturn < 0) {
printf ("\\npoll() failed \\n");
return -1;
}
else if (pollReturn == 0) {
threadData->speed = 0;
}
else if (gpioDescriptor.revents & POLLPRI && pollReturn > 0) {
readReturn = read (gpioDescriptor.fd, buffer, 64);
lastTime = currentTime;
gettimeofday(&systemTime, 0);
currentTime = (systemTime.tv_sec) * 1000 + (systemTime.tv_usec) / 1000;
pthread_mutex_lock(&(threadData->theMutex));
unsigned long int elapsedMilliSeconds = currentTime - lastTime;
if (threadData->isFront)
threadData->speed = 1000 * 3.6 * 1.626 / elapsedMilliSeconds;
else
threadData->speed = 1000 * 3.6 * 1.785 / elapsedMilliSeconds;
pthread_mutex_unlock(&(threadData->theMutex));
}
fflush (stdout);
}
return 0;
}
int hallGPIOSetup (char pin[2]) {
char pinLocation[30];
strncpy (pinLocation, "/sys/class/gpio", 16);
strncat (pinLocation, "/gpio", 5);
strncat (pinLocation, pin, 2);
char pinEdge[30];
strncpy (pinEdge, pinLocation, 23);
strncat (pinEdge, "/edge", 5);
char pinExport[30];
strncpy (pinExport, "/sys/class/gpio", 16);
strncat (pinExport, "/export", 7);
char pinValue[30];
strncpy (pinValue, pinLocation, 23);
strncat (pinValue, "/value", 7);
fileExport = fopen (pinExport, "w");
if (!fileExport) {
printf("Could not open export file\\n");
return 0;
}
fprintf (fileExport,"%s\\n",pin);
fclose (fileExport);
fileEdge = fopen (pinEdge, "w");
if (!fileEdge) {
printf("Could not open pin edge file\\n");
}
fprintf (fileEdge, "rising\\n");
fclose (fileEdge);
int fileDescriptor = open (pinValue, O_RDONLY | O_NONBLOCK);
return fileDescriptor;
}
int hallGPIOleanup (struct hallThreadData* dataStruct) {
close (dataStruct->speed);
free (dataStruct);
return 1;
}
| 1
|
#include <pthread.h>
static struct Directory directory[ENTRIES];
static pthread_mutex_t directoryMutex;
void DirectoryInit()
{
int i;
pthread_mutex_init(&directoryMutex, 0);
for (i = 0; i < ENTRIES; i++) {
directory[i].used = 0;
}
}
void DirectoryAdd(char *file, struct sockaddr_in address)
{
int i, old;
time_t current;
char dest[INET_ADDRSTRLEN];
pthread_mutex_lock(&directoryMutex);
time(¤t);
for (i = 0; i < ENTRIES; i++) {
if (directory[i].used == 0) {
old = i;
break;
}
else if (file != 0 && directory[i].file != 0) {
if (strcmp(file, directory[i].file) == 0) {
if ((directory[i].peer.sin_port == address.sin_port)
&& directory[i].peer.sin_addr.s_addr == address.sin_addr.s_addr) {
directory[i].timestamp = current;
pthread_mutex_unlock(&directoryMutex);
return;
}
}
}
else {
if (directory[i].timestamp < current) {
current = directory[i].timestamp;
old = i;
}
}
}
if (file != 0) {
strcpy(directory[old].file, file);
}
memcpy(&directory[old].peer, &address, sizeof(struct sockaddr_in));
time(&directory[old].timestamp);
directory[i].used = 1;
pthread_mutex_unlock(&directoryMutex);
}
struct Directory * DirectoryGet()
{
return directory;
}
int DirectoryGetList(struct sockaddr_in *addresses)
{
int i, j, count = 0;
char unique;
struct sockaddr_in current;
pthread_mutex_lock(&directoryMutex);
for (i = 0; i < ENTRIES; i++) {
unique = 1;
if (directory[i].used == 1) {
current = directory[i].peer;
}
else
break;
memcpy(&addresses[count], ¤t,
sizeof(struct sockaddr_in));
count++;
}
pthread_mutex_unlock(&directoryMutex);
return count;
}
int DirectoryGetListBySearch(char *search, struct sockaddr_in *addresses)
{
int i, j, count = 0;
struct sockaddr_in current;
pthread_mutex_lock(&directoryMutex);
for (i = 0; i < ENTRIES; i++) {
if (directory[i].used == 1
&& strcmp(search, directory[i].file) == 0) {
current = directory[i].peer;
}
else
continue;
memcpy(&addresses[count], ¤t,
sizeof(struct sockaddr_in));
count++;
}
pthread_mutex_unlock(&directoryMutex);
return count;
}
| 0
|
#include <pthread.h>
struct object
{
pthread_mutex_t mutex;
int data;
};
void object_init(struct object *object)
{
object->data = 0;
}
void object_method_0(struct object *object)
{
pthread_mutex_lock(&object->mutex);
object->data++;
pthread_mutex_unlock(&object->mutex);
}
void object_method_1(struct object *object)
{
pthread_mutex_lock(&object->mutex);
object_method_0(object);
object->data++;
pthread_mutex_unlock(&object->mutex);
}
void *entry_0(void *arg)
{
int i;
struct object *object = (struct object *)arg;
for (i = 0; i < 3; i++) {
puts("Thread 0 is executing ...");
object_method_1(object);
sleep(1);
}
return 0;
}
void *entry_1(void *arg)
{
int i;
struct object *object = (struct object *)arg;
for (i = 0; i < 3; i++) {
puts("Thread 1 is executing ...");
object_method_1(object);
sleep(1);
}
return 0;
}
int main()
{
struct object object;
pthread_t thread_0;
pthread_t thread_1;
object_init(&object);
pthread_create(&thread_0, 0, entry_0, &object);
pthread_create(&thread_1, 0, entry_1, &object);
pthread_join(thread_0, 0);
pthread_join(thread_1, 0);
return 0;
}
| 1
|
#include <pthread.h>
inline int obd_data(int obd_flag ,unsigned char* buf)
{
pthread_mutex_lock(&g_mtx);
char* buf_rcv[256];
unsigned char buf_tmp[256]={0};
int wread=0;
int i;
memset(buf_rcv,0,256);
buf_rcv[0] = "BT+MIL\\r\\n";
buf_rcv[1] = "BT+SPWR\\r\\n";
buf_rcv[2] = "BT+RDTC\\r\\n";
buf_rcv[3] = "BT+DATA.Load\\r\\n";
buf_rcv[4] = "BT+DATA.ECT\\r\\n";
buf_rcv[5] = "BT+DATA.RPM\\r\\n";
buf_rcv[6] = "BT+DATA.MAX_R\\r\\n";
buf_rcv[7] = "BT+DATA.VSS\\r\\n";
buf_rcv[8] = "BT+DATA.MAX_S\\r\\n";
buf_rcv[9] = "BT+DATA.BAD_H\\r\\n";
buf_rcv[10] = "BT+DATA.CAC_AFE\\r\\n";
buf_rcv[11] = "BT+DATA.WHP\\r\\n";
buf_rcv[12] = "BT+DATA.AD_Mil\\r\\n";
buf_rcv[13] = "BT+DATA.AD_FEH\\r\\n";
buf_rcv[14] = "BT+DATA.ICO2\\r\\n";
buf_rcv[15] = "BT+DATA.DriT\\r\\n";
switch(obd_flag)
{
case 0XB0:
i=1;
break;
case 0XB1:
i=3;
break;
case 0XB2:
i=4;
break;
case 0XB3:
i=5;
break;
case 0XB4:
i=6;
break;
case 0XB5:
i=7;
break;
case 0XB6:
i=8;
break;
case 0XB7:
i=9;
break;
case 0XB8:
i=10;
break;
case 0XB9:
i=11;
break;
case 0XC0:
i=12;
break;
case 0XC1:
i=13;
break;
case 0XC2:
i=14;
break;
case 0XC3:
i=15;
break;
default:
break;
}
wread = write(OBDfd,buf_rcv[i], strlen(buf_rcv[i]));
if(wread < 0)
{
perror("write");
return -1;
}
printf("wread = %d wcv: %s\\n", wread, buf_rcv[i]);
sleep(2);
int nread=0; int j;
nread = read(OBDfd, buf_tmp, 256);
printf("read: %s\\n",buf_tmp);
for(j=0;j<= nread;j++)
{
printf("buf[%d]=%c\\n",j,buf_tmp[j]);
}
strcpy(buf,buf_tmp);
printf("%s\\n",buf);
pthread_mutex_unlock(&g_mtx);
}
| 0
|
#include <pthread.h>
void *consumeTen();
void *consumeFifteen();
struct data
{
char name;
int pearlsTaken;
int *pearls;
};
int pearls = 1000;
pthread_mutex_t mutex;
pthread_cond_t full_cond;
pthread_cond_t empty_cond;
struct data threadData[4];
int main()
{
int i, j;
pthread_t threadID[4];
threadData[0].name = 'A';
threadData[0].pearlsTaken = 0;
threadData[1].name = 'B';
threadData[1].pearlsTaken = 0;
threadData[2].name = 'C';
threadData[2].pearlsTaken = 0;
threadData[3].name = 'D';
threadData[3].pearlsTaken = 0;
pthread_setconcurrency(4);
pthread_create(&threadID[0], 0, (void *(*)(void *))consumeTen, &threadData[0]);
pthread_create(&threadID[1], 0, (void *(*)(void *))consumeTen, &threadData[1]);
pthread_create(&threadID[2], 0, (void *(*)(void *))consumeFifteen, &threadData[2]);
pthread_create(&threadID[3], 0, (void *(*)(void *))consumeFifteen, &threadData[3]);
pthread_exit(0);
}
void *consumeTen()
{
double pearlsToTake = 0;
while(pearls != 0)
{
pthread_mutex_lock(&mutex);
pearlsToTake = (.10) * pearls;
pearlsToTake = ceil(pearlsToTake);
printf("Pirate TEN %c took %d pearls from the chest \\n", threadData->name, pearlsToTake);
pearls -= pearlsToTake;
threadData->pearlsTaken += pearlsToTake;
pthread_mutex_unlock(&mutex);
}
}
void *consumeFifteen()
{
double pearlsToTake = 0;
while(pearls != 0)
{
pthread_mutex_lock(&mutex);
pearlsToTake = (.15) * pearls;
pearlsToTake = ceil(pearlsToTake);
printf("Pirate FIFTEEN %c took %d pearls from the chest \\n", threadData->name, pearlsToTake);
pearls -= pearlsToTake;
threadData->pearlsTaken += pearlsToTake;
pthread_mutex_unlock(&mutex);
}
}
| 1
|
#include <pthread.h>
static pthread_mutex_t mutex;
static pthread_cond_t cond;
void printBuf(unsigned char *buf, int len) {
int i = 0;
printf("address:%d\\n", buf);
for (i=0; i<len; i++) {
printf("%x ", buf[i]);
}
printf("\\n");
}
void *test_thread(void *arg) {
unsigned char *inaddr;
char instr[15];
int inNum = 0;
printf("please input:\\n");
fgets(instr, 15, stdin);
inNum = atoi(instr);
inaddr = (unsigned char *)inNum;
printf("in thread:%x\\n", *inaddr);
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
printf("please input:\\n");
fgets(instr, 15, stdin);
inNum = atoi(instr);
inaddr = (unsigned char *)inNum;
printf("in thread:%x\\n", *inaddr);
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
int main(int argc, char **argv) {
unsigned char *buf=0;
pthread_t thread_id;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
pthread_create(&thread_id, 0, test_thread, 0);
buf = (unsigned char *)malloc(20);
printBuf(buf, 20);
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
memset(buf, 0xaa, 20);
printBuf(buf, 20);
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
free(buf);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex_device;
int found = -1;
char *found_path_file;
char *get_event_file_path(int id_file){
char id_file_c[4];
snprintf(id_file_c, sizeof(id_file_c), "%d", id_file);
char *partial_path = "/dev/input/event";
char *complete_path = (char *) malloc(strlen(partial_path)+strlen(id_file_c));
strcpy(complete_path, partial_path);
strcat(complete_path, id_file_c);
return complete_path;
}
void *listen_event_file(void *arg)
{
int id_file = (int) *((int *) arg);
char * path_file = get_event_file_path(id_file);
printf("listen to %s\\n",path_file);
int fd = open(path_file, O_RDONLY | O_NONBLOCK);
struct input_event ev;
while (found < 0)
{
int count = read(fd, &ev, sizeof(struct input_event));
if (ev.type == 1)
{
pthread_mutex_lock(&mutex_device);
found = id_file;
pthread_mutex_unlock(&mutex_device);
found_path_file = path_file;
}
pthread_yield();
}
pthread_exit(0);
}
int main(int argc, char **argv)
{
char count_device_command[] = "ls /dev/input/event* | wc -w";
char count_device_value[4];
FILE* fp = popen(count_device_command, "r");
while (fgets(count_device_value, 4, fp) != 0);
pclose(fp);
int nb_device = atoi(count_device_value);
pthread_mutex_init(&mutex_device, 0);
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_t listener[nb_device];
int device_id[nb_device];
void *status;
printf("found %d devices\\n",nb_device);
int i;
for (i=0; i<nb_device;i++)
device_id[i] = i;
for (i=0; i<nb_device; i++)
pthread_create(&listener[i], &attr, listen_event_file, (void *) &device_id[i]);
pthread_attr_destroy(&attr);
for (i=0; i<nb_device; i++)
pthread_join(listener[i], &status);
pthread_mutex_destroy(&mutex_device);
printf("keyboard found in file %s\\n",found_path_file);
int fd = open(found_path_file, O_RDONLY);
struct input_event ev;
while (1)
{
read(fd, &ev, sizeof(struct input_event));
if(ev.type == 1)
printf("key %i state %i\\n", ev.code, ev.value);
}
}
| 1
|
#include <pthread.h>
int in = 0;
int out = 0;
int buff[10] = {0};
sem_t empty_sem;
sem_t full_sem;
pthread_mutex_t mutex;
int product_id = 0;
int prochase_id = 0;
void print()
{
int i;
for(i = 0; i < 10; i++)
printf("%d ", buff[i]);
printf("\\n");
}
void *product()
{
int id = ++product_id;
while(1)
{
sleep(1);
sem_wait(&empty_sem);
pthread_mutex_lock(&mutex);
in = in % 10;
printf("product%d in %d. like: \\t", id, in);
buff[in] = 1;
print();
++in;
pthread_mutex_unlock(&mutex);
sem_post(&full_sem);
}
}
void *prochase()
{
int id = ++prochase_id;
while(1)
{
sleep(1);
sem_wait(&full_sem);
pthread_mutex_lock(&mutex);
out = out % 10;
printf("prochase%d in %d. like: \\t", id, out);
buff[out] = 0;
print();
++out;
pthread_mutex_unlock(&mutex);
sem_post(&empty_sem);
}
}
int main()
{
pthread_t id1[2];
pthread_t id2[2];
int i;
int ret[2];
int ini1 = sem_init(&empty_sem, 0, 10);
int ini2 = sem_init(&full_sem, 0, 0);
if(ini1 && ini2 != 0)
{
printf("sem init failed \\n");
exit(1);
}
int ini3 = pthread_mutex_init(&mutex, 0);
if(ini3 != 0)
{
printf("mutex init failed \\n");
exit(1);
}
for(i = 0; i < 2; i++)
{
ret[i] = pthread_create(&id1[i], 0, product, (void *)(&i));
if(ret[i] != 0)
{
printf("product%d creation failed \\n", i);
exit(1);
}
}
for(i = 0; i < 2; i++)
{
ret[i] = pthread_create(&id2[i], 0, prochase, 0);
if(ret[i] != 0)
{
printf("prochase%d creation failed \\n", i);
exit(1);
}
}
for(i = 0; i < 2; i++)
{
pthread_join(id1[i],0);
pthread_join(id2[i],0);
}
exit(0);
}
| 0
|
#include <pthread.h>
long ninc_per_thread;
long a;
long b;
long r;
long * p;
pthread_mutex_t * m;
} arg_t;
void * f(void * arg_) {
arg_t * arg = (arg_t *)arg_;
long a = arg->a, b = arg->b;
long ninc_per_thread = arg->ninc_per_thread;
if (b - a == 1) {
int i;
for (i = 0; i < ninc_per_thread; i++) {
pthread_mutex_lock(arg->m);
arg->p[0]++;
pthread_mutex_unlock(arg->m);
}
arg->r = a;
} else {
long c = (a + b) / 2;
arg_t cargs[2] = { { ninc_per_thread, a, c, 0, arg->p, arg->m },
{ ninc_per_thread, c, b, 0, arg->p, arg->m } };
pthread_t tid;
pthread_create(&tid, 0, f, cargs);
f(cargs + 1);
pthread_join(tid, 0);
arg->r = cargs[0].r + cargs[1].r;
}
return 0;
}
pthread_mutex_t m[1];
int main(int argc, char ** argv) {
long nthreads = (argc > 1 ? atol(argv[1]) : 100);
long ninc_per_thread = (argc > 2 ? atol(argv[2]) : 10000);
pthread_mutex_init(m, 0);
long p[1] = { 0 };
arg_t arg[1] = { { ninc_per_thread, 0, nthreads, 0, p, m } };
pthread_t tid;
pthread_create(&tid, 0, f, arg);
pthread_join(tid, 0);
if (arg->r == (nthreads - 1) * nthreads / 2
&& arg->p[0] == nthreads * ninc_per_thread) {
printf("OK\\n");
return 0;
} else {
printf("NG: p = %ld != nthreads * ninc_per_thread = %ld\\n",
arg->p[0], nthreads * ninc_per_thread);
return 1;
}
}
| 1
|
#include <pthread.h>
void *thread_function(void *arg);
pthread_mutex_t work_mutex;
char work_area[1024];
int time_to_exit = 0;
int main() {
int res;
pthread_t a_thread;
void *thread_result;
res = thread_mutex_init(&work_mutex, 0);
if (res != 0) {
perror("Mutex initialization failed");
exit(1);
}
res = pthread_create(&a_thread, 0, thread_function, 0);
if (res != 0) {
perror("Thread creation failed");
exit(1);
}
pthread_mutex_lock(&work_mutex);
printf("Input some text. Enter 'end' to finish\\n");
while(!time_to_exit) {
fgets(work_area, 1024, stdin);
pthread_mutex_unlock(&work_mutex);
while(1) {
pthread_mutex_lock(&work_mutex);
if (work_area[0] != '\\0') {
pthread_mutex_unlock(&work_mutex);
sleep(1);
}
else {
break;
}
}
}
pthread_mutex_unlock(&work_mutex);
printf("\\nWaiting for thread to finish...\\n");
res = pthread_join(a_thread, &thread_result);
if (res != 0) {
perror("Thread join failed");
exit(1);
}
printf("Thread join failed\\n");
pthread_mutex_destroy(&work_mutex);
exit(0);
}
void *thread_function(void *arg) {
sleep(1);
pthread_mutex_lock(&work_mutex);
while(strncmp("end", work_area, 3) != 0) {
printf("You input %d characters\\n", strlen(work_area) - 1);
work_area[0] = '\\0';
pthread_mutex_unlock(&work_mutex);
sleep(1);
pthread_mutex_lock(&work_mutex);
while (work_area[0] == '\\0') {
pthread_mutex_unlock(&work_mutex);
sleep(1);
pthread_mutex_lock(&work_mutex);
}
time_to_exit = 1;
work_area[0] = '\\0';
pthread_mutex_unlock(&work_mutex);
}
time_to_exit = 1;
work_area[0] = '\\0';
pthread_mutex_unlock(&work_mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
extern char **environ;
pthread_mutex_t env_mutex;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
static void thread_init(void)
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&env_mutex, &attr);
pthread_mutexattr_destroy(&attr);
}
int getenv_r(const char *name, char *buf, int buflen)
{
int i, len, olen;
pthread_once(&init_done, thread_init);
len = strlen(name);
pthread_mutex_lock(&env_mutex);
for (i = 0; environ[i] != 0; i++) {
if ((strncmp(name, environ[i], len) == 0) &&
(environ[i][len] == '=')) {
olen = strlen(&environ[i][len+1]);
if (olen >= buflen) {
pthread_mutex_unlock(&env_mutex);
return(ENOSPC);
}
strcpy(buf, &environ[i][len+1]);
pthread_mutex_unlock(&env_mutex);
return(0);
}
}
pthread_mutex_unlock(&env_mutex);
return(ENOENT);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_rwlock_t rwlock;
pthread_cond_t cond;
static int do_output;
static void output(char *string)
{
if (!do_output)
return;
printf("%s", string);
}
void *thread_func(void *p)
{
output("thread_func\\n");
pthread_mutex_lock(&mutex);
output("got mutex lock\\n");
sleep(5);
pthread_mutex_unlock(&mutex);
output("thread done\\n");
return 0;
}
void *wrlock_thread(void *p)
{
pthread_rwlock_rdlock(&rwlock);
output("thread got read lock\\n");
sleep(2);
pthread_rwlock_unlock(&rwlock);
pthread_rwlock_wrlock(&rwlock);
output("thread got write lock\\n");
return 0;
}
void *condvar_thread(void *p)
{
int i;
pthread_mutex_lock(&count_mutex);
for (i=0; i < 10; i++)
{
output("Going for sleep for 1 sec\\n");
sleep(1);
}
pthread_cond_signal(&cond);
pthread_mutex_unlock(&count_mutex);
return 0;
}
void *condvar_wait_thread(void *p)
{
pthread_mutex_lock(&count_mutex);
pthread_cond_wait(&cond, &count_mutex);
output("thread wakeup on cond var\\n");
pthread_mutex_unlock(&count_mutex);
return 0;
}
int main(int argc, char *argv[])
{
pthread_t tid, tid2;
struct timespec abs_time;
do_output = (argc > 1 && strcmp("-v", argv[1]) == 0);
pthread_mutex_init(&mutex, 0);
pthread_mutex_lock(&mutex);
pthread_create(&tid, 0, thread_func, 0);
pthread_mutex_unlock(&mutex);
sleep(1);
while (1)
{
int ret;
clock_gettime(CLOCK_REALTIME, &abs_time);
abs_time.tv_sec += 1;
ret = pthread_mutex_timedlock(&mutex, &abs_time);
if (ret == ETIMEDOUT)
{
output("ETIMEDOUT\\n");
}
else if (ret == 0)
{
output("pthread_mutex_timedlock succ.\\n");
break;
}
}
pthread_mutex_destroy(&mutex);
pthread_join(tid, 0);
pthread_rwlock_init(&rwlock, 0);
pthread_create(&tid, 0, wrlock_thread, 0);
pthread_rwlock_rdlock(&rwlock);
sleep(1);
pthread_rwlock_unlock(&rwlock);
pthread_join(tid, 0);
pthread_cond_init(&cond, 0);
pthread_mutex_lock(&count_mutex);
pthread_create(&tid, 0, condvar_thread, 0);
pthread_cond_wait(&cond, &count_mutex);
pthread_cond_init(&cond, 0);
pthread_mutex_init(&count_mutex, 0);
pthread_mutex_lock(&count_mutex);
pthread_create(&tid, 0, condvar_thread, 0);
clock_gettime(CLOCK_REALTIME, &abs_time);
abs_time.tv_sec += 1;
if (pthread_cond_timedwait(&cond, &count_mutex, &abs_time) == ETIMEDOUT)
output("cond_timedwait ETIMEDOUT\\n");
pthread_cond_init(&cond, 0);
pthread_mutex_init(&count_mutex, 0);
pthread_create(&tid, 0, condvar_wait_thread, 0);
pthread_create(&tid2, 0, condvar_wait_thread, 0);
sleep(1);
pthread_mutex_lock(&count_mutex);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&count_mutex);
pthread_join(tid, 0);
pthread_join(tid2, 0);
return 0;
}
| 0
|
#include <pthread.h>
double *a, *b, sum;
int length;
} DOTDATA;
DOTDATA dotstr;
pthread_mutex_t mutexsum;
void *dotprod (void *rank){
int i, start, end, len;
double my_sum, *x, *y;
int my_rank = (int) rank;
len = dotstr.length;
start = my_rank*len;
end = start + len;
x = dotstr.a;
y = dotstr.b;
my_sum = 0;
for(i = start; i<end; i++){
my_sum += x[i]*y[i];
}
pthread_mutex_lock(&mutexsum);
dotstr.sum += my_sum;
pthread_mutex_unlock(&mutexsum);
return 0;
}
int main(int argc, char *argv[]){
printf("%d\\n",atoi(argv[1]));
int thread_num = atoi(argv[1]);
pthread_t threads[thread_num];
int i;
double *x = malloc(thread_num*10000000*sizeof(double));
double *y = malloc(thread_num*10000000*sizeof(double));
for (i = 0; i < thread_num*10000000; i++){
x[i] = 1;
y[i] = 1;
}
dotstr.length = 10000000;
dotstr.a = x;
dotstr.b = y;
dotstr.sum = 0;
pthread_mutex_init(&mutexsum, 0);
for(i = 0; i<thread_num; i++){
pthread_create(&threads[i], 0, dotprod, (void *) i);
}
for(i = 0; i<thread_num; i++){
pthread_join(threads[i], 0);
}
printf("Sum = %f\\n", dotstr.sum);
free(x);
free(y);
pthread_mutex_destroy(&mutexsum);
return 0;
}
| 1
|
#include <pthread.h>
static void* (*malloc0)(size_t size);
static void (*free0)(void* ptr);
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static int fd;
static void
init()
{
* (void**)&malloc0 = dlsym(RTLD_NEXT, "malloc");
* (void**)&free0 = dlsym(RTLD_NEXT, "free");
char* filename = getenv("MALLOC_TRACER_FILENAME");
fd = open(filename ? filename : "malloc_trace.log",
O_RDWR | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWOTH);
char* maps = getenv("MALLOC_TRACER_MAPS");
if (maps && strlen(maps) > 0) {
int src = open("/proc/self/maps", O_RDONLY);
int dst = open(maps,
O_RDWR | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWOTH);
char buf[(4 * 1024)];
ssize_t b;
while ((b = read(src, buf, sizeof(buf))) > 0) {
write(dst, buf, b);
}
close(src);
close(dst);
}
}
static void
fin()
{
close(fd);
}
struct layout_t {
struct layout *next;
void *ret;
};
static char hex2char(int hex)
{
if (hex < 10) {
return hex + '0';
}
return (hex - 10) + 'a';
}
static int hexdump(char* buf, const char* ptr, size_t length)
{
int idx = 0;
buf[idx++] = '0';
buf[idx++] = 'x';
for (int i = 0; i < length; ++i) {
const unsigned char c = ptr[length - 1 - i];
buf[idx++] = hex2char(c / 16);
buf[idx++] = hex2char(c % 16);
}
return idx;
}
static int
dump_callstack(char* buf)
{
int pos = 0;
struct layout_t* lo = __builtin_frame_address(0);
while (lo) {
void* caller = lo->ret;
buf[pos++] = ' ';
pos += hexdump(&buf[pos], (char*) &caller, sizeof(caller));
lo = (struct layout_t*) lo->next;
}
return pos;
}
void* malloc(size_t size)
{
void* ptr = malloc0(size);
char buf[(4 * 1024)];
int pos = 0;
buf[pos++] = 'm';
buf[pos++] = ' ';
pos += hexdump(&buf[pos], (char*) &ptr, sizeof(ptr));
buf[pos++] = ' ';
pos += hexdump(&buf[pos], (char*) &size, sizeof(size));
pos += dump_callstack(&buf[pos]);
buf[pos++] = '\\n';
pthread_mutex_lock(&mutex);
write(fd, buf, pos);
pthread_mutex_unlock(&mutex);
return ptr;
}
void free(void* ptr)
{
free0(ptr);
if (ptr == 0) return;
char buf[(4 * 1024)];
int pos = 0;
buf[pos++] = 'f';
buf[pos++] = ' ';
pos += hexdump(&buf[pos], (char*) &ptr, sizeof(ptr));
buf[pos++] = ' ';
size_t dummy = 0;
pos += hexdump(&buf[pos], (char*) &dummy, sizeof(dummy));
pos += dump_callstack(&buf[pos]);
buf[pos++] = '\\n';
pthread_mutex_lock(&mutex);
write(fd, buf, pos);
pthread_mutex_unlock(&mutex);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cnd = PTHREAD_COND_INITIALIZER;
struct global_data{
char task;
const int count;
};
void * task_a(void * ctx)
{
struct global_data *d = ctx;
int i;
printf("started task_a\\n");
printf("a before loop\\n");
for(i=0; i < d->count; ++i){
pthread_mutex_lock(&mtx);
printf("here\\n");
while(d->task != 'a') pthread_cond_wait(&cnd, &mtx);
printf("task_a: %d\\n",i);
image = capture_get_frame(ms);
d->task = 'b';
pthread_cond_signal(&cnd);
pthread_mutex_unlock(&mtx);
}
capture_close_stream(ms);
return 0;
}
void * task_b(void * ctx)
{
struct global_data *d = ctx;
int i;
printf("started task_b\\n");
for(i=0; i < d->count; ++i){
pthread_mutex_lock(&mtx);
while(d->task != 'b') pthread_cond_wait(&cnd, &mtx);
printf("b\\n");
d->task = 'a';
pthread_cond_signal(&cnd);
pthread_mutex_unlock(&mtx);
}
return 0;
}
int main()
{
struct global_data data = {0,10};
const char * c = "c";
media_stream * ms;
media_frame * image;
byte * b;
ms = capture_open_stream(c, c);
pthread_t imageThread;
pthread_t thread_b;
if(pthread_create(&imageThread, 0, task_a, &data)){
printf("Failed to create thread_a\\n");
exit(1);
}
if(pthread_create(&thread_b, 0, task_b, &data)){
printf("Failed to create thread_b\\n");
exit(2);
}
sleep(1);
pthread_mutex_lock(&mtx);
printf("setting task to a\\n");
data.task = 'a';
pthread_cond_signal(&cnd);
pthread_mutex_unlock(&mtx);
pthread_join(imageThread, 0);
pthread_join(thread_b, 0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t w_lock;
pthread_mutex_t r_lock;
int readcnt=0;
FILE *fp;
void *writer(void *args){
int pos=*(int*)args;
char ch;
pthread_mutex_lock(&w_lock);
fp=fopen("test.txt","a");
if(fp==0)
printf("\\nUnable to open file\\n");
else{
printf("\\nThe thread no. %d is writing in file\\n",pos);
printf("\\nEnter the text tobe entered\\n");
do{
scanf(" %c",&ch);
fputc(ch,fp);
}while(isalnum(ch));
}
fclose(fp);
sleep(1000);
pthread_mutex_unlock(&w_lock);
pthread_exit(0);
}
void *reader(void *args){
int pos=*(int*)args;
pthread_mutex_lock(&r_lock);
readcnt++;
char ch;
if(readcnt==1)
pthread_mutex_lock(&w_lock);
pthread_mutex_unlock(&r_lock);
fp=fopen("test.txt","r");
if(fp==0)
printf("\\nUnable to open file\\n");
else{
printf("\\nThe thread no. %d is reading the file\\n",pos);
printf("\\nhe is reading..\\n");
ch = fgetc(fp);
while (ch != EOF){
printf ("%c", ch);
ch = fgetc(fp);
}
pthread_mutex_lock(&r_lock);
readcnt--;
if(readcnt==0)
pthread_mutex_unlock(&w_lock);
pthread_mutex_unlock(&r_lock);
fclose(fp);
}
pthread_exit(0);
}
int main(){
pthread_mutex_init(&w_lock,0);
pthread_mutex_init(&r_lock,0);
pthread_t threadarray[10];
int bufferin[10];
int i=0;
int ch;
printf("Read write?\\n1:Write\\n2:Read");
scanf("%d",&ch);
switch(ch){
case 1:{
pthread_create(threadarray + i, 0 , writer , (bufferin + i) );
}
case 2:{
pthread_create(threadarray + i, 0 , reader , (bufferin + i) );
}
default:{
printf("choose something\\n");
}
}
i = 0;
for(;i<10;i++){
pthread_join(*(threadarray+i) ,0);
}
pthread_mutex_destroy(&r_lock);
pthread_mutex_destroy(&w_lock);
}
| 0
|
#include <pthread.h>
const char* const short_options = "hlsc";
const struct option long_options[] = {
{"help", 0, 0, 'h'},
{"lock", 0, 0, 'l'},
{"semaphore", 0, 0, 's'},
{"condition", 0, 0, 'c'},
{0, 0, 0 , 0}
};
void semaphore_case(void);
void* sem_thread_fun(void* arg);
void lock_case(void);
void* lock_thread_fun(void *arg);
void condition_case(void);
void* cond_thread_fun(void *arg);
void print_usage(void)
{
printf("Sychronization machanism for race condition\\n");
printf(" -h -help Display usage information\\n");
printf(" -l -lock Mutex/spinlock/rwlock\\n");
printf(" -s -semaphore thread/process semaphore\\n");
printf(" -c -condition condition variables\\n");
}
int main(int argc, char* argv[])
{
int option;
do {
option = getopt_long(argc, argv, short_options, long_options, 0);
switch(option)
{
case 'h':
print_usage();
break;
case 'l':
lock_case();
break;
case 's':
semaphore_case();
break;
case 'c':
condition_case();
break;
case -1:
break;
default:
print_usage();
break;
}
} while (option != -1);
}
void semaphore_case(void)
{
int ret;
sem_t sem;
printf("This is semaphore case\\n");
ret = sem_init(&sem, 0, 0);
if(ret)
{
printf("Semaphore init failed\\n");
exit(1);
}
pthread_t sem_thread;
ret = pthread_create(&sem_thread, 0, sem_thread_fun, &sem);
if(ret)
{
printf("create semaphore test thread failed\\n");
exit(1);
}
int count = 5;
while(count > 0)
{
sem_post(&sem);
sleep(3);
count--;
}
ret = pthread_cancel(sem_thread);
if(ret)
{
printf("cancel sem thread failed\\n");
exit(1);
}
pthread_join(sem_thread, 0);
sem_destroy(&sem);
}
void* sem_thread_fun(void* arg)
{
sem_t *sem = (sem_t*)arg;
while(1)
{
sem_wait(sem);
printf("This is sem_thread\\n");
}
}
void lock_case(void)
{
int ret;
pthread_t lock_thread;
printf("This is lock case\\n");
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, 0);
ret = pthread_create(&lock_thread, 0, lock_thread_fun, &mutex);
if(ret)
{
printf("create lock thread failed\\n");
exit(1);
}
sleep(1);
int count = 5;
while(count > 0)
{
pthread_mutex_lock(&mutex);
sleep(3);
pthread_mutex_unlock(&mutex);
printf("unlock in main thread\\n");
count--;
}
ret = pthread_cancel(lock_thread);
if(ret)
{
printf("cancel sem thread failed\\n");
exit(1);
}
pthread_join(lock_thread, 0);
}
void* lock_thread_fun(void *arg)
{
pthread_mutex_t *mutex = (pthread_mutex_t *)arg;
while(1)
{
pthread_mutex_lock(mutex);
printf("This is lock_thread_fun\\n");
sleep(1);
pthread_mutex_unlock(mutex);
printf("unlocked in lock thread\\n");
}
}
void condition_case(void)
{
int ret;
struct _cond {
int flag;
pthread_mutex_t mutex;
pthread_cond_t condition;
} cond;
printf("This is condition case\\n");
pthread_mutex_init(&cond.mutex, 0);
pthread_cond_init(&cond.condition, 0);
cond.flag = 0;
pthread_t cond_thread;
ret = pthread_create(&cond_thread, 0, cond_thread_fun, &cond);
if(ret)
{
printf("create cond thread failed\\n");
exit(1);
}
sleep(5);
pthread_mutex_lock(&cond.mutex);
printf("locked in main thread\\n");
cond.flag = 1;
pthread_cond_signal(&cond.condition);
pthread_mutex_unlock(&cond.mutex);
printf("unlocked in main thread\\n");
pthread_join(cond_thread, 0);
}
void *cond_thread_fun(void *arg)
{
struct _cond {
int flag;
pthread_mutex_t mutex;
pthread_cond_t condition;
} *cond;
cond = arg;
pthread_mutex_lock(&cond->mutex);
printf("locked in cond thread\\n");
while(cond->flag == 0)
{
printf("wait for condition ready\\n");
pthread_cond_wait(&cond->condition, &cond->mutex);
}
pthread_mutex_unlock(&cond->mutex);
printf("unlocked in cond thread\\n");
}
| 1
|
#include <pthread.h>
int N, C, D, tmin, tmax;
pthread_mutex_t hashi[20];
pthread_t filosofo[20];
int id[20], refeicoes[20];
enum _status { PENSANDO, FAMINTO, COMENDO } status[20];
void pegaHashi(int f){
pthread_mutex_lock(&hashi[f]);
printf("Filosofo %d esta com fome e pegou o 1o garfo\\n", f);
pthread_mutex_lock(&hashi[(f+1)%N]);
printf("Filosofo %d continua com fome e pegou o 2o garfo\\n", f);
}
void soltaHashi(int f){
pthread_mutex_unlock(&hashi[f]);
pthread_mutex_unlock(&hashi[(f+1)%N]);
printf("Filosofo %d acabou de comer pela %da vez e liberou os garfos\\n",
f, ++refeicoes[f]);
}
void realizaAtividade(int f, const char *s){
int tempo = (rand() % (1 + tmax - tmin)) + tmin;
printf("Filosofo %d %s por %.3lfs...\\n", f, s, (double) tempo / 1000.0);
usleep(tempo);
}
void *vidaDeUmFilosofo(void *arg){
int f = *(int*) arg;
while(refeicoes[f] < C){
status[f] = PENSANDO;
realizaAtividade(f, "pensando");
status[f] = FAMINTO;
pegaHashi(f);
status[f] = COMENDO;
realizaAtividade(f, "comendo");
soltaHashi(f);
}
pthread_exit(0);
}
int main(int argc, char **argv){
int i;
if(argc == 1) scanf("%d %d %d %d %d", &N, &C, &D, &tmin, &tmax);
else if(argc == 6){
sscanf(argv[1], "%d", &N);
sscanf(argv[2], "%d", &C);
sscanf(argv[3], "%d", &D);
sscanf(argv[4], "%d", &tmin);
sscanf(argv[5], "%d", &tmax);
}
else{
fprintf(stderr, "uso: %s N C D Min Max", argv[0]);
fprintf(stderr, "onde:"
" N = quantidade de filosofos"
" C = maximo de refeicoes"
" D = 0 se permite deadlock; 1 caso contrario"
" Min = tempo minimo para dormir ou comer"
" Max = tempo maximo para dormir ou comer"
);
return 1;
}
srand(time(0));
memset(refeicoes, 0, sizeof(refeicoes));
for(i = 0; i < N; i++){
pthread_mutex_init(&hashi[i], 0);
}
for(i = 0; i < N; i++){
id[i] = i;
pthread_create(&filosofo[i], 0, &vidaDeUmFilosofo, (void*) &id[i]);
}
while(1);
return 0;
}
| 0
|
#include <pthread.h>
struct producers {
int buffer[4];
pthread_mutex_t lock;
int readpos, writepos;
pthread_cond_t notempty;
pthread_cond_t notfull;
};
void init(struct producers *b) {
pthread_mutex_init(&b->lock, 0);
pthread_cond_init(&b->notempty, 0);
pthread_cond_init(&b->notfull, 0);
b->readpos = 0;
b->writepos = 0;
}
void put(struct producers *b, int data) {
pthread_mutex_lock(&b->lock);
while ((b->writepos + 1) % 4 == b->readpos) {
pthread_cond_wait(&b->notfull, &b->lock);
}
b->buffer[b->writepos] = data;
b->writepos++;
if (b->writepos >= 4)
b->writepos = 0;
pthread_cond_signal(&b->notempty);
pthread_mutex_unlock(&b->lock);
}
int get(struct producers *b) {
int data;
pthread_mutex_lock(&b->lock);
while (b->writepos == b->readpos) {
pthread_cond_wait(&b->notempty, &b->lock);
}
data = b->buffer[b->readpos];
b->readpos++;
if (b->readpos >= 4)
b->readpos = 0;
pthread_cond_signal(&b->notfull);
pthread_mutex_unlock(&b->lock);
return data;
}
struct producers buffer;
void *producer(void *data) {
int n;
for (n = 0; n < 10; n++) {
printf("Producer : %d-->\\n", n);
put(&buffer, n);
}
put(&buffer, (-1));
return 0;
}
void *consumer(void *data) {
int d;
while (1) {
d = get(&buffer);
if (d == (-1))
break;
printf("Consumer: --> %d\\n", d);
}
return 0;
}
int main() {
pthread_t tha, thb;
void *retval;
init(&buffer);
pthread_create(&tha, 0, producer, 0);
pthread_create(&thb, 0, consumer, 0);
pthread_join(tha, &retval);
pthread_join(thb, &retval);
return 0;
}
| 1
|
#include <pthread.h>
count_t total_ccount = 0;
count_t total_wcount = 0;
count_t total_lcount = 0;
char **file_list = 0;
int file_count;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct file_data {
count_t *ccount;
count_t *wcount;
count_t *lcount;
};
static void
error_print (int perr, char *fmt, va_list ap)
{
vfprintf (stderr, fmt, ap);
if (perr)
perror (" ");
else
fprintf (stderr, "\\n");
exit (1);
}
static void
errf (char *fmt, ...)
{
va_list ap;
__builtin_va_start((ap));
error_print (0, fmt, ap);
;
}
static void
perrf (char *fmt, ...)
{
va_list ap;
__builtin_va_start((ap));
error_print (1, fmt, ap);
;
}
void
report (char *file, count_t ccount, count_t wcount, count_t lcount)
{
printf ("%6lu %6lu %6lu %s\\n", lcount, wcount, ccount, file);
}
static int
isword (unsigned char c)
{
return isalpha (c);
}
int
getword (FILE *fp, count_t *ccount, count_t *wcount, count_t *lcount)
{
int c;
int word = 0;
if (feof (fp))
return 0;
while ((c = getc (fp)) != EOF)
{
if (isword (c))
{
(*wcount)++;
break;
}
(*ccount)++; if ((c) == '\\n') (*lcount)++;;
}
for (; c != EOF; c = getc (fp))
{
(*ccount)++; if ((c) == '\\n') (*lcount)++;;
if (!isword (c))
break;
}
return c != EOF;
}
void
counter (char *file, count_t *ccount, count_t *wcount, count_t *lcount)
{
FILE *fp = fopen (file, "r");
if (!fp)
perrf ("cannot open file `%s'", file);
*ccount = *wcount = *lcount = 0;
while (getword (fp, ccount, wcount, lcount))
;
fclose (fp);
}
int
get_index() {
static int i = 0;
int j;
pthread_mutex_lock(&mutex);
j = i+1;
i++;
pthread_mutex_unlock(&mutex);
if (j < file_count)
return j;
else
return -1;
}
void *
parallel_wc(void *data) {
file_data *my_files = (file_data*) data;
int i;
while((i = get_index()) != -1) {
counter(file_list[i], &(my_files->ccount[i]),
&(my_files->wcount[i]),
&(my_files->lcount[i]));
}
return data;
}
int
main (int argc, char **argv)
{
int i, j;
pthread_t *tid;
file_data *list;
count_t cc, wc, lc;
int no_cpu;
no_cpu = sysconf( _SC_NPROCESSORS_ONLN );
tid = (pthread_t *) malloc (no_cpu * sizeof(pthread_t));
if (argc < 2)
errf ("usage: wc FILE [FILE...]");
file_list = argv;
file_count = argc;
for (i = 0; i < no_cpu; i++) {
list = (file_data *) malloc (sizeof(file_data));
list->ccount = (count_t *) malloc ((argc+1)*sizeof(count_t));
list->wcount = (count_t *) malloc ((argc+1)*sizeof(count_t));
list->lcount = (count_t *) malloc ((argc+1)*sizeof(count_t));
for(j = 1; j <= argc; j++) {
list->ccount[j] = list->wcount[j] = list->lcount[j] = 0;
}
pthread_create(&tid[i], 0, parallel_wc, (void *)list);
}
for(i = 0; i < no_cpu; i++) {
pthread_join(tid[i], (void *)&list);
for(j = 1; j < argc; j++) {
if (list->ccount[j] && list->wcount[j] && list->lcount[j]) {
report(argv[j], list->ccount[j], list->wcount[j], list->lcount[j]);
total_ccount += list->ccount[j];
total_wcount += list->wcount[j];
total_lcount += list->lcount[j];
}
}
}
if (argc > 2)
report ("total", total_ccount, total_wcount, total_lcount);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer = 0;
void * producer(void *ptr)
{
int i;
for(i = 0; i < 20; i++)
{
printf("producer locking critical region\\n");
pthread_mutex_lock(&the_mutex);
printf("producer producing %d\\n", i);
while(buffer != 0)
{
printf("buffer not empty, producer sleeping\\n");
pthread_cond_wait(&condp, &the_mutex);
}
buffer = i;
printf("producer signaling consumer to wake up\\n");
pthread_cond_signal(&condc);
printf("producer releasing lock on critical region\\n");
pthread_mutex_unlock(&the_mutex);
}
}
void * consumer(void *ptr)
{
int i;
for(i = 1; i < 20; i++)
{
printf("consumer locking critical region\\n");
pthread_mutex_lock(&the_mutex);
printf("consumer consuming %d\\n", i);
while(buffer == 0)
{
printf("buffer is empty, consumer sleeping\\n");
pthread_cond_wait(&condc, &the_mutex);
}
buffer = 0;
printf("consumer signaling producer to wake up\\n");
pthread_cond_signal(&condp);
printf("consumer releasing lock on critical region\\n");
pthread_mutex_unlock(&the_mutex);
}
}
int main()
{
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>
pthread_mutex_t tabaco;
pthread_mutex_t papel;
pthread_mutex_t lanzaLLamas;
pthread_mutex_t ocupado0;
pthread_mutex_t ocupado1;
pthread_mutex_t ocupado2;
int hay_tabaco;
int hay_papel;
int hay_lanzaLLamas;
int esta_ocupado0;
int esta_ocupado1;
int esta_ocupado2;
void *agente(void *);
void *fumador(void *);
void fumar(int);
int main() {
pthread_t agente_cancerigeno;
pthread_t fumadores[3];
int *arg0, *arg1, *arg2;
arg0 = (int *)malloc(sizeof(*arg0));
arg1 = (int *)malloc(sizeof(*arg1));
arg2 = (int *)malloc(sizeof(*arg2));
*arg0 = 0;
*arg1 = 1;
*arg2 = 2;
pthread_create(&agente_cancerigeno, 0, agente, 0);
pthread_create(&fumadores[0], 0, fumador, arg0);
pthread_create(&fumadores[1], 0, fumador, arg1);
pthread_create(&fumadores[2], 0, fumador, arg2);
pthread_join(agente, 0);
pthread_join(fumadores[0], 0);
pthread_join(fumadores[1], 0);
pthread_join(fumadores[2], 0);
return 0;
}
void *agente(void *arg) {
while (1) {
pthread_mutex_lock(&tabaco);
if (hay_tabaco) {
pthread_mutex_unlock(&tabaco);
} else {
pthread_mutex_lock(&ocupado0);
if (esta_ocupado0) {
printf("Apurate maldito fumador con el tabaco\\n");
pthread_mutex_unlock(&ocupado0);
pthread_mutex_unlock(&tabaco);
} else {
printf("Gracias por el tabaco\\n");
hay_tabaco = 1;
pthread_mutex_unlock(&ocupado0);
pthread_mutex_unlock(&tabaco);
sleep(15);
}
}
if (hay_papel) {
pthread_mutex_unlock(&papel);
} else {
pthread_mutex_lock(&ocupado1);
if (esta_ocupado1) {
printf("Apurate maldito fumador con el papel\\n");
pthread_mutex_unlock(&ocupado1);
pthread_mutex_unlock(&papel);
} else {
printf("Gracias por el papel\\n");
hay_papel = 1;
pthread_mutex_unlock(&ocupado1);
pthread_mutex_unlock(&papel);
sleep(15);
}
}
if (hay_lanzaLLamas) {
pthread_mutex_unlock(&lanzaLLamas);
} else {
pthread_mutex_lock(&ocupado2);
if (esta_ocupado2) {
printf("Apurate maldito fumador con el fuego\\n");
pthread_mutex_unlock(&ocupado2);
pthread_mutex_unlock(&lanzaLLamas);
} else {
printf("Gracias por el fuego\\n");
hay_lanzaLLamas = 1;
pthread_mutex_unlock(&ocupado2);
pthread_mutex_unlock(&lanzaLLamas);
sleep(15);
}
}
}
}
void *fumador(void *arg) {
int m = *((int *)arg);
while (1) {
if (m == 0) {
fumar(0);
} else if (m == 1) {
fumar(1);
} else if (m == 2) {
fumar(2);
} else {
printf("Algo salio pero muy mal!!!\\n");
}
}
}
void fumar(int m) {
pthread_mutex_lock(&tabaco);
pthread_mutex_lock(&papel);
pthread_mutex_lock(&lanzaLLamas);
if (hay_lanzaLLamas && hay_papel && hay_tabaco) {
printf("Me voy a echar un rico cigarro\\n");
hay_lanzaLLamas = 0;
hay_papel = 0;
hay_tabaco = 0;
pthread_mutex_unlock(&tabaco);
pthread_mutex_unlock(&papel);
pthread_mutex_unlock(&lanzaLLamas);
if (m == 0) {
pthread_mutex_lock(&ocupado0);
esta_ocupado0 = 1;
pthread_mutex_unlock(&ocupado0);
} else if (m == 1) {
pthread_mutex_lock(&ocupado1);
esta_ocupado1 = 1;
pthread_mutex_unlock(&ocupado1);
} else if (m == 2) {
pthread_mutex_lock(&ocupado2);
esta_ocupado2 = 1;
pthread_mutex_unlock(&ocupado2);
} else {
printf("Algo salio pero muy mal!!!\\n");
}
sleep(10);
printf("Listo, voy a esperarme o me va dar cancer\\n");
if (m == 0) {
pthread_mutex_lock(&ocupado0);
esta_ocupado0 = 0;
pthread_mutex_unlock(&ocupado0);
} else if (m == 1) {
pthread_mutex_lock(&ocupado1);
esta_ocupado1 = 0;
pthread_mutex_unlock(&ocupado1);
} else if (m == 2) {
pthread_mutex_lock(&ocupado2);
esta_ocupado2 = 0;
pthread_mutex_unlock(&ocupado2);
} else {
printf("Algo salio pero muy mal!!!\\n");
}
sleep(20);
printf("Ya puedo fumar\\n");
} else {
pthread_mutex_unlock(&tabaco);
pthread_mutex_unlock(&papel);
pthread_mutex_unlock(&lanzaLLamas);
}
}
| 0
|
#include <pthread.h>
int post_signal(pthread_t pth, int sig)
{
int res;
if( pth <= 0 ) {
return FAIL;
}
res = pthread_kill(pth, sig);
if(res != 0) {
LOG(m_res, ERROR, "send signal to thread failed\\n");
return FAIL;
}
LOG(m_res, DEBUG, "send signal to thread success\\n");
return SUCCESS;
}
int init_try_time()
{
int res;
inform_retry = 0;
res = pthread_mutex_init(&try_time_lock, 0);
if(res != 0) {
LOG(m_res, ERROR, "Mutex try_time initialization failed.\\n");
return FAIL;
} else {
LOG(m_res, DEBUG, "Mutex try_time initialization success\\n");
}
return SUCCESS;
}
int get_max_try_time()
{
int result;
pthread_mutex_lock(&try_time_lock);
result = max_try_time;
pthread_mutex_unlock(&try_time_lock);
return result;
}
void set_max_try_time(int time)
{
pthread_mutex_lock(&try_time_lock);
max_try_time = time;
pthread_mutex_unlock(&try_time_lock);
}
int reset_sys_sem()
{
sem_destroy(&SEM_SEND);
sem_destroy(&SEM_RECV);
sem_destroy(&SEM_HANDLER_ABORT);
sem_init(&SEM_SEND, 0, 0);
sem_init(&SEM_RECV, 0, 0);
sem_init(&SEM_HANDLER_ABORT, 0, 0);
return SUCCESS;
}
int init_conf_path()
{
DIR *dp;
if((conf_dir[0] != '/') || (conf_dir[strlen(conf_dir)-1] != '/')) {
printf("the path of configure file directory should be /dir/.\\n");
return FAIL;
}
if((dp = opendir(conf_dir)) == 0) {
printf("can not open directory: %s\\n", conf_dir);
return FAIL;
}
sprintf(dl_conf_path, "%sdl.conf", conf_dir);
sprintf(rbc_conf_path, "%srbc.conf", conf_dir);
sprintf(attri_conf_path, "%sattri.conf", conf_dir);
sprintf(conn_req_conf_path, "%sconn_req.conf", conf_dir);
sprintf(log_file_bak, "%scpe.log.bak", conf_dir);
sprintf(param_conf_path, "%sparam.xml", conf_dir);
sprintf(agent_conf_path, "%sagent.conf", conf_dir);
closedir(dp);
return SUCCESS;
}
time_t dev_get_cur_time()
{
time_t cur_time;
cur_time = time((time_t *)0);
LOG(m_device, DEBUG, "current time is %ld\\n", cur_time);
return cur_time;
}
| 1
|
#include <pthread.h>
sem_t even_lock, odd_lock;
pthread_mutex_t even_mutex, odd_mutex;
void * even_thread(void *args) {
int i = 0;
while (i < 10) {
sem_wait(&even_lock);
sleep(random()%3);
printf("%d\\n", i);
i+=2;
sem_post(&odd_lock);
}
pthread_exit(0);
}
void * odd_thread(void *args) {
int i = 1;
while (i < 10) {
sem_wait(&odd_lock);
sleep(random()%4);
printf("%d\\n", i);
i+=2;
sem_post(&even_lock);
}
pthread_exit(0);
}
void * even_thread2(void *args) {
int i = 0;
while (i < 10) {
pthread_mutex_lock(&even_mutex);
sleep(random()%3);
printf("%d\\n", i);
i+=2;
pthread_mutex_unlock(&odd_mutex);
}
pthread_exit(0);
}
void * odd_thread2(void *args) {
int i = 1;
while (i < 10) {
pthread_mutex_lock(&odd_mutex);
sleep(random()%4);
printf("%d\\n", i);
i+=2;
pthread_mutex_unlock(&even_mutex);
}
pthread_exit(0);
}
int main() {
pthread_t thread[2];
sem_init(&even_lock, 0, 1);
sem_init(&odd_lock, 0, 0);
printf("Solution semaphores:\\n");
pthread_create(&thread[0], 0, even_thread, 0);
pthread_create(&thread[1], 0, odd_thread, 0);
pthread_join(thread[0], 0);
pthread_join(thread[1], 0);
pthread_mutex_init(&even_mutex, 0);
pthread_mutex_init(&odd_mutex, 0);
printf("Solution mutexes:\\n");
pthread_create(&thread[0], 0, even_thread2, 0);
pthread_create(&thread[1], 0, odd_thread2, 0);
pthread_join(thread[0], 0);
pthread_join(thread[1], 0);
sem_destroy(&even_lock);
sem_destroy(&odd_lock);
pthread_mutex_destroy(&even_mutex);
pthread_mutex_destroy(&odd_mutex);
return 0;
}
| 0
|
#include <pthread.h>
static inline bool irq_masked(intr) {
return intr >= __NR_INTR_MASK_MIN
&& intr <= __NR_INTR_MASK_MAX
&& intr_line.intr_masked;
}
static void reset_all_intrs(void) {
pthread_mutex_lock(&intr_line.intr_mutex);
intr_line.intr[0] = 0;
intr_line.intr[1] = 0;
intr_line.intr[2] = 0;
intr_line.intr[3] = 0;
intr_line.intr_masked = 0;
pthread_mutex_unlock(&intr_line.intr_mutex);
}
void init_pic(void) {
pthread_mutex_init(&intr_line.intr_mutex, 0);
reset_all_intrs();
}
int raise_intr(int intr_num) {
pthread_mutex_lock(&intr_line.intr_mutex);
if (irq_masked(intr_num));
return -1;
if (intr_num < 64) {
(set_bit64(intr_num,&intr_line.intr[0]));
} else if (intr_num >= 64 && intr_num < 128) {
(set_bit64(intr_num%64,&intr_line.intr[1]));
} else if (intr_num >= 128 && intr_num < 192) {
(set_bit64(intr_num%128,&intr_line.intr[2]));
} else {
(set_bit64(intr_num%192,&intr_line.intr[3]));
}
pthread_mutex_unlock(&intr_line.intr_mutex);
return 0;
}
| 1
|
#include <pthread.h>
const char* SPLITTER = "\\n--------------------------------------------------\\n";
const int ARRAYS_NUMBER = 4;
char* DEFAULT_SORTING_MODE = "ASC";
int workersCompleted = 0;
pthread_mutex_t lock;
struct bubbleSortArgs {
int* array;
int arraySize;
char* mode;
};
int* createArray(int arraySize) {
return (int*) malloc (arraySize * sizeof(int));
}
int* cloneArray(int* array, int arraySize){
int* cloneArray = createArray(arraySize);
for(int i = 0; i < arraySize; i++){
cloneArray[i] = array[i];
}
return cloneArray;
}
int* generateArray(int arraySize) {
int* result = createArray(arraySize);
for(int i = 0; i < arraySize; i++){
result[i] = rand() % 100;
}
return result;
}
void* bubbleSort(void* arg) {
struct bubbleSortArgs* args = (struct bubbleSortArgs*) arg;
int* copyArray = cloneArray(args->array, args->arraySize);
for(int i = 0; i < args->arraySize; i++){
for(int j = i; j < args->arraySize; j++) {
if( (strcmp(args->mode, DEFAULT_SORTING_MODE) == 0 && copyArray[i] > copyArray[j]) ||
(strcmp(args->mode, DEFAULT_SORTING_MODE) != 0 && copyArray[i] < copyArray[j])) {
copyArray[i] += copyArray[j];
copyArray[j] = copyArray[i] - copyArray[j];
copyArray[i] = copyArray[i] - copyArray[j];
}
}
}
pthread_mutex_lock(&lock);
workersCompleted++;
pthread_mutex_unlock(&lock);
return copyArray;
}
void displayUsage(char* message){
char buffer[256];
snprintf(buffer, sizeof(buffer), "%s%s%s%s%s%s%s",
message,
SPLITTER,
"Usage help:\\n",
"-r\\t- generate random array;\\n",
"-s\\t- set size of array;\\n" ,
"-m\\t- set sorting mode (asc/desc).", SPLITTER);
printf("%s", buffer);
}
void displayArray(int* array, int arraySize) {
printf("\\nArray values: ");
if(arraySize > 100) arraySize = 100;
for(int i = 0; i < arraySize; i++) {
printf("%d ", array[i]);
}
if(arraySize > 99) printf("...");
}
int main(int argc, char* argv[]) {
if(argc == 0)
displayUsage("");
int generateArrays = 1;
int arraySize = 0;
char* mode = DEFAULT_SORTING_MODE;
pthread_mutex_init(&lock, 0);
for(int i = 0; i < argc; i++){
printf("%d - %s | ", i, argv[i]);
if(strcmp(argv[i], "-r") == 0) { generateArrays = 1; }
else if(strcmp(argv[i], "-s") == 0) { arraySize = atoi(argv[i+1]); i++; }
else if(strcmp(argv[i], "-m") == 0) { mode = argv[i+1]; i++; }
}
struct bubbleSortArgs* arrays = (struct bubbleSortArgs*) malloc (ARRAYS_NUMBER * sizeof(struct bubbleSortArgs));
if(generateArrays == 1) {
srand(time(0));
for(int i = 0; i < ARRAYS_NUMBER; i++){
arrays[i].array = generateArray(arraySize);
arrays[i].arraySize = arraySize;
arrays[i].mode = mode;
}
}
else {
}
if(strcmp(mode, "ASC") != 0 && strcmp(mode, "DESC") != 0) {
mode = DEFAULT_SORTING_MODE;
}
printf("\\nOrigin:");
for(int i = 0; i < ARRAYS_NUMBER; i++) {
displayArray(arrays[i].array, arrays[i].arraySize);
}
struct timeval stop, start;
gettimeofday(&start, 0);
pthread_t threads[ARRAYS_NUMBER];
for(int i = 0; i < ARRAYS_NUMBER; i++) {
if(pthread_create(&threads[i], 0, bubbleSort, &arrays[i]) == 0)
;
else
;
}
while(workersCompleted < ARRAYS_NUMBER) {
nanosleep((const struct timespec[]) {{ 0, 100000000L }}, 0);
}
gettimeofday(&stop, 0);
for(int i = 0; i < ARRAYS_NUMBER; i++) {
int* result = (int*) malloc(arraySize * sizeof(int));
pthread_join(threads[i], (void**)&result);
free(arrays[i].array);
arrays[i].array = result;
}
printf("\\n\\nResult:");
for(int i = 0; i < ARRAYS_NUMBER; i++) {
displayArray(arrays[i].array, arrays[i].arraySize);
}
printf("%sTotal time is %f%s", SPLITTER, (stop.tv_sec - start.tv_sec) * 1000.0f + (stop.tv_usec - start.tv_usec) / 1000.0f, SPLITTER);
for(int i = 0; i < ARRAYS_NUMBER; i++) {
free(arrays[i].array);
}
free(arrays);
pthread_mutex_destroy(&lock);
return 0;
}
| 0
|
#include <pthread.h>
struct arg_set{
char *fname;
int count;
};
struct arg_set *mailbox;
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t flag=PTHREAD_COND_INITIALIZER;
int main(int ac,char *av[]){
pthread_t t1,t2;
struct arg_set args1,args2;
void *count_words(void *);
int reports_in=0;
int total_words=0;
if(ac!=3){
printf("usage: %s file1 file2",av[0]);
exit(1);
}
args1.fname=av[1];
args1.count=0;
pthread_create(&t1,0,count_words,(void *)&args1);
args2.fname=av[2];
args2.count=0;
pthread_create(&t2,0,count_words,(void *)&args2);
while(reports_in<2){
printf("MAIN:waiting for flag to go up\\n");
pthread_cond_wait(&flag,&lock);
printf("MAIN:wow!flag was raised,i have the lock\\n");
printf("%7d: %s\\n",mailbox->count,mailbox->fname);
total_words+=mailbox->count;
if(mailbox==&args1)
pthread_join(t1,0);
if(mailbox==&args2)
pthread_join(t2,0);
mailbox=0;
pthread_cond_signal(&flag);
reports_in++;
}
printf("%7d: total words\\n",total_words);
}
void *count_words(void *a){
struct arg_set *args=a;
FILE *fp;
int c,prevc='\\0';
if((fp=fopen(args->fname,"r"))!=0){
while((c=getc(fp))!=EOF){
args->count++;
prevc=c;
}
fclose(fp);
}
else
perror(args->fname);
printf("count:waiting to get lock\\n");
pthread_mutex_lock(&lock);
printf("count:have lock,storing data\\n");
if(mailbox!=0){
pthread_cond_wait(&flag,&lock);
mailbox=args;
printf("count:raising flag\\n");
pthread_cond_signal(&flag);
printf("count:unlocking box\\n");
pthread_mutex_unlock(&lock);
return 0;
}
}
| 1
|
#include <pthread.h>
int *arr;
int num;
} Arr_Num;
int n, v[50000000], step;
Arr_Num *an_list[50000000];
pthread_t tid[50000000], tid2[50000000];
pthread_mutex_t mutex;
int cmp(const void *a, const void *b) {
return *(int*)a - *(int*)b;
}
int min(int a, int b) {
return a < b ? a : b;
}
int _ceil(int a, int b) {
if (a % b == 0) {
return a / b;
}
else {
return a / b + 1;
}
}
void *sort(void *arg) {
pthread_mutex_lock(&mutex);
long idx = (long)arg;
printf("Handling elements:\\n");
int *_arr = an_list[idx]->arr, _num = an_list[idx]->num;
for (int i = 0; i < _num; i++) {
printf("%d%s", _arr[i], i+1 == _num ? "\\n" : " ");
}
printf("Sorted %d elements.\\n", _num);
pthread_mutex_unlock(&mutex);
qsort(_arr, _num, sizeof(int), cmp);
return (void*)0;
}
void *merge(void *arg) {
long L = (long)arg, R = L + step/2;
int nl = an_list[L]->num, nr = an_list[R]->num, total = nl + nr;
int dup = 0;
int i = 0, il = 0, ir = 0;
int *tmp = (int*)malloc(sizeof(int)*total);
while (i < total && il < nl && ir < nr) {
int d = an_list[L]->arr[il] - an_list[R]->arr[ir];
if (d <= 0) {
tmp[i++] = an_list[L]->arr[il++];
if (d == 0) {
dup++;
}
}
else if (d > 0) {
tmp[i++] = an_list[R]->arr[ir++];
}
}
while (il < nl) {
tmp[i++] = an_list[L]->arr[il++];
}
while (ir < nr) {
tmp[i++] = an_list[R]->arr[ir++];
}
pthread_mutex_lock(&mutex);
printf("Handling elements:\\n");
for (int i = 0; i < total; i++) {
printf("%d%s", an_list[L]->arr[i], i+1 == total ? "\\n" : " ");
}
printf("Merged %d and %d elements with %d duplicates.\\n", nl, nr, dup);
pthread_mutex_unlock(&mutex);
an_list[L]->num = total;
for (int i = 0; i < total; i++) {
an_list[L]->arr[i] = tmp[i];
}
free(tmp);
return (void*)0;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: ./merger [segment_size]\\n");
return -1;
}
int seg_size = atoi(argv[1]);
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &v[i]);
}
int thr_num = _ceil(n, seg_size);
for (int i = 0; i < thr_num; i++) {
an_list[i] = (Arr_Num*)malloc(sizeof(Arr_Num));
an_list[i]->arr = v + i*seg_size;
an_list[i]->num = min(seg_size, n - i*seg_size);
}
pthread_mutex_init(&mutex, 0);
for (long i = 0; i < thr_num; i++) {
pthread_create(&tid[i], 0, sort, (void*)i);
}
for (long i = 0; i < thr_num; i++) {
pthread_join(tid[i], 0);
}
step = 2;
int cnt = thr_num;
while (cnt > 1) {
int round = cnt / 2;
for (long i = 0; i < round; i++) {
pthread_create(&tid2[i], 0, merge, (void*)(i * step));
}
for (long i = 0; i < round; i++) {
pthread_join(tid2[i], 0);
}
cnt -= round;
step *= 2;
}
for (int i = 0; i < n; i++) {
printf("%d%s", v[i], i+1 == n ? "\\n" : " ");
}
printf("\\n");
for (int i = 0; i < thr_num; i++) {
free(an_list[i]);
}
pthread_mutex_destroy(&mutex);
return 0;
}
| 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>
char* shm;
pthread_mutex_t* mutex;
int bNeedInit = 0;
char* attach_shm()
{
int fd = shm_open("/share_m", O_RDWR|O_CREAT|O_EXCL, 0777);
if(fd > 0)
{
ftruncate(fd, 4096);
bNeedInit = 1;
}
else
{
fd = shm_open("/share_m", O_RDWR, 0777);
}
printf("fd is %d\\n", fd);
void* ptr = mmap(0, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if(ptr == MAP_FAILED)
{
printf("map error");
}
return ptr;
}
int main()
{
shm = attach_shm();
strcpy((char*)shm, "hello");
mutex = (pthread_mutex_t*)(shm+10);
if(bNeedInit)
{
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_setpshared(&mutexattr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(mutex, &mutexattr);
}
pthread_mutex_lock(mutex);
printf("get mutex\\n");
getchar();
printf("ready to release mutex\\n");
pthread_mutex_unlock(mutex);
printf("release mutex done\\n");
shm_unlink("/share_m");
}
| 0
|
#include <pthread.h>
pthread_mutex_t cond_mutex;
pthread_cond_t cond;
int count = 0;
void* function_cond1(void*);
void* function_cond2(void*);
void practice_cond();
void practice_cond() {
pthread_t thread1,thread2;
pthread_mutex_init(&cond_mutex, 0);
pthread_cond_init(&cond,0);
pthread_create(&thread1, 0, function_cond1, (void*)1);
pthread_create(&thread2, 0, function_cond2, (void*)2);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
printf("Final count:%d\\n",count);
}
void* function_cond1(void *msg){
for(;;) {
printf("functionCount1 receive\\n");
pthread_mutex_lock(&cond_mutex);
pthread_cond_wait(&cond,&cond_mutex);
count++;
printf("Counter value functionCount1: %d\\n",count);
pthread_mutex_unlock(&cond_mutex);
if(count>=10) return 0;
}
}
void* function_cond2(void *msg){
for(;;) {
printf("functionCount2 receive\\n");
pthread_mutex_lock(&cond_mutex);
if(count <3 || count >6) {
pthread_cond_signal(&cond);
} else {
count++;
printf("Counter value functionCount2: %d\\n",count);
}
pthread_mutex_unlock(&cond_mutex);
if(count>=10) return 0;
}
}
| 1
|
#include <pthread.h>
void *mathProfArrive();
void *mathProfLeave();
void *csProfArrive();
void *csProfLeave();
void delay(int);
int sign_value = -1;
int numCsProfsInRoom = 0;
int numMathProfsInRoom = 0;
pthread_mutex_t sign_mutex;
pthread_cond_t csProfsCv;
pthread_cond_t mathProfsCv;
int main()
{
pthread_mutex_init(&sign_mutex,0);
pthread_cond_init(&csProfsCv,0);
pthread_cond_init(&mathProfsCv,0);
pthread_t mathProf1,mathProf2,csProf1,csProf2;
pthread_create(&mathProf1, 0, mathProfArrive,0);
pthread_create(&mathProf2, 0, mathProfArrive,0);
pthread_create(&csProf1, 0, csProfArrive,0);
pthread_create(&csProf1, 0, csProfArrive,0);
pthread_join(mathProf1,0);
pthread_join(mathProf2,0);
pthread_join(csProf1,0);
pthread_join(csProf2,0);
pthread_mutex_destroy(&sign_mutex);
pthread_cond_destroy(&csProfsCv);
pthread_cond_destroy(&mathProfsCv);
return 0;
}
void *mathProfArrive()
{
printf("Math prof arrives\\n");
fflush(stdout);
pthread_mutex_lock(&sign_mutex);
while (sign_value == 0)
{
pthread_cond_wait(&mathProfsCv, &sign_mutex);
}
printf("Math prof enters lounge\\n");
fflush(stdout);
sign_value = 1;
numMathProfsInRoom ++;
pthread_mutex_unlock(&sign_mutex);
return (void *)0;
}
void *csProfArrive()
{
printf("CS prof arrives\\n");
fflush(stdout);
pthread_mutex_lock(&sign_mutex);
while (sign_value == 1)
{
pthread_cond_wait(&csProfsCv, &sign_mutex);
}
printf("CS prof enters lounge\\n");
fflush(stdout);
sign_value = 0;
numCsProfsInRoom ++;
pthread_mutex_unlock(&sign_mutex);
return (void *)0;
}
void *mathProfLeave()
{
pthread_mutex_lock(&sign_mutex);
numMathProfsInRoom --;
printf("Math prof leaves lounge\\n");
fflush(stdout);
if (numMathProfsInRoom == 0)
{
sign_value = -1;
pthread_cond_broadcast(&csProfsCv);
}
pthread_mutex_unlock(&sign_mutex);
return (void *) 0;
}
void *csProfLeave()
{
pthread_mutex_lock(&sign_mutex);
numMathProfsInRoom --;
printf("CS prof leaves lounge\\n");
fflush(stdout);
if (numCsProfsInRoom == 0)
{
sign_value = -1;
pthread_cond_broadcast(&mathProfsCv);
}
pthread_mutex_unlock(&sign_mutex);
return (void *) 0;
}
void delay(int n)
{
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
}
}
}
| 0
|
#include <pthread.h>
static inline void ws2801_auto_commit(struct ws2801_driver *ws_driver)
{
if (ws_driver->auto_commit)
ws_driver->commit(ws_driver);
}
int ws2801_init(struct ws2801_driver *ws_driver, unsigned int num_leds)
{
int err;
ws_driver->leds = calloc(num_leds, sizeof(struct led));
if (!ws_driver->leds)
return -ENOMEM;
ws_driver->num_leds = num_leds;
err = pthread_mutex_init(&ws_driver->data_lock, 0);
if (err) {
free(ws_driver->leds);
return err;
}
ws2801_set_auto_commit(ws_driver, WS2801_DEFAULT_AUTO_COMMIT);
return 0;
}
void ws2801_free(struct ws2801_driver *ws_driver)
{
if (ws_driver->leds)
free(ws_driver->leds);
pthread_mutex_destroy(&ws_driver->data_lock);
}
void ws2801_set_auto_commit(struct ws2801_driver *ws_driver, bool auto_commit)
{
ws_driver->auto_commit = auto_commit;
}
void ws2801_clear(struct ws2801_driver *ws_driver)
{
pthread_mutex_lock(&ws_driver->data_lock);
memset(ws_driver->leds, 0,
ws_driver->num_leds * sizeof(*ws_driver->leds));
pthread_mutex_unlock(&ws_driver->data_lock);
ws2801_auto_commit(ws_driver);
}
int ws2801_set_led(struct ws2801_driver *ws_driver, unsigned int num,
const struct led *led)
{
pthread_mutex_lock(&ws_driver->data_lock);
if (num >= ws_driver->num_leds) {
pthread_mutex_unlock(&ws_driver->data_lock);
return -ERANGE;
}
ws_driver->leds[num] = *led;
pthread_mutex_unlock(&ws_driver->data_lock);
ws2801_auto_commit(ws_driver);
return 0;
}
int ws2801_set_leds(struct ws2801_driver *ws_driver, const struct led *leds,
unsigned int offset, unsigned int num_leds)
{
if (offset >= ws_driver->num_leds)
return 0;
pthread_mutex_lock(&ws_driver->data_lock);
if (num_leds + offset >= ws_driver->num_leds)
num_leds = ws_driver->num_leds - offset;
memcpy(ws_driver->leds + offset, leds, num_leds * sizeof(*leds));
pthread_mutex_unlock(&ws_driver->data_lock);
ws2801_auto_commit(ws_driver);
return num_leds;
}
int ws2801_full_on(struct ws2801_driver *ws_driver, const struct led *color)
{
unsigned int i;
int err;
for (i = 0; i < ws_driver->num_leds; i++) {
err = ws_driver->set_led(ws_driver, i, color);
if (err)
break;
}
return err;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void dieWithError(char *msg)
{
printf("[-]ERROR:%s\\n", msg);
exit(0);
}
void* writer(void *arg)
{
int fd, string_num = 1;
char buffer[128];
time_t rawtime;
struct tm *timeinfo;
while(1)
{
pthread_mutex_lock(&mutex);
time(&rawtime);
timeinfo = localtime(&rawtime);
if ((fd = open("file1", O_CREAT|O_WRONLY|O_APPEND, 0744)) < 0)
dieWithError("Can't open the file\\n");
sprintf(buffer, "string number:%d %d:%d:%d\\n", string_num, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
if (write(fd, buffer, strlen(buffer)) < 0)
dieWithError("write() failed");
string_num++;
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_exit(0);
}
void* reader(void *arg)
{
int fd, buffer_read = 0, buffer_written = 0;
char buffer[128];
while(1)
{
pthread_mutex_lock(&mutex);
if ((fd = open("file1", O_CREAT|O_RDONLY, 0744)) < 0)
dieWithError("Can't open the file\\n");
printf("=============================================\\n");
printf("\\tReader thread[%ld]\\n", pthread_self());
printf("=============================================\\n");
while ((buffer_read = read(fd, buffer, 128)) > 0)
{
buffer_written = write (1, buffer, buffer_read);
if (buffer_written != buffer_read)
dieWithError("Write() failed\\n");
}
pthread_mutex_unlock(&mutex);
sleep(5);
}
pthread_exit(0);
}
int main(void)
{
pthread_t read_tid[10];
pthread_t write_tid;
int i = 0;
if (pthread_create(&write_tid, 0, writer, 0) < 0)
dieWithError("Can't create writer thread\\n");
for (i = 0; i < 10; i++)
if (pthread_create(&read_tid[i], 0, reader, 0) < 0)
dieWithError("Can't create reader thread\\n");
if (pthread_join(write_tid, 0) < 0)
dieWithError("Join writer failed\\n");
for (i = 0; i < 10; i++)
if (pthread_join(read_tid[i], 0) < 0)
dieWithError("Join reader failed\\n");
return 0;
}
| 0
|
#include <pthread.h>
void gw_dm_pending ( void *_job_id )
{
gw_job_t * job;
int job_id;
if ( _job_id != 0 )
{
job_id = *( (int *) _job_id );
job = gw_job_pool_get(job_id, GW_TRUE);
if ( job == 0 )
{
gw_log_print("DM",'E',"Job %i does not exist (JOB_STATE_PENDING).\\n",job_id);
free(_job_id);
return;
}
}
else
return;
gw_job_print(job,"DM",'I',"Rescheduling job.\\n");
gw_log_print("DM",'I',"Rescheduling job %d.\\n", job->id);
if (job->history != 0)
if (job->job_state != GW_JOB_STATE_EPILOG_RESTART )
job->history->reason = GW_REASON_EXECUTION_ERROR;
job->reschedule = GW_TRUE;
gw_job_set_state (job, GW_JOB_STATE_PENDING, GW_FALSE);
gw_user_pool_dec_running_jobs(job->user_id);
pthread_mutex_lock(&(job->history->host->mutex));
job->history->host->running_jobs--;
pthread_mutex_unlock(&(job->history->host->mutex));
free(_job_id);
pthread_mutex_unlock(&(job->mutex));
}
| 1
|
#include <pthread.h>
struct jfs *jfopen(const char *path, const char *mode)
{
int flags;
int pos_at_the_beginning;
struct jfs *fs;
if (strlen(mode) < 1)
return 0;
if (mode[0] == 'r') {
pos_at_the_beginning = 1;
if (strlen(mode) > 1 && strchr(mode, '+'))
flags = O_RDWR;
else
flags = O_RDONLY;
} else if (mode[0] == 'a') {
if (strlen(mode) > 1 && strchr(mode, '+'))
pos_at_the_beginning = 1;
else
pos_at_the_beginning = 0;
flags = O_RDWR | O_CREAT | O_APPEND;
} else if (mode[0] == 'w') {
pos_at_the_beginning = 1;
flags = O_RDWR | O_CREAT | O_TRUNC;
} else {
return 0;
}
fs = jopen(path, flags, 0666, 0);
if (fs == 0)
return 0;
if (pos_at_the_beginning)
lseek(fs->fd, 0, 0);
else
lseek(fs->fd, 0, 2);
return fs;
}
int jfclose(struct jfs *stream)
{
int rv;
rv = jclose(stream);
free(stream);
if (rv == 0)
return 0;
else
return EOF;
}
struct jfs *jfreopen(const char *path, const char *mode, struct jfs *stream)
{
if (stream)
jfclose(stream);
stream = jfopen(path, mode);
return stream;
}
size_t jfread(void *ptr, size_t size, size_t nmemb, struct jfs *stream)
{
int rv;
rv = jread(stream, ptr, size * nmemb);
if (rv <= 0)
return 0;
return rv / size;
}
size_t jfwrite(const void *ptr, size_t size, size_t nmemb, struct jfs *stream)
{
int rv;
rv = jwrite(stream, ptr, size * nmemb);
if (rv <= 0)
return 0;
return rv / size;
}
int jfileno(struct jfs *stream)
{
return stream->fd;
}
int jfeof(struct jfs *stream)
{
off_t curpos, endpos;
pthread_mutex_lock(&(stream->lock));
curpos = lseek(jfileno(stream), 0, 1);
endpos = lseek(jfileno(stream), 0, 2);
lseek(jfileno(stream), curpos, 0);
pthread_mutex_unlock(&(stream->lock));
if (curpos >= endpos)
return 1;
else
return 0;
}
void jclearerr(struct jfs *stream)
{
}
int jferror(struct jfs *stream)
{
return 0;
}
int jfseek(struct jfs *stream, long offset, int whence)
{
off_t pos;
pthread_mutex_lock(&(stream->lock));
pos = lseek(stream->fd, offset, whence);
pthread_mutex_unlock(&(stream->lock));
if (pos == -1)
return 1;
return 0;
}
long jftell(struct jfs *stream)
{
return (long) lseek(stream->fd, 0, 1);
}
void jrewind(struct jfs *stream)
{
lseek(stream->fd, 0, 0);
}
FILE *jfsopen(struct jfs *stream, const char *mode)
{
return fdopen(stream->fd, mode);
}
| 0
|
#include <pthread.h>
static char * previousToken;
static char * currentToken;
static time_t tokenGeneratedTime;
static pthread_mutex_t tokenMutex;
void initTokenGenerator()
{
srand((unsigned)time(0));
pthread_mutex_init(&tokenMutex, 0);
}
static
int isTokenExpired()
{
time_t now;
time(&now);
return (0 == currentToken) ||
(difftime(now, tokenGeneratedTime) >= 2 * 60);
}
char * getProxyAuthToken()
{
pthread_mutex_lock(&tokenMutex);
if (isTokenExpired())
{
if (previousToken) free(previousToken);
previousToken = currentToken;
char* memoryAllocationForCurrentToken = malloc(sizeof(char) * (32 +1));
if (memoryAllocationForCurrentToken == 0) {
return 0;
}else {
currentToken = memoryAllocationForCurrentToken;
}
memset(currentToken,0x0,32 +1);
for (int i = 0; i < 32; i++) {
sprintf(¤tToken[i],"%x",arc4random());
}
tokenGeneratedTime = time(0);
}
pthread_mutex_unlock(&tokenMutex);
return currentToken;
}
int isTokenValid(const char * tokenToVerify)
{
pthread_mutex_lock(&tokenMutex);
int isEqualToCurrentToken = 0;
if (tokenToVerify != 0 &&
currentToken != 0) {
isEqualToCurrentToken = strncmp(tokenToVerify, currentToken, strlen(currentToken)) == 0;
}
int isEqualToPreviousToken = 0;
if (previousToken != 0 &&
tokenToVerify != 0) {
isEqualToPreviousToken = strncmp(tokenToVerify, previousToken, strlen(previousToken)) ==0;
}
pthread_mutex_unlock(&tokenMutex);
return (isEqualToCurrentToken || isEqualToPreviousToken);
}
| 1
|
#include <pthread.h>
{
double *a;
double *b;
double sum;
int veclen;
} DOTDATA;
DOTDATA dotstr;
pthread_t callThd[4];
pthread_mutex_t mutexsum;
void *dotprod(void *arg)
{
int i, start, end, len ;
long offset;
double mysum, *x, *y;
offset = (long)arg;
len = dotstr.veclen;
start = offset*len;
end = start + len;
x = dotstr.a;
y = dotstr.b;
mysum = 0;
for (i=start; i<end ; i++)
{
mysum += (x[i] * y[i]);
}
pthread_mutex_lock (&mutexsum);
dotstr.sum += mysum;
printf("Thread %ld did %d to %d: mysum=%f global sum=%f\\n",offset,start,end,mysum,dotstr.sum);
pthread_mutex_unlock (&mutexsum);
pthread_exit((void*) 0);
}
int main (int argc, char *argv[])
{
long i;
double *a, *b;
void *status;
pthread_attr_t attr;
a = (double*) malloc (4*100000*sizeof(double));
b = (double*) malloc (4*100000*sizeof(double));
for (i=0; i<100000*4; i++) {
a[i]=1;
b[i]=a[i];
}
dotstr.veclen = 100000;
dotstr.a = a;
dotstr.b = b;
dotstr.sum=0;
pthread_mutex_init(&mutexsum, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i=0;i<4;i++)
{
pthread_create(&callThd[i], &attr, dotprod, (void *)i);
}
pthread_attr_destroy(&attr);
for(i=0;i<4;i++) {
pthread_join(callThd[i], &status);
}
printf ("Sum = %f \\n", dotstr.sum);
free (a);
free (b);
pthread_mutex_destroy(&mutexsum);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int begin;
int end;
int k;
} msg_t;
pthread_t * threads;
int * results;
int can_read = 0;
pthread_cond_t read_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t read_mutex = PTHREAD_MUTEX_INITIALIZER;
int count(int n){
int i,j=0;
for(i=2; i*i <= n; i++){
if(n % i == 0) return 0;
}
return 1;
}
void * thread_function(void * arg){
int i,res;
msg_t * param = (msg_t *)arg;
int k, begin, end;
pthread_mutex_lock(&read_mutex);
k= param->k;
begin = param->begin;
end = param-> end;
can_read = 1;
pthread_cond_signal(&read_cond);
pthread_mutex_unlock(&read_mutex);
printf("Thread %d begin : %d edn : %d\\n", k, begin, end);
res = 0;
for(i=begin; i<=end; i++){
if(count(i)) res++;
}
printf("Thread %d found %d\\n", k, res);
pthread_exit((void *)res);
return 0;
}
int main(int argc, char const *argv[]){
int i,d,n,begin,end,b,e,sum,res;
msg_t msg;
begin = atoi(argv[1]);
end = atoi(argv[2]);
n = atoi(argv[3]);
d = (end-begin+1) / n;
threads = (pthread_t *)malloc(sizeof(pthread_t *) * n);
results = (int *)malloc(sizeof(int) * n);
for(i=0; i<n; i++){
pthread_mutex_lock(&read_mutex);
b = begin + i*d;
if(i == n-1)
e = end;
else
e = begin + (i+1)*d - 1;
msg.begin = b;
msg.end = e;
msg.k = i+1;
pthread_create(threads + i, 0, thread_function, &msg);
while(can_read == 0) pthread_cond_wait(&read_cond, &read_mutex);
can_read = 0;
pthread_mutex_unlock(&read_mutex);
}
sum = 0;
for(i=0; i<n; i++){
pthread_join(threads[i], (void **)(results + i));
sum += results[i];
}
printf("Sum: %d\\n", sum);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex1, mutex2;
int a = 1, b = 1;
void *tfc(void *arg)
{
int err;
srand(time(0));
while(1) {
pthread_mutex_lock(&mutex1);
sleep(rand()%3);
pthread_mutex_trylock(&mutex2);
if(err) {
pthread_mutex_unlock(&mutex1);
}
printf("sub thread get a = %d, b = %d\\n", a, b);
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
}
return 0;
}
int main()
{
srand(time(0));
pthread_t tid;
int err;
err = pthread_create(&tid, 0, tfc, 0);
if(err) {
printf("thread create error:%s\\n", strerror(err));
exit(1);
}
err = pthread_mutex_init(&mutex1, 0);
if(err) {
printf("mutex init error:%s\\n", strerror(err));
exit(1);
}
err = pthread_mutex_init(&mutex2, 0);
if(err) {
printf("mutex2 init error:%s\\n", strerror(err));
exit(1);
}
while(1) {
pthread_mutex_lock(&mutex2);
sleep(rand()%3);
pthread_mutex_trylock(&mutex1);
if(err) {
pthread_mutex_unlock(&mutex2);
}
printf("main thread get a = %d, b = %d\\n", a, b);
pthread_mutex_unlock(&mutex1);
pthread_mutex_unlock(&mutex2);
}
return 0;
}
| 0
|
#include <pthread.h>
int l, r;
} Info;
int l1, r1, l2, r2;
} pmInfo;
int* A;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t v = PTHREAD_MUTEX_INITIALIZER;
int cmp(const void* a, const void* b)
{
int pa = *(int*) a;
int pb = *(int*) b;
if(pa > pb) return 1;
else if(pa < pb) return -1;
else return 0;
}
void* msort(void *range)
{
Info* prange = (Info*) range;
int l = prange->l, r = prange->r;
int size = r-l;
pthread_mutex_lock(&m);
printf("Handling elements:\\n");
for(int i = l; i < r; i++)
printf("%d%s", A[i], (i == r-1)? "\\n": " ");
printf("Sorted %d elements.\\n", size);
pthread_mutex_unlock(&m);
qsort(A+l, size, sizeof(int), cmp);
pthread_exit(0);
}
void* pmerge(void* range)
{
pmInfo* prange = (pmInfo*) range;
int l1 = prange->l1, r1 = prange->r1;
int l2 = prange->l2, r2 = prange->r2;
int size1 = r1 - l1, size2 = r2 - l2;
int iteration1 = l1, iteration2 = l2, k = 0;
int duplicate = 0;
int* t;
t = (int *) malloc((size1 + size2 + 4) * sizeof(int));
while(iteration1 != r1 && iteration2 != r2){
if(A[iteration1] < A[iteration2])
t[k++] = A[iteration1++];
else if(A[iteration1] > A[iteration2])
t[k++] = A[iteration2++];
else if(A[iteration1] == A[iteration2]){
duplicate++;
t[k++] = A[iteration1++];
}
}
while(iteration1 != r1) t[k++] = A[iteration1++];
while(iteration2 != r2) t[k++] = A[iteration2++];
pthread_mutex_lock(&v);
printf("Handling elements:\\n");
for(int i = l1; i < r2; i++)
printf("%d%s", A[i], (i == r2-1)? "\\n": " ");
printf("Merged %d and %d elements with %d duplicates.\\n", size1, size2, duplicate);
memcpy(A+l1, t, sizeof(int) * (size1+size2));
free(t);
pthread_mutex_unlock(&v);
pthread_exit(0);
}
int main(int argc, char* argv[])
{
int seg_size = atoi(argv[1]);
int n;
scanf("%d", &n);
A = (int*) malloc((n+4) * sizeof(int));
for(int i = 0; i < n; i++)
scanf("%d", &A[i]);
int thread_num = n / seg_size;
if(n % seg_size != 0) thread_num++;
pthread_t* tid;
Info* range;
int* size;
tid = (pthread_t*) malloc((thread_num + 4) * sizeof(pthread_t));
range = (Info*) malloc((thread_num + 4) * sizeof(Info));
size = (int*) malloc((thread_num + 4) * sizeof(int));
for(int i = 0; i < thread_num; i++){
range[i].l = i * seg_size;
range[i].r = (i + 1) * seg_size;
if(i == thread_num - 1) range[i].r = n;
size[i] = range[i].r - range[i].l;
pthread_create(&tid[i], 0, &msort, &range[i]);
}
for(int i = 0; i < thread_num; i++)
pthread_join(tid[i], 0);
free(tid);
free(range);
while(thread_num / 2 != 0){
int odd = 0, origin;
if(thread_num % 2 == 1){
odd = 1;
origin = thread_num;
}
thread_num /= 2;
pthread_t* tid;
pmInfo* range;
tid = (pthread_t*) malloc((thread_num + 4) * sizeof(pthread_t));
range = (pmInfo*) malloc((thread_num + 4) * sizeof(pmInfo));
int pre = 0;
for(int i = 0; i < thread_num; i++){
range[i].l1 = pre;
range[i].r1 = range[i].l1 + size[2*i];
range[i].l2 = range[i].r1;
range[i].r2 = range[i].l2 + size[2*i+1];
size[i] = range[i].r2 - range[i].l1;
pre = range[i].r2;
pthread_create(&tid[i], 0, &pmerge, &range[i]);
}
for(int i = 0; i < thread_num; i++)
pthread_join(tid[i], 0);
if(odd == 1) size[thread_num] = size[origin - 1];
thread_num += odd;
free(tid);
free(range);
}
for(int i = 0; i < n; i++)
printf("%d%s", A[i], (i == n-1)? "\\n": " ");
free(size);
return 0;
}
| 1
|
#include <pthread.h>
int quit,sum;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc =PTHREAD_COND_INITIALIZER;
void *thr_fn(void *arg)
{
int i = *(int *)arg;
printf("thr_fn\\n");
if (i==0){
printf("the transfer the param success\\n");
pthread_mutex_lock(&lock);
while(i<=100){
sum += i;
i++;
}
pthread_mutex_unlock(&lock);
printf("the sum:%d\\n", sum);
}
pthread_exit((void *)0);
}
int main(int argc, char **argv) {
int i,err,num =0;
pthread_t tid[i];
pthread_attr_t attr;
err = pthread_attr_init(&attr);
if (err)
return(err);
err = pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
if (err==0){
for (int i = 0; i < 5; ++i)
{
err = pthread_create(&tid[i],&attr,thr_fn,(void *)&num);
if (err) {
printf("craete err\\n");
}
}
}else
printf("set pthread detach failed\\n");
pthread_attr_destroy(&attr);
sleep(1);
for (int i = 5; i >0; --i)
{
printf("wait the thread:%d\\n", i);
err = pthread_join(tid[i],(void *)&err);
if (!err)
{
printf("wait success thread :%d\\n",i);
}
}
return 0;
}
| 0
|
#include <pthread.h>
int arr[100 ];
pthread_mutex_t lock;
sem_t c;
struct t
{
int low , high;
} l3;
void * sort(void *b)
{ pthread_t th0,th1;
int low,high;
struct t *y1= (struct t *) b;
low = y1->low;
high = y1->high;
struct t l2,l1;
if(low<high)
{
pthread_t th0,th1;
int mid=(low+high)/2;
int valuel;
pthread_mutex_lock(&lock);
sem_getvalue(&c, &valuel);
l1.low = low;
l1.high = mid;
l2.low = mid +1;
l2.high = high;
if(valuel>=2)
{
sem_wait(&c);
sem_wait(&c);
pthread_create(&(th0), 0, sort, (void*)&l1);
pthread_create(&(th1), 0, sort, (void*)&l2);
sem_post(&c);
sem_post(&c);
}
pthread_mutex_unlock(&lock);
pthread_join(th0, 0);
pthread_join(th1, 0);
merge(low,high);
}
}
void merge (int l1 ,int h)
{
int low,high,mid;
int i2;
low =l1;
high =h;
mid=(low+high)/2;
int k,m,x,y,sizel=0,sizer=0,j;
int n;
int l[5];
int r[5];
for(k=low,x=1;k<=mid;k++,x++)
{
l[x]=arr[k];
sizel++;
}
for(n=mid+1,y=1;n<=high;n++,y++)
{
r[y]=arr[n];
sizer++;
}
i2=1;j=1;
k=low;
while((i2<=sizel)&&(j<=sizer))
{
if(l[i2]>=r[j])
{
arr[k]=r[j];
j++;
k++;
}
else
{
arr[k]=l[i2];
i2++;
k++;
}
}
if(i2<=sizel)
{
while(i2<=sizel)
{
arr[k]=l[i2];
k++;
i2++;
}
}
if(j<=sizer)
{
while(j<=sizer)
{
arr[k]=r[j];
k++;
j++;
}
}
}
int main()
{
int i1,i;
pthread_t t;
int n1,n=2;
printf("Enter n to sort 2^n elements");
scanf("%d",&n1);
for(i=1;i<n1;i++)
n=n*2;
printf("Enter elements of array to sort:");
for(i1=1;i1<=n;i1++)
{
scanf("%d", &arr[i1]);
}
for(i1=1;i1<n+1;i1++)
printf(" %d ", arr[i1]);
pthread_mutex_init(&lock, 0);
sem_init(&c,0,4);
l3.low=1;
l3.high = n+1;
pthread_create(&(t), 0, sort, &l3);
pthread_join(t,0);
printf("\\n FINALLY SORTED ARRAY :");
for(i1=1;i1<n+1;i1++)
printf(" %d ", arr[i1]);
return 0;
}
| 1
|
#include <pthread.h>
int in = 0;
int out = 0;
int buff[10] = {0};
sem_t empty_sem;
sem_t full_sem;
pthread_mutex_t mutex;
int product_id = 0;
int prochase_id = 0;
void print()
{
int i;
for(i = 0; i < 10; i++)
printf("%d ", buff[i]);
printf("\\n");
}
void *product()
{
int id = ++product_id;
for(;;)
{
sleep(1);
sem_wait(&empty_sem);
pthread_mutex_lock(&mutex);
in = in % 10;
printf("product%d in %d. like: \\t", id, in);
buff[in] = 1;
print();
++in;
pthread_mutex_unlock(&mutex);
sem_post(&full_sem);
}
}
int sum=0;
void *prochase()
{
int id = ++prochase_id;
for(int j=0;j<25;j++)
{
sleep(1);
sem_wait(&full_sem);
pthread_mutex_lock(&mutex);
out = out % 10;
printf("prochase%d in %d. like: \\t", id, out);
buff[out] = 0;
print();
++out;
pthread_mutex_unlock(&mutex);
sem_post(&empty_sem);
sum++;
if(sum==50)exit(1);
}
}
int main()
{
pthread_t id1[3];
pthread_t id2[2];
int i;
int ret[3],RET[2];
int ini1 = sem_init(&empty_sem, 0, 2);
int ini2 = sem_init(&full_sem, 0, 0);
if(ini1 && ini2 != 0)
{
printf("sem init failed \\n");
exit(1);
}
int ini3 = pthread_mutex_init(&mutex, 0);
if(ini3 != 0)
{
printf("mutex init failed \\n");
exit(1);
}
for(i = 0; i < 3; i++)
{
ret[i] = pthread_create(&id1[i], 0, product, (void *)(&i));
if(ret[i] != 0)
{
printf("product%d creation failed \\n", i);
exit(1);
}
}
for(i = 0; i < 2; i++)
{
RET[i] = pthread_create(&id2[i], 0, prochase, 0);
if(RET[i] != 0)
{
printf("prochase%d creation failed \\n", i);
exit(1);
}
}
for(i = 0; i < 3; i++)
{
pthread_join(id1[i],0);
}
for(i = 0; i < 2; i++)
{
pthread_join(id2[i],0);
}
exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
void fun(void);
void *thread_func(void *args)
{
printf("%lu locking mutex\\n",pthread_self());
pthread_mutex_lock(&mutex);
printf("%lu locked mutex\\n",pthread_self());
fun();
sleep(2);
pthread_mutex_unlock(&mutex);
}
void fun(void)
{
if(pthread_mutex_lock(&mutex) == 35 )
{
printf("! (%lu) already locked the mutex \\n",pthread_self());
}
}
int main()
{
pthread_t tid1,tid2,tid3;
pthread_create(&tid1, 0, thread_func, 0);
pthread_create(&tid2, 0, thread_func, 0);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
return 0;
}
| 1
|
#include <pthread.h>
struct person_info {
int sex;
char name[32 +1];
int age;
};
pthread_mutex_t mutex;
void *write_thread_routine(void * arg)
{
int i;
char buf[1024];
struct person_info *pInfo = (struct person_info *)arg;
printf("I'm sub thread,my thread ID is:0x%x\\n", (int)pthread_self());
if(!pInfo) {
pthread_exit(0);
}
while (1) {
fprintf (stderr, "writer: please input string:");
bzero (buf, 1024);
if (fgets (buf, 1024 - 1, stdin) == 0) {
perror ("fgets");
continue;
}
int len = strlen(buf);
if(len > 32) {
len = 32;
}
pthread_mutex_lock(&mutex);
pInfo->sex = 1;
pInfo->age = 18;
bzero(pInfo->name, 32 +1);
strncpy(pInfo->name, buf, len);
pthread_mutex_unlock(&mutex);
if ( !strncasecmp (buf, "quit", strlen ("quit"))) {
break;
}
}
pthread_exit((void *)pInfo);
}
void read_thread_routine(void *arg)
{
struct person_info *pInfo = (struct person_info *)arg;
printf("I'm read thread!\\n");
if(!pInfo) {
pthread_exit(0);
}
while(1) {
pthread_mutex_lock(&mutex);
if ( !strncasecmp (pInfo->name, "quit", strlen ("quit"))) {
pthread_mutex_unlock(&mutex);
break;
}
printf("read: sex = %d, age=%d, name=%s\\n", pInfo->sex, pInfo->age, pInfo->name);
pthread_mutex_unlock(&mutex);
usleep(200000);
}
pthread_exit(0);
}
int main(void)
{
pthread_t tid_w, tid_r;
char *msg = "Hello, 1510";
struct person_info *pInfo = 0;
printf("thread demo!\\n");
pInfo = (struct person_info *)malloc(sizeof(struct person_info));
if(!pInfo) {
exit(1);
}
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_TIMED_NP);
pthread_mutex_init(&mutex, &mutexattr);
pthread_mutexattr_destroy(&mutexattr);
pthread_create(&tid_w, 0, write_thread_routine, (void *)pInfo);
pthread_create(&tid_r, 0, (void *)read_thread_routine, (void *)pInfo);
pthread_join(tid_w, 0);
pthread_join(tid_r, 0);
pthread_mutex_destroy(&mutex);
if(pInfo) free(pInfo);
sleep(5);
return 0;
}
| 0
|
#include <pthread.h>
volatile int nShared = 0;
pthread_mutex_t verrou;
void* decr(void* ptr)
{
char* msg = (char*) ptr;
int count = 10000;
while(count>0)
{
pthread_mutex_lock(&verrou);
while(nShared<=0)
{
pthread_mutex_unlock(&verrou);
sched_yield();
pthread_mutex_lock(&verrou);
printf("%s waits nShared become non-zero (%d)\\n", msg, nShared);
}
nShared--;
pthread_mutex_unlock(&verrou);
count--;
printf("%s decreased 1 to %d\\n", msg, nShared);
}
return 0;
}
void* incr(void* ptr)
{
char* msg = (char*) ptr;
int count = 10000;
while(count>0)
{
pthread_mutex_lock(&verrou);
nShared++;
pthread_mutex_unlock(&verrou);
count--;
printf("%s increased 1 to %d\\n", msg, nShared);
}
return 0;
}
void* print_message(void* ptr)
{
char* msg = (char*) ptr;
int count = 5000;
while(count>0)
{
pthread_mutex_lock(&verrou);
nShared++;
pthread_mutex_unlock(&verrou);
count--;
printf("%s increased 1 to %d\\n", msg, nShared);
}
return 0;
}
double time_diff(struct timeval x , struct timeval y)
{
double x_ms , y_ms , diff;
x_ms = (double)x.tv_sec*1000000 + (double)x.tv_usec;
y_ms = (double)y.tv_sec*1000000 + (double)y.tv_usec;
diff = (double)y_ms - (double)x_ms;
return diff;
}
int main (int argc, char* argv[])
{
struct timeval before , after;
gettimeofday(&before , 0);
pthread_t t1, t2;
char* pName1 = "Thread 1";
char* pName2 = "Thread 2";
pthread_mutex_init(&verrou, 0);
int rc1 = pthread_create(&t1, 0, incr, (void*)pName1 );
int rc2 = pthread_create(&t2, 0, decr, (void*)pName2 );
pthread_join(t1, 0);
pthread_join(t2, 0);
gettimeofday(&after , 0);
printf("Final result=%d. Time=%f\\n", nShared, time_diff(before, after));
return 0;
}
| 1
|
#include <pthread.h>
int n;
sockaddr_in from = { 0 };
int fromsize = sizeof from;
char buffer[1025];
int threadsit = 0;
pthread_t threads[10] = {0};
pthread_mutex_t buffer_lock, socket_lock;
void *sendroutine() {
sockaddr_in sin = { 0 };
sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_family = AF_INET;
sin.sin_port = htons(0);
int sock = socket(AF_INET, SOCK_DGRAM, 0);
sockaddr_in fromcpy = from;
int ncpy = n;
char* buffercpy = (char*)malloc(sizeof(char) * (ncpy+1));
strcpy(buffercpy, buffer);
pthread_mutex_unlock(&buffer_lock);
usleep(1000000);
if(bind(sock, (sockaddr *) &sin, sizeof sin) > 0)
{
perror("bind()");
exit(1);
}
printf("%d\\n", sock);
if(sendto(sock, buffercpy, ncpy, 0, (sockaddr *)&fromcpy, sizeof(fromcpy)) < 0)
{
perror("sendto()");
exit(1);
}
if(close(sock) > 0)
{
perror("close()");
exit(1);
}
free(buffercpy);
printf("ended!\\n");
return 0;
}
int main(int argc, char* argv[]) {
if (argc != 2) {
perror("The wgetX must have exactly 1 parameter as input. \\n");
exit(1);
}
char *end;
long port = strtol(argv[1], &end, 10);
sockaddr_in sin = { 0 };
sin.sin_addr.s_addr = htonl(INADDR_ANY);
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
int sock;
if (pthread_mutex_init(&buffer_lock, 0) != 0){
printf("buffer lock mutex init failed\\n");
return 1;
}
if (pthread_mutex_init(&socket_lock, 0) != 0){
printf("socket lock mutex init failed\\n");
return 1;
}
while(1) {
if(threads[threadsit]) {
pthread_join(threads[threadsit], 0);
}
printf("waiting1\\n");
pthread_mutex_lock(&buffer_lock);
sock = socket(AF_INET, SOCK_DGRAM, 0);
printf("%d\\n", sock);
if(bind(sock, (sockaddr *) &sin, sizeof sin) > 0)
{
perror("bind()");
exit(1);
}
printf("waiting2\\n");
if((n = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&from, &fromsize)) < 0)
{
perror("recvfrom()");
exit(1);
}
if(close(sock) > 0)
{
perror("close()");
exit(1);
}
buffer[n] = '\\0';
printf("waiting3\\n");
pthread_create(&threads[threadsit], 0, sendroutine, 0);
threadsit = (threadsit+1) % 10;
}
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t mutex;
static sem_t empty;
static sem_t full;
void init(void)
{
pthread_mutex_init(&mutex, 0);
sem_init(&empty, 0, 40);
sem_init(&full, 0, 0);
}
void producer(int max)
{
int i;
int item;
for(i = 0; i < max; ++i) {
item = produce();
sem_wait(&empty);
pthread_mutex_lock(&mutex);
insert(item);
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
| 1
|
#include <pthread.h>
int i;
pthread_cond_t rc;
pthread_mutex_t rm;
int r_counter;
pthread_cond_t wc;
pthread_mutex_t wm;
int w_counter;
}Storage;
void set_data(Storage *s,int i)
{
s->i = i;
}
int get_data(Storage *s)
{
return s->i;
}
void *set_th(void *arg)
{
Storage *s = (Storage *)arg;
int i = 1;
for(; i <= 100; i++)
{
set_data(s,i+100);
pthread_mutex_lock(&s->rm);
while(s->r_counter < 2)
{
pthread_mutex_unlock(&s->rm);
usleep(100);
pthread_mutex_lock(&s->rm);
}
s->r_counter = 0;
pthread_mutex_unlock(&s->rm);
pthread_cond_broadcast(&s->rc);
pthread_mutex_lock(&s->wm);
s->w_counter = 1;
pthread_cond_wait(&s->wc,&s->wm);
pthread_mutex_unlock(&s->wm);
}
return (void*)0;
}
void *get_th(void *arg)
{
Storage *s = (Storage *)arg;
int i = 1, d;
for(; i <= 100; i++)
{
pthread_mutex_lock(&s->rm);
s->r_counter++;
pthread_cond_wait(&s->rc,&s->rm);
pthread_mutex_unlock(&s->rm);
d = get_data(s);
printf("0x%1x(%-3d):%5d\\n",pthread_self(),i,d);
pthread_mutex_lock(&s->wm);
while(s->w_counter != 1)
{
pthread_mutex_unlock(&s->wm);
usleep(100);
pthread_mutex_lock(&s->wm);
}
pthread_mutex_unlock(&s->wm);
pthread_cond_broadcast(&s->wc);
}
return (void*)0;
}
int main()
{
int err;
pthread_t wth,rth1,rth2;
Storage s;
s.r_counter = 0;
s.w_counter = 0;
pthread_mutex_init (&s.rm,0);
pthread_mutex_init (&s.wm,0);
pthread_cond_init(&s.rc,0);
pthread_cond_init(&s.wc,0);
if((err = pthread_create(&rth1,0,get_th,(void*)&s)) != 0){
fprintf(stderr,"%s\\n",strerror(err));
}
if((err = pthread_create(&rth2,0,get_th,(void*)&s)) != 0){
fprintf(stderr,"%s\\n",strerror(err));
}
if((err = pthread_create(&wth,0,set_th,(void*)&s)) != 0){
fprintf(stderr,"%s\\n",strerror(err));
}
pthread_join(rth1,0);
pthread_join(rth2,0);
pthread_join(wth,0);
return 0;
}
| 0
|
#include <pthread.h>
int tab [100];
int finish = 0;
pthread_mutex_t verrou;
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void* bubbleSort()
{
pthread_mutex_lock(&verrou);
int i, j;
for (i = 0; i < 100 -1; ++i){
for (j = 0; j < 100 -i-1; ++j)
if (tab[j] > tab[j+1]){
swap(&tab[j], &tab[j+1]);
pthread_mutex_unlock(&verrou);
sleep(1);
pthread_mutex_lock(&verrou);
}
}
finish = 1;
pthread_mutex_unlock(&verrou);
}
void* printArray()
{
pthread_mutex_lock(&verrou);
do{
int i;
for (i=0; i < 100; i++)
printf("%d ", tab[i]);
printf("\\n");
pthread_mutex_unlock(&verrou);
sleep(1);
pthread_mutex_lock(&verrou);
} while (!finish);
}
int main()
{
int n = 100;
srand(time(0));
int i;
for (i = 0; i < 100; ++i){
tab[i] = rand() % 100;
}
pthread_t threada;
pthread_t threadb;
pthread_mutex_init(&verrou, 0);
if(pthread_create(&threada, 0, bubbleSort, 0) == -1) {
perror("pthread_create");
return -1;
}
sleep(1);
if(pthread_create(&threadb, 0, printArray, 0) == -1) {
perror("pthread_create");
return -1;
}
pthread_join(threada, 0);
pthread_join(threadb, 0);
return 0;
}
| 1
|
#include <pthread.h>
int thread_flag;
pthread_mutex_t thread_flag_mutex;
void initialize_flag() {
pthread_mutex_init(&thread_flag_mutex, 0);
thread_flag = 0;
}
void do_work()
{
printf("Doing work\\n");
sleep(1);
}
void* thread_function(void* thread_arg) {
while (1) {
int flag_is_set;
pthread_mutex_lock(&thread_flag_mutex);
flag_is_set = thread_flag;
pthread_mutex_unlock(&thread_flag_mutex);
if (flag_is_set)
do_work();
}
return 0;
}
void set_thread_flag(int flag_value) {
pthread_mutex_lock(&thread_flag_mutex);
thread_flag = flag_value;
pthread_mutex_unlock(&thread_flag_mutex);
}
int main(int argc, char *argv[])
{
initialize_flag();
pthread_t thread;
int status;
status = pthread_create(&thread, 0, thread_function, 0);
if (status)
{
printf("can not create a thread");
}
int tmp_val=rand()%2;
set_thread_flag(tmp_val);
printf("main\\n");
}
| 0
|
#include <pthread.h>
pensar,
fome,
comer,
} Filosofos;
int Filosofos_esquerda(int filo_n);
int Filosofos_direita(int filo_n);
void *Filosofos_checkin(void *filo);
pthread_mutex_t forks;
Filosofos *FilosofosN;
int main(int filo, char **time){
pthread_t *thread;
int CADEIRAS, TIMEWAIT_MAX;
CADEIRAS = atoi(filo[2]);
TIMEWAIT_MAX = atoi(time[2]);
FilosofosN = (Filosofos *) calloc(CADEIRAS, sizeof(Filosofos));
if(FilosofosN == 0){
printf("\\nErro ao alocar os filosofos!\\n");
return -1;
}
thread = (pthread_t *) calloc(CADEIRAS, sizeof(pthread_t));
if(thread == 0){
printf("\\nErro ao alocar as threads!\\n");
return -1;
}
pthread_mutex_init(&forks, 0);
int i;
for(i=0; i<CADEIRAS; i++){
FilosofosN[i] = pensar;
pthread_create(&thread[i], 0, Filosofos_checkin, (void *) i);
}
for(i=0; i<CADEIRAS; i++){
pthread_join(thread[i], 0);
}
return 0;
}
int Filosofos_esquerda(int filo_n){
return (filo_n + CADEIRAS - 1) % CADEIRAS;
}
int Filosofos_direita(int filo_n){
return (filo_n + 1) % CADEIRAS;
}
void *Filosofos_checkin(void *filo){
int filo_n = (int) filo;
while(1){
pthread_mutex_lock(&forks);
switch(FilosofosN[filo_n]){
case pensar:
FilosofosN[filo_n] = fome;
pthread_mutex_unlock(&forks);
sleep(random() % TIMEWAIT_MAX);
break;
case comer:
FilosofosN[filo_n] = pensar;
pthread_mutex_unlock(&forks);
sleep(random() % TIMEWAIT_MAX);
break;
case fome:
if(FilosofosN[Filosofos_esquerda(filo_n)] == comer){
pthread_mutex_unlock(&forks);
} else if(FilosofosN[Filosofos_direita(filo_n)] == comer){
pthread_mutex_unlock(&forks);
}else{
FilosofosN[filo_n] = comer;
pthread_mutex_unlock(&forks);
}
sleep(random() % TIMEWAIT_MAX);
break;
}
}
}
| 1
|
#include <pthread.h>
static pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
int lksmith_get_ignored_frame_patterns(char *** ignored, int *num_ignored);
static int check_ignored_frame_patterns(void)
{
char **ignored = 0;
int num_ignored = 0;
EXPECT_EQ(0, lksmith_get_ignored_frame_patterns(&ignored, &num_ignored));
EXPECT_EQ(3, num_ignored);
EXPECT_ZERO(strcmp("*ignore1*", ignored[0]));
EXPECT_ZERO(strcmp("*ignore2*", ignored[1]));
EXPECT_ZERO(strcmp("*ignore3*", ignored[2]));
return 0;
}
void ignore1(void)
{
pthread_mutex_lock(&lock2);
pthread_mutex_lock(&lock1);
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
static int verify_ignored_frame_patterns_work(void)
{
clear_recorded_errors();
pthread_mutex_lock(&lock1);
pthread_mutex_lock(&lock2);
pthread_mutex_unlock(&lock2);
pthread_mutex_unlock(&lock1);
ignore1();
EXPECT_EQ(num_recorded_errors(), 0);
return 0;
}
int main(void)
{
putenv("LKSMITH_IGNORED_FRAME_PATTERNS=*ignore3*:*ignore2*:*ignore1*");
set_error_cb(record_error);
EXPECT_ZERO(check_ignored_frame_patterns());
EXPECT_ZERO(verify_ignored_frame_patterns_work());
return 0;
}
| 0
|
#include <pthread.h>
extern struct free_pool_data* free_pool_table;
extern struct file_cache* file_cache_head;
void file_cache_unpin_files(struct file_cache *cache, const char **files, int num_files){
int i;
struct file_data header_ptr;
struct file_data* temp_ptr;
pthread_mutex_lock(&(cache->fc_mutex_lock));
int offset = (char*)(&header_ptr.data) - (char *)(&header_ptr);
int max_files = cache->max_entries;
struct file_cache_entry* entry;
for(i=0;i<num_files;i++){
temp_ptr = (struct file_data*)((char*)(files[i]) - offset);
entry = (temp_ptr->file_data_head_info).file_entry_ptr;
if (entry->pinned_clean == 1){
entry->pinned_clean = 0;
entry->unpinned_clean = 1;
entry->last_accessed = get_time_stamp();
remove_queue(cache->pinned_clean, entry);
insert_queue(cache->unpinned_clean, entry);
entry->pinned_count--;
cache->num_files_pinned_clean--;
cache->num_files_unpinned_clean++;
entry->valid = 0;
}
else
entry->pinned_count--;
if (entry->pinned_dirty == 1){
entry->pinned_dirty = 0;
entry->unpinned_dirty = 1;
entry->last_accessed = get_time_stamp();
remove_queue(cache->pinned_dirty, entry);
insert_queue(cache->unpinned_dirty, entry);
entry->pinned_count--;
cache->num_files_pinned_dirty--;
cache->num_files_unpinned_dirty++;
entry->valid = 0;
}
else
entry->pinned_count--;
}
pthread_mutex_unlock(&(cache->fc_mutex_lock));
}
| 1
|
#include <pthread.h>
int NB_FICHIER_TODO = 0;
pthread_mutex_t mutex_nb_fichier = PTHREAD_MUTEX_INITIALIZER;
void* upperDeleg(void* arg) {
char** paths = (char **) arg;
int *ret = malloc(sizeof(int));
pthread_mutex_lock(&mutex_nb_fichier);
while(NB_FICHIER_TODO > 0) {
int filenumber = NB_FICHIER_TODO;
NB_FICHIER_TODO--;
pthread_mutex_unlock(&mutex_nb_fichier);
*ret = upper(paths[filenumber+1]);
if((*ret) != 0)
pthread_exit(ret);
pthread_mutex_lock(&mutex_nb_fichier);
}
pthread_mutex_unlock(&mutex_nb_fichier);
pthread_exit(ret);
}
int main(int argc, char* argv[]) {
pthread_t* tids;
int nb_thread;
int i, errorCount;
int *threadret;
errorCount = 0;
if(argc < 3)
{
printf("Bad args\\n");
return 1;
}
nb_thread = atoi(argv[1]);
NB_FICHIER_TODO = argc -2;
if( (nb_thread >= NB_FICHIER_TODO) || (nb_thread <= 0) )
{
printf("Wrong number of threads asked\\n");
return 1;
}
tids = malloc(sizeof(pthread_t)*(nb_thread));
for(i = 0; i < (nb_thread); i++)
{
if(pthread_create(&tids[i], 0, upperDeleg, argv) != 0) {
perror("error p_create");
return 1;
}
}
for(i = 0; i < nb_thread; i++)
{
if((pthread_join(tids[i%nb_thread], (void*) &threadret) != 0) || !threadret) {
printf("error p_join on file %s\\n", argv[i+2]);
errorCount++;
}
}
free(tids);
free(threadret);
return errorCount;
}
| 0
|
#include <pthread.h>
int arr[1000][1000];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void initArray()
{
int i = 0;
int j = 0;
for (i = 0; i < 1000; i++)
{
for (j = 0; j < 1000; j++)
{
srand(time(0));
arr[i][j] = rand() % 1 + 1;
}
}
}
int main()
{
initArray();
int sum = 0;
omp_set_num_threads(20);
int privatesum;
int id;
int i;
int j;
int startc;
int startr;
int finishc;
int finishr;
int c;
int r;
{
id = omp_get_thread_num();
privatesum = 0;
r = id / 5;
c = id % 5;
startc = 200 * c;
finishc = startc + 200;
startr = 250 * r;
finishr = startr + 250;
for (i = startr; i < finishr; i++)
{
for (j = startc; j < finishc; j++)
{
privatesum += arr[i][j];
}
}
pthread_mutex_lock(&mutex);
sum += privatesum;
pthread_mutex_unlock(&mutex);
}
printf("Sum: %d", sum);
}
| 1
|
#include <pthread.h>
pthread_t tid[10];
pthread_mutex_t critical;
int total;
struct PROCESSOR
{
int clk,incr,id;
};
struct PROCESSOR p[10],sender;
void* increment(void *proc)
{
struct PROCESSOR*current=(struct PROCESSOR*)proc;
while(1)
{
sleep(2);
printf("Incrementing Processor %d's clk from [%d o'clock] ",current->id,current->clk);
current->clk+=current->incr;
printf("to [%d o'clock]\\n",current->clk);
}
}
void *sync(void* processor)
{
pthread_t interval;
pthread_create(&interval,0,&increment,processor);
struct PROCESSOR*current=(struct PROCESSOR*)processor;
while(1)
{
sleep(5);
pthread_mutex_lock(&critical);
if(sender.id!=current->id)
if(sender.clk>current->clk)
{
printf("Processor %d(at [%d o'clock]) got message from Processor %d(at [%d o'clock]),so sync'ing Processor %d...\\n",current->id,current->clk,sender.id,sender.clk,current->id);
current->clk=sender.clk+1;
printf("Processor %d's clock sync'd to [%d o'clock]\\n",current->id,current->clk);
}
else
{
printf("Processor %d(at [%d o'clock]) got message from Processor %d(at [%d o'clock]),so no sync'ing required...\\n",current->id,current->clk,sender.id,sender.clk);
}
sender.id=current->id;
printf("Now Processor %d sends msg at [%d o'clock]\\n",current->id,current->clk);
pthread_mutex_unlock(&critical);
}
pthread_join(interval,0);
}
int main(int argc,char *argv[])
{
int i;
sender.id=1;
sender.clk=0;
sender.incr=atoi(argv[1]);
pthread_create(&tid[0],0,&sync,&sender);
for(i=1;i<(total=argc-1);i++)
{
p[i].clk=0;
p[i].incr=atoi(argv[i+1]);
p[i].id=i+1;
pthread_create(&tid[i],0,&sync,&p[i]);
}
for(i=0;i<total;i++)
pthread_join(tid[i],0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
sem_t semph;
int risultatiSondaggi[3][5];
int n;
float avg[3];
} gestoreSondaggi;
gestoreSondaggi G;
void printResults()
{
int i, j, sum;
for(i=0; i<3; i++)
{
for(j=0, sum=0; j<5; j++)
{
if(G.risultatiSondaggi[i][j]!=0)
{
sum+=G.risultatiSondaggi[i][j];
}
}
G.avg[i] = (float)sum/G.n;
printf("Risultati dopo %d sondaggi:\\n", G.n);
printf("Film %i ha una media voto di: %.2f\\n", i, G.avg[i]);
}
printf("\\n\\n");
}
void printBestFilm()
{
int i, maxFilm;
float maxAvg=1;
for (i=0; i<3; i++)
if (G.avg[i]>maxAvg)
{
maxFilm=i;
maxAvg=G.avg[i];
}
printf("Il miglior film della stagione è stato il film %i con una media voto di: %.2f\\n", maxFilm, maxAvg);
}
void * user(void * t)
{
int tid = (intptr_t) t;
int i;
pthread_mutex_lock(&G.mutex);
sem_post(&G.semph);
for(i=0; i < 3; i++)
{
G.risultatiSondaggi[i][tid] = (rand() % 10) + 1;
printf("Persona %d - Voto: %d al film %d\\n", tid, G.risultatiSondaggi[i][tid], i);
}
G.n++;
printResults();
sem_post(&G.semph);
pthread_mutex_unlock(&G.mutex);
pthread_exit (0);
}
int main (int argc, char * argv[])
{
int i, j;
pthread_t thread[5];
srand(time(0));
pthread_mutex_init(&G.mutex, 0);
G.n=0;
for(i=0; i < 3; i++)
{
sem_init(&G.semph, 0, 1);
}
for(i=0; i < 3; i++)
{
for(j=0; j < 5; j++)
G.risultatiSondaggi[3][5]=0;
}
for(i=0; i < 5; i++)
{
pthread_create(&thread[i], 0, user, (void*)(intptr_t)i);
}
for(i=0; i < 5; i++)
{
pthread_join(thread[i], 0);
}
printBestFilm();
return 0;
}
| 1
|
#include <pthread.h>
void *producer(void *param);
void *consumer(void *param);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t buf_full = PTHREAD_COND_INITIALIZER;
pthread_cond_t buf_empty = PTHREAD_COND_INITIALIZER;
int times;
int con_count;
int num_consumed = 0;
int buffer[1];
void *produce (void *param)
{
unsigned int seed = 10000;
int i = 0;
while (i < times) {
if (i == 0) {
pthread_mutex_lock(&mutex);
} else {
pthread_cond_wait(&buf_empty, &mutex);
}
int num = rand_r(&seed) % 101;
buffer[0] = num;
printf("Producer: produced %d!\\n", num);
pthread_cond_signal(&buf_full);
i++;
}
pthread_mutex_unlock(&mutex);
return 0;
}
void *consume (void *param)
{
long thread_num = (long) param;
int val;
int i = 0;
while (i < times) {
pthread_cond_wait(&buf_full, &mutex);
val = buffer[0];
num_consumed++;
if (num_consumed == con_count) {
buffer[0] = 0;
printf("Consumer: I am thread %ld, and I have just read in the value: %d.\\n---\\n", thread_num, val);
num_consumed = 0;
pthread_cond_signal(&buf_empty);
} else {
printf("Consumer: I am thread %ld, and I have just read in the value: %d.\\n", thread_num, val);
pthread_cond_signal(&buf_full);
}
pthread_mutex_unlock(&mutex);
i++;
}
return 0;
}
int
main (int argc, char **argv)
{
if (argc == 3) {
times = atoi(argv[1]);
con_count = atoi(argv[2]);
} else {
times = 4;
con_count = 4;
}
buffer[0] = 0;
long i;
pthread_t producer_thread;
pthread_t consumer_threads[con_count];
printf("%d consumer threads, producing %d times.\\n", con_count, times);
for (i = 0; i < con_count; i++) {
(void) pthread_create(&consumer_threads[i], 0, consume, (void*) i);
}
(void) pthread_create(&producer_thread, 0, produce, 0);
pthread_cond_signal(&buf_empty);
(void) pthread_join(producer_thread, 0);
for (i = 0; i < con_count; i++) {
(void) pthread_join(consumer_threads[i], 0);
}
pthread_cond_destroy(&buf_empty);
pthread_cond_destroy(&buf_full);
printf("all done!\\n");
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex3 = PTHREAD_MUTEX_INITIALIZER;
pthread_t chCliente;
pthread_t caixas [5];
int filas_vazia = 5;
int clientes=20;
sem_t filas [5];
int cliente_fila = 0;
sem_t empty;
sem_t full;
void PrintFila(){
int k;
for(k=0;k<5;k++)
printf("Caixa %d -> %d\\n",k, filas[k]);
}
void NoCaixa(float delay1) {
if(delay1<0.001)
return;
float inst1=0;
float inst2=0;
inst1 = (float)clock()/(float)CLOCKS_PER_SEC;
while(inst2-inst1<delay1)
inst2 = (float)clock()/(float)CLOCKS_PER_SEC;
return;
}
void *ChegadaCliente(void *thread_id){
int j;
int caixa;
int menorFila;
int i;
while(clientes>0){
menorFila = 20;
NoCaixa(1);
pthread_mutex_lock(&mutex);
for(i=0;i<5; i++){
if(filas[i]==0){
caixa=i;
break;
}
else if(filas[i]<menorFila){
menorFila = filas[i];
caixa = i;
}
}
if(filas[caixa]==0){
filas_vazia--;
}
cliente_fila++;
clientes--;
pthread_mutex_unlock(&mutex);
sem_post(&filas[caixa]++);
printf("INSERIRU CLIENTE NA FILA DO CAIXA: %d \\n", caixa);
printf("FALTAM %d CLIENTES P/ CHEGAR.\\n", clientes);
PrintFila();
}
}
void *AtendeCliente(void *thread_id){
printf("funcao atende..\\n");
int maiorFila;
int transfere;
int i;
while(clientes>0){
NoCaixa(3);
maiorFila = 0;
pthread_mutex_lock(&mutex2);
if(filas[(int)thread_id]==0){
for(i = 0; i<5;i++){
if(filas[i]>maiorFila){
maiorFila = filas[i];
transfere = i;
}
}
pthread_mutex_unlock(&mutex2);
sem_wait(&filas[transfere]--);
printf("O Caixa %d atendeu, o cliente da Fila %d e sobrou %d clientes na fila.\\n", (int)thread_id, transfere, filas[(int)thread_id]);
printf("Falta ser atendido %d clientes.\\n\\n", clientes);
}
else if(filas[(int)thread_id]==1){
pthread_mutex_lock(&mutex2);
filas_vazia++;
cliente_fila--;
pthread_mutex_unlock(&mutex2);
sem_wait(&filas[(int)thread_id]--);
printf("O Caixa %d atendeu, e sobrou %d clientes na fila.", (int)thread_id, filas[(int)thread_id]);
printf("Falta ser atendido %d clientes.\\n\\n", clientes);
}
else{
pthread_mutex_lock(&mutex2);
cliente_fila--;
pthread_mutex_unlock(&mutex2);
sem_wait(&filas[(int)thread_id]--);
printf("O Caixa %d atendeu, e sobrou %d clientes na fila.", (int)thread_id, filas[(int)thread_id]);
printf("Falta ser atendido %d clientes.\\n\\n", clientes);
}
}
}
int main(int argc, char *argv[]){
int i,t;
for(i=0; i<5;i++){
filas[i] = 0;
}
srand( (unsigned)time(0) );
sem_init(&filas, 0, 5);
pthread_create(&chCliente, 0, ChegadaCliente, (void*)20);
for(t=0; t<5; t++){
filas[t] = 0;
if (pthread_create(&caixas[t], 0, AtendeCliente, (void*)t))
printf("Erro na criação da Thread da Fila: %d\\n", t);;
}
pthread_exit(0);
printf("Acabou threads\\n");
return 0;
}
| 1
|
#include <pthread.h>
void tq_init(struct tqFormat *tqh, int qlen) {
pthread_mutex_init(&tqh->count_mutex, 0);
pthread_cond_init (&tqh->count_empty_cv, 0);
pthread_cond_init (&tqh->count_full_cv, 0);
tqh->count = 0;
tqh->have_data = 1;
tqh->qlen = qlen;
printf("qlen %i\\n",tqh->qlen);
if ((tqh->q = malloc( (sizeof(void *) * tqh->qlen) )) == 0) {
perror("malloc");
exit(1);
}
}
int tq_get(struct tqFormat *tqh, void **data) {
int my_id = 0;
while((tqh->have_data) || (tqh->count != 0)) {
pthread_mutex_lock(&tqh->count_mutex);
if ((tqh->count == 0) && (tqh->have_data)) {
pthread_cond_signal(&tqh->count_empty_cv);
pthread_cond_wait(&tqh->count_full_cv, &tqh->count_mutex);
}
*data = 0;
if (tqh->count == 0) {
}
else {
tqh->count--;
*data = tqh->q[tqh->count];
}
if ((tqh->count == ( tqh->qlen / 2 )) && (tqh->have_data)) {
pthread_cond_signal(&tqh->count_empty_cv);
}
pthread_mutex_unlock(&tqh->count_mutex);
if (*data != 0) {
return 1;
}
}
printf("inc_count(): thread %d, count = %d, exiting\\n", my_id, tqh->count);
return 0;
}
void tq_add(struct tqFormat *tqh, void *data) {
pthread_mutex_lock(&tqh->count_mutex);
if (tqh->count == tqh->qlen) {
pthread_cond_wait(&tqh->count_empty_cv, &tqh->count_mutex);
}
if (tqh->count == 0) {
pthread_cond_signal(&tqh->count_full_cv);
}
tqh->q[tqh->count] = data;
++tqh->count;
pthread_mutex_unlock(&tqh->count_mutex);
}
void tq_end(struct tqFormat *tqh) {
pthread_mutex_lock(&tqh->count_mutex);
tqh->have_data = 0;
pthread_mutex_unlock(&tqh->count_mutex);
printf("waking threads\\n");
pthread_cond_signal(&tqh->count_full_cv);
pthread_cond_broadcast(&tqh->count_full_cv);
}
void tq_free(struct tqFormat *tqh) {
pthread_mutex_destroy(&tqh->count_mutex);
pthread_cond_destroy(&tqh->count_empty_cv);
pthread_cond_destroy(&tqh->count_full_cv);
}
| 0
|
#include <pthread.h>
struct product_cons
{
int buffer[5];
pthread_mutex_t lock;
int readpos, writepos;
pthread_cond_t notempty;
pthread_cond_t notfull;
pthread_mutex_t lock2;
int cnt_p;
pthread_mutex_t lock3;
int cnt_c;
}buffer;
void init(struct product_cons *p)
{
pthread_mutex_init(&p->lock, 0);
pthread_cond_init(&p->notempty, 0);
pthread_cond_init(&p->notfull, 0);
p->readpos = 0;
p->writepos = 0;
pthread_mutex_init(&p->lock2, 0);
p->cnt_p = 0;
pthread_mutex_init(&p->lock3, 0);
p->cnt_c = 0;
}
void fini(struct product_cons *p)
{
pthread_mutex_destroy(&p->lock);
pthread_cond_destroy(&p->notempty);
pthread_cond_destroy(&p->notfull);
p->readpos = 0;
p->writepos = 0;
pthread_mutex_destroy(&p->lock2);
p->cnt_p = 0;
pthread_mutex_destroy(&p->lock3);
p->cnt_c = 0;
}
void put(struct product_cons *p, int data)
{
pthread_mutex_lock(&p->lock);
while((p->writepos + 1) % 5 == p->readpos)
{
printf("producer wait for not full\\n");
pthread_cond_wait(&p->notfull, &p->lock);
}
p->buffer[p->writepos] = data;
p->writepos++;
if(p->writepos >= 5)
p->writepos = 0;
pthread_cond_signal(&p->notempty);
pthread_mutex_unlock(&p->lock);
}
int get(struct product_cons *p)
{
int data = 0;
pthread_mutex_lock(&p->lock);
while(p->writepos == p->readpos)
{
printf("consumer wait for not empty\\n");
pthread_cond_wait(&p->notempty,&p->lock);
}
data = p->buffer[p->readpos];
p->readpos++;
if(p->readpos >= 5)
p->readpos = 0;
pthread_cond_signal(&p->notfull);
pthread_mutex_unlock(&p->lock);
return data;
}
void *producer(void *data)
{
int flag = -1;
while(1)
{
pthread_mutex_lock(&buffer.lock2);
if(buffer.cnt_p < 50)
{
++buffer.cnt_p;
printf("%s put the %d product\\n", (char*)data, buffer.cnt_p);
put(&buffer, buffer.cnt_p);
}
else
flag = 0;
pthread_mutex_unlock(&buffer.lock2);
if(!flag)
break;
sleep(2);
}
printf("%s producer stopped\\n", (char*)data);
return 0;
}
void *consumer(void *data)
{
int flag = -1;
while(1)
{
pthread_mutex_lock(&buffer.lock3);
if(buffer.cnt_c < 50)
{
printf("%s get the %d product\\n", (char*)data, get(&buffer));
++buffer.cnt_c;
}
else
flag = 0;
pthread_mutex_unlock(&buffer.lock3);
if(!flag)
break;
sleep(2);
}
printf("%s consumer stopped\\n", (char*)data);
return 0;
}
int main(int argc, char *argv[])
{
pthread_t th_a[3],th_b[3];
void *retval;
init(&buffer);
pthread_create(&th_a[0], 0, producer, (void*)"th_a[0]");
pthread_create(&th_a[1], 0, producer, (void*)"th_a[1]");
pthread_create(&th_a[2], 0, producer, (void*)"th_a[2]");
pthread_create(&th_b[0], 0, consumer, (void*)"th_b[0]");
pthread_create(&th_b[1], 0, consumer, (void*)"th_b[1]");
pthread_create(&th_b[2], 0, consumer, (void*)"th_b[2]");
pthread_join(th_a[0], &retval);
pthread_join(th_a[1], &retval);
pthread_join(th_a[2], &retval);
pthread_join(th_b[0], &retval);
pthread_join(th_b[1], &retval);
pthread_join(th_b[2], &retval);
fini(&buffer);
return 0;
}
| 1
|
#include <pthread.h>
struct testdata
{
pthread_mutex_t mutex;
pthread_cond_t cond;
} td;
int t1_start = 0;
int signaled = 0;
void *t1_func(void *arg)
{
int rc;
struct timespec timeout;
struct timeval curtime;
if (pthread_mutex_lock(&td.mutex) != 0) {
fprintf(stderr,"Thread1: Fail to acquire mutex\\n");
exit(PTS_UNRESOLVED);
}
fprintf(stderr,"Thread1 started\\n");
t1_start = 1;
if (gettimeofday(&curtime, 0) !=0 ) {
fprintf(stderr,"Fail to get current time\\n");
exit(PTS_UNRESOLVED);
}
timeout.tv_sec = curtime.tv_sec;
timeout.tv_nsec = curtime.tv_usec * 1000;
timeout.tv_sec += 5;
fprintf(stderr,"Thread1 is waiting for the cond\\n");
rc = pthread_cond_timedwait(&td.cond, &td.mutex, &timeout);
if(rc != 0) {
if (rc == ETIMEDOUT) {
fprintf(stderr,"Thread1 stops waiting when time is out\\n");
exit(PTS_UNRESOLVED);
}
else {
fprintf(stderr,"pthread_cond_timedwait return %d\\n", rc);
exit(PTS_UNRESOLVED);
}
}
fprintf(stderr,"Thread1 wakened up\\n");
if(signaled == 0) {
fprintf(stderr,"Thread1 did not block on the cond at all\\n");
printf("Test FAILED\\n");
exit(PTS_FAIL);
}
pthread_mutex_unlock(&td.mutex);
return 0;
}
int main()
{
pthread_t thread1;
if (pthread_mutex_init(&td.mutex, 0) != 0) {
fprintf(stderr,"Fail to initialize mutex\\n");
return PTS_UNRESOLVED;
}
if (pthread_cond_init(&td.cond, 0) != 0) {
fprintf(stderr,"Fail to initialize cond\\n");
return PTS_UNRESOLVED;
}
if (pthread_create(&thread1, 0, t1_func, 0) != 0) {
fprintf(stderr,"Fail to create thread 1\\n");
return PTS_UNRESOLVED;
}
while(!t1_start)
usleep(100);
if (pthread_mutex_lock(&td.mutex) != 0) {
fprintf(stderr,"Main: Fail to acquire mutex\\n");
return PTS_UNRESOLVED;
}
if (pthread_mutex_unlock(&td.mutex) != 0) {
fprintf(stderr,"Main: Fail to release mutex\\n");
return PTS_UNRESOLVED;
}
sleep(1);
fprintf(stderr,"Time to wake up thread1 by signaling a condition\\n");
signaled = 1;
if (pthread_cond_signal(&td.cond) != 0) {
fprintf(stderr,"Main: Fail to signal cond\\n");
return PTS_UNRESOLVED;
}
pthread_join(thread1, 0);
printf("Test PASSED\\n");
return PTS_PASS;
}
| 0
|
#include <pthread.h>
int conPos = 0, proPos = 0;
int *buffer;
sem_t full, empty;
static int INDEX = 85;
pthread_cond_t consumer_cond;
pthread_mutex_t count_mutex;
FILE* logFile;
int main(void){
pthread_t threads[TTL_THREADS];
pthread_attr_t attr;
logFile = fopen("./logLinux.txt", "wt");
buffer = (int *) malloc(sizeof(int)*BUFFSIZE);
pthread_mutex_init(&count_mutex, 0);
sem_init(&full, 0, 0);
sem_init(&empty, 0, BUFFSIZE);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
long x;
for(x = 0; x < NUM_CONSUMER; x++)
pthread_create(&threads[x], &attr, producer, (void *)x);
for( ; x < TTL_THREADS; x++)
pthread_create(&threads[x], &attr, consumer, (void *)x);
for(x=0; x < TTL_THREADS; x++)
pthread_join(threads[x], 0);
fprintf(logFile, "Threads have completed\\n");
for(x = 0; x < BUFFSIZE; x++)
fprintf(logFile, "Buffer[%ld] is __** %4d **__\\n", x, buffer[x]);
fclose(logFile);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
sem_destroy(&full);
sem_destroy(&empty);
pthread_exit(0);
}
void *producer(void* t){
int product, i;
for(i = 0; i < INDEX; i++){
sleep((rand()%1)/100);
product = rand()%100 + 1;
sem_wait(&empty);
pthread_mutex_lock(&count_mutex);
buffer[proPos%BUFFSIZE] = product;
proPos++;
fprintf(logFile,"Produced %d <==\\n", product);
pthread_mutex_unlock(&count_mutex);
sem_post(&full);
}
pthread_exit(0);
}
void *consumer(void* t){
int consumed, i;
for(i = 0; i < INDEX; i++){
sleep(rand()%1);
sem_wait(&full);
pthread_mutex_lock(&count_mutex);
consumed = buffer[conPos%BUFFSIZE];
conPos++;
fprintf(logFile,"Consumed %d ==>\\n", consumed);
pthread_mutex_unlock(&count_mutex);
sem_post(&empty);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int propertyIndex, numThreads, segmentLength, numSegments;
char *S;
int Stail = 0;
int segmentsThatSatisfy = 0;
pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER;
char c0, c1, c2;
void *threadFunc(void* threadIndexArg)
{
long threadIndex = (long)threadIndexArg;
char character = 'a' + threadIndex;
unsigned int rseed = (unsigned int)threadIndex;
struct timespec sleepDuration = {0, 0};
while (Stail < numSegments * segmentLength)
{
sleepDuration.tv_nsec = (long int)(100000000.0 + rand_r(&rseed) * 400000000.0 / 32767);
nanosleep(&sleepDuration, 0);
pthread_mutex_lock(&mx);
if (Stail < numSegments * segmentLength)
S[Stail++] = character;
pthread_mutex_unlock(&mx);
}
int i, j;
for (i = 0; i < numSegments / numThreads; ++i)
{
int segmentStart = segmentLength * (i * numThreads + threadIndex);
int count[3] = { 0, 0, 0 };
for (j = 0; j < segmentLength; ++j)
{
char c = S[segmentStart+j];
if (c == c0) ++count[0];
if (c == c1) ++count[1];
if (c == c2) ++count[2];
}
int satisfies = 0;
switch (propertyIndex)
{
case 0: satisfies = (count[0] + count[1] == count[2]); break;
case 1: satisfies = (count[0] + count[1]*2 == count[2]); break;
case 2: satisfies = (count[0] * count[1] == count[2]); break;
default: satisfies = (count[0] - count[1] == count[2]); break;
}
if (satisfies)
{
pthread_mutex_lock(&mx);
++segmentsThatSatisfy;
pthread_mutex_unlock(&mx);
}
}
return 0;
}
int main(int argc, char ** argv)
{
if (argc != 8)
{
fprintf(stderr, "Usage: %s i N L M c0 c1 c2\\n", argv[0]);
fprintf(stderr, "i: index of the property which each segment needs to satisfy\\n");
fprintf(stderr, "N: number of threads\\n");
fprintf(stderr, "L: length of each segment\\n");
fprintf(stderr, "M: number of segments to generate\\n");
fprintf(stderr, "c0, c1, c2: letters to use in property check\\n");
exit(1);
}
propertyIndex = atoi(argv[1]);
numThreads = atoi(argv[2]);
segmentLength = atoi(argv[3]);
numSegments = atoi(argv[4]);
c0 = argv[5][0];
c1 = argv[6][0];
c2 = argv[7][0];
if (propertyIndex < 0 || propertyIndex > 3)
{
fprintf(stderr, "Error: property index must be in the range [0, 3] (got %d)\\n", propertyIndex);
exit(1);
}
if (numThreads < 3 || numThreads > 8)
{
fprintf(stderr, "Error: number of threads must be in the range [3, 8] (got %d)\\n", numThreads);
exit(1);
}
if (segmentLength < 0) segmentLength = -segmentLength;
if (numSegments < 0) numSegments = -numSegments;
char s[segmentLength * numSegments];
S = s;
pthread_t threads[numThreads];
long threadIndex;
fprintf(stderr, "Creating threads... ");
for (threadIndex = 0; threadIndex < numThreads; ++threadIndex)
pthread_create(&threads[threadIndex], 0, threadFunc, (void*)threadIndex);
fprintf(stderr, "All threads created.\\nWaiting for completion... ");
for (threadIndex = 0; threadIndex < numThreads; ++threadIndex)
pthread_join(threads[threadIndex], 0);
fprintf(stderr, "All threads completed.\\n");
FILE *outFile = fopen("out.txt", "w");
fprintf(outFile, "%s\\n%d\\n", S, segmentsThatSatisfy);
fprintf(stdout, "%s\\n%d\\n", S, segmentsThatSatisfy);
fclose(outFile);
return 0;
}
| 0
|
#include <pthread.h>
struct Madt *apics = 0;
struct Srat *srat = 0;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static void *core_proxy(void *arg)
{
int coreid = (int)(long)arg;
pin_to_core(coreid);
struct Apicst *new_st = calloc(1, sizeof(struct Apicst));
new_st->type = ASlapic;
new_st->lapic.id = get_apic_id();
struct Srat *new_srat = calloc(1, sizeof(struct Srat));
new_srat->type = SRlapic;
new_srat->lapic.dom = numa_node_of_cpu(coreid);
new_srat->lapic.apic = new_st->lapic.id;
pthread_mutex_lock(&mutex);
new_st->next = apics->st;
apics->st = new_st;
new_srat->next = srat;
srat = new_srat;
pthread_mutex_unlock(&mutex);
}
void acpiinit()
{
int ncpus = get_nprocs();
pthread_t pthread[ncpus];
apics = calloc(1, sizeof(struct Madt));
for (int i=0; i<ncpus; i++) {
pthread_create(&pthread[i], 0, core_proxy, (void*)(long)i);
}
for (int i=0; i<ncpus; i++) {
pthread_join(pthread[i], 0);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* thread_write(void*);
void* thread_read(void*);
int
main(int argc, char **argv)
{
pthread_t t_write;
pthread_t t_read;
evthread_use_pthreads();
struct evbuffer* buf = evbuffer_new();
if (0 == buf) {
printf("evbuffer_new failed");
return -1;
}
evbuffer_enable_locking(buf,0);
pthread_create(&t_write,0,thread_write,(void*)buf);
pthread_create(&t_read,0,thread_read,(void*)buf);
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond,&mutex);
pthread_mutex_unlock(&mutex);
evbuffer_free(buf);
return (0);
}
void* thread_read(void* arg) {
struct evbuffer* buf = (struct evbuffer*)arg;
char* read_message;
size_t read_message_len;
size_t length = 0;
while(1) {
read_message = evbuffer_readln(buf,&read_message_len,EVBUFFER_EOL_CRLF);
if (0 != read_message) {
printf("thread read :%s\\n",read_message);
length += read_message_len;
}
sleep(1);
}
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond,&mutex);
pthread_mutex_unlock(&mutex);
while(1){
read_message = evbuffer_readln(buf,&read_message_len,EVBUFFER_EOL_CRLF);
if(read_message==0)
break;
length += read_message_len;
}
printf("thread read total :%d\\n",length);
}
void* thread_write(void* arg) {
char message_s[]="hello world at %d\\n";
char message[128];
int message_len;
int count = 0;
size_t length;
size_t total = 0;
struct evbuffer* buf = (struct evbuffer*)arg;
while(1) {
sprintf(message,message_s,++count);
message_len = strlen(message);
evbuffer_add(buf,message,message_len);
length = evbuffer_get_length(buf);
printf("thread write :%d\\n",length);
total += message_len;
sleep(1);
}
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
printf("thread write total :%d\\n",total);
}
| 0
|
#include <pthread.h>
pthread_mutex_t refr;
int visit[10][2];
bool ownerdo = 0;
int nbotle_refr = 10;
void *guestFunc(void* i)
{
int arg = * (int*) i;
while(1)
{
visit[arg][1]=1;
pthread_mutex_lock(&refr);
visit[arg][1]=2;
napms(5000);
if(ownerdo==0)
pthread_mutex_unlock(&refr);
visit[arg][1]=3;
napms(10000);
--nbotle_refr;
++visit[arg][2];
if(visit[arg][2]==10) {visit[arg][1]=4; napms(120000);}
}
}
void *ownerFunc()
{
pthread_mutex_init(&refr, 0);
srand(time(0));
while(1)
{
if(rand()%50 +1 == 1)
{
ownerdo=1;
pthread_mutex_init(&refr, 0);
pthread_mutex_lock(&refr);
napms(30000);
pthread_mutex_unlock(&refr);
nbotle_refr+=3;
ownerdo=0;
}
napms(1000);
}
}
int h;
int main()
{
pthread_t owner;
pthread_t guests[10];
initscr();
printw("\\n");
pthread_create(&owner, 0, ownerFunc, 0);
int j;
for (j = 0; j < 10; ++j)
{
pthread_create(&guests[j], 0, guestFunc, &j);
visit[j][2] = 0;
}
while(1)
{
for(h = 0; h < 10; ++h)
{
printw("\\n");
printw(" %d guest ", h);
printw("drank %d bottles. Now he ", visit[h][2]);
if(visit[h][1]==1) printw("stands in line to refrigerator.");
if(visit[h][1]==2) printw("takes a bottle of beer.");
if(visit[h][1]==3) printw("drinks beer.");
if(visit[h][1]==4) printw("sleeps.");
printw("\\n\\n\\n");
}
if(ownerdo==1) printw(" Owner finds the bottle and puts %d new bottle\\n *Visitor can not use the fridge\\n\\n", 10 -1);
if(ownerdo==0) printw(" Owner is smoking some Nakhla\\n\\n");
printw(" Bottles in the fridge = %d\\n", nbotle_refr );
refresh();
napms(1000);
clear();
if (nbotle_refr<=0) { printw("The bear ran out. GAME OVER"); refresh(); napms(60000); endwin();}
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer = 0;
void* producer(void *ptr) {
int i;
for (i = 1; i <= 10; i++) {
pthread_mutex_lock(&the_mutex);
while (buffer != 0)
pthread_cond_wait(&condp, &the_mutex);
buffer = i;
printf("P: buffer=%d\\n",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);
buffer = 0;
printf("C: buffer=%d\\n",i);
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(con, 0);
pthread_join(pro, 0);
pthread_mutex_destroy(&the_mutex);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
}
| 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);
fp = 0;
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 (0 == --fp->f_count) {
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
fp = 0;
}
else {
pthread_mutex_unlock(&fp->f_lock);
}
}
| 1
|
#include <pthread.h>
static inline void init_send_buffer(struct send_buffer *s, char *ptr)
{
memset(s, 0, sizeof(struct send_buffer));
s->start_ptr = ptr;
s->end_ptr = ptr;
pthread_mutex_init(&(s->lock), 0);
}
static inline void lock_send_buffer(struct send_buffer *s)
{
pthread_mutex_lock(&s->lock);
}
static inline void unlock_send_buffer(struct send_buffer *s)
{
pthread_mutex_unlock(&s->lock);
}
int init_send_buffers(struct sb_config *sb, int buffer_size, int n_buffers)
{
void *ptr, *p;
int i;
memset(sb, 0, sizeof(struct sb_config));
if ((ptr = (void *)malloc((buffer_size * n_buffers))) == 0)
return -1;
if ((sb->buffers =
(void *)malloc(sizeof(struct send_buffer) * n_buffers)) == 0)
return -1;
for (i = 0, p = sb->buffers; i < n_buffers; ++i)
init_send_buffer((p + (i * sizeof(struct send_buffer))),
(ptr + (i * buffer_size)));
sb->buffer_size = buffer_size;
sb->n_buffers = n_buffers;
pthread_mutex_init(&(sb->lock), 0);
return 0;
}
int copy_to_send_buffer(struct sb_config *sb, void *p, unsigned int len)
{
struct send_buffer *tmp = &(sb->buffers[sb->current_buffer]);
unsigned int unoccupied;
lock_send_buffer(tmp);
unoccupied = (sb->buffer_size - (tmp->end_ptr - tmp->start_ptr));
if (unoccupied >= len) {
memcpy(tmp->end_ptr, p, len);
tmp->end_ptr += len;
unlock_send_buffer(tmp);
return 0;
}
unlock_send_buffer(tmp);
pthread_mutex_lock(&sb->lock);
++(sb->current_buffer);
sb->current_buffer %= sb->n_buffers;
pthread_mutex_unlock(&sb->lock);
tmp = &(sb->buffers[sb->current_buffer]);
lock_send_buffer(tmp);
unoccupied = (sb->buffer_size - (tmp->end_ptr - tmp->start_ptr));
if (unoccupied >= len) {
memcpy(tmp->end_ptr, p, len);
tmp->end_ptr += len;
unlock_send_buffer(tmp);
return 0;
}
unlock_send_buffer(tmp);
return -1;
}
static inline int __flush_send_buffer(struct send_buffer *s, struct connection_pair *cp){
register int j, l;
lock_send_buffer(s);
l= (s->end_ptr - s->start_ptr);
if(l <= 0){
unlock_send_buffer(s);
return l;
}
for (j = 0; j < cp->n_remote; ++j) {
if (!cp->remote[j].socketfd)
continue;
if (write (cp->remote[j].socketfd, s->start_ptr, l) < 0) {
close(cp->remote[j].socketfd);
fclose(cp->remote[j].socketfp);
memset(&cp->remote[j], 0, sizeof(struct connection));
continue;
}
}
s->end_ptr = s->start_ptr;
unlock_send_buffer(s);
return l;
}
void flush_send_buffers(struct sb_config *sb, struct connection_pair *cp)
{
register int i, cb, pb;
pthread_mutex_lock(&sb->lock);
cb = sb->current_buffer;
pb = sb->prev_buffer;
pthread_mutex_unlock(&sb->lock);
if (cb > 0) {
for (i = (cb - 1); i != 0; --i)
__flush_send_buffer(&sb->buffers[i], cp);
__flush_send_buffer(&sb->buffers[0], cp);
}
if (pb > cb) {
fprintf(stderr, "looks like buffer wrapped around. (%d, %d)", pb, cb);
for (i = pb; i < sb->n_buffers; ++i)
__flush_send_buffer(&sb->buffers[i], cp);
}
if (pb == cb) {
if (sb->skips == 8) {
fprintf(stderr, "buffer %d had 8 chances to fill but did not!\\n", cb);
if(__flush_send_buffer(&sb->buffers[cb], cp) <= 0){
u_sleep(0, FLUSH_TIMEOUT);
}else{
sb->skips = 0;
}
} else {
++(sb->skips);
}
}
pthread_mutex_lock(&sb->lock);
sb->prev_buffer = cb;
pthread_mutex_unlock(&sb->lock);
}
| 0
|
#include <pthread.h>
pthread_mutex_t gm;
int node_id;
struct node *next ;
}node_t;
{
int arr[5];
node_t *head;
} llist_t;
struct thread_data {
int tid;
llist_t *local_data;
};
void *t(void *args){
nvcheckpoint();
pthread_exit(0);
}
node_t* new_node(int node_id, node_t *next)
{
printf("New node method\\n");
node_t* node = (node_t*)nvmalloc(sizeof(node_t), (char*)"f");
node->node_id = node_id;
node->next = next;
return node;
}
llist_t* list_new()
{
printf("Create list method\\n");
llist_t *f = (llist_t*)nvmalloc(sizeof(llist_t), (char*)"f");
f->head = new_node(10, 0);
return f;
}
void *add(void *args){
struct thread_data *data = (struct thread_data*)args;
int tid = data->tid;
llist_t *tmp = data->local_data;
pthread_mutex_lock(&gm);
pthread_mutex_unlock(&gm);
free(args);
pthread_exit(0);
}
int main(){
pthread_mutex_init(&gm, 0);
pthread_t tid[1];
pthread_t tid1;
printf("Checking crash status\\n");
if ( isCrashed() ) {
printf("I need to recover!\\n");
llist_t *f = (llist_t*)nvmalloc(sizeof(llist_t), (char*)"f");
nvrecover(f, sizeof(llist_t), (char *)"f");
if(f->head)
printf("f->head->node_id --> %d\\n", f->head->node_id);
else
printf("nil head\\n");
printf("f->arr --> %d, %d, %d, %d\\n", f->arr[0], f->arr[1], f->arr[2],f->arr[3]);
free(f);
}
else{
printf("Program did not crash before, continue normal execution.\\n");
pthread_create(&tid1, 0, t, 0);
llist_t *f = list_new();
f->arr[0] = 20;
f->arr[1] = 30;
f->arr[2] = 40;
f->arr[3] = 50;
printf("finish writing to values\\n");
nvcheckpoint();
printf("f->arr --> %d, %d, %d, %d\\n", f->arr[0], f->arr[1], f->arr[2],f->arr[3]);
printf("f->head->node_id --> %d\\n", f->head->node_id);
pthread_join(tid1, 0);
printf("internally abort!\\n");
abort();
}
printf("-------------main exits-------------------\\n");
return 0;
}
| 1
|
#include <pthread.h>
int *all_buffers;
int num_producers;
int num_consumers;
int num_buffers;
int num_items;
int inpipe;
int outpipe;
int num_consumer_iterations;
pthread_mutex_t should_continue_consuming_lock;
sem_t total_full;
sem_t buffer_lock;
sem_t send_message_lock;
bool shouldContinueConsuming() {
if (num_consumer_iterations <= num_items) {
num_consumer_iterations++;
return 1;
} else {
return 0;
}
}
void send_message_to_producer(int index){
int write_result = write(outpipe, &index, sizeof(int));
if (write_result < 0) {
printf("Consumer write_result: %d, error string: %s\\n", write_result, strerror(errno));
}
}
void *consumer(void *t_number) {
int thread_number = *((int *) t_number);
while (1) {
pthread_mutex_lock(&should_continue_consuming_lock);
bool shouldContinue = shouldContinueConsuming();
pthread_mutex_unlock(&should_continue_consuming_lock);
if (shouldContinue == 0) {
break;
}
while (sem_trywait(&total_full) != 0){
pthread_yield();
}
int index_of_buffer_that_was_decremented = 0;
sem_wait(&buffer_lock);
int i;
for (i = 0; i < num_buffers; i++) {
if (all_buffers[i]> 0) {
all_buffers[i]--;
index_of_buffer_that_was_decremented = i;
break;
}
}
sem_post(&buffer_lock);
sem_wait(&send_message_lock);
send_message_to_producer(index_of_buffer_that_was_decremented);
sem_post(&send_message_lock);
}
}
void handle_received_message(){
int received_messages = 0;
while (received_messages <= num_items) {
int index_to_increment;
if (read(inpipe, &index_to_increment, sizeof(int)) == 0) {
break;
}
sem_wait(&buffer_lock);
all_buffers[index_to_increment]++;
sem_post(&total_full);
sem_post(&buffer_lock);
received_messages++;
}
}
void *pipereader(void *unneeded_arg) {
handle_received_message();
close(inpipe);
}
void main(int argc, char *argv[]) {
if (argc != 7) {
printf("Wrong number of arguments...Exiting\\n");
return;
}
num_producers = atoi(argv[1]);
num_consumers = atoi(argv[2]);
num_buffers = atoi(argv[3]);
num_items = atoi(argv[4]);
inpipe = atoi(argv[5]);
outpipe = atoi(argv[6]);
printf("Num producers: %d, Num Conusumers: %d,"
" Num Buffers: %d, Num Items: %d\\n",
num_producers, num_consumers, num_buffers, num_items);
num_consumer_iterations = 0;
all_buffers = (int *)malloc(num_buffers * sizeof(int));
int i;
for (i = 0; i < num_buffers; ++i) {
all_buffers[i] = 0;
}
sem_init(&total_full,0,0);
sem_init(&buffer_lock,0,1);
sem_init(&send_message_lock,0,1);
pthread_mutex_init(&should_continue_consuming_lock, 0);
pthread_t reader;
pthread_create(&reader, 0, &pipereader, 0);
sleep(1);
pthread_t *consumer_threads = (pthread_t *) malloc(num_consumers * sizeof(pthread_t));
int *consumer_counters = (int *) malloc(num_consumers * sizeof(int));
int counter;
for (counter = 0; counter < num_consumers; ++counter) {
consumer_counters[counter] = counter;
}
for (counter = 0; counter < num_consumers; ++counter) {
printf("Creating consumer thread %d\\n", counter);
pthread_create(&consumer_threads[counter], 0, consumer, (void *) &consumer_counters[counter]);
}
for (counter = 0; counter < num_consumers; ++counter) {
pthread_join(consumer_threads[counter], 0);
}
close(outpipe);
pthread_join(reader, 0);
}
| 0
|
#include <pthread.h>
int somma_voti;
int votanti;
} Film;
struct Film arrayFilm[10];
sem_t barriera;
sem_t evento;
pthread_mutex_t mutex_threads[10];
int completati=0, bestfilm;
float votomedio = 0, bestvoto =0;
void *ThreadCode(void *t) {
long tid;
long result = 1;
int i;
int voto;
tid = (int)t;
for (i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex_threads[i]);
voto = rand() % 10 + 1;
arrayFilm[i].somma_voti += voto;
arrayFilm[i].votanti++;
completati++;
printf("Utente %ld. Film %d - Voto %d\\n", tid, i, voto);
if(completati == 10*3){
sem_post(&evento);
}
pthread_mutex_unlock(&mutex_threads[i]);
}
sem_wait(&barriera);
sem_post(&barriera);
printf("Utente %ld: guarda film %d\\n", tid, bestfilm);
sleep(rand() % 5 + 5);
printf("Utente %ld: finisce di guardare film %d\\n", tid, bestfilm);
pthread_exit((void*) result);
}
int main (int argc, char *argv[]) {
int i, rc;
long t;
long result;
float voto;
pthread_t threads[3];
sem_init (&barriera, 0, 0);
sem_init (&evento, 0, 0);
srand(time(0));
for (i = 0; i < 10; i++) {
pthread_mutex_init(&mutex_threads[i], 0);
arrayFilm[i] = (Film){.somma_voti = 0, .votanti = 0};
}
for (t = 0; t < 3; t++) {
printf("Main: Intervistato %ld.\\n", t);
rc = pthread_create(&threads[t], 0, ThreadCode, (void*)t);
if (rc) {
printf ("ERRORE: %d\\n", rc);
exit(-1);
}
}
sem_wait(&evento);
printf("\\n\\nMain: Risultati finali.\\n");
for (i = 0; i < 10; i++) {
votomedio = arrayFilm[i].somma_voti/((double)arrayFilm[i].votanti);
printf("Film %d: %f\\n", i, votomedio);
if(votomedio> bestvoto)
{
bestvoto = votomedio;
bestfilm=i;
}
}
printf("\\nMiglior film %d con voto %f\\n\\n",bestfilm,bestvoto);
sem_post(&barriera);
for (t = 0; t < 3; t++) {
rc = pthread_join(threads[t], (void *)&result);
if (rc) {
printf ("ERRORE: join thread %ld codice %d.\\n", t, rc);
} else {
printf("Main: Finito Utente %ld.\\n", t);
}
}
printf("Main: Termino...\\n\\n");
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex_muzi;
pthread_mutex_t mutex_zeny;
sem_t emptyRoom;
int muziCount;
int zenyCount;
sem_t muzi;
sem_t zeny;
sem_t turnstile;
} Buffer;
int id;
Buffer * buffer;
} WorkerData;
void BufferInit(Buffer * buffer)
{
pthread_mutex_init(&buffer->mutex_muzi, 0);
pthread_mutex_init(&buffer->mutex_zeny, 0);
sem_init(&buffer->emptyRoom, 0, 1);
sem_init(&buffer->turnstile, 0, 1);
sem_init(&buffer->zeny, 0, 3);
sem_init(&buffer->muzi, 0, 3);
buffer->muziCount = 0;
buffer->zenyCount = 0;
}
void * muziThread(void *inputData) {
WorkerData * data = (WorkerData*) inputData;
Buffer *buffer = data->buffer;
int ID = data->id;
while(1) {
sem_wait(&buffer->turnstile);
pthread_mutex_lock(&buffer->mutex_muzi);
buffer->muziCount++;
if (buffer->muziCount == 1) {
sem_wait(&buffer->emptyRoom);
}
pthread_mutex_unlock(&buffer->mutex_muzi);
sem_post(&buffer->turnstile);
sem_wait(&buffer->muzi);
printf("kupem sa muz s ID:%2d \\n", ID);
usleep((30 + rand()%4) * 1000);
printf("odchadzam muz s ID:%2d \\n", ID);
sem_post(&buffer->muzi);
pthread_mutex_lock(&buffer->mutex_muzi);
buffer->muziCount--;
if (buffer->muziCount == 0) {
sem_post(&buffer->emptyRoom);
}
pthread_mutex_unlock(&buffer->mutex_muzi);
}
}
void * zenyThread(void *inputData) {
WorkerData * data = (WorkerData*) inputData;
Buffer *buffer = data->buffer;
int ID = data->id;
while(1) {
sem_wait(&buffer->turnstile);
pthread_mutex_lock(&buffer->mutex_zeny);
buffer->zenyCount++;
if (buffer->zenyCount == 1) {
sem_wait(&buffer->emptyRoom);
}
pthread_mutex_unlock(&buffer->mutex_zeny);
sem_post(&buffer->turnstile);
sem_wait(&buffer->zeny);
printf("kupem sa zena s ID:%2d \\n", ID);
usleep((30 + rand()%4) * 1000);
printf("odchadzam sa zena s ID:%2d \\n", ID);
sem_post(&buffer->zeny);
pthread_mutex_lock(&buffer->mutex_zeny);
buffer->zenyCount--;
if (buffer->zenyCount == 0) {
sem_post(&buffer->emptyRoom);
}
pthread_mutex_unlock(&buffer->mutex_zeny);
}
}
int main(int argc, char *argv[]) {
int const MUZI = 20;
int const ZENY = 20;
pthread_t muziID[MUZI];
pthread_t zenyID[ZENY];
int i;
Buffer buffer;
WorkerData * data;
srand(time(0));
BufferInit(&buffer);
for(i = 0; i < MUZI; i++ ) {
data = (WorkerData*) malloc(sizeof(WorkerData));
data->id = i;
data->buffer = &buffer;
pthread_create(&muziID[i], 0, muziThread, (void*) data);
}
for(i = 0; i < ZENY; i++ ) {
data = (WorkerData*) malloc(sizeof(WorkerData));
data->id = i;
data->buffer = &buffer;
pthread_create(&zenyID[i], 0, zenyThread, (void*) data);
}
for(i = 0; i < MUZI; i++ ) {
pthread_join(muziID[i], 0);
}
for(i = 0; i < ZENY; i++ ) {
pthread_join(zenyID[i], 0);
}
printf("vsetky pracovne vlakna ukoncene\\n");
return 0;
}
| 0
|
#include <pthread.h>
pthread_t *Students;
pthread_t TA;
int ChairsCount = 0;
int CurrentIndex = 0;
sem_t TA_Sleep;
sem_t Student_Sem;
sem_t ChairsSem[3];
pthread_mutex_t ChairAccess;
void *TA_Activity();
void *Student_Activity(void *threadID);
int main(int argc, char* argv[])
{
int number_of_students;
int id;
srand(time(0));
sem_init(&TA_Sleep, 0, 0);
sem_init(&Student_Sem, 0, 0);
for(id = 0; id < 3; ++id)
sem_init(&ChairsSem[id], 0, 0);
pthread_mutex_init(&ChairAccess, 0);
if(argc<2)
{
printf("Number of Students not specified. Using default (5) students.\\n");
number_of_students = 5;
}
else
{
printf("Number of Students specified. Creating %d threads.\\n", number_of_students);
number_of_students = atoi(argv[1]);
}
Students = (pthread_t*) malloc(sizeof(pthread_t)*number_of_students);
pthread_create(&TA, 0, TA_Activity, 0);
for(id = 0; id < number_of_students; id++)
pthread_create(&Students[id], 0, Student_Activity,(void*) (long)id);
pthread_join(TA, 0);
for(id = 0; id < number_of_students; id++)
pthread_join(Students[id], 0);
free(Students);
return 0;
}
void *TA_Activity()
{
while(1)
{
sem_wait(&TA_Sleep);
printf("~~~~~~~~~~~~~~~~~~~~~TA has been awakened by a student.~~~~~~~~~~~~~~~~~~~~~\\n");
while(1)
{
pthread_mutex_lock(&ChairAccess);
if(ChairsCount == 0)
{
pthread_mutex_unlock(&ChairAccess);
break;
}
sem_post(&ChairsSem[CurrentIndex]);
ChairsCount--;
printf("Student left his/her chair. Remaining Chairs %d\\n", 3 - ChairsCount);
CurrentIndex = (CurrentIndex + 1) % 3;
pthread_mutex_unlock(&ChairAccess);
printf("\\t TA is currently helping the student.\\n");
sleep(5);
sem_post(&Student_Sem);
usleep(1000);
}
}
}
void *Student_Activity(void *threadID)
{
int ProgrammingTime;
while(1)
{
printf("Student %ld is doing programming assignment.\\n", (long)threadID);
ProgrammingTime = rand() % 10 + 1;
sleep(ProgrammingTime);
printf("Student %ld needs help from the TA\\n", (long)threadID);
pthread_mutex_lock(&ChairAccess);
int count = ChairsCount;
pthread_mutex_unlock(&ChairAccess);
if(count < 3)
{
if(count == 0)
sem_post(&TA_Sleep);
else
printf("Student %ld sat on a chair waiting for the TA to finish. \\n", (long)threadID);
pthread_mutex_lock(&ChairAccess);
int index = (CurrentIndex + ChairsCount) % 3;
ChairsCount++;
printf("Student sat on chair.Chairs Remaining: %d\\n", 3 - ChairsCount);
pthread_mutex_unlock(&ChairAccess);
sem_wait(&ChairsSem[index]);
printf("\\t Student %ld is getting help from the TA. \\n", (long)threadID);
sem_wait(&Student_Sem);
printf("Student %ld left TA room.\\n",(long)threadID);
}
else
printf("Student %ld will return at another time. \\n", (long)threadID);
}
}
| 1
|
#include <pthread.h>
pthread_t atendentes [3];
pthread_t gclientes;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex3 = PTHREAD_MUTEX_INITIALIZER;
int filas_vazias = 3;
int clientes = 9;
int i;
int ncli = 0;
int tem_cliente = 0;
int tamfila[3];
sem_t empty;
sem_t full;
void NoCaixa (float delay1) {
if (delay1<0.001) return;
float inst1=0;
float inst2=0;
inst1 = (float)clock()/(float)CLOCKS_PER_SEC;
while (inst2-inst1<delay1) inst2 = (float)clock()/(float)CLOCKS_PER_SEC;
return;
}
void *Clientes(void *thread_id){
int menorfila;
int caixa;
while(ncli < 9){
menorfila = 9;
caixa = 3 + 1;
pthread_mutex_lock(&mutex);
for(i=0; i<3; i++){
if(tamfila[i] < menorfila){
menorfila = tamfila[i];
caixa = i;
}
}
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&mutex);
tamfila[caixa]++;
tem_cliente++;
ncli++;
printf("INSERIRU CLIENTE NA FILA DO CAIXA: %d \\n", caixa);
pthread_mutex_unlock(&mutex);
}
}
int *Atende(void *thread_id){
int caixa;
int maiorfila;
int caixa_maiorfila;
while (clientes > 0){
if(tem_cliente > 0){
caixa = (int)thread_id;
maiorfila = tamfila[0];
caixa_maiorfila = 0;
if(tamfila[caixa] == 0){
pthread_mutex_lock(&mutex);
for(i=0; i<3; i++){
if(tamfila[i] > maiorfila && tamfila[i] > 0 ){
maiorfila = tamfila[i];
caixa_maiorfila = i;
}
}
pthread_mutex_unlock(&mutex);
NoCaixa (2);
pthread_mutex_lock(&mutex3);
printf("O CAIXA %d ATENDEU CLIENTE DO CAIXA %d\\n\\n", caixa, caixa_maiorfila);
tamfila[caixa_maiorfila]--;
tem_cliente--;
clientes--;
pthread_mutex_unlock(&mutex3);
}
else{
NoCaixa (2);
pthread_mutex_lock(&mutex);
printf("O CAIXA %d ATENDEU - %d\\n\\n", caixa);
tamfila[caixa]--;
tem_cliente--;
clientes--;
pthread_mutex_unlock(&mutex);
}
}
}
printf("Acabou o processamento da thread %d\\n", (int)thread_id);
pthread_exit(0);
}
int main(int argc, char *argv[]) {
int t;
srand( (unsigned)time(0) );
sem_init(&empty, 0, 3);
sem_init(&full, 0, 0);
for(i=0; i<3; i++){
tamfila[i] = 0;
}
pthread_create(&gclientes, 0, Clientes, (void*)9);
for (t = 0; t<3; t++){
if (pthread_create(&atendentes[t], 0, Atende, (void*)t)) {
printf("Erro criação fila %d\\n", t);
}
}
printf("Acabou a thread\\n");
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
int val;
struct node_t *next;
} node_t;
node_t *head;
node_t *tail;
pthread_mutex_t *head_lock;
pthread_mutex_t *tail_lock;
} queue_t;
queue_t *Q;
int ready = 0;
int done = 0;
pthread_mutex_t ready_lock;
pthread_mutex_t done_lock;
uint32_t queue_rgn_id;
void traverse();
void initialize() {
void *rgn_root = NVM_GetRegionRoot(queue_rgn_id);
if (rgn_root) {
Q = (queue_t *)rgn_root;
Q->head_lock = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
pthread_mutex_init(Q->head_lock, 0);
Q->tail_lock = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
pthread_mutex_init(Q->tail_lock, 0);
fprintf(stderr, "Found queue at %p\\n", (void *)Q);
traverse();
} else {
node_t *node = (node_t *)nvm_alloc(sizeof(node_t), queue_rgn_id);
node->val = -1;
node->next = 0;
Q = (queue_t *)nvm_alloc(sizeof(queue_t), queue_rgn_id);
fprintf(stderr, "Created Q at %p\\n", (void *)Q);
Q->head_lock = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
pthread_mutex_init(Q->head_lock, 0);
Q->tail_lock = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
pthread_mutex_init(Q->tail_lock, 0);
NVM_BEGIN_DURABLE();
Q->head = node;
Q->tail = node;
NVM_SetRegionRoot(queue_rgn_id, Q);
NVM_END_DURABLE();
}
}
void traverse() {
assert(Q);
assert(Q->head);
assert(Q->tail);
node_t *t = Q->head;
fprintf(stderr, "Contents of existing queue: ");
int elem_count = 0;
while (t) {
++elem_count;
t = t->next;
}
fprintf(stderr, "elem_count = %d\\n", elem_count);
}
void enqueue(int val) {
node_t *node = (node_t *)nvm_alloc(sizeof(node_t), queue_rgn_id);
node->val = val;
node->next = 0;
pthread_mutex_lock(Q->tail_lock);
Q->tail->next = node;
Q->tail = node;
pthread_mutex_unlock(Q->tail_lock);
}
int dequeue(int *valp) {
pthread_mutex_lock(Q->head_lock);
node_t *node = Q->head;
node_t *new_head = node->next;
if (new_head == 0) {
pthread_mutex_unlock(Q->head_lock);
return 0;
}
*valp = new_head->val;
Q->head = new_head;
pthread_mutex_unlock(Q->head_lock);
nvm_free(node);
return 1;
}
void *do_work() {
pthread_mutex_lock(&ready_lock);
ready = 1;
pthread_mutex_unlock(&ready_lock);
int global_count = 0;
int t = 0;
while (1) {
int val;
int status = dequeue(&val);
if (status) {
++global_count;
} else if (t) {
break;
}
pthread_mutex_lock(&done_lock);
t = done;
pthread_mutex_unlock(&done_lock);
}
return 0;
}
int main() {
pthread_t thread;
struct timeval tv_start;
struct timeval tv_end;
gettimeofday(&tv_start, 0);
NVM_Initialize();
queue_rgn_id = NVM_FindOrCreateRegion("queue", O_RDWR, 0);
initialize();
pthread_create(&thread, 0, (void *(*)(void *))do_work, 0);
int t = 0;
while (!t) {
pthread_mutex_lock(&ready_lock);
t = ready;
pthread_mutex_unlock(&ready_lock);
}
for (int i = 0; i < 100000; ++i) {
enqueue(i);
}
pthread_mutex_lock(&done_lock);
done = 1;
pthread_mutex_unlock(&done_lock);
pthread_join(thread, 0);
NVM_CloseRegion(queue_rgn_id);
NVM_Finalize();
gettimeofday(&tv_end, 0);
fprintf(stderr, "time elapsed %ld us\\n",
tv_end.tv_usec - tv_start.tv_usec +
(tv_end.tv_sec - tv_start.tv_sec) * 1000000);
return 0;
}
| 1
|
#include <pthread.h> extern void __VERIFIER_error() ;
void __VERIFIER_assert(int cond) { if (!(cond)) { ERROR: __VERIFIER_error(); } return; }
int myglobal;
pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
void *thread_function_mutex(void *arg)
{
int i,j;
for ( i=0; i<20; i++ )
{
pthread_mutex_lock(&mymutex);
j=myglobal;
j=j+1;
printf("\\nIn thread_function_mutex..\\t");
myglobal=j;
pthread_mutex_unlock(&mymutex);
}
return 0;
}
int main(void)
{
pthread_t mythread;
int i;
printf("\\n\\t\\t---------------------------------------------------------------------------");
printf("\\n\\t\\t Centre for Development of Advanced Computing (C-DAC)");
printf("\\n\\t\\t Email : hpcfte@cdac.in");
printf("\\n\\t\\t---------------------------------------------------------------------------");
myglobal = 0;
if ( pthread_create( &mythread, 0, thread_function_mutex, 0) )
{
exit(-1);
}
for ( i=0; i<20; i++)
{
pthread_mutex_lock(&mymutex);
myglobal=myglobal+1;
pthread_mutex_unlock(&mymutex);
}
if ( pthread_join ( mythread, 0 ) )
{
exit(-1);
}
__VERIFIER_assert(myglobal == 40);
exit(0);
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.