text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
struct packet
{
int clnt_sock;
char ip_addr[100];
};
void * handle_clnt(void * arg);
void send_msg(char * msg, int len);
void error_handling(char * msg);
int clnt_cnt=0;
int clnt_socks[256];
int name_size = 0;
pthread_mutex_t mutx;
int main(int argc, char *argv[])
{
int serv_sock, clnt_sock;
struct sockaddr_in serv_adr, clnt_adr;
int clnt_adr_sz;
pthread_t t_id;
data data1;
if(argc!=2) {
printf("Usage : %s <port>\\n", argv[0]);
exit(1);
}
pthread_mutex_init(&mutx, 0);
serv_sock=socket(PF_INET, SOCK_STREAM, 0);
memset(&serv_adr, 0, sizeof(serv_adr));
serv_adr.sin_family=AF_INET;
serv_adr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_adr.sin_port=htons(atoi(argv[1]));
if(bind(serv_sock, (struct sockaddr*) &serv_adr, sizeof(serv_adr))==-1)
error_handling("bind() error");
if(listen(serv_sock, 5)==-1)
error_handling("listen() error");
while(1)
{
clnt_adr_sz=sizeof(clnt_adr);
clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_adr,&clnt_adr_sz);
pthread_mutex_lock(&mutx);
clnt_socks[clnt_cnt++]=clnt_sock;
pthread_mutex_unlock(&mutx);
data1.clnt_sock = clnt_sock;
sprintf(data1.ip_addr,"%s",inet_ntoa(clnt_adr.sin_addr));
pthread_create(&t_id, 0, handle_clnt, (void*)&data1);
pthread_detach(t_id);
printf("Connected client IP: %s \\n", inet_ntoa(clnt_adr.sin_addr));
printf("Now Connecting : %d persons\\n", clnt_cnt);
}
close(serv_sock);
return 0;
}
void * handle_clnt(void * arg)
{
data data1 =* ((data*)arg);
int clnt_sock=data1.clnt_sock;
int str_len=0, i;
char msg[100];
char ip[100];
sprintf(ip,"%s",data1.ip_addr);
while((str_len=read(clnt_sock, msg, sizeof(msg)))!=0)
send_msg(msg, str_len);
pthread_mutex_lock(&mutx);
for(i=0; i<clnt_cnt; i++)
{
if(clnt_sock==clnt_socks[i])
{
while(i++<clnt_cnt-1)
clnt_socks[i]=clnt_socks[i+1];
break;
}
}
clnt_cnt--;
printf("%s is disconnected\\n", ip);
printf("Now Connecting : %d persons\\n", clnt_cnt);
pthread_mutex_unlock(&mutx);
close(clnt_sock);
return 0;
}
void send_msg(char * msg, int len)
{
int i;
pthread_mutex_lock(&mutx);
for(i=0; i<clnt_cnt; i++)
write(clnt_socks[i], msg, len);
pthread_mutex_unlock(&mutx);
}
void error_handling(char * msg)
{
fputs(msg, stderr);
fputc('\\n', stderr);
exit(1);
}
| 1
|
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER;
void *functionCount1();
void *functionCount2();
int count = 0;
main()
{
pthread_t thread1, thread2;
pthread_create( &thread1, 0, &functionCount1, 0);
pthread_create( &thread2, 0, &functionCount2, 0);
pthread_join( thread1, 0);
pthread_join( thread2, 0);
exit(0);
}
void *functionCount1()
{
for(;;)
{
pthread_mutex_lock( &condition_mutex );
while( count >= 3 && count <= 6 )
{
pthread_cond_wait( &condition_cond, &condition_mutex );
}
pthread_mutex_unlock( &condition_mutex );
pthread_mutex_lock( &count_mutex );
count++;
printf("Thread : %ld Counter value functionCount1: %d\\n",pthread_self(),count);
pthread_mutex_unlock( &count_mutex );
if(count >= 10) return(0);
}
}
void *functionCount2()
{
for(;;)
{
pthread_mutex_lock( &condition_mutex );
if( count < 3 || count > 6 )
{
pthread_cond_signal( &condition_cond );
}
pthread_mutex_unlock( &condition_mutex );
pthread_mutex_lock( &count_mutex );
count++;
printf("Thread : %ld Counter value functionCount2: %d\\n",pthread_self(),count);
pthread_mutex_unlock( &count_mutex );
if(count >= 10) return(0);
}
}
| 0
|
#include <pthread.h>
static pthread_mutex_t *lockarray;
static void lock_callback(int mode, int type, char *file, int line)
{
(void)file;
(void)line;
if (mode & CRYPTO_LOCK) {
pthread_mutex_lock(&(lockarray[type]));
} else {
pthread_mutex_unlock(&(lockarray[type]));
}
}
static unsigned long thread_id(void)
{
unsigned long ret;
ret = (unsigned long)pthread_self();
return (ret);
}
void init_locks(void)
{
int i;
lockarray = (pthread_mutex_t *)OPENSSL_malloc(CRYPTO_num_locks() *
sizeof(pthread_mutex_t));
for (i = 0; i < CRYPTO_num_locks(); i++) {
pthread_mutex_init(&(lockarray[i]), 0);
}
CRYPTO_set_id_callback((unsigned long(*)())thread_id);
CRYPTO_set_locking_callback((void (*)())lock_callback);
}
void kill_locks(void)
{
int i;
CRYPTO_set_locking_callback(0);
for (i = 0; i < CRYPTO_num_locks(); i++) {
pthread_mutex_destroy(&(lockarray[i]));
}
OPENSSL_free(lockarray);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
unsigned int seed;
long red=0,blue=0;
void* runner(void* arg)
{
double x,y;
x=(double)rand_r(&seed) / (double)32767 ;
y=(double)rand_r(&seed)/(double)32767 ;
if(sqrt((x*x)+(y*y))<=1)
{
pthread_mutex_lock(&mutex);
red++;
pthread_mutex_unlock(&mutex);
}
else
{
pthread_mutex_lock(&mutex);
blue++;
pthread_mutex_unlock(&mutex);
}
return 0;
}
int main(int argc, char *argv[])
{
if(argc!=3)
{
printf("Insufficient argument. Command must be like :(./example 1000000 4)\\n ");
return 0;
}
else
{
int numThread = atoi(argv[2]);
long iteration = atol(argv[1])/numThread;
pthread_t *threads = malloc(numThread*sizeof(pthread_t));
int i,j;
for (i = 0; i < numThread; i++)
{
for(j=0;j<iteration;j++)
{
pthread_create(&threads[i], 0, runner, 0);
}
}
for (i = 0; i < numThread; i++)
{
pthread_join(threads[i], 0);
}
pthread_mutex_destroy(&mutex);
free(threads);
double result = (double)(4*(double)red/(double)(red+blue));
printf("Pi = %lf\\n", result);
return 0;
}
}
| 0
|
#include <pthread.h>
static void monitor_callback(int pin, void* arg);
struct Piphoned_HwActions_TriggerMonitor* piphoned_hwactions_triggermonitor_new(unsigned long grace_time, int pin, void (*p_callback)(int, void*), void* p_userdata)
{
struct Piphoned_HwActions_TriggerMonitor* p_monitor = (struct Piphoned_HwActions_TriggerMonitor*) malloc(sizeof(struct Piphoned_HwActions_TriggerMonitor));
memset(p_monitor, '\\0', sizeof(struct Piphoned_HwActions_TriggerMonitor));
p_monitor->grace_time = grace_time;
p_monitor->p_callback = p_callback;
p_monitor->p_userdata = p_userdata;
p_monitor->pin = pin;
return p_monitor;
}
void piphoned_hwactions_triggermonitor_free(struct Piphoned_HwActions_TriggerMonitor* p_monitor)
{
if (p_monitor) {
syslog(LOG_DEBUG, "Stopping and freeing monitor on pin %d", p_monitor->pin);
piphoned_terminate_pin_interrupt_handler(p_monitor->pin);
free(p_monitor);
}
}
void piphoned_hwactions_triggermonitor_setup(struct Piphoned_HwActions_TriggerMonitor* p_monitor, int edgetype)
{
int pin = p_monitor->pin;
syslog(LOG_DEBUG, "Noramlizing pin state on pin %d", pin);
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
pinMode(pin, INPUT);
gettimeofday(&p_monitor->timestamp, 0);
p_monitor->microseconds_last = p_monitor->timestamp.tv_sec * 1000000 + p_monitor->timestamp.tv_usec;
syslog(LOG_DEBUG, "Registering triggermonitor callback on pin %d", pin);
if (!piphoned_handle_pin_interrupt(pin, edgetype, monitor_callback, p_monitor))
syslog(LOG_ERR, "Failed to setup trigger mointor on pin %d.", pin);
}
void monitor_callback(int pin, void* arg)
{
struct Piphoned_HwActions_TriggerMonitor* p_monitor = (struct Piphoned_HwActions_TriggerMonitor*) arg;
pthread_mutex_lock(&p_monitor->action_mutex);
gettimeofday(&p_monitor->timestamp, 0);
p_monitor->microseconds_now = p_monitor->timestamp.tv_sec * 1000000 + p_monitor->timestamp.tv_usec;
if (p_monitor->microseconds_now - p_monitor->microseconds_last <= p_monitor->grace_time)
goto unlock_mutex;
syslog(LOG_DEBUG, "Received relevant unfiltered interrupt on pin %d", pin);
p_monitor->p_callback(pin, p_monitor->p_userdata);
p_monitor->microseconds_last = p_monitor->microseconds_now;
unlock_mutex:
pthread_mutex_unlock(&p_monitor->action_mutex);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
sem_t full, empty;
buffer_item buffer[25];
int counter;
int numberToBeProduced;
int numberProduced = 0;
int runningThreads = 0;
pthread_t tid,tid0, tid1;
pthread_attr_t attr;
void *producer(void *param);
void *consumer0(void *param);
void *consumer1f(void *param);
void initializeData() {
pthread_mutex_init(&mutex, 0);
sem_init(&full, 0, 0);
sem_init(&empty, 0, 25);
pthread_attr_init(&attr);
counter = 0;
}
void *producer(void *param) {
buffer_item item;
while(1) {
sleep(1);
sem_wait(&empty);
pthread_mutex_lock(&mutex);
while(numberToBeProduced-1>=numberProduced){
item = numberProduced;
if(insert_item(item)) {
fprintf(stderr, " Producer report error condition\\n");
}
else {
printf("producer produced %d\\n", item);
}
numberProduced++;
}
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void *consumer0(void *param) {
buffer_item item;
int consID = 0;
int loopCheck = 1;
while(loopCheck ==1) {
sleep(1);
sem_wait(&full);
pthread_mutex_lock(&mutex);
if(remove_item(&item)) {
fprintf(stderr, "Consumer report error condition \\n");
printf(" the item causing the error is %d \\n",item);
}
else {
printf("ConsumerID: %d. Item: %d.\\n",consID, item);
}
if(item <= 0){
printf("ConsumerID: %d. Nothing to consume. \\n",consID);
printf("The program will exit\\n");
exit(0);
}
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
void *consumer1(void *param) {
buffer_item item;
int consID = 1;
int loopCheck = 1;
while(loopCheck ==1) {
sleep(1);
sem_wait(&full);
pthread_mutex_lock(&mutex);
if(remove_item(&item)) {
fprintf(stderr, "Consumer report error condition \\n");
printf(" the item causing the error is %d \\n",item);
}
else {
printf("Consumerid: %d. Item: %d \\n",consID, item);
}
if(item <= 0){
printf("ConsumerID: %d. Nothing to consume. \\n",consID);
printf("The program will exit\\n");
exit(0);
}
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
int insert_item(buffer_item item) {
if(counter < 25) {
buffer[counter] = item;
counter++;
return 0;
}
else {
return -1;
}
}
int remove_item(buffer_item *item) {
if(counter > 0) {
*item = buffer[(counter-1)];
counter--;
return 0;
}
else {
return -1;
}
}
int main(int argc, char *argv[]) {
int i;
numberToBeProduced = 25;
initializeData();
pthread_create(&tid,&attr,producer,0);
pthread_create(&tid0,&attr,consumer0,0);
pthread_create(&tid1,&attr,consumer1,0);
(void) pthread_join(tid0, 0);
(void) pthread_join(tid1, 0);
return(0);
}
| 0
|
#include <pthread.h>
void *row_compute();
void gauss_pthread();
int min(int a, int b){
if (a >= b){
return b;
}else{
return a;
}
}
char *ID;
int N;
int procs;
int row_count;
pthread_mutex_t row_lock;
volatile float A[5000][5000], B[5000], X[5000];
void gauss();
unsigned int time_seed() {
struct timeval t;
struct timezone tzdummy;
gettimeofday(&t, &tzdummy);
return (unsigned int)(t.tv_usec);
}
void parameters(int argc, char **argv) {
int submit = 0;
int seed = 0;
char uid[L_cuserid + 2];
if ( argc == 1 && !strcmp(argv[1], "submit") ) {
submit = 1;
N = 4;
procs = 2;
printf("\\nSubmission run for \\"%s\\".\\n", cuserid(uid));
strcpy(uid,ID);
srand(4|2[uid]&3);
}
else {
if (argc == 3) {
seed = atoi(argv[3]);
srand(seed);
printf("Random seed = %i\\n", seed);
}
else {
printf("Usage: %s <matrix_dimension> <num_procs> [random seed]\\n",
argv[0]);
printf(" %s submit\\n", argv[0]);
exit(0);
}
}
if (!submit) {
N = atoi(argv[1]);
if (N < 1 || N > 5000) {
printf("N = %i is out of range.\\n", N);
exit(0);
}
procs = atoi(argv[2]);
if (procs < 1) {
printf("Warning: Invalid number of processors = %i. Using 1.\\n", procs);
procs = 1;
}
}
printf("\\nMatrix dimension N = %i.\\n", N);
printf("Number of processors = %i.\\n", procs);
}
void initialize_inputs() {
int row, col;
printf("\\nInitializing...\\n");
for (col = 0; col < N; col++) {
for (row = 0; row < N; row++) {
A[row][col] = (float)rand() / 32768.0;
}
B[col] = (float)rand() / 32768.0;
X[col] = 0.0;
}
}
void print_inputs() {
int row, col;
if (N < 10) {
printf("\\nA =\\n\\t");
for (row = 0; row < N; row++) {
for (col = 0; col < N; col++) {
printf("%5.2f%s", A[row][col], (col < N-1) ? ", " : ";\\n\\t");
}
}
printf("\\nB = [");
for (col = 0; col < N; col++) {
printf("%5.2f%s", B[col], (col < N-1) ? "; " : "]\\n");
}
}
}
void print_X() {
int row;
if (N < 10) {
printf("\\nX = [");
for (row = 0; row < N; row++) {
printf("%5.2f%s", X[row], (row < N-1) ? "; " : "]\\n");
}
}
}
int main(int argc, char **argv) {
struct timeval etstart, etstop;
struct timezone tzdummy;
clock_t etstart2, etstop2;
unsigned long long usecstart, usecstop;
struct tms cputstart, cputstop;
ID = argv[argc-1];
argc--;
parameters(argc, argv);
initialize_inputs();
print_inputs();
printf("\\nStarting clock.\\n");
gettimeofday(&etstart, &tzdummy);
etstart2 = times(&cputstart);
pthread_mutex_init(&row_lock, 0);
gauss_pthread();
gettimeofday(&etstop, &tzdummy);
etstop2 = times(&cputstop);
printf("Stopped clock.\\n");
usecstart = (unsigned long long)etstart.tv_sec * 1000000 + etstart.tv_usec;
usecstop = (unsigned long long)etstop.tv_sec * 1000000 + etstop.tv_usec;
print_X();
printf("\\nElapsed time = %g ms.\\n",
(float)(usecstop - usecstart)/(float)1000);
pthread_mutex_destroy(&row_lock);
pthread_exit(0);
}
void *compute(void *n){
long norm = (long)n;
int row_1;
int j = 0;
float multiplier;
while(j < N){
pthread_mutex_lock(&row_lock);
j = row_count;
row_count += 100;
pthread_mutex_unlock(&row_lock);
for(row_1 = j; row_1<min(j+100, N); row_1++){
multiplier = A[row_1][norm] / A[norm][norm];
for (int col = norm; col < N; col++) {
A[row_1][col] -= A[norm][col] * multiplier;
}
B[row_1] -= B[norm] * multiplier;
}
}
}
void gauss_pthread(){
int norm, row, col;
pthread_t threads[procs];
printf("Computing in pthread!\\n");
for(norm = 0; norm < N - 1; norm++){
row_count = norm + 1;
for (int i = 0; i < procs; i++){
pthread_create(&threads[i],0,&compute,(void*)norm);
}
for (int i = 0; i < procs; i++){
pthread_join(threads[i], 0);
}
}
for (row = N - 1; row >= 0; row--) {
X[row] = B[row];
for (col = N-1; col > row; col--) {
X[row] -= A[row][col] * X[col];
}
X[row] /= A[row][row];
}
}
| 1
|
#include <pthread.h>
int n;
int n_max;
unsigned char* primes;
pthread_mutex_t index_cond_lock;
void run() {
while(1) {
pthread_mutex_lock(&index_cond_lock);
if(n > sqrt(n_max)) {
pthread_mutex_unlock(&index_cond_lock);
return;
}
int i = n;
n++;
pthread_mutex_unlock(&index_cond_lock);
if (primes[i] == 1) {
for (int j = 2; i*j <= n_max; j++) {
primes[i*j] = 0;
}
}
}
return;
}
int main (int argc, char **argv) {
if (argc > 1) {
n_max = atoi(argv[1]);
int n_threads = atoi(argv[2]);
primes = (unsigned char*)malloc(sizeof(unsigned char) * (n_max+1));
for (int i = 0; i <= n_max; i++) {
primes[i] = 1;
}
primes[0] = 0;
primes[1] = 1;
pthread_t* threads = calloc(sizeof(pthread_t), n_threads);
pthread_mutex_init(&index_cond_lock, 0);
n = 2;
for(int i = 0; i < n_threads; i++) {
if (pthread_create(&threads[i], 0, (void *) run, (void *) 0) != 0) {
printf("ERROR - pthread_created failed!\\n");
exit(0);
}
}
for(int i = 0; i < n_threads; i++) {
pthread_join(threads[i], 0);
}
} else {
printf("usage: ./e_con n t [--print]\\n"
"n: maximum number\\n"
"t: number of threads\\n");
}
if (argc > 3) {
int count = 0;
for (int i = 0; i <= n_max; i++) {
if (primes[i] == 1) {
printf("%d\\n", i);
count++;
}
}
printf("\\nThere are %d primes less than or equal to %d\\n\\n", count, n_max);
}
return 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;
while (1) {
err = sigwait(&mask, &signo);
if (err != 0) {
err_exit(err, "sigwait failed");
}
switch (signo) {
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&waitloc);
return 0;
default:
printf("unexpected signal %d\\n", signo);
exit(1);
}
}
}
int main(int argc, const char *argv[]) {
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) {
err_exit(err, "SIG_BLOCK error");
}
err = pthread_create(&tid, 0, thr_fn, 0);
if (err != 0) {
err_exit(err, "can`t create thread");
}
pthread_mutex_lock(&lock);
while (quitflag == 0) {
pthread_cond_wait(&waitloc, &lock);
}
pthread_mutex_unlock(&lock);
quitflag = 0;
if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) {
err_sys("SIG_SETMASK error");
}
exit(0);
}
| 1
|
#include <pthread.h>
extern char **environ;
pthread_mutex_t env_mutex;
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_mutex, &attr);
pthread_mutexattr_destroy(&attr);
}
int getenv_t(const char *name, char *buf, int buflen) {
int i, len, olen;
pthread_once(&init_done, thread_init);
len = strlen(name);
pthread_mutex_lock(&env_mutex);
for (i = 0; environ[i] != 0; i++) {
if ((strncmp(name, environ[i], len) == 0) &&
(environ[i][len] == '=')) {
olen = strlen(&environ[i][len+1]);
if (olen >= buflen) {
pthread_mutex_unlock(&env_mutex);
return ENOSPC;
}
strcpy(buf, &environ[i][len+1]);
pthread_mutex_unlock(&env_mutex);
return 0;
}
}
pthread_mutex_unlock(&env_mutex);
return ENOENT;
}
| 0
|
#include <pthread.h>
int main(int argc, char* argv[])
{
srand(time(0));
readConfigFile(argc, argv[0], argv[1]);
configSocket();
inicio_simulacao = time(0);
acabou = 0;
thcounter = 0;
pthread_mutex_init(&trinco_thcounter, 0);
pthread_mutex_init(&trinco_salaA, 0);
sem_init(&sem_salaA, 0, NUM_MAXIMO_USERS_SALA_A);
lugares_fila_salaA = TAMANHO_FILA_SALA_A;
pthread_mutex_init(&trinco_salaB, 0);
sem_init(&sem_vip_salaB, 0, 0);
sem_init(&sem_norm_salaB, 0, 0);
vips_espera_entrar_salaB = 0;
norm_espera_entrar_salaB = 0;
lugares_ocupados_salaB = 0;
lugares_fila_salaB = TAMANHO_FILA_SALA_B;
pthread_mutex_init(&trinco_salaC, 0);
sem_init(&sem_homem_salaC, 0, 0);
sem_init(&sem_mulher_salaC, 0, 0);
homens_espera_entrar_salaC = 0;
mulheres_espera_entrar_salaC = 0;
threadGenerator();
int i, j;
pthread_mutex_lock(&trinco_salaC);
acabou = 1;
if(mulheres_espera_entrar_salaC > 0)
{
for (i = 0; i < mulheres_espera_entrar_salaC; i++)
{
sem_post(&sem_mulher_salaC);
}
}
else
{
if(homens_espera_entrar_salaC > 0)
{
for(j = 0; j < homens_espera_entrar_salaC; j++)
{
sem_post(&sem_homem_salaC);
}
}
}
pthread_mutex_unlock(&trinco_salaC);
while(thcounter != 0)
{
usleep(1000000);
}
sendMessage(0, 0, 0, 99, 0);
printf("***FIM DA SIMULAรรO*** \\n");
pthread_mutex_destroy(&trinco_thcounter);
pthread_mutex_destroy(&trinco_salaA);
pthread_mutex_destroy(&trinco_salaB);
pthread_mutex_destroy(&trinco_salaC);
sem_destroy(&sem_salaA);
sem_destroy(&sem_vip_salaB);
sem_destroy(&sem_norm_salaB);
sem_destroy(&sem_homem_salaC);
sem_destroy(&sem_mulher_salaC);
close(sockfd);
return 0;
}
| 1
|
#include <pthread.h>
static struct net_ring_common * net_work_module_ring;
static pthread_mutex_t net_work_module_mutex;
static pthread_cond_t net_work_module_cond;
static int net_work_module_inside_parser(struct net_common_ring_node *node)
{
uint32_t ipaddr;
int n, ret = 0, len = 0;
char *pos1 = node->data.request, *pos2 = 0, *h = node->shost;
struct net_common_dnsheader *hdr = (struct net_common_dnsheader*)pos1;
if((n = ntohs(hdr->qdcount)) != 1)
{
ret = -1;
goto out;
}
if((n = ntohs(hdr->ancount)) != 0)
{
ret = -1;
goto out;
}
if((n = ntohs(hdr->nscount)) != 0)
{
ret = -1;
goto out;
}
if((n = ntohs(hdr->arcount)) > 1 )
{
ret = -1;
goto out;
}
node->iden = hdr->iden;
node->flags = &(hdr->flags);
pos2 = (char *)(hdr + 1);
if(pos2[0] <= 0)
{
ret = -1;
goto out;
}
int tmp, j;
while((tmp = *pos2) != 0)
{
pos2++;
for(j = 0; j < tmp; j++)
{
*h++ = *pos2++;
len ++;
}
if(*pos2 != 0)
{
*h++ = '.';
len ++;
}
}
pos2++;
if(NET_REQUEST_TYPE_A != ntohs(*(uint16_t *)pos2))
{
ret = -1;
goto out;
}
pos2 += 2;
node->phost = (char *)(hdr + 1);
node->host_len = len;
ipaddr = net_hashmap_core_module.search(node->shost, node->host_len);
if(ipaddr == 0)
{
net_forward_module.enqueue(node);
}
else
{
node->ipv4 = ipaddr;
net_bundle_core_module.enqueue(node);
}
out:
return ret;
}
static void *net_work_module_inside_loop(void* arg)
{
int ret;
struct net_common_ring_node *node;
pthread_detach(pthread_self());
pthread_cond_wait(&net_work_module_cond,
&net_work_module_mutex);
pthread_mutex_unlock(&net_work_module_mutex);
while(1)
{
ret = net_work_module.dequeue((void **)&node);
if(ret)
{
usleep(1000);
continue;
}
net_work_module_inside_parser(node);
}
return 0;
}
static int net_work_module_inside_loop_init(void)
{
int ret;
pthread_t loopid;
if(pthread_create(&loopid, 0, net_work_module_inside_loop, 0))
{
printf("net_work_module_inside_loop_init error in create.\\n");
ret = -1;
goto out;
}
ret = 0;
out:
return ret;
}
static int net_work_module_inside_ring_init(void)
{
int ret;
net_work_module_ring = net_ring_common_module.create(NET_WORK_RING_SIZE);
if(!net_work_module_ring)
{
ret = -1;
printf("net_ring_common_module.create.\\n");
goto out;
}
ret = 0;
out:
return ret;
}
static int net_work_module_inside_mutex_init()
{
int ret;
if(pthread_mutex_init(&net_work_module_mutex, 0) ||
pthread_cond_init(&net_work_module_cond, 0))
{
printf("net_work_module mutex init error.\\n");
ret = -1;
goto out;
}
if(pthread_mutex_lock(&net_work_module_mutex))
{
printf("net_work_module mutex lock error.\\n");
ret = -1;
goto out;
}
ret = 0;
out:
return ret;
}
static int net_work_module_init(void)
{
int ret = 0;
if(net_work_module_inside_ring_init() ||
net_work_module_inside_mutex_init() ||
net_work_module_inside_loop_init())
{
printf("net_work_module_init error .\\n");
ret = -1;
}
return ret;
}
static int net_work_module_enqueue(void *node)
{
return net_ring_common_module.enqueue(net_work_module_ring, node);
}
static int net_work_module_dequeue(void **node)
{
return net_ring_common_module.dequeue(net_work_module_ring, node);
}
static int net_work_module_run(void)
{
pthread_mutex_lock(&net_work_module_mutex);
pthread_cond_signal(&net_work_module_cond);
pthread_mutex_unlock(&net_work_module_mutex);
return 0;
}
struct net_work_module net_work_module =
{
.init = net_work_module_init,
.run = net_work_module_run,
.enqueue = net_work_module_enqueue,
.dequeue = net_work_module_dequeue,
};
| 0
|
#include <pthread.h>
static const int NUM_TASKS = 30;
static const int NUM_THREADS = 10;
static int tasks[NUM_TASKS];
static pthread_mutex_t lock;
static int next_task = 0;
static sem_t *semaphore;
void *worker(void *_unused)
{
while (1) {
int my_task;
pthread_mutex_lock(&lock);
my_task = next_task;
next_task++;
pthread_mutex_unlock(&lock);
if (my_task < NUM_TASKS) {
usleep(rand() % 20000);
tasks[my_task] = 1;
printf("Done with task %d!\\n", my_task);
sem_post(semaphore);
}
}
}
int main(int argc, char **argv)
{
pthread_t threads[NUM_THREADS];
pthread_mutex_init(&lock, 0);
semaphore = sem_open("x", O_CREAT, 0644, 0);
bzero(tasks, NUM_TASKS * sizeof(int));
srand(time(0));
for (int i = 0; i < NUM_THREADS; i++) {
pthread_create(&threads[i], 0, worker, 0);
}
for (int i = 0; i < NUM_TASKS; i++) {
sem_wait(semaphore);
}
for (int i = 0; i < NUM_TASKS; i++) {
if (tasks[i] == 0) {
printf("Uh oh, looks like task %d got skipped!\\n", i);
}
}
printf("All done!\\n");
sem_close(semaphore);
return 0;
}
| 1
|
#include <pthread.h>
int input[10]={1,2,3,4,5,6,7,8,9,10}, FIFO01[10], FIFO02[10], FIFO13[10], FIFO23[10];
int h01=0, h02=0, h13=0, h23=0,
t01=0, t02=0, t13=0, t23=0,
c01=0, c02=0, c13=0, c23=0;
pthread_mutex_t m01=PTHREAD_MUTEX_INITIALIZER,
m02=PTHREAD_MUTEX_INITIALIZER,
m13=PTHREAD_MUTEX_INITIALIZER,
m23=PTHREAD_MUTEX_INITIALIZER;
void* t0(){
for(int i=0 ; i<10 ; i++){
while(c01==10);
FIFO01[t01] = input[i];
t01 = (t01+1)%10;
pthread_mutex_lock(&m01);
c01++;
pthread_mutex_unlock(&m01);
while(c02==10);
FIFO02[i] = input[i];
t02 = (t02+1)%10;
pthread_mutex_lock(&m02);
c02++;
pthread_mutex_unlock(&m02);
}
}
void* t1(){
while(1){
int x;
while(c01==0);
x = FIFO01[h01];
h01 = (h01+1)%10;
pthread_mutex_lock(&m01);
c01--;
pthread_mutex_unlock(&m01);
while(c13==10);
FIFO13[t13] = x*x;
t13 = (t13+1)%10;
pthread_mutex_lock(&m13);
c13++;
pthread_mutex_unlock(&m13);
}
}
void* t2(){
while(1){
int x;
while(c02==0);
x = FIFO02[h02];
h02 = (h02+1)%10;
pthread_mutex_lock(&m02);
c02--;
pthread_mutex_unlock(&m02);
while(c23==10);
FIFO23[t23] = 4*x;
t23 = (t23+1)%10;
pthread_mutex_lock(&m23);
c23++;
pthread_mutex_unlock(&m23);
}
}
void* t3(){
while(1){
int x;
while(c13==0 || c23==0);
x = FIFO13[h13] + FIFO23[h23] -7;
h13 = (h13+1)%10;
h23 = (h23+1)%10;
pthread_mutex_lock(&m13);
c13--;
pthread_mutex_unlock(&m13);
pthread_mutex_lock(&m23);
c23--;
pthread_mutex_unlock(&m23);
printf("%d\\n",x);
}
}
void main(){
pthread_t t0h, t1h, t2h, t3h;
int t0r, t1r, t2r, t3r;
t0r = pthread_create(&t0h, 0, (void*)t0, 0);
if(t0r){
fprintf(stderr,"t0 was not created code %d\\n",t0r);
}
t1r = pthread_create(&t1h, 0, (void*)t1, 0);
if(t1r){
fprintf(stderr,"t1 was not created code %d\\n",t1r);
}
t2r = pthread_create(&t2h, 0, (void*)t2, 0);
if(t2r){
fprintf(stderr,"t2 was not created code %d\\n",t2r);
}
t3r = pthread_create(&t3h, 0, (void*)t3, 0);
if(t3r){
fprintf(stderr,"t3 was not created code %d",t3r);
}
pthread_join(t0h, 0);
pthread_join(t1h, 0);
pthread_join(t2h, 0);
pthread_join(t3h, 0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t chopsticks[5];
void * philosopher(void * arg)
{
int i = *((int *) arg);
if (i % 2)
{
pthread_mutex_lock (&chopsticks[i]);
sleep(1);
pthread_mutex_lock (&chopsticks[(i+1)%5]);
printf ("philosopher%d is eating.\\n", i);
sleep(3);
pthread_mutex_unlock (&chopsticks[(i+1)%5]);
sleep(1);
pthread_mutex_unlock (&chopsticks[i]);
printf ("philosopher%d is thinking.\\n", i);
sleep(3);
}
else
{
pthread_mutex_lock (&chopsticks[(i+1)%5]);
sleep(1);
pthread_mutex_lock (&chopsticks[i]);
printf ("philosopher%d is eating.\\n", i);
sleep(3);
pthread_mutex_unlock (&chopsticks[i]);
sleep(1);
pthread_mutex_unlock (&chopsticks[(i+1)%5]);
printf ("philosopher%d is thinking.\\n", i);
sleep(3);
}
}
int main ()
{
int i;
pthread_t thread[5];
int number[5];
for (i = 0; i < 5; i++)
{
number[i] = i;
pthread_create (&thread[i], 0, philosopher, &number[i]);
}
for ( i = 0; i < 5; i++)
{
pthread_join(thread[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t Lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t PiesToEat = PTHREAD_COND_INITIALIZER;
int Done[3];
int PiecesOfPie;
void * baker()
{
int i, AllDone;
while (!AllDone)
{
AllDone = 1;
for (i = 0; i < 3; i++)
AllDone = (Done[i] && AllDone);
if(AllDone)
{
printf("All Eaters are done\\n");
}
else
{
pthread_mutex_lock(&Lock);
if (PiecesOfPie == 0)
{
PiecesOfPie += 2;
printf("Baked 2 Pieces of Pie\\n");
}
pthread_cond_broadcast(&PiesToEat);
pthread_mutex_unlock(&Lock);
}
usleep(100);
}
printf("Done Baking\\n");
pthread_exit(0);
}
void * eater(void * TID)
{
long threadID = (long) TID;
int PiecesEaten = 0;
Done[threadID] = 0;
while (PiecesEaten < 2)
{
pthread_mutex_lock(&Lock);
if (PiecesOfPie == 0)
{
printf("No pieces of pie for thread %ld\\n", threadID);
pthread_cond_wait(&PiesToEat, &Lock);
printf("Thread %ld waited for baker\\n", threadID);
}
else
{
PiecesOfPie--;
PiecesEaten++;
printf("Thread %ld ate a piece of pie\\n", threadID);
}
pthread_mutex_unlock(&Lock);
usleep(1);
}
printf("Thread %ld has eaten 2 pieces of pie\\n", threadID);
Done[threadID] = 1;
pthread_exit(0);
}
int main()
{
pthread_t threads[3];
pthread_t PieBaker;
PiecesOfPie = 0;
long i;
for(i = 0; i < 3; i++)
{
pthread_create(&threads[i], 0, eater, (void *)i);
}
printf("IN MAIN: creating the baker\\n");
pthread_create(&PieBaker, 0, baker, 0);
pthread_mutex_destroy(&Lock);
pthread_join(PieBaker, 0);
printf("Done in main\\n");
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t current_column_mutex = PTHREAD_MUTEX_INITIALIZER;
static int current_column;
static int columns_per_thread;
static double step_r, step_i, min_r, max_r, min_i, max_i;
void *generator_render_part(void *);
int generator_get_next_column();
void generator_render(
double mini_r, double maxi_r, double mini_i, double maxi_i,
int threads_n, int cols_n)
{
assert(cols_n > 0);
assert(threads_n > 0);
columns_per_thread = cols_n;
current_column = -columns_per_thread;
min_r = mini_r;
max_r = maxi_r;
min_i = mini_i;
max_i = maxi_i;
step_r = (max_r - min_r) / IMAGE_WIDTH;
step_i = (max_i - min_i) / IMAGE_HEIGHT;
pthread_t threads[threads_n];
for (int i = 0; i < threads_n; i++)
pthread_create(&threads[i], 0, generator_render_part, 0);
for (int i = 0; i < threads_n; i++)
pthread_join(threads[i], 0);
pthread_mutex_destroy(¤t_column_mutex);
}
void *generator_render_part(void *param)
{
double c_r, c_i, z_r, z_new_r, z_i, z_new_i;
int k = 0, prv_current_column;
while ((prv_current_column = generator_get_next_column()) != -1)
{
pthread_mutex_unlock(¤t_column_mutex);
for (int x = columns_per_thread; x >= 0; x--)
{
if ((prv_current_column + x) >= IMAGE_WIDTH)
continue;
for (int j = 0; j < IMAGE_HEIGHT; j++)
{
c_r = min_r + (prv_current_column + x) * step_r;
c_i = min_i + j * step_i;
z_r = z_i = 0.;
k = 0;
while (k < MAX_ITER && ((z_r * z_r + z_i * z_i) < MAX_Z))
{
z_new_r = z_r * z_r - z_i * z_i + c_r;
z_new_i = 2 * z_r * z_i + c_i;
z_r = z_new_r;
z_i = z_new_i;
k++;
}
}
}
}
pthread_mutex_unlock(¤t_column_mutex);
pthread_exit(0);
}
int generator_get_next_column()
{
pthread_mutex_lock(¤t_column_mutex);
if (current_column >= IMAGE_WIDTH)
return -1;
current_column += columns_per_thread;
return current_column;
}
| 1
|
#include <pthread.h>
struct bfs_queue* bfs_queue_new(){
struct bfs_queue* bq = (struct bfs_queue*) malloc(sizeof(*bq));
bq->head = 0;
bq->tail = 0;
pthread_mutex_init(&bq->mutex, 0);
return bq;
}
int bfs_queue_destroy(struct bfs_queue **pbq){
if (0 == pbq){
perror("bpq:");
return -1;
}
struct bfs_queue* bq = *pbq;
if (0 == bq){
perror("bq:");
return -1;
}
while (bq->head != 0)
bfs_queue_pop(bq);
free(bq);
*pbq = 0;
return 0;
}
int bfs_queue_push(struct bfs_queue *bq, struct msgpk_object* obj){
if (0 == obj){
perror("obj:");
return -1;
}
struct bfs_queue_node* new_node = (struct bfs_queue_node*) malloc(sizeof(*new_node));
new_node->obj = obj;
new_node->next_node = 0;
pthread_mutex_lock(&bq->mutex);
if (0 == bq->tail){
bq->head = new_node;
bq->tail = new_node;
} else {
bq->tail->next_node = new_node;
bq->tail = new_node;
}
pthread_mutex_unlock(&bq->mutex);
return 0;
}
struct msgpk_object* bfs_queue_pop(struct bfs_queue *bq){
pthread_mutex_lock(&bq->mutex);
if (0 == bq->head){
printf("queue is empty\\n");
pthread_mutex_unlock(&bq->mutex);
return 0;
} else {
struct bfs_queue_node* node = bq->head;
bq->head = bq->head->next_node;
if (0 == bq->head)
bq->tail = 0;
pthread_mutex_unlock(&bq->mutex);
struct msgpk_object* obj = node->obj;
free(node);
return obj;
}
}
| 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) {
long my_id = (long) t;
for (int 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 unlock 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>
static int counter;
pthread_mutex_t mutex;
void incr_counter(void *p) {
do {
pthread_mutex_lock(&mutex);
counter++;
printf("%d\\n", counter);
sleep(1);
pthread_mutex_unlock(&mutex);
sleep(2);
} while ( 1 );
}
void reset_counter(void *p) {
int buf;
int num = 0;
int rc;
printf("Enter the number and press 'Enter' to initialize the counter with new value anytime.\\n");
sleep(3);
do {
if ( scanf("%d", &num)<0 )
return;
if(pthread_mutex_trylock(&mutex)!=0){
printf("Mutex is already locked by another process.\\n");
printf("Let's lock mutex using pthread_mutex_lock()\\n");
pthread_mutex_lock(&mutex);
}
counter = num;
printf("New value for counter is %d\\n", counter);
pthread_mutex_unlock(&mutex);
} while ( 1 );
}
int main(int argc, char ** argv) {
pthread_t thread_1;
pthread_t thread_2;
counter = 0;
pthread_create(&thread_1, 0, (void *)&incr_counter, 0);
pthread_create(&thread_2, 0, (void *)&reset_counter, 0);
pthread_join(thread_1,0);
pthread_join(thread_2, 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_mutex_t mutex2;
int nThreads = 4;
int **grid;
int rows, columns;
int allocate_grid() {
grid = (int**)malloc(sizeof(int*)*rows);
int i;
for (i = 0; i < rows; i++)
grid[i] = (int*)malloc(sizeof(int)*columns);
return grid;
}
void free_grid() {
int i;
for (i = 0; i < rows; i++)
free(grid[i]);
free(grid);
}
void free_newGrid(int **newgrid) {
int i;
for (i = 0; i < rows; i++)
free(newgrid[i]);
free(newgrid);
}
void convert(int size, int buf[]) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < columns; ++j) {
grid[i][j] = buf[i * (size*size) + j];
}
}
}
int check(int row, int column, int number, int**grid[rows][columns]) {
int square = (int)(sqrt(rows));
if (grid[row][column] == number) return 1;
if (grid[row][column] != 0) return 0;
for (int j = 0; j < columns; j++)
if (grid[row][j] == number) return 0;
for (int i = 0; i < rows; i++)
if (grid[i][column] == number) return 0;
int sector_row = row / square;
int sector_column = column / square;
for (int i = sector_row * square; i < (sector_row + 1) * square; ++i)
for (int j = sector_column * square; j < (sector_column + 1) * square; ++j)
if (grid[i][j] == number) return 0;
return 1;
}
void solve(int row, int column, int **newgrid) {
int static n = 0;
if (n < nThreads) {
n++;
pthread_mutex_lock(&mutex2);
int **newGrid[rows][columns];
newGrid = (int**)malloc(sizeof(int*)*rows);
for (int i = 0; i < rows; i++){
newGrid[i] = (int*)malloc(sizeof(int)*columns);
}
for (int row = 0; row < rows; row++) {
for (int column = 0; column < columns; column++) {
newGrid[row][column] = grid[row][column];
}
}
}
int* args = malloc(sizeof(int)*4);
args[0] = 0;
args[1] = 0;
args[2] = newGrid[rows][columns];
pthread_t thread;
pthread_create(&thread, 0, solve, (void*) args);
pthread_join(thread, 0);
pthread_mutex_unlock(&mutex2);
int number, attempt;
if (row == rows) {
print();
} else {
for (number = 1; number <= rows; number++) {
if (check(row, column, number, newGrid[rows][columns])) {
attempt = newgrid[row][column];
newGrid[row][column] = number;
if (column == columns - 1)
solve(row + 1, 0, newGrid[rows][columns]);
else
solve(row, column + 1, newGrid[rows][columns]);
newGrid[row][column] = attempt;
}
}
}
}
int main(int argc, char **argv) {
if (argc == 2) {
nThreads = atoi(argv[1]);
if (nThreads < 1) {
printf("Erro: Nรบmero de threads deve ser positivo.\\n");
return 0;
}
}
int size;
assert(scanf("%d", &size) == 1);
assert (size <= 8);
int buf_size = size * size * size * size;
int buf[buf_size];
for (int i = 0; i < buf_size; i++) {
if (scanf("%d", &buf[i]) != 1) {
printf("error reading file (%d)\\n", i);
exit(1);
}
}
pthread_mutex_init(&mutex, 0);
rows = size*size;
columns = size*size;
allocate_grid();
convert(size, buf);
pthread_t threads[nThreads];
free_grid();
pthread_mutex_destroy(&mutex);
pthread_mutex_destroy(&mutex2);
}
void print() {
int row, column;
static int solutions = 0;
printf("Solutions: %d\\n", ++solutions);
for (row = 0; row < rows; row++) {
for (column = 0; column < columns; column++) {
printf (" %d",grid[row][column]);
if (column % columns == (columns - 1)) printf (" ");
}
printf ("\\n");
if (row % rows == (rows - 1)) printf ("\\n");
}
}
| 1
|
#include <pthread.h>
int status = 0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void *cond_signal()
{
printf("\\nIn cond_signal function \\nThread id = %ld\\n", pthread_self());
pthread_mutex_lock(&mutex);
status = 20;
printf("Status before sending signal: %d\\n", status);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void *cond_wait()
{
size_t sz;
pthread_attr_t attr;
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
printf("\\nIn cond_wait function \\nThread id = %ld\\n", pthread_self());
status++;
printf("status after recieving signal: %d\\n", status);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void main()
{
pthread_t thread, thread1;
void *status;
size_t sz;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_getstacksize(&attr, &sz);
printf("Default stack size = %li\\n", sz);
sz = sz + 1;
pthread_attr_setstacksize (&attr, sz);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
pthread_create(&thread1, &attr, cond_signal, 0);
pthread_create(&thread, &attr, cond_wait, 0);
pthread_attr_destroy(&attr);
pthread_join(thread1, &status);
pthread_join(thread, &status);
pthread_mutex_destroy(&mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
long lButterflyBaudrate = 19200;
int iButterflyFile;
unsigned char ucButterflyDeviceName[256] = "/dev/ttyS0";
unsigned char ucButterflyDeviceOpened = 0;
unsigned char aButterflyRxBuffer[1024];
unsigned char aButterflyTxBuffer[1024];
struct sButterflyType sButterflyThread = {-1,-1,0,0,MAGIC_POSITION_NUMBER,0,0,0};
uint16_t sOldTargetPosition = MAGIC_POSITION_NUMBER;
pthread_mutex_t mButterflyMutex;
int ButterflyInit(void)
{
int iRetCode;
pthread_t ptButterflyThread;
iButterflyFile = serial_open((char*)ucButterflyDeviceName, lButterflyBaudrate);
sButterflyThread.iFD = iButterflyFile;
iRetCode = pthread_create(&ptButterflyThread, 0, (void*)&ButterflyThreadFunc,(void*) &sButterflyThread);
if(iRetCode > 0)
{
printf("In ButterflyInit: pthread_create failed!\\n\\r");
return (1);
};
return(0);
};
void ButterflyThreadFunc(void* pArgument)
{
static unsigned char ucExclamationSeen = 0;
int iBytesRead;
int iIndex;
unsigned char aStatusLine[256];
char aBuffer[256];
unsigned char *pCurrentChar;
int iStatusLineIndex = 0;
struct sButterflyType *sStructure = (struct sButterflyType *) pArgument;
pthread_mutex_init(&mButterflyMutex,0);
while(1)
{
iBytesRead = read(sStructure->iFD, aButterflyRxBuffer, 1024);
if(iBytesRead > 0)
{
pCurrentChar = aButterflyRxBuffer;
for(iIndex = 0; iIndex < iBytesRead; iIndex++)
{
if(*pCurrentChar == '!')
{
ucExclamationSeen = 1;
};
if((*pCurrentChar != '!') && (ucExclamationSeen == 1) && (iStatusLineIndex < 256))
{
aStatusLine[iStatusLineIndex++] = *pCurrentChar;
};
if((*pCurrentChar == 0x0D) && (ucExclamationSeen == 1))
{
aStatusLine[iStatusLineIndex] = 0;
ButterflyParseLine(aStatusLine, iStatusLineIndex, sStructure);
iStatusLineIndex = 0;
ucExclamationSeen = 0;
};
pCurrentChar++;
};
pCurrentChar = aButterflyRxBuffer;
};
pthread_mutex_lock(&mButterflyMutex);
volatile uint16_t sTempSetPos = sStructure->sTargetPositionSet;
pthread_mutex_unlock(&mButterflyMutex);
if(sTempSetPos != MAGIC_POSITION_NUMBER)
{
if(sTempSetPos != sOldTargetPosition)
{
int iSize = sprintf(aBuffer,"!goto %d\\r",(int)sTempSetPos);
if(write(sStructure->iFD, aBuffer, iSize) < 0)
printf("Write failed!\\n\\r");
sOldTargetPosition = sTempSetPos;
};
};
usleep(100*1000);
};
};
void ButterflyParseLine(unsigned char* aBuffer, int iLength, struct sButterflyType* sTheStructure)
{
char cTempChar;
int iTempArg[5];
if(iLength == 38)
{
sscanf((char*)aBuffer, " %c%01d %c %05d %c %05d %c 0x%04x %c 0x%02x",
&cTempChar,
&iTempArg[0],
&cTempChar,
&iTempArg[1],
&cTempChar,
&iTempArg[2],
&cTempChar,
&iTempArg[3],
&cTempChar,
&iTempArg[4]);
pthread_mutex_lock(&mButterflyMutex);
sTheStructure->ucPositionValid = (unsigned char)iTempArg[0];
sTheStructure->sCurrentPosition = (uint16_t)iTempArg[1];
sTheStructure->sTargetPositionRead = (uint16_t)iTempArg[2];
sTheStructure->sMotorControlWord = (uint16_t)iTempArg[3];
sTheStructure->ucCPUFlags = (uint8_t)iTempArg[4];
pthread_mutex_unlock(&mButterflyMutex);
};
};
| 1
|
#include <pthread.h>
static pthread_once_t g_init = PTHREAD_ONCE_INIT;
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
char const*const LCD_FILE
= "/sys/class/backlight/omap_bl/brightness";
char const*const BUTTON_FILE
= "/sys/class/leds/button-backlight/brightness";
void init_globals(void)
{
pthread_mutex_init(&g_lock, 0);
}
static int
write_int(char const* path, int value)
{
int fd;
static int already_warned = 0;
fd = open(path, O_RDWR);
if (fd >= 0) {
char buffer[20];
int bytes = sprintf(buffer, "%d\\n", value);
int amt = write(fd, buffer, bytes);
close(fd);
return amt == -1 ? -errno : 0;
} else {
if (already_warned == 0) {
ALOGE("write_int failed to open %s\\n", path);
already_warned = 1;
}
return -errno;
}
}
static int
is_lit(struct light_state_t const* state)
{
return state->color & 0x00ffffff;
}
static int
rgb_to_brightness(struct light_state_t const* state)
{
int color = state->color & 0x00ffffff;
return ((77*((color>>16)&0x00ff))
+ (150*((color>>8)&0x00ff)) + (29*(color&0x00ff))) >> 8;
}
static int
set_light_backlight(struct light_device_t* dev,
struct light_state_t const* state)
{
int err = 0;
int brightness = rgb_to_brightness(state);
pthread_mutex_lock(&g_lock);
err = write_int(LCD_FILE, brightness);
pthread_mutex_unlock(&g_lock);
return err;
}
static int
set_light_leds(struct light_state_t const *state)
{
int err = 0;
pthread_mutex_lock(&g_lock);
switch (state->flashMode) {
case LIGHT_FLASH_NONE:
err = write_int(BUTTON_FILE, 0);
break;
case LIGHT_FLASH_TIMED:
case LIGHT_FLASH_HARDWARE:
err = write_int(BUTTON_FILE, 100);
break;
default:
err = -EINVAL;
}
pthread_mutex_unlock(&g_lock);
return err;
}
static int
set_light_notification(struct light_device_t* dev,
struct light_state_t const* state)
{
ALOGI("%s: color %u fm %u is lit %u", __func__,
state->color, state->flashMode, (state->color & 0x00ffffff));
return set_light_leds(state);
}
static int
close_lights(struct light_device_t *dev)
{
if (dev) {
free(dev);
}
return 0;
}
static int open_lights(const struct hw_module_t* module, char const* name,
struct hw_device_t** device)
{
int (*set_light)(struct light_device_t* dev,
struct light_state_t const* state);
if (0 == strcmp(LIGHT_ID_BACKLIGHT, name))
set_light = set_light_backlight;
else if (0 == strcmp(LIGHT_ID_NOTIFICATIONS, name))
set_light = set_light_notification;
else
return -EINVAL;
pthread_once(&g_init, init_globals);
struct light_device_t *dev = malloc(sizeof(struct light_device_t));
memset(dev, 0, sizeof(*dev));
dev->common.tag = HARDWARE_DEVICE_TAG;
dev->common.version = 0;
dev->common.module = (struct hw_module_t*)module;
dev->common.close = (int (*)(struct hw_device_t*))close_lights;
dev->set_light = set_light;
*device = (struct hw_device_t*)dev;
return 0;
}
static struct hw_module_methods_t lights_module_methods = {
.open = open_lights,
};
struct hw_module_t HAL_MODULE_INFO_SYM = {
.tag = HARDWARE_MODULE_TAG,
.version_major = 1,
.version_minor = 0,
.id = LIGHTS_HARDWARE_MODULE_ID,
.name = "Aalto board lights module-",
.author = "Codeworkx/Dhiru1602/Sconosciuto/Androthan",
.methods = &lights_module_methods,
};
| 0
|
#include <pthread.h>
buffer_item_t data[5];
pthread_mutex_t mutex;
sem_t* full;
sem_t* empty;
int in;
int out;
} buffer_t;
buffer_t buffer;
int buffer_init()
{
memset(buffer.data, '\\0', sizeof(buffer_item_t)*5);
buffer.in = 0;
buffer.out = 0;
if((pthread_mutex_init(&buffer.mutex, 0) == -1) ||
((buffer.full = sem_open("/FULL", O_CREAT, S_IRWXU, 5)) == SEM_FAILED) ||
((buffer.empty = sem_open("/EMPTY", O_CREAT, S_IRWXU, 0)) == SEM_FAILED))
{
return -1;
}
return 0;
}
void buffer_destroy()
{
sem_close(buffer.full);
sem_unlink("/FULL");
sem_close(buffer.empty);
sem_unlink("/EMPTY");
}
int insert_item(buffer_item_t* item)
{
sem_wait(buffer.full);
pthread_mutex_lock(&buffer.mutex);
buffer.data[buffer.in] = *item;
buffer.in = (buffer.in + 1) % 5;
pthread_mutex_unlock(&buffer.mutex);
sem_post(buffer.empty);
return 0;
}
int remove_item(buffer_item_t* item)
{
sem_wait(buffer.empty);
pthread_mutex_lock(&buffer.mutex);
*item = buffer.data[buffer.out];
buffer.out = (buffer.out + 1) % 5;
pthread_mutex_unlock(&buffer.mutex);
sem_wait(buffer.full);
return 0;
}
void* producer()
{
pid_t tid = syscall(SYS_gettid);
pthread_t ptid = pthread_self();
while(1)
{
int sleepy = (rand() % 1000) + 10;
usleep(sleepy);
buffer_item_t item = rand() % 100;
if (insert_item(&item) == -1)
{
fprintf(stdout, "Producer [%d]: Failed to insert %d\\n", tid, item);
pthread_detach(ptid);
pthread_exit(0);
}
else
{
fprintf(stdout, "Producer [%d]: produced %d\\n", tid, item);
fflush(stdout);
}
}
}
void* consumer()
{
pid_t tid = syscall(SYS_gettid);
pthread_t ptid = pthread_self();
while(1)
{
int sleepy = (rand() % 90) + 10;
usleep(sleepy);
buffer_item_t item;
if (remove_item(&item) == -1)
{
fprintf(stdout, "Consumer [%d]: Failed to remove item from the buffer\\n", tid);
pthread_detach(ptid);
pthread_exit(0);
}
else
{
fprintf(stdout, "Consumer [%d]: Consumed %d\\n", tid, item);
fflush(stdout);
}
}
}
int main(int argc, char** argv)
{
char usage[] = "USAGE: prob6_40 <seconds run time> <num producers> <num consumers>";
if (argc != 4)
{
fprintf(stdout, "%s\\n", usage);
exit(1);
}
int run_time = atoi(argv[1]);
int num_producers = atoi(argv[2]);
int num_consumers = atoi(argv[3]);
int num_threads = num_producers + num_consumers;
int tid_idx = 0;
if (num_threads > 20)
{
fprintf(stderr, "%s\\n", usage);
exit(1);
}
pthread_t tid[20];
pthread_t *p_tid = tid;
pthread_attr_t tattr;
pthread_attr_init(&tattr);
if (buffer_init() == -1) {
exit(1);
}
for (int i = 0; i < num_producers; ++i)
{
int err = pthread_create(p_tid + tid_idx, &tattr, producer, 0);
if (err == 0) { ++tid_idx; }
}
for (int i = 0; i < num_consumers; ++i)
{
int err = pthread_create(p_tid + tid_idx, &tattr, consumer, 0);
if (err == 0) { ++tid_idx; }
}
sleep(run_time);
for (int i = 0; i < tid_idx; ++i)
{
pthread_cancel(p_tid[i]);
}
buffer_destroy();
return 0;
}
| 1
|
#include <pthread.h>
int gate_array[2];
int runway_array[1];
int id;
pthread_t tid;
} airplanes;
pthread_mutex_t runway_lock;
pthread_mutex_t gate_lock;
static void runway_init(int arr[1]) {
int i;
for (i = 0; i < 1; i++) {
arr[i] = 0;
}
}
static void gate_init(int arr[2]) {
int i;
for (i = 0; i < 2; i++) {
arr[i] = 0;
}
}
static void landing_function(int id) {
printf("[AC]: Flight %d requesting landing\\n", id);
pthread_mutex_lock(&runway_lock);
int i;
int stop = 0;
while (stop == 0) {
for (i = 0; i < 1; i++) {
if (runway_array[i] == 0) {
stop = 1;
runway_array[i] = id;
break;
}
}
if (stop == 1){
break;
}
}
printf("[GC]: Airplane %d assigned runway %d\\n", id, i + 1);
pthread_mutex_unlock(&runway_lock);
printf("[AC]: Airplane %d has landed\\n", id);
}
static void proceed_to_gate(int id) {
printf("[AC]: Airplane %d requesting gate\\n", id);
pthread_mutex_lock(&gate_lock);
int i, j;
int stop = 0;
while (stop == 0) {
for (i = 0; i < 2; i++) {
if (gate_array[i] == 0) {
stop = 1;
gate_array[i] = id;
break;
}
}
if (stop == 1){
break;
}
}
for (j = 0; j < 1; j++) {
if (runway_array[j] == id) {
runway_array[j] = 0;
break;
}
}
printf("[GC]: Airplane %d assigned gate %d\\n", id, i + 1);
pthread_mutex_unlock(&gate_lock);
}
static void proceed_to_hangar(int id) {
int i;
sleep(10);
printf("[AC]: Airplane %d heading to hangar\\n", id);
for (i = 0; i < 2; i++) {
if (gate_array[i] == id) {
gate_array[i] = 0;
break;
}
}
}
static void* airplane_control(void* args) {
airplanes* plane = (airplanes*)args;
landing_function(plane->id);
proceed_to_gate(plane->id);
proceed_to_hangar(plane->id);
return 0;
}
int main(int argc, char* argv[]) {
int i, status;
airplanes* planes;
runway_init(runway_array);
gate_init(gate_array);
if (pthread_mutex_init(&runway_lock, 0) != 0 || pthread_mutex_init(&gate_lock, 0) != 0)
{
printf("Mutex init failed\\n");
return 1;
}
planes = (airplanes *)calloc(3, sizeof(airplanes));
if (!planes) {
printf("Error in memory Allocation!\\n");
exit(1);
}
for (i = 0; i < 3; i++) {
planes[i].id = i + 1;
status = pthread_create(&planes[i].tid, 0, airplane_control, (void*)&planes[i]);
if (status != 0) {
printf("Error in function pthread_create()!\\n");
}
}
for (i = 0; i < 3; i++) {
pthread_join( planes[i].tid, 0);
}
(void) free(planes);
if (pthread_mutex_destroy(&runway_lock) || pthread_mutex_destroy(&gate_lock)) {
printf("Unable to destory Mutexes properly!\\n");
exit(1);
}
return 0;
}
| 0
|
#include <pthread.h>
int fragment[10];
char buf[10][1000];
int empty[10];
} Buffer;
int sock;
struct sockaddr_in echoServAddr;
struct sockaddr_in echoClntAddr;
unsigned int cliAddrLen;
char echoBuffer[1004];
unsigned short echoServPort;
int recvMsgSize;
Buffer b;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void DieWithError(char *errorMessage) {
printf("%s", errorMessage);
};
void initsocket() {
echoServPort = 2000;
if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
DieWithError("socket() failed");
memset(&echoServAddr, 0, sizeof(echoServAddr));
echoServAddr.sin_family = AF_INET;
echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY);
echoServAddr.sin_port = htons(echoServPort);
if (bind(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
DieWithError("bind() failed");
}
void *th3(void *ptr);
void *th4(void *ptr);
void AssembleFileFromPackets() {
char *x;
pthread_t thread3, thread4;
int iret3, iret4;
iret3 = pthread_create(&thread3, 0, th3, (void*) x);
iret4 = pthread_create(&thread4, 0, th4, (void*) x);
pthread_join(thread3, 0);
pthread_join(thread4, 0);
exit(0);
}
int main(int argc, char *argv[]) {
int i;
for (i = 0; i < 10; i++) {
b.fragment[i] = -1;
b.empty[i] = 0;
}
initsocket();
AssembleFileFromPackets();
close(sock);
}
void *th3(void *ptr) {
int cont1 = 1;
int i, fragnum, x, try;
char pkt[1000];
int success = 1;
int num_of_pkts = 0;
while (cont1) {
try = 0;
if (success) {
cliAddrLen = sizeof(echoClntAddr);
if ((recvMsgSize = recvfrom(sock, echoBuffer, 1004, 0,
(struct sockaddr *) &echoClntAddr, &cliAddrLen)) < 0)
DieWithError("recvfrom() failed");
fragnum = 0;
fragnum += (echoBuffer[0] & 0xFF);
fragnum += (echoBuffer[1] & 0xFF) << 8;
fragnum += (echoBuffer[2] & 0xFF) << 16;
fragnum += (echoBuffer[3] & 0xFF) << 24;
printf("%d\\n", fragnum);
for (i = 0; i < 1000; i++)
pkt[i] = echoBuffer[i + 4];
num_of_pkts++;
}
pthread_mutex_lock(&mutex);
x = 0;
while ((b.empty[x] != 0) && x < 10)
x++;
if (b.empty[x] == 0) {
success = 1;
b.empty[x] = 1;
b.fragment[x] = fragnum;
for (i = 0; i < 1000; i++)
b.buf[x][i] = pkt[i];
}
else
success = 0;
if ((success == 0) && (try < 1)) {
try++;
pthread_mutex_unlock(&mutex);
usleep(5000);
}
else if ((success == 0) && (try == 1))
success = 1;
pthread_mutex_unlock(&mutex);
if ((num_of_pkts == 10000 - 1) && (try == 1))
cont1 = 0;
}
}
void *th4(void *ptr) {
int cont2 = 1;
int i, x, min;
char s[1000];
int pos = 0;
int fragnum = 0;
time_t t1, t2;
int timer;
int fd = open("copy.txt", O_RDWR);
while (cont2) {
time(&t1);
min = 10000;
pthread_mutex_lock(&mutex);
for (i = 0; i < 10; i++) {
if ((b.empty[i] != 0) && (b.fragment[i] < min)) {
min = b.fragment[i];
x = i;
}
}
if (b.fragment[x] != -1) {
for (i = 0; i < 1000; i++)
s[i] = b.buf[x][i];
if (lseek(fd, pos, 0) >= 0) {
write(fd, s, 1000);
fragnum = b.fragment[x];
b.empty[x] = 0;
b.fragment[x] = -1;
pos += 1000;
}
else {
printf("Could not write to file");
return;
}
}
else if (b.fragment[x] == -1){
time(&t2);
timer += (int) t2-t1;
if (timer > 60) {
printf("Program timeout.");
cont2 = 0;
}
}
pthread_mutex_unlock(&mutex);
}
close(fd);
return;
}
| 1
|
#include <pthread.h>
double *a;
double *b;
double sum;
int veclen;
} DOTDATA;
DOTDATA dotstr;
pthread_t callThd[8];
pthread_mutex_t mutexsum;
void* dotprod(void* arg);
int main (int argc, char* argv[]) {
long i;
double *a, *b;
void* status;
pthread_attr_t attr;
a = (double*) malloc (8*100000*sizeof(double));
b = (double*) malloc (8*100000*sizeof(double));
for (i=0; i<100000*8; i++) {
a[i]=1;
b[i]=a[i];
}
dotstr.veclen = 100000;
dotstr.a = a;
dotstr.b = b;
dotstr.sum=0;
pthread_mutex_init(&mutexsum, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i=0;i<8;i++) {
pthread_create(&callThd[i], &attr, dotprod, (void *)i);
}
pthread_attr_destroy(&attr);
for(i=0;i<8;i++) {
pthread_join(callThd[i], &status);
}
printf ("Sum = %f \\n", dotstr.sum);
free (a);
free (b);
pthread_mutex_destroy(&mutexsum);
pthread_exit(0);
return 0;
}
void* dotprod(void* arg){
int i, start, end, len ;
long offset;
double mysum, *x, *y;
offset = (long)arg;
len = dotstr.veclen;
start = offset*len;
end = start + len;
x = dotstr.a;
y = dotstr.b;
mysum = 0;
for (i=start; i<end ; i++) {
mysum += (x[i] * y[i]);
}
pthread_mutex_lock (&mutexsum);
dotstr.sum += mysum;
printf("Thread %ld did %d to %d: mysum=%f global sum=%f\\n",offset,start,end,mysum,dotstr.sum);
pthread_mutex_unlock (&mutexsum);
pthread_exit((void*) 0);
}
| 0
|
#include <pthread.h>
int flag;
pthread_cond_t cond;
pthread_mutex_t mutex;
void initialize_flag()
{
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
flag = 0;
}
void set_thread_flag (int v)
{
pthread_mutex_lock(&mutex);
flag = v;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
void *thread_wait(void *pid)
{
int id = *(int *)pid;
while (1)
{
pthread_mutex_lock(&mutex);
if (!flag)
{
printf("thread%d wait begin\\n", id);
pthread_cond_wait(&cond, &mutex);
printf("thread%d wait end\\n", id);
}
printf("thread %d is running\\n", id);
pthread_mutex_unlock(&mutex);
}
return 0;
}
void *thread_notify()
{
sleep(3);
printf("thread notify is running\\n");
set_thread_flag(1);
return 0;
}
int a_main(int argc, char *argv[])
{
(void)argc;
(void)argv;
pthread_t wait1, wait2, notify;
int id = 1;
initialize_flag();
pthread_create(&wait1, 0, thread_wait, &id);
id = 2;
pthread_create(&wait2, 0, thread_wait, &id);
pthread_create(¬ify, 0, thread_notify, 0);
printf("main thread is running\\n");
sleep(5);
printf("end main\\n");
return 0;
}
| 1
|
#include <pthread.h>
struct player_info {
char ptype;
int duration;
};
struct thread_arguments {
int duration;
int id;
};
void * reader(void *argument);
void * writer(void *argument);
void * clock2(void *argument);
void delay(int units);
pthread_mutex_t mutexsem;
int critical = 0;
int time2 = 0;
int main()
{
FILE * pFile;
int numplayers;
struct player_info player[100];
int duration;
pthread_t threads[100];
pthread_attr_t attr[100];
struct thread_arguments threadarg[100];
pthread_t threadclock;
pthread_attr_t attrclock;
int mtime;
char cstring[100];
int i;
pFile = fopen("playerstats","r");
fscanf(pFile, "%d", &numplayers);
for (i=0; i<numplayers; i++) {
fscanf(pFile, "%s %d", cstring, &duration);
player[i].ptype = cstring[0];
player[i].duration = duration;
}
printf("\\n");
printf("Data that was loaded\\n");
printf("Number of players = %d\\n",numplayers);
for (i=0; i<numplayers; i++) {
printf("Player %d: type=%c duration=%d\\n",i,player[i].ptype,player[i].duration);
}
mtime = 40;
pthread_attr_init(&attrclock);
pthread_create(&threadclock,&attrclock,clock2, (void *) &mtime);
printf("\\nPlayers are created\\n");
for (i=0; i<numplayers; i++) {
threadarg[i].id = i;
threadarg[i].duration = player[i].duration;
pthread_attr_init(&attr[i]);
if (player[i].ptype == 'R') {
pthread_create(&threads[i],&attr[i],reader,(void *) &threadarg[i]);
}
else if (player[i].ptype == 'W') {
pthread_create(&threads[i],&attr[i],writer,(void *) &threadarg[i]);
}
delay(1);
}
for (i=0; i<numplayers; i++) {
pthread_join(threads[i], 0);
}
pthread_join(threadclock,0);
exit(0);
}
void * reader(void *arg)
{
struct thread_arguments * targ;
targ = arg;
printf("** Reader %d is created, time=%d\\n", targ->id,time2);
pthread_mutex_lock (&mutexsem);
printf("-> Reader %d enters critical section, duration=%d, time=%d\\n",targ->id,targ->duration,time2);
delay(targ->duration);
printf(" <- Reader %d exits critical section, critical = %d, time=%d\\n",targ->id, critical,time2);
pthread_mutex_unlock (&mutexsem);
pthread_exit(0);
}
void * writer(void *argument)
{
struct thread_arguments * targ;
targ = argument;
printf("** Writer %d is created, time=%d\\n", targ->id,time2);
pthread_mutex_lock (&mutexsem);
printf("-> Writer %d enters critical section, duration=%d, time=%d\\n",targ->id,targ->duration,time2);
critical++;
delay(targ->duration);
printf(" <- Writer %d exits critical section, critical = %d, time=%d\\n",targ->id, critical,time2);
pthread_mutex_unlock (&mutexsem);
pthread_exit(0);
}
void * clock2(void *argument)
{
int i;
int * mtimeptr;
int mtime;
mtimeptr = argument;
mtime = * mtimeptr;
for (i=0; i<mtime; i++) {
delay(1);
time2++;
}
pthread_exit(0);
}
void delay(int units)
{
int i;
for (i=0; i<units; i++) usleep(250000);
}
| 0
|
#include <pthread.h>
int send_port, rec_port;
char remote_address[30] = "127.0.0.1";
void* senderT(void*);
void* receiverT(void*);
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int main(int argc, char** argv)
{
if (argc != 4)
{
printf("Usage: peer <Dest address> <Dest Port> <RecPort>\\n");
exit(1);
}
strcpy(remote_address, argv[1]);
send_port = atoi(argv[2]);
rec_port = atoi(argv[3]);
int sockfd;
pthread_t sender, receiver;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(pthread_create(&receiver, 0, receiverT, (void*) &sockfd) != 0)
{
printf("Error al crear Thread Receiver\\n");
exit(1);
}
if(pthread_create(&sender, 0, senderT, (void*) &sockfd) != 0)
{
printf("Error al crear Thread Sender\\n");
exit(1);
}
pthread_join(sender, 0);
pthread_join(receiver, 0);
}
void* receiverT(void* arg){
int n, sockfd;
struct sockaddr_in recaddr;
char recline[1500];
sockfd = *((int*) arg);
recaddr.sin_family = AF_INET;htonl(INADDR_ANY);
recaddr.sin_addr.s_addr = htonl(INADDR_ANY);
recaddr.sin_port = htons(rec_port);
bind(sockfd, (struct sockaddr*) &recaddr, sizeof(recaddr));
printf("Receiver started on port: %d\\n", rec_port);
for(;;){
n = recvfrom(sockfd, recline, 1500, 0, 0, 0);
recline[n] = 0;
if(n > 0)
printf("<-- %s", recline);
}
printf("Receiver thread ended\\n");
}
void* senderT(void* arg){
int sockfd;
struct sockaddr_in servaddr;
char sendline[1500];
sockfd = *((int*) arg);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr=inet_addr(remote_address);
servaddr.sin_port=htons(send_port);
printf("Sender started on port: %d\\n", send_port);
while (fgets(sendline, 10*1500,stdin) != 0)
{
pthread_mutex_lock(&lock);
sendto(sockfd,sendline,strlen(sendline),0,(struct sockaddr *)&servaddr,sizeof(servaddr));
pthread_mutex_unlock(&lock);
printf("--> %s", sendline);
}
printf("Sender thread ended\\n");
}
| 1
|
#include <pthread.h>
int variable_global=0;
pthread_mutex_t verrou = PTHREAD_MUTEX_INITIALIZER;
struct data {
int *Tab1;
int *Tab2;
int i;
};
void * Mul(void * par){
pthread_t moi = pthread_self();
int resultat;
struct data *mon_D1 = (struct data*)par;
pthread_mutex_lock(&verrou);
resultat=(*mon_D1).Tab1[(*mon_D1).i] * (*mon_D1).Tab2[(*mon_D1).i] ;
printf("Je suis le thread %lu\\n",moi);
(*mon_D1).i++;
variable_global+=resultat;
pthread_mutex_unlock(&verrou);
pthread_exit(0);
}
int main(){
int taille=0;
printf("Entrez la taille de vos vecteurs\\n");
scanf("%i",&taille);
int *T1=malloc(sizeof(int)*taille), *T2=malloc(sizeof(int)*taille);
printf("Entrez la valeur du premier vecteur\\n");
for(int i=0;i<taille;i++){
printf("La valeur du %i-eme parametre: ",i);
scanf("%i",&T1[i]);
}
printf("Entrez la valeur du deuxieme vecteur\\n");
for(int i=0;i<taille;i++){
printf("La valeur du %i-eme parametre: ",i);
scanf("%i",&T2[i]);
}
struct data D1; D1.Tab1=T1; D1.Tab2=T2; D1.i=0;
pthread_t *TabDeThread = malloc(taille*sizeof(pthread_t));
for(int i=0;i<taille;i++){
pthread_create(&(TabDeThread[i]),0,Mul,&D1);
}
for(int i=0;i<taille;i++){
pthread_join(TabDeThread[i],0);
}
printf("La somme des vecteurs : V1(");
for(int i=0;i<taille-1;i++){
printf("%i,",T1[i]);
}
printf("%i) et V2(",T1[taille-1]);
for(int i=0;i<taille-1;i++){
printf("%i,",T2[i]);
}
printf("%i) a pour resultat : %i\\n",T2[taille-1], variable_global);
return 0;
}
| 0
|
#include <pthread.h>
int waiting_chair_count;
pthread_mutex_t barber_chair_mutex;
pthread_mutex_t hair_cut_mutex;
void * barber()
{
while(1){
pthread_mutex_lock(&hair_cut_mutex);
fprintf(stdout,"barber started cut_hair\\n");
int rd_bar = 1+rand()%2;
sleep(rd_bar);
pthread_mutex_unlock(&barber_chair_mutex);
fprintf(stdout,"barber finished cut_hair\\n");
}
}
void * customer(void* arg)
{
int cust_no = *((int*)arg);
if (waiting_chair_count>0)
{
waiting_chair_count--;
pthread_mutex_lock(&barber_chair_mutex);
waiting_chair_count++;
pthread_mutex_unlock(&hair_cut_mutex);
fprintf(stdout,"customer No.%d get_hair_cut\\n",cust_no);
}
else
{
fprintf(stdout,"customer No.%d had no waiting chair and left.\\n",cust_no);
}
return 0;
}
int main(int argc, char *argv[])
{
srand(time(0));
pthread_mutex_init(&barber_chair_mutex, 0);
pthread_mutex_init(&hair_cut_mutex, 0);
pthread_mutex_lock(&hair_cut_mutex);
int num_waiting_chairs;
int num_customers;
if( argc != 3 ) {
printf("usage: %s NUM_WAITING_CHAIRS NUM_CUSTOMERS\\n(2 integer args)\\n%s 3 20 is a good default\\n", argv[0],argv[0]);
exit(0);
}
num_waiting_chairs = atoi(argv[1]);
num_customers = atoi(argv[2]);
waiting_chair_count = num_waiting_chairs;
pthread_t thread_barber;
pthread_t thread_customers[num_customers];
int args[num_customers];
for (int i=0; i<num_customers; i++)
args[i] = i;
pthread_create(&thread_barber, 0, barber, 0);
int rd_cus = 0;
for(int i=0;i<num_customers;i=i+rd_cus)
{
rd_cus= rand()%3;
sleep(1);
if (i+rd_cus >= num_customers)
rd_cus = num_customers-i;
for (int j=1; j<=rd_cus; j++)
pthread_create(&thread_customers[i+j-1], 0, customer, (void *)&args[i+j-1]);
}
void* status;
for (int i=0; i<num_customers; i++)
pthread_join(thread_customers[i], &status);
pthread_join(thread_barber, &status);
pthread_mutex_destroy(&barber_chair_mutex);
pthread_mutex_destroy(&hair_cut_mutex);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t sumLock;
pthread_mutex_t bot;
int numWorkers;
int numArrived = 0;
int tasks = 0;
int sums = 0;
int maxInd[3] = {0, 0, 0};
int minInd[3] = {32767, 0, 0};
int size;
int bagOfTasks(){
pthread_mutex_lock(&bot);
if(tasks < size){
tasks++;
pthread_mutex_unlock(&bot);
return tasks-1;
} else{
pthread_mutex_unlock(&bot);
return -1;
}
}
void sum(int partialsum, int max, int maxI, int maxJ, int min, int minI, int minJ){
pthread_mutex_lock(&sumLock);
sums += partialsum;
if(max > maxInd[0]){
maxInd[0] = max;
maxInd[1] = maxI;
maxInd[2] = maxJ;
}
if(min < minInd[0]){
minInd[0] = min;
minInd[1] = minI;
minInd[2] = minJ;
}
pthread_mutex_unlock(&sumLock);
}
double read_timer() {
static bool initialized = 0;
static struct timeval start;
struct timeval end;
if( !initialized ){
gettimeofday( &start, 0 );
initialized = 1;
}
gettimeofday( &end, 0 );
return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec);
}
double start_time, end_time;
int matrix[10000][10000];
void *Worker(void *);
int main(int argc, char *argv[]) {
int i, j;
long l;
pthread_attr_t attr;
pthread_t workerid[10];
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
pthread_mutex_init(&sumLock, 0);
pthread_mutex_init(&bot, 0);
size = (argc > 1)? atoi(argv[1]) : 10000;
numWorkers = (argc > 2)? atoi(argv[2]) : 10;
if (size > 10000) size = 10000;
if (numWorkers > 10) numWorkers = 10;
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
matrix[i][j] = rand()%99;
}
}
start_time = read_timer();
for (l = 0; l < numWorkers; l++)
pthread_create(&workerid[l], &attr, Worker, (void *) l);
for(l; l > 0; l--)
pthread_join(workerid[l], 0);
end_time = read_timer();
printf("The maxImum element is %i with index %i %i\\n", maxInd[0], maxInd[1], maxInd[2]);
printf("The minImum element is %i with index %i %i\\n", minInd[0], minInd[1], minInd[2]);
printf("The total is %d\\n", sums);
printf("The execution time is %g sec\\n", end_time - start_time);
}
void *Worker(void *arg) {
long myid = (long) arg;
int total, j;
int maxIndex, minIndex, max, min;
int currentRow;
while(1){
currentRow = bagOfTasks();
if(currentRow == -1)
break;
total = 0;
max = 0;
min = 32767;
for (j = 0; j < size; j++){
total += matrix[currentRow][j];
if(matrix[currentRow][j] > max){
max = matrix[currentRow][j];
maxIndex = j;
}
if(matrix[currentRow][j] < min){
min = matrix[currentRow][j];
minIndex = j;
}
}
sum(total, max, currentRow, maxIndex, min, currentRow, minIndex);
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int a, b;
pthread_mutex_t mtxa = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mtxb = PTHREAD_MUTEX_INITIALIZER;
void* f(void * p)
{
char* sir = (char*)p;
for ( int i = 0; sir[i]; i++)
{
if (sir[i] == '5')
{
pthread_mutex_lock(&mtxa);
a++;
pthread_mutex_unlock(&mtxa);
}
if (sir[i] == '7')
{
pthread_mutex_lock(&mtxb);
b++;
pthread_mutex_unlock(&mtxb);
}
}
return 0;
}
int main(int argc, char** argv)
{
int i;
pthread_t * th;
th = (pthread_t *)malloc(sizeof(pthread_t) * argc);
for (i = 1; i < argc; i++)
{
pthread_create(th + i, 0, f, (void *)argv[i]);
}
for (i = 0; i < argc; ++i )
pthread_join(th[i], 0);
printf("a = %d\\nb = %d\\n", a, b);
free(th);
return 0;
}
| 1
|
#include <pthread.h>
void *Producer();
void *Consumer();
int BufferIndex=0;
char *BUFFER[10];
pthread_cond_t Buffer_Not_Full=PTHREAD_COND_INITIALIZER;
pthread_cond_t Buffer_Not_Empty=PTHREAD_COND_INITIALIZER;
pthread_mutex_t mVar=PTHREAD_MUTEX_INITIALIZER;
int main()
{
pthread_t ptid,ctid;
pthread_create(&ptid,0,Producer,0);
pthread_create(&ctid,0,Consumer,0);
pthread_join(ptid,0);
pthread_join(ctid,0);
return 0;
}
void *Producer()
{
for(;;)
{
pthread_mutex_lock(&mVar);
if(BufferIndex==10)
{
pthread_cond_wait(&Buffer_Not_Full,&mVar);
}
BUFFER[BufferIndex++]='@';
printf("Produce : %d \\n",BufferIndex);
pthread_mutex_unlock(&mVar);
pthread_cond_signal(&Buffer_Not_Empty);
}
}
void *Consumer()
{
for(;;)
{
pthread_mutex_lock(&mVar);
if(BufferIndex==-1)
{
pthread_cond_wait(&Buffer_Not_Empty,&mVar);
}
printf("Consume : %d \\n",BufferIndex--);
pthread_mutex_unlock(&mVar);
pthread_cond_signal(&Buffer_Not_Full);
}
}
| 0
|
#include <pthread.h>
struct {
int nused;
int next_write;
int next_read;
int data[10];
} buf = {0, 0, 0, {0}};
pthread_cond_t prKey = PTHREAD_COND_INITIALIZER;
pthread_cond_t coKey = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* produce(void* arg) {
int item = 0;
int id = (int)(uintptr_t) arg;
while(1) {
pthread_mutex_lock(&mutex);
while(buf.nused == 10) {
pthread_cond_wait(&prKey, &mutex);
printf("producer in the buffer\\n");
}
buf.nused++;
buf.data[buf.next_write] = item;
item++;
printf("P%d: %d --> [%d] thread used: %d\\n", id, buf.data[buf.next_write], buf.next_write, buf.nused);
buf.next_write = (buf.next_write + 1) % 10;
pthread_cond_signal(&coKey);
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_exit(0);
}
void* consume(void* arg) {
int i;
int id = (int)(uintptr_t) arg;
while(1) {
pthread_mutex_lock(&mutex);
while(buf.nused == 0) {
pthread_cond_wait(&coKey, &mutex);
printf("consumer wait");
}
buf.nused--;
i = buf.next_read;
printf("C%d: %d <-- [%d] thread used: %d\\n", id, buf.data[i], i, buf.nused);
buf.next_read = (buf.next_read+1) % 10;
pthread_cond_signal(&prKey);
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_exit(0);
}
int main(void) {
pthread_t pid1, pid2, pid3, pid4;
pthread_create(&pid1, 0, produce, (void*) 0);
pthread_create(&pid2, 0, produce, (void*) 1);
pthread_create(&pid3, 0, consume, (void*) 0);
pthread_create(&pid4, 0, consume, (void*) 1);
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
int ring[64];
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
sem_t blank_sem;
sem_t data_sem;
void* product(void *arg)
{
int data = 0;
static int step = 0;
while(1)
{
pthread_mutex_lock(&lock1);
int data = rand()%1234;
sem_wait(&blank_sem);
ring[step] = data;
sem_post(&data_sem);
printf("The product done: %d\\n", data);
step++;
step %= 64;
pthread_mutex_unlock(&lock1);
sleep(2);
}
}
void* consume(void *arg)
{
static int step = 0;
while(1)
{
pthread_mutex_lock(&lock2);
int data = -1;
sem_wait(&data_sem);
data = ring[step];
sem_post(&blank_sem);
printf("The consume done: %d\\n", data);
step++;
step %= 64;
pthread_mutex_unlock(&lock2);
sleep(2);
}
}
int main()
{
pthread_t p[3];
pthread_t c[3];
int i = 0;
for(i = 0; i < 3; i++)
{
pthread_create(&p[i], 0, product, 0);
}
for(i = 0; i < 3; i++)
{
pthread_create(&c[i], 0, consume, 0);
}
sem_init(&blank_sem, 0, 64);
sem_init(&data_sem, 0, 0);
for(i = 0; i < 3; i++)
{
pthread_join(p[i], 0);
}
for(i = 0; i < 3; i++)
{
pthread_join(c[i], 0);
}
sem_destroy(&blank_sem);
sem_destroy(&data_sem);
pthread_mutex_destroy(&lock1);
pthread_mutex_destroy(&lock2);
return 0;
}
| 0
|
#include <pthread.h>
long double pi = 0.0;
pthread_mutex_t Locked;
long double intervals;
int numThreads;
double numiter;
void *calculPI(void *id)
{
unsigned int seed=time(0);
double z,x,y,localSum=0;
int i,count=0;
srand(time(0));
for(i = 0 ; i < numiter; i ++) {
x = ( double)rand_r(&seed)/32767;
y = ( double)rand_r(&seed)/32767;
z = x*x+y*y;
if (z<=1) count++;
}
pthread_mutex_lock(&Locked);
pi = (double)(count)/numiter*4;
pthread_mutex_unlock(&Locked);
return 0;
}
int main(int argc, char **argv)
{
pthread_t *threads;
int i;
if (argc == 3) {
intervals = atol(argv[1]);
numThreads = atoi(argv[2]);
threads = malloc(numThreads*sizeof(pthread_t));
pthread_mutex_init(&Locked, 0);
numiter = intervals/numThreads;
for (i = 0; i < numThreads; i++) {
pthread_create(&threads[i], 0, calculPI,0);
}
for (i = 0; i < numThreads; i++) {
pthread_join(threads[i], 0);
}
printf("Hesaplanan pi sayฤฑsฤฑ : %32.30Lf \\n", pi);
printf("Pi sayฤฑsฤฑnฤฑn deฤeri : 3.141592653589793238462643383279...\\n");
}
else {
printf("รALIลTIRMA ลEKLฤฐ: ./pi <numIntervals> <numThreads>");
}
return 0;
}
| 1
|
#include <pthread.h>
int capacity, prod_threads, cons_threads, producer_loops, consumer_loops, avg1, avg2;
int *buffer;
int buffer_index;
pthread_mutex_t buffer_mutex;
sem_t full;
sem_t empty;
int ex(int a)
{
int var = (-1)*((rand() % 10) + 1)/a;
int x = 100* (exp(var));
x = x/a;
return x;
}
void insertItem(int item)
{
if (buffer_index < capacity)
{
buffer[buffer_index++] = item;
}
else
{
printf("Buffer overflow\\n");
}
}
int removeItem()
{
if (buffer_index > 0)
{
return buffer[--buffer_index];
}
else
{
printf("Buffer underflow\\n");
}
return 0;
}
long long total_prod = 0;
struct timeval timevar;
void *producer(void *param)
{
struct tm *prodTime;
gettimeofday(&timevar, 0);
long long t1 = timevar.tv_usec;
int item, pro_thr_num, i;
pro_thr_num = *(int *)param;
for(i=0; i<producer_loops; i++)
{
item = rand() % 100;
pthread_mutex_lock(&buffer_mutex);
do {
pthread_mutex_unlock(&buffer_mutex);
sem_wait(&full);
pthread_mutex_lock(&buffer_mutex);
} while (buffer_index == capacity);
insertItem(item);
time_t current;
time(¤t);
prodTime = localtime(¤t);
pthread_mutex_unlock(&buffer_mutex);
sem_post(&empty);
printf("%dth item produced by thread %d at %s into buffer location %d, item is %d\\n", i, pro_thr_num, asctime(prodTime), buffer_index, item);
sleep(ex(avg1));
}
gettimeofday(&timevar, 0);
long long t2 = timevar.tv_usec;
total_prod += (t2-t1)/producer_loops;
pthread_exit(0);
}
long long total_cons = 0;
void *consumer(void *param)
{
struct tm *consTime;
gettimeofday(&timevar, 0);
long long t1 = timevar.tv_usec;
int item, cons_thr_num, i;
cons_thr_num = *(int *)param;
for(i=0; i<consumer_loops; i++)
{
pthread_mutex_lock(&buffer_mutex);
do
{
pthread_mutex_unlock(&buffer_mutex);
sem_wait(&empty);
pthread_mutex_lock(&buffer_mutex);
} while (buffer_index == 0);
item = removeItem(item);
time_t current;
time(¤t);
consTime = localtime(¤t);
pthread_mutex_unlock(&buffer_mutex);
sem_post(&full);
printf("%dth item read from buffer by thread %d at %s from buffer location %d, item is %d\\n", i, cons_thr_num, asctime(consTime), buffer_index, item);
sleep(ex(avg2));
}
gettimeofday(&timevar, 0);
long long t2 = timevar.tv_usec;
total_cons += (t2-t1)/consumer_loops;
pthread_exit(0);
}
int main(int argc, char *argv[])
{
buffer_index = 0;
FILE *fp;
fp = fopen("input.txt", "r");
if(fp == 0)
{
printf("error in opening the file\\n");
exit(-1);
}
fscanf(fp, "%d %d %d %d %d %d %d", &capacity, &prod_threads, &producer_loops, &cons_threads, &consumer_loops, &avg1, &avg2);
buffer = malloc(capacity * sizeof(int));
pthread_mutex_init(&buffer_mutex, 0);
sem_init(&full, 0, capacity);
sem_init(&empty, 0, 0);
pthread_t prod_thread[prod_threads];
pthread_t cons_thread[cons_threads];
int prod_thr_num[prod_threads];
int cons_thr_num[cons_threads];
int i;
for(i=0; i<prod_threads; i++)
{
prod_thr_num[i] = i;
pthread_create(&prod_thread[i], 0, producer, &prod_thr_num[i]);
}
for(i=0; i<cons_threads; i++)
{
cons_thr_num[i] = i;
pthread_create(&cons_thread[i], 0, consumer, &cons_thr_num[i]);
}
for (i = 0; i < prod_threads; i++)
pthread_join(prod_thread[i], 0);
for(i=0; i<cons_threads; i++)
pthread_join(cons_thread[i], 0);
pthread_mutex_destroy(&buffer_mutex);
sem_destroy(&full);
sem_destroy(&empty);
printf("avg time taken by producer thread is %lld usec\\n", total_prod/(prod_threads));
printf("avg time taken by consumer thread is %lld usec\\n", total_cons/(cons_threads));
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mu;
pthread_cond_t registerSignal;
key_t shmkey;
int shmid;
sem_t *sem;
int nXray = 3;
int toTreat = 0, nTreated = 0, size = 0, dep_no = 0;
int **treatTimes;
void fileOP(const char* inputFile) {
int num, num2, i, j;
FILE* file = fopen(inputFile, "r");
while (!feof(file)) {
fscanf(file, "%d %d", &num, &num);
size++;
}
fclose(file);
treatTimes = malloc(size * sizeof(int*));
for (i = 0; i < size; i++) {
treatTimes[i] = malloc(2 * sizeof(int));
}
file = fopen(inputFile, "r");
for (i = 0; i < size; i++)
fscanf(file, "%d %d", &treatTimes[i][0], &treatTimes[i][1]);
fclose(file);
}
void* nurse(void *ptr) {
int i;
for (i = 0; i < size; i++) {
sleep(2);
pthread_mutex_lock(&mu);
printf("Department no: %d Nurse: Patient %d registered \\n", dep_no,
i + 1);
toTreat++;
pthread_cond_signal(®isterSignal);
pthread_mutex_unlock(&mu);
}
pthread_cond_signal(®isterSignal);
pthread_exit(0);
}
void* doctor(int dNo) {
while (1) {
pthread_mutex_lock(&mu);
while (toTreat <= 0 && nTreated < size)
pthread_cond_wait(®isterSignal, &mu);
int tmp = nTreated;
toTreat--;
nTreated++;
pthread_mutex_unlock(&mu);
if (tmp < size) {
sleep(treatTimes[tmp][0]);
pthread_mutex_lock(&mu);
if (!treatTimes[tmp][1])
printf("Department no: %d Doctor %d: Patient %d treated \\n",
dep_no, dNo, tmp + 1);
pthread_mutex_unlock(&mu);
if (treatTimes[tmp][1]){
sem_wait(sem);
sleep(2);
pthread_mutex_lock(&mu);
printf(
"Department no: %d Doctor %d: Patient %d treated (X-Ray taken)\\n",
dep_no, dNo, tmp + 1);
pthread_mutex_unlock(&mu);
sem_post(sem);
}
}
if (nTreated >= size)
break;
}
pthread_exit(0);
}
int main(int argc, char **argv) {
int i, f;
shmkey = ftok("/dev/null", 5);
shmid = shmget(shmkey, sizeof(int), 0644 | IPC_CREAT);
if (shmid < 0) {
perror("shmget\\n");
exit(1);
}
sem = sem_open("pSem", O_CREAT | O_EXCL, 0644, nXray);
sem_unlink("pSem");
for (i = 0; i < argc-1; i++) {
f = fork();
if (f == 0) {
dep_no = i + 1;
break;
} else if (f == -1) {
printf("Fork error! Restart the program");
return 0;
}
}
if (f == 0) {
pthread_t nurse_t, doc1_t, doc2_t;
pthread_mutex_init(&mu, 0);
pthread_cond_init(®isterSignal, 0);
fileOP(argv[dep_no]);
pthread_create(&nurse_t, 0, nurse, 0);
pthread_create(&doc1_t, 0, doctor, 1);
pthread_create(&doc2_t, 0, doctor, 2);
pthread_join(doc1_t, 0);
pthread_join(doc2_t, 0);
pthread_join(nurse_t, 0);
pthread_mutex_destroy(&mu);
pthread_cond_destroy(®isterSignal);
free(treatTimes);
} else {
wait(0);
shmctl(shmid, IPC_RMID, 0);
sem_destroy(sem);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t stack_mutex;
struct timeval tm1, tm2;
void start()
{
gettimeofday(&tm1, 0);
}
void stop()
{
gettimeofday(&tm2, 0);
unsigned long long t = ((tm2.tv_sec - tm1.tv_sec) * 1000000)
+ (tm2.tv_usec - tm1.tv_usec);
printf("\\n%llu microseconds occured\\n",t);
}
double *stackElements;
int size;
long long StackCount=0;
struct timeval tm1, tm2;
struct stack {
double *s;
int top;
} st;
void pop() {
if(st.top == 0)
{
}
else
{
pthread_mutex_lock(&stack_mutex);
st.top--;
StackCount--;
pthread_mutex_unlock(&stack_mutex);
}
}
int push(double number)
{
if(st.top==size-1)
{
st.s[st.top] = number;
}
else
{
pthread_mutex_lock(&stack_mutex);
st.s[st.top] = number;
st.top++;
StackCount++;
pthread_mutex_unlock(&stack_mutex);
}
return number;
}
long long GetStackCount()
{
return StackCount;
}
void *push_pop(void *t)
{
int i,x,k,i1;
long tid = (long) t;
int lines = size/100;
int start = tid*lines;
int stop = start+lines-1;
st.s = malloc(size * sizeof(double));
for(i1=0;i1<size;i1++)
{
st.s[i1] = (uintptr_t)malloc(size * sizeof(double));
}
for(i=0;i<size;i++)
{
push(stackElements[i]);
GetStackCount();
}
for(k=size-1;k>=0;k--)
{
pop();
GetStackCount();
}
pthread_exit(0);
}
void main()
{
start();
FILE* fp = fopen("numbers.txt", "r");
st.top=0;
int number=5;
char * read_line;
int i,j=0;
int x=0,y=0,z=0;
size_t count=0;
int p=0,q=0;
char * token=0,line[1000000];
char comma[2];
int k=0 ,i1=0,p1=0;
long t;
pthread_t threads[100];
int rc;
if(fp == 0)
{
printf("Error in file reading\\n");
}
for (i=0;getline(&read_line, &count, fp)!= -1;i++)
{
sprintf(line, "%s", read_line);
if(i == 0)
{
size = atoi(read_line);
stackElements = malloc(size * sizeof(double));
for(i1=0;i1<size;i1++)
{
stackElements[i1] = (uintptr_t)malloc(size * sizeof(double));
}
}
else
{
token = strtok(line, ",");
j = 0;
stackElements[(i-1)*size + (j)] = 0;
while( token != 0 )
{
stackElements[(i-1)*size + (j)] = atof(token);
j++;
token = strtok(0, ",");
}
}
}
for(t=0;t<100;t++)
{
rc = pthread_create(&threads[t],0,push_pop,(void *)t);
if(rc)
{
printf("ERROR; return code from pthread_create() is %d\\n",rc);
exit(-1);
}
}
for(i=0;i<100;i++)
{
rc = pthread_join(threads[i], 0);
if(rc)
{
printf("\\n Error occured in pthread_join %d",rc);
}
}
stop();
pthread_exit(0);
}
| 0
|
#include <pthread.h>
void bag_of_tasks(int*, int*);
int find_word(const char*);
char *strrev(char *);
void write_output_buffer(const char*);
void increment_sum(void);
int *words, numWords, sum = 0, current_task = 0, outBuffer_offset =0;
char *inBuffer, *outBuffer;
FILE *outFile;
pthread_mutex_t write_lock, sum_lock, bag_lock;
char *strrev(char *str) {
char *p1, *p2;
if (! str || ! *str)
return str;
for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2) {
*p1 ^= *p2;
*p2 ^= *p1;
*p1 ^= *p2;
}
return str;
}
double read_timer() {
static bool initialized = 0;
static struct timeval start;
struct timeval end;
if( !initialized )
{
gettimeofday( &start, 0 );
initialized = 1;
}
gettimeofday( &end, 0 );
return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec);
}
void write_output_buffer(const char *p) {
pthread_mutex_lock(&write_lock);
strcpy(outBuffer + outBuffer_offset, p);
outBuffer_offset+=strlen(p);
outBuffer[outBuffer_offset++] = '\\n';
pthread_mutex_unlock(&write_lock);
}
void increment_sum() {
pthread_mutex_lock(&sum_lock);
sum++;
pthread_mutex_unlock(&sum_lock);
}
void bag_of_tasks(int *start, int *end) {
pthread_mutex_lock(&bag_lock);
if(current_task==numWords) *start = -1;
else {
*start = current_task;
*end = (current_task + 100 -1 > numWords -1) ? numWords -1 : current_task + 100 -1;
current_task = *end + 1;
}
pthread_mutex_unlock(&bag_lock);
}
int find_word(const char *w) {
int i;
for(i = 0; i < numWords; i++)
if(!strcasecmp(w, inBuffer + words[i])) return i;
return -1;
}
void worker(void *arg) {
int start=0, end, myPalindromes=0;
long myid = (long) arg;
char wordBuffer[30];
while(1) {
bag_of_tasks(&start,&end);
if(start==-1) break;
while(start<=end) {
strcpy(wordBuffer, inBuffer + words[start]);
strrev(wordBuffer);
if( -1 != find_word(wordBuffer) ) {
increment_sum();
myPalindromes++;
write_output_buffer(inBuffer + words[start]);
}
start++;
}
}
printf("Thread with ID %lu found %d palindromes\\n", myid, myPalindromes);
}
int main(int argc, char *argv[]) {
FILE *inFile;
long numBytes, l;
double start_time, end_time;
int i, j, wordstart;
pthread_attr_t attr;
pthread_t workerid[20];
inFile = fopen("words","r");
if(!inFile) {
fprintf(stderr, "Could not open file \\"words\\"\\n");
exit(1);
}
outFile = fopen("output", "w");
fseek(inFile, 0L, 2);
numBytes = ftell(inFile);
fseek(inFile, 0L, 0);
inBuffer = (char*)calloc(numBytes, sizeof(char));
outBuffer = (char*)calloc(numBytes, sizeof(char));
fread(inBuffer, sizeof(char), numBytes, inFile);
fclose(inFile);
for(i=0, numWords=0; i < numBytes; i++)
if('\\n'==inBuffer[i])
numWords++;
words = malloc(sizeof(int) * numWords);
for(i = 0, j=0, wordstart=0; i < numBytes; i++)
if(inBuffer[i]=='\\n') {
inBuffer[i]='\\0';
words[j++] = wordstart;
wordstart = i+1;
}
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
pthread_mutex_init(&bag_lock, 0);
pthread_mutex_init(&write_lock, 0);
pthread_mutex_init(&sum_lock, 0);
start_time = read_timer();
for (l = 0; l < 20; l++)
pthread_create(&workerid[l], &attr, (void *)&worker, (void *) l);
for (l = 0; l < 20; l++)
pthread_join(workerid[l], 0);
end_time = read_timer();
outBuffer[outBuffer_offset]='\\0';
fprintf(outFile, "%s", (const char *)outBuffer);
fclose(outFile); free(inBuffer); free(outBuffer); free(words);
printf("A total number of %d palindromes found by %d threads!\\n",sum, 20);
printf("The execution time was %g sec\\n", end_time - start_time);
}
| 1
|
#include <pthread.h>
pthread_mutex_t forks[5];
pthread_t phils[5];
void *philosopher (void *id);
int food_on_table ();
void get_fork (int, int, char *);
void down_forks (int, int);
pthread_mutex_t foodlock;
int sleep_seconds = 0;
int
main (int argn,
char **argv)
{
int i;
if (argn == 2)
sleep_seconds = atoi (argv[1]);
pthread_mutex_init (&foodlock, 0);
for (i = 0; i < 5; i++)
pthread_mutex_init (&forks[i], 0);
for (i = 0; i < 5; i++)
pthread_create (&phils[i], 0, philosopher, (void *)i);
for (i = 0; i < 5; i++)
pthread_join (phils[i], 0);
return 0;
}
void *
philosopher (void *num)
{
int id;
int left_fork, right_fork, f;
id = (int)num;
printf ("Philosopher %d sitting down to dinner.\\n", id);
right_fork = id;
left_fork = id + 1;
if (left_fork == 5)
left_fork = 0;
while (f = food_on_table ()) {
if (id == 1)
sleep (sleep_seconds);
printf ("Philosopher %d: get dish %d.\\n", id, f);
get_fork (id, right_fork, "right");
get_fork (id, left_fork, "left ");
printf ("Philosopher %d: eating.\\n", id);
usleep (30000 * (50 - f + 1));
down_forks (left_fork, right_fork);
}
printf ("Philosopher %d is done eating.\\n", id);
return (0);
}
int
food_on_table ()
{
static int food = 50;
int myfood;
pthread_mutex_lock (&foodlock);
if (food > 0) {
food--;
}
myfood = food;
pthread_mutex_unlock (&foodlock);
return myfood;
}
void
get_fork (int phil,
int fork,
char *hand)
{
pthread_mutex_lock (&forks[fork]);
printf ("Philosopher %d: got %s fork %d\\n", phil, hand, fork);
}
void
down_forks (int f1,
int f2)
{
pthread_mutex_unlock (&forks[f1]);
pthread_mutex_unlock (&forks[f2]);
}
| 0
|
#include <pthread.h>
int const MAX=5;
int buffer[MAX];
int fill = 0;
int use =0;
int loops = 10;
sem_t *items;
sem_t *slots;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
void put(int value){
sem_wait(slots);
pthread_mutex_lock(&mut);
printf("fill buffer %d with %d by thread %ld\\n",fill,value,(long)pthread_self());
buffer[fill] = value;
fill= (fill+1)%MAX;
pthread_mutex_unlock(&mut);
sem_post(items);
}
int get(){
sem_wait(items);
pthread_mutex_lock(&mut);
int tmp = buffer[use];
printf("Access get by Thread %ld with index %d\\n",(long)pthread_self(),use);
use = (use+1)%MAX;
pthread_mutex_unlock(&mut);
sem_post(slots);
return tmp;
}
void *producer(void *arg){
int i;
for (i=0;i<loops;i++){
put(i);
}
pthread_exit(0);
}
void *consumer(void *arg){
int i;
for (i=0;i<loops;i++){
int temp = get();
printf("Thread %ld consumes %d\\n",(long)pthread_self(),temp);
}
pthread_exit(0);
}
int main()
{
slots = sem_open("/item", O_CREAT, 0644 ,1);
items = sem_open("/slot", O_CREAT, 0644 ,MAX);
pthread_t pid1, pid2, cid1,cid2;
pthread_create(&pid1, 0, producer, 0);
pthread_create(&pid2, 0, producer, 0);
pthread_create(&cid1, 0, consumer, 0);
pthread_create(&cid2, 0, consumer, 0);
pthread_join(pid1, 0);
pthread_join(pid2, 0);
pthread_join(cid1, 0);
pthread_join(cid2, 0);
exit(0);
}
| 1
|
#include <pthread.h>
int main(void)
{
pid_t pid;
int mid;
int bCreate = 0;
key_t key = 0x12341235;
pthread_mutex_t *mut;
pthread_mutexattr_t attr;
mid = shmget(key, 0, 0);
printf("sizeof mutex: %d\\n" ,sizeof(pthread_mutex_t));
if( mid == -1 )
{
bCreate = 1;
mid = shmget(key, 64, IPC_CREAT | 0666);
}
mut = (pthread_mutex_t *) shmat(mid, 0, 0);
if( bCreate == 1 )
{
pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(mut, &attr);
pthread_mutexattr_destroy(&attr);
}
printf("lock\\n");
pthread_mutex_lock(mut);
printf("fork\\n");
pid = fork();
if( pid == 0 )
{
while( 1 ) pause();
exit(0);
}
printf("unlock\\n");
pthread_mutex_unlock(mut);
printf("lock again\\n");
pthread_mutex_lock(mut);
printf("over\\n");
pthread_mutex_unlock(mut);
pthread_mutex_destroy(mut);
kill(pid, SIGKILL);
return(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex1;
pthread_mutex_t mutex2;
void usage(char *argv0, char *msg) {
if (msg != 0 && strlen(msg) > 0) {
printf("%s\\n\\n", msg);
}
printf("obtain and release mutex_locks in wrong order (lock 1, lock 2, unlock 1, unlock 2)\\n\\n");
printf("Usage\\n\\n");
printf("%s -d\\n mutex_type=PTHREAD_MUTEX_DEFAULT\\n\\n", argv0);
printf("%s -n\\n mutex_type=PTHREAD_MUTEX_NORMAL\\n\\n", argv0);
printf("%s -e\\n mutex_type=PTHREAD_MUTEX_ERRORCHECK\\n\\n", argv0);
printf("%s -r\\n mutex_type=PTHREAD_MUTEX_RECURSIVE\\n\\n", argv0);
printf("%s -x\\n no attribute used\\n\\n", argv0);
exit(1);
}
int main(int argc, char *argv[]) {
int retcode;
if (is_help_requested(argc, argv)) {
usage(argv[0], "");
}
pthread_mutexattr_t mutex_attr;
pthread_mutexattr_init(&mutex_attr);
char mutex_type = 'x';
if (argc >= 2 && strlen(argv[1]) == 2 && argv[1][0] == '-') {
mutex_type = argv[1][1];
}
switch (mutex_type) {
case 'd':
pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_DEFAULT);
break;
case 'n':
pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_NORMAL);
break;
case 'e':
pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_ERRORCHECK);
break;
case 'r':
pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE);
break;
case 'x':
break;
default:
usage(argv[0], "unknown option, supported: -d -n -e -r -x");
}
if (mutex_type == 'x') {
retcode = pthread_mutex_init(&mutex1, 0);
} else {
retcode = pthread_mutex_init(&mutex1, &mutex_attr);
}
handle_thread_error(retcode, "pthread_mutex_init (1)", PROCESS_EXIT);
if (mutex_type == 'x') {
retcode = pthread_mutex_init(&mutex2, 0);
} else {
retcode = pthread_mutex_init(&mutex2, &mutex_attr);
}
handle_thread_error(retcode, "pthread_mutex_init (2)", PROCESS_EXIT);
printf("in parent thread: getting mutex1\\n");
pthread_mutex_lock(&mutex1);
printf("in parent thread: got mutex1\\n");
sleep(1);
printf("in parent thread: getting mutex2\\n");
pthread_mutex_lock(&mutex2);
printf("in parent thread: got mutex2\\n");
sleep(1);
printf("in parent thread: releasing mutex1\\n");
pthread_mutex_unlock(&mutex1);
printf("in parent thread: releasing mutex2\\n");
pthread_mutex_unlock(&mutex2);
printf("in parent thread: done\\n");
retcode = pthread_mutex_destroy(&mutex1);
handle_thread_error(retcode, "pthread_mutex_destroy", PROCESS_EXIT);
retcode = pthread_mutex_destroy(&mutex2);
handle_thread_error(retcode, "pthread_mutex_destroy", PROCESS_EXIT);
printf("done\\n");
exit(0);
}
| 1
|
#include <pthread.h>
long long num_steps = 1000000000;
double step;
double pi;
int NO_PROC = 4;
int counter = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *hiloFunc(void *args){
double x, sum=0.0;
pthread_mutex_lock(&mutex);
long range= counter*250000000;
counter++;
pthread_mutex_unlock(&mutex);
printf("%lu\\n",range);
for (int i=range; i<range+250000000; i++){
x = (i + .5)*step;
sum = sum + 4.0/(1.+ x*x);
}
pthread_mutex_lock(&mutex);
pi = pi+(sum*step);
pthread_mutex_unlock(&mutex);
}
int main(int argc, char* argv[]){
long long start_ts;
long long stop_ts;
float elapsed_time;
long lElapsedTime;
struct timeval ts;
gettimeofday(&ts, 0);
start_ts = ts.tv_sec * 1000000 + ts.tv_usec;
step = 1./(double)num_steps;
pthread_t idhilo[4];
for(int i=0;i<4;i++){
pthread_create(&idhilo[i],0,hiloFunc,0);
}
for(int i=0;i<4;i++){
pthread_join(idhilo[i],0);
}
gettimeofday(&ts, 0);
stop_ts = ts.tv_sec * 1000000 + ts.tv_usec;
elapsed_time = (float) (stop_ts - start_ts)/1000000.0;
printf("El valor de PI es %1.12f\\n",pi);
printf("Tiempo = %2.2f segundos\\n",elapsed_time);
return 0;
}
| 0
|
#include <pthread.h>
static void readfunc();
static void writefunc();
char buffer[256];
int buffer_has_item = 0;
int retflag = 0;
pthread_mutex_t mutex;
int pthread_mutex_test(){
pthread_t reader;
pthread_mutex_init(&mutex, 0);
pthread_create(&reader, 0, (void *)&readfunc, 0);
writefunc();
pthread_mutex_destroy (&mutex);
return 0;
}
void readfunc (){
while(1){
if(retflag){
return;
}
pthread_mutex_lock (&mutex);
if(buffer_has_item == 1){
printf("%s", buffer);
buffer_has_item = 0;
}
pthread_mutex_unlock (&mutex);
}
}
void writefunc (){
int i = 0;
while(1){
if(i == 10){
retflag = 1;
return;
}
pthread_mutex_lock(&mutex);
if(buffer_has_item == 0){
sprintf(buffer, "This is %d\\n", i++);
buffer_has_item = 1;
}
pthread_mutex_unlock (&mutex);
}
}
| 1
|
#include <pthread.h>
struct block_hd *next;
struct block_hd *prev;
int size;
} block_header;
block_header* start;
int reverse;
int size;
} myarg_t;
block_header* current;
int status;
} myret_t;
block_header* list_head = 0;
block_header* list_tail = 0;
void *thread_space;
int search_done = 0;
pthread_mutex_t lock;
pthread_cond_t init;
int Mem_Init(int sizeOfRegion){
pthread_mutex_init(&lock, 0);
pthread_cond_init(&init, 0);
int fd;
void* space_ptr;
fd = open ("/dev/zero", O_RDWR);
space_ptr = mmap(0,sizeOfRegion, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
thread_space = space_ptr;
list_head = (block_header*)((char*)space_ptr + 2 * sizeof(myret_t));
list_tail = (block_header*)((char*)space_ptr + sizeOfRegion - sizeof(block_header));
list_head->next = list_tail;
list_head->prev = 0;
list_head->size = sizeOfRegion - 2 * sizeof(myret_t) - 2 * (int)sizeof(block_header);
list_tail->next = 0;
list_tail->prev = list_head;
list_tail->size = 0;
close(fd);
return 0;
}
void* List_Search(void* args){
int reverse = ((myarg_t*)args)->reverse;
int size = ((myarg_t*)args)->size;
block_header* current = ((myarg_t*)args)->start;
myret_t *ret;
if(!reverse){
ret = (myret_t*)thread_space;
}
else if(reverse){
ret = ((myret_t*)thread_space) + 1;
}
if(!reverse){
while(current){
if(!(current->size & 0x0001)){
if(size + sizeof(block_header) < current->size){
ret->status = 1;
ret->current = current;
pthread_mutex_lock(&lock);
search_done = 1;
pthread_cond_signal(&init);
pthread_mutex_unlock(&lock);
return ret;
}
else if(size == current->size){
ret->status = 0;
pthread_mutex_lock(&lock);
search_done = 1;
pthread_cond_signal(&init);
pthread_mutex_unlock(&lock);
ret->current = current;
return ret;
}
}
current = current->next;
}
}
else if(reverse){
while(current){
if(!(current->size & 0x0001)){
if(size + sizeof(block_header) < current->size){
ret->status = 1;
ret->current = current;
pthread_mutex_lock(&lock);
search_done = 1;
pthread_cond_signal(&init);
pthread_mutex_unlock(&lock);
return ret;
}
else if(size == current->size){
ret->status = 0;
ret->current = current;
pthread_mutex_lock(&lock);
search_done = 1;
pthread_cond_signal(&init);
pthread_mutex_unlock(&lock);
return ret;
}
}
current = current->prev;
}
}
printf("WaaaH\\n");
return ret;
}
void* Mem_Alloc(int size){
pthread_t p1;
pthread_t p2;
myarg_t args1;
myarg_t args2;
args1.size = size; args1.start = list_head; args1.reverse = 0;
args2.size = size; args2.start = list_tail; args2.reverse = 1;
pthread_create(&p1, 0, List_Search, &args1);
pthread_create(&p2, 0, List_Search, &args2);
pthread_mutex_lock(&lock);
while (search_done == 0)
pthread_cond_wait(&init, &lock);
pthread_mutex_unlock(&lock);
if(size + sizeof(block_header) < current->size){
block_header *next = (block_header*)(((char*)(current+1)) + size);
next->size = current->size -size - sizeof(block_header);
next->next = current->next;
next->prev = current;
current->next = next;
current->size = size;
(current->size) ++;
return (void*)(current+1);
}
else if(size == current->size){
(current->size) ++;
return (void*)(current+1);
}
return 0;
}
int Mem_Free(void *ptr){
block_header* current = (block_header*)((char*)ptr -sizeof(block_header));
(current->size)--;
if((current->next) && (!((current->next->size)&0x0001))){
current->size += ((current->next->size) + sizeof(block_header));
current->next = current->next->next;
if(current->next)
current->next->prev = current;
}
if((current->prev) && (!((current->prev->size)&0x0001))){
current->prev->size += ((current->size) + sizeof(block_header));
current->prev->next = current->next;
if(current->next)
current->next->prev = current->prev;
}
return 0;
}
| 0
|
#include <pthread.h>
static const unsigned int kNumPhilosophers = 5;
static const unsigned int kNumForks = kNumPhilosophers;
static const unsigned int kNumMeals = 3;
static pthread_mutex_t forks[kNumForks];
static int getSleepTime()
{
return rand() % 200000;
}
static int getEatTime()
{
return rand() % 100000;
}
static int getThinkTime()
{
return rand() % 300000;
}
static int getPickupDelayTime()
{
return 200000;
}
static void think(unsigned int id) {
printf("%u starts thinking.\\n", id);
usleep(getThinkTime());
printf("%u all done thinking.\\n", id);
}
static void eat(unsigned int id) {
unsigned int left = id;
unsigned int right = (id + 1) % kNumForks;
pthread_mutex_lock(&forks[left]);
usleep(getPickupDelayTime());
pthread_mutex_lock(&forks[right]);
printf("%u starts eating om nom nom nom.\\n", id);
usleep(getEatTime());
printf("%u all done eating.\\n", id);
pthread_mutex_unlock(&forks[left]);
pthread_mutex_unlock(&forks[right]);
}
static void *philosopher(void *data)
{
for (unsigned int i = 0; i < kNumMeals; i++) {
think((unsigned int) data);
eat((unsigned int) data);
}
return 0;
}
int main(int argc, char **argv)
{
srand(time(0));
pthread_t philosophers[kNumPhilosophers];
for (unsigned int i = 0; i < kNumForks; i++) {
pthread_mutex_init(&forks[i], 0);
}
for (unsigned int i = 0; i < kNumPhilosophers; i++) {
pthread_create(&philosophers[i], 0, philosopher, (void *) i);
}
for (unsigned int i = 0; i < kNumPhilosophers; i++) {
pthread_join(philosophers[i], 0);
}
exit(0);
}
| 1
|
#include <pthread.h>
struct task_node_t
{
struct task_node_t *next;
task_fun_t task;
void *args;
};
struct task_queue_t
{
struct task_node_t *work_task_head;
struct task_node_t *work_task_tail;
struct task_node_t *free_task;
int num;
};
static int tn_clear(struct task_node_t *tn)
{
assert(tn != 0);
tn->next = 0;
tn->task = 0;
tn->args = 0;
return 0;
}
static int tq_ini(struct task_queue_t *tq)
{
assert(tq != 0);
tq->work_task_head = 0;
tq->work_task_tail = 0;
tq->free_task = 0;
tq->num = 0;
return 0;
}
static int tq_fini(struct task_queue_t *tq)
{
assert(tq != 0);
struct task_node_t *tn = 0;
tn = tq->work_task_head;
while (tn != 0)
{
tq->work_task_head = tq->work_task_head->next;
free(tn);
tn = tq->work_task_head;
}
tq->work_task_tail = 0;
tn = tq->free_task;
while (tn != 0)
{
tq->free_task = tq->free_task->next;
free(tn);
tn = tq->free_task;
}
tq->num = 0;
return 0;
}
static struct task_node_t *get_task_node(struct task_queue_t *tq)
{
if (tq->free_task == 0)
{
tq->free_task = (struct task_node_t *)malloc(sizeof (struct task_node_t));
if (tq->free_task == 0)
return 0;
tq->free_task->next = 0;
}
struct task_node_t *tn = tq->free_task;
tq->free_task = tq->free_task->next;
tn_clear(tn);
return tn;
}
static int tq_put(struct task_queue_t *tq, task_fun_t task, void *args)
{
assert(tq != 0);
struct task_node_t *tn = 0;
tn = get_task_node(tq);
tn->task = task;
tn->args = args;
if (tq->work_task_head == 0)
{
tq->work_task_head = tn;
tq->work_task_tail = tn;
}
else
{
tq->work_task_tail->next = tn;
tq->work_task_tail = tn;
}
tq->num++;
return 0;
}
static struct task_node_t tq_get(struct task_queue_t *tq)
{
assert(tq != 0);
struct task_node_t tn;
tn_clear(&tn);
if (tq->num == 0)
return tn;
tn = *(tq->work_task_head);
tq->work_task_head = tq->work_task_head->next;
if (tq->work_task_head == 0)
tq->work_task_tail = 0;
tq->num--;
tn.next = 0;
return tn;
}
struct mthread_pool_t
{
struct mthread_t **mts;
int num;
int run;
pthread_mutex_t mutex;
pthread_cond_t cond;
struct task_queue_t tq;
};
struct mthread_pool_t *mtp_ini()
{
struct mthread_pool_t *mtp = (struct mthread_pool_t *)malloc(sizeof (struct mthread_pool_t));
if (mtp == 0)
return 0;
mtp->mts = 0;
mtp->num = 0;
mtp->run = 0;
pthread_mutex_init(&mtp->mutex, 0);
pthread_cond_init(&mtp->cond, 0);
tq_ini(&mtp->tq);
return mtp;
}
int mtp_fini(struct mthread_pool_t *mtp)
{
if (mtp == 0)
return MTP_NULL_POOL;
if(mtp->run)
mtp_stop(mtp);
if (mtp->mts != 0)
{
int i;
for (i = 0; i < mtp->num; i++)
mt_fini(mtp->mts[i]);
free(mtp->mts);
}
pthread_cond_destroy(&mtp->cond);
pthread_mutex_destroy(&mtp->mutex);
tq_fini(&mtp->tq);
return MTP_OK;
}
static struct task_node_t take(struct mthread_pool_t *mtp)
{
assert(mtp != 0);
pthread_mutex_lock(&mtp->mutex);
while (mtp->tq.num == 0 && mtp->run)
pthread_cond_wait(&mtp->cond, &mtp->mutex);
struct task_node_t tn = tq_get(&mtp->tq);
pthread_mutex_unlock(&mtp->mutex);
return tn;
}
static void *thread_fun(void *args)
{
assert(args != 0);
struct mthread_pool_t *mtp = (struct mthread_pool_t *)args;
while (mtp->run)
{
struct task_node_t tn = take(mtp);
if (tn.task != 0)
tn.task(tn.args);
}
return 0;
}
int mtp_start(struct mthread_pool_t *mtp, int num)
{
if (mtp == 0)
return MTP_NULL_POOL;
if (mtp->run)
mtp_stop(mtp);
mtp->mts = (struct mthread_t **)malloc(num * sizeof (struct mthread_t *));
if (mtp->mts == 0)
return MTP_MEM_ERROR;
mtp->num = num;
mtp->run = 1;
int i;
for (i = 0; i < mtp->num; i++)
{
mtp->mts[i] = mt_ini(thread_fun);
assert(mtp->mts[i] != 0);
mt_start(mtp->mts[i], mtp);
}
return MTP_OK;
}
int mtp_stop(struct mthread_pool_t *mtp)
{
pthread_mutex_lock(&mtp->mutex);
mtp->run = 0;
pthread_mutex_unlock(&mtp->mutex);
pthread_cond_broadcast(&mtp->cond);
int i;
for (i = 0; i < mtp->num; i++)
mt_join(mtp->mts[i]);
return MTP_OK;
}
int mtp_run(struct mthread_pool_t *mtp, void *(*fun)(void *), void *args)
{
if (mtp == 0)
return MTP_NULL_POOL;
if (mtp->tq.num == 0 && mtp->run)
fun(args);
else
{
pthread_mutex_lock(&mtp->mutex);
tq_put(&mtp->tq, fun, args);
pthread_mutex_unlock(&mtp->mutex);
pthread_cond_signal(&mtp->cond);
}
return 0;
}
| 0
|
#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;
main()
{
pthread_t thread1, thread2;
pthread_create( &thread1, 0, &functionCount1, 0);
pthread_create( &thread2, 0, &functionCount2, 0);
pthread_join( thread1, 0);
pthread_join( thread2, 0);
printf("Final count: %d\\n",count);
exit(0);
}
void *functionCount1()
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
pthread_cond_wait( &condition_var, &count_mutex );
count++;
printf("Counter value functionCount1: %d\\n",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_signal( &condition_var );
}
else
{
count++;
printf("Counter value functionCount2: %d\\n",count);
}
pthread_mutex_unlock( &count_mutex );
if(count >= 10) return(0);
}
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
extern int __VERIFIER_nondet_int();
int idx=0;
int ctr1=1, ctr2=0;
int readerprogress1=0, readerprogress2=0;
pthread_mutex_t mutex;
void __VERIFIER_atomic_use1(int myidx) {
__VERIFIER_assume(myidx <= 0 && ctr1>0);
ctr1++;
}
void __VERIFIER_atomic_use2(int myidx) {
__VERIFIER_assume(myidx >= 1 && ctr2>0);
ctr2++;
}
void __VERIFIER_atomic_use_done(int myidx) {
if (myidx <= 0) { ctr1--; }
else { ctr2--; }
}
void __VERIFIER_atomic_take_snapshot(int *readerstart1, int *readerstart2) {
*readerstart1 = readerprogress1;
*readerstart2 = readerprogress2;
}
void __VERIFIER_atomic_check_progress1(int readerstart1) {
if (__VERIFIER_nondet_int()) {
__VERIFIER_assume(readerstart1 == 1 && readerprogress1 == 1);
if (!(0)) ERROR: __VERIFIER_error();;
}
return;
}
void __VERIFIER_atomic_check_progress2(int readerstart2) {
if (__VERIFIER_nondet_int()) {
__VERIFIER_assume(readerstart2 == 1 && readerprogress2 == 1);
if (!(0)) ERROR: __VERIFIER_error();;
}
return;
}
void *qrcu_reader1() {
int myidx;
while (1) {
myidx = idx;
if (__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use1(myidx);
break;
} else {
if (__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use2(myidx);
break;
} else {}
}
}
readerprogress1 = 1;
readerprogress1 = 2;
__VERIFIER_atomic_use_done(myidx);
return 0;
}
void *qrcu_reader2() {
int myidx;
while (1) {
myidx = idx;
if (__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use1(myidx);
break;
} else {
if (__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use2(myidx);
break;
} else {}
}
}
readerprogress2 = 1;
readerprogress2 = 2;
__VERIFIER_atomic_use_done(myidx);
return 0;
}
void* qrcu_updater() {
int i;
int readerstart1, readerstart2;
int sum;
__VERIFIER_atomic_take_snapshot(&readerstart1, &readerstart2);
if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; };
if (sum <= 1) { if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; }; }
else {}
if (sum > 1) {
pthread_mutex_lock(&mutex);
if (idx <= 0) { ctr2++; idx = 1; ctr1--; }
else { ctr1++; idx = 0; ctr2--; }
if (idx <= 0) { while (ctr1 > 0); }
else { while (ctr2 > 0); }
pthread_mutex_unlock(&mutex);
} else {}
__VERIFIER_atomic_check_progress1(readerstart1);
__VERIFIER_atomic_check_progress2(readerstart2);
return 0;
}
int main() {
pthread_t t1, t2, t3;
pthread_mutex_init(&mutex, 0);
pthread_create(&t1, 0, qrcu_reader1, 0);
pthread_create(&t2, 0, qrcu_reader2, 0);
pthread_create(&t3, 0, qrcu_updater, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_join(t3, 0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
int Buffer_Index_Value = 0;
char *Buffer_Queue;
pthread_mutex_t mutex_variable = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t Buffer_Queue_Not_Full = PTHREAD_COND_INITIALIZER;
pthread_cond_t Buffer_Queue_Not_Empty = PTHREAD_COND_INITIALIZER;
void *Consumer()
{
while(1)
{
pthread_mutex_lock(&mutex_variable);
if(Buffer_Index_Value == -1)
{
pthread_cond_wait(&Buffer_Queue_Not_Empty, &mutex_variable);
}
printf("Consumer:%d\\t", Buffer_Index_Value--);
pthread_mutex_unlock(&mutex_variable);
pthread_cond_signal(&Buffer_Queue_Not_Full);
}
}
void *Producer()
{
while(1)
{
pthread_mutex_lock(&mutex_variable);
if(Buffer_Index_Value == 10)
{
pthread_cond_wait(&Buffer_Queue_Not_Full, &mutex_variable);
}
Buffer_Queue[Buffer_Index_Value++] = '@';
printf("Producer:%d\\t", Buffer_Index_Value);
pthread_mutex_unlock(&mutex_variable);
pthread_cond_signal(&Buffer_Queue_Not_Empty);
}
}
int main()
{
pthread_t producer_thread_id, consumer_thread_id;
Buffer_Queue = (char *) malloc(sizeof(char) * 10);
pthread_create(&producer_thread_id, 0, Producer, 0);
pthread_create(&consumer_thread_id, 0, Consumer, 0);
pthread_join(producer_thread_id, 0);
pthread_join(consumer_thread_id, 0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
sem_t full,empty;
pthread_t producer[5],consumer[5];
int counter,buffer[10];
void *produce(void*);
void *consume(void*);
int main()
{
pthread_mutex_init(&mutex,0);
sem_init(&full,1,0);
sem_init(&empty,1,10);
counter=0;
int i=0;
for(i=0;i<=2;i++)
{
pthread_create(&producer[i],0,produce,0);
pthread_create(&consumer[i],0,consume,0);
}
for(i=0;i<=2;i++)
{
pthread_join(producer[i],0);
pthread_join(consumer[i],0);
}
return 0;
}
void *produce(void *arg)
{
int item = rand()%5;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
printf("\\nProducer produced:%d",item);
buffer[counter++]=item;
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
void *consume(void *arg)
{
sem_wait(&full);
pthread_mutex_lock(&mutex);
int item=buffer[--counter];
printf("\\nConsumer consumed:%d",item);
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
| 0
|
#include <pthread.h>
static pthread_key_t key;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;
extern char **environ;
static void thread_init(void)
{
thread_key_create(&key, free);
}
char *getenv(const char *name)
{
int i, len;
char *envbuf;
pthread_once(&init_done, thread_init);
pthread_mutex_lock(&env_mutex);
envbuf = (char *)pthread_getspecific(key);
if (envbuf == 0) {
envbuf = malloc(4096);
if (envbuf == 0) {
pthread_mutex_unlock(&env_mutex);
return(0);
}
pthread_setspecific(key, envbuf);
}
len = strlen(name);
for (i = 0; environ[i] != 0; i++) {
if ((strncmp(name, environ[i], len) == 0) &&
(environ[i][len] == '=')) {
strncpy(envbuf, &environ[i][len+1], 4096 -1);
pthread_mutex_unlock(&env_mutex);
return(envbuf);
}
}
pthread_mutex_unlock(&env_mutex);
return(0);
}
| 1
|
#include <pthread.h>
void mux_2_regdst(void *not_used){
pthread_barrier_wait(&threads_creation);
while(1){
pthread_mutex_lock(&control_sign);
if(!cs.isUpdated){
while(pthread_cond_wait(&control_sign_wait,&control_sign) != 0);
}
pthread_mutex_unlock(&control_sign);
if(cs.invalidInstruction){
pthread_barrier_wait(&update_registers);
pthread_exit(0);
}
if((( (separa_RegDst & cs.value) >> RegDst_POS) & 0x01) == 0){
mux_regdst_buffer.value = ((ir & separa_rt) >> 16) & 0x0000001f;
}
else mux_regdst_buffer.value = ((ir & separa_rd) >> 11) & 0x0000001f;
pthread_mutex_lock(&mux_regdst_result);
mux_regdst_buffer.isUpdated = 1;
pthread_cond_signal(&mux_regdst_execution_wait);
pthread_mutex_unlock(&mux_regdst_result);
pthread_barrier_wait(¤t_cycle);
mux_regdst_buffer.isUpdated = 0;
pthread_barrier_wait(&update_registers);
}
}
| 0
|
#include <pthread.h>
pthread_cond_t cond;
pthread_mutex_t mutex;
void* p_func(void* p)
{
pthread_mutex_lock(&mutex);
int ret;
int i=(int)p;
printf("I am child %d,I am here\\n",i);
ret=pthread_cond_wait(&cond,&mutex);
if(0!=ret)
{
printf("pthread_cond_wait ret=%d\\n",ret);
}
printf("I am child thread %d,I am wake\\n",i);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main()
{
int ret;
ret=pthread_cond_init(&cond,0);
if(0!=ret)
{
printf("pthread_cond_init ret=%d\\n",ret);
return -1;
}
ret=pthread_mutex_init(&mutex,0);
if(0!=ret)
{
printf("pthread_mutex_init ret=%d\\n",ret);
return -1;
}
pthread_t thid[5];
int i;
for(i=0;i<5;i++)
{
pthread_create(&thid[i],0,p_func,(void*)i);
}
sleep(1);
pthread_cond_broadcast(&cond);
for(i=0;i<5;i++)
{
ret=pthread_join(thid[i],0);
if(0!=ret)
{
printf("pthread_join ret=%d\\n",ret);
return -1;
}
}
ret=pthread_cond_destroy(&cond);
if(0!=ret)
{
printf("pthread_cond_destroy ret=%d\\n",ret);
return -1;
}
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
int threads_amount;
char *file_name;
int records_to_read;
char *to_find;
int records_size = 1024;
int fd;
int END_FILE = 0;
int records_transfered;
int *finished;
pthread_key_t records;
pthread_t *threads;
pthread_mutex_t out_mutex = PTHREAD_MUTEX_INITIALIZER;
int main(int argc, char *argv[]) {
if (argc < 5) {
printf("Usage: finder threads_amount file_name records_to_read to_find\\n");
exit(0);
} else {
threads_amount = atoi(argv[1]);
file_name = argv[2];
records_to_read = atoi(argv[3]);
to_find = argv[4];
}
fd = open(file_name, O_RDONLY);
if (fd == -1) {
perror("File doesn't exists!");
exit(-1);
}
int err;
pthread_key_create(&records, 0);
threads = malloc(threads_amount * sizeof(pthread_t));
for (int t = 0; t < threads_amount; t++) {
err = pthread_create(&threads[t], 0, &do_some_thing, 0);
if (err == -1) {
perror("erroor while creating thread\\n");
}
}
for (int t = 0; t < threads_amount; t++)
pthread_join(threads[t], 0);
for (int r = 0; r < records_to_read; r++) {
pthread_key_delete(records);
}
return 0;
}
void *do_some_thing(void *arg) {
pthread_t myTID = pthread_self();
if (-1 == pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0)) {
perror("setting cancel_type");
exit(-1);
}
while (!END_FILE) {
if (read_file()) {
END_FILE = 1;
} else {
void *buff;
buff = pthread_getspecific(records);
int index;
char *record = malloc(sizeof(char) * 1020);
for (int r = 0; r < records_to_read; r++) {
memcpy(&index, buff, sizeof(int));
buff += sizeof(int);
memcpy(record, buff, 1020);
if (record)
if (strstr(record, to_find) != 0) {
pthread_mutex_lock(&out_mutex);
for (int act_t = 0; act_t < threads_amount; act_t++) {
if (!pthread_equal(myTID, threads[act_t])) {
pthread_cancel(threads[act_t]);
}
END_FILE = 1;
}
printf("TID: %ld Found %s in\\n %d %s\\n", myTID, to_find, index, record);
pthread_mutex_unlock(&out_mutex);
pthread_cancel(myTID);
break;
}
buff += 1020;
}
}
}
}
int read_file() {
void *buff = malloc(sizeof(char) * 1024 * records_to_read);
ssize_t bytes_read;
bytes_read = read(fd, buff, sizeof(char) * 1024 * records_to_read);
pthread_setspecific(records, buff);
return !bytes_read;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *thread0(void *arg)
{
printf("thread0 wait for lock\\n");
pthread_mutex_lock(&mutex);
printf("thread0 get lock\\n");
printf("thread0 wait for cond\\n");
pthread_cond_wait(&cond, &mutex);
printf("thread0 get cond\\n");
pthread_mutex_unlock(&mutex);
printf("thread0 unlock\\n");
pthread_exit(0);
}
void *thread1(void *arg)
{
sleep(4);
printf("thread1 wait for lock\\n");
pthread_mutex_lock(&mutex);
printf("thread1 get lock\\n");
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
printf("thread1 unlock\\n");
pthread_exit(0);
}
int main()
{
pthread_t thid[2];
if (pthread_create(&thid[0], 0, thread0, 0) != 0)
exit(0);
if (pthread_create(&thid[1], 0, thread1, 0) != 0)
exit(0);
sleep(2);
printf("main cencel thread0\\n");
pthread_cancel(thid[0]);
pthread_join(thid[0], 0);
pthread_join(thid[1], 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
| 1
|
#include <pthread.h>
uint32_t get_user_id(char* username)
{
if(username)
{
for(uint32_t i = 1; i < user_count; i++)
{
if(strcmp((users+i)->name, username) == 0) return i;
}
}
return 0;
}
char* contains_group(char* name)
{
char* groupname = 0;
if(name)
{
for(uint32_t i = 0; i < strlen(name); i++)
{
if(name[i] == '/')
{
groupname = malloc(strlen(name+i+1)+1);
strcpy(groupname, name+i+1);
break;
}
}
}
return groupname;
}
char* get_group_user(char* groupname, uint32_t user_number)
{
struct group* current_group;
struct dynamic_array* members;
for(uint32_t i = 0; i < groups->length; i++)
{
current_group = (struct group*)dynamic_array_at(groups, i);
if(strcmp(current_group->name, groupname) == 0)
{
members = current_group->members;
return dynamic_array_at(members, user_number);
}
}
return 0;
}
void put_message_local(const struct string_info* info)
{
uint32_t server_found = 0;
uint32_t user_id;
char* target_name = 0;
char* groupname;
for(uint32_t i = 0; i < info->message->length; i++)
{
if(server_found && (info->message->data[i] == ':'))
{
target_name = malloc(i-server_found+1);
memcpy(target_name, info->message->data+server_found, i-server_found);
target_name[i-server_found] = '\\0';
break;
}
if(info->message->data[i] == '@')
server_found = i+1;
}
uint32_t complete_length = (uint32_t)(strlen(info->source_server) + strlen(info->source_user) + strlen(info->message->data + info->message_begin) + 8 + 3 + 1);
struct string* message = malloc(sizeof(*message));
message->data = malloc(complete_length);
message->length = 0;
message->capacity = complete_length;
copy_helper(message, (const void*)&info->timestamp, 8, '>');
copy_helper(message, (const void*)info->source_server, (uint32_t)strlen(info->source_server), '@');
copy_helper(message, (const void*)info->source_user, (uint32_t)strlen(info->source_user), ':');
copy_helper(message, (const void*)(info->message->data + info->message_begin), (uint32_t)strlen(info->message->data + info->message_begin), '\\0');
printf("here\\n");
pthread_mutex_lock(&groups->mutex);
if((groupname = contains_group(target_name)))
{
char* username = 0;
struct string* tmp;
for(uint32_t i = 0; (username = get_group_user(groupname, i)) != 0; i++)
{
printf("%p\\n", username);
printf("name: %s\\n", username);
if((user_id = get_user_id(username)) == 0)
continue;
tmp = malloc(sizeof(*tmp));
string_copy(tmp, message);
pthread_mutex_lock(&(users+user_id)->messages->mutex);
dynamic_array_push((users+user_id)->messages, tmp);
pthread_mutex_unlock(&(users+user_id)->messages->mutex);
}
free(message->data);
free(message);
free(groupname);
} else {
printf("User-name = %s\\n", target_name);
if((user_id = get_user_id(target_name)) == 0)
goto cleanup;
pthread_mutex_lock(&(users+user_id)->messages->mutex);
dynamic_array_push((users+user_id)->messages, message);
pthread_mutex_unlock(&(users+user_id)->messages->mutex);
}
printf("through\\n");
cleanup:
free(target_name);
pthread_mutex_unlock(&groups->mutex);
}
void copy_helper(struct string* message, const void* source, uint32_t length, char insert)
{
memcpy(message->data + message->length, source, length);
message->length += length;
message->data[message->length] = insert;
message->length += 1;
}
| 0
|
#include <pthread.h>
pthread_mutex_t kljuc = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t d = PTHREAD_COND_INITIALIZER;
pthread_cond_t l = PTHREAD_COND_INITIALIZER;
pthread_cond_t plovi = PTHREAD_COND_INITIALIZER;
int obala;
int index;
}podaci;
int obala_camac = 1;
int broj_kanibala_na_camcu = 0;
int broj_misionara_na_camcu = 0;
ulazak_kanibala(int k, int m){
return !( k + m + 1 < 8 && ( k + 1 < 4 || m == 0) );
}
ulazak_misionara(int k, int m){
return !( k + m + 1 < 8 && ( k < 4 ) );
}
void* kanibal( void * id_ ){
podaci* id = (podaci*) id_;
int index = id->index;
int obala = id->obala;
pthread_mutex_lock( &kljuc );
while( obala != obala_camac ||
ulazak_kanibala(broj_kanibala_na_camcu, broj_misionara_na_camcu) ) {
if(obala == 1)
pthread_cond_wait( &d, &kljuc );
else
pthread_cond_wait( &l, &kljuc );
}
broj_kanibala_na_camcu++;
int k = broj_kanibala_na_camcu, m = broj_misionara_na_camcu, o = obala_camac;
printf("kanibal%d se utrpao na camac na %d obali ... (%d, %d, %d)\\n", index, obala, m, k, o);
if( (broj_kanibala_na_camcu <= broj_misionara_na_camcu
|| broj_misionara_na_camcu == 0)
&& broj_kanibala_na_camcu + broj_misionara_na_camcu > 2 ){
pthread_cond_signal( &plovi );
}
pthread_mutex_unlock( &kljuc );
free(id_);
}
void* misionar( void * id_ ){
podaci* id = (podaci*) id_;
int index = id->index;
int obala = id->obala;
pthread_mutex_lock( &kljuc );
while( obala != obala_camac ||
ulazak_misionara(broj_kanibala_na_camcu, broj_misionara_na_camcu) ){
if(obala == 1)
pthread_cond_wait( &d, &kljuc );
else
pthread_cond_wait( &l, &kljuc );
}
broj_misionara_na_camcu++;
int k = broj_kanibala_na_camcu, m = broj_misionara_na_camcu, o = obala_camac;
printf("misionar%d se utrpao na camac na %d obali....(%d, %d, %d)\\n", index, obala, m, k, o);
if( (broj_kanibala_na_camcu <= broj_misionara_na_camcu
|| broj_misionara_na_camcu == 0 )&&
broj_kanibala_na_camcu + broj_misionara_na_camcu > 2 ){
pthread_cond_signal( &plovi );
}
pthread_mutex_unlock( &kljuc );
free(id_);
}
void* camac( void* a){
while(1){
pthread_mutex_lock(&kljuc);
while( broj_kanibala_na_camcu + broj_misionara_na_camcu < 3
|| ( broj_misionara_na_camcu < broj_kanibala_na_camcu
&& broj_misionara_na_camcu != 0 ) ){
pthread_cond_wait(&plovi, &kljuc);
}
sleep(1);
printf("prevozim s %d obale na %d obalu %d misionara i %d kanibala\\n",
obala_camac, 1-obala_camac, broj_misionara_na_camcu, broj_kanibala_na_camcu);
obala_camac = 1 - obala_camac;
broj_misionara_na_camcu = 0;
broj_kanibala_na_camcu = 0;
sleep( 2 );
if(obala_camac == 0){
pthread_cond_broadcast( &l );
}
else{
pthread_cond_broadcast( &d );
}
pthread_mutex_unlock(&kljuc);
}
}
int main(){
pthread_t dretva;
pthread_attr_t atribut;
int br_misionari = 0, br_kanibali = 0;
podaci* id;
pthread_attr_init(&atribut);
pthread_attr_setdetachstate(&atribut, PTHREAD_CREATE_DETACHED);
pthread_create(&dretva, &atribut, camac, 0);
while( 1 ){
id = (podaci*)malloc( sizeof( podaci ) );
id->index = br_kanibali;
id->obala = rand() % 2;
pthread_create( &dretva, &atribut, kanibal, (void*)id );
br_kanibali++;
id = malloc( sizeof( podaci ) );
id->index = br_misionari;
id->obala = rand() % 2;
pthread_create( &dretva, &atribut, misionar, (void*)id );
br_misionari++;
sleep( 1 );
id = malloc( sizeof( podaci ) );
id->index = br_kanibali;
id->obala = rand() % 2;
pthread_create( &dretva, &atribut, kanibal, (void*)id );
br_kanibali++;
sleep( 1 );
}
return 0;
}
| 1
|
#include <pthread.h>
int *array;
int length, count= 0;
pthread_t *ids;
pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER;
int length_per_thread;
void * count3p(void *myI){
int i, myStart, myEnd, myIdx= (int)myI;
myStart= length_per_thread * myIdx; myEnd= myStart + length_per_thread;
printf("Thread idx %d, Starting at %d Ending at %d\\n", myIdx, myStart, myEnd-1);
for(i=myStart; i < myEnd; i++){
if(array[i] == 3){
pthread_mutex_lock(&mtx);
count++;
pthread_mutex_unlock(&mtx);
}
}
}
void count3Launcher(int n) {
int i;
for (i= 0; i < n; i++) {
Pthread_create(&ids[i], 0, count3p, (void *)i);
}
}
void count3Joiner(int n) {
int i;
for (i= 0; i < n; i++) {
Pthread_join(ids[i], 0);
}
}
int main( int argc, char *argv[]){
int i;
struct timeval s,t;
if ( argc != 2 ) {
printf("Usage: %s <number of threads>\\n", argv[0]); return 1;
}
int n = atoi(argv[1]);
ids = (pthread_t *)malloc(n*sizeof(pthread_t));
array= (int *)malloc(384*1024*1024*sizeof(int));
length = 384*1024*1024;
srand(0);
for(i=0; i < length; i++){
array[i] = rand() % 4;
}
if ( (384*1024*1024 % n) != 0 ) {
printf("Work unevenly distributed among threads is not supported by this implementation!!!\\n");
return 2;
}
length_per_thread = 384*1024*1024 / n;
printf("Using %d threads; length_per_thread = %d\\n", n, length_per_thread);
gettimeofday(&s, 0);
count3Launcher(n);
count3Joiner(n);
gettimeofday(&t, 0);
printf("Count of 3s = %d\\n", count);
printf("Elapsed time (us) = %ld\\n",
(t.tv_sec - s.tv_sec)*1000000 + (t.tv_usec - s.tv_usec));
return 0;
}
| 0
|
#include <pthread.h>
enum memmodel
{
MEMMODEL_RELAXED = 0,
MEMMODEL_CONSUME = 1,
MEMMODEL_ACQUIRE = 2,
MEMMODEL_RELEASE = 3,
MEMMODEL_ACQ_REL = 4,
MEMMODEL_SEQ_CST = 5
};
inline static void mysync(int id, int volatile * b){
if(id == 0) {
*b = 1;
} else {
while(*b == 0);
}
}
int main(void){
int core[48] = {0};
int a [48 / 2] = {0};
int b [48 / 2] = {0};
int c [48 / 2] = {0};
int r1[10000][48 / 2] = {{0}};
int r2[10000][48 / 2] = {{0}};
pthread_mutex_t mutex1;
pthread_mutex_t mutex2;
pthread_mutex_init(&mutex1, 0);
pthread_mutex_init(&mutex2, 0);
{
core[omp_get_thread_num()] = sched_getcpu();
for(int i = 0; i < 10000; i++){
if (omp_get_thread_num() % 2 == 0)
{
int id = omp_get_thread_num() / 2;
mysync(0, &(c[id]));
__atomic_thread_fence(MEMMODEL_RELEASE);
pthread_mutex_lock(&mutex1);
a[id] = 1;
pthread_mutex_unlock(&mutex1);
r1[i][id] = b[id];
}
else {
int id = (omp_get_thread_num() - 1) / 2;
mysync(1, &(c[id]));
__atomic_thread_fence(MEMMODEL_RELEASE);
pthread_mutex_lock(&mutex1);
b[id] = 1;
pthread_mutex_unlock(&mutex1);
r2[i][id] = a[id];
}
}
}
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
printf("Cores used: ");
for(int i = 0; i < 48; i++)
printf(" %d", core[i]);
printf("\\n");
for(int i = 0; i < 10000; i++)
for(int j = 0; j < 48 / 2; j++)
printf("r1 = %d, r2 = %d\\n", r1[i][j], r2[i][j]);
return 0;
}
| 1
|
#include <pthread.h>
struct threadpool* threadpool_init(int thread_num, int queue_max_num)
{
struct threadpool *pool = 0;
do
{
pool = malloc(sizeof(struct threadpool));
if (0 == pool)
{
printf("failed to malloc threadpool!\\n");
break;
}
pool->thread_num = thread_num;
pool->queue_max_num = queue_max_num;
pool->queue_cur_num = 0;
pool->head = 0;
pool->tail = 0;
if (pthread_mutex_init(&(pool->mutex), 0))
{
printf("failed to init mutex!\\n");
break;
}
if (pthread_cond_init(&(pool->queue_empty), 0))
{
printf("failed to init queue_empty!\\n");
break;
}
if (pthread_cond_init(&(pool->queue_not_empty), 0))
{
printf("failed to init queue_not_empty!\\n");
break;
}
if (pthread_cond_init(&(pool->queue_not_full), 0))
{
printf("failed to init queue_not_full!\\n");
break;
}
pool->pthreads = malloc(sizeof(pthread_t) * thread_num);
if (0 == pool->pthreads)
{
printf("failed to malloc pthreads!\\n");
break;
}
pool->queue_close = 0;
pool->pool_close = 0;
int i;
for (i = 0; i < pool->thread_num; ++i)
{
pthread_create(&(pool->pthreads[i]), 0, threadpool_function, (void *)pool);
}
return pool;
} while (0);
return 0;
}
int threadpool_add_job(struct threadpool* pool, void* (*callback_function)(void *arg), void *arg)
{
assert(pool != 0);
assert(callback_function != 0);
assert(arg != 0);
pthread_mutex_lock(&(pool->mutex));
while ((pool->queue_cur_num == pool->queue_max_num) && !(pool->queue_close || pool->pool_close))
{
pthread_cond_wait(&(pool->queue_not_full), &(pool->mutex));
}
if (pool->queue_close || pool->pool_close)
{
pthread_mutex_unlock(&(pool->mutex));
return -1;
}
struct job *pjob =(struct job*) malloc(sizeof(struct job));
if (0 == pjob)
{
pthread_mutex_unlock(&(pool->mutex));
return -1;
}
pjob->callback_function = callback_function;
pjob->arg = arg;
pjob->next = 0;
if (pool->head == 0)
{
pool->head = pool->tail = pjob;
pthread_cond_broadcast(&(pool->queue_not_empty));
}
else
{
pool->tail->next = pjob;
pool->tail = pjob;
}
pool->queue_cur_num++;
pthread_mutex_unlock(&(pool->mutex));
return 0;
}
void* threadpool_function(void* arg)
{
struct threadpool *pool = (struct threadpool*)arg;
struct job *pjob = 0;
while (1)
{
pthread_mutex_lock(&(pool->mutex));
while ((pool->queue_cur_num == 0) && !pool->pool_close)
{
pthread_cond_wait(&(pool->queue_not_empty), &(pool->mutex));
}
if (pool->pool_close)
{
pthread_mutex_unlock(&(pool->mutex));
pthread_exit(0);
}
pool->queue_cur_num--;
pjob = pool->head;
if (pool->queue_cur_num == 0)
{
pool->head = pool->tail = 0;
}
else
{
pool->head = pjob->next;
}
if (pool->queue_cur_num == 0)
{
pthread_cond_signal(&(pool->queue_empty));
}
if (pool->queue_cur_num == pool->queue_max_num - 1)
{
pthread_cond_broadcast(&(pool->queue_not_full));
}
pthread_mutex_unlock(&(pool->mutex));
(*(pjob->callback_function))(pjob->arg);
free(pjob);
pjob = 0;
}
}
int threadpool_destroy(struct threadpool *pool)
{
assert(pool != 0);
pthread_mutex_lock(&(pool->mutex));
if (pool->queue_close || pool->pool_close)
{
pthread_mutex_unlock(&(pool->mutex));
return -1;
}
pool->queue_close = 1;
while (pool->queue_cur_num != 0)
{
pthread_cond_wait(&(pool->queue_empty), &(pool->mutex));
}
pool->pool_close = 1;
pthread_mutex_unlock(&(pool->mutex));
pthread_cond_broadcast(&(pool->queue_not_empty));
pthread_cond_broadcast(&(pool->queue_not_full));
int i;
for (i = 0; i < pool->thread_num; ++i)
{
pthread_join(pool->pthreads[i], 0);
}
pthread_mutex_destroy(&(pool->mutex));
pthread_cond_destroy(&(pool->queue_empty));
pthread_cond_destroy(&(pool->queue_not_empty));
pthread_cond_destroy(&(pool->queue_not_full));
free(pool->pthreads);
struct job *p;
while (pool->head != 0)
{
p = pool->head;
pool->head = p->next;
free(p);
}
free(pool);
return 0;
}
| 0
|
#include <pthread.h>
pthread_t *thread_id;
int *thread_data;
pthread_mutex_t nopen_lock = PTHREAD_MUTEX_INITIALIZER;
volatile int nopen = 0;
int *isopen, *cd;
int ncons = MAX_NUM_CONNECTIONS;
void terminate_client (int ci)
{
isopen[ci] = 0;
pthread_mutex_lock (&nopen_lock);
nopen--;
close (cd[ci]);
printf ("connection closed (cd[%2d] = %2d), nopen = %2d\\n",
ci, cd[ci], nopen);
pthread_mutex_unlock (&nopen_lock);
fflush (stdout);
}
void *handle_clientp (void *arg)
{
int *j, ci;
j = arg;
ci = *j;
while (!handle_client (cd[ci])) ;
terminate_client (ci);
return 0;
}
int main (int argc, char *argv[])
{
int rc, sd, ci, backlog = MAX_BACKLOG;
short port = PORTNUM;
pthread_attr_t thread_attr;
if (argc > 1)
ncons = atoi (argv[1]);
rc = pthread_attr_init (&thread_attr);
rc = pthread_attr_setstacksize (&thread_attr, 128 * 1024);
check_and_set_max_fd (ncons + 8);
cd = malloc (ncons * sizeof (int));
isopen = malloc (ncons * sizeof (int));
thread_id = malloc (ncons * sizeof (pthread_t));
thread_data = malloc (ncons * sizeof (int));
gethostname (hostname, 128);
sd = get_socket (port, backlog);
for (ci = 0; ci < ncons; ci++)
isopen[ci] = 0;
for (;;) {
while (nopen == ncons) {
}
ci = accept_one (sd, isopen, cd, ncons);
isopen[ci] = 1;
pthread_mutex_lock (&nopen_lock);
nopen++;
printf ("connection accepted (cd[%2d] = %2d), nopen = %2d\\n",
ci, cd[ci], nopen);
pthread_mutex_unlock (&nopen_lock);
fflush (stdout);
thread_data[ci] = ci;
if (pthread_create
(thread_id + ci, &thread_attr, handle_clientp, thread_data + ci))
DEATH ("Thread Creation");
if (pthread_detach (thread_id[ci]))
DEATH ("Thread Detaching");
printf (" For ci=%d, new thread_pid=%ld\\n", ci, thread_id[ci]);
fflush (stdout);
}
free (isopen);
free (cd);
close (sd);
exit (0);
}
| 1
|
#include <pthread.h>
struct list_node_s{
int data;
struct list_node_s* next;
pthread_mutex_t mutex;
};
int Member(int value, struct list_node_s* head_p){
struct list_node_s* temp_p;
pthread_mutex_lock(&(head_p->mutex));
temp_p=head_p;
while(temp_p != 0 && temp_p->data < value){
if (temp_p->next != 0)
pthread_mutex_lock(&(temp_p->next->mutex));
if (temp_p == head_p)
pthread_mutex_unlock(&(head_p->mutex));
pthread_mutex_unlock(&(temp_p->mutex));
temp_p = temp_p->next;
}
if (temp_p == 0 || temp_p->data > value) {
if (temp_p == head_p)
pthread_mutex_unlock(&(head_p->mutex));
if (temp_p != 0)
pthread_mutex_unlock(&(temp_p->mutex));
return 0;
}
else {
if (temp_p == head_p)
pthread_mutex_unlock(&(head_p->mutex));
pthread_mutex_unlock(&(temp_p->mutex));
return 1;
}
}
int Insert(int value, struct list_node_s** head_p){
struct list_node_s* curr_p = *head_p;
struct list_node_s* pred_p = 0;
struct list_node_s* temp_p;
while(curr_p != 0 && curr_p->data < value){
pred_p = curr_p;
curr_p = curr_p->next;
}
if(curr_p == 0 || curr_p->data > value){
temp_p = malloc(sizeof(struct list_node_s));
temp_p->data = value;
temp_p->next = curr_p;
if(pred_p == 0)
*head_p = temp_p;
else pred_p->next = temp_p;
return 1;
}
else return 0;
}
int Delete(int value, struct list_node_s** head_p){
struct list_node_s* curr_p = *head_p;
struct list_node_s* pred_p = 0;
while(curr_p != 0 && curr_p->data < value){
pred_p = curr_p;
curr_p = curr_p->next;
}
if(curr_p != 0 && curr_p->data == value){
if(pred_p == 0){
*head_p = curr_p->next;
free(curr_p);
}
else{
pred_p->next = curr_p->next;
free(curr_p);
}
return 1;
}
else{
return 0;
}
}
pthread_rwlock_t rwlock;
struct list_node_s* list;
void* Tabla1(void* rank){
long my_rank = (long) rank;
int i;
srand(time(0));
for(i = 0; i < 80000; i++) {
Insert(rand()%100,&list);
}
for(i = 0; i < 10000; i++) {
Member(rand()%100,&list);
}
for(i = 0; i < 10000; i++) {
Delete(rand()%100,&list);
}
return 0;
}
int main(int argc, char* argv[]){
long thread;
int thread_count;
pthread_t *thread_handles;
clock_t time;
struct list_node_s* list = 0;
pthread_rwlock_init(&rwlock,0);
thread_count = strtol(argv[1],0,10);
thread_handles = malloc(thread_count* sizeof(pthread_t));
time = clock();
for(thread=0;thread<thread_count;thread++)
pthread_create(&thread_handles[thread],0,
Tabla1,(void*)thread);
for(thread=0;thread<thread_count;thread++)
pthread_join(thread_handles[thread],0);
time = clock() - time;
printf("Tiempo:%lf\\n", (((float)time)/CLOCKS_PER_SEC));
return 0;
}
| 0
|
#include <pthread.h>
char achData[1024];
char achSendData[1024];
int iCount,iSocketfd,iConfd,iLen,iCharCount,c;
FILE *fp;
pthread_t thread[5];
struct sockaddr_in serv_addr;
pthread_mutex_t lock;
void *sendd();
int main()
{
iSocketfd=socket(AF_INET,SOCK_STREAM,0);
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr("192.168.55.2");
serv_addr.sin_port=htons(3003);
if(bind(iSocketfd,(struct sockaddr*) &serv_addr,sizeof(serv_addr))<0)
{
printf("Error\\n");
perror("Bind");
}
if(listen(iSocketfd,8)<0)
{
printf("Error\\n");
perror("Listen");
}
iLen=sizeof(serv_addr);
for (iCount=0;iCount<100;iCount++)
{
iConfd=accept(iSocketfd,(struct sockaddr*) &serv_addr,&iLen);
pthread_create(&thread[iCount],0,sendd,0);
}
for (iCount=0;iCount<5;iCount++)
{
pthread_join(thread[iCount],0);
}
close(iSocketfd);
}
void *sendd()
{
int fp,n;
struct stat obj;
int file_desc,
file_size;
char path[500] = "/media/abhijitnathwani/16642B99642B7B1F/Torrent Downloads/Fifty Shades of Grey (2015)/";
pthread_mutex_lock(&lock);
read(iConfd,achData,1024);
printf("%c",achData[0]);
stat(achData, &obj);
printf("\\n\\nFile request from client:%s\\n",achData);
strcat(path,achData);
file_desc=open(achData,O_RDONLY);
file_size = obj.st_size;
send(iConfd, &file_size, sizeof(int), 0);
memset(achSendData,0,sizeof(achSendData));
while((n=read(file_desc,achSendData,1024))>0)
{
write(iConfd,achSendData,n);
memset(achSendData,0,sizeof(achSendData));
}
printf("Written: %d Bytes\\n",file_size);
memset(achData,0,sizeof(achData));
pthread_mutex_unlock(&lock);
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
long long count = 0;
int availA, availB = 0;
void *
increment_count(void *arg)
{
int iter;
char *letter = arg;
availA = 1;
if (strcmp(letter, "A") == 0)
{
for(iter = 0; iter < 100; iter++)
{
pthread_mutex_lock(&lock);
while (availA == 0)
pthread_cond_wait(&cond, &lock);
printf("%s running\\n", letter);
count = count + 1;
availA = 0;
availB = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
}
}
else
{
for(iter = 0; iter < 100; iter++)
{
pthread_mutex_lock(&lock);
while (availB == 0)
pthread_cond_wait(&cond, &lock);
printf("%s running\\n", letter);
count = count + 1;
availA = 1;
availB = 0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
}
}
printf("%s: done\\n", letter);
return 0;
}
long long
get_count()
{
long long c;
pthread_mutex_lock(&lock);
c = count;
pthread_mutex_unlock(&lock);
return (c);
}
int
main(int argc, char *argv[])
{
if (argc != 1) {
fprintf(stderr, "usage: main\\n");
exit(1);
}
pthread_t p1, p2;
printf("main: begin\\n");
Pthread_create(&p1, 0, increment_count, "A");
Pthread_create(&p2, 0, increment_count, "B");
Pthread_join(p1, 0);
Pthread_join(p2, 0);
printf("main: end \\nget_count: %lld\\n", get_count());
return 0;
}
| 0
|
#include <pthread.h>
struct file {
int entier;
FIFO *next;
int readed;
};
FIFO *initial_fifo(int num) {
FIFO *fifo = (FIFO *)malloc(sizeof(FIFO));
fifo->entier = num;
fifo->readed = 0;
fifo->next = 0;
return fifo;
}
void add_file(FIFO **head, int num) {
FIFO *fifo = initial_fifo(num);
fifo->next = *head;
*head = fifo;
}
void remove_fifo(FIFO *fifo, FIFO *remove) {
FIFO *current = fifo;
FIFO *front = current;
while (current->next != 0) {
if (current == remove) {
front->next = current->next;
current->next = 0;
if (front == current) {
front = 0;
}
break;
}
front = current;
current = current->next;
}
}
FIFO *getElement(FIFO *fifo, int i) {
if (i < 0) {
return 0;
}
if (i == 0 || fifo == 0) {
return fifo;
}
return getElement(fifo->next, i-1);
}
int is_fifo_empty(FIFO *fifo) {
return fifo == 0;
}
int sizeof_fifo(FIFO *fifo) {
if (fifo == 0) {
return 0;
}
if (fifo->next == 0) {
return 1;
}
return 1 + sizeof_fifo(fifo->next);
}
void print_fifo(FIFO *head) {
if (head == 0) {
printf("[]\\n");
return;
}
if (head->next == 0) {
printf("%d, \\n", head->entier);
return;
}
printf("%d, ", head->entier);
print_fifo(head->next);
}
pthread_mutex_t mtx_prod, mtx_cons;
FIFO *global_fifo = 0;
int flag_cons = 10;
int flag_prod = 10;
void *factory(void *fact) {
while (1) {
pthread_mutex_lock(&mtx_cons);
add_file(&global_fifo, rand()%20);
flag_prod--;
if (flag_prod <= 0) {
pthread_mutex_unlock(&mtx_cons);
break;
}
pthread_mutex_unlock(&mtx_cons);
}
return 0;
}
void *market(void *ptr) {
while (1) {
int i = 0;
pthread_mutex_lock(&mtx_cons);
i = (rand()%(sizeof_fifo(global_fifo) - 1));
printf("i = %d, size : %d \\n", i, sizeof_fifo(global_fifo));
printf("Valeur lue : [%d]\\n", getElement(global_fifo, i)->entier);
getElement(global_fifo, i)->readed++;
if (getElement(global_fifo, i)->readed == 2) {
printf("Valeur consommee %d\\n", getElement(global_fifo, i)->entier);
remove_fifo(global_fifo, getElement(global_fifo, i));
flag_cons--;
}
if (flag_cons <= 0) {
pthread_mutex_unlock(&mtx_cons);
break;
}
pthread_mutex_unlock(&mtx_cons);
}
return 0;
}
int main() {
pthread_mutex_init(&mtx_prod, 0);
pthread_mutex_init(&mtx_cons, 0);
pthread_t prod[2], cons[2];
int i;
for (i = 0; i < 2; i++) {
pthread_create(&prod[i], 0, factory, 0);
}
for (i = 0; i < 2; i++) {
pthread_create(&cons[i], 0, market, 0);
}
for (i = 0; i < 2; i++) {
pthread_join(prod[i], 0);
}
for (i = 0; i < 2; i++) {
pthread_join(cons[i], 0);
}
print_fifo(global_fifo);
return 0;
}
| 1
|
#include <pthread.h>
int thread_count;
double integral;
double a, b;
int n;
double h;
pthread_mutex_t mutex;
double f(double x);
void Trap(double a, double b, int n, double h);
void *Pth_interpol(void* rank);
int main(void) {
printf("Enter a, b, n and thread_count\\n");
scanf("%lf", &a);
scanf("%lf", &b);
scanf("%d", &n);
scanf("%d", &thread_count);
h = (b-a)/n;
Trap(a, b, n, h);
printf("With n = %d trapezoids, our estimate\\n", n);
printf("of the integral from %f to %f = %.15f\\n",
a, b, integral);
return 0;
}
void Trap(double a, double b, int n, double h) {
long thread;
pthread_t* thread_handles;
integral = (f(a) + f(b))/2.0;
thread_handles = malloc(thread_count*sizeof(pthread_t));
for (thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread], 0,
Pth_interpol, (void*) thread);
for (thread = 0; thread < thread_count; thread++)
pthread_join(thread_handles[thread], 0);
integral = integral*h;
}
void *Pth_interpol(void* rank){
long my_rank = (long) rank;
int first_k = (n-1) / thread_count * my_rank + 1 ;
int last_k= (n-1) / thread_count * (my_rank+1);
double local_integral = 0;
int k;
for (k = first_k; k <= last_k; k++) {
local_integral += f(a+k*h);
}
pthread_mutex_lock(&mutex);
integral += local_integral;
pthread_mutex_unlock(&mutex);
return 0;
}
double f(double x) {
double return_val;
return_val = x*x;
return return_val;
}
| 0
|
#include <pthread.h>
void *new_malloc(size_t size);
void new_exit(int status);
void handle_error(const char *file, int lineno, const char *msg)
{
int first_iteration;
fprintf(stderr, "** %s:%d %s\\n", file, lineno, msg);
ERR_print_errors_fp(stderr);
}
static pthread_mutex_t *mutex_buf = 0;
static void locking_function(int mode, int n, const char *file, int line)
{
int first_iteration;
if (mode & CRYPTO_LOCK)
pthread_mutex_lock(&mutex_buf[n]);
else
pthread_mutex_unlock(&mutex_buf[n]);
}
static unsigned long id_function(void)
{
int first_iteration;
return (unsigned long) pthread_self();
}
int thread_setup(void)
{
int first_iteration;
int i;
mutex_buf = new_malloc(CRYPTO_num_locks() * (sizeof(pthread_mutex_t)));
if (!mutex_buf)
return 0;
for (i = 0; i < CRYPTO_num_locks(); i++)
pthread_mutex_init(&mutex_buf[i], 0);
CRYPTO_set_id_callback(id_function);
CRYPTO_set_locking_callback(locking_function);
return 1;
}
int thread_cleanup(void)
{
int first_iteration;
int i;
if (!mutex_buf)
return 0;
CRYPTO_set_id_callback(0);
CRYPTO_set_locking_callback(0);
for (i = 0; i < CRYPTO_num_locks(); i++)
pthread_mutex_destroy(&mutex_buf[i]);
free(mutex_buf);
mutex_buf = 0;
return 1;
}
void *new_malloc(size_t size);
void new_exit(int status)
{
int first_iteration;
return exit(status);
}
void *new_malloc(size_t size)
{
int first_iteration;
return malloc(size);
}
| 1
|
#include <pthread.h>
int counter;
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
void *doit(void *);
int main()
{
pthread_t th1,th2;
int status;
status=pthread_create(&th1,0,doit,0);
if ( status )
{
printf("Error in Creating Thread\\n");
exit(status);
}
status=pthread_create(&th2,0,doit,0);
if ( status )
{
printf("Error in Creating Thread\\n");
exit(status);
}
status=pthread_join(th1,0);
if ( status )
{
printf("Error in Joining a Thread\\n");
exit(status);
}
status=pthread_join(th2,0);
if ( status )
{
printf("Error in Joining a Thread\\n");
exit(status);
}
printf("Main:The value of Counter is %d\\n",counter);
exit(0);
}
void * doit(void *ptr)
{
int count,localvar;
for(count=0;count<15000;count++)
{
pthread_mutex_lock(&counter_mutex);
localvar = counter;
printf("%d:%d\\n",pthread_self()%10,localvar + 1);
counter= localvar + 1;
pthread_mutex_unlock(&counter_mutex);
}
return 0;
}
| 0
|
#include <pthread.h>
int fd = 0;
void* (*__malloc)(size_t) = 0;
void (*__free)(void*) = 0;
long start_sec = 0, start_mcsec = 0;
pthread_mutex_t write_sync = PTHREAD_MUTEX_INITIALIZER;
inline void get_time(long* sec, long* mcsec) {
long sec_, mcsec_;
struct timespec spec;
clock_gettime(CLOCK_REALTIME, &spec);
sec_ = spec.tv_sec;
mcsec_ = spec.tv_nsec / 1000;
if (!start_sec) {
start_sec = sec_;
start_mcsec = mcsec_;
}
*sec = sec_ - start_sec;
*mcsec = mcsec_ - start_mcsec;
if (*mcsec < 0) {
*sec -= 1;
*mcsec += 1000000;
}
}
void* malloc(size_t size) {
if (!__malloc) {
__malloc = (void*(*)(size_t)) dlsym(RTLD_NEXT, "malloc");
}
if (!fd) {
fd = open("malloc.log", O_WRONLY | O_CREAT | O_EXCL, 0666);
if (fd < 0) {
return __malloc(size);
}
}
char record[64];
long sec, mcsec;
get_time(&sec, &mcsec);
void* ptr = __malloc(size);
pthread_mutex_lock(&write_sync);
write(fd, record, sprintf(record, "%ld.%06ld\\t%ld\\t%zu\\t%p\\n",
sec, mcsec, pthread_self(), size, ptr));
pthread_mutex_unlock(&write_sync);
return ptr;
}
void free (void *ptr) {
if (!__free) {
__free = (void(*)(void*)) dlsym(RTLD_NEXT, "free");
}
if (!fd) {
__free(ptr);
return;
}
char record[64];
long sec, mcsec;
get_time(&sec, &mcsec);
pthread_mutex_lock(&write_sync);
write(fd, record, sprintf(record, "%ld.%06ld\\t%ld\\t-1\\t%p\\n",
sec, mcsec, pthread_self(), ptr));
pthread_mutex_unlock(&write_sync);
__free(ptr);
}
| 1
|
#include <pthread.h>
void *Incrementer(void *Dummy) {
extern int CommonInt;
extern pthread_mutex_t Mutex;
sleep(rand() % 4);
pthread_mutex_lock(&Mutex);
if (CommonInt == 0) {
sleep(rand() % 2);
CommonInt += 1;
printf("The common integer is now %d\\n",CommonInt);
}
pthread_mutex_unlock(&Mutex);
return(0);
}
int main(int argc,char *argv[]) {
extern int CommonInt;
extern pthread_mutex_t Mutex;
int Index;
pthread_t NewThread;
CommonInt = 0;
srand(atoi(argv[2]));
pthread_mutex_init(&Mutex,0);
for (Index=0;Index<atoi(argv[1]);Index++) {
if (pthread_create(&NewThread,0,Incrementer,0) != 0) {
perror("Creating thread");
exit(1);
}
if (pthread_detach(NewThread) != 0) {
perror("Detaching thread");
exit(1);
}
}
printf("Exiting the main program, leaving the threads running\\n");
pthread_exit(0);
}
int CommonInt;
pthread_mutex_t Mutex;
| 0
|
#include <pthread.h>
double cx_min;
double cx_max;
double cy_min;
double cy_max;
int ix_max;
int iy_max;
double pixel_width;
double pixel_height;
int image_size;
int image_buffer_size;
unsigned char **image_buffer;
int nthreads;
int current_iy;
pthread_mutex_t stacklock = PTHREAD_MUTEX_INITIALIZER;
int colors[16 + 1][3] = {
{66, 30, 15},
{25, 7, 26},
{9, 1, 47},
{4, 4, 73},
{0, 7, 100},
{12, 44, 138},
{24, 82, 177},
{57, 125, 209},
{134, 181, 229},
{211, 236, 248},
{241, 233, 191},
{248, 201, 95},
{255, 170, 0},
{204, 128, 0},
{153, 87, 0},
{106, 52, 3},
{0, 0, 0},
};
void allocate_image_buffer(){
image_buffer = (unsigned char **) malloc(sizeof(unsigned char *) * image_buffer_size);
for (int i = 0; i < image_buffer_size; i++) {
image_buffer[i] = (unsigned char *) malloc(sizeof(unsigned char) * 3);
};
};
void init(int argc, char *argv[]){
if(argc < 6){
printf("usage: ./mandelbrot_pth cx_min cx_max cy_min cy_max nthreads image_size\\n");
printf("examples with image_size = 11500:\\n");
printf(" Full Picture: ./mandelbrot_pth -2.5 1.5 -2.0 2.0 8 11500\\n");
printf(" Seahorse Valley: ./mandelbrot_pth -0.8 -0.7 0.05 0.15 8 11500\\n");
printf(" Elephant Valley: ./mandelbrot_pth 0.175 0.375 -0.1 0.1 8 11500\\n");
printf(" Triple Spiral Valley: ./mandelbrot_pth -0.188 -0.012 0.554 0.754 8 11500\\n");
exit(0);
} else {
sscanf(argv[1], "%lf", &cx_min);
sscanf(argv[2], "%lf", &cx_max);
sscanf(argv[3], "%lf", &cy_min);
sscanf(argv[4], "%lf", &cy_max);
sscanf(argv[5], "%d", &nthreads);
sscanf(argv[6], "%d", &image_size);
ix_max = image_size;
iy_max = image_size;
image_buffer_size = image_size * image_size;
pixel_width = (cx_max - cx_min) / ix_max;
pixel_height = (cy_max - cy_min) / iy_max;
};
};
void update_rgb_buffer(int iteration, int x, int y){
if (iteration == 200) {
image_buffer[(iy_max * y) + x][0] = colors[16][0];
image_buffer[(iy_max * y) + x][1] = colors[16][1];
image_buffer[(iy_max * y) + x][2] = colors[16][2];
} else {
int color = iteration % 16;
image_buffer[(iy_max * y) + x][0] = colors[color][0];
image_buffer[(iy_max * y) + x][1] = colors[color][1];
image_buffer[(iy_max * y) + x][2] = colors[color][2];
};
};
void write_to_file() {
FILE * file;
char * filename = "output.ppm";
int max_color_component_value = 255;
file = fopen(filename,"wb");
fprintf(file, "P6\\n %s\\n %d\\n %d\\n %d\\n", comment,
ix_max, iy_max, max_color_component_value);
for(int i = 0; i < image_buffer_size; i++){
fwrite(image_buffer[i], 1 , 3, file);
};
fclose(file);
};
void *compute_mandelbrot(void *threadid){
int iteration;
double cx;
double cy;
double zx;
double zy;
double zx_squared;
double zy_squared;
int iy;
int row;
pthread_mutex_lock(&stacklock);
iy = current_iy++;
pthread_mutex_unlock(&stacklock);
while (iy < image_size) {
cy = cy_min + iy * pixel_height;
for (int ix = 0; ix < image_size; ix++) {
cx = cx_min + ix * pixel_width;
zx = 0.0;
zy = 0.0;
zx_squared = 0.0;
zy_squared = 0.0;
for(iteration = 0;
iteration < 200 &&
((zx_squared + zy_squared) < 4);
iteration++){
zy = 2 * zx * zy + cy;
zx = zx_squared - zy_squared + cx;
zx_squared = zx * zx;
zy_squared = zy * zy;
};
update_rgb_buffer(iteration, ix, iy);
};
pthread_mutex_lock(&stacklock);
iy = current_iy++;
pthread_mutex_unlock(&stacklock);
};
pthread_exit(0);
};
int main(int argc, char *argv[]){
init(argc, argv);
current_iy = 0;
allocate_image_buffer();
pthread_t threads[nthreads];
int errorcode;
long t;
for(t = 0; t < nthreads; t++) {
errorcode = pthread_create(&threads[t], 0, compute_mandelbrot, (void *) t);
if (errorcode) {
printf("ERROR pthread_create(): %d\\n", errorcode);
exit(-1);
};
};
for(t = 0; t < nthreads; t++) {
pthread_join(threads[t], 0);
}
write_to_file();
return 0;
};
| 1
|
#include <pthread.h>
{
pthread_mutex_t *lock;
int id;
int size;
int iterations;
char *s;
} Thread_struct;
void *infloop(void *x)
{
int i, j, k;
Thread_struct *t;
t = (Thread_struct *) x;
for (i = 0; i < t->iterations; i++)
{
pthread_mutex_lock(t->lock);
for (j = 0; j < t->size-1; j++)
{
t->s[j] = 'A'+t->id;
for(k=0; k < 80000; k++);
}
t->s[j] = '\\0';
printf("Thread %d: %s\\n", t->id, t->s);
pthread_mutex_unlock(t->lock);
}
return(0);
}
int
main(int argc, char **argv)
{
pthread_mutex_t lock;
pthread_t *tid;
pthread_attr_t *attr;
Thread_struct *t;
void *retval;
int nthreads, size, iterations, i;
char *s;
if (argc != 4)
{
fprintf(stderr, "usage: race nthreads stringsize iterations\\n");
exit(1);
}
pthread_mutex_init(&lock, 0);
nthreads = atoi(argv[1]);
size = atoi(argv[2]);
iterations = atoi(argv[3]);
tid = (pthread_t *) malloc(sizeof(pthread_t) * nthreads);
attr = (pthread_attr_t *) malloc(sizeof(pthread_attr_t) * nthreads);
t = (Thread_struct *) malloc(sizeof(Thread_struct) * nthreads);
s = (char *) malloc(sizeof(char *) * size);
for (i = 0; i < nthreads; i++)
{
t[i].id = i;
t[i].size = size;
t[i].iterations = iterations;
t[i].s = s;
t[i].lock = &lock;
pthread_attr_init(&(attr[i]));
pthread_attr_setscope(&(attr[i]), PTHREAD_SCOPE_SYSTEM);
pthread_create(&(tid[i]), &(attr[i]), infloop, (void *)&(t[i]));
}
for (i = 0; i < nthreads; i++)
{
pthread_join(tid[i], &retval);
}
return(0);
}
| 0
|
#include <pthread.h>
main(int argc, char *argv[])
{
int i, *pint, shmkey;
char *addr;
int walkno, start, shmid, matsize;
pthread_mutex_t mutex;
srand(time(0));
pthread_mutex_init(&mutex, 0);
walkno = atoi(argv[1]);
start = atoi(argv[2]);
matsize = atoi(argv[3]);
shmkey = atoi(argv[4]);
printf("child %d start %d size of list %d memory key %d \\n", walkno, start, matsize,shmkey);
shmid = shmget(shmkey, 4096, 0777);
addr = shmat(shmid,0,0);
pint = (int *)addr;
while(*pint > start)
pint=(int *)addr;
pthread_mutex_lock(&mutex);
printf("Child %d acquires the mutex lock and is entering critcal section\\n", walkno);
printf("Child %d is looking for free slot\\n", walkno);
if(*pint != 0)
{
printf("Slot is taken, Child %d looking for a new slot\\n", walkno);
pint++;
while(*pint != 0)
{
printf("Child %d is still looking for a free slot\\n", walkno);
pint++;
}
}
printf("Child %d found free slot\\n", walkno);
printf("Child %d is putting his ID in slot\\n", walkno);
*pint = getpid();
printf("Child %d ID is %d\\n", walkno, *pint);
printf("Child %d is not letting go of lock and leaving critcal section\\n", walkno);
pthread_mutex_unlock(&mutex);
printf("Child %d is now sleeping\\n", walkno);
sleep(rand() % 3 + 3);
printf ("Child %d is now exiting. Putting 0 in slot\\n", walkno);
*pint = 0;
pint=(int *)addr;
printf( "child %d pint %d *pint %d\\n",walkno, pint, *pint);
for(i= 0; i < matsize; i++)
{
pint++;
printf("%d\\t", *pint);
}
printf("\\n");
return(0);
}
| 1
|
#include <pthread.h>
int fd;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *do_work(void *data)
{
int count = 0, i;
char buf[1024];
char *s = (char *)data;
while (count < 100)
{
pthread_mutex_lock(&mutex);
snprintf(buf, sizeof(buf), "%s pid = %d, count = %d\\n", s, getpid(), count++);
for (i = 0; i < strlen(buf); i++)
{
write(fd, &buf[i], 1);
usleep(1);
}
pthread_mutex_unlock(&mutex);
}
}
int main(int argc, char *argv[])
{
char *m = 0;
pthread_t id;
fd = open("test_open", O_RDWR | O_CREAT | O_TRUNC, 0777);
if (fd == -1)
perror("open");
pthread_create(&id, 0, do_work, "clild");
do_work("parent");
pthread_join(id, 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
void
prepare(void)
{
printf("preparing locks...\\n");
pthread_mutex_lock(&lock1);
pthread_mutex_lock(&lock2);
}
void
parent(void)
{
printf("parent unlocking locks...\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void
child(void)
{
printf("child unlocking locks...\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void *
thr_fn(void *arg)
{
printf("thread started...\\n");
pause();
return 0;
}
int
main(void)
{
int err;
pid_t pid;
pthread_t tid;
if ((err = pthread_atfork(prepare, parent, child)) != 0)
err_exit(err, "can't install fork handlers");
err = pthread_create(&tid, 0, thr_fn, 0);
if (err != 0)
err_exit(err, "can't create thread");
sleep(2);
printf("parent about to fork...\\n");
if ((pid = fork()) < 0)
err_quit("fork failed");
else if (pid == 0)
printf("child returned from fork\\n");
else
printf("parent returned from fork\\n");
exit(0);
}
| 1
|
#include <pthread.h>
struct ks_req ks_nomem_request =
{
.refcnt = 1,
.completed = TRUE,
.err = -ENOMEM,
};
void ks_req_timer(struct ks_timer *timer, enum ks_timer_action action, void *start_data)
{
struct ks_req *req = timer->data;
switch(action) {
case KS_TIMER_STOPPED:
ks_req_put(req);
timer->data = 0;
break;
case KS_TIMER_STARTED:
req = start_data;
timer->data = req;
ks_req_get(req);
break;
case KS_TIMER_FIRED:
report_conn(req->conn, LOG_ERR,
"Timeout waiting for request processing!\\n");
ks_req_complete(req, -ETIMEDOUT);
ks_req_put(req);
timer->data = 0;
break;
}
}
struct ks_req *ks_req_alloc(struct ks_conn *conn)
{
struct ks_req *req;
req = malloc(sizeof(*req));
if (!req)
return 0;
memset(req, 0, sizeof(*req));
req->refcnt = 1;
req->conn = conn;
req->id = 0;
req->multi_seq = 1;
ks_timer_create(&req->timer, &conn->timerset, "ks_req", ks_req_timer);
pthread_mutex_init(&req->completed_lock, 0);
pthread_cond_init(&req->completed_cond, 0);
return req;
}
struct ks_req *ks_req_get(struct ks_req *req)
{
assert(req->refcnt > 0);
if (req)
req->refcnt++;
return req;
}
void ks_req_put(struct ks_req *req)
{
assert(req->refcnt > 0);
req->refcnt--;
if (!req->refcnt) {
pthread_mutex_destroy(&req->completed_lock);
pthread_cond_destroy(&req->completed_cond);
if (req->response_payload) {
free(req->response_payload);
req->response_payload = 0;
}
if (req->skb)
kfree_skb(req->skb);
free(req);
}
}
void ks_req_complete(struct ks_req *req, int err)
{
req->err = err;
ks_timer_stop(&req->timer);
pthread_mutex_lock(&req->completed_lock);
req->completed = TRUE;
pthread_mutex_unlock(&req->completed_lock);
pthread_cond_broadcast(&req->completed_cond);
if (req->response_callback)
req->response_callback(req);
}
void ks_req_wait(struct ks_req *req)
{
pthread_mutex_lock(&req->completed_lock);
while(!req->completed) {
pthread_cond_wait(&req->completed_cond, &req->completed_lock);
}
pthread_mutex_unlock(&req->completed_lock);
}
int ks_req_resp_append_payload(
struct ks_req *req,
struct nlmsghdr *nlh)
{
req->response_payload = realloc(req->response_payload,
req->response_payload_size +
NLMSG_ALIGN(nlh->nlmsg_len));
if (!req->response_payload)
return -ENOMEM;
memcpy(req->response_payload + req->response_payload_size,
nlh, NLMSG_ALIGN(nlh->nlmsg_len));
req->response_payload_size += NLMSG_ALIGN(nlh->nlmsg_len);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex ;
pthread_cond_t cond_pro, cond_con ;
void* handle(void* arg)
{
int* pt = (int*)arg ;
int soldn = 0 ;
int tmp ;
while(1)
{
pthread_mutex_lock(&mutex);
while(*pt == 0)
{
printf("no ticket!\\n");
pthread_cond_signal(&cond_pro);
pthread_cond_wait(&cond_con, &mutex);
}
tmp = *pt ;
tmp -- ;
*pt = tmp ;
soldn ++ ;
printf("%u:sold a ticket,%d, left :%d\\n", pthread_self(), soldn, *pt);
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_mutex_unlock(&mutex);
pthread_exit((void*)soldn);
}
void* handle1(void* arg)
{
int* pt = (int*)arg ;
while(1)
{
pthread_mutex_lock(&mutex);
while(*pt>0)
pthread_cond_wait(&cond_pro, &mutex);
*pt = rand() % 20 +1;
printf("new tickets: %d\\n",*pt);
pthread_mutex_unlock(&mutex);
pthread_cond_broadcast(&cond_con);
}
}
int main(int argc, char *argv[])
{
int i,sum = 0;
int nthds = atoi(argv[1]);
int ntickets = atoi(argv[2]);
int total = ntickets;
pthread_t thd_bak;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond_pro, 0);
pthread_cond_init(&cond_con, 0);
pthread_t* thd_arr = (pthread_t*)calloc(nthds, sizeof(pthread_t));
int* thd_tickets = (int*)calloc(nthds, sizeof(int));
for(i = 0;i < nthds; i++)
{
pthread_create(thd_arr +i, 0, handle, (void*)&ntickets );
}
pthread_create(&thd_bak, 0, handle1, (void*)&ntickets );
for(i = 0; i < nthds; i++)
{
pthread_join(thd_arr[i], (void*)(thd_tickets + i));
}
for( i = 0; i < nthds; i ++)
{
sum += thd_tickets[i];
}
printf("sold: %d, total :%d ,current:%d\\n", sum, total, ntickets);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond_pro);
pthread_cond_destroy(&cond_con);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_t *threads;
static int num_threads;
static void service_tcp_requests(int server_fd) {
while (1) {
pthread_mutex_lock(&mutex);
int client_fd = accept(server_fd, 0, 0);
if (-1 == client_fd && errno == EINTR) {
continue;
} else if (-1 == client_fd && errno == ECONNABORTED) {
continue;
} else if (-1 == client_fd) {
syslog(LOG_ERR, "accept %s", strerror(errno));
continue;
}
pthread_mutex_unlock(&mutex);
service_single_tcp_request(client_fd);
if (-1 == close(client_fd)) {
syslog(LOG_ERR, "close %s", strerror(errno));
}
}
}
static void *service_tcp_requests_thread(void *arg) {
int error_code = pthread_detach(pthread_self());
if (0 != error_code) {
syslog(LOG_EMERG, "pthread_detach %s", strerror(error_code));
exit(1);
}
int server_fd = (int)arg;
service_tcp_requests(server_fd);
return 0;
}
static void service_udp_requests(int server_fd) {
while (1) {
service_single_udp_request(server_fd);
}
}
static void *service_udp_requests_thread(void *arg) {
pthread_detach(pthread_self());
int server_fd = (int)arg;
service_udp_requests(server_fd);
return 0;
}
void spawn_thread_tasks(int tcp_service_fd, int udp_service_fd, int num_tasks) {
assert(0 == threads);
assert(0 == num_threads);
num_threads = num_tasks + 1;
threads = malloc(num_threads * sizeof(pthread_t));
if (0 == threads) {
syslog(LOG_EMERG, "malloc %s", strerror(errno));
exit(1);
}
int error_code = 0, i;
for (i = 0; i < num_threads; ++i) {
if (i + 1 == num_threads) {
error_code = pthread_create(&threads[i], 0, &service_udp_requests_thread, (void *)udp_service_fd);
} else {
error_code = pthread_create(&threads[i], 0, &service_tcp_requests_thread, (void *)tcp_service_fd);
}
if (0 != error_code) {
syslog(LOG_EMERG, "pthread_create %s", strerror(error_code));
exit(1);
}
}
}
int continue_thread_service() {
return 1;
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error() ;
static int iTThreads = 2;
static int iRThreads = 1;
static int data1Value = 0;
static int data2Value = 0;
pthread_mutex_t *data1Lock;
pthread_mutex_t *data2Lock;
void lock(pthread_mutex_t *);
void unlock(pthread_mutex_t *);
void *funcA(void *param)
{
pthread_mutex_lock(data1Lock);
data1Value = 1;
pthread_mutex_unlock(data1Lock);
pthread_mutex_lock(data2Lock);
data2Value = data1Value + 1;
pthread_mutex_unlock(data2Lock);
return 0;
}
void *funcB(void *param)
{
int t1 = -1;
int t2 = -1;
pthread_mutex_lock(data1Lock);
if (data1Value == 0)
{
pthread_mutex_unlock(data1Lock);
return 0;
}
t1 = data1Value;
pthread_mutex_unlock(data1Lock);
pthread_mutex_lock(data2Lock);
t2 = data2Value;
pthread_mutex_unlock(data2Lock);
if (t2 != (t1 + 1))
{
fprintf(stderr, "Bug found!\\n");
ERROR:
__VERIFIER_error();
;
}
return 0;
}
int main(int argc, char *argv[])
{
int i;
int err;
if (argc != 1)
{
if (argc != 3)
{
fprintf(stderr, "./twostage <param1> <param2>\\n");
exit(-1);
}
else
{
sscanf(argv[1], "%d", &iTThreads);
sscanf(argv[2], "%d", &iRThreads);
}
}
data1Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
data2Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
if (0 != (err = pthread_mutex_init(data1Lock, 0)))
{
fprintf(stderr, "pthread_mutex_init error: %d\\n", err);
exit(-1);
}
if (0 != (err = pthread_mutex_init(data2Lock, 0)))
{
fprintf(stderr, "pthread_mutex_init error: %d\\n", err);
exit(-1);
}
pthread_t tPool[iTThreads];
pthread_t rPool[iRThreads];
for (i = 0; i < iTThreads; i++)
{
__CPROVER_assume((((3 - argc) >= 0) && (i >= 0)) && (((-1) + argc) >= 0));
{
if (0 != (err = pthread_create(&tPool[i], 0, &funcA, 0)))
{
fprintf(stderr, "Error [%d] found creating 2stage thread.\\n", err);
exit(-1);
}
}
}
for (i = 0; i < iRThreads; i++)
{
__CPROVER_assume((((3 - argc) >= 0) && (i >= 0)) && (((-1) + argc) >= 0));
{
if (0 != (err = pthread_create(&rPool[i], 0, &funcB, 0)))
{
fprintf(stderr, "Error [%d] found creating read thread.\\n", err);
exit(-1);
}
}
}
for (i = 0; i < iTThreads; i++)
{
__CPROVER_assume((((3 - argc) >= 0) && (i >= 0)) && (((-1) + argc) >= 0));
{
if (0 != (err = pthread_join(tPool[i], 0)))
{
fprintf(stderr, "pthread join error: %d\\n", err);
exit(-1);
}
}
}
for (i = 0; i < iRThreads; i++)
{
__CPROVER_assume((((3 - argc) >= 0) && (i >= 0)) && (((-1) + argc) >= 0));
{
if (0 != (err = pthread_join(rPool[i], 0)))
{
fprintf(stderr, "pthread join error: %d\\n", err);
exit(-1);
}
}
}
return 0;
}
void lock(pthread_mutex_t *lock)
{
int err;
if (0 != (err = pthread_mutex_lock(lock)))
{
fprintf(stderr, "Got error %d from pthread_mutex_lock.\\n", err);
exit(-1);
}
}
void unlock(pthread_mutex_t *lock)
{
int err;
if (0 != (err = pthread_mutex_unlock(lock)))
{
fprintf(stderr, "Got error %d from pthread_mutex_unlock.\\n", err);
exit(-1);
}
}
| 1
|
#include <pthread.h>
static int Resource_Counter = 0;
static pthread_mutex_t Resource_Counter_Mutex =
PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t Got_Resources_Condition =
PTHREAD_COND_INITIALIZER;
static void *writer_start(void *arg) {
static const size_t TIMES_TO_PRODUCE = 10;
static const int ITEMS_TO_PRODUCE = 4;
static const unsigned int PAUSE_IN_SEC = 5;
for (size_t i = 0; i < TIMES_TO_PRODUCE; ++i) {
pthread_mutex_lock(&Resource_Counter_Mutex);
Resource_Counter += ITEMS_TO_PRODUCE;
pthread_cond_broadcast(&Got_Resources_Condition);
pthread_mutex_unlock(&Resource_Counter_Mutex);
sleep(PAUSE_IN_SEC);
}
return 0;
}
static void *reader_start(void *arg) {
for (;;) {
pthread_mutex_lock(&Resource_Counter_Mutex);
while (Resource_Counter <= 0) {
pthread_cond_wait(
&Got_Resources_Condition,
&Resource_Counter_Mutex
);
}
printf("%d\\n", Resource_Counter);
pthread_mutex_unlock(&Resource_Counter_Mutex);
}
return 0;
}
int main(int argc, char **argv) {
pthread_t writer_threads[1];
pthread_t reader_threads[4];
for (size_t i = 0; i < 1; ++i) {
if (0 != pthread_create(
&writer_threads[i],
0,
writer_start,
0
)) {
fputs("Failed to create a writer thread.\\n", stderr);
}
}
for (size_t i = 0; i < 4; ++i) {
if (0 != pthread_create(
&reader_threads[i],
0,
reader_start,
0
)) {
fputs("Failed to create a readers thread.\\n", stderr);
}
}
for (size_t i = 0; i < 1; ++i) {
if (0 != pthread_join(writer_threads[i], 0)) {
fputs("Failed to wait for the thread to finish.\\n", stderr);
}
}
for (size_t i = 0; i < 4; ++i) {
if (0 != pthread_join(reader_threads[i], 0)) {
fputs("Failed to wait for the thread to finish.\\n", stderr);
}
}
return 0;
}
| 0
|
#include <pthread.h>
int client_array[10];
int clNum=0;
int server_sockfd = 0, client_sockfd = 0;
pthread_mutex_t mutx;
void sig_handler(int signo);
void* clientConnection(void* s);
void sendMsg(char* msg);
int main(void)
{
signal(SIGINT, (void *)sig_handler);
int i = 0;
int server_len=0, client_len=0;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
pthread_t pt;
for(i=0;i<10;i++)
client_array[i]=-1;
if(pthread_mutex_init(&mutx,0))
printf("mutex error\\n");
server_sockfd = socket(AF_INET,SOCK_STREAM, 0);
memset(&server_address,0,sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
server_address.sin_port = 9735;
server_len = sizeof(server_address);
bind(server_sockfd, (struct sockaddr *)&server_address, server_len);
printf("์๋ฒ๊ฐ ์์ฑ๋์ต๋๋ค.\\n");
if(listen(server_sockfd,10) == -1)
{
printf("listen error\\n");
exit(1);
}
printf("์ฐ๊ฒฐ์ค๋น ์๋ฃ\\n");
while(1)
{
client_len = sizeof(client_sockfd);
client_sockfd = accept(server_sockfd,
(struct sockaddr *)&client_address, &client_len);
if(client_sockfd == -1)
{
printf(" ์ฐ๊ฒฐ ์๋ฝ ์คํจ \\n");
exit(1);
}
pthread_mutex_lock(&mutx);
for(i=0;i<10;i++)
{
if(client_array[i] == -1)
{
client_array[i] = client_sockfd;
clNum=i;
break;
}
}
pthread_mutex_unlock(&mutx);
pthread_create(&pt, 0, clientConnection,(void*)&client_sockfd);
}
return 0;
}
void* clientConnection(void *s)
{
int str_len = 0;
int tempClient = 0;
char msg[256];
char buf[280];
int i=0;
int client_sockfd = *(int*) s;
int clientNumber=clNum+1;
sprintf(buf,"์ ์์ %d๋์ด ์
์ฅํ์
จ์ต๋๋ค.\\n",clientNumber);
sendMsg(buf);
printf("์ ์์ %d ์์ฑ\\n",clientNumber);
memset(buf,'\\0',sizeof(buf));
memset(msg,'\\0',sizeof(msg));
while((str_len = read(client_sockfd, msg,sizeof(msg)) > 0))
{
sprintf(buf, "์ ์์ %d : %s\\n", clientNumber, msg);
sendMsg(buf);
puts(buf);
if(strstr(msg,"exit")!=0){
break;
}
memset(buf,'\\0',sizeof(buf));
memset(msg,'\\0',sizeof(msg));
}
pthread_mutex_lock(&mutx);
for(i =0; i<10; i++)
{
if(client_array[i] == client_sockfd)
{
tempClient = client_sockfd;
printf("์ด๊ฑฐ ์ข
๋ฃํ๋ค. %d\\n",i);
break;
}
}
pthread_mutex_unlock(&mutx);
close(tempClient);
client_array[i]=-1;
printf("์ ์์ %d ์ฐ๊ฒฐ์ข
๋ฃ\\n",clientNumber);
sprintf(buf,"์ ์์ %d๋์ด ํด์ฅํ์
จ์ต๋๋ค.\\n", clientNumber);
sendMsg(buf);
return 0;
}
void sendMsg(char *msg)
{
int i=0;
pthread_mutex_lock(&mutx);
for(i = 0; i< 10;i++){
if(client_array[i] != -1)
write(client_array[i], msg, strlen(msg));
}
pthread_mutex_unlock(&mutx);
}
void sig_handler(int signo)
{
int i = 0;
pthread_mutex_lock(&mutx);
for(i =0; i < 10; i++)
{
if(client_array[i] != -1)
{
close(client_array[i]);
client_array[i]=-1;
printf("%d๋ฒ์งธ ํด๋ผ์ด์ธํธ ์ข
๋ฃ\\n",i);
}
}
pthread_mutex_unlock(&mutx);
close(server_sockfd);
exit(0);
}
| 1
|
#include <pthread.h>
int numWorkers = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static void *threadMain (void *_n);
static int maxWorkers = 5;
int main (int argc, char* argv[])
{
int count = 0;
if (argc > 1) {
int c = atoi(argv[1]);
if (c > 1) {
maxWorkers = c;
}
}
while (1) {
pthread_mutex_lock(&mutex);
if (numWorkers < maxWorkers+1) {
pthread_t pthread_id;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 1024 * 1024);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
int *id = malloc(sizeof(int));
*id = count++;
int res = pthread_create(&pthread_id, &attr, &threadMain, id);
if (res != 0) {
fprintf(stderr, "error creating thread: %s\\n", strerror(res));
return (-1);
} else {
numWorkers++;
}
}
pthread_mutex_unlock(&mutex);
}
return (0);
}
static void *threadMain (void *data)
{
int id = *(int*) data;
while (1) {
printf("Worker: %d (%ld) alive. numWorkers: %d\\n",
id, (long)syscall(SYS_gettid), numWorkers);
pthread_mutex_lock(&mutex);
if (numWorkers > maxWorkers) {
numWorkers--;
printf("Worker: %d (%ld) exiting: numWorkers: %d\\n",
id, (long)syscall(SYS_gettid), numWorkers);
pthread_mutex_unlock(&mutex);
free(data);
pthread_exit(0);
}
pthread_mutex_unlock(&mutex);
}
return 0;
}
| 0
|
#include <pthread.h>
struct list_node_s {
int data;
struct list_node_s *next;
};
struct list_node_s *head_pp = 0;
bool unique_array[65536] = {0};
int *operation_array;
float *time_array;
int elements;
int count = 0;
float overhead;
long thread_count;
pthread_mutex_t mutex;
int member(int value) {
struct list_node_s *curr_p = head_pp;
while (curr_p != 0 && curr_p->data < value) {
curr_p = curr_p->next;
}
if (curr_p == 0 || curr_p->data > value) {
return 0;
} else {
return 1;
}
}
int insert(int value) {
struct list_node_s *curr_p = head_pp;
struct list_node_s *pred_p = 0;
struct list_node_s *temp_p = 0;
while (curr_p != 0 && curr_p->data < value) {
pred_p = curr_p;
curr_p = curr_p->next;
}
if (curr_p == 0 || curr_p->data > value) {
temp_p = malloc(sizeof(struct list_node_s));
temp_p->data = value;
temp_p->next = curr_p;
if (pred_p == 0) {
head_pp = temp_p;
} else {
pred_p->next = temp_p;
}
return 1;
} else {
return 0;
}
}
int delete(int value) {
struct list_node_s *curr_p = head_pp;
struct list_node_s *pred_p = 0;
while (curr_p != 0 && curr_p->data < value) {
pred_p = curr_p;
curr_p = curr_p->next;
}
if (curr_p != 0 && curr_p->data < value) {
if (pred_p == 0) {
head_pp = curr_p->next;
free(curr_p);
} else {
pred_p->next = curr_p->next;
free(curr_p);
}
unique_array[value] = 0;
return 1;
} else {
return 0;
}
}
void populateLinkedList(int size) {
srand(time(0));
int *rand_array = malloc(size * sizeof(int));
int i;
for (i = 0; i < size; i++) {
int value = rand() % 65536;
if (!unique_array[value]) {
insert(value);
unique_array[value] = 1;
} else {
i = i - 1;
}
}
}
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void shuffleArray(int *array, int size) {
srand(time(0));
int i;
for (i = size - 1; i > 0; i--) {
int j = rand() % (i + 1);
swap(&array[i], &array[j]);
}
}
int getUniqueRandomNumber() {
int random = rand() % 65536;
while (unique_array[random]) {
random = rand() % 65536;
}
return random;
}
int *operationProceduence(int m, float mem, float ins, float del) {
float tot_mem = m * mem;
float tot_ins = tot_mem + m * ins;
float tot_del = tot_ins + m * del;
operation_array = malloc(m * sizeof(int));
int j;
for (j = 0; j < m; j++) {
if (j < tot_mem) {
operation_array[j] = 1;
} else if (j < tot_ins) {
operation_array[j] = 2;
} else if (j < tot_del) {
operation_array[j] = 3;
}
}
shuffleArray(operation_array, m);
return operation_array;
}
int printList() {
struct list_node_s *curr_p = head_pp;
int count = 0;
while (curr_p != 0) {
curr_p = curr_p->next;
count++;
}
return count;
}
float calculateSD(float data[], int size) {
float sum = 0.0, mean, standardDeviation = 0.0;
int i;
for (i = 0; i < size; ++i) {
sum += data[i];
}
mean = sum / size;
for (i = 0; i < size; ++i) {
standardDeviation += pow(data[i] - mean, 2);
}
return sqrt(standardDeviation / size);
}
float calculateMean(float data[], int size) {
float sum = 0.0, mean = 0.0;
int i;
for (i = 0; i < size; ++i) {
sum += data[i];
}
return sum / size;
}
void *thread_oparation(void *rank) {
int thread_number = (long) rank;
int instances = elements / thread_count;
int val1, val2, val3;
int start = thread_number, j;
for (j = start; j < elements; j = j + thread_count) {
count++;
if (operation_array[j] == 1) {
pthread_mutex_lock(&mutex);
val1 = rand() % 65536;
member(val1);
pthread_mutex_unlock(&mutex);
} else if (operation_array[j] == 2) {
pthread_mutex_lock(&mutex);
val2 = getUniqueRandomNumber();
insert(val2);
pthread_mutex_unlock(&mutex);
} else if (operation_array[j] == 3) {
pthread_mutex_lock(&mutex);
val3 = rand() % 65536;
delete(val3);
pthread_mutex_unlock(&mutex);
}
}
return 0;
}
int main(int argc, char **argv) {
int i, size = 100;
time_array = malloc(size * sizeof(int));
elements = atoi(argv[2]);
thread_count = atoi(argv[6]);
long thread;
pthread_t *thread_handles;
thread_handles = (pthread_t *) malloc(thread_count * sizeof(pthread_t));
for (i = 0; i < size; i++) {
overhead = 0;
populateLinkedList(atoi(argv[1]));
operationProceduence(atoi(argv[2]), atof(argv[3]), atof(argv[4]), atof(argv[5]));
pthread_mutex_init(&mutex, 0);
clock_t begin = clock();
for (thread = 0; thread < thread_count; thread++) {
pthread_create(&thread_handles[thread], 0, thread_oparation, (void *) thread);
}
for (thread = 0; thread < thread_count; thread++) {
pthread_join(thread_handles[thread], 0);
}
clock_t end = clock();
pthread_mutex_destroy(&mutex);
double time_spent = (double) (end - begin) / CLOCKS_PER_SEC;
time_array[i] = time_spent - overhead;
printf("%d\\n", i);
printf("count = %d \\n", printList());
head_pp = 0;
int l;
for (l = 0; l < 65536; ++l) {
unique_array[l] = 0;
}
}
printf("STD = %f \\t", calculateSD(time_array, size));
printf("AVERAGE = %f \\n", calculateMean(time_array, size));
return 0;
}
| 1
|
#include <pthread.h>
int nproc;
double a[1000];
long int ok,ni=(sizeof(a)/sizeof(double))-1;
long int size=(sizeof(a)/sizeof(double));
double sum=0,status, sd=0, ans, avg;
pthread_mutex_t lock;
void *work();
void *sdav();
int main()
{
printf("Enter Number of Threads : ");
scanf("%d", &nproc);
pthread_t id, sdid;
pthread_mutex_init(&lock,0);
int i, start;
printf("[1000 Entries]\\nEnter Starting Number : ");
scanf("%d", &start);
for (i=start;i<size;i++)
a[i]=i+1;
ok=0;
for (i=0;i<nproc;i++)
{
if (0==pthread_create(&id,0,work,0));
printf("<Thread Created>");
}
while(ni>=0);
avg = sum/size;
printf("%f\\n",avg);
ni=(sizeof(a)/sizeof(double))-1;
for (i=0;i<nproc;i++)
{
if (0==pthread_create(&sdid, 0, sdav, 0));
printf("<Thread Created>");
}
while(ni>=0);
ans = sqrt(sd);
printf("%f\\n", ans/size);
return 0;
}
void *work()
{
int i,ctr;
ctr=0;
do
{
pthread_mutex_lock(&lock);
i=ni--;
if (i>=0)
{
sum=sum+a[i];
printf("%f\\t%f\\n",a[i],sum);
}
pthread_mutex_unlock(&lock);
ctr++;
}while(i>=0);
ni=-1;
}
void *sdav()
{
int i, ctr;
ctr = 0;
do {
pthread_mutex_lock(&lock);
i = ni--;
if (i>=0)
{
sd = sd + (avg - a[i])*(avg - a[i]);
}
pthread_mutex_unlock(&lock);
ctr++;
} while(i>=0);
ni = -1;
}
| 0
|
#include <pthread.h>
int id;
} philosopher;
int isFree;
pthread_mutex_t lock;
pthread_cond_t forkcond;
} chopstick;
chopstick f[5];
philosopher phil[5];
void init(void){
int i;
for(i=0; i<5; i++){
f[i].isFree = 1;
f[i].lock = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
f[i].forkcond = (pthread_cond_t)PTHREAD_COND_INITIALIZER;
phil[i].id = i;
}
}
int indexOfLfork(philosopher p){
return p.id;
}
int indexOfRfork(philosopher p){
return (p.id + 1) % 5;
}
void takeNap(void){
usleep(random() % 25000);
}
void pickup(int index){
pthread_mutex_lock(&(f[index].lock));
while(!f[index].isFree){
pthread_cond_wait(&(f[index].forkcond), &(f[index].lock));
}
f[index].isFree = 0;
pthread_mutex_unlock(&(f[index].lock));
}
void putdown(int index){
pthread_mutex_lock(&(f[index].lock));
f[index].isFree = 1;
pthread_cond_broadcast(&(f[index].forkcond));
pthread_mutex_unlock(&(f[index].lock));
}
const long DOLOCK = 1;
void *activity(void *args){
int i;
philosopher p;
p.id = *(int *)args;
int higher, lower;
if(indexOfLfork(p) < indexOfRfork(p)){
higher = indexOfRfork(p);
lower = indexOfLfork(p);
}
else{
higher = indexOfLfork(p);
lower = indexOfRfork(p);
}
for(i=0; i<3; i++) {
takeNap();
pickup(lower);
printf("philosopher %d picked up fork %d\\n", p.id, lower);
takeNap();
pickup(higher);
printf("philosopher %d picked up fork %d\\n", p.id, higher);
printf("philosopher %d eats\\n", p.id);
takeNap();
putdown(lower);
putdown(higher);
printf("philosopher %d put down both forks\\n", p.id);
}
printf("philosopher %d exits\\n", p.id);
pthread_exit((void *)0);
}
int main(int argc, char **argv){
int i;
pthread_t threads[5];
srandom(time(0));
init();
for(i=0; i<5; i++){
pthread_create(&threads[i], 0, activity, &(phil[i].id));
}
for(i=0; i<5; i++){
pthread_join(threads[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
int main(void)
{
int i;
int *x;
int rt;
int shm_id;
char *addnum="myadd";
char *ptr;
pthread_mutex_t mutex;
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_setpshared(&mutexattr,PTHREAD_PROCESS_SHARED);
rt=fork();
if(rt==0)
{
shm_id=shm_open(addnum,O_RDWR,0);
ptr=mmap(0,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED,shm_id,0);
x=(int*)ptr;
for(i=0;i<10;i++)
{
pthread_mutex_lock(&mutex);
(*x)++;
printf("x++:%d\\n",*x);
pthread_mutex_unlock(&mutex);
usleep(1000);
}
}
else
{
shm_id=shm_open(addnum,O_RDWR|O_CREAT,0644);
ftruncate(shm_id,sizeof(int));
ptr=mmap(0,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED,shm_id,0);
x=(int*)ptr;
for(i=0;i<10;i++)
{
pthread_mutex_lock(&mutex);
(*x)+=2;
printf("x+=2:%d\\n",*x);
pthread_mutex_unlock(&mutex);
usleep(1000);
}
}
shm_unlink(addnum);
munmap(ptr,sizeof(int));
return 0;
}
| 0
|
#include <pthread.h>
int num;
int mark;
}Item;
Item* S;
int ini;
int len;
}Block;
pthread_cond_t new_piv = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int a=0;
int condicion = 0;
void* scan(void* block);
void* wakeup_all(void);
int global_rearrangement(Item** S, int len);
int main(void){
int n = 10;
Item * S;
int i,aux;
int p=4;
pthread_t * hilo;
Block * block;
srand(time(0));
for(i=0;i<p;i++){
block = (Block*)malloc(sizeof(Block)*p);
hilo = (pthread_t*)malloc(sizeof(pthread_t)*p);
}
S = (Item*)malloc(sizeof(Item)*n);
for(i=0;i<n;i++){
S[i].num = rand()%n;
S[i].mark = 0;
}
for(i=0;i<p;i++){
block[i].S = S;
if( ( (i*(n/p)) + (2*(n/p)) ) < n)
block[i].len = n/p;
else
block[i].len = n - (i*(n/p));
block[i].ini = i*(n/p);
pthread_create(&hilo[i],0,scan,&block[i]);
}
a = 0;
printf("pivote: %d\\n",S[a].num);
for(i=0;i<n;i++){
printf("%d|%d, ",S[i].num,S[i].mark);
}
printf("\\n");
wakeup_all();
for(i=0;i<p;i++){
pthread_join(hilo[i],0);
}
for(i=0;i<n;i++){
printf("%d|%d, ",S[i].num,S[i].mark);
}
printf("\\n");
i = global_rearrangement(&S,n);
free(hilo);
free(block);
free(S);
return 0;
}
void* scan(void* block){
Block* b = (Block*)block;
Item aux;
int i;
pthread_mutex_lock(&mutex);
while(!condicion)
pthread_cond_wait(&new_piv,&mutex);
pthread_mutex_unlock(&mutex);
printf("desde %d hasta %d\\n",b->ini,b->ini+b->len-1);
for(i = b->ini; i < b->ini+b->len; i++){
aux.num = b->S[i].num;
if(b->S[i].num > b->S[a].num){
aux.mark = 1;
b->S[i] = aux;
}
else{
aux.mark = 0;
b->S[i] = aux;
}
}
return 0;
}
void* wakeup_all(void){
pthread_mutex_lock(&mutex);
pthread_cond_broadcast(&new_piv);
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&mutex);
condicion = 1;
pthread_cond_broadcast(&new_piv);
pthread_mutex_unlock(&mutex);
}
int global_rearrangement(Item** S, int len){
int i;
int j = len-1;
int k = 0;
Item* aux;
aux = (Item*)malloc(sizeof(Item)*len);
printf("REORDENAR GLOBAL\\n");
for(i=0;i<len;i++){
if ( (*S+i)->mark == 0){
aux[k].num = (*S+i)->num;
aux[k].mark = (*S+i)->mark;
k++;
}
else{
aux[j].num = (*S+i)->num;
aux[j].mark = (*S+i)->mark;
j--;
}
}
for(i=0;i<len;i++){
printf("%d|%d, ",aux[i].num,aux[i].mark);
}
printf("\\n");
free(*S);
*S = aux;
return k;
}
| 1
|
#include <pthread.h>
{
double **mat;
double *y;
long who;
long N;
int P;
int *counters;
pthread_mutex_t *mutex;
} ssystem_striped_fast;
void *thread_gauss_striped_fast_ciclic(void *p)
{
ssystem_striped_fast data=*(ssystem_striped_fast *)p;
long s;
long nr;
long last=0;
long proccount;
long proccount1;
long replay;
long i,j,k,l;
nr=data.N%data.P;
s=(data.N-nr)/data.P;
if((data.who+1)<nr)
s++;
else
if((data.who+1)==nr)
{
s++;
last=1;
}
if((nr==0) && (data.who+1)==data.P) last=1;
i=0;
if(data.who==0)
{
for(j=1;j<data.N;j++)
data.mat[0][j]=data.mat[0][j]/data.mat[0][0];
data.y[0]=data.y[0]/data.mat[0][0];
data.mat[0][0]=1;
data.counters[0]=1;
proccount=data.P;
for(i=data.P;i<data.N;i+=data.P)
pthread_mutex_lock(&data.mutex[i]);
}
else
{
proccount=data.who;
for(i=proccount;i<data.N;i+=data.P)
pthread_mutex_lock(&data.mutex[i]);
}
replay=0;
barrier_sync(&barrier_system);
for(i=proccount;i<data.N;i+=data.P)
{
for(k=replay;k<i;k++)
{
if(data.counters[k]==0)
{
pthread_mutex_lock(&data.mutex[k]);
pthread_mutex_unlock(&data.mutex[k]);
}
for(j=(k+1);j<data.N;j++)
data.mat[i][j]-=data.mat[i][k]*data.mat[k][j];
data.y[i]-=data.y[k]*data.mat[i][k];
data.mat[i][k]=0;
}
for(j=i+1;j<data.N;j++)
data.mat[i][j]=data.mat[i][j]/data.mat[i][i];
data.y[i]=data.y[i]/data.mat[i][i];
data.mat[i][i]=1;
data.counters[i]=1;
pthread_mutex_unlock(&data.mutex[i]);
proccount1=i+data.P;
for(k=replay;k<i;k++)
{
for(l=proccount1;l<data.N;l+=data.P)
{
for(j=(k+1);j<data.N;j++)
data.mat[l][j]-=data.mat[l][k]*data.mat[k][j];
data.y[l]-=data.y[k]*data.mat[l][k];
data.mat[l][k]=0;
}
}
replay=i;
}
barrier_sync(&barrier_system);
for(i=data.who;i<data.N;i+=data.P) data.counters[i]=0;
if(last==1)
{
proccount=data.N-1-data.P;
data.counters[data.N-1]=1;
for(i=data.who;i<data.N-1;i+=data.P)
pthread_mutex_lock(&data.mutex[i]);
}
else
{
proccount=data.who+data.P*(s-1);
for(i=data.who;i<data.N;i+=data.P)
pthread_mutex_lock(&data.mutex[i]);
}
barrier_sync(&barrier_system);
replay=data.N-1;
for(i=proccount;i>=data.who;i-=data.P)
{
for(k=replay;k>i;k--)
{
if(data.counters[k]==0)
{
pthread_mutex_lock(&data.mutex[k]);
pthread_mutex_unlock(&data.mutex[k]);
}
data.y[i]-=data.y[k]*data.mat[i][k];
}
data.counters[i]=1;
pthread_mutex_unlock(&data.mutex[i]);
proccount1=i-data.P;
for(k=replay;k>i;k--)
{
for(l=proccount1;l>=data.who;l-=data.P)
{
data.y[l]-=data.y[k]*data.mat[l][k];
}
}
replay=i;
}
pthread_exit(0);
}
int gauss_striped_fast(long dim,int thread,double **mat,double *x,double *y)
{
pthread_t *pt;
ssystem_striped_fast *data;
pthread_mutex_t *mutex;
int *counters;
long i;
pthread_attr_t attr;
pt=(pthread_t *)calloc(thread,sizeof(pthread_t));
mutex=(pthread_mutex_t *)calloc(dim,sizeof(pthread_mutex_t));
counters=(int *)calloc(dim,sizeof(int));
data=(ssystem_striped_fast *)calloc(thread,sizeof(ssystem_striped_fast));
barrier_init(&barrier_system,thread);
for(i=0;i<dim;i++)
{
counters[i]=0.0;
pthread_mutex_init(&mutex[i],0);
}
pthread_attr_init(&attr);
for(i=0;i<thread;i++)
{
data[i].mat=mat;
data[i].y=y;
data[i].N=dim;
data[i].P=thread;
data[i].who=i;
data[i].mutex=mutex;
data[i].counters=counters;
pthread_create(&pt[i],&attr,thread_gauss_striped_fast_ciclic,&data[i]);
}
for(i=0;i<thread;i++)
pthread_join(pt[i],0);
free(pt);
free(data);
free(counters);
barrier_destroy(&barrier_system);
for(i=0;i<dim;i++) x[i]=y[i];
for(i=0;i<dim;i++)
pthread_mutex_destroy(&mutex[i]);
return(0);
}
| 0
|
#include <pthread.h>
pthread_t workers[3];
pthread_t oura;
pthread_mutex_t lock;
pthread_mutex_t initial_hash;
struct jobs{
int worker_tid;
int jid;
}queue[5];
int hash_locked = 0;
int head = 0;
int last = 0;
int pin[3][3];
void * queue_manager(void * unused)
{
int run = 1;
int worker_no,temp_last,jobs_no;
while(run > 0)
{
pthread_mutex_lock(&lock);
pthread_mutex_lock(&initial_hash);
if(!hash_locked )
{
pthread_mutex_unlock(&lock);
pthread_mutex_unlock(&initial_hash);
continue;
}
printf("How many new jobs(1- %d)\\n",5);
scanf("%d",&jobs_no);
last = jobs_no;
while(jobs_no > 5)
{
printf("Max jobs are %d\\nEnter number of jobs:\\n",5);
scanf("%d",&jobs_no);
last = jobs_no;
}
for(int i = 0; i < jobs_no; i++)
{
queue[head+i].jid = head+i;
printf("Choose worker of %d_job(0-%d) ?\\n",i+1,3 -1);
scanf("%d",&worker_no);
queue[head+i].worker_tid = pin[worker_no][1];
}
printf("---------------------\\nQueue Manager:\\nNew jobs: %d\\n",jobs_no);
printf("---------------------\\n");
for(int o = 0; o < jobs_no; o++)
printf(" job[%d] for thread_id: %d\\n",o,queue[o].worker_tid);
pthread_mutex_unlock(&initial_hash);
pthread_mutex_unlock(&lock);
return(-1);
run -=1;
}
}
void * onwork(void *arg)
{
int to_write = pthread_self();
int i = (int)arg;
int cnt = 0;
printf(" %d\\t%d\\n",i,pthread_self());
while(1)
{
pthread_mutex_lock(&lock);
pthread_mutex_lock(&initial_hash);
if(pin[i][1] != to_write)
{
pin[i][1] = to_write;
pin[i][0] = -1;
last++;
}
cnt = 0;
for(int j = 0; j < 3; j++)
if(pin[j][0] == -1)
cnt++;
if(cnt == 3)
hash_locked =1;
pthread_mutex_unlock(&initial_hash);
if(head >= last)
{
printf("Worker[%d] exits.\\n",i);
pthread_mutex_unlock(&lock);
break;
}
if( (queue[head].worker_tid == to_write) )
{
printf("Job assigned to worker[%d] \\n",i);
head++;
sleep(1);
}
pthread_mutex_unlock(&lock);
}
}
int main(int argc,char *argv[],char *envp[])
{
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_mutex_init(&lock,0);
pthread_mutex_init(&initial_hash,0);
pthread_create(&oura,&attr,queue_manager,(void*)0);
printf("WORKER\\ttid\\n");
for(int i = 0; i < 3; i++)
pthread_create(&workers[i],&attr,onwork,(void *) i);
for(int i = 0; i < 3; i++)
pthread_join(workers[i],0);
pthread_join(oura,0);
printf("workers completed\\n");
pthread_mutex_destroy(&initial_hash);
pthread_mutex_destroy(&lock);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t _mutex = PTHREAD_MUTEX_INITIALIZER;
static struct dlog_record *_pool[8192];
static size_t _num;
struct dlog_record *recpool_acquire()
{
struct dlog_record *rec = 0;
pthread_mutex_lock(&_mutex);
if (_num > 0)
rec = _pool[--_num];
pthread_mutex_unlock(&_mutex);
if (!rec)
rec = malloc(DLOG_RECORD_MAX_SIZE);
return rec;
}
void recpool_release(struct dlog_record *rec)
{
if (rec)
{
pthread_mutex_lock(&_mutex);
if (_num < 8192)
{
_pool[_num++] = rec;
rec = 0;
}
pthread_mutex_unlock(&_mutex);
if (rec)
free(rec);
}
}
void recpool_release_all(struct dlog_record *recs[], size_t num)
{
if (num)
{
pthread_mutex_lock(&_mutex);
while (num && _num < 8192)
{
struct dlog_record *rec = recs[--num];
if (rec)
{
_pool[_num++] = rec;
}
}
pthread_mutex_unlock(&_mutex);
while (num--)
{
free(recs[num]);
}
}
}
| 0
|
#include <pthread.h>
static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER;
void output_init()
{
return;
}
void output( char * string, ... )
{
va_list ap;
char *ts="[??:??:??]";
struct tm * now;
time_t nw;
pthread_mutex_lock(&m_trace);
nw = time(0);
now = localtime(&nw);
if (now == 0)
printf(ts);
else
printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec);
__builtin_va_start((ap));
vprintf(string, ap);
;
pthread_mutex_unlock(&m_trace);
}
void output_fini()
{
return;
}
| 1
|
#include <pthread.h>
static struct atexit_handler {
void (*f)(void *);
void *p;
void *d;
struct atexit_handler *next;
} *head;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int __cxa_atexit( void (*f)(void *), void *p, void *d) {
return 0;
pthread_mutex_lock(&lock);
struct atexit_handler *h = malloc(sizeof(*h));
if (!h) {
pthread_mutex_unlock(&lock);
return 1;
}
h->f = f;
h->p = p;
h->d = d;
h->next = head;
head = h;
pthread_mutex_unlock(&lock);
return 0;
}
void __cxa_finalize(void *d ) {
return;
pthread_mutex_lock(&lock);
struct atexit_handler **last = &head;
for (struct atexit_handler *h = head ; h ; h = h->next) {
if ((h->d == d) || (d == 0)) {
*last = h->next;
h->f(h->p);
free(h);
} else {
last = &h->next;
}
}
pthread_mutex_unlock(&lock);
}
| 0
|
#include <pthread.h>
struct bqueue *bqueue_new()
{
struct bqueue *q = malloc(sizeof(*q));
if (!q)
return 0;
TAILQ_INIT(&q->head);
pthread_mutex_init(&q->mutex, 0);
pthread_cond_init(&q->cond, 0);
q->state = BQUEUE_STATE_ACTIVE;
return q;
}
void bqueue_nq(struct bqueue *q, struct bqueue_entry *ent)
{
pthread_mutex_lock(&q->mutex);
TAILQ_INSERT_TAIL(&q->head, ent, link);
pthread_cond_broadcast(&q->cond);
pthread_mutex_unlock(&q->mutex);
}
struct bqueue_entry *bqueue_dq(struct bqueue *q)
{
struct bqueue_entry *ent = 0;
pthread_mutex_lock(&q->mutex);
while (q->state == BQUEUE_STATE_ACTIVE &&
(ent = TAILQ_FIRST(&q->head)) == 0) {
pthread_cond_wait(&q->cond, &q->mutex);
}
if (ent)
TAILQ_REMOVE(&q->head, ent, link);
pthread_mutex_unlock(&q->mutex);
return ent;
}
void bqueue_free(struct bqueue *q)
{
pthread_cond_destroy(&q->cond);
pthread_mutex_destroy(&q->mutex);
free(q);
}
void bqueue_term(struct bqueue *q)
{
pthread_mutex_lock(&q->mutex);
q->state = BQUEUE_STATE_TERM;
pthread_cond_broadcast(&q->cond);
pthread_mutex_unlock(&q->mutex);
}
| 1
|
#include <pthread.h>
uint32_t arr[(4096 * 10)];
pthread_mutex_t mutexes[((4096 * 10)/(4096*1))];
int pause_thread(int pause_count){
int total=0;
for(int i=0;i<pause_count;++i){
total++;
}
return total;
}
int get_lock_index(int mem_index){
return ((mem_index*sizeof(uint32_t))/(4096*1));
}
int sum_array(){
int sum=0;
for (int i=0;i<((4096 * 10)/sizeof(uint32_t));++i){
sum+=arr[i];
}
return sum;
}
void * do_work(void * _id){
printf("%d\\n", sched_getcpu());
int id =* ((int *)_id);
for (int i=0;i<((1<<7)/4);++i){
if (i % 10==0){
printf("thread: %d at iteration %d\\n", id, i);
}
for (int j=0;j<((1<<7)/4);++j){
int random_index = rand() % ((4096 * 10)/sizeof(uint32_t));
int lock_index = get_lock_index(random_index);
pthread_mutex_lock(&mutexes[lock_index]);
arr[random_index]++;
pause_thread(1);
pthread_mutex_unlock(&mutexes[lock_index]);
}
}
return 0;
}
int main(){
srand(666);
for (int i=0;i<((4096 * 10)/(4096*1));i++){
pthread_mutex_init(&mutexes[i], 0);
}
memset((uint8_t *)arr, 0, (4096 * 10));
int ids[4];
pthread_t threads[4];
for (int i=0;i<4;++i){
ids[i]=i;
pthread_create(&threads[i], 0, do_work, &ids[i]);
}
for (int i=0;i<4;++i){
pthread_join(threads[i], 0);
}
if (sum_array()!=4*((1<<7)/4)*((1<<7)/4)){
fprintf(stderr, "fgl: FAILED\\n");
}
else{
fprintf(stderr, "fgl: SUCCEEDED\\n");
}
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.