text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
int gnum = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *thread1(void *);
void *thread2(void *);
int main(void)
{
pthread_t t1;
pthread_t t2;
pthread_create(&t1, 0, thread1, (void *)0);
pthread_create(&t2, 0, thread2, (void *)0);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
exit(0);
}
void *thread1(void *m)
{
for(;;) {
pthread_mutex_lock(&mutex);
if(gnum % 3 == 0)
pthread_cond_signal(&cond);
else {
printf("thread1: %d\\n", gnum);
gnum ++;
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void *thread2(void *m)
{
while(1) {
pthread_mutex_lock(&mutex);
if(gnum % 3 != 0)
pthread_cond_wait(&cond, &mutex);
printf("thread2: %d\\n", gnum);
gnum ++;
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t mulo = PTHREAD_MUTEX_INITIALIZER;
int total;
int portNumber;
int ServerSocket;
struct sockaddr_in ServerStructure, ClientStructure;
pthread_cond_t c = PTHREAD_COND_INITIALIZER;
void *socket_connection(void *passedvalue);
int main(int argc, char *argv[]) {
pthread_mutex_init(&mulo, 0);
if (argc < 2) {
fprintf(stderr, "ERROR, no port provided\\n");
exit(1);
}
if ((ServerSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket");
exit(1);
}
portNumber = atoi(argv[1]);
bzero((char *) &ServerStructure, sizeof(ServerStructure));
ServerStructure.sin_family = AF_INET;
ServerStructure.sin_addr.s_addr = INADDR_ANY;
ServerStructure.sin_port = htons(portNumber);
if (bind(ServerSocket, (struct sockaddr *) &ServerStructure, sizeof(ServerStructure)) < 0) {
perror("bind");
exit(1);
}
if (listen(ServerSocket, 5) < 0) {
perror("listen");
exit(1);
}
int i = 0;
pthread_t array[6];
for (; ;) {
pthread_create(&array[i], 0, socket_connection, (void *) &total);
pthread_cond_wait(&c, &mulo);
}
}
void *socket_connection(void *passedvalue) {
struct sockaddr_in ClientStructure;
int ClientLength = sizeof(ClientStructure);
int ClientSocket;
if ((ClientSocket = accept(ServerSocket, (struct sockaddr *) &ClientStructure, &ClientLength)) < 0) {
perror("accept");
exit(1);
}
printf("Client Connected Successfully \\n");
char buffer[1024] = "/0";
ssize_t bytesRead;
int passed = 1;
printf("enter the while \\n");
while (passed != 0) {
int *passed_in_value = ((int *) passedvalue);
printf("fd entered \\n");
bytesRead = recv(ClientSocket, (void *) buffer, sizeof(buffer), 0);
printf("Buffer read\\n");
pthread_mutex_lock(&mulo);
passed = atoi(buffer);
*passed_in_value += passed;
pthread_mutex_unlock(&mulo);
if (bytesRead < 1) {
printf("bytes read fail: %d\\n ---> %s\\n ---> %d\\n ---> %d\\n ---> %i\\n", bytesRead, buffer,
passed,
*passed_in_value, errno);
close(ClientSocket);
exit(0);
}
pthread_cond_signal(&c);
buffer[0] = '\\0';
sprintf(buffer, "%d", *passed_in_value);
printf("passed in value: %i\\n", *passed_in_value);
send(ClientSocket, buffer, (size_t) bytesRead, 0);
printf("\\nend of the while\\n");
}
}
| 0
|
#include <pthread.h>
static lp_pthread_mutex_func next_pthread_mutex_lock = 0;
static lp_pthread_mutex_func next_pthread_mutex_trylock = 0;
static lp_pthread_mutex_func next_pthread_mutex_unlock = 0;
static int
lp_hookfunc(lp_pthread_mutex_func *fptr, const char *fname)
{
char *msg = 0;
assert(fname != 0);
if (*fptr == 0) {
lp_report("dlsym : wrapping %s\\n", fname);
*fptr = dlsym(RTLD_NEXT, fname);
lp_report("next_%s = %p\\n", fname, *fptr);
if ((*fptr == 0) || ((msg = dlerror()) != 0)) {
lp_report("dlsym %s failed : %s\\n", fname, msg);
return -1;
} else {
lp_report("dlsym: wrapping %s done\\n", fname);
return 0;
}
} else {
return 0;
}
}
static void
lp_hookfuncs(void)
{
if (next_pthread_mutex_lock == 0) {
lp_hookfunc(&next_pthread_mutex_lock, "pthread_mutex_lock");
lp_hookfunc(&next_pthread_mutex_trylock, "pthread_mutex_trylock");
lp_hookfunc(&next_pthread_mutex_unlock, "pthread_mutex_unlock");
if ( 0 == next_pthread_mutex_lock
|| 0 == next_pthread_mutex_trylock
|| 0 == next_pthread_mutex_unlock
) {
lp_report("liblockpick failed to hook.\\n");
exit(1);
}
if (0 != lp_data_init()) {
lp_report("liblockpick initialisation failed.\\n");
exit(1);
}
}
}
int
pthread_mutex_lock(pthread_mutex_t *mutex)
{
int rc = EINVAL;
if (mutex != 0) {
lp_lock_precheck(mutex);
rc = DL_CALL_FCT(next_pthread_mutex_lock, (mutex));
lp_lock_postcheck(mutex, rc);
} else {
lp_report("%s(): mutex* is NULL.\\n", __FUNCTION__ );
}
return rc;
}
int
lp_mutex_lock(pthread_mutex_t *mutex)
{
int rc = EINVAL;
rc = next_pthread_mutex_lock(mutex);
return rc;
}
int
pthread_mutex_trylock(pthread_mutex_t *mutex)
{
int rc = EINVAL;
if (mutex != 0) {
lp_lock_precheck(mutex);
rc = DL_CALL_FCT(next_pthread_mutex_trylock, (mutex));
lp_lock_postcheck(mutex, rc);
} else {
lp_report("%s(): mutex* is NULL.\\n", __FUNCTION__ );
}
return rc;
}
int
lp_mutex_trylock(pthread_mutex_t *mutex)
{
int rc = EINVAL;
rc = next_pthread_mutex_trylock(mutex);
return rc;
}
int
pthread_mutex_unlock(pthread_mutex_t *mutex)
{
int rc = EINVAL;
if (mutex != 0) {
lp_unlock_precheck(mutex);
rc = DL_CALL_FCT(next_pthread_mutex_unlock, (mutex));
lp_unlock_postcheck(mutex, rc);
} else {
lp_report("%s(): mutex* is NULL.\\n", __FUNCTION__ );
}
return rc;
}
int
lp_mutex_unlock(pthread_mutex_t *mutex)
{
int rc = EINVAL;
rc = next_pthread_mutex_unlock(mutex);
return rc;
}
void _init() ;
void
_init()
{
lp_report("*** liblockpick _init().\\n");
lp_hookfuncs();
}
void _fini() ;
void
_fini()
{
lp_report("*** liblockpick _fini().\\n");
}
| 1
|
#include <pthread.h>
static pthread_mutex_t nightWiringMutexes[4];
int nightWiringThreadCreate (void *(*fn)(void *))
{
pthread_t myThread;
return pthread_create (&myThread, 0, fn, 0);
}
void nightWiringLock (int key)
{
pthread_mutex_lock (&nightWiringMutexes[key]);
}
void nightWiringUnlock (int key)
{
pthread_mutex_unlock (&nightWiringMutexes[key]);
}
| 0
|
#include <pthread.h>
static void waitForMessage(struct DibDriverDebugInstance *i, int id)
{
i->Platform.expectedId = id;
pthread_cond_wait(&i->Platform.msgResponseCondition, &i->Platform.msgBufferLock);
}
static int regAccess(struct DibDriverDebugInstance *i, uint32_t address, uint32_t value, uint32_t bits, uint8_t rw)
{
char result[25];
struct MsgRegisterAccess access = {
.Head = {
.MsgSize = GetWords(MsgRegisterAccessBits, 32),
.ChipId = 0,
.MsgId = OUT_MSG_REGISTER_ACCESS,
.Sender = 0,
.Type = MSG_TYPE_DEBUG,
},
.ReadWrite = rw,
.Address = address,
.Offset = 0,
.Bits = bits,
.AccessType = bits,
.Msb = 0,
.Lsb = value,
};
pthread_mutex_lock(&i->Platform.msgBufferLock);
MsgRegisterAccessPackInit(&access, &i->Platform.SerialBuf);
DibDriverDebugOutMessageCollector(i, i->Platform.Buffer, &access.Head);
waitForMessage(i, IN_MSG_REGISTER_ACCESS_ACK);
struct MsgRegisterAccessAck ack;
MsgRegisterAccessAckUnpackInit(&i->Platform.SerialBuf, &ack);
if (rw)
snprintf(result, sizeof(result), "OK");
else
snprintf(result, sizeof(result), "%u", ack.Lsb);
pthread_mutex_unlock(&i->Platform.msgBufferLock);
DibDriverDebugPlatformInstanceWriteRaw(i, result, strlen(result));
return 1;
}
static int readI2C(struct DibDriverDebugInstance *i, const char *p1, const char *p2, const char *p3)
{
int address = strtol(p1, 0, 10);
return regAccess(i, 0x10000000 + address, 0, 16, 0);
}
static int writeI2C(struct DibDriverDebugInstance *i, const char *p1, const char *p2, const char *p3)
{
int address = strtol(p1, 0, 10);
int value = strtol(p2, 0, 10);
return regAccess(i, 0x10000000 + address, value, 16, 1);
}
static int read65Nm(struct DibDriverDebugInstance *i, const char *p1, const char *p2, const char *p3)
{
int bus = strtol(p1, 0, 10);
int address = strtol(p2, 0, 10);
return regAccess(i, 0x10000000 + (bus * 500) + address , 0, 32, 0);
}
static int write65Nm(struct DibDriverDebugInstance *i, const char *p1, const char *p2, const char *p3)
{
int bus = strtol(p1, 0, 10);
int address = strtol(p2, 0, 10);
int value = strtol(p3, 0, 10);
return regAccess(i, 0x10000000 + (bus * 500) + address, value, 32, 1);
}
static int getChannel(struct DibDriverDebugInstance *i, const char *p1, const char *p2, const char *p3)
{
DibDriverDebugPlatformInstanceWriteRaw(i, "OK", 2);
return 1;
}
static const struct {
const char *cmd;
int (*handle)(struct DibDriverDebugInstance *, const char *, const char *, const char *);
} command[] = {
{ "READI2C", readI2C },
{ "WRITEI2C", writeI2C },
{ "READ_65NM", read65Nm },
{ "WRITE_65NM", write65Nm },
{ "WRITE0WIR", 0 },
{ "IADC", 0 },
{ "QADC", 0 },
{ "BER", 0 },
{ "SNR", 0 },
{ "MPEG", 0 },
{ "QUAD", 0 },
{ "UQMIS", 0 },
{ "PACKET", 0 },
{ "CARR", 0 },
{ "CHAN", 0 },
{ "SCAN", getChannel },
};
int DibDriverDebugTunerEmulatorAccess(struct DibDriverDebugInstance *instance, char *b, uint32_t size)
{
const char *Par0, *Par1, *Par2, *Par3;
char *pos;
int i;
fprintf(stderr, "received '%s' in %d chars: ", b, size);
Par0=strtok_r(b," ", &pos);
Par1=strtok_r(0," ", &pos);
Par2=strtok_r(0," ", &pos);
Par3=strtok_r(0," ", &pos);
fprintf(stderr, "after parsing: '%s' '%s' '%s' '%s'\\n", Par0, Par1, Par2, Par3);
for (i = 0; i < sizeof(command)/sizeof(command[0]); i++) {
if (strcasecmp(command[i].cmd, Par0) == 0) {
if (command[i].handle)
command[i].handle(instance, Par1, Par2, Par3);
else
fprintf(stderr, "unhandled command received: '%s' (with '%s' and '%s' as parameter)\\n", Par0, Par1, Par2);
break;
}
}
if (i == sizeof(command)/sizeof(command[0])) {
fprintf(stderr, "unknown command received: '%s' (with '%s' and '%s' as parameter)\\n", Par0, Par1, Par2);
DibDriverDebugPlatformInstanceWriteRaw(instance, "NOK", 3);
}
return 1;
}
void DibDriverDebugTunerEmulatorAccessMsgResponse(struct DibDriverDebugInstance *i, const uint32_t *data, uint32_t size)
{
struct MsgHeader head;
pthread_mutex_lock(&i->Platform.msgBufferLock);
memcpy(i->Platform.Buffer, data, size * 4);
MsgHeaderUnpackInit(&i->Platform.SerialBuf, &head);
if (head.MsgId == i->Platform.expectedId)
pthread_cond_signal(&i->Platform.msgResponseCondition);
else
fprintf(stderr, "unexpected message has arrived (ID: %d) -> dropped\\n", head.MsgId);
pthread_mutex_unlock(&i->Platform.msgBufferLock);
}
| 1
|
#include <pthread.h>
int x = 0;
pthread_mutex_t x_mutex;
pthread_cond_t x_cond;
void *A (void *t) {
int boba1, boba2;
printf("A: Comecei\\n");
boba1=10000; boba2=-10000; while (boba2 < boba1) boba2++;
printf("HELLO\\n");
pthread_mutex_lock(&x_mutex);
x++;
if (x==2) {
printf("A: x = %d, vai sinalizar a condicao \\n", x);
pthread_cond_broadcast(&x_cond);
}
pthread_mutex_unlock(&x_mutex);
pthread_exit(0);
}
void *B (void *t) {
printf("B: Comecei\\n");
pthread_mutex_lock(&x_mutex);
if (x < 2) {
printf("B: x= %d, vai se bloquear...\\n", x);
pthread_cond_wait(&x_cond, &x_mutex);
printf("B: sinal recebido e mutex realocado, x = %d\\n", x);
}
printf("BYE BYE\\n");
pthread_mutex_unlock(&x_mutex);
pthread_exit(0);
}
int main(int argc, char *argv[]) {
int i;
pthread_t threads[4];
pthread_mutex_init(&x_mutex, 0);
pthread_cond_init (&x_cond, 0);
pthread_create(&threads[0], 0, B, 0);
pthread_create(&threads[1], 0, B, 0);
pthread_create(&threads[2], 0, A, 0);
pthread_create(&threads[3], 0, A, 0);
for (i = 0; i < 4; i++) {
pthread_join(threads[i], 0);
}
printf ("\\nFIM\\n");
pthread_mutex_destroy(&x_mutex);
pthread_cond_destroy(&x_cond);
pthread_exit (0);
}
| 0
|
#include <pthread.h>
int val;
pthread_mutex_t mutex;
pthread_cond_t cond;
}semaphore;
void sem_init(semaphore *Initial, int value)
{
Initial->val = value;
}
void sem_post(semaphore *sem)
{
pthread_mutex_lock(&(sem->mutex));
s->val++;
pthread_cond_signal(&(sem->cond));
pthread_mutex_lock(&(sem->mutex));
}
void sem_wait(semaphore *s)
{
pthread_mutex_lock(&(s->mutex));
while(s->val <= 0)
{
pthread_cond_wait(&(s->cond),&(s->mutex));
s->val--;
}
pthread_mutex_unlock(&(s->mutex));
}
| 1
|
#include <pthread.h>
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
struct node
{
int n_number;
struct node *n_next;
} *head = 0;
static void cleanup_handler(void *arg)
{
printf("Cleanup handler of second thread.\\n");
free(arg);
(void)pthread_mutex_unlock(&mtx);
}
static void *thread_func(void *arg)
{
struct node *p = 0;
pthread_cleanup_push(cleanup_handler, p);
while (1)
{
pthread_mutex_lock(&mtx);
while (head != 0)
{
pthread_cond_wait(&cond, &mtx);
p = head;
head = head->n_next;
printf("Got %d from front of queue\\n", p->n_number);
free(p);
}
pthread_mutex_unlock(&mtx);
}
pthread_cleanup_pop(0);
return 0;
}
int main(void)
{
pthread_t tid;
int i;
struct node *p;
pthread_create(&tid, 0, thread_func, 0);
for (i = 0; i < 10; i++)
{
p = (struct node *)malloc(sizeof(struct node));
p->n_number = i;
pthread_mutex_lock(&mtx);
p->n_next = head;
head = p;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mtx);
sleep(1);
}
printf("thread 1 wanna end the cancel thread 2.\\n");
pthread_cancel(tid);
pthread_join(tid, 0);
printf("All done -- exiting\\n");
return 0;
}
| 0
|
#include <pthread.h>
int MYTHREADS = 10;
int count = 0;
int n = 10000;
int xArray[10][10000];
int yArray[10][10000];
int a = 5;
int b = 12;
int yMax = 12 * 12;
int recArea = (12 * 12) * (12 - 5);
float threadArray[10];
struct params {
pthread_mutex_t mutex;
pthread_cond_t done;
int id;
};
void* threadWork(void* arg) {
int count = 0;
int id;
pthread_mutex_lock(&(*(params_t*)(arg)).mutex);
id = (*(params_t*)(arg)).id;
pthread_mutex_unlock(&(*(params_t*)(arg)).mutex);
pthread_cond_signal (&(*(params_t*)(arg)).done);
int j;
for ( j = 0; j < n; j++) {
xArray[id][j] = (rand() % (b + 1 - a)) + a;
}
int k;
for (k = 0; k < n; k++) {
yArray[id][k] = rand() % yMax + 1;
}
int p;
for ( p = 0; p < n; p++) {
if ((xArray[id][p]*xArray[id][p]) > yArray[id][p]) {
count++;
}
}
float percentBelow = (float)count / (float)n;
threadArray[id] = (float)percentBelow * (float)recArea;
printf("Thread %d: %f \\n", id, threadArray[id]);
}
int main()
{
int x, y, n, i, k, h;
int xMin, xMax, yMax, nMax;
time_t t;
srand((unsigned) time(&t));
float finalSum;
float finalAvg;
pthread_t threads[MYTHREADS];
params_t params;
pthread_mutex_init (¶ms.mutex , 0);
pthread_cond_init (¶ms.done, 0);
pthread_mutex_lock (¶ms.mutex);
for (i = 0; i < MYTHREADS; i++) {
params.id = i;
pthread_create(&threads[i], 0, threadWork, ¶ms);
pthread_cond_wait (¶ms.done, ¶ms.mutex);
}
for (i = 0; i < MYTHREADS; i++) {
pthread_join(threads[i], 0);
}
pthread_mutex_destroy (¶ms.mutex);
pthread_cond_destroy (¶ms.done);
for (i = 0; i < MYTHREADS ; i++)
{
finalSum = threadArray[i] + finalSum;
}
finalAvg = finalSum / MYTHREADS;
printf("Thread Average: %f", finalAvg);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex_count=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_mutex1= PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_mutex2= PTHREAD_COND_INITIALIZER;
int count = 0;
void * thread1(void *ptr){
printf("This is thread 1\\n");
while(1){
pthread_mutex_lock(&mutex_count);
pthread_cond_wait(&cond_mutex1,&mutex_count);
count++;
printf("%d\\n", count);
if(count >= 10){
pthread_cond_signal(&cond_mutex2);
pthread_mutex_unlock(&mutex_count);
return;
}
pthread_cond_signal(&cond_mutex2);
pthread_mutex_unlock(&mutex_count);
}
return ;
}
void *thread2(void* ptr){
sleep(1);
printf("This is thread 2\\n");
pthread_cond_signal(&cond_mutex1);
while(1){
pthread_mutex_lock(&mutex_count);
pthread_cond_wait(&cond_mutex2,&mutex_count);
count++;
printf("%d\\n", count);
if(count >= 10){
pthread_cond_signal(&cond_mutex1);
pthread_mutex_unlock(&mutex_count);
return ;
}
pthread_cond_signal(&cond_mutex1);
pthread_mutex_unlock(&mutex_count);
}
return ;
}
int main(void){
pthread_t pid1, pid2;
void *ptr;
int ret;
ret = pthread_create(&pid1,0,&thread1,0);
ret = pthread_create(&pid2,0,&thread2,0);
pthread_join(pid1,&ptr);
return 0;
}
| 0
|
#include <pthread.h>
int val_thread_max;
int val_inside_barrier=0;
int condition = 0;
int *args;
pthread_t *tabThread;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void wait_barrier(int arg){
pthread_mutex_lock(&mutex);
val_inside_barrier++;
if (val_inside_barrier == arg) {
condition = 1;
pthread_cond_broadcast(&cond);
}else {
while(!condition){
pthread_cond_wait(&cond, &mutex);
}
}
pthread_mutex_unlock(&mutex);
return;
}
void* thread_func (void *arg) {
printf ("%ld | avant barriere\\n",(long)pthread_self());
wait_barrier(((int *)args)[0]);
printf ("%ld | après barriere\\n",(long)pthread_self());
pthread_exit ( 0);
}
int main(int argc, char *argv[]) {
int i = 0;
int *pi;
int *valeur;
if(argc != 2)
return 1;
val_thread_max = atoi(argv[1]);
tabThread = malloc(val_thread_max *sizeof(pthread_t));
args = malloc(val_thread_max *sizeof(int));
for (i =0;i<val_thread_max;i++) {
args[i] = val_thread_max - i;
printf("args[%d] = %d\\n", i,args[i]);
pi = malloc(sizeof(int));
*pi = i;
pthread_create(&tabThread[i],0,thread_func,pi);
}
for (i = 0; i < val_thread_max; i++) {
if(pthread_join(tabThread[i],0 ) !=0){
printf("pthread_join\\n");
exit(1);
}
}
}
| 1
|
#include <pthread.h>
int asc_code;
int ocorrencias;
}Caracter;
long posicao_global = 0;
long buffleng;
char *buffer;
Caracter *lista_asc;
pthread_mutex_t mutex;
Caracter* preenche_asc(){
int i;
Caracter *vetor = (Caracter*) malloc(96*sizeof(Caracter));
for(i = 0; i < 96; i++){
vetor[i].asc_code = i + 33;
vetor[i].ocorrencias = 0;
}
return vetor;
}
char* gera_buffer(FILE* arq_entrada ){
fseek(arq_entrada, 0 , 2);
buffleng = ftell(arq_entrada);
rewind(arq_entrada);
char *buffer = (char*) malloc((buffleng )*sizeof(char));
return buffer;
}
void* conta_caracteres(void* args){
long posicao_local = 0; int j = 0, tid = *(int*) args;
while(posicao_local < buffleng){
pthread_mutex_lock(&mutex);
posicao_local = posicao_global;
for ( j=0; j<96; j++){
if( buffer[posicao_local] == lista_asc[j].asc_code){
lista_asc[j].ocorrencias ++;
break;
}
}
posicao_local++;
posicao_global = posicao_local;
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void escreve_saida(FILE* arq_saida){
int i;
fprintf(arq_saida, "Simbolo | Codigo Asc\\n");
for( i = 0; i < 96;i++)
if(lista_asc[i]. ocorrencias != 0)
fprintf(arq_saida, " %c, %d\\n", lista_asc[i].asc_code, lista_asc[i].ocorrencias);
fclose(arq_saida);
}
int main(int argc, char* argv[]){
if(argc < 4 ){
printf("passe %s <arquivo de texto a ser lido> <nome do arquivo de saida> <número de threads>\\n",argv[0]);
exit(1);
}
FILE* arq_entrada = fopen(argv[1], "rb");
FILE* arq_saida = fopen( argv[2], "w");
buffer = gera_buffer(arq_entrada);
lista_asc = preenche_asc();
fread(buffer, buffleng, 1, arq_entrada);
printf("CONTANDO CARACTERES DO TEXTO...\\n");
int t, nthreads = atoi(argv[3]); double inicio, fim , tempo;
pthread_t thread[nthreads];
int *tid;
pthread_mutex_init(&mutex, 0);
GET_TIME(inicio);
for( t=0; t<nthreads; t++){
tid = (int*) malloc(sizeof(int));
*tid = t;
pthread_create(&thread[t], 0, conta_caracteres,(void*) tid);
}
for (t = 0; t < nthreads; t++) {
pthread_join(thread[t], 0);
}
GET_TIME(fim);
tempo = fim - inicio;
fclose(arq_entrada);
escreve_saida(arq_saida);
printf("TEMPO EM MINUTOS COM %d threads: %.8f minutos.\\n", nthreads,tempo/60);
pthread_mutex_destroy(&mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
void* handle_client(void*);
struct sockaddr_in server;
unsigned long long n=0;
char message[45] = "GET / HTTP/1.1\\r\\nHost: 127.0.0.1\\r\\n\\r\\n";
pthread_mutex_t mutex1,mutex2;
int pool_num=-1;
int conn_pool[100];
int main(int argc , char *argv[])
{
unsigned long long N;
if (argc != 3) {
fprintf(stderr, "We need two positional parameter (n,c)");
return 1;
}
unsigned long c;
unsigned long j;
double t1,t2;
N=atoi(argv[1]);
c=atoi(argv[2]);
n=N/c;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons( 80 );
pthread_t* handles = (pthread_t*) malloc (c*sizeof(pthread_t));
GET_TIME(t1);
for (j=0; j<c; j++)
pthread_create( &handles[j], 0, handle_client, (void*)j );
for (j=0; j<c; j++) {
pthread_join(handles[j], 0);
}
GET_TIME(t2);
return 0;
}
void* handle_client(void* rank) {
int socket_desc;
char server_reply[2000];
unsigned long long i;
char assigned=0;
if (pool_num>=0) {
pthread_mutex_lock(&mutex1);
if (pool_num>=0){
socket_desc=conn_pool[pool_num];
pool_num--;
assigned=1;}
pthread_mutex_unlock(&mutex1);
}
if (assigned == 0){
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
printf("Could not create socket");
}
if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0)
{
puts("connect error");
return 0;
}
}
for(i=0; i<n; i++){
if( send(socket_desc , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 0;
}
if( recv(socket_desc, server_reply , 2000 , 0) < 0)
{
puts("recv failed");
}
}
pthread_mutex_lock(&mutex2);
pool_num++;
conn_pool[pool_num]=socket_desc;
pthread_mutex_unlock(&mutex2);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t blanks;
sem_t datas;
int ringBuf[30];
void *productRun(void *arg)
{
int i = 0;
while(1)
{
sem_wait(&blanks);
int data = rand()%1234;
ringBuf[i++] = data;
i %= 30;
printf("product is done... data is: %d\\n",data);
sem_post(&datas);
}
}
void *productRun2(void *arg)
{
int i = 0;
while(1)
{
sem_wait(&blanks);
int data = rand()%1234;
ringBuf[i++] = data;
i %= 30;
printf("product2 is done... data is: %d\\n",data);
sem_post(&datas);
}
}
void *consumerRun(void *arg)
{
int i = 0;
while(1)
{
usleep(1456);
pthread_mutex_lock(&mutex);
sem_wait(&datas);
int data = ringBuf[i++];
i %= 30;
printf("consumer is done... data is: %d\\n",data);
sem_post(&blanks);
pthread_mutex_unlock(&mutex);
}
}
void *consumerRun2(void *arg)
{
int i = 0;
while(1)
{
usleep(1234);
pthread_mutex_lock(&mutex);
sem_wait(&datas);
int data = ringBuf[i++];
i %= 30;
printf("consumer2 is done...data2 is: %d\\n",data);
sem_post(&blanks);
pthread_mutex_unlock(&mutex);
}
}
int main()
{
sem_init(&blanks, 0, 30);
sem_init(&datas, 0, 0);
pthread_t tid1,tid2,tid3,tid4;
pthread_create(&tid1, 0, productRun, 0);
pthread_create(&tid4, 0, productRun2, 0);
pthread_create(&tid2, 0, consumerRun, 0);
pthread_create(&tid3, 0, consumerRun2, 0);
pthread_join(tid1,0);
pthread_join(tid2,0);
pthread_join(tid3,0);
pthread_join(tid4,0);
sem_destroy(&blanks);
sem_destroy(&datas);
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t mutex;
static pthread_cond_t cond;
static unsigned int count = 0;
void *thread1(void *dummy);
void *thread2(void *dummy);
int main (void)
{
int i, rtn;
pthread_t th1, th2;
int err;
struct timespec req, res;
req.tv_sec = 10;
req.tv_nsec = 0;
rtn = pthread_mutex_init(&mutex, 0);
if (rtn != 0) {
fprintf(stderr, "pthread_mutex_init() failed for %d.\\n", rtn);
exit(1);
}
rtn = pthread_cond_init(&cond, 0);
if (rtn != 0) {
fprintf(stderr, "pthread_cond_init() failed for %d.\\n", rtn);
exit(1);
}
rtn = pthread_create(&th1, 0, thread1, (void *)0);
if (rtn != 0) {
exit(1);
}
rtn = pthread_create(&th2, 0, thread2, (void *)0);
if (rtn != 0) {
exit(1);
}
pthread_join(th1, 0);
printf("joined thread1 \\n");
pthread_cancel(th2);
printf("cancled thread2 \\n");
err = pthread_join(th2, 0);
printf("joined thread2 \\n");
err = pthread_cond_destroy(&cond);
printf("pthread_cond_destory %d\\n",err);
err = pthread_mutex_destroy(&mutex);
printf("pthread_mutex_destroy %d\\n",err);
exit(0);
}
void *thread1(void *dummy)
{
int ret;
struct timespec req, res;
req.tv_sec = 1;
req.tv_nsec = 0;
while(1) {
putchar('0');
pthread_mutex_lock(&mutex);
count++;
pthread_mutex_unlock(&mutex);
if (count == 8){
pthread_cond_signal(&cond);
break;
}
ret = nanosleep(&req, &res);
while (ret != 0 && errno == EINTR)
ret = nanosleep(&req, &res);
if (ret != 0) {
perror("nanosleep()");
return (void *) 0;
}
fflush(stdout);
}
pthread_exit(0);
putchar('1');
return (void *) 0;
}
void *thread2(void *dummy)
{
struct timespec req;
req.tv_sec = 0;
req.tv_nsec = 10*1000*1000;
pthread_cleanup_push(pthread_mutex_unlock,&mutex);
printf("set mutex_unlock in cleanup");
printf("fall into the waiting...");
while (1) {
pthread_mutex_lock(&mutex);
pthread_cond_timedwait(&cond, &mutex,&req);
pthread_mutex_unlock(&mutex);
}
pthread_cleanup_pop(0);
pthread_exit(0);
return (void *) 0;
}
| 1
|
#include <pthread.h>
static struct Entries rds[3];
pthread_mutex_t *rds_mutex;
void * RdsMain(void *args)
{
int retval, i;
time_t current;
struct timespec sleep, wait;
sleep.tv_sec = 0;
sleep.tv_nsec = 0x1dcd6500;
while (1) {
time(¤t);
retval = pthread_mutex_lock (rds_mutex);
if (retval != 0) {
pthread_mutex_unlock(rds_mutex);
return;
}
for (i = 0; i < 3; i++) {
if (((current - rds[i].timestamp) > 5) && (rds[i].used)) {
printf("File %s timed out\\n", rds[i].filename);
rds[i].used = 0;
}
}
retval = pthread_mutex_unlock(rds_mutex);
if (retval != 0)
return;
nanosleep(&sleep, &wait);
}
}
int RdsInit()
{
int retval, i;
rds_mutex = malloc(sizeof(pthread_mutex_t));
if (rds_mutex == 0)
return ERROR;
retval = pthread_mutex_init (rds_mutex, 0);
if (retval != 0)
return ERROR;
for (i = 0; i < 3; i++) {
rds[i].used = 0;
}
return OK;
}
int RdsDestroy()
{
int retval;
pthread_mutex_destroy(rds_mutex);
if (retval != 0)
return ERROR;
return OK;
}
int RdsAdd(char filename[])
{
int retval, i, oldest;
time_t oldtime;
retval = pthread_mutex_lock (rds_mutex);
if (retval != 0) {
printf("Mutex Lock\\n");
pthread_mutex_unlock(rds_mutex);
return ERROR;
}
for (i = 0; i < 3; i++) {
if (!rds[i].used) {
rds[i].used = 1;
strcpy(rds[i].filename, filename);
time(&oldtime);
rds[i].timestamp = oldtime;
pthread_mutex_unlock(rds_mutex);
return OK;
}
else if (strcmp(filename, rds[i].filename) == 0) {
pthread_mutex_unlock(rds_mutex);
return OK;
}
else {
time(&oldtime);
if (oldtime > rds[i].timestamp) {
oldest = i; oldtime = rds[i].timestamp;
}
}
}
time(&oldtime);
printf("Replacing %s, with %s\\n", rds[oldest].filename, filename);
strcpy(rds[oldest].filename, filename);
rds[oldest].timestamp = oldtime;
retval = pthread_mutex_unlock(rds_mutex);
if (retval != 0) {
printf("Error on Mutex unlock\\n");
return ERROR;
}
return OK;
}
int RdsRemove(char filename[])
{
int retval, i;
retval = pthread_mutex_lock (rds_mutex);
if (retval != 0) {
pthread_mutex_unlock(rds_mutex);
return ERROR;
}
for (i = 0; i < 3; i++) {
if (strcmp(rds[i].filename, filename) == 0) {
rds[i].used = 0;
strcpy(rds[i].filename, "");
pthread_mutex_unlock(rds_mutex);
return OK;
}
}
retval = pthread_mutex_unlock(rds_mutex);
if (retval != 0)
return ERROR;
return NOT_FOUND;
}
int RdsSearch(char *filename)
{
int retval, i;
retval = pthread_mutex_lock (rds_mutex);
if (retval != 0) {
pthread_mutex_unlock(rds_mutex);
return ERROR;
}
for (i = 0; i < 3; i++) {
if (strcmp(rds[i].filename, filename) == 0) {
pthread_mutex_unlock(rds_mutex);
return OK;
}
}
retval = pthread_mutex_unlock(rds_mutex);
if (retval != 0)
return ERROR;
return NOT_FOUND;
}
| 0
|
#include <pthread.h>
void sig_catch(int sig);
void barber(void *);
void customer(void *);
void get_hair_cut(void);
void cut_hair(void);
void line_pop(void);
void line_push(void);
struct chair {
struct chair *next;
};
struct line {
int number_of_customers;
int chairs;
struct chair *current;
struct chair *next;
};
pthread_mutex_t barber_lock;
pthread_mutex_t add_lock;
struct line global_queue;
void sig_catch(int sig){
printf("Catching signal %d\\n", sig);
kill(0,sig);
exit(0);
}
void line_push(void)
{
struct chair new;
struct chair *ref = global_queue.current;
if(global_queue.number_of_customers >= global_queue.chairs)
{
return;
}
new.next = 0;
while(global_queue.next != 0)
{
ref = ref->next;
}
ref->next = &new;
global_queue.number_of_customers++;
}
void line_pop(void)
{
struct chair *ref = global_queue.current;
global_queue.number_of_customers--;
global_queue.current = global_queue.next;
if(global_queue.next != 0)
{
global_queue.next = global_queue.current->next;
}
ref = 0;
}
void barber(void *queue)
{
int i;
int copy_of_customer_number;
for(;;)
{
i = 0;
copy_of_customer_number = global_queue.number_of_customers;
while(global_queue.number_of_customers == 0)
{
printf("The Barber is sleeping\\n");
sleep(5);
}
for(i = 0; i < copy_of_customer_number; i++)
{
cut_hair();
}
}
}
void customer(void *queue)
{
if(global_queue.number_of_customers >= global_queue.chairs)
{
printf("Line is full. Leaving\\n");
return;
}
pthread_mutex_lock(&add_lock);
line_push();
pthread_mutex_unlock(&add_lock);
printf("In chair waiting\\n");
pthread_mutex_lock(&barber_lock);
get_hair_cut();
line_pop();
pthread_mutex_unlock(&barber_lock);
}
void cut_hair(void)
{
printf("Cutting hair\\n");
sleep(10);
printf("Done cutting hair\\n");
}
void get_hair_cut(void)
{
printf("Getting hair cut\\n");
sleep(10);
printf("Done getting hair cut\\n");
}
int main(int argc, char **argv) {
pthread_t barber_thread;
pthread_t c1, c2, c3, c4;
void *barber_func = barber;
void *customer_func = customer;
struct chair one;
struct sigaction sig;
sig.sa_flags = 0;
sig.sa_handler = sig_catch;
sigaction(SIGINT, &sig, 0);
one.next = 0;
global_queue.current = &one;
pthread_mutex_init(&barber_lock, 0);
pthread_mutex_init(&add_lock, 0);
global_queue.chairs = 3;
global_queue.number_of_customers = 0;
pthread_create(&barber_thread, 0, barber_func, 0);
sleep(5);
pthread_create(&c1, 0, customer_func, 0);
pthread_create(&c2, 0, customer_func, 0);
pthread_create(&c3, 0, customer_func, 0);
pthread_create(&c4, 0, customer_func, 0);
for(;;)
{
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t fMutex;
int fCounter;
int fLoops;
char fType;
} Shared;
void *
MutexPerformanceProc(void *arg)
{
Shared * shared = (Shared *)arg;
int i;
if (shared->fType == 'm') {
for (i = 0; i < shared->fLoops; i++) {
pthread_mutex_lock(&shared->fMutex);
shared->fCounter++;
pthread_mutex_unlock(&shared->fMutex);
}
} else {
pthread_mutex_lock(&shared->fMutex);
pthread_mutex_unlock(&shared->fMutex);
for (i = 0; i < shared->fLoops; i++) {
shared->fCounter++;
if (shared->fType == 'y')
sched_yield();
}
}
return(0);
}
void MutexPerformance(char ch1, char ch2, const char * cmd)
{
int nloops;
int nthreads;
pthread_t tid[20];
Shared shared;
int i;
int fairness;
unsigned long start_time;
unsigned long stop_time;
if (sscanf(cmd, "%d %d", &shared.fLoops, &nthreads) != 2)
Usage(ch1, ch2);
else {
if (nthreads < 1) {
printf("Too few threads specified, using 1\\n");
nthreads = 1;
} else if (nthreads > 20) {
printf("Too many threads specified, using 20\\n");
nthreads = 20;
}
shared.fCounter = 0;
shared.fType = ch1;
pthread_mutex_init(&shared.fMutex, 0);
pthread_mutex_lock(&shared.fMutex);
for (i = 0; i < nthreads; i++)
pthread_create(&tid[i], 0, MutexPerformanceProc, &shared);
start_time = LMGetTicks();
pthread_mutex_unlock(&shared.fMutex);
pthread_join(tid[0], 0);
fairness = shared.fCounter;
for (i = 1; i < nthreads; i++)
pthread_join(tid[i], 0);
stop_time = LMGetTicks();
printf("Time: %f seconds, Fairness: %.2f%\\n",
(stop_time - start_time) / 60.0,
(fairness * 100.0) / ((shared.fLoops-1) * nthreads + 1));
if (shared.fCounter != shared.fLoops * nthreads)
printf("error: counter = %ld\\n", shared.fCounter);
pthread_mutex_destroy(&shared.fMutex);
}
}
void Sleep(char ch1, char ch2, const char * cmd)
{
int seconds;
if (sscanf(cmd, "%d", &seconds) != 1)
Usage(ch1, ch2);
else
printf("Remaining: %ds\\n", sleep(seconds));
}
void Times(char ch1, char ch2, const char * cmd)
{
time_t lmk, gmk;
time_t now = time(0);
struct tm * t = localtime(&now);
printf("Localtime %d/%d/%d %d:%02d:%02d %s\\n",
t->tm_year+1900, t->tm_mon+1, t->tm_mday,
t->tm_hour, t->tm_min, t->tm_sec, t->tm_isdst ? "DST" : "");
lmk = mktime(t);
t = gmtime(&now);
printf("GMtime %d/%d/%d %d:%02d:%02d %s\\n",
t->tm_year+1900, t->tm_mon+1, t->tm_mday,
t->tm_hour, t->tm_min, t->tm_sec, t->tm_isdst ? "DST" : "");
gmk = mktime(t);
printf("Now %u Local %u GM %u\\n", now, lmk, gmk);
}
main(int argc, char ** argv)
{
printf("GUSIFileTest MN 25OCt00\\n\\n");
COMMAND('s', 'l', Sleep, "seconds", "sleep");
COMMAND('t', 'm', Times, "", "Test time related functions");
RunTest(argc, argv);
}
| 0
|
#include <pthread.h>
int randomGaussian_r(int mean, int stddev, unsigned int* state);
void* philoFunc(void* p);
void eat(int sec, int ph);
void think(int sec, int ph);
int leftChop(int ph);
int rightChop(int ph);
int chopArray[5], eatArr[5], thinkArr[5];
pthread_mutex_t mutex;
int ph[5];
int main()
{
srand(time(0));
for(int i=0; i<5; i++) {ph[i]=i; chopArray[i] = eatArr[5] = thinkArr[i] = 0;}
pthread_mutex_init(&mutex, 0);
pthread_t thread0, thread1, thread2, thread3, thread4;
if(pthread_create(&thread0, 0, philoFunc, &ph[0])) {fprintf(stderr, "Error creating thread 0\\n"); return 1;}
if(pthread_create(&thread1, 0, philoFunc, &ph[1])) {fprintf(stderr, "Error creating thread 1\\n"); return 1;}
if(pthread_create(&thread2, 0, philoFunc, &ph[2])) {fprintf(stderr, "Error creating thread 2\\n"); return 1;}
if(pthread_create(&thread3, 0, philoFunc, &ph[3])) {fprintf(stderr, "Error creating thread 3\\n"); return 1;}
if(pthread_create(&thread4, 0, philoFunc, &ph[4])) {fprintf(stderr, "Error creating thread 4\\n"); return 1;}
if(pthread_join(thread0, 0)) {fprintf(stderr, "Error joining thread 0\\n"); return 2;}
if(pthread_join(thread1, 0)) {fprintf(stderr, "Error joining thread 1\\n"); return 2;}
if(pthread_join(thread2, 0)) {fprintf(stderr, "Error joining thread 2\\n"); return 2;}
if(pthread_join(thread3, 0)) {fprintf(stderr, "Error joining thread 3\\n"); return 2;}
if(pthread_join(thread4, 0)) {fprintf(stderr, "Error joining thread 4\\n"); return 2;}
for (int myPh=0; myPh<5; myPh++)
printf("Philosopher %d ate for %2d seconds, thought for %2d seconds, and left the table.\\n", myPh, eatArr[myPh], thinkArr[myPh]);
return 0;
}
void* philoFunc(void* p)
{
int ph= *((int*)p);
unsigned int myRand = rand();
int eatSum=0, thinkSum=0, eatTime, thinkTime;
while (eatSum < 100)
{
eatTime = randomGaussian_r(9, 3, &myRand);
if (eatTime<0) eatTime=0;
eat (eatTime, ph);
eatSum = eatSum + eatTime;
myRand = rand();
thinkTime = randomGaussian_r(11, 7, &myRand);
if (thinkTime<0) thinkTime=0;
think (thinkTime, ph);
thinkSum = thinkSum + thinkTime;
}
eatArr[ph]=eatSum; thinkArr[ph]=thinkSum;
return 0;
}
void eat(int sec, int ph)
{
while (1)
{
pthread_mutex_lock(&mutex );
if (chopArray[leftChop(ph)]==1 || chopArray[rightChop(ph)]==1)
{
pthread_mutex_unlock(&mutex);
sleep(1);
}
else
break;
}
chopArray[leftChop(ph)] = chopArray[rightChop(ph)] = 1;
pthread_mutex_unlock(&mutex);
printf("Philosopher %d eats for %d seconds.\\n", ph, sec);
sleep(sec);
chopArray[leftChop(ph)] = chopArray[rightChop(ph)] = 0;
return;
}
void think(int sec, int ph)
{
printf("Philosopher %d thinks for %d seconds.\\n", ph, sec);
sleep(sec);
}
int leftChop(int ph){ return ((ph)%5);}
int rightChop(int ph){ return ((ph+1)%5);}
int randomGaussian_r(int mean, int stddev, unsigned int* state) {
double mu = 0.5 + (double) mean;
double sigma = fabs((double) stddev);
double f1 = sqrt(-2.0 * log((double) rand_r(state) / (double) 32767));
double f2 = 2.0 * 3.14159265359 * (double) rand_r(state) / (double) 32767;
if (rand_r(state) & (1 << 5))
return (int) floor(mu + sigma * cos(f2) * f1);
else
return (int) floor(mu + sigma * sin(f2) * f1);
}
| 1
|
#include <pthread.h>
pthread_t thread[3];
pthread_mutex_t mut;
int number=0, i;
char buf[1024]={0},str[7]={0};
sem_t sem;
void *thread1()
{
printf ("thread1 : I'm thread 1\\n");
while(1)
{
pthread_mutex_lock(&mut);
if(number<10){
number++;
}
else
break;
pthread_mutex_unlock(&mut);
sem_wait(&sem);
sprintf(str,"%d.dat",number);
FILE *fp=fopen(str,"r");
fgets(buf,1024,fp);
printf("thread1 : %d.dat\\n%s\\n",number,buf);
if(!fp)
fclose(fp);
sem_post(&sem);
}
pthread_mutex_unlock(&mut);
printf("thread1 :主函数在等待吗?\\n");
pthread_exit(0);
}
void *thread2()
{
printf ("thread2 : I'm thread 2\\n");
while(1)
{
pthread_mutex_lock(&mut);
if(number<10){
number++;
}
else
break;
pthread_mutex_unlock(&mut);
sem_wait(&sem);
sprintf(str,"%d.dat",number);
FILE *fp=fopen(str,"r");
fgets(buf,1024,fp);
printf("thread2 : %d.dat\\n%s\\n",number,buf);
if(!fp)
fclose(fp);
sem_post(&sem);
}
pthread_mutex_unlock(&mut);
printf("thread2 :主函数在等待吗?\\n");
pthread_exit(0);
}
void *thread3()
{
printf ("thread3 : I'm thread 3\\n");
while(1)
{
pthread_mutex_lock(&mut);
if(number<10){
number++;
}
else
break;
pthread_mutex_unlock(&mut);
sem_wait(&sem);
sprintf(str,"%d.dat",number);
FILE *fp=fopen(str,"r");
fgets(buf,1024,fp);
printf("thread3 : %d.dat\\n%s\\n",number,buf);
if(!fp)
fclose(fp);
sem_post(&sem);
}
pthread_mutex_unlock(&mut);
printf("thread3 :主函数在等待吗?\\n");
pthread_exit(0);
}
void thread_create(void)
{
int temp;
memset(&thread, 0, sizeof(thread));
if((temp = pthread_create(&thread[0], 0, thread1, 0)) != 0)
printf("线程1创建失败!\\n");
else
printf("线程1被创建\\n");
if((temp = pthread_create(&thread[1], 0, thread2, 0)) != 0)
printf("线程2创建失败");
else
printf("线程2被创建\\n");
if((temp = pthread_create(&thread[2], 0, thread3, 0)) != 0)
printf("线程3创建失败!\\n");
else
printf("线程3被创建\\n");
}
void thread_wait(void)
{
if(thread[0] !=0)
{
pthread_join(thread[0],0);
printf("线程1已经结束\\n");
}
if(thread[1] !=0)
{
pthread_join(thread[1],0);
printf("线程2已经结束\\n");
}
if(thread[2] !=0)
{
pthread_join(thread[2],0);
printf("线程3已经结束\\n");
}
}
int main()
{
pthread_mutex_init(&mut,0);
sem_init(&sem,0,2);
printf("主函数,正在创建线程\\n");
thread_create();
printf("主函数,正在等待线程完成任务\\n");
thread_wait();
return 0;
}
| 0
|
#include <pthread.h>
static const unsigned int kBaseIDNumber = 101;
static const unsigned int kNumAgents = 10;
static const unsigned int kNumTickets = 100;
static pthread_mutex_t ticketsLock;
static unsigned int remainingTickets = kNumTickets;
static void ticketAgent(size_t id) {
while (1) {
pthread_mutex_lock(&ticketsLock);
if (remainingTickets == 0) break;
unsigned int curRemainingTickets = remainingTickets;
usleep(5000);
remainingTickets = curRemainingTickets - 1;
pthread_mutex_unlock(&ticketsLock);
usleep(20000);
}
pthread_mutex_unlock(&ticketsLock);
}
static void *ticketAgentFunction(void *data)
{
ticketAgent((size_t) data);
return 0;
}
int main(int argc, const char *argv[]) {
pthread_mutex_init(&ticketsLock, 0);
pthread_t agents[kNumAgents];
for (size_t i = 0; i < kNumAgents; i++)
pthread_create(&agents[i], 0, ticketAgentFunction, (void *) (kBaseIDNumber + i));
for (size_t i = 0; i < kNumAgents; i++)
pthread_join(agents[i], 0);
printf("End of business day!\\n");
return 0;
}
| 1
|
#include <pthread.h>
void *find_min(void *list_ptr);
pthread_mutex_t minimum_value_lock;
int minimum_value, partial_list_size,list_elements_size;
int j=0;
main() {
int i,k;
minimum_value = 0;
pthread_mutex_init(&minimum_value_lock, 0);
int pthread_count;
printf("Enter the values for list size and thread count:");
scanf("%d %d",&list_elements_size,&pthread_count);
pthread_t thread[pthread_count];
static int list_elements[100000000];
for(i=0;i<list_elements_size;i++)
{
list_elements[i]=rand_r()%100000000 + (-99999999);
}
partial_list_size=list_elements_size/pthread_count;
for(k=0;k<pthread_count;k++)
{
pthread_create(&thread[k],0,(void *)&find_min,(void *)&list_elements[j]);
j=j+partial_list_size;
}
for(i=0;i< pthread_count;i++)
{
pthread_join(thread[i],0);
}
printf("The minimum value in the list : %d",minimum_value);
}
void *find_min(void *list_ptr) {
j=1;
int *partial_list_pointer, my_min,i;
my_min = 0;
partial_list_pointer = (int *) list_ptr;
for (i = 0; i < partial_list_size; i++)
if (partial_list_pointer[i] < my_min)
my_min = partial_list_pointer[i];
pthread_mutex_lock(&minimum_value_lock);
if (my_min < minimum_value)
minimum_value = my_min;
pthread_mutex_unlock(&minimum_value_lock);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
static void link(struct Area *a, struct Berth *f, struct Berth *t) {
short oldLen = f->nextcount;
char **oldAry = f->next;
f->nextcount++;
f->next = (char **) malloc(sizeof (char *)*f->nextcount);
memcpy(f->next, oldAry, sizeof (char *)*oldLen);
f->next[oldLen] = t->name;
}
void td_berthStep(struct TDMap *map, char *area, char *from, char *to, char *desc) {
if (area && from && to) {
struct Area *a = td_getArea(map, area);
struct Berth *f = td_getBerth(a, from);
struct Berth *t = td_getBerth(a, to);
if (a && f && t && 0 == pthread_mutex_lock(&a->mutex)) {
f->val[0] = 0;
if (desc)
strncpy(t->val, desc, TD_DESC_LEN);
else
t->val[0] = 0;
if (!f->nextcount)
link(a, f, t);
else {
int i = 0;
for (; i < f->nextcount; i++)
if (strcmp(f->next[i], t->name) == 0)
break;
if (i == f->nextcount)
link(a, f, t);
}
pthread_mutex_unlock(&a->mutex);
}
}
}
| 1
|
#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,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++) {
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++) {
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++) {
if (0 != (err = pthread_join(tPool[i], 0))) {
fprintf(stderr, "pthread join error: %d\\n", err);
exit(-1);
}
}
for (
i = 0; i < iRThreads; i++) {
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);
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;;
int global = 0;
void* thread1(void* arg)
{
pthread_cleanup_push(pthread_mutex_unlock, &mutex);
while(1)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
printf("thread1's gloabl is %d\\n",++global);
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_cleanup_pop(0);
return 0;
}
void* thread2(void* arg)
{
pthread_cleanup_push(pthread_mutex_unlock, &mutex);
while(1)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
printf("thread2's gloabl is %d\\n",++global);
pthread_mutex_unlock(&mutex);
sleep(2);
}
pthread_cleanup_pop(0);
return 0;
}
void* thread3(void* arg)
{
pthread_cleanup_push(pthread_mutex_unlock, &mutex);
while(1)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
printf("thread3's gloabl is %d\\n",++global);
pthread_mutex_unlock(&mutex);
sleep(3);
}
pthread_cleanup_pop(0);
return 0;
}
int main(void)
{
pthread_t tid1, tid2, tid3;
int status;
printf("the main thread is running \\n");
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
pthread_create(&tid1, 0, thread1, 0);
pthread_create(&tid2, 0, thread2, 0);
pthread_create(&tid3, 0, thread3, 0);
do
{
pthread_cond_signal(&cond);
}while(1);
pthread_join(tid1, (void*)status);
pthread_join(tid2, (void*)status);
pthread_join(tid3, (void*)status);
printf("the thread is over\\n");
pthread_exit(0);
}
| 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 = pthread_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\\n");
exit(1);
}
printf("Thread joined\\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);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
char char_buffer[67108864];
int ascii_num[128];
pthread_mutex_t lock;
int thread_id;
int partition_bounds;
} thread_info;
void *ascii_counting (void* thread){
char current_char;
int t,thread_begin_location;
thread_info *td= (thread_info*) thread;
t = td->thread_id;
thread_begin_location= t * td->partition_bounds;
for (int i = 0; i < td->partition_bounds; ++i)
{
current_char = char_buffer[thread_begin_location+i];
pthread_mutex_lock(&lock);
ascii_num[(int)current_char]++;
pthread_mutex_unlock(&lock);
}
pthread_exit(0);
}
int main(int argc, char const *argv[]){
int fd, length_per_thread;
pthread_t threads[8];
thread_info t_info[8];
pthread_attr_t thread_attr;
ssize_t bytes_read =0;
if(argc !=2){
printf("Incorrect cmd format, please check!");
exit (1);
}
fd=open(argv[1],O_RDONLY);
if (fd<0)
{
perror("Open file fail: ");
exit(1);
}
pthread_attr_init(&thread_attr);
if(pthread_mutex_init(&lock,0)!=0)
{
printf("\\n mutex init failed \\n");
exit(1);
}
for (;;)
{
bytes_read=read(fd,char_buffer,67108864);
if(bytes_read == 0){
close(fd);
break;
}
if (bytes_read == -1)
{
perror("Reading fail");
exit(1);
}
length_per_thread=(double)bytes_read/(double)8;
for (int i = 0; i < 8; ++i)
{
t_info[i].thread_id = i;
t_info[i].partition_bounds=length_per_thread;
pthread_create(&threads[i], &thread_attr, ascii_counting, &t_info[i]);
}
for (int i = 0; i < 8; ++i)
{
pthread_join(threads[i],0);
}
}
for (int i = 0; i < 128; ++i)
{
printf("%i occurrences of ", ascii_num[i] );
if (i < 33 || i == 127){
}else{
printf("%c\\n", i);
}
}
return 0;
}
| 1
|
#include <pthread.h>
struct thread_args {
int ident ;
pthread_mutex_t *resA ;
pthread_mutex_t *resB ;
};
void run_thread_one(thread_args_t *);
void run_thread_two(thread_args_t *);
int main(int argc, char** argv)
{
pthread_t thread_one;
pthread_t thread_two;
thread_args_t args_one,args_two;
void *statusp ;
int conditionAMet;
int conditionBMet;
pthread_cond_t condA;
pthread_condattr_t condAttrA;
pthread_cond_t condB;
pthread_condattr_t condAttrB;
conditionAMet = pthread_cond_init(&condA, 0);
conditionAMet = pthread_cond_init(&condA, &condAttrA);
conditionBMet = pthread_cond_init(&condB, 0);
conditionBMet = pthread_cond_init(&condB, &condAttrB);
pthread_mutex_t resA_lock = PTHREAD_MUTEX_INITIALIZER ;
pthread_mutex_t resB_lock = PTHREAD_MUTEX_INITIALIZER ;
printf("deadlock program starting. \\n");
srand( (unsigned)time( 0 ) );
args_one.ident = 1 ;
args_one.resA = &resA_lock;
args_one.resB = &resB_lock;
args_one.condAMet = &conditionAMet;
args_one.condBMet = &conditionBMet;
args_one.condA = &condA;
args_one.condB = &condB;
pthread_create(&thread_one,
0,
(void *) run_thread_one,
(void *) &args_one) ;
args_two.ident = 2 ;
args_two.resA = &resA_lock;
args_two.resB = &resB_lock;
args_two.condAMet = &conditionAMet;
args_two.condBMet = &conditionBMet;
args_two.condA = &condA;
args_two.condB = &condB;
pthread_create(&thread_two,
0,
(void *) run_thread_two,
(void *) &args_two) ;
sleep(60);
return(0);
}
void run_thread_one(thread_args_t *args){
printf("Hello world, I'm thread %d\\n",args->ident);
printf("thread %d about to get resource A \\n",args->ident);
pthread_mutex_lock(args->resA);
{
printf("thread %d: I got resource A \\n",args->ident);
sleep(1);
printf("thread %d about to get resource B \\n",args->ident);
pthread_mutex_lock(args->resB);
printf("thread %d: I've both resouces :) \\n",args->ident);
}
while (!args->condMet)
pthread_cond_wait(args->condB, args->resB);
pthread_mutex_unlock(args->resB);
while (!argsg->condAMet)
pthread_cond_wait(args->condA, args->resA);
pthread_mutex_unlock(args->resA);
}
void run_thread_two(thread_args_t *args){
printf("Hello world, I'm thread %d\\n",args->ident);
printf("thread %d about to get resource B \\n",args->ident);
pthread_mutex_lock(args->resB);
{
printf("thread %d: I got resource B \\n",args->ident);
sleep(1);
printf("thread %d about to get resource A \\n",args->ident);
pthread_mutex_lock(args->resA);
printf("thread %d: I've both resouces :) \\n",args->ident);
}
pthread_mutex_unlock(args->resB);
pthread_mutex_unlock(args->resA);
}
| 0
|
#include <pthread.h>
static int g_num=0;
static pthread_mutex_t g_mutex;
void *thread_handle(void *arg)
{
int i=0;
for(i=0;i<10;i++)
{
pthread_mutex_lock(&g_mutex);
printf("线程[1] brfore %d\\n",g_num);
g_num++;
sleep(1);
printf("线程[1] after %d\\n",g_num);
pthread_mutex_unlock(&g_mutex);
sleep(1);
}
printf("线程[1] exit\\n");
return 0;
}
void *thread_handle_new(void *arg)
{
int i=0;
for(i=0;i<10;i++)
{
pthread_mutex_lock(&g_mutex);
printf("线程[2] brfore %d\\n",g_num);
g_num--;
sleep(2);
printf("线程[2] after %d\\n",g_num);
pthread_mutex_unlock(&g_mutex);
sleep(2);
}
printf("线程[2] exit\\n");
return 0;
}
int main()
{
pthread_mutex_init(&g_mutex,0);
pthread_t pid =0;
int ret=pthread_create(&pid,0,thread_handle,0);
if(ret!=0)
{
perror(strerror(errno));
return 0;
}
int ret_new= pthread_create(&pid,0,thread_handle_new,0);
if(ret_new!=0)
{
perror(strerror(errno));
return 0;
}
pthread_join(pid,0);
pthread_mutex_destroy(&g_mutex);
printf("退出\\n");
return 0;
}
| 1
|
#include <pthread.h>
double total_sum = 0;
pthread_mutex_t lock;
struct meta_data {
int partition_size;
int total;
double *start;
int thread_id;
};
void run_test(int n, int threads);
void *partition_sum(struct meta_data *meta);
int main(void)
{
int threads[3] = {2, 4, 8};
int n[2] = {10, 11};
int num_tests = 2;
int num_threads = 3;
int i, j;
for(i=0; i<num_threads; i++)
{
for(j=0; j<num_tests; j++)
{
run_test(n[j], threads[i]);
}
}
return 0;
}
void run_test(int n, int threads)
{
struct timespec start, finish;
double elapsed;
clock_gettime(CLOCK_MONOTONIC, &start);
pthread_t thread_array[threads];
struct meta_data meta[threads];
int partition_size = n / threads;
int extra = n % threads;
int i;
double *array = malloc(n * sizeof(double));
pthread_mutex_init(&lock, 0);
for (i = 0; i < threads ; i++)
{
meta[i].partition_size = partition_size;
meta[i].start = malloc(sizeof(double*));
meta[i].start = &array[i*partition_size];
meta[i].thread_id = i;
if (i+1 == threads)
{
meta[i].total = partition_size + extra;
}
else
{
meta[i].total = partition_size;
}
pthread_create(&thread_array[i], 0, (void*) partition_sum, &meta[i]);
}
for (i = 0; i < threads ; i++)
{
pthread_join(thread_array[i], 0);
}
printf("The summation of the %d array elements is %f \\n", (int) n, total_sum);
clock_gettime(CLOCK_MONOTONIC, &finish);
elapsed = (finish.tv_sec - start.tv_sec);
elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0;
printf("The total elapsed time was %f seconds \\n",elapsed);
pthread_mutex_lock(&lock);
total_sum = 0;
pthread_mutex_unlock(&lock);
pthread_mutex_destroy(&lock);
free(array);
}
void *partition_sum(struct meta_data *meta)
{
double local_sum = 0;
int start = meta->partition_size * meta->thread_id;
int end = start + meta->total - 1;
printf("Thread %d processes array elements %d-%d \\n", meta->thread_id, start, end);
int i;
for (i = 0; i < meta->total; i++)
{
meta->start[i] = i;
local_sum = local_sum + meta->start[i];
}
pthread_mutex_lock(&lock);
total_sum = total_sum + local_sum;
pthread_mutex_unlock(&lock);
return 0;
}
| 0
|
#include <pthread.h>
int joker_open(struct joker_t *joker)
{
struct libusb_context *ctx = 0;
struct libusb_device **usb_list = 0;
struct libusb_device_handle *devh = 0;
struct libusb_device_descriptor desc;
int usb_devs, i, r, ret, transferred;
unsigned char buf[JCMD_BUF_LEN];
unsigned char in_buf[JCMD_BUF_LEN];
int isoc_len = USB_PACKET_SIZE;
if (!joker)
return EINVAL;
ret = libusb_init(0);
if (ret < 0) {
fprintf(stderr, "libusb_init failed\\n");
return ENODEV;
}
if (joker->libusb_verbose == 0)
joker->libusb_verbose = 1;
libusb_set_debug(0, joker->libusb_verbose);
usb_devs = libusb_get_device_list(ctx, &usb_list);
for(i = 0 ; i < usb_devs ; ++i) {
r = libusb_get_device_descriptor(usb_list[i], &desc);
if(r < 0) {
fprintf(stderr, "desc.idVendor=0x%x desc.idProduct=0x%x\\n",
desc.idVendor, desc.idProduct);
}
if (desc.idVendor == NETUP_VID && desc.idProduct == JOKER_TV_PID)
{
r = libusb_open(usb_list[i], &devh);
if (r)
libusb_error_name(r);
joker->fw_ver = desc.bcdDevice;
break;
}
}
if (devh <= 0) {
fprintf(stderr, "usb device not found\\n");
return ENODEV;
}
printf("usb device found. firmware version 0x%x\\n", joker->fw_ver);
ret = libusb_set_configuration(devh, 1);
if (ret < 0) {
fprintf(stderr, "Can't set config: %s\\n", libusb_error_name(ret));
libusb_close(devh);
return EIO;
}
ret = libusb_claim_interface(devh, 0);
if (ret < 0) {
fprintf(stderr, "Can't claim interface: %s\\n", libusb_error_name(ret));
libusb_close(devh);
return EIO;
}
joker->libusb_opaque = (void *)devh;
jdebug("open:dev=%p \\n", devh);
joker->io_mux_opaq = malloc(sizeof(pthread_mutex_t));
if (!joker->io_mux_opaq)
return ENOMEM;
pthread_mutex_init((pthread_mutex_t*)joker->io_mux_opaq, 0);
libusb_bulk_transfer(devh, USB_EP1_IN, in_buf, JCMD_BUF_LEN, &transferred, 1);
libusb_bulk_transfer(devh, USB_EP1_IN, in_buf, JCMD_BUF_LEN, &transferred, 1);
libusb_bulk_transfer(devh, USB_EP1_IN, in_buf, JCMD_BUF_LEN, &transferred, 1);
buf[0] = J_CMD_ISOC_LEN_WRITE_HI;
buf[1] = (isoc_len >> 8) & 0x7;
if ((ret = joker_cmd(joker, buf, 2, 0 , 0 ))) {
printf("Can't set isoc transfers size (high)\\n");
return ret;
}
buf[0] = J_CMD_ISOC_LEN_WRITE_LO;
buf[1] = isoc_len & 0xFF;
if ((ret = joker_cmd(joker, buf, 2, 0 , 0 ))) {
printf("Can't set isoc transfers size (low)\\n");
return ret;
}
if ((ret = joker_i2c_init(joker))) {
printf("Can't init i2c bus \\n");
return ret;
}
joker_reset(joker, 0xFF );
if (joker_ci_en50221_init(joker)) {
printf("Can't init EN50221 \\n");
return -EIO;
}
return 0;
}
int joker_close(struct joker_t * joker) {
struct libusb_device_handle *dev = 0;
int ret = 0;
if (!joker)
return EINVAL;
joker_ci_close(joker);
printf("%s: CI stack stopped \\n", __func__);
stop_service_thread(joker);
printf("%s: service thread stopped \\n", __func__);
if((ret = joker_i2c_close(joker)))
return ret;
dev = (struct libusb_device_handle *)joker->libusb_opaque;
libusb_release_interface(dev, 0);
if(dev)
libusb_close(dev);
joker->libusb_opaque = 0;
printf("%s: done\\n", __func__);
}
int joker_io(struct joker_t * joker, struct jcmd_t * jcmd) {
struct libusb_device_handle *dev = 0;
unsigned char buf[JCMD_BUF_LEN];
int ret = 0, transferred = 0;
pthread_mutex_t *mux = 0;
if (!joker || !joker->io_mux_opaq)
return -EINVAL;
mux = (pthread_mutex_t*)joker->io_mux_opaq;
dev = (struct libusb_device_handle *)joker->libusb_opaque;
pthread_mutex_lock(mux);
ret = libusb_bulk_transfer(dev, USB_EP2_OUT, jcmd->buf, jcmd->len, &transferred, 2000);
if (ret < 0 || transferred != jcmd->len) {
pthread_mutex_unlock(mux);
jdebug("%s: USB bulk transaction failed. cmd=0x%x len=%d ret=%d transferred=%d \\n",
__func__, jcmd->buf[0], jcmd->len, ret, transferred);
return -EIO;
}
if (jcmd->in_len > 0) {
ret = libusb_bulk_transfer(dev, USB_EP1_IN, jcmd->in_buf, jcmd->in_len, &transferred, 2000);
if (ret < 0 || transferred != jcmd->in_len) {
printf("%s: failed to read reply. ret=%d transferred=%d expected %d\\n",
__func__, ret, transferred, jcmd->in_len );
pthread_mutex_unlock(mux);
return -EIO;
}
}
pthread_mutex_unlock(mux);
return 0;
}
int joker_send_ts_loop(struct joker_t * joker, unsigned char *buf, int len) {
struct libusb_device_handle *dev = 0;
int ret = 0, transferred = 0;
if (!joker)
return -EINVAL;
dev = (struct libusb_device_handle *)joker->libusb_opaque;
ret = libusb_bulk_transfer(dev, USB_EP4_OUT, buf, len, &transferred, 0);
if (ret < 0 || transferred != len) {
jdebug("%s: USB bulk transaction failed. ret=%d transferred=%d \\n", __func__, ret, transferred);
return -EIO;
}
return 0;
}
int joker_cmd(struct joker_t * joker, unsigned char *data, int len, unsigned char * in_buf, int in_len) {
int ret = 0;
struct jcmd_t jcmd;
int i = 0;
if (!joker)
return -EINVAL;
jcmd.buf = data;
jcmd.len = len;
jcmd.in_buf = in_buf;
jcmd.in_len = in_len;
if ((ret = joker_io(joker, &jcmd)))
return ret;
return 0;
}
| 1
|
#include <pthread.h>
int n, capacity, linn = 0, sinn = 0, threadcount = 0;
pthread_mutex_t idlock;
sem_t fulllock, innlock, lock_first[2], lock_second[2];
int count_inside[2];
void lock_init()
{
sem_init(&fulllock, 0, capacity);
sem_init(&innlock, 0, 1);
pthread_mutex_init(&idlock, 0);
int i;
for(i = 0; i<2; i++)
{
sem_init(&lock_first[i], 0, 1);
sem_init(&lock_second[i], 0, 1);
count_inside[i] = 0;
}
}
void getlock(int faction)
{
sem_wait(&lock_first[faction]);
sem_wait(&lock_second[faction]);
count_inside[faction]++;
if(count_inside[faction] == 1)
sem_wait(&innlock);
sem_post(&lock_second[faction]);
sem_wait(&fulllock);
sem_post(&lock_first[faction]);
}
void releaselock(int faction)
{
sem_wait(&lock_second[faction]);
if(count_inside[faction] == 1)
sem_post(&innlock);
count_inside[faction]--;
sem_post(&lock_second[faction]);
sem_post(&fulllock);
}
void *soldier(void *args)
{
int faction = rand() % 2;
pthread_mutex_lock(&idlock);
int id = ++threadcount;
pthread_mutex_unlock(&idlock);
getlock(faction);
if(faction == 0)
printf("Soldier %d of Lannister inside inn\\n", id);
else
printf("Soldier %d of Stark inside inn\\n", id);
sleep(1 + rand() % 3);
if(faction == 0)
printf("Soldier %d of Lannister moving out\\n", id);
else
printf("Soldier %d of Stark moving out\\n", id);
releaselock(faction);
}
int main()
{
printf("Enter the capacity of inn and total number of soldiers: ");
scanf("%d %d", &capacity, &n);
pthread_t p[n];
int i, rc;
lock_init();
srand(time(0));
printf("Initiate simulation\\n");
for(i = 0; i<n; i++)
{
rc = pthread_create(&p[i], 0, soldier, 0);
assert (rc == 0);
}
for(i = 0; i<n; i++)
{
pthread_join(p[i], 0);
}
printf("End simulation\\n");
return 0;
}
| 0
|
#include <pthread.h>
int count = 0;
int thread_ids[3] = {0,1,2};
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *inc_count(void *t)
{
int i;
long my_id = (long)t;
for (i=0; i<10; i++) {
pthread_mutex_lock(&count_mutex);
count++;
if (count == 12) {
pthread_cond_signal(&count_threshold_cv);
printf("inc_count(): thread %ld, count = %d Threshold reached.\\n",
my_id, count);
}
printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n",
my_id, count);
pthread_mutex_unlock(&count_mutex);
sleep(1);
}
pthread_exit(0);
}
void *watch_count(void *t)
{
long my_id = (long)t;
printf("Starting watch_count(): thread %ld\\n", my_id);
pthread_mutex_lock(&count_mutex);
while (count<12) {
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %ld Condition signal received.\\n", my_id);
count += 125;
printf("watch_count(): thread %ld count now = %d.\\n", my_id, count);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main (int argc, char *argv[])
{
int i, rc;
long t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, watch_count, (void *)t1);
pthread_create(&threads[1], &attr, inc_count, (void *)t2);
pthread_create(&threads[2], &attr, inc_count, (void *)t3);
for (i=0; i<3; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited on %d threads. Done.\\n", 3);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
int chunk_size,nRows,nCols,padding,nThread;
int seek=0,fd;
pthread_t *t;
int thread_block;
int *MatrixA,*MatrixB,*MatrixC;
void fillMatrix(char *name)
{
FILE *fp=fopen(name,"w+");
if(fp==0)
{
perror("Error in opening file");
exit(1);
}
int i,j;
padding=nRows%(chunk_size/4);
if(padding!=0)
padding=chunk_size/4-padding;
printf(" \\n padding is %d\\n",padding);
for(i=0;i<nRows;i++)
{
for(j=0;j<nCols;j++)
{
int x=2,nwrite;
nwrite=fwrite(&x,sizeof(int),1,fp);
assert(nwrite==1);
}
for(j=0;j<padding;j++)
{
int x=0,nwrite;
nwrite=fwrite(&x,sizeof(int),1,fp);
assert(nwrite==1);
}
}
fclose(fp);
}
void printMatrix(char *name)
{
FILE *fp=fopen(name,"r");
if(fp==0)
{
perror("Error in Opening File");
exit(1);
}
int i,j;
int val,nread;
for(i=0;i<nRows;i++)
{
for(j=0;j<nCols;j++)
{
nread=fread(&val,sizeof(int),1,fp);
assert(nread==1);
printf("%d ",val);
}
for(j=0;j<padding;j++)
{
nread=fread(&val,sizeof(int),1,fp);
assert(nread==1);
printf("%d ",val);
}
printf("\\n");
}
fclose(fp);
}
void printresult(char * name,int index)
{int i ,buf;
int fd=open(name,O_RDONLY);
lseek(fd,index,0);
for(i=0;i<chunk_size/4;i++)
{
read(fd,&buf,4);printf("%d ",buf);
}
close(fd);
}
int chunk_by_chunk_multiply()
{
size_t i,j,k;
int sum;
sum=0;
for(j=0;j<chunk_size/4;j++)
{
sum+=MatrixA[j]*MatrixB[j];
}
return sum;
}
int* map_matrix_chunk(char * name,int mode,int rowindex,int colindex)
{
int fd;
if(mode==1)
fd=open(name,O_RDONLY);
else if(mode==2)
fd=open(name,O_RDWR);
if(fd==-1)
{
perror("File not Opened ");
exit(1);
}
int cur_position =rowindex*nRows*4+colindex*chunk_size;
lseek(fd,cur_position,0);
int *map_addr=0;
if(mode==1)
map_addr=mmap(0,chunk_size,PROT_READ,MAP_SHARED,fd,0);
else if(mode==2)
map_addr=mmap(0,chunk_size,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if(map_addr==MAP_FAILED)
{
perror("MMAP Error");exit(1);}
close(fd);
return map_addr;
}
int* map_matrix_chunk2(char * name,int mode,int rowindex,int colindex)
{
int fd;
if(mode==1)
fd=open(name,O_RDONLY);
else if(mode==2)
fd=open(name,O_RDWR);
if(fd==-1)
{
perror("File not Opened ");
exit(1);
}
int cur_position =rowindex*4+colindex*chunk_size;
lseek(fd,cur_position,0);
int *map_addr=0;
if(mode==1)
map_addr=mmap(0,chunk_size,PROT_READ,MAP_SHARED,fd,0);
else if(mode==2)
map_addr=mmap(0,chunk_size,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
if(map_addr==MAP_FAILED)
{
perror("MMAP Error");exit(1);}
close(fd);
return map_addr;
}
void * dowork(void *arg)
{
int i,j,k,index;
int tid=*(int*)arg;
int start,end;
start=tid*thread_block;
end=(tid+1)*thread_block-1;
for(i=start;i<=end;i++)
{
pthread_mutex_lock(&lock);
for(j=0;j<(nCols);j++)
{
printf("\\n ------------- i and j vale is %d %d\\n",i,j);
if(j%(chunk_size/4)==0)
{
MatrixC=map_matrix_chunk2("./MatrixC",2,i,j%(chunk_size/4));
memset(MatrixC,0,chunk_size);
index=0;
}
for(k=0;k<(nCols*4/chunk_size);k++)
{
MatrixA=map_matrix_chunk2("./MatrixA",1,i,k);
MatrixB=map_matrix_chunk("./MatrixB",1,j,k);
MatrixC[index]+=chunk_by_chunk_multiply(k);
munmap(MatrixB,chunk_size);
munmap(MatrixA,chunk_size);
}
index++;
if((j+1)%(chunk_size/4)==0)
{
int loc=0,w,buf=0;
for(loc=0;loc<chunk_size/4;loc++)
{buf=MatrixC[loc];
w=write(fd,&buf,4);
}
munmap(MatrixC,chunk_size);
}
}
pthread_mutex_unlock(&lock);
}
}
void map_Matrix()
{
int i,j,k,index;
fd=open("./MatrixC",O_RDWR);
if(fd==-1)
{
perror("File not opened ");
exit(1);
}
for(i=0;i<nThread;i++)
{
int *x=(int*)malloc(4);
*x=i;
pthread_create(&t[i],0,dowork,x);
}
for(i=0;i<nThread;i++)
pthread_join(t[i],0);
close(fd);
}
int main(int argc,char **argv)
{
pthread_mutex_init(&lock,0);
if(argc==4)
{
nRows=atoi(argv[1]);chunk_size=atoi(argv[2]);
nThread=atoi(argv[3]);
if(chunk_size&(chunk_size-1)!=0)
{
printf("\\n Chunk_Size should be Power of 2\\n");
exit(1);
}
}
else if(argc==2)
{
nRows=atoi(argv[1]);
nThread=16;
printf("\\nWe assuming chunk size as 4096 and nThread as 10\\n");chunk_size=4096;
}
else if(argc==1)
{
printf("\\n We assuming array size as 8192 and Chunk Size as 4096 and nThread as 10\\n");
nRows=8192;
chunk_size=4096;
nThread=16;
}
nCols=nRows;
fillMatrix("./MatrixA");
printf("\\n\\n Matrix A is......\\n\\n");
fillMatrix("./MatrixB");
printf("\\n\\n Matrix B is ...........\\n\\n");
fillMatrix("./MatrixC");
printf("\\n\\n Matric C.....\\n\\n");
nRows=nRows;
nCols=nRows+padding;
thread_block=nRows/nThread;
t=(pthread_t *)malloc(sizeof(pthread_t)*nThread);
struct timeval tv_start,tv_end;
gettimeofday(&tv_start,0);
printf("\\n hi\\n");
map_Matrix();
gettimeofday(&tv_end,0);
nCols=nCols-padding;
padding=0;
printMatrix("./MatrixC");
printf("\\n\\n-----------------------------------------------------------------------------------------------\\n\\n");
printf("\\n \\n time taken is %f sec ",(double)((tv_end.tv_sec-tv_start.tv_sec)+((tv_end.tv_usec-tv_start.tv_usec)/1000000)));
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
int m;
int biggest = 100;
int n;
int rank;
int* array;
}arg_struct;
void *findGreatest(void* arg){
arg_struct *thread = (arg_struct *)arg;
int *segment = thread->array;
for(int i = 0; i < n; i++){
if(biggest < segment[i]){
pthread_mutex_lock(&mutex);
biggest = segment[i];
pthread_mutex_unlock(&mutex);
}
free(arg);
}
return 0;
}
int main(void) {
srand(time(0));
long t;
m = rand() % (21 - 10) + 10;
n = rand() % (1001 - 100) + 100;
while(n % m != 0){
n++;
}
int* a;
a = (int * ) malloc(sizeof(int) * 1000);
for (int i = 0; i < n; i++) {
int r = rand() % (1001 - 100) + 100;
a[i] = r;
}
int** segments = malloc((m) * sizeof(int *));
for (int i = 0; i < m; i++) {
segments[i] = malloc((n) * sizeof(int));
}
pthread_t* thread_handles;
arg_struct thread[4];
pthread_mutex_init(&mutex, 0);
thread_handles = malloc(m*sizeof(pthread_t));
for (t = 0; t < m; t++) {
thread[t].rank = t;
thread[t].array = segments[t];
pthread_create(&thread_handles[t], 0, findGreatest, &thread[t]);
}
for (t = 0; t < m; t++){
pthread_join(thread_handles[t], 0);
}
pthread_mutex_destroy(&mutex);
free(thread_handles);
printf("%i",biggest);
return 0;
}
| 1
|
#include <pthread.h>
void init_matrix (int **matrix, int fils, int cols) {
int i, j;
for (i = 0; i < fils; i++) {
for (j = 0; j < cols; j++) {
matrix[i][j] = 1;
}
}
}
int **matrix1;
int **matrix2;
int **matrixR;
int matrix1_fils;
int matrix1_cols;
int matrix2_fils;
int matrix2_cols;
pthread_t *thread_list;
pthread_mutex_t mutex;
int pending_jobs = 0;
struct job {
int i;
struct job *next;
};
struct job *job_list = 0;
struct job *last_job = 0;
void add_job(int i){
struct job *job = malloc(sizeof(struct job));
job->i = i;
job->next = 0;
if(pending_jobs == 0){
job_list = job;
last_job = job;
}
else{
last_job->next = job;
last_job = job;
}
pending_jobs++;
}
struct job* get_job(){
struct job *job = 0;
if(pending_jobs > 0){
job = job_list;
job_list = job->next;
if(job_list == 0){
last_job = 0;
}
pending_jobs--;
}
return job;
}
void do_job(struct job *job) {
int j, k, acum;
for (j = 0; j < matrix2_cols; j++) {
acum = 0;
for (k = 0; k < matrix1_cols; k++) {
acum += matrix1[job->i][k] * matrix2[k][j];
}
matrixR[job->i][j] = acum;
}
}
void* dispatch_job () {
struct job *job;
while(1) {
pthread_mutex_lock(&mutex);
job = get_job();
pthread_mutex_unlock(&mutex);
if (job) {
do_job(job);
free(job);
}
else {
pthread_exit(0);
}
}
}
int main (int argc, char **argv) {
if (argc > 3) {
printf("\\n%s %s %s %s\\n", argv[0], argv[1], argv[2], argv[3]);
matrix1_fils = strtol(argv[1], (char **) 0, 10);
matrix1_cols = strtol(argv[2], (char **) 0, 10);
matrix2_fils = matrix1_cols;
matrix2_cols = strtol(argv[3], (char **) 0, 10);
int i;
matrix1 = (int **) calloc(matrix1_fils, sizeof(int*));
for (i = 0; i < matrix1_fils; i++){
matrix1[i] = (int *) calloc(matrix1_cols, sizeof(int));
}
matrix2 = (int **) calloc(matrix2_fils, sizeof(int*));
for (i = 0; i < matrix2_fils; i++){
matrix2[i] = (int *) calloc(matrix2_cols, sizeof(int));
}
matrixR = (int **) malloc(matrix1_fils * sizeof(int*));
for (i = 0; i < matrix1_fils; i++){
matrixR[i] = (int *) malloc(matrix2_cols * sizeof(int));
}
init_matrix(matrix1, matrix1_fils, matrix1_cols);
init_matrix(matrix2, matrix2_fils, matrix2_cols);
for (i = 0; i < matrix1_fils; i++) {
add_job(i);
}
thread_list = malloc(sizeof(int) * 3);
pthread_mutex_init(&mutex, 0);
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
for (i = 0; i < 3; i++) {
pthread_create(&thread_list[i], &attr, dispatch_job, 0);
}
for (i = 0; i < 3; i++) {
pthread_join(thread_list[i], 0);
}
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&mutex);
free(thread_list);
for (i = 0; i < matrix1_fils; i++) {
free(matrix1[i]);
}
free(matrix1);
for (i = 0; i < matrix2_fils; i++) {
free(matrix2[i]);
}
free(matrix2);
for (i = 0; i < matrix1_fils; i++) {
free(matrixR[i]);
}
free(matrixR);
return 0;
}
fprintf(stderr, "Uso: %s filas_matriz1 columnas_matriz1 columnas_matriz2\\n", argv[0]);
return -1;
}
| 0
|
#include <pthread.h>
int element[(20)];
int head;
int tail;
int amount;
} QType;
pthread_mutex_t m;
int stored_elements[(20)];
_Bool enqueue_flag, dequeue_flag;
QType queue;
int init(QType *q)
{
q->head=0;
q->tail=0;
q->amount=0;
}
int empty(QType * q)
{
if (q->head == q->tail)
{
printf("queue is empty\\n");
return (-1);
}
else
return 0;
}
int full(QType * q)
{
if (q->amount == (20))
{
printf("queue is full\\n");
return (-2);
}
else
return 0;
}
int enqueue(QType *q, int x)
{
q->element[q->tail] = x;
q->amount++;
if (q->tail == (20))
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == (20))
{
q->head = 1;
}
else
q->head++;
return x;
}
void *t1(void *arg)
{
int value, i;
pthread_mutex_lock(&m);
value = 0;
assert(!enqueue(&queue,value));
stored_elements[0]=value;
assert(!empty(&queue));
pthread_mutex_unlock(&m);
for(i=0; i<((20)-1); i++)
{
pthread_mutex_lock(&m);
if (enqueue_flag)
{
value++;
enqueue(&queue,value);
stored_elements[i+1]=value;
enqueue_flag=(0);
dequeue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
}
void *t2(void *arg)
{
int i;
for(i=0; i<(20); i++)
{
pthread_mutex_lock(&m);
if (dequeue_flag)
{
assert(dequeue(&queue)==stored_elements[i]);
dequeue_flag=(0);
enqueue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
}
int main(void)
{
pthread_t id1, id2;
enqueue_flag=(1);
dequeue_flag=(0);
init(&queue);
assert(empty(&queue)==(-1));
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, &queue);
pthread_create(&id2, 0, t2, &queue);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 1
|
#include <pthread.h>
int buffer[3];
pthread_mutex_t buff_lock;
void *p1()
{
int i;
int j = 1;
while(1) {
if(j >= 1000){
j = 1;
}
for(i=0; i< 3; i = i+1){
if(buffer[i] == 0){
pthread_mutex_lock(buff_lock);
buffer[i] = j;
pthread_mutex_unlock(buff_lock);
j = j +1;
}
}
}
}
void *c1()
{
int i;
while (1){
for (i = 3 -1; i >=0 ; i= i-1){
if (buffer[i] !=0) {
pthread_mutex_lock(buff_lock);
buffer[i] = 0;
pthread_mutex_unlock(buff_lock);
}
}
}
}
void *c2()
{
int i;
while (1){
for (i = 3 -1; i >=0 ; i= i-1){
if (buffer[i] !=0) {
pthread_mutex_lock(buff_lock);
buffer[i] = 0;
pthread_mutex_unlock(buff_lock);
}
}
}
}
int main()
{
pthread_t producer;
pthread_t cons1, cons2;
int i;
for (i=0; i <3; i=i+1)
buffer[i] =0;
pthread_mutex_init(buff_lock, 0);
pthread_create(producer, 0, p1, 0);
pthread_create(cons1, 0, c1, 0);
pthread_create(cons2, 0, c2, 0);
pthread_join(producer, 0);
pthread_join(cons1, 0);
pthread_join(cons2, 0);
}
| 0
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER;
void *thr_fn(void *arg)
{
int err, signo;
for (;;)
{
err = sigwait(&mask, &signo);
if (err!=0)
{
err_sys(err, "sigwait failed");
}
switch (signo)
{
case SIGINT:
printf("\\ninterrupte\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&waitloc);
break;
default:
printf("unexpeced signal %d\\n", signo);
exit(1);
}
}
}
int main(void)
{
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask))!=0)
{
err_sys(err,"SIG_BLOCK error");
}
err = pthread_create(&tid, 0, thr_fn,0);
if (err!=0)
{
err_sys(err,"can't create thread");
}
pthread_mutex_lock(&lock);
while(quitflag==0)
{
pthread_cond_wait(&waitloc, &lock);
}
pthread_mutex_unlock(&lock);
quitflag = 0;
if (sigprocmask(SIG_SETMASK, &oldmask, 0)<0)
{
err_sys("SIG_SETMASK error");
}
exit(0);
}
| 1
|
#include <pthread.h>
void *count_frequency_function( void *ptr );
pthread_mutex_t count_frequency_mutex;
struct word_count
{
char ch[15];
int count;
};
struct track_thread
{
int thread_number;
char *message;
};
int main()
{
pthread_t mapper1, mapper2, mapper3;
char ch[] = "Hello World World this this is Joyanta, please take me-to David Gilmouru sdkhcskch jcjklcjlwdj";
double len = (double) strlen(ch);
int first_index = (int)floor(len/3.0);
while(ch[first_index]!=' ')
{
first_index++;
}
int second_index = (int)floor(len/3.0);
while(ch[first_index+second_index] != ' ')
{
second_index++;
}
int third_index = (int) len - (second_index + first_index);
struct track_thread *t_info1;
struct track_thread *t_info2;
struct track_thread *t_info3;
t_info1 = malloc(sizeof(struct track_thread));
t_info2 = malloc(sizeof(struct track_thread));
t_info3 = malloc(sizeof(struct track_thread));
t_info1->thread_number = 1;
t_info1->message = malloc(sizeof(char) * (first_index+1));
t_info2->thread_number = 2;
t_info2->message = malloc(sizeof(char) * (second_index+1));
t_info3->thread_number = 3;
t_info3->message = malloc(sizeof(char) * (third_index+1));
strncpy(t_info1->message, ch, first_index);
t_info1->message[first_index] = '\\0';
strncpy(t_info2->message, ch+first_index, second_index);
t_info2->message[second_index] = '\\0';
strncpy(t_info3->message, ch+first_index+second_index, third_index);
t_info3->message[third_index] = '\\0';
int iret1, iret2, iret3;
iret1 = pthread_create( &mapper1, 0, count_frequency_function, (void*) t_info1);
iret2 = pthread_create( &mapper2, 0, count_frequency_function, (void*) t_info2);
iret3 = pthread_create( &mapper3, 0, count_frequency_function, (void*) t_info3);
sleep(1);
pthread_join( mapper1, 0);
pthread_join( mapper2, 0);
pthread_join( mapper3, 0);
printf("Mapper 1 returns: %d\\n",iret1);
printf("Mapper 2 returns: %d\\n",iret2);
printf("Mapper 3 returns: %d\\n",iret3);
exit(0);
}
void WriteToReducerDataStructure(struct word_count record[], int diff_word)
{
pthread_mutex_lock(&count_frequency_mutex);
for(int i=0; i<diff_word;i++)
{
sleep(1);
printf("%s----%d\\n", record[i].ch, record[i].count);
}
pthread_mutex_unlock(&count_frequency_mutex);
}
void *count_frequency_function( void *ptr )
{
struct track_thread *thread_information = (struct track_thread*)ptr;
printf("Thread %d String: %s\\n", thread_information->thread_number, thread_information->message);
struct word_count record[5000];
char* pch = strtok ( thread_information->message ," ,.-");
int counter = 0;
int diff_word = 0;
int struct_counter;
while (pch != 0)
{
struct_counter = 0;
while(struct_counter <= diff_word)
{
if(struct_counter == diff_word) break;
if(strcmp(record[struct_counter].ch, pch)==0)
{
record[struct_counter].count ++;
break;
}
struct_counter++;
}
if(struct_counter == diff_word)
{
strcpy(record[diff_word].ch, pch);
record[diff_word].count = 1;
diff_word = diff_word + 1;
}
pch = strtok (0, " ,.-");
counter++;
}
WriteToReducerDataStructure(record, diff_word);
printf("\\n\\n");
}
| 0
|
#include <pthread.h>
pthread_cond_t cond_a = PTHREAD_COND_INITIALIZER;
int condition_a = 0, condition_b = 0;
pthread_cond_t cond_b = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_rwlock_t rwlock;
static void* pthread_a_work(void* args) {
sorm_connection_t *_conn;
int ret = sorm_open("pthread.db", SORM_DB_SQLITE, 0, &rwlock,
SORM_ENABLE_RWLOCK, &_conn);
assert(ret == SORM_OK);
device_t *device;
sorm_iterator_t *iterator;
ret = device_select_iterate_by_open(_conn, ALL_COLUMNS,
0, &iterator);
sorm_begin_read_transaction(_conn);
int i;
for (i = 0; i < 4; i ++) {
device_select_iterate_by(iterator, &device);
char string[1024];
printf("select : %s\\n",
device_to_string(device, string, 1024));
device_free(device);
}
sorm_begin_write_transaction(_conn);
device = device_new();
device_set_id(device, 3);
device_set_uuid(device, "uuid-3");
device_set_name(device, "name-3");
device_set_password(device, "passwd-3");
ret = device_insert(_conn, device);
assert(ret == SORM_OK);
device_free(device);
printf("insert uuid-3\\n");
pthread_mutex_lock(&mutex);
condition_b = 1;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond_b);
printf("wait for input\\n");
ret = getchar();
printf("continue running\\n");
sorm_commit_transaction(_conn);
while (1) {
device_select_iterate_by(iterator, &device);
if (!device_select_iterate_more(iterator)) {
break;
}
char string[1024];
printf("select : %s\\n",
device_to_string(device, string, 1024));
device_free(device);
}
sorm_commit_transaction(_conn);
device_select_iterate_close(iterator);
printf("a finish\\n");
sorm_close(_conn);
}
static void* pthread_b_work(void* args) {
sorm_connection_t *_conn;
int ret = sorm_open("pthread.db", SORM_DB_SQLITE, 0, &rwlock,
SORM_ENABLE_RWLOCK, &_conn);
assert(ret == SORM_OK);
pthread_mutex_lock(&mutex);
while (condition_b == 0) {
pthread_cond_wait(&cond_b, &mutex);
}
pthread_mutex_unlock(&mutex);
sorm_iterator_t *iterator;
sorm_begin_read_transaction(_conn);
device_t *device;
ret = device_select_iterate_by_open(_conn, ALL_COLUMNS,
0, &iterator);
while (1) {
device_select_iterate_by(iterator, &device);
if (!device_select_iterate_more(iterator)) {
break;
}
char string[1024];
printf("select : %s\\n",
device_to_string(device, string, 1024));
device_free(device);
}
device_select_iterate_close(iterator);
sorm_commit_transaction(_conn);
printf("b finish\\n");
sorm_close(_conn);
}
int main() {
pthread_rwlock_init(&rwlock, 0);
pthread_t p1, p2;
sorm_init(0);
sorm_connection_t *_conn;
int ret = sorm_open("pthread.db", SORM_DB_SQLITE, 0, &rwlock,
SORM_ENABLE_RWLOCK, &_conn);
ret = device_create_table(_conn);
assert(ret == SORM_OK);
int i;
device_t *device;
for(i = 0; i < 10; i ++)
{
if (i == 3) {
continue;
}
device = device_new();
device->id = i;
device->id_stat = SORM_STAT_VALUED;
sprintf(device->uuid,"uuid-%d", i);
device->uuid_stat = SORM_STAT_VALUED;
sprintf(device->name,"name-%d", i);
device->name_stat = SORM_STAT_VALUED;
sprintf(device->password, "passwd-%d", i);
device->password_stat = SORM_STAT_VALUED;
device_insert(_conn, device);
device_free(device);
}
ret = pthread_create(&p1, 0, pthread_a_work, (void*)_conn);
assert(ret == 0);
ret = pthread_create(&p2, 0, pthread_b_work, (void*)_conn);
assert(ret == 0);
pthread_join(p1, 0);
pthread_join(p2, 0);
sorm_iterator_t *iterator;
ret = device_select_iterate_by_open(_conn, ALL_COLUMNS,
0, &iterator);
while (1) {
device_select_iterate_by(iterator, &device);
if (!device_select_iterate_more(iterator)) {
break;
}
char string[1024];
printf("select : %s\\n",
device_to_string(device, string, 1024));
device_free(device);
}
device_select_iterate_close(iterator);
ret = device_delete_table(_conn);
assert(ret == SORM_OK);
sorm_close(_conn);
}
| 1
|
#include <pthread.h>
struct foo{
int f_count;
pthread_mutex_t f_lock;
};
struct foo *foo_alloc(void){
struct foo *fp;
if((fp = malloc(sizeof(struct foo))) != 0){
fp->f_count = 1;
if(pthread_mutex_init(&fp->f_lock, 0) != 0){
free(fp);
return (0);
}
}
return (fp);
}
void foo_hold(struct foo *fp){
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
void foo_rele(struct foo *fp){
pthread_mutex_lock(&fp->f_lock);
if(--fp->f_count == 0){
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
}else{
pthread_mutex_unlock(&fp->f_lock);
}
}
void *fun1(struct foo *fp){
printf("thead1 start\\n");
printf("fun1 %d\\n", fp->f_count);
foo_hold(fp);
printf("fun1 %d\\n", fp->f_count);
foo_rele(fp);
pthread_exit((void *)1);
}
void *fun2(struct foo *fp){
printf("thead2 start\\n");
foo_hold(fp);
printf("fun2 %d\\n", fp->f_count);
foo_rele(fp);
pthread_exit((void *)1);
}
int main(){
struct foo *ptr = foo_alloc();
pthread_t tid1, tid2;
int err;
printf("Main %d\\n", ptr->f_count);
sleep(2);
err = pthread_create(&tid1, 0, fun1, &ptr);
if(err != 0){
printf("error\\n");
}
sleep(2);
err = pthread_create(&tid2, 0, fun2, &ptr);
if(err != 0){
printf("error\\n");
}
printf("Main %d\\n", ptr->f_count);
return 0;
}
| 0
|
#include <pthread.h>
int *is_processing_user_command;
void *runSensor(void *is_processing_user_command_ptr)
{
pinMode (0, INPUT);
pinMode (2, OUTPUT);
digitalWrite(2, LOW);
delay(30);
int distance;
printf("SENSOR: %d\\n", sensor);
while (1) {
pthread_mutex_lock(&sensor_lock);
while(!sensor) {
printf("Sensor waiting on condition\\n");
pthread_cond_wait(&sensor_cond, &sensor_lock);
}
pthread_mutex_unlock(&sensor_lock);
distance = getCM();
printf("distance: %d\\n", distance);
if (distance < 30) {
digitalWrite (8, HIGH ) ;
digitalWrite (9, LOW) ;
digitalWrite (3, LOW) ;
digitalWrite (12, HIGH) ;
delay(800);
pthread_mutex_lock(&sensor_lock);
if (sensor) {
digitalWrite (8, LOW ) ;
digitalWrite (9, HIGH) ;
digitalWrite (3, LOW) ;
digitalWrite (12, HIGH) ;
}
pthread_mutex_unlock(&sensor_lock);
}
delay(300);
}
return 0 ;
}
int getCM() {
printf("Send trig pulse\\n");
digitalWrite(2, HIGH);
delayMicroseconds(20);
printf("trig pulse sent\\n");
digitalWrite(2, LOW);
while(digitalRead(0) == LOW) {
};
long startTime = micros();
while(digitalRead(0) == HIGH);
long travelTime = micros() - startTime;
int distance = travelTime / 58;
return distance;
}
| 1
|
#include <pthread.h>
static void analysis_web_from_job(struct Job *current_job);
static void analysis_web_from_http_list(struct Http_List *list,time_t current_time,
struct tuple4 addr);
static void analysis_web_from_http(struct Http *http,time_t current_time,
struct tuple4 addr);
static void process_function_actual(int job_type);
static int process_judege(struct Job *job);
static void *process_function(void *);
static int hash_index;
static char buffer_postdata[1024*1024*100];
static void analysis_web_from_job(struct Job *current_job){
struct Http_RR *http_rr = current_job->http_rr;
if(http_rr == 0)
return;
analysis_web_from_http_list(http_rr->request_list,current_job->time,
current_job->ip_and_port);
analysis_web_from_http_list(http_rr->response_list,current_job->time,
current_job->ip_and_port);
}
static void analysis_web_from_http_list(struct Http_List *list,time_t current_time,
struct tuple4 addr){
if(list == 0)
return;
struct Http * point = list->head;
while(point != 0){
analysis_web_from_http(point,current_time, addr);
point = point->next;
}
}
static void analysis_web_from_http(struct Http *http,time_t current_time,
struct tuple4 addr){
if(http->type != PATTERN_REQUEST_HEAD)
return;
struct WebInformation webinfo;
webinfo.request = http->method;
webinfo.host = http->host;
webinfo.url = http->uri;
webinfo.referer = http->referer;
webinfo.time = current_time;
webinfo.data_length = 0;
webinfo.data_type = 0;
webinfo.data = 0;
strcpy(webinfo.srcip, int_ntoa(addr.saddr));
strcpy(webinfo.dstip, int_ntoa(addr.daddr));
char segment[] = "\\n";
if(strstr(webinfo.request,"POST")!= 0){
int length = 0;
struct Entity_List *entity_list;
struct Entity *entity;
entity_list = http->entity_list;
if(entity_list != 0){
entity = entity_list->head;
while(entity != 0){
if(entity->entity_length <= 0 || entity->entity_length > 1024*1024*100){
entity = entity->next;
continue;
}
length += entity->entity_length;
length += 1;
entity = entity->next;
}
}
if(length > 1 && length < 1024*1024*100){
memset(buffer_postdata,0,length+1);
entity_list = http->entity_list;
if(entity_list != 0){
entity = entity_list->head;
while(entity != 0){
if(entity->entity_length <= 0 || entity->entity_length > 1024*1024*100){
entity = entity->next;
continue;
}
memcpy(buffer_postdata + length,entity->entity_content,entity->entity_length);
length += entity->entity_length;
memcpy(buffer_postdata + length,segment,1);
length += 1;
entity = entity->next;
}
}
webinfo.data_length = length;
webinfo.data_type = "";
webinfo.data = buffer_postdata;
}
}
sql_factory_add_web_record(&webinfo,hash_index);
}
static void *process_function(void *arg){
int job_type = JOB_TYPE_WEB;
while(1){
pthread_mutex_lock(&(job_mutex_for_cond[job_type]));
pthread_cond_wait(&(job_cond[job_type]),&(job_mutex_for_cond[job_type]));
pthread_mutex_unlock(&(job_mutex_for_cond[job_type]));
process_function_actual(job_type);
}
return 0;
}
static void process_function_actual(int job_type){
struct Job_Queue private_jobs;
private_jobs.front = 0;
private_jobs.rear = 0;
get_jobs(job_type,&private_jobs);
struct Job current_job;
while(!jobqueue_isEmpty(&private_jobs)){
jobqueue_delete(&private_jobs,¤t_job);
hash_index = current_job.hash_index;
analysis_web_from_job(¤t_job);
if(current_job.http_rr != 0)
free_http_rr(current_job.http_rr);
}
}
static int process_judege(struct Job *job){
return 1;
}
extern void web_analysis_init(){
register_job(JOB_TYPE_WEB,process_function,process_judege,CALL_BY_HTTP_ANALYSIS);
}
| 0
|
#include <pthread.h>
char buffer[65536];
int array[128];
pthread_mutex_t lock;
{
int thread, start, end;
} startEndPoint;
void *counting (void *ptr) {
startEndPoint *data = (startEndPoint *) ptr;
printf("Thread ID: %d, Start: %d, End: %d\\n", data->thread, data->start, data->end);
pthread_mutex_lock(&lock);
for(int i = data->start; i < data->end; i++){
array[(int)buffer[i]]++;
}
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
int main(int argc, const char * argv[]) {
pthread_t workers[8];
const char *file;
int fd;
size_t bufferReadSize;
int sizeDiv;
startEndPoint data[8];
int i = 0;
int temp = 0;
int loop, gate = 0;
int threadCount;
if(argc > 2 || argc < 2){
return 1;
}else{
file = argv[1];
fd = open(file, O_RDONLY);
while((bufferReadSize = read(fd, &buffer, 65536))){
if(bufferReadSize<8){
sizeDiv = (int)bufferReadSize;
}else{
sizeDiv = (int)bufferReadSize / 8;
sizeDiv = (int)ceil(sizeDiv);
}
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("Mutex failed.\\n");
return 1;
}
threadCount = 8;
for(int i = 0; i < threadCount; i++){
data[i].thread = i;
data[i].start = i * sizeDiv;
if(8>bufferReadSize&&gate == 0){
threadCount = threadCount - (8 -(int)bufferReadSize);
sizeDiv = 1;
gate = 1;
}
if(i != 8 -1){
data[i].end = (i+1) * sizeDiv;
}
else if(i == 8 -1){
data[i].end = (int)bufferReadSize;
}
if(pthread_create(&workers[i], 0, counting, &data[i])!= 0){
printf("CREATE PROCESS FAILED!\\n");
return 1;
}
}
for(int j = 0; j < 8; j++){
pthread_join(workers[j], 0);
}
pthread_mutex_destroy(&lock);
}
for( i = 0; i <= 32; i++){
printf("%d occurrences of 0x%x\\n", array[i], i);
}
for(; i < 127; i++){
printf("%d occurrences of '%c'\\n", array[i], i);
}
printf("%d occurrences of 0x%x\\n", temp, i);
}
printf("%d\\n", array[65]);
close(fd);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
void *thread1(void *arg);
void *thread2(void *arg);
int main(void)
{
pthread_t tid1,tid2;
printf("Start!\\n");
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond,0);
pthread_create(&tid1,0,thread1,0);
pthread_create(&tid2,0,thread2,0);
do
{
pthread_cond_signal(&cond);
}
while(1);
sleep(50);
pthread_exit(0);
}
void *thread1(void *arg)
{
while(1)
{
printf("1 is running!\\n");
pthread_mutex_lock(&mutex);
printf("1111111\\n");
pthread_cond_wait(&cond,&mutex);
printf("1 applied the condition!\\n");
pthread_mutex_unlock(&mutex);
printf("AAAAAAAAA\\n");
sleep(4);
}
}
void *thread2(void *arg)
{
while(1)
{
printf("2 is running\\n");
pthread_mutex_lock(&mutex);
printf("22222222\\n");
pthread_cond_wait(&cond,&mutex);
printf("2 applied the condition!\\n");
pthread_mutex_unlock(&mutex);
printf("BBBBBBBBBB\\n");
sleep(1);
}
}
| 0
|
#include <pthread.h>
pthread_t thread[2];
pthread_mutex_t mut;
int number=0, i;
void *thread1()
{
printf ("thread1 : I'm thread 1\\n");
for (i = 0; i < 10; i++)
{
printf("thread1 : number = %d\\n",number);
pthread_mutex_lock(&mut);
number++;
pthread_mutex_unlock(&mut);
sleep(2);
}
printf("thread1 :主函数在等待吗?\\n");
pthread_exit(0);
}
void *thread2()
{
printf("thread2 : I'm thread 2\\n");
for (i = 0; i < 10; i++)
{
printf("thread2 : number = %d\\n",number);
pthread_mutex_lock(&mut);
number++;
pthread_mutex_unlock(&mut);
sleep(3);
}
printf("thread2 :主函数在等待吗?\\n");
pthread_exit(0);
}
void thread_create(void)
{
int temp;
memset(&thread, 0, sizeof(thread));
if((temp = pthread_create(&thread[0], 0, thread1, 0)) != 0)
printf("线程1创建失败!\\n");
else
printf("线程1被创建\\n");
if((temp = pthread_create(&thread[1], 0, thread2, 0)) != 0)
printf("线程2创建失败");
else
printf("线程2被创建\\n");
}
void thread_wait(void)
{
if(thread[0] !=0)
{
pthread_join(thread[0],0);
printf("线程1已经结束\\n");
}
if(thread[1] !=0)
{
pthread_join(thread[1],0);
printf("线程2已经结束\\n");
}
}
int main()
{
pthread_mutex_init(&mut,0);
printf("主函数,正在创建线程\\n");
thread_create();
printf("主函数,正在等待线程完成任务\\n");
thread_wait();
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
struct node {
int n_number;
struct node *n_next;
} *head = 0;
static void cleanup_handler(void *arg)
{
printf("Cleanup handler of second thread.\\n");
free(arg);
(void)pthread_mutex_unlock(&mtx);
}
static void *thread_func(void *arg)
{
struct node *p = 0;
pthread_cleanup_push(cleanup_handler, p);
while (1) {
pthread_mutex_lock(&mtx);
while (head == 0) {
pthread_cond_wait(&cond, &mtx);
}
p = head;
head = head->n_next;
printf("Got %d from front of queue\\n", p->n_number);
free(p);
pthread_mutex_unlock(&mtx);
}
pthread_cleanup_pop(0);
return 0;
}
int main(void)
{
pthread_t tid;
int i;
struct node *p;
pthread_create(&tid, 0, thread_func, 0);
for (i = 0; i < 10; i++) {
p = malloc(sizeof(struct node));
p->n_number = i;
pthread_mutex_lock(&mtx);
p->n_next = head;
head = p;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mtx);
sleep(1);
}
printf("thread 1 wanna end the line.So cancel thread 2.\\n");
pthread_cancel(tid);
pthread_join(tid, 0);
printf("All done -- exiting\\n");
return 0;
}
| 0
|
#include <pthread.h>
const long long MUL = 31;
int N;
pthread_mutex_t mutex;
const char *str;
const char *patt;
int pos = -1;
void update_pos(int p) {
pthread_mutex_lock(&mutex);
if (p < pos && p != -1 || pos == -1) {
pos = p;
}
pthread_mutex_unlock(&mutex);
}
void* rabin_karp_worker(void *thread_id) {
long id;
int start, end;
int i, patt_len;
long long patt_hash = 0, str_hash = 0, pow = 0;
id = (long) thread_id;
start = id * N / 2;
end = (id + 1) * N / 2;
for (i = 0; str[i + start] && patt[i]; i++) {
patt_hash = patt_hash * MUL + patt[i];
str_hash = str_hash * MUL + str[i + start];
if (pow) {
pow *= MUL;
} else {
pow = 1;
}
}
if (patt[i]) {
return 0;
}
patt_len = i;
end += patt_len;
i += start;
while (str[i]) {
if (patt_hash == str_hash) {
if (strncmp(str + i - patt_len, patt, patt_len) == 0) {
update_pos(i - patt_len);
return 0;
}
}
str_hash -= str[i - patt_len] * pow;
str_hash = str_hash * MUL + str[i];
i++;
}
if (strncmp(str + i - patt_len, patt, patt_len) == 0) {
update_pos(i - patt_len);
return 0;
}
return 0;
}
int rabin_karp(const char *s, int n, const char *p) {
int status;
long id;
str = s;
patt = p;
N = n;
pthread_t threads[2];
pthread_mutex_init(&mutex, 0);
pos = -1;
for (id = 0; id < 2; id++) {
status = pthread_create(&threads[id], 0, rabin_karp_worker,
(void*) id);
if (status) {
fprintf(stderr, "error %d in pthread_create\\n", status);
}
}
for (id = 0; id < 2; id++) {
pthread_join(threads[id], 0);
}
return pos;
}
int main() {
assert(rabin_karp("hello world", 12, "world") == 6);
assert(rabin_karp("hello world", 12, "galaxy") == -1);
assert(rabin_karp("abcdefghijk", 12, "c") == 2);
assert(rabin_karp("abcdefghijk", 12, "l") == -1);
assert(rabin_karp("first second", 13, "first") == 0);
assert(rabin_karp("long", 4, "longer") == -1);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
void *functionCount1();
void *functionCount2();
int count = 0;
int main()
{
pthread_t thread1, thread2, thread3;
int i1=1, i3=3;
pthread_create( &thread1, 0, &functionCount1, &i1);
pthread_create( &thread2, 0, &functionCount2, 0);
pthread_create( &thread3, 0, &functionCount1, &i3);
pthread_join( thread1, 0);
pthread_join( thread2, 0);
pthread_join( thread3, 0);
printf("Final count: %d\\n",count);
return 0;
}
void *functionCount1(void *i)
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
pthread_cond_wait( &condition_var, &count_mutex );
count++;
printf("Counter value functionCount%d: %d\\n", *((int *) i), count);
pthread_mutex_unlock( &count_mutex );
if(count >= 10) return(0);
}
}
void *functionCount2()
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
if( count < 3 || count > 6 )
{
pthread_cond_broadcast( &condition_var );
}
else
{
count++;
printf("Counter value functionCount2: %d\\n",count);
}
pthread_mutex_unlock( &count_mutex );
if(count >= 10) return(0);
}
}
| 0
|
#include <pthread.h>
static int s_finished_count;
static int s_set_thread_name;
static pthread_mutex_t s_mutex;
static void set_thread_name(const char* const fmt, const int arg)
{
if (s_set_thread_name)
{
int res;
char name[32];
snprintf(name, sizeof(name), fmt, arg);
name[sizeof(name) - 1] = 0;
VALGRIND_DO_CLIENT_REQUEST(res, 0, VG_USERREQ__SET_THREAD_NAME,
name, 0, 0, 0, 0);
}
}
void increment_finished_count()
{
pthread_mutex_lock(&s_mutex);
s_finished_count++;
pthread_mutex_unlock(&s_mutex);
}
int get_finished_count()
{
int result;
pthread_mutex_lock(&s_mutex);
result = s_finished_count;
pthread_mutex_unlock(&s_mutex);
return result;
}
static void* thread_func1(void* arg)
{
set_thread_name("thread_func1[%d]", *(int*)arg);
write(STDOUT_FILENO, ".\\n", 2);
increment_finished_count();
return 0;
}
static void* thread_func2(void* arg)
{
set_thread_name("thread_func2[%d]", *(int*)arg);
pthread_detach(pthread_self());
write(STDOUT_FILENO, ".\\n", 2);
increment_finished_count();
return 0;
}
int main(int argc, char** argv)
{
const int count1 = argc > 1 ? atoi(argv[1]) : 100;
const int count2 = argc > 2 ? atoi(argv[2]) : 100;
const int do_set_thread_name = argc > 3 ? atoi(argv[3]) != 0 : 0;
int thread_arg[count1 > count2 ? count1 : count2];
int i;
int detachstate;
pthread_attr_t attr;
s_set_thread_name = do_set_thread_name;
set_thread_name("main", 0);
for (i = 0; i < count1 || i < count2; i++)
thread_arg[i] = i;
pthread_mutex_init(&s_mutex, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
assert(pthread_attr_getdetachstate(&attr, &detachstate) == 0);
assert(detachstate == PTHREAD_CREATE_DETACHED);
pthread_attr_setstacksize(&attr, 16384);
for (i = 0; i < count1; i++)
{
pthread_t thread;
pthread_create(&thread, &attr, thread_func1, &thread_arg[i]);
}
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
assert(pthread_attr_getdetachstate(&attr, &detachstate) == 0);
assert(detachstate == PTHREAD_CREATE_JOINABLE);
for (i = 0; i < count2; i++)
{
pthread_t thread;
pthread_create(&thread, &attr, thread_func2, &thread_arg[i]);
}
pthread_attr_destroy(&attr);
while (get_finished_count() < count1 + count2)
{
struct timespec delay = { 0, 1 * 1000 * 1000 };
nanosleep(&delay, 0);
}
printf("\\n");
pthread_mutex_destroy(&s_mutex);
return 0;
}
| 1
|
#include <pthread.h>
int count = 0;
void __VERIFIER_atomic_inc()
{
__atomic_begin();
count++;
__atomic_end();
}
void __VERIFIER_atomic_dec()
{
__atomic_begin();
count--;
__atomic_end();
}
pthread_mutex_t mutexa,mutexb;
void my_thread1() {
pthread_mutex_lock(&mutexa);
__VERIFIER_atomic_inc();
__VERIFIER_atomic_dec();
pthread_mutex_unlock(&mutexa);
}
void my_thread2() {
pthread_mutex_lock(&mutexb);
__VERIFIER_atomic_dec();
__VERIFIER_atomic_inc();
pthread_mutex_unlock(&mutexb);
}
void* thr1(void* arg) {
while(1) {
pthread_mutex_lock(&mutexa);
assert(count >= -1);
pthread_mutex_lock(&mutexb);
assert(count == 0);
pthread_mutex_unlock(&mutexb);
pthread_mutex_unlock(&mutexa);
}
return 0;
}
void* thr2(void* arg) {
if(__nondet_int())
my_thread1();
else
my_thread2();
return 0;
}
int main(void)
{
pthread_t t1,t2,t3;
pthread_create(&t1, 0, thr1, 0);
pthread_create(&t2, 0, thr2, 0);
pthread_create(&t3, 0, thr2, 0);
return 0;
}
| 0
|
#include <pthread.h>
uint8_t hour;
uint8_t min;
uint8_t mode;
uint8_t repeat_factor;
char name[128];
struct AlarmClockInfo *next;
} AlarmClockInfo;
AlarmClockInfo **AlarmClockTab;
pthread_mutex_t AlarmClockLockTab[32];
int set_alarms = 0;
int update_alarms = 0;
int cancelled_alarms = 0;
int failed_cancel_alarms = 0;
AlarmClockInfo *CreateNewInfo(uint8_t hour, uint8_t min, uint8_t mode,
uint8_t repeat_factor, const char *name) {
AlarmClockInfo *ninfo = (AlarmClockInfo *)malloc(sizeof(AlarmClockInfo));
ninfo->hour = hour;
ninfo->min = min;
ninfo->mode = mode;
ninfo->repeat_factor = repeat_factor;
strcpy(ninfo->name, name);
ninfo->next = 0;
return ninfo;
}
static inline pthread_mutex_t *GetLock(uint8_t hour, uint8_t min) {
return (AlarmClockLockTab + (((hour) + (min)) & (32 - 1)));
}
static inline AlarmClockInfo *GetHeader(uint8_t hour, uint8_t min) {
return *(AlarmClockTab + (((hour) + (min)) & (32 - 1)));
}
int add_or_update_alarm(uint8_t hour, uint8_t min, uint8_t mode,
uint8_t repeat_factor, const char *name) {
pthread_mutex_t *bucket_mtx = GetLock(hour, min);
pthread_mutex_lock(bucket_mtx);
AlarmClockInfo *header = GetHeader(hour, min);
AlarmClockInfo *temp = header;
while (temp) {
if (temp->hour == hour && temp->min == min) {
temp->mode = mode;
temp->repeat_factor = repeat_factor;
strcpy(temp->name, name);
pthread_mutex_unlock(bucket_mtx);
return 0;
}
temp = temp->next;
}
AlarmClockInfo *naci = CreateNewInfo(hour, min, mode, repeat_factor, name);
naci->next = header;
*(AlarmClockTab + (((hour) + (min)) & (32 - 1))) = naci;
pthread_mutex_unlock(bucket_mtx);
return 1;
}
int cancel_alarm(uint8_t hour, uint8_t min, int play) {
pthread_mutex_t *bucket_mtx = GetLock(hour, min);
pthread_mutex_lock(bucket_mtx);
AlarmClockInfo *cand = GetHeader(hour, min);
AlarmClockInfo *prev = 0;
while (cand) {
if (cand->hour == hour && cand->min == min) {
if (play) {
;
}
if (!prev) {
*(AlarmClockTab + (((hour) + (min)) & (32 - 1))) = cand->next;
} else {
prev->next = cand->next;
}
free(cand);
pthread_mutex_unlock(bucket_mtx);
return 1;
}
prev = cand;
cand = cand->next;
}
pthread_mutex_unlock(bucket_mtx);
return 0;
}
void print_alarms() {
fprintf(stderr, "---------------\\n");
for (int i = 0; i < 32; ++i) {
AlarmClockInfo *aci = AlarmClockTab[i];
while (aci) {
fprintf(stderr, "%d %d %d %d %s\\n", aci->hour, aci->min, aci->mode,
aci->repeat_factor, aci->name);
aci = aci->next;
}
}
}
void *play_alarms() {
int8_t hour = 23;
int8_t min;
int status;
while (hour >= 0) {
min = 59;
while (min >= 0) {
status = cancel_alarm(hour, min, 1);
if (status) {
++cancelled_alarms;
} else {
++failed_cancel_alarms;
}
min -= 1;
}
--hour;
}
return 0;
}
int main() {
struct timeval tv_start;
struct timeval tv_end;
gettimeofday(&tv_start, 0);
pthread_t th;
AlarmClockTab =
(AlarmClockInfo **)malloc(32 * sizeof(AlarmClockInfo *));
pthread_create(&th, 0, (void *(*)(void *))play_alarms, 0);
uint8_t hour = 0;
uint8_t min;
int ret;
while (hour < 24) {
min = 0;
while (min < 60) {
ret = add_or_update_alarm(hour, min, 0, 0, "");
if (ret) {
++set_alarms;
} else {
++update_alarms;
}
min += 1;
}
hour += 1;
}
pthread_join(th, 0);
fprintf(stderr,
"Set = %d Updated = %d Cancelled = %d Failed canceling = %d\\n",
set_alarms, update_alarms, cancelled_alarms, failed_cancel_alarms);
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>
double sum;
void *runner(void *param);
struct thread_param {
int min;
int max;
};
pthread_mutex_t lock;
int main(int argc, char* argv[])
{
int n = atoi(argv[1]);
int thread_no = atoi(argv[2]);
if (thread_no < 1) {
printf("Error: There must be atleast one thread");
exit(0);
}
if (n % thread_no != 0) {
printf("Error: n must be divisible with thread_no");
exit(0);
}
pthread_mutex_init(&lock,0);
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_t *tid = malloc(sizeof(pthread_t)*thread_no);
struct thread_param *tp = malloc(sizeof(struct thread_param));
int diffsize = n / thread_no;
for(int i = 0; i < thread_no;i++) {
tp[i].min = 1+i*diffsize;
tp[i].max = (i+1)*diffsize;
pthread_create(&tid[i],&attr,runner,&tp[i]);
}
for(int i = 0; i < thread_no;i++) {
pthread_join(tid[i],0);
}
printf("sum = %f\\n",sum);
free(tid);
free(tp);
}
void *runner(void *arg)
{
struct thread_param *tp = arg;
double value = 0;
for (int i=tp->min;i <= tp->max;i++) {
value +=sqrt(i);
}
pthread_mutex_lock(&lock);
sum += value;
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
long long int compteur = 0;
pthread_mutex_t mtx_compteur = PTHREAD_MUTEX_INITIALIZER;
void * fonction(void * arg)
{
long nb_iterations = (long) arg;
int i;
pthread_mutex_lock(& mtx_compteur);
for (i = 0; i < nb_iterations; i ++)
compteur = compteur + 1;
pthread_mutex_unlock(& mtx_compteur);
return 0;
}
int main(int argc, char * argv[])
{
pthread_t * thr;
int i;
int nb_threads;
long nb_iterations;
if ((argc != 3) || (sscanf(argv[1], "%d", &nb_threads) != 1)
|| (sscanf(argv[2], "%ld", & nb_iterations) != 1)) {
fprintf(stderr, "usage: %s nb_threads nb_iterations\\n", argv[0]);
exit(1);
}
thr = calloc(nb_threads, sizeof(pthread_t));
for (i = 0; i < nb_threads; i ++)
pthread_create(& (thr[i]), 0, fonction, (void *)nb_iterations);
for (i = 0; i < nb_threads; i ++)
pthread_join(thr[i], 0);
fprintf(stderr, "Compteur = %lld\\n",compteur);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t lleno;
pthread_cond_t vacio;
int n_elementos;
int pos_p = 0;
int pos_c = 0;
int buffer[1024];
void *Productor(void *arg);
void *Consumidor(void *arg);
int main(int argc, char *argv[]){
pthread_t th1, th2;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&lleno, 0);
pthread_cond_init(&vacio, 0);
pthread_create(&th1, 0, Productor, 0);
pthread_create(&th2, 0, Consumidor, 0);
pthread_join(th1, 0);
pthread_join(th2, 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&lleno);
pthread_cond_destroy(&vacio);
exit(0);
}
void *Productor(void *arg)
{
int dato, i ,pos = 0;
for(i=0; i < 100000; i++ ) {
dato = dato+5;
pthread_mutex_lock(&mutex);
if (n_elementos == 1024)
pthread_cond_wait(&lleno, &mutex);
buffer[pos_p] = dato;
printf("%d %d\\n", pos, dato);
pos_p = (pos_p + 1) % 1024;
n_elementos ++;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&vacio);
}
pthread_exit(0);
}
void *Consumidor(void *arg) {
int dato, i ,pos = 0;
for(i=0; i < 100000; i++ ) {
pthread_mutex_lock(&mutex);
if (n_elementos == 0)
pthread_cond_wait(&vacio, &mutex);
dato = buffer[pos_c];
pos_c = (pos_c + 1) % 1024;
printf("%d\\n", dato);
n_elementos --;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&lleno);
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
static const char rcsid[]="$Id: diag.c,v 1.7 2007/05/18 23:14:40 santinod Exp $";
static pthread_mutex_t diag_mtx=PTHREAD_MUTEX_INITIALIZER;
static FILE *lf;
int debug_level;
void diag_restart(char *log_file)
{
pthread_mutex_lock(&diag_mtx);
fclose(lf);
lf=fopen(log_file,"a");
pthread_mutex_unlock(&diag_mtx);
if(!lf) {
lf=stderr;
diag(ERR,"Cannot reopen log file `%s'",log_file);
}
diag(INFO,"Log restarted\\n");
}
void diag_setfile(char *log_file)
{
FILE *f;
lf=stderr;
if(!log_file) return;
if(!(f=fopen(log_file,"a"))) diag(ERR,"Cannot open log file `%s'",log_file);
else lf=f;
}
void diag(int pri, char *format, ...)
{
va_list ap;
static char *subsystem[]={"","main","net","audio","devices","config","http",
"video"};
int subsys=pri>>9;
if((pri&(ERRMASK|DIE))<debug_level) return;
__builtin_va_start((ap));
pthread_mutex_lock(&diag_mtx);
if(!(pri&NOTIME)) {
char timestamp[60];
time_t now;
time(&now);
if(strftime(timestamp,60,"%b %e %T",localtime(&now) ) )
fprintf(lf,"%s ",timestamp);
}
if(subsys) fprintf(lf,"[%s] ",subsystem[subsys]);
if(pri&DIE) fprintf(lf,"** Fatal error: ");
vfprintf(lf,format,ap);
if(pri&ERRNO) fprintf(lf,": %s\\n",strerror(errno));
if(lf!=stderr) fflush(lf);
pthread_mutex_unlock(&diag_mtx);
;
if(pri&DIE) {
if(lf!=stderr) fclose(lf);
exit(pri);
}
}
| 1
|
#include <pthread.h>
extern int errno;
int gridsize = 0;
int grid[10][10];
int threads_left = 0;
pthread_mutex_t lock[10][10];
time_t start_t, end_t;
int PrintGrid(int grid[10][10], int gridsize)
{
int i;
int j;
for (i = 0; i < gridsize; i++)
{
for (j = 0; j < gridsize; j++)
fprintf(stdout, "%d\\t", grid[i][j]);
fprintf(stdout, "\\n");
}
return 0;
}
long InitGrid(int grid[10][10], int gridsize)
{
int i;
int j;
long sum = 0;
int temp = 0;
srand( (unsigned int)time( 0 ) );
for (i = 0; i < gridsize; i++)
for (j = 0; j < gridsize; j++) {
temp = rand() % 100;
grid[i][j] = temp;
sum = sum + temp;
if (pthread_mutex_init(&lock[i][j], 0) != 0)
{
printf("\\n mutex initialization failed!\\n");
return 1;
}
}
return sum;
}
long SumGrid(int grid[10][10], int gridsize)
{
int i;
int j;
long sum = 0;
for (i = 0; i < gridsize; i++){
for (j = 0; j < gridsize; j++) {
sum = sum + grid[i][j];
}
}
return sum;
}
int max(int x, int y)
{
if (x > y)
return x;
return y;
}
int min(int x, int y)
{
if (x < y)
return x;
return y;
}
void* do_swaps(void* args)
{
int i, row1, column1, row2, column2;
int temp;
grain_type* gran_type = (grain_type*)args;
threads_left++;
for(i=0; i<20; i++)
{
row1 = rand() % gridsize;
column1 = rand() % gridsize;
row2 = rand() % gridsize;
column2 = rand() % gridsize;
if (*gran_type == ROW)
{
pthread_mutex_lock(&lock[min(row1, row2)][0]);
if(!(row1 == row2))
{
pthread_mutex_lock(&lock[max(row1, row2)][0]);
}
}
else if (*gran_type == CELL)
{
if (((row1 * gridsize) + column1) < ((row2 * gridsize) + column2))
{
pthread_mutex_lock(&lock[row1][column1]);
if (!((row1 == row2) && (column1 == column2)))
{
pthread_mutex_lock(&lock[row2][column2]);
}
}
else
{
pthread_mutex_lock(&lock[row2][column2]);
if (!((row1 == row2) && (column1 == column2)))
{
pthread_mutex_lock(&lock[row1][column1]);
}
}
}
else if (*gran_type == GRID)
{
pthread_mutex_lock(&lock[0][0]);
}
temp = grid[row1][column1];
sleep(1);
grid[row1][column1]=grid[row2][column2];
grid[row2][column2]=temp;
if (*gran_type == ROW)
{
pthread_mutex_unlock(&lock[row1][0]);
if (!(row1 == row2))
{
pthread_mutex_unlock(&lock[row2][0]);
}
}
else if (*gran_type == CELL)
{
if (((row1 * gridsize) + column1) < ((row2 * gridsize) + column2))
{
pthread_mutex_unlock(&lock[row1][column1]);
if (!((row1 == row2) && (column1 == column2)))
{
pthread_mutex_unlock(&lock[row2][column2]);
}
}
else
{
pthread_mutex_unlock(&lock[row2][column2]);
pthread_mutex_unlock(&lock[row1][column1]);
}
}
else if (*gran_type == GRID)
{
pthread_mutex_unlock(&lock[0][0]);
}
}
threads_left--;
if (threads_left == 0){
time(&end_t);
}
return 0;
}
int main(int argc, char **argv)
{
int nthreads = 0;
pthread_t threads[1000];
grain_type rowGranularity = NONE;
long initSum = 0, finalSum = 0;
int i;
if (argc > 3)
{
gridsize = atoi(argv[1]);
if (gridsize > 10 || gridsize < 1)
{
printf("Grid size must be between 1 and 10.\\n");
return(1);
}
nthreads = atoi(argv[2]);
if (nthreads < 1 || nthreads > 1000)
{
printf("Number of threads must be between 1 and 1000.");
return(1);
}
if (argv[3][1] == 'r' || argv[3][1] == 'R')
rowGranularity = ROW;
if (argv[3][1] == 'c' || argv[3][1] == 'C')
rowGranularity = CELL;
if (argv[3][1] == 'g' || argv[3][1] == 'G')
rowGranularity = GRID;
}
else
{
printf("Format: gridapp gridSize numThreads -cell\\n");
printf(" gridapp gridSize numThreads -row\\n");
printf(" gridapp gridSize numThreads -grid\\n");
printf(" gridapp gridSize numThreads -none\\n");
return(1);
}
printf("Initial Grid:\\n\\n");
initSum = InitGrid(grid, gridsize);
PrintGrid(grid, gridsize);
printf("\\nInitial Sum: %d\\n", initSum);
printf("Executing threads...\\n");
srand((unsigned int)time( 0 ) );
time(&start_t);
for (i = 0; i < nthreads; i++)
{
if (pthread_create(&(threads[i]), 0, do_swaps, (void *)(&rowGranularity)) != 0)
{
perror("thread creation failed:");
exit(-1);
}
}
for (i = 0; i < nthreads; i++)
pthread_detach(threads[i]);
while (1)
{
sleep(2);
if (threads_left == 0)
{
fprintf(stdout, "\\nFinal Grid:\\n\\n");
PrintGrid(grid, gridsize);
finalSum = SumGrid(grid, gridsize);
fprintf(stdout, "\\n\\nFinal Sum: %d\\n", finalSum);
if (initSum != finalSum){
fprintf(stdout,"DATA INTEGRITY VIOLATION!!!!!\\n");
} else {
fprintf(stdout,"DATA INTEGRITY MAINTAINED!!!!!\\n");
}
fprintf(stdout, "Secs elapsed: %g\\n", difftime(end_t, start_t));
exit(0);
}
}
return(0);
}
| 0
|
#include <pthread.h>
void *function1();
void *function2();
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond;
int my_turn = 0;
int main(int argc, char* argv[])
{
int rc1, rc2;
pthread_t thread1, thread2;
pthread_cond_init(&cond, 0);
if( (rc1=pthread_create( &thread1, 0, &function1, 0)) )
{
printf("Thread creation failed: %d\\n", rc1);
}
if( (rc2=pthread_create( &thread2, 0, &function2, 0)) )
{
printf("Thread creation failed: %d\\n", rc2);
}
pthread_join( thread1, 0);
pthread_join( thread2, 0);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
exit(0);
}
void* function1(void* arg)
{
int i;
pthread_t tid;
tid = pthread_self();
printf("Thread fucntion1: thread id = 0x%04x\\n", (unsigned int)tid);
for(i = 0; i <= 100; i+=2)
{
pthread_mutex_lock(&lock);
while (my_turn != 0)
{
pthread_cond_wait(&cond, &lock);
}
printf("Thread1 for even numbers: %d\\n", i);
my_turn = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
}
}
void* function2(void)
{
int i;
pthread_t tid;
tid = pthread_self();
printf("Thread fucntion2: thread id = 0x%04x\\n", (unsigned int)tid);
for(i = 1; i < 100; i+=2)
{
pthread_mutex_lock(&lock);
while (my_turn != 1)
{
pthread_cond_wait(&cond, &lock);
}
printf("Thread2 for odd numbers: %d\\n", i);
my_turn = 0;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
}
}
| 1
|
#include <pthread.h>
extern char ** environ;
pthread_mutex_t env_mtx;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
static void thread_init()
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&env_mtx, &attr);
pthread_mutexattr_destroy(&attr);
}
int _getenv(const char *name, char *buf, int buflen)
{
int i, len, olen;
pthread_once(&init_done, thread_init);
len = strlen(name);
pthread_mutex_lock(&env_mtx);
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_mtx);
return -1;
}
strcpy(buf, &environ[i][len+1]);
pthread_mutex_unlock(&env_mtx);
return 1;
}
}
pthread_mutex_unlock(&env_mtx);
return -2;
}
int main(void)
{
char name[10] = "LANG";
char *val = malloc(30);
if(_getenv(name, val, 30) == 1)
{
printf("%s\\n", val);
}
else
{
printf("%s\\n", "error");
}
return 0;
}
| 0
|
#include <pthread.h>
struct mtx Giant;
static void
assert_mtx(struct lock_object *lock, int what)
{
mtx_assert((struct mtx *)lock, what);
}
static void
lock_mtx(struct lock_object *lock, int how)
{
mtx_lock((struct mtx *)lock);
}
static int
unlock_mtx(struct lock_object *lock)
{
struct mtx *m;
m = (struct mtx *)lock;
mtx_assert(m, MA_OWNED | MA_NOTRECURSED);
mtx_unlock(m);
return (0);
}
struct lock_class lock_class_mtx_sleep = {
.lc_name = "sleep mutex",
.lc_flags = LC_SLEEPLOCK | LC_RECURSABLE,
.lc_assert = assert_mtx,
.lc_lock = lock_mtx,
.lc_unlock = unlock_mtx,
};
struct lock_class lock_class_mtx_spin;
void
_thread_lock_flags(struct thread *td, int opts, const char *file, int line)
{
mtx_lock(td->td_lock);
}
void
mutex_init(void)
{
mtx_init(&Giant, "Giant", 0, MTX_DEF | MTX_RECURSE);
}
void
mtx_init(struct mtx *m, const char *name, const char *type, int opts)
{
pthread_mutexattr_t attr;
lock_init(&m->lock_object, &lock_class_mtx_sleep, name, type, opts);
pthread_mutexattr_init(&attr);
pthread_mutex_init(&m->mtx_lock, &attr);
}
void
mtx_destroy(struct mtx *m)
{
pthread_mutex_destroy(&m->mtx_lock);
}
void
mtx_sysinit(void *arg)
{
struct mtx_args *margs = arg;
mtx_init(margs->ma_mtx, margs->ma_desc, 0, margs->ma_opts);
}
void
_mtx_lock_flags(struct mtx *m, int opts, const char *file, int line)
{
pthread_mutex_lock(&m->mtx_lock);
}
void
_mtx_unlock_flags(struct mtx *m, int opts, const char *file, int line)
{
pthread_mutex_unlock(&m->mtx_lock);
}
int
_mtx_trylock(struct mtx *m, int opts, const char *file, int line)
{
return (pthread_mutex_trylock(&m->mtx_lock));
}
void
_mtx_lock_spin_flags(struct mtx *m, int opts, const char *file, int line)
{
pthread_mutex_lock(&m->mtx_lock);
}
void
_mtx_unlock_spin_flags(struct mtx *m, int opts, const char *file, int line)
{
pthread_mutex_unlock(&m->mtx_lock);
}
| 1
|
#include <pthread.h>
char senha[11] = "ABCDEFGhIJ\\0";
char result[11] = { '\\0' };
int index_letra = 0;
pthread_t threads[4];
pthread_barrier_t barrier;
pthread_mutex_t mutex_index_letra = PTHREAD_MUTEX_INITIALIZER;
int incrementar_index_letra(int id){
int i;
pthread_mutex_lock(&mutex_index_letra);
printf("\\tindex_letra atual: %d, chamado pela thread: %d \\n", index_letra, id);
if(index_letra < 11){
i = index_letra;
index_letra++;
}
pthread_mutex_unlock(&mutex_index_letra);
return i;
}
void* decifra(void * arg){
int i = ((int) arg)%100;
int id = ((int) arg)/100;
int teste = 32;
while(index_letra < 11){
printf("thread %d trabalhando com index %d.\\n", id, i);
for(teste = 32; teste != senha[i]; teste++);
printf("fim: teste= '%c'\\n", teste);
result[i] = teste;
i = incrementar_index_letra(id);
}
printf("thread %d na barreira...\\n", id);
pthread_barrier_wait(&barrier);
printf("thread %d finalizada.\\n", id);
pthread_exit(0);
}
int main (){
pthread_barrier_init(&barrier, 0, 4 + 1);
for(int id = 0; id < 4; id++){
pthread_mutex_lock(&mutex_index_letra);
pthread_create(&threads[id], 0, decifra, (void *) index_letra + 100*id);
printf("\\tindex_letra atual: %d, chamado pela main\\n", index_letra);
if(index_letra < 11)
index_letra++;
pthread_mutex_unlock(&mutex_index_letra);
}
pthread_barrier_wait(&barrier);
pthread_barrier_destroy(&barrier);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int thread_count;
double a, b, h;
int n, local_n;
pthread_mutex_t mutex;
double total;
double f(double x) {
double return_val;
return_val = x*x;
return return_val;
}
double Trap( double local_a, double local_b,int local_n,double h)
{
double integral;
double x;
int i;
integral = (f(local_a) + f(local_b))/2.0;
x = local_a;
for (i = 1; i <= local_n-1; i++) {
x = local_a + i*h;
integral += f(x);
}
integral = integral*h;
return integral;
}
void *Thread_work(void* rank)
{
double local_a;
double local_b;
double my_int;
long my_rank = (long) rank;
local_a = a + my_rank*local_n*h;
local_b = local_a + local_n*h;
my_int = Trap(local_a, local_b, local_n, h);
pthread_mutex_lock(&mutex);
total += my_int;
pthread_mutex_unlock(&mutex);
return 0;
}
int main(int argc, char** argv) {
long i;
pthread_t* thread_handles;
total = 0.0;
if (argc != 2) {
fprintf(stderr, "Uso: %s <numeros de threads>\\n", argv[0]);
exit(0);
}
thread_count = strtol(argv[1], 0, 10);
printf("Ingresar a, b, n\\n");
scanf("%lf %lf %d", &a, &b, &n);
h = (b-a)/n;
local_n = n/thread_count;
thread_handles = malloc (thread_count*sizeof(pthread_t));
pthread_mutex_init(&mutex, 0);
for (i = 0; i < thread_count; i++) {
pthread_create(&thread_handles[i], 0, Thread_work,
(void*) i);
}
for (i = 0; i < thread_count; i++) {
pthread_join(thread_handles[i], 0);
}
printf("Con n = %d trapecios, es\\n",n);
printf("Integral de %f a %f = %19.15e\\n",a, b, total);
pthread_mutex_destroy(&mutex);
free(thread_handles);
return 0;
}
| 1
|
#include <pthread.h>
int VT_mc13783_SU_setup(void) {
int rv = TFAIL;
rv = TPASS;
return rv;
}
int VT_mc13783_SU_cleanup(void) {
int rv = TFAIL;
rv = TPASS;
return rv;
}
int VT_mc13783_test_SU(void) {
int rv = TPASS, fd;
int event = EVENT_TSI;
fd = open(MC13783_DEVICE, O_RDWR);
if (fd < 0) {
pthread_mutex_lock(&mutex);
tst_resm(TFAIL, "Unable to open %s", MC13783_DEVICE);
pthread_mutex_unlock(&mutex);
return TFAIL;
}
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
if (VT_mc13783_subscribe(fd, event) != TPASS) {
rv = TFAIL;
}
if (VT_mc13783_unsubscribe(fd, event) != TPASS) {
rv = TFAIL;
}
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
if (VT_mc13783_subscribe(fd, event) != TPASS) {
rv = TFAIL;
}
if (VT_mc13783_subscribe(fd, event) != TPASS) {
rv = TFAIL;
}
if (VT_mc13783_unsubscribe(fd, event) != TPASS) {
rv = TFAIL;
}
if (VT_mc13783_unsubscribe(fd, event) != TPASS) {
rv = TFAIL;
}
if (close(fd) < 0) {
pthread_mutex_lock(&mutex);
tst_resm(TFAIL, "Unable to close file descriptor %d",
fd);
pthread_mutex_unlock(&mutex);
return TFAIL;
}
return rv;
}
| 0
|
#include <pthread.h>
struct job {
struct job *j_next;
struct job *j_prev;
pthread_t j_id;
};
struct queue {
struct job *q_head;
struct job *q_tail;
pthread_rwlock_t q_lock;
pthread_cond_t q_cond_lock;
pthread_mutex_t q_mutex_lock;
};
int queue_init(struct queue *qp) {
int err;
qp->q_head = 0;
qp->q_tail = 0;
err = pthread_rwlock_init(&qp->q_lock, 0);
if (err != 0)
return err;
err = pthread_cond_init(&qp->q_cond_lock, 0);
if (err != 0)
return err;
err = pthread_mutex_init(&qp->q_mutex_lock, 0);
if (err != 0)
return err;
return 0;
}
int queue_is_empty(struct queue *qp) {
return qp->q_head == 0;
}
void job_insert(struct queue *qp, struct job *jp) {
pthread_rwlock_wrlock(&qp->q_lock);
jp->j_next = qp->q_head;
jp->j_prev = 0;
if(qp->q_head != 0) {
qp->q_head->j_prev = jp;
} else
qp->q_tail = jp;
qp->q_head = jp;
pthread_rwlock_unlock(&qp->q_lock);
pthread_cond_broadcast(&qp->q_cond_lock);
}
void job_append(struct queue *qp, struct job *jp) {
pthread_rwlock_wrlock(&qp->q_lock);
jp->j_next = 0;
jp->j_prev = qp->q_tail;
if(qp->q_tail != 0) {
qp->q_tail->j_next = jp;
} else
qp->q_head = jp;
qp->q_tail = jp;
pthread_rwlock_unlock(&qp->q_lock);
pthread_cond_broadcast(&qp->q_cond_lock);
}
void job_remove(struct queue *qp, struct job *jp) {
pthread_rwlock_wrlock(&qp->q_lock);
if(jp == qp->q_head) {
qp->q_head = jp->j_next;
if(qp->q_tail == jp)
qp->q_tail = 0;
else
jp->j_next->j_prev = 0;
} else if(jp == qp->q_tail) {
qp->q_tail = jp->j_prev;
if(qp->q_head == jp)
qp->q_head = 0;
else
jp->j_prev->j_next = 0;
} else {
jp->j_prev->j_next = jp->j_next;
jp->j_next->j_prev = jp->j_prev;
}
pthread_rwlock_unlock(&qp->q_lock);
}
struct job *job_find(struct queue *qp, pthread_t id) {
struct job *jp;
if(pthread_rwlock_rdlock(&qp->q_lock) != 0)
return 0;
for(jp = qp->q_head; jp != 0; jp = jp->j_next)
if(jp->j_id == id)
break;
pthread_rwlock_unlock(&qp->q_lock);
return jp;
}
struct queue gq;
pthread_t thdarr[100];
void *thr_fn(void *arg) {
struct job *jp;
pthread_t tid = pthread_self();
for ( ; ; ) {
pthread_mutex_lock(&gq.q_mutex_lock);
while(gq.q_head == 0) {
pthread_cond_wait(&gq.q_cond_lock, &gq.q_mutex_lock);
printf("thread %ld wakes up\\n", tid);
}
pthread_mutex_unlock(&gq.q_mutex_lock);
if((jp = job_find(&gq, tid)) != 0) {
job_remove(&gq, jp);
printf("thread %ld gets job\\n", tid);
free(jp);
} else
printf("thread %ld can't find job\\n", tid);
}
return (void *)0;
}
int main(void) {
int i, err, idx;
pthread_t tid;
struct job *jp;
queue_init(&gq);
for (i = 0; i < 100; ++i) {
err = pthread_create(&tid, 0, thr_fn, 0);
if (err != 0)
err_quit("can't create thread: %s\\n", strerror(err));
thdarr[i] = tid;
printf("new thread %ld\\n", tid);
}
sleep(1);
for (i = 0; i < 20; ++i) {
if((jp = malloc(sizeof(struct job))) != 0) {
jp->j_next = 0;
jp->j_prev = 0;
idx = i % 100;
jp->j_id = thdarr[idx];
job_insert(&gq, jp);
printf("job id %ld created\\n", jp->j_id);
}
}
while(!queue_is_empty(&gq))
sleep(1);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mesa = PTHREAD_MUTEX_INITIALIZER;
sem_t sem_fumar, sem_vacio, sem_fumando;
void * agente(void *);
void * fumador(void *);
void fumar(int comp);
void setcomp();
int getcomp();
int comp[2];
int main(int argc, char** argv) {
int i;
sem_init(&sem_vacio, 0, 0);
sem_init(&sem_fumar, 0, 0);
sem_init(&sem_fumando, 0, 0);
pthread_t tid;
pthread_t tids[3];
pthread_create(&tid, 0, agente, 0);
for(i=0; i<3; ++i)
pthread_create(&tids[i], 0, fumador, (void *)i);
pthread_join(tid, 0);
for(i=0; i<3; ++i)
pthread_join(tids[i], 0);
sem_destroy(&sem_vacio);
sem_destroy(&sem_fumar);
sem_destroy(&sem_fumando);
return (0);
}
void * agente(void * args){
while(1){
pthread_mutex_lock(&mesa);
setcomp();
pthread_mutex_unlock(&mesa);
sem_post(&sem_fumar);
sem_wait(&sem_fumando);
sem_wait(&sem_vacio);
}
}
void * fumador(void * args){
int id = (int)args;
int componente;
switch(id){
case 0: printf("Fumador %d, tengo el tabaco\\n",id); break;
case 1: printf("Fumador %d, tengo el papel\\n",id); break;
case 2: printf("Fumador %d, tengo los fosforos\\n",id); break;
}
while(1){
sem_wait(&sem_fumar);
pthread_mutex_lock(&mesa);
componente=getcomp();
if(componente==id){
fumar(componente);
sem_post(&sem_fumando);
}
else{
sem_post(&sem_fumar);
}
pthread_mutex_unlock(&mesa);
sem_post(&sem_vacio);
}
}
void fumar(int comp){
switch(comp){
case 0: printf("\\nAgente ofrece papel y fosforos.\\n Fumador 0 Fumando \\n"); sleep(2); break;
case 1: printf("\\nAgente ofrece tabaco y fosforos.\\n Fumador 1 Fumando \\n"); sleep(2); break;
case 2: printf("\\nAgente ofrece tabaco y papel.\\n Fumador 2 Fumando \\n"); sleep(2); break;
}
}
void setcomp(){
int opc = rand()%3;
switch(opc){
case 0: comp[0]=0; comp[1]=1; break;
case 1: comp[0]=1; comp[1]=2; break;
case 2: comp[0]=2; comp[1]=0; break;
}
}
int getcomp(){
if(comp[0]!=0 && comp[1]!=0)
return 0;
else if(comp[0]!=1 && comp[1]!=1)
return 1;
else if(comp[0]!=2 && comp[1]!=2)
return 2;
}
| 0
|
#include <pthread.h>
char c;
short int x;
short int y;
short int step;
}Word;
int nums;
int step;
Word* ary;
pthread_cond_t mycond=PTHREAD_COND_INITIALIZER;
pthread_mutex_t mymutex1=PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mymutex2=PTHREAD_MUTEX_INITIALIZER;
void getChars(int width,Word* ary,int nums)
{
int i;
char cc;
for(i=0;i<nums;++i){
cc='!';
cc=cc+rand()%96;
ary[i].c=cc;
ary[i].y=0;
ary[i].x=1+width*(i+1);
}
}
void* changXY(void* arg)
{
Word* pary=(Word*)arg;
int mm=0;
while(mm<LINES){
pthread_mutex_lock(&mymutex1);
(*pary).y+=step;
mm+=step;
pthread_cond_signal(&mycond);
pthread_mutex_unlock(&mymutex1);
}
return 0;
}
int main()
{
initscr();
int i;
printw("Please input the number of words you want:");
scanw("%d",&nums);
printw("Plses input your speed (1-5):");
scanw("%d",&step);
int width=COLS/(nums+1);
ary=(Word*)calloc(nums,sizeof(Word));
srand(time(0));
getChars(width,ary,nums);
pthread_mutex_lock(&mymutex1);
pthread_t pid[nums];
for(i=0;i<nums;++i){
Word* pary=(ary+i);
pthread_create(&pid[i],0,changXY,(void*)pary);
}
pthread_mutex_lock(&mymutex2);
while(1){
pthread_cond_wait(&mycond,&mymutex1);
for(i=0;i<nums;++i){
mvprintw(ary[i].y,ary[i].x,"%c",ary[i].c);
refresh();
}
}
pthread_mutex_unlock(&mymutex2);
pthread_mutex_unlock(&mymutex1);
pthread_mutex_destroy(&mymutex1);
pthread_mutex_destroy(&mymutex2);
pthread_cond_destroy(&mycond);
endwin();
return 0;
}
| 1
|
#include <pthread.h>
static int s_trace_level = DEFAULT_APPLICATION_TRACE_LEVEL;
static pthread_mutex_t s_mutex = PTHREAD_MUTEX_INITIALIZER;
FILE* s_log_file = 0;
int get_trace_level()
{
return s_trace_level;
}
void set_trace_level(int level)
{
s_trace_level = level;
}
static const int MAX_PATH = 1024;
void trace_event(int event_trace_level,
int add_strerr_info,
const char* _file,
const int line,
const char * format,
...)
{
if (s_log_file == 0)
s_log_file = stdout;
va_list va_ap;
struct tm result;
int errnum = errno;
if((event_trace_level <= s_trace_level) && (s_trace_level > 0)) {
char buf[65536], color_out_buf[65536], out_buf[65536];
char theDate[32];
char *file = (char*)_file;
char extra_msg[100] = {'\\0'};
time_t theTime = time(0);
char filebuf[MAX_PATH];
const char *backslash = strrchr(_file, '/');
if(backslash != 0) {
snprintf(filebuf, sizeof(filebuf), "%s", &backslash[1]);
file = (char*)filebuf;
}
__builtin_va_start((va_ap));
pthread_mutex_lock(&s_mutex);
memset(buf, 0, sizeof(buf));
strftime(theDate, 32, "%d/%b/%Y %H:%M:%S", localtime_r(&theTime, &result));
vsnprintf(buf, sizeof(buf) - 1, format, va_ap);
if (event_trace_level == TRACE_LEVEL_ERROR) {
strcat(extra_msg, "ERROR: ");
if (add_strerr_info) {
strcat(extra_msg, "(");
strcat(extra_msg, strerror(errnum));
strcat(extra_msg, ") ");
}
} else if(event_trace_level == TRACE_LEVEL_WARNING ) {
strcat(extra_msg, "WARNING: ");
}
while(buf[strlen(buf) - 1] == '\\n') buf[strlen(buf) - 1] = '\\0';
const char *begin_color_tag = "";
switch (event_trace_level) {
case (TRACE_LEVEL_ERROR):
begin_color_tag = "\\x1b[31m";
break;
case (TRACE_LEVEL_WARNING):
begin_color_tag = "\\x1b[33m";
break;
case (TRACE_LEVEL_NORMAL):
begin_color_tag = "\\x1b[32m";
break;
case (TRACE_LEVEL_INFO):
begin_color_tag = "\\x1b[34m";
break;
case (TRACE_LEVEL_DEBUG):
begin_color_tag = "\\x1b[0m";
break;
};
const char *end_color_tag = "\\x1b[0m";
snprintf(color_out_buf, sizeof(color_out_buf), "%s%s [%s:%d]%s %s%s",
begin_color_tag, theDate, file, line, end_color_tag, extra_msg, buf);
snprintf(out_buf, sizeof(out_buf), "%s [%s:%d] %s%s", theDate, file, line, extra_msg, buf);
fprintf(s_log_file, "%s\\n", isatty(fileno(s_log_file)) ? color_out_buf : out_buf);
fflush(s_log_file);
if (s_log_file != stdout) {
printf("%s\\n", isatty(fileno(stdout)) ? color_out_buf : out_buf);
fflush(stdout);
}
;
pthread_mutex_unlock(&s_mutex);
}
}
| 0
|
#include <pthread.h>
int stack[100][10];
int size=0;
sem_t sem;
pthread_t thread[2];
pthread_mutex_t mut;
int number=1,i;
int fd;
char buf[1023]={0};
char str[1024]={0};
void *thread1()
{
while(1){
pthread_mutex_lock(&mut);
if(number>10){ pthread_mutex_unlock(&mut);break;}
sprintf(str,"%d.dat",number);
number++;
pthread_mutex_unlock(&mut);
fd=open(str,O_RDONLY);
read(fd,buf,sizeof(buf));
printf("Thread1:%s\\n",buf);
close(fd);
}
printf("thread1 :主函数在等待吗?\\n");
pthread_exit(0);
}
void *thread2()
{
while(1){
pthread_mutex_lock(&mut);
if(number>10){ pthread_mutex_unlock(&mut);break;}
sprintf(str,"%d.dat",number);
number++;
pthread_mutex_unlock(&mut);
fd=open(str,O_RDONLY);
read(fd,buf,sizeof(buf));
printf("Thread2:%s\\n",buf);
close(fd);
}
printf("thread1 :主函数在等待吗?\\n");
pthread_exit(0);
}
void thread_create(void)
{
int temp;
memset(&thread, 0, sizeof(thread));
if((temp = pthread_create(&thread[0], 0, thread1, 0)) != 0)
printf("线程1创建失败!\\n");
else
printf("线程1被创建\\n");
if((temp = pthread_create(&thread[1], 0, thread2, 0)) != 0)
printf("线程2创建失败");
else
printf("线程2被创建\\n");
}
void thread_wait(void)
{
if(thread[0] !=0)
{
pthread_join(thread[0],0);
printf("线程1已经结束\\n");
}
if(thread[1] !=0)
{
pthread_join(thread[1],0);
printf("线程2已经结束\\n");
}
}
int main()
{
pthread_mutex_init(&mut,0);
printf("主函数,正在创建线程\\n");
thread_create();
printf("主函数,正在等待线程完成任务\\n");
thread_wait();
return 0;
}
| 1
|
#include <pthread.h>
char mapper_pool[500];
char reducer_pool[5*500];
pthread_mutex_t mapper_lock=PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t reducer_lock=PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t gen_read=PTHREAD_MUTEX_INITIALIZER;
sem_t sem_write,sem_read,sem_read1,sem_write1;
sem_t sem_read2,sem_write2,sem_read3,sem_read4,sem_write3,sem_write4;
int doneReading=0,doneReading1=0;
int no_of_mapper_thread,no_of_reducer_thread,no_of_summarizer_thread;
pthread_t mapper_thread[1000];
pthread_t reducer_thread[1000];
pthread_t summarizer_thread[1000];
pthread_t write_thread,letter_thread;
pthread_t file_reader;
extern void* wordCountWriter(void *);
extern void* reducer(void *);
extern void* summarizer(void *);
extern void* write_letter(void *);
void* mapper_pool_updater(void *buf1)
{
char *buf=(char*)buf1;
FILE *fs=fopen(buf,"r");
if(!fs) {
printf("Wrong File Used ... Exiting\\n");
exit(1);
}
char buffer[500];
char ch='%',prev_char='%';
int i=0,size=0,j,i1;
while(!feof(fs)) {
j=0;i1=0;
while(ch==' '||ch=='\\n') ch=fgetc(fs);
if(prev_char=='%'){
ch=fgetc(fs);
while(ch==' '||ch=='\\n')ch=fgetc(fs);
prev_char=ch;
}
if(size<500 -1) {
buffer[i++]=ch;
size++;
}
else {
buffer[i]='\\0';
i=0;size=0;
sem_wait(&sem_read);
pthread_mutex_lock(&mapper_lock);
while(buffer[j]) {
mapper_pool[i1++]=buffer[j++];
}
mapper_pool[i1]='\\0';
pthread_mutex_unlock(&mapper_lock);
sem_post(&sem_write);
continue;
}
ch=fgetc(fs);
if(ch==' ' || ch=='\\n') {
while(ch==' '|| ch=='\\n') ch=fgetc(fs);
if(ch!=prev_char) {
buffer[i]='\\0';
i=0;size=0;
prev_char=ch;
sem_wait(&sem_read);
pthread_mutex_lock(&mapper_lock);
while(buffer[j]) {
mapper_pool[i1++]=buffer[j++];
}
mapper_pool[i1]='\\0';
pthread_mutex_unlock(&mapper_lock);
sem_post(&sem_write);
continue;
}
else {
if(size<500 -1) {
buffer[i++]=' ';
size++;
}
else {
buffer[500 -1]='\\0';
i=0;size=0;
sem_wait(&sem_read);
pthread_mutex_lock(&mapper_lock);
while(buffer[j]) {
mapper_pool[i1++]=buffer[j++];
}
mapper_pool[i1]='\\0';
pthread_mutex_unlock(&mapper_lock);
sem_post(&sem_write);
continue;
}
}
}
}
int ind;
fclose(fs);
sem_wait(&sem_read);
pthread_mutex_lock(&gen_read);
doneReading=1;
pthread_mutex_unlock(&gen_read);
sem_post(&sem_write);
}
void* mapper(void *map)
{
char buffer[500];
int done;
while(1){
int i=0,i1=0;
sem_wait(&sem_write);
sem_wait(&sem_read1);
pthread_mutex_lock(&gen_read);
done=doneReading;
if(done){
int i,ind;
doneReading1+=1;
sem_post(&sem_read);
sem_post(&sem_write1);
for(ind=0;ind<no_of_reducer_thread;++ind)
sem_post(&sem_write1);
pthread_mutex_unlock(&gen_read);
pthread_exit(0);
}
else {
pthread_mutex_unlock(&gen_read);
}
pthread_mutex_lock(&mapper_lock);
while(mapper_pool[i]) {
buffer[i1++]=mapper_pool[i];
mapper_pool[i++]=0;
}
pthread_mutex_unlock(&mapper_lock);
char *pointToCh;int size=0;
pointToCh=(char*)strtok(buffer," \\n");
pthread_mutex_lock(&reducer_lock);
while(pointToCh!=0)
{
sprintf(reducer_pool+size,"(%s,1) ",pointToCh);
size+=strlen(pointToCh)+5;
pointToCh=(char*)strtok(0," \\n");
}
pthread_mutex_unlock(&reducer_lock);
sem_post(&sem_write1);
sem_post(&sem_read);
memset(buffer,0,500);
}
peintf("Mapper Thread %lld Exited\\n");
}
void init() {
sem_init(&sem_write,0,0);
sem_init(&sem_read,0,1);
sem_init(&sem_read1,0,1);
sem_init(&sem_write1,0,0);
sem_init(&sem_write2,0,0);
sem_init(&sem_read2,0,1);
sem_init(&sem_write3,0,0);
sem_init(&sem_read3,0,0);
sem_init(&sem_write4,0,0);
sem_init(&sem_read4,0,1);
}
int main(int argc,char* argv[]){
int i,j;
char file_name[500];
if(argc<5) {
printf("Wrong Usage\\n");
exit(1);
}
init();
strcpy(file_name,argv[1]);
no_of_mapper_thread=atoi(argv[2]);
no_of_reducer_thread=atoi(argv[3]);
no_of_summarizer_thread=atoi(argv[4]);
if(no_of_mapper_thread<=0 || no_of_mapper_thread>1000 || no_of_reducer_thread<=0 || no_of_reducer_thread>1000 ||no_of_summarizer_thread>1000|| no_of_summarizer_thread<=0) {
printf("Wrong Value for number of threads\\n");
exit(1);
}
char *file_to_read=file_name;
pthread_create(&file_reader,0,mapper_pool_updater,(void*)file_to_read);
for(i=0;i<no_of_mapper_thread;++i)
pthread_create(&mapper_thread[i],0,mapper,0);
for(i=0;i<no_of_reducer_thread;++i)
pthread_create(&reducer_thread[i],0,reducer,0);
for(i=0;i<no_of_summarizer_thread;++i)
pthread_create(&summarizer_thread[i],0,summarizer,0);
pthread_create(&write_thread,0,wordCountWriter,0);
pthread_create(&letter_thread,0,write_letter,0);
pthread_join(file_reader,0);
pthread_join(write_thread,0);
pthread_join(letter_thread,0);
return 0;
}
| 0
|
#include <pthread.h>
int number;
pthread_mutex_t mu= PTHREAD_MUTEX_INITIALIZER;
sem_t full_sem;
sem_t empty_sem;
pthread_cond_t sig_consumer= PTHREAD_COND_INITIALIZER;
pthread_cond_t sig_producer= PTHREAD_COND_INITIALIZER;
void *consumer(void *dummy)
{
int printed= 0;
" now\\"\\n", pthread_self());
while (1)
{
sem_wait(&empty_sem);
pthread_mutex_lock(&mu);
number--;
pthread_mutex_unlock(&mu);
sem_post(&full_sem);
if (number == 10)
{
printf("Consumer done.. !!\\n");
break;
}
}
pthread_exit(0);
}
void *producer(void *dummy)
{
" now\\"\\n", pthread_self());
while (1)
{
sem_wait(&full_sem);
pthread_mutex_lock(&mu);
number ++;
if (number != 10)
pthread_mutex_unlock(&mu);
sem_post(&empty_sem);
if (number == 10)
{
printf("Producer done.. !!\\n");
break;
}
}
pthread_exit(0);
}
int main()
{
int rc, i;
sem_init(&full_sem,
0,
5);
sem_init(&empty_sem,
0, 0);
pthread_t t[2];
number= 0;
if ((rc= pthread_create(&t[0], 0, consumer, 0)))
printf("Error creating the 2nd consumer thread..\\n");
if ((rc= pthread_create(&t[1], 0, consumer, 0)))
printf("Error creating the 1st consumer thread..\\n");
if ((rc= pthread_create(&t[2], 0, producer, 0)))
printf("Error creating the producer thread..\\n");
if ((rc= pthread_create(&t[3], 0, producer, 0)))
printf("Error creating the producer thread..\\n");
for (i= 0; i < 2; i ++)
pthread_join(t[i], 0);
printf("Done..\\n");
pthread_mutex_destroy(&mu);
sem_destroy(&full_sem);
sem_destroy(&empty_sem);
return 0;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.