text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
int pbs_sigjob_err(
int c,
char *jobid,
char *signal,
char *extend,
int *local_errno)
{
int rc = 0;
struct batch_reply *reply;
if ((jobid == (char *)0) || (*jobid == '\\0') ||
(signal == (char *)0) || (*signal == '\\0'))
return (PBSE_IVALREQ);
if ((c < 0) ||
(c >= PBS_NET_MAX_CONNECTIONS))
{
return(PBSE_IVALREQ);
}
if ((rc = PBSD_sig_put(c, jobid, signal, extend)) != 0)
return (rc);
pthread_mutex_lock(connection[c].ch_mutex);
reply = PBSD_rdrpy(local_errno, c);
PBSD_FreeReply(reply);
rc = connection[c].ch_errno;
pthread_mutex_unlock(connection[c].ch_mutex);
return(rc);
}
int pbs_sigjob(
int c,
char *jobid,
char *signal,
char *extend)
{
pbs_errno = 0;
return(pbs_sigjob_err(c, jobid, signal, extend, &pbs_errno));
}
int pbs_sigjobasync_err(
int c,
char *jobid,
char *signal,
char *extend,
int *local_errno)
{
int rc = 0;
struct batch_reply *reply;
if ((jobid == (char *)0) || (*jobid == '\\0') ||
(signal == (char *)0) || (*jobid == '\\0'))
return (PBSE_IVALREQ);
if ((c < 0) ||
(c >= PBS_NET_MAX_CONNECTIONS))
{
return(PBSE_IVALREQ);
}
if ((rc = PBSD_async_sig_put(c, jobid, signal, extend)) != 0)
return (rc);
pthread_mutex_lock(connection[c].ch_mutex);
reply = PBSD_rdrpy(local_errno, c);
PBSD_FreeReply(reply);
rc = connection[c].ch_errno;
pthread_mutex_unlock(connection[c].ch_mutex);
return(rc);
}
int pbs_sigjobasync(
int c,
char *jobid,
char *signal,
char *extend)
{
pbs_errno = 0;
return(pbs_sigjobasync_err(c, jobid, signal, extend, &pbs_errno));
}
| 1
|
#include <pthread.h>
int counter = 0;
pthread_mutex_t mux;
void thread1(void *arg);
void thread2(void *arg);
int main(int argc,char *argv[])
{
pthread_t id1,id2;
unsigned int slp1,slp2;
pthread_mutex_init(&mux,0);
printf("please print the sleep time slp1 and slp2:\\n");
scanf("%d",&slp1);
scanf("%d",&slp2);
pthread_create(&id1,0,(void *)thread1,(void *)&slp1);
pthread_create(&id2,0,(void *)thread2,(void *)&slp2);
pthread_join(id1,0);
pthread_join(id2,0);
printf("最后的 counter 值%d\\n",counter);
exit(0);
}
void thread1(void *arg)
{
int i,val;
for(i=1;i<=5;i++){
pthread_mutex_lock(&mux);
val=++counter;
printf("第一个线程:第 %d 次循环,第一次引用counter=%d\\n",i,counter);
sleep(*((unsigned int *)arg));
counter=val;
pthread_mutex_unlock(&mux);
}
}
void thread2(void *arg)
{
int i,val;
for(i=1;i<=5;i++){
pthread_mutex_lock(&mux);
val=++counter;
sleep(*((unsigned int *)arg));
printf("第二个线程:第 %d 次循环,counter=%d\\n",i,counter);
counter=val;
pthread_mutex_unlock(&mux);
}
}
| 0
|
#include <pthread.h>
char name[80];
int amount;
} BANK_CLIENT, *BANK_CLIENT_PTR;
static BANK_CLIENT bank[2]= {{"yossi", 250}, {"shimon", 400}};
pthread_mutex_t mutex1;
void *tradeForever(){
int sums[] ={50, 100, -75, -50, 125, -100, -50};
int n = 7;
int index = 0;
int amountToTrade;
int fromAmount;
while(1){
amountToTrade = sums[index];
index = (index + 1)%n;
pthread_mutex_lock(&mutex1);
bank[0].amount -= amountToTrade;
bank[1].amount += amountToTrade;
pthread_mutex_unlock(&mutex1);
}
}
void *checkTotalAmount(){
while(1){
pthread_mutex_lock(&mutex1);
printf("Total amount in Bank: %d\\n", bank[0].amount + bank[1].amount);
pthread_mutex_unlock(&mutex1);
}
}
int main(){
pthread_t thread_no1, thread_no2;
pthread_create(&thread_no1, 0, tradeForever, 0);
pthread_create(&thread_no2,0, checkTotalAmount,0);
pthread_join( thread_no1, 0);
pthread_join( thread_no2, 0);
}
| 1
|
#include <pthread.h>
{
bool done;
pthread_mutex_t mutex;
} shared_data;
static shared_data* data = 0;
void initialise_shared()
{
int prot = PROT_READ | PROT_WRITE;
int flags = MAP_SHARED | MAP_ANONYMOUS;
data = mmap(0, sizeof(shared_data), prot, flags, -1, 0);
assert(data);
data->done = 0;
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&data->mutex, &attr);
}
void run_child()
{
while (1)
{
puts("child waiting. .. ");
usleep(50000);
pthread_mutex_lock(&data->mutex);
puts(" MUTEX: locked");
if (data->done) {
pthread_mutex_unlock(&data->mutex);
puts(" MUTEX: unlocked");
puts("got done!");
break;
}
pthread_mutex_unlock(&data->mutex);
puts(" MUTEX: unlocked");
}
puts("child exiting ..");
}
void run_parent(pid_t pid)
{
puts("parent sleeping ..");
sleep(2);
puts("setting done ..");
pthread_mutex_lock(&data->mutex);
puts(" MUTEX: locked");
data->done = 1;
pthread_mutex_unlock(&data->mutex);
puts(" MUTEX: unlocked");
waitpid(pid, 0, 0);
puts("parent exiting ..");
}
int main(int argc, char** argv)
{
initialise_shared();
pid_t pid = fork();
if (!pid) {
run_child();
}
else {
run_parent(pid);
}
munmap(data, sizeof(data));
return 0;
}
| 0
|
#include <pthread.h>
const int MAX_THREADS = 1024;
pthread_mutex_t mutex;
long thread_count;
long n;
int in_circle;
void* pi_calc(void* rank);
void Get_args(int argc, char* argv[]);
void Usage(char* prog_name);
double random_double()
{
double base = (double) rand() / 32767;
return (base * 2) - 1;
}
int main(int argc, char* argv[]) {
long i;
srand(time(0));
pthread_t* thread_handles;
Get_args(argc, argv);
thread_handles = malloc(sizeof(pthread_t) * thread_count);
printf("Making %ld threads, %ld throws\\n", thread_count, n);
pthread_mutex_init(&mutex, 0);
for (i = 0; i < thread_count; i++) {
long* index = malloc(sizeof(long));
*index = i;
pthread_create(&thread_handles[i], 0, pi_calc, index);
}
for (i = 0; i < thread_count; i++) {
pthread_join(thread_handles[i], 0);
}
printf("Estimate of pi: %lf\\n", 4.0 * (((double) in_circle) / ((double) n)));
pthread_mutex_destroy(&mutex);
return 0;
}
void* pi_calc(void* rank) {
int i;
int local_in_circle = 0;
long local_tosses = n / thread_count;
double x, y, distance_squared;
for (i = 0; i < local_tosses; i++) {
x = random_double();
y = random_double();
distance_squared = (x * x) + (y * y);
if (distance_squared <= 1) {
local_in_circle++;
}
}
pthread_mutex_lock(&mutex);
in_circle += local_in_circle;
pthread_mutex_unlock(&mutex);
return 0;
}
void Get_args(int argc, char* argv[]) {
if (argc != 3) Usage(argv[0]);
thread_count = strtol(argv[1], 0, 10);
n = strtol(argv[2], 0, 10);
if (thread_count <= 0) Usage(argv[0]);
}
void Usage(char* prog_name) {
fprintf(stderr, "usage: %s <k> <n>\\n", prog_name);
fprintf(stderr, " k should be the number of threads\\n n should be the number of throws\\n");
exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t request_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
pthread_cond_t got_request = PTHREAD_COND_INITIALIZER;
int num_requests = 0;
int done_creating_requests = 0;
struct request {
int number;
struct request* next;
};
struct request* requests = 0;
struct request* last_request = 0;
void
add_request(int request_num,
pthread_mutex_t* p_mutex,
pthread_cond_t* p_cond_var)
{
int rc;
struct request* a_request;
a_request = (struct request*)malloc(sizeof(struct request));
if (!a_request) {
fprintf(stderr, "add_request: out of memory\\n");
exit(1);
}
a_request->number = request_num;
a_request->next = 0;
rc = pthread_mutex_lock(p_mutex);
if (num_requests == 0) {
requests = a_request;
last_request = a_request;
}
else {
last_request->next = a_request;
last_request = a_request;
}
num_requests++;
rc = pthread_mutex_unlock(p_mutex);
rc = pthread_cond_signal(p_cond_var);
}
struct request*
get_request(pthread_mutex_t* p_mutex)
{
int rc;
struct request* a_request;
rc = pthread_mutex_lock(p_mutex);
if (num_requests > 0) {
a_request = requests;
requests = a_request->next;
if (requests == 0) {
last_request = 0;
}
num_requests--;
}
else {
a_request = 0;
}
rc = pthread_mutex_unlock(p_mutex);
return a_request;
}
void
handle_request(struct request* a_request, int thread_id)
{
struct timespec delay;
if (a_request) {
printf("Thread '%d' handled request '%d'\\n",
thread_id, a_request->number);
fflush(stdout);
}
}
void*
handle_requests_loop(void* data)
{
int rc;
struct request* a_request;
int thread_id = *((int*)data);
rc = pthread_mutex_lock(&request_mutex);
while (1) {
if (num_requests > 0) {
a_request = get_request(&request_mutex);
if (a_request) {
handle_request(a_request, thread_id);
free(a_request);
}
}
else {
if (done_creating_requests) {
pthread_mutex_unlock(&request_mutex);
printf("thread '%d' exiting\\n", thread_id);
fflush(stdout);
pthread_exit(0);
}
else {
}
rc = pthread_cond_wait(&got_request, &request_mutex);
}
}
}
int
main(int argc, char* argv[])
{
int i;
int thr_num[3];
pthread_t p_threads[3];
struct timespec delay;
for (i=0; i<3; i++) {
thr_num[i] = i;
pthread_create(&p_threads[i], 0, handle_requests_loop, (void*)&thr_num[i]);
}
for (i=0; i<600; i++) {
add_request(i, &request_mutex, &got_request);
if (rand() > 3*(32767/4)) {
delay.tv_sec = 0;
delay.tv_nsec = 1;
nanosleep(&delay, 0);
}
}
{
int rc;
rc = pthread_mutex_lock(&request_mutex);
done_creating_requests = 1;
rc = pthread_cond_broadcast(&got_request);
rc = pthread_mutex_unlock(&request_mutex);
}
for (i=0; i<3; i++) {
void* thr_retval;
pthread_join(p_threads[i], &thr_retval);
}
printf("Glory, we are done.\\n");
return 0;
}
| 0
|
#include <pthread.h>
void NouveauRapport()
{
FILE* fichierIndex = 0;
int caractereActuel = 0;
int cpt=0;
char chaine[10000];
int unite;
int dixaine;
int add;
if(pthread_mutex_init(&mutexRapport, 0) == -1)
{
perror("Initialisation mutex de synchro de machine\\n");
exit(1);
}
fichierIndex = fopen("Rapport/Index_Rapport.txt", "a+");
if (fichierIndex != 0)
{
do
{
caractereActuel = fgetc(fichierIndex);
chaine[cpt]=caractereActuel;
cpt++;
} while (caractereActuel != EOF);
if (cpt < 3)
{
add=1;
}
else
{
dixaine=(int)chaine[cpt-4];
dixaine=dixaine-'0';
if(dixaine > 9 || dixaine < 1)
{dixaine=0;}
unite=(int)chaine[cpt-3];
unite=unite-'0';
add=unite+(10*dixaine)+1;
}
fprintf(fichierIndex, "Rapport %d\\n", add);
fclose(fichierIndex);
sprintf(nomRapport, "Rapport/Rapport%d.txt", add);
fichierRapport = fopen(nomRapport, "a+");
fprintf(fichierRapport, "Rapport %d\\n\\n", add);
fclose(fichierRapport);
}
}
void EcrireRapport(char * MessageRapport)
{
pthread_mutex_lock(&mutexRapport);
fichierRapport = fopen(nomRapport, "a+");
fprintf(fichierRapport,"%s", MessageRapport);
fclose(fichierRapport);
pthread_mutex_unlock(&mutexRapport);
}
| 1
|
#include <pthread.h>
static uint32_t crc32_table[256];
static uint64_t crc64_table[256];
static bool crc_initialized = 0;
pthread_mutex_t crc_init_lock = PTHREAD_MUTEX_INITIALIZER;
static void crc_init_tables (void) {
pthread_mutex_lock (&crc_init_lock);
if (crc_initialized) {
pthread_mutex_unlock (&crc_init_lock);
return;
}
for (int i = 0 ; i < 256 ; i++) {
uint32_t r = i;
for (int j = 0; j < 8; j++) {
if (r & 1)
r = (r >> 1) ^ 0x04C11DB7l;
else
r >>= 1;
}
crc32_table[i] = r;
}
for (int i = 0 ; i < 256 ; i++) {
uint64_t r = i;
for (int j = 0; j < 8; j++) {
if (r & 1)
r = (r >> 1) ^ 0xC96C5795D7870F42ul;
else
r >>= 1;
}
crc64_table[i] = r;
}
crc_initialized = 1;
pthread_mutex_unlock (&crc_init_lock);
}
uint32_t hioi_crc32 (uint8_t *buf, size_t length) {
uint32_t crc = 0;
if (!crc_initialized)
crc_init_tables ();
for (int i = 0 ; i < length ; i++)
crc = (crc >> 8) ^ crc32_table[(crc ^ buf[i]) & 0xff];
return crc;
}
uint64_t hioi_crc64 (uint8_t *buf, size_t length) {
uint64_t crc = 0;
if (!crc_initialized)
crc_init_tables ();
for (int i = 0 ; i < length ; ++i)
crc = (crc >> 8) ^ crc64_table[(crc ^ buf[i]) & 0xff];
return crc;
}
| 0
|
#include <pthread.h>
const int MAX_THREADS = 1024;
const int MSG_MAX = 100;
void* send_msg(void* rank);
void get_args(int argc, char* argv[]);
void usage(char* prog_name);
long thread_count;
int message_available;
char** messages;
pthread_mutex_t mutex;
int main(int argc, char* argv[] ) {
long thread;
pthread_t* thread_handles;
get_args(argc, argv);
thread_handles = malloc(thread_count * sizeof(pthread_t) );
messages = malloc(thread_count * sizeof(char*) );
for(thread = 0; thread < thread_count; thread++) {
messages[thread] = 0;
}
pthread_mutex_init(&mutex, 0);
message_available = 0;
for(thread = 0; thread < thread_count; thread++) {
pthread_create(&thread_handles[thread], 0, send_msg, (void*) thread);
}
for(thread = 0; thread < thread_count; thread++) {
pthread_join(thread_handles[thread], 0);
}
pthread_mutex_destroy(&mutex);
for(thread = 0; thread < thread_count; thread++) {
free(messages[thread]);
}
free(messages);
free(thread_handles);
return 0;
}
void* send_msg(void* rank) {
long my_rank = (long) rank;
long dest = (my_rank + 1) % thread_count;
char* my_msg = malloc(MSG_MAX * sizeof(char) );
while(1) {
pthread_mutex_lock(&mutex);
if(my_rank % 2 != 0) {
if(message_available) {
printf("Consumer thread %ld message: %s\\n", my_rank, messages[my_rank] );
message_available = 0;
pthread_mutex_unlock(&mutex);
break;
}
} else {
sprintf(my_msg, "Hello to %ld from producer thread %ld", dest, my_rank);
messages[dest] = my_msg;
message_available = 1;
pthread_mutex_unlock(&mutex);
break;
}
pthread_mutex_unlock(&mutex);
}
return 0;
}
void get_args(int argc, char* argv[]) {
if (argc != 2) {
usage(argv[0]);
}
thread_count = strtol(argv[1], 0, 10);
if (thread_count <= 0 || thread_count > MAX_THREADS) {
usage(argv[0]);
}
}
void usage(char* prog_name) {
fprintf(stderr, "usage: %s <number of threads>\\n", prog_name);
exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
int n = 0;
int threads;
int iters;
int count;
void *thread(void *vargp) {
printf("Start new Thread\\n");
srand(n);
int i = 0;
int k = 0;
for (i = 0; i < count; i++) {
float x = rand() / 1.0 / 32767;
float y = rand() / 1.0 / 32767;
if (x * x + y * y < 1) {
k++;
}
}
pthread_mutex_lock(&mutex);
n += k;
pthread_mutex_unlock(&mutex);
pthread_exit((void*)1);
}
int main(int argc, char** argv) {
if (argc == 3) {
threads = atoi(argv[1]);
iters = atoi(argv[2]);
count = iters / threads;
pthread_t* array = malloc(threads * sizeof(pthread_t));
pthread_mutex_init(&mutex,0);
int i;
for (i = 0; i < threads; i++) {
if (pthread_create(&array[i], 0, thread, 0) != 0) {
perror("Cannot create thread");
return -1;
}
}
pthread_mutex_destroy(&mutex);
for (i = 0; i < threads; i++) {
pthread_join(array[i], 0);
}
printf("Total circle is %d \\n", n);
float pi = 4.0 * n / iters;
printf("PI is %1.6f \\n", pi);
free(array);
} else {
perror("Wrong Count of Arguments");
return -1;
}
}
| 0
|
#include <pthread.h>
static int glob = 0;
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static void *thread_routine(void *arg)
{
int loc, j;
for (j = 0; j < 10000000; j++) {
pthread_mutex_lock(&mtx);
loc = glob;
loc++;
glob = loc;
pthread_mutex_unlock(&mtx);
}
return 0;
}
int main(int argc, char *argv[])
{
pthread_t t1, t2;
int s;
s = pthread_create(&t1, 0, thread_routine, 0);
if (s != 0)
do { errno = s; perror("pthread_create"); exit(1); } while (0);
s = pthread_create(&t2, 0, thread_routine, 0);
if (s != 0)
do { errno = s; perror("pthread_create"); exit(1); } while (0);
s = pthread_join(t1, 0);
if (s != 0)
do { errno = s; perror("pthread_join"); exit(1); } while (0);
s = pthread_join(t2, 0);
if (s != 0)
do { errno = s; perror("pthread_join"); exit(1); } while (0);
printf("glob = %d\\n", glob);
exit(0);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t _auth_shadow_mutex = PTHREAD_MUTEX_INITIALIZER;
int shadow_user_pass_verify(const char *username, const char *password) {
int errsv = 0;
struct spwd *spentp = 0;
size_t salt_len = 0;
char *salt = 0, *local_hash = 0, *user_hash = 0;
if (!username || !password) {
errno = EINVAL;
return -1;
}
pthread_mutex_lock(&_auth_shadow_mutex);
spentp = getspnam(username);
errsv = errno;
pthread_mutex_unlock(&_auth_shadow_mutex);
if (!spentp) {
errno = errsv;
return -1;
}
if (!(local_hash = strrchr(spentp->sp_pwdp, '$'))) {
if (strlen(spentp->sp_pwdp) <= 2) {
errno = ENOSYS;
return -1;
}
salt_len = 2;
} else {
local_hash ++;
salt_len = local_hash - spentp->sp_pwdp;
}
if (!(salt = malloc(salt_len + 1)))
return -1;
memcpy(salt, spentp->sp_pwdp, salt_len);
salt[salt_len] = 0;
pthread_mutex_lock(&_auth_shadow_mutex);
if (!(user_hash = crypt(password, salt))) {
errsv = errno;
free(salt);
errno = errsv;
return -1;
}
pthread_mutex_unlock(&_auth_shadow_mutex);
free(salt);
if (strcmp(spentp->sp_pwdp, user_hash)) {
errno = EINVAL;
return -1;
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex_lock;
sem_t students_sem;
sem_t ta_sem;
int waiting_students;
void* programming();
void* helping();
unsigned int ranTime(int id);
int seed = 23;
int officeClosed = 0;
int student_num;
} student_info;
int main() {
printf("CS149 SleepingTA from Jennifer Earley\\n");
pthread_t *students[4];
student_info *infor[4];
waiting_students = 0;
sem_init(&students_sem, 0, 0);
sem_init(&ta_sem, 0, 1);
pthread_mutex_init(&mutex_lock, 0);
pthread_t *taThread = (pthread_t *) malloc(sizeof(pthread_t));
pthread_create(taThread, 0, helping, 0);
for(int i = 0; i < 4; i++) {
pthread_t *studentThread = (pthread_t *) malloc(sizeof(pthread_t));
students[i] = studentThread;
student_info *studentInfo = (student_info *) malloc(sizeof(student_info));
studentInfo->student_num = i + 1;
infor[i] = studentInfo;
pthread_create(studentThread, 0, programming, studentInfo);
}
for(int i = 0; i < 4; i++){
pthread_join(*students[i], 0);
free(students[i]);
free(infor[i]);
}
officeClosed = 1;
sem_post(&students_sem);
pthread_join(*taThread, 0);
free(taThread);
sem_destroy(&students_sem);
sem_destroy(&ta_sem);
pthread_mutex_destroy(&mutex_lock);
}
void* helping(void * p) {
sem_wait(&students_sem);
while(!officeClosed) {
pthread_mutex_lock(&mutex_lock);
waiting_students--;
pthread_mutex_unlock(&mutex_lock);
int time = ranTime(seed);
sleep(time);
sem_post(&ta_sem);
sem_wait(&students_sem);
}
return 0;
}
void* programming(void * s){
student_info * data = (student_info *) s;
int studentNum = data->student_num;
int helps = 0;
int time1 = ranTime(studentNum);
printf("Student %d programming for %d seconds\\n", studentNum, time1);
sleep(time1);
while(helps < 2){
pthread_mutex_lock(&mutex_lock);
if(waiting_students < 2){
waiting_students++;
sem_post(&students_sem);
pthread_mutex_unlock(&mutex_lock);
sem_wait(&ta_sem);
printf("Student %d receiving help\\n", studentNum);
helps++;
} else {
pthread_mutex_unlock(&mutex_lock);
printf("Student %d will try later\\n", studentNum);
int time2 = ranTime(studentNum);
printf("Student %d programming for %d seconds\\n", studentNum, time2);
sleep(time2);
}
}
return 0;
}
unsigned int ranTime(int id){
unsigned int t = (unsigned int) id * seed;
return (unsigned int) (rand_r(&t) % 3) + 1;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cnd = PTHREAD_COND_INITIALIZER;
int toexit = 0;
void * start_thread(void * arg) {
pthread_mutex_lock(&mtx);
while(0 == toexit) {
do{ printf("ptid [%ld] -- ", (long int)pthread_self()); printf("wait..."); printf("\\n"); }while(0);
pthread_cond_wait(&cnd, &mtx);
}
pthread_mutex_unlock(&mtx);
do{ printf("ptid [%ld] -- ", (long int)pthread_self()); printf("\\033[0;31mget toexit, and exit\\033[0m"); printf("\\n"); }while(0);
return 0;
}
int main(int argc, char * argv[]) {
pthread_t ptl[5];
int i = 0;
for(i = 0; i < 5; i++) {
if(0 != pthread_create(&ptl[i], 0, start_thread, 0)) {
do{ printf("ptid [%ld] -- ", (long int)pthread_self()); printf("create thread faild"); printf("\\n"); }while(0);
return -1;
}
}
while(1) {
int lives = 0;
for(i = 0; i < 5; i++) {
if(0 == pthread_kill(ptl[i], 0)) {
lives ++;
}
}
if(lives <= 0) {
do{ printf("ptid [%ld] -- ", (long int)pthread_self()); printf("no sub threads alive"); printf("\\n"); }while(0);
break;
}
do{ printf("ptid [%ld] -- ", (long int)pthread_self()); printf("\\033[0;32mEnter to continue, 'q' or 'Q' to quit :\\033[0m "); printf("\\n"); }while(0);
char c = getchar();
pthread_mutex_lock(&mtx);
if('Q' == c || 'q' == c) {
toexit = 1;
do{ printf("ptid [%ld] -- ", (long int)pthread_self()); printf("set toexit"); printf("\\n"); }while(0);
}
pthread_mutex_unlock(&mtx);
int err = 0;
err = pthread_cond_signal(&cnd);
if(0 != err) {
do{ printf("ptid [%ld] -- ", (long int)pthread_self()); printf("send signal faild"); printf("\\n"); }while(0);
} else {
do{ printf("ptid [%ld] -- ", (long int)pthread_self()); printf("send signal success"); printf("\\n"); }while(0);
}
usleep(10000);
}
void * st = 0;
for(i = 0; i < 5; i++) {
pthread_join(ptl[i], &st);
}
do{ printf("ptid [%ld] -- ", (long int)pthread_self()); printf("main over"); printf("\\n"); }while(0);
return 0;
}
| 0
|
#include <pthread.h>
int num = 0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void *print1(void *arg){
pthread_mutex_lock(&mutex);
++num;
printf("%d\\n", num);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
return 0;
}
void *print2(void *arg){
pthread_mutex_lock(&mutex);
while(num != 1)
pthread_cond_wait(&cond, &mutex);
++num;
printf("%d\\n", num);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
return 0;
}
void *print3(void *arg){
pthread_mutex_lock(&mutex);
while(num != 2)
pthread_cond_wait(&cond, &mutex);
++num;
printf("%d\\n", num);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
return 0;
}
void *print4(void *arg){
pthread_mutex_lock(&mutex);
while(num != 3)
pthread_cond_wait(&cond, &mutex);
++num;
printf("%d\\n", num);
pthread_mutex_unlock(&mutex);
return 0;
}
int main(int argc, char* argv[])
{
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
pthread_t tid1,tid2,tid3,tid4;
pthread_create(&tid1, 0, print1, 0);
pthread_create(&tid2, 0, print2, 0);
pthread_create(&tid3, 0, print3, 0);
pthread_create(&tid4, 0, print4, 0);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
pthread_join(tid3, 0);
pthread_join(tid4, 0);
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
static struct camData lastCamData[MAX_TRI];
static struct hokData lastHokData[NBR_ROBOTS];
static int last_cam_nbr = 0;
static long last_hok_timestamp = 0;
static pthread_mutex_t mutexCam, mutexHok;
void pushCamData(struct camData *data, int nbr) {
pthread_mutex_lock(&mutexCam);
last_cam_nbr = nbr;
memcpy(lastCamData, data, nbr*sizeof(struct camData));
pthread_mutex_unlock(&mutexCam);
}
void pushHokData(struct hokData *data, long timestamp) {
pthread_mutex_lock(&mutexHok);
last_hok_timestamp = timestamp;
memcpy(lastHokData, data, NBR_ROBOTS*sizeof(struct hokData));
pthread_mutex_unlock(&mutexHok);
}
int switchOrdre(unsigned char ordre, unsigned char *argv, unsigned char *ret, bool doublon){
int ret_size = 0;
switch(ordre){
case T_GET_HOKUYO: {
struct hokData data[NBR_ROBOTS];
int i;
long timestamp = 0;
pthread_mutex_lock(&mutexHok);
memcpy(data, lastHokData, NBR_ROBOTS*sizeof(struct hokData));
timestamp = last_hok_timestamp;
pthread_mutex_unlock(&mutexHok);
ltob(timestamp, ret);
ret+=4;
for (i=0; i<NBR_ROBOTS; i++) {
itob(data[i].x, ret);
itob(data[i].y, ret+2);
ret += 4;
}
ret_size = 20;
break;
}
case T_GET_CAM: {
static int datas_left = 0;
static int current_index = 0;
static struct camData data[MAX_TRI];
if (datas_left == 0) {
pthread_mutex_lock(&mutexCam);
if (last_cam_nbr > 0) {
memcpy(data, lastCamData, last_cam_nbr*sizeof(struct camData));
} else {
data[0].x = -1;
data[0].y = -1;
}
datas_left = last_cam_nbr;
pthread_mutex_unlock(&mutexCam);
current_index = 0;
}
datas_left--;
itob(data[current_index].x, ret);
itob(data[current_index].y, ret+2);
itob(datas_left, ret+4);
if (datas_left > 0) {
current_index++;
} else {
datas_left = 0;
}
ret_size = 6;
break;
}
default:
return -1;
}
return ret_size;
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
void prepare(void){
printf("prepare() lock....\\n");
pthread_mutex_lock(&lock1);
pthread_mutex_lock(&lock2);
}
void parent(void){
printf("parent() ....\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void child(void){
printf("child() ....\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void* thr_fn(void* arg){
printf("thread started ...\\n");
printf("pause done \\n");
return 0;
}
int main(void){
int err;
pid_t pid;
pthread_t tid;
prepare();
err = pthread_create(&tid,0,thr_fn,0);
if(err !=0)
err_exit(err,"pthread_create error");
sleep(2);
printf("parent about to fork....\\n");
if((pid=fork()) <0)
err_quit("fork failed");
else if(pid == 0){
pthread_mutex_lock(&lock1);
pthread_mutex_lock(&lock2);
printf("child returned from fork \\n");
}else{
pthread_mutex_lock(&lock1);
pthread_mutex_lock(&lock2);
printf("parent returned from fork \\n");
}
exit(0);
}
| 1
|
#include <pthread.h>
pthread_t t1,t2;
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER,
lock2 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t e1 = PTHREAD_COND_INITIALIZER,
e2 = PTHREAD_COND_INITIALIZER;
void* run1 (void *args)
{
int i;
pthread_mutex_lock (&lock1);
pthread_cond_wait (&e1,&lock1);
pthread_mutex_unlock (&lock1);
pthread_cancel (t2);
for (i=0;i<1000000;i++) {
fprintf (stderr,"*");
}
fprintf (stderr,"t1 terminated\\n");
return 0;
}
void* run2 (void *args)
{
int i;
pthread_mutex_lock (&lock2);
pthread_cond_wait (&e2,&lock2);
pthread_mutex_unlock (&lock2);
pthread_cancel (t1);
for (i=0;i<1000000;i++) {
}
return 0;
}
void* gen (void *args)
{
usleep (1);
pthread_mutex_lock (&lock1);
pthread_mutex_lock (&lock2);
pthread_cond_broadcast (&e1);
fprintf (stdout,"broadcast e1\\n");
pthread_cond_broadcast (&e2);
fprintf (stdout,"broadcast e2\\n");
pthread_mutex_unlock (&lock1);
pthread_mutex_unlock (&lock2);
return 0;
}
int main (void)
{
int c, *cell = &c;
pthread_t g;
pthread_create (&t1,0,run1,0);
pthread_create (&t2,0,run2,0);
pthread_create (&g,0,gen,0);
pthread_join (t1,(void**)cell);
pthread_join (t2,(void**)cell);
fprintf (stdout,"exit\\n");
exit (0);
return 0;
}
| 0
|
#include <pthread.h>
int thread_count;
double a, b, h;
int n, local_n;
pthread_mutex_t mutex;
double total;
void *Thread_work(void* rank);
double Trap(double local_a, double local_b, int local_n,
double h);
double f(double x);
int main(int argc, char** argv) {
long i;
pthread_t* thread_handles;
total = 0.0;
if (argc != 2) {
fprintf(stderr, "usage: %s <numero de threads>\\n", argv[0]);
exit(0);
}
thread_count = strtol(argv[1], 0, 10);
printf("Ingresa a, b, n\\n");
scanf("%lf %lf %d", &a, &b, &n);
h = (b-a)/n;
local_n = n/thread_count;
thread_handles = malloc (thread_count*sizeof(pthread_t));
pthread_mutex_init(&mutex, 0);
for (i = 0; i < thread_count; i++) {
pthread_create(&thread_handles[i], 0, Thread_work,
(void*) i);
}
for (i = 0; i < thread_count; i++) {
pthread_join(thread_handles[i], 0);
}
printf("Con n = %d trapezoides, la estimacion\\n",
n);
printf("de la integral desde %f y %f = %19.15e\\n",
a, b, total);
pthread_mutex_destroy(&mutex);
free(thread_handles);
return 0;
}
void *Thread_work(void* rank) {
double local_a;
double local_b;
double my_int;
long my_rank = (long) rank;
local_a = a + my_rank*local_n*h;
local_b = local_a + local_n*h;
my_int = Trap(local_a, local_b, local_n, h);
pthread_mutex_lock(&mutex);
total += my_int;
pthread_mutex_unlock(&mutex);
return 0;
}
double Trap(
double local_a ,
double local_b ,
int local_n ,
double h ) {
double integral;
double x;
int i;
integral = (f(local_a) + f(local_b))/2.0;
x = local_a;
for (i = 1; i <= local_n-1; i++) {
x = local_a + i*h;
integral += f(x);
}
integral = integral*h;
return integral;
}
double f(double x) {
double return_val;
return_val = x*x;
return return_val;
}
| 1
|
#include <pthread.h>
int counter;
pthread_mutex_t counter_mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t counter_mutex2 = PTHREAD_MUTEX_INITIALIZER;
void *doit1(void *vptr)
{
int i;
for (i = 0; i < 5000; i++)
{
pthread_mutex_lock(&counter_mutex1);
printf("%x: %d\\n",(unsigned int)pthread_self(), ++counter);
printf("pthread 1 is dead lock\\n");
pthread_mutex_lock(&counter_mutex2);
pthread_mutex_unlock(&counter_mutex1);
}
return 0;
}
void *doit2(void *vptr)
{
int i;
for (i = 0; i < 5000; i++)
{
pthread_mutex_lock(&counter_mutex2);
printf("%x: %d\\n",(unsigned int)pthread_self(), ++counter);
printf("pthread 2 is dead lock\\n");
pthread_mutex_lock(&counter_mutex1);
pthread_mutex_unlock(&counter_mutex2);
}
return 0;
}
int main(int argc, const char *argv[])
{
pid_t pid;
pid = fork();
if (pid < 0)
{
perror("fork");
exit(-1);
}
if (pid == 0)
{
pthread_t tidA, tidB;
pthread_create(&tidA,0, &doit1, 0);
pthread_create(&tidB,0, &doit2, 0);
pthread_join(tidA, 0);
pthread_join(tidB, 0);
}
else
{
printf("parent 1\\n");
sleep(1);
printf("parent 2\\n");
sleep(1);
printf("parent 3\\n");
sleep(1);
kill(pid, 9);
printf("child process exit succeed\\n");
printf("parent process exit succeed\\n");
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mut1 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mut2 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond1B = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mut1B = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond2B = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mut2B = PTHREAD_MUTEX_INITIALIZER;
int done = 0;
int todo = 0;
int doneB = 0;
int todoB = 0;
double wtime(void);
void* thread1_fn(void* foo);
void* thread1_fnB(void* foo);
void wakeywakeyB(void);
void wakeywakey(void);
double wtime(void)
{
struct timeval t;
gettimeofday(&t, 0);
return((double)t.tv_sec + (double)t.tv_usec / 1000000);
}
void* thread1_fn(void* foo)
{
int ret = -1;
while(1)
{
pthread_mutex_lock(&mut1);
while(todo == 0)
{
ret = pthread_cond_wait(&cond1, &mut1);
assert(ret == 0);
}
wakeywakeyB();
todo = 0;
pthread_mutex_unlock(&mut1);
pthread_mutex_lock(&mut2);
done = 1;
pthread_mutex_unlock(&mut2);
pthread_cond_signal(&cond2);
}
}
void* thread1_fnB(void* foo)
{
int ret = -1;
while(1)
{
pthread_mutex_lock(&mut1B);
while(todoB == 0)
{
ret = pthread_cond_wait(&cond1B, &mut1B);
assert(ret == 0);
}
todoB = 0;
pthread_mutex_unlock(&mut1B);
pthread_mutex_lock(&mut2B);
doneB = 1;
pthread_mutex_unlock(&mut2B);
pthread_cond_signal(&cond2B);
}
}
void wakeywakeyB(void)
{
int ret = -1;
pthread_mutex_lock(&mut1B);
todoB = 1;
pthread_mutex_unlock(&mut1B);
pthread_cond_signal(&cond1B);
pthread_mutex_lock(&mut2B);
while(doneB == 0)
{
ret = pthread_cond_wait(&cond2B, &mut2B);
assert(ret == 0);
}
doneB = 0;
pthread_mutex_unlock(&mut2B);
}
void wakeywakey(void)
{
int ret = -1;
pthread_mutex_lock(&mut1);
todo = 1;
pthread_mutex_unlock(&mut1);
pthread_cond_signal(&cond1);
pthread_mutex_lock(&mut2);
while(done == 0)
{
ret = pthread_cond_wait(&cond2, &mut2);
assert(ret == 0);
}
done = 0;
pthread_mutex_unlock(&mut2);
}
int main(int argc, char **argv)
{
pthread_t thread1;
pthread_t thread1B;
int ret = -1;
int i = 0;
double time1, time2;
ret = pthread_create(&thread1, 0, thread1_fn, 0);
assert(ret == 0);
ret = pthread_create(&thread1B, 0, thread1_fnB, 0);
assert(ret == 0);
time1 = wtime();
for(i=0; i<100000; i++)
{
wakeywakey();
}
time2 = wtime();
printf("time for %d iterations: %f seconds.\\n", 100000, (time2-time1));
printf("per iteration: %f\\n", (time2-time1)/(double)100000);
return(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
int value;
}SharedInt;
struct SharedInt2{
pthread_mutex_t lock;
int value;
};
sem_t sem;
SharedInt* sip;
void *functionWithCriticalSection(int* v2) {
pthread_mutex_lock(&(sip->lock));
sip->value = sip->value + *v2;
pthread_mutex_unlock(&(sip->lock));
sem_post(&sem);
}
int main() {
sem_init(&sem, 0, 0);
SharedInt si;
sip = &si;
sip->value = 0;
int v2 = 1;
pthread_mutex_init(&(sip->lock), 0);
pthread_t thread1;
pthread_t thread2;
pthread_create (&thread1,0,functionWithCriticalSection,&v2);
pthread_create (&thread2,0,functionWithCriticalSection,&v2);
sem_wait(&sem);
sem_wait(&sem);
pthread_mutex_destroy(&(sip->lock));
sem_destroy(&sem);
printf("%d\\n", sip->value);
return 0;
}
| 0
|
#include <pthread.h>
static unsigned long mapblocksize;
static unsigned long root2;
unsigned char bitmap[125];
unsigned char *sievemap;
static int gnum_threads, sievebit = 2;
pthread_mutex_t sievemutex;
pthread_mutex_t *blockmutex;
unsigned long sieve = 2, sieveblock = 0;
void errExit(char *s)
{
perror(s);
exit(-1);
}
int printPrimes(void)
{
long i, j, prinum = 0;
unsigned long num = 0;
for (i = 0; i < 125; i++)
for (j = 0; j < 8; j++, num++)
if (!(bitmap[i] & 1<<j)) {
prinum++;
}
long size = 125*8;
printf("%ld primes found below %ld.\\n", prinum, size);
return 0;
}
void sievemap_init()
{
unsigned long iblock = 0, block = 0, sv = 2, adder = 0;
int ibit = 0, bit = 2;
unsigned long numblocks = (root2+1)/8;
while (sv <= root2) {
bit++; sv++;
for (; block < numblocks; block++) {
for (; bit < 8; sv++, bit++)
if (!(sievemap[block] & 1 << bit))
break;
if (bit >= 8)
bit = 0;
else
break;
}
adder = sv*2;
iblock = block;
ibit = bit + adder;
for (; iblock < numblocks; iblock++) {
for (; ibit < 8; ibit += adder)
sievemap[iblock] |= (1 << ibit);
if (ibit >= 8)
ibit -= 8;
}
}
return;
}
void init_bm(unsigned char* bm, unsigned long size)
{
unsigned long i;
for (i = 0; i < size; i++)
bm[i] = 0x55;
return;
}
void init_gbm()
{
int i;
for (i = 0; i < 125; i++)
bitmap[i] = 0x55;
bitmap[0] = 0x53;
return;
}
int nextSieve()
{
sievebit++; sieve++;
for (; sieveblock < (root2+1)/8; sieveblock++) {
for (; sievebit < 8; sievebit++, sieve++)
if (!(sievemap[sieveblock] & 1 << sievebit))
break;
if (sievebit >= 8)
sievebit = 0;
else
return 0;
}
return -1;
}
int sieveBlock(unsigned char *bm, unsigned long *sv, int *bit, unsigned long *block,
unsigned long start, unsigned long end)
{
unsigned long adder = *sv * 2;
for (; *block < end && *block >= start; (*block)++) {
for (; *bit < 8; *bit += adder)
bm[*block] |= (1 << *bit);
if (*bit >= 8)
*bit -= 8;
}
return 0;
}
static void *
third(void *arg)
{
long id = (long) arg;
int i;
int localbit;
unsigned long localblock = 0;
unsigned long localsv = 0;
unsigned long *bstart = malloc((gnum_threads+1) * sizeof(int));
for (i = 0; i < gnum_threads; i++) {
bstart[i] = (mapblocksize + 1) * i;
}
bstart[gnum_threads] = 125;
while (localsv <= root2) {
pthread_mutex_lock(&sievemutex);
if (nextSieve() == -1) {
pthread_mutex_unlock(&sievemutex);
break;
}
localsv = sieve;
localbit = sievebit + localsv*2;
localblock = sieveblock;
pthread_mutex_unlock(&sievemutex);
for (i = 0; i < gnum_threads; i++) {
pthread_mutex_lock(&blockmutex[i]);
if (localblock < bstart[i+1] && localblock >= bstart[i])
sieveBlock(bitmap, &localsv, &localbit, &localblock,
bstart[i], bstart[i+1]);
pthread_mutex_unlock(&blockmutex[i]);
}
}
pthread_exit((void*) 0);
}
int makeIntArray(unsigned int ***thrdata, int numrows, int numcols)
{
int i, j;
*thrdata = malloc(numrows * sizeof(int *));
if (*thrdata == 0)
errExit("out of memory for thread data array");
for (i = 0; i < numrows; i++) {
(*thrdata)[i] = malloc(numcols * sizeof(int));
if ((*thrdata)[i] == 0)
errExit("out of memory for thread data");
for (j = 0; j < numcols; j++)
(*thrdata)[i][j] = 0;
}
return 0;
}
int beginThreading(int num_threads)
{
void *status;
init_gbm();
root2 = (unsigned int) sqrt((double) 125 * 8);
gnum_threads = num_threads;
mapblocksize = 125 / num_threads;
if (mapblocksize * 8 < root2) {
printf("Too many threads\\n");
return 0;
}
sievemap = malloc((root2+1)/8 * sizeof(unsigned char));
if (sievemap == 0)
errExit("out of memory for local bitmap");
init_bm(sievemap, (unsigned long) (root2+1)/8);
sievemap[0] = 0x53;
sievemap_init();
long i;
pthread_mutex_init(&sievemutex, 0);
blockmutex = malloc(num_threads * sizeof(pthread_mutex_t));
if (blockmutex == 0)
errExit("not enough memory for mutex array");
for (i = 0; i < num_threads; i++)
pthread_mutex_init(&blockmutex[i], 0);
pthread_t *svthr = malloc(num_threads * sizeof(pthread_t));
if (svthr == 0)
errExit("not enough memory for thread array");
for (i = 0; i < num_threads; i++)
if (pthread_create(&svthr[i], 0, third, (void*) i) != 0)
errExit("couldn't make thread");
for (i = 0; i < num_threads; i++)
if (pthread_join(svthr[i], &status) != 0)
errExit("couldn't join thread");
printPrimes();
return 0;
}
int main(int argc, char **argv)
{
int num_threads;
switch(argc) {
case 0:
case 1:
printf("Defaulting to one thread.\\n");
beginThreading(1);
return 0;
case 2:
if ((num_threads = atoi(argv[1])) > 0)
beginThreading(num_threads);
else
printf("%s is not a positive integer.\\n", argv[1]);
return 0;
default:
printf("Too many arguments.\\n");
return 0;
}
}
| 1
|
#include <pthread.h>
unlong number_in_circle = 0;
unlong points_per_thread;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *runner() {
unlong number_in_circle_in_thread = 0;
unsigned int rand_state = rand();
unlong i;
for (i = 0; i < points_per_thread; i++) {
double x = rand_r(&rand_state) / ((double)32767 + 1) * 2.0 - 1.0;
double y = rand_r(&rand_state) / ((double)32767 + 1) * 2.0 - 1.0;
if (x * x + y * y <= 1) {
number_in_circle_in_thread++;
}
}
pthread_mutex_lock(&mutex);
number_in_circle += number_in_circle_in_thread;
pthread_mutex_unlock(&mutex);
return 0;
}
int main(int argc, const char *argv[])
{
if (argc != 3) {
fprintf(stderr, "usage: ./pi <number of tosses> <threads>\\n");
exit(1);
}
unlong number_of_tosses = atoll(argv[1]);
int thread_count = atoi(argv[2]);
points_per_thread = number_of_tosses / thread_count;
time_t start = time(0);
srand((unsigned)time(0));
pthread_t *threads = malloc(thread_count * sizeof(pthread_t));
pthread_attr_t attr;
pthread_attr_init(&attr);
int i;
for (i = 0; i < thread_count; i++) {
pthread_create(&threads[i], &attr, runner, (void *) 0);
}
for (i = 0; i < thread_count; i++) {
pthread_join(threads[i], 0);
}
pthread_mutex_destroy(&mutex);
free(threads);
double pi_estimate = (4. * (unlong)number_in_circle) / ((unlong)points_per_thread * thread_count);
printf("%f\\n", pi_estimate);
printf("Time: %d sec\\n", (int)(time(0) - start));
return 0;
}
| 0
|
#include <pthread.h>
int start_recovery()
{
pthread_mutex_lock(&lock);
struct marked_for_recovery* head;
head = (struct marked_for_recovery*)malloc(sizeof(struct marked_for_recovery));
head->link = 0;
int field1;
char field2[MAX];
char field3[MAX];
char field4[MAX];
FILE* fd = 0;
long sz;
int count=0;
fd = fopen("journal.txt", "rb");
sz = fsize(fd);
if (sz > 0)
{
char buf[MAX];
char tmp[MAX];
char *token;
fseek(fd, sz, 0);
while (fgetsr(buf, sizeof(buf), fd) != 0)
{
if(strstr(buf, "RECOVERY END") != 0)
{
break;
}
else
{
if(strstr(buf, "RECOVERY START") == 0)
{
field1=0;
memset(field2, 0, MAX);
memset(field3, 0, MAX);
memset(field4, 0, MAX);
strcpy(tmp,buf);
token = strtok(tmp,",");
while(isspace(*token)) token++;
field1 = atoi(token);
token = strtok(0, ",");
while(isspace(*token)) token++;
strcpy(field2, token);
token = strtok(0, ",");
while(isspace(*token)) token++;
strcpy(field3, token);
token = strtok(0, ",");
while(isspace(*token)) token++;
size_t ln = strlen(token) - 1;
if(token[ln] == '\\n')
token[ln] = '\\0';
strcpy(field4, token);
head = create_recovery_list(head, field1, field2, field3, field4);
}
}
}
}
pthread_mutex_unlock(&lock);
count = execute_recovery(head);
return count;
}
int execute_recovery(struct marked_for_recovery* head)
{
struct marked_for_recovery* temp;
int count = 0;
temp = (struct marked_for_recovery*)malloc(sizeof(struct marked_for_recovery));
temp = head->link;
while(temp!=0)
{
if(temp->commited != 1)
{
count++;
all_or_nothing_get(temp->name);
}
temp = temp->link;
}
return count;
}
struct marked_for_recovery* create_recovery_list(struct marked_for_recovery* head, int field1, char field2[], char field3[], char field4[])
{
int isExist=0;
isExist = check_tid_in_list(head,field1);
struct marked_for_recovery* temp;
if(isExist == 0)
{
temp = (struct marked_for_recovery*)malloc(sizeof(struct marked_for_recovery));
temp->link = 0;
temp->tid = field1;
strcpy(temp->name, field3);
strcpy(temp->operation, field2);
if(!strcmp(field4, "pending"))
temp->pending = 1;
else if(!strcmp(field4, "commit"))
temp->commited = 1;
else if(!strcmp(field4, "end"))
temp->end = 1;
if(head->link == 0)
{
head->link = temp;
return head;
}
temp->link = head->link;
head->link = temp;
}
else
{
update_recovery_list(head, field1, field4);
}
return head;
}
int check_tid_in_list(struct marked_for_recovery* head, int field1)
{
struct marked_for_recovery* temp;
temp = (struct marked_for_recovery*)malloc(sizeof(struct marked_for_recovery));
temp = head->link;
while(temp!=0)
{
if(temp->tid == field1)
{
return 1;
}
temp = temp->link;
}
return 0;
}
void update_recovery_list(struct marked_for_recovery* head, int field1, char field4[])
{
struct marked_for_recovery* temp;
temp = (struct marked_for_recovery*)malloc(sizeof(struct marked_for_recovery));
temp = head->link;
while(temp!=0)
{
if(temp->tid == field1)
{
if(!strcmp(field4, "pending"))
temp->pending = 1;
else if(!strcmp(field4, "commit"))
temp->commited = 1;
else if(!strcmp(field4, "end"))
temp->end = 1;
break;
}
temp = temp->link;
}
}
| 1
|
#include <pthread.h>
extern int makethread(void *(*)(void *), void *);
struct to_info {
void (*to_fn)(void *);
void *to_arg;
struct timespec to_wait;
};
void clock_gettime(int id, struct timesec *tsp) {
struct timeval tv;
gettimeofday(&tv, 0);
tsp->tv_sec = tv.tv_sec;
tsp->tv_nsec = tv.tv_nsec * 1000;
}
void *timeout_helper(void *arg) {
struct to_info *tip;
tip = (struct to_info *)arg;
nanosleep((&tip->to_wait), (0));
(*tip->to_fn)(tip->to_arg);
free(arg);
return(0);
}
void timeout(const struct timespec *when, void (*func)(void *), void *arg) {
struct timespec now;
struct to_info *tip;
int err;
clock_gettime(0, &now);
if ((when->tv_sec > now.tv_sec) ||
(when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) {
tip = malloc(sizeof(struct to_info));
if (tip != 0) {
tip->to_fn = func;
tip->to_arg = arg;
tip->to_wait.tv_sec = when->tv_sec - now.tv_sec;
if (when->tv_nsec >= now.tv_nsec) {
tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec;
} else {
tip->to_wait.tv_sec--;
tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec +
when->tv_nsec;
}
err = makethread(timeout_helper, (void *)tip);
if (err == 0)
return;
else
free(arg);
}
}
(*func)(arg);
}
pthread_mutexattr_t attr;
pthread_mutex_t mutex;
void retry(void *arg) {
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
}
int main(void) {
int err, conditoin, arg;
struct timespec when;
if ((err = pthread_mutexattr_init(&attr)) != 0)
err_exit(err, "pthread_mutexattr_init failed");
if ((err = pthread_mutexattr_settype(&attr,
PTHREAD_MUTEX_RECURSIVE)) != 0)
err_exit(err, "can't set recursive type");
if ((err = pthread_mutex_init(&mutex, &attr)) != 0)
err_exit(err, "can't create recursive mutex");
pthread_mutex_lock(&mutex);
if (condition) {
clock_gettime(0, &when);
when.tv_sec += 10;
timeout(&when, retry, (void *)((unsigned long)arg));
}
pthread_mutex_unlock(&mutex);
exit(0);
}
| 0
|
#include <pthread.h>
struct CircularQueue{
int rear;
int front;
int queue[5];
int full;
int empt;
};
struct Thread{
int id;
pthread_t thread;
};
pthread_mutex_t mutex;
struct CircularQueue *cq;
void initialize(struct CircularQueue *cq){
cq->rear = -1;
cq->front = -1;
cq->full = 0;
cq->empt = 1;
}
void enqueue(struct CircularQueue *cq,int data){
cq->rear = (cq->rear + 1) % 5;
cq->queue[cq->rear] = data;
if(cq->rear == cq->front || (cq->front == -1 && cq->rear == 5 - 1)){
cq->full = 1;
}
if(cq->empt == 1){
cq->empt = 0;
}
}
int dequeue(struct CircularQueue *cq){
cq->front = (cq->front + 1) % 5;
if(cq->front == cq->rear || cq->rear == -1){
cq->empt = 1;
}
if(cq->full == 1){
cq->full = 0;
}
return cq->queue[cq->front];
}
void produce(void *producerThread){
struct Thread *producer = (struct Thread*) producerThread;
int s = producer->id;
int seedForRandomNum = producer->id;
while(1){
sleep(rand_r(&s) % 3 + 1);
int data = rand_r(&seedForRandomNum) % 50 + 1;
pthread_mutex_lock(&mutex);
if(!cq->full){
enqueue(cq,data);
printf("Producer[%d] produces data[%d]: %d\\n",producer->id,cq->rear,data);
}else{
printf("Queue is Full\\n");
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void consume(void *consumerThread){
int conData;
struct Thread *consumer= (struct Thread*) consumerThread;
int s = consumer->id;
while(1){
sleep(rand_r(&s) % 3 + 1);
pthread_mutex_lock(&mutex);
if(!cq->empt){
conData = dequeue(cq);
printf("\\t\\t\\t\\tConsumer[%d] consumes data[%d]: %d \\n",consumer->id,cq->front,conData);
}else{
printf("\\t\\t\\t\\tQueue is Emtpy\\n");
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main(){
int i;
int producerCount;
int consumerCount;
cq = (struct CircularQueue *)malloc(sizeof(struct CircularQueue));
initialize(cq);
printf("Enter the number of Producers: ");
scanf("%d",&producerCount);
printf("Enter the number of Consumers: ");
scanf("%d",&consumerCount);
struct Thread *pThreadProducer = (struct Thread*)malloc(sizeof(struct Thread)*producerCount);
struct Thread *pThreadConsumer = (struct Thread*)malloc(sizeof(struct Thread)* consumerCount);
if(pthread_mutex_init(&mutex, 0) != 0){
perror("Error on mutex initialization");
exit(1);
}
for(i = 0; i < producerCount; i++){
pThreadProducer[i].id = i;
if(pthread_create(&pThreadProducer[i].thread,0, (void *)&produce, (void*) &pThreadProducer[i]) != 0){
perror("Error on producer thread creation");
exit(1);
}
}
for(i =0; i < consumerCount; i++){
pThreadConsumer[i].id = i;
if(pthread_create(&pThreadConsumer[i].thread,0,(void *) &consume, (void*) &pThreadConsumer[i]) != 0){
perror("Error on consumer thread creation");
exit(1);
}
}
for(i = 0; i < producerCount; i++){
pthread_join(pThreadProducer[i].thread,0);
}
for(i =0; i < consumerCount; i++){
pthread_join(pThreadConsumer[i].thread, 0);
}
pthread_mutex_destroy(&mutex);
free(pThreadProducer);
free(pThreadConsumer);
free(cq);
return 0;
}
| 1
|
#include <pthread.h>
static struct tree_node *create_tree_node(void *value)
{
struct tree_node *node = malloc(sizeof(struct tree_node));
if (node == 0) {
fprintf(stderr, "ERROR: Memory allocation failure.\\n");
}
pthread_mutex_init(&(node->lock), 0);
node->child_count = 0;
node->children = 0;
node->value = value;
}
static void _lock(struct tree_node *node)
{
pthread_mutex_lock(&(node->lock));
}
static void _unlock(struct tree_node *node)
{
pthread_mutex_unlock(&(node->lock));
}
void free_tree_node(struct tree_node *node, void (*free_value)(void *))
{
if (free_value != 0)
free_value(node->value);
free(node->children);
free(node);
}
void recursive_free_tree(struct tree_node *root, void (*free_value)(void *), struct tree_node *except)
{
if (root == except)
return;
if (free_value != 0)
free_value(root->value);
for (int i=0; i<root->child_count; i++) {
recursive_free_tree(root->children[i], free_value, except);
}
if (root->children != 0)
free(root->children);
free(root);
}
struct tree_node *init_tree(void *value)
{
struct tree_node *root = create_tree_node(value);
root->depth = 0;
return root;
}
void breadth_traverse(struct tree_node *root, int max_depth, void (*eval)(struct tree_node *))
{
struct queue *to_see = init_queue();
struct tree_node *cur;
int start_depth = root->depth;
enqueue(to_see, root);
while ((cur = dequeue(to_see)) != 0) {
if (max_depth == -1 || cur->depth - start_depth < max_depth) {
eval(cur);
int child_count = 0;
struct tree_node **children = get_tree_children(cur, &child_count);
for (int i=0; i<child_count; i++) {
enqueue(to_see, children[i]);
}
free(children);
}
}
free_queue(to_see, 0);
}
struct tree_node *add_tree_child(struct tree_node *parent, void *child_value)
{
_lock(parent);
struct tree_node *child = create_tree_node(child_value);
child->depth = parent->depth + 1;
parent->child_count++;
if (parent->children == 0) {
parent->children = malloc(sizeof(struct tree_node *) * parent->child_count);
} else {
parent->children = realloc(parent->children, sizeof(struct tree_node *) * parent->child_count);
}
if (parent->children == 0) {
fprintf(stderr, "ERROR: Memory allocation failure.\\n");
exit(1);
}
parent->children[parent->child_count - 1] = child;
_unlock(parent);
return child;
}
struct tree_node **get_tree_children(struct tree_node *parent, int *count)
{
_lock(parent);
size_t size_of_array = sizeof(struct tree_node *) * parent->child_count;
struct tree_node **cloned_children = malloc(size_of_array);
if (cloned_children == 0) {
fprintf(stderr, "ERROR: Memory allocation failure.\\n");
exit(1);
}
memcpy(cloned_children, parent->children, size_of_array);
*count = parent->child_count;
_unlock(parent);
return cloned_children;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
long int sum = 0;
void * sum_of_number(void *argv) {
long i = 0;
long * limit_ptr = (long *) argv;
long limit = *limit_ptr;
pthread_mutex_lock(&mutex);
sum = 0;
for (; i <=limit ; i++ ) {
sum += i;
}
sleep(1);
printf("thread = %d calculated sum = %ld for numnber = %ld \\n",pthread_self(),sum,limit);
pthread_mutex_unlock(&mutex);
long * return_value = malloc(sizeof(*return_value));
*return_value = sum;
pthread_exit(return_value);
}
int main (int argc, char ** argv) {
short int num_of_arg = 0, counter;
if (argc < 2 ) {
printf ("one agrument expected, provided 0\\n");
exit(0);
}
num_of_arg = argc - 1;
pthread_t pid[num_of_arg];
long limit;
for (counter =1; counter <= num_of_arg; counter++) {
pthread_attr_t attr;
pthread_attr_init(&attr);
limit = atol(argv[counter]);
long *limit_ptr = malloc(sizeof(*limit_ptr));
*limit_ptr = limit;
pthread_create(&pid[counter - 1], &attr, sum_of_number, limit_ptr);
}
for (counter = 1; counter <= num_of_arg; counter++) {
long *return_value = 0 ;
pthread_join(pid[counter-1], (void **) &return_value);
free(return_value);
}
exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
void *lowprio(void *null)
{
int i;
printf("LOWPRIO : contending for mutex lock \\n");
if(pthread_mutex_lock(&mutex)==0)
{
printf("LOWPRIO : lock acquired\\n");
printf("LOWPRIO : executing critical op ......\\n");
while(i<40000000)
i++;
printf("LOWPRIO : Done\\n");
printf("LOWPRIO : Releasing mutex \\n");
}
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void * highprio(void *null)
{
printf("HIGHPRIO : contending for mutex lock \\n");
if(pthread_mutex_lock(&mutex)==0)
{
printf("HIGHPRIO : lock acquired \\n");
printf("HIGHPRIO : executing critical op ......\\n");
printf("HIGHPRIO : Done\\n");
printf("HIGHPRIO : Releasing mutex \\n");
}
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void * medprio(void *null)
{
int i= 1;
printf("MEDPRIO : acquired cpu \\n");
while(i<100){
printf("MEDPRIO : running\\n");
i++;
}
}
int main (int argc, char *argv[])
{
pthread_mutexattr_t attrmutex;
int inherit,policy,priority,rc;
struct sched_param param;
pthread_t tcb1,tcb2,tcb3;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_mutexattr_init(&attrmutex);
pthread_mutexattr_setprotocol(&attrmutex,PTHREAD_PRIO_INHERIT);
pthread_mutex_init(&mutex,&attrmutex);
pthread_attr_setinheritsched(&attr,PTHREAD_EXPLICIT_SCHED);
param.sched_priority=1;
pthread_attr_setschedpolicy(&attr, SCHED_RR);
pthread_attr_setschedparam(&attr, ¶m);
pthread_create(&tcb1, &attr, lowprio, 0);
param.sched_priority=60;
pthread_attr_setschedpolicy(&attr,SCHED_RR);
pthread_attr_setschedparam(&attr,¶m);
pthread_create(&tcb2, &attr, highprio, 0);
param.sched_priority=50;
pthread_attr_setschedpolicy(&attr,SCHED_RR);
pthread_attr_setschedparam(&attr,¶m);
pthread_create(&tcb3, &attr, medprio, 0);
pthread_attr_destroy(&attr);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
{
pthread_mutex_t lock;
pthread_cond_t coda[4][2];
int sospesi[4][2];
int sulponte[2];
} monitor;
monitor m;
void init_monitor(monitor* m)
{
int i = 0;
pthread_mutex_init(&m->lock, 0);
for (i = 0; i<4; i++){
pthread_cond_init(&m->coda[i][0], 0);
pthread_cond_init(&m->coda[i][1], 0);
m->sospesi[i][0] = 0;
m->sospesi[i][1] = 0;
}
m->sulponte[0] = 0;
m->sulponte[1] = 0;
}
void entraNORD(monitor* m, int id,int tipo)
{
pthread_mutex_lock (&m->lock);
while ( m->sulponte[0] + m->sulponte[1] == 10 ||
(tipo == 0 && m->sospesi[0][1]>0) ||
(abs(m->sulponte[0]-m->sulponte[1])==3 &&
m->sulponte[0] > m->sulponte[1]))
{
printf("Mezzo %d sospeso di tipo %d in ingresso della corsia NORD!\\n", id,tipo);
m->sospesi[0][tipo]++;
pthread_cond_wait(&m->coda[0][tipo], &m->lock);
m->sospesi[0][tipo]--;
}
printf("Mezzo %d di tipo %d DENTRO la corsia NORD!\\n", id,tipo);
m->sulponte[0]++;
if (m->sulponte[0] < m->sulponte[1])
{
if (m->sospesi[1][1]>0)
pthread_cond_signal(&m->coda[1][1]);
else if (m->sospesi[1][0]>0)
pthread_cond_signal(&m->coda[1][0]);
else if (m->sospesi[2][1]>0)
pthread_cond_signal(&m->coda[2][1]);
else if (m->sospesi[2][0]>0)
pthread_cond_signal(&m->coda[2][0]);
}
pthread_mutex_unlock (&m->lock);
}
void entraSUD(monitor* m, int id,int tipo)
{
pthread_mutex_lock (&m->lock);
while (
m->sulponte[0] + m->sulponte[1] >= 10 ||
(tipo == 0 && m->sospesi[2][1]>0) ||
(abs(m->sulponte[0]-m->sulponte[1])==3 && m->sulponte[0] < m->sulponte[1]))
{
printf("Mezzo %d sospeso di tipo %d in ingresso della corsia SUD!\\n", id,tipo);
m->sospesi[2][tipo]++;
pthread_cond_wait(&m->coda[2][tipo], &m->lock);
m->sospesi[2][tipo]--;
}
printf("Mezzo %d di tipo %d DENTRO la corsia SUD!\\n", id,tipo);
m->sulponte[1]++;
if (m->sulponte[0] > m->sulponte[1])
{
if (m->sospesi[3][1]>0)
pthread_cond_signal(&m->coda[3][1]);
else if (m->sospesi[3][0]>0)
pthread_cond_signal(&m->coda[3][0]);
else if (m->sospesi[0][1]>0)
pthread_cond_signal(&m->coda[0][1]);
else if (m->sospesi[0][0]>0)
pthread_cond_signal(&m->coda[0][0]);
}
pthread_mutex_unlock (&m->lock);
}
void esceNORD(monitor* m, int id,int tipo)
{
pthread_mutex_lock (&m->lock);
while (
abs(m->sulponte[0]-m->sulponte[1])==3 &&
m->sulponte[0] < m->sulponte[1])
{
printf("Mezzo %d di tipo %d proveniente da nord sospeso in uscita!\\n", id, tipo);
m->sospesi[1][tipo]++;
pthread_cond_wait(&m->coda[1][tipo], &m->lock);
m->sospesi[1][tipo]--;
}
printf("Mezzo %d di tipo %d ESCE dalla corsia NORD!\\n", id, tipo);
m->sulponte[0]--;
if (m->sospesi[0][1] > 0)
pthread_cond_signal(&m->coda[0][1]);
else if (m->sospesi[0][0] > 0)
pthread_cond_signal(&m->coda[0][0]);
else if (m->sulponte[0] > m->sulponte[1])
{
if (m->sospesi[3][1]>0)
pthread_cond_signal(&m->coda[3][1]);
else if (m->sospesi[3][0]>0)
pthread_cond_signal(&m->coda[3][0]);
}
pthread_mutex_unlock (&m->lock);
}
void esceSUD(monitor* m, int id,int tipo)
{
pthread_mutex_lock (&m->lock);
while (
abs(m->sulponte[0]-m->sulponte[1])==3 &&
m->sulponte[0] > m->sulponte[1])
{
printf("Mezzo %d di tipo %d proveniente da nord sospeso in uscita!\\n", id, tipo);
m->sospesi[3][tipo]++;
pthread_cond_wait(&m->coda[3][tipo], &m->lock);
m->sospesi[3][tipo]--;
}
printf("Mezzo %d di tipo %d ESCE dalla corsia SUD!\\n", id, tipo);
m->sulponte[1]--;
if (m->sospesi[2][1] > 0)
pthread_cond_signal(&m->coda[2][1]);
else if (m->sospesi[2][0] > 0)
pthread_cond_signal(&m->coda[2][0]);
else if (m->sulponte[0] < m->sulponte[1])
{
if (m->sospesi[1][1]>0)
pthread_cond_signal(&m->coda[1][1]);
else if (m->sospesi[1][0]>0)
pthread_cond_signal(&m->coda[1][0]);
}
pthread_mutex_unlock (&m->lock);
}
void* pNORD(void* arg)
{
int id = (int)arg;
int tipo = rand() % 2;
printf("Mezzo %d di tipo %d NORD!\\n", id, tipo);
entraNORD(&m, id,tipo);
sleep(1);
esceNORD(&m, id,tipo);
pthread_exit(0);
}
void* pSUD(void* arg)
{
int id = (int)arg;
int tipo = rand() % 2;
printf("Mezzo %d di tipo %d SUD!\\n", id, tipo);
entraSUD(&m, id,tipo);
sleep(1);
esceSUD(&m, id,tipo);
pthread_exit(0);
}
int main (int argc, char** argv)
{
int i, tipo;
pthread_t thread[10];
init_monitor(&m);
srand(time(0));
for(i = 0; i < 10; i++)
{
tipo = rand() % 2;
if (tipo)
pthread_create(&thread[i], 0, pNORD, (void*)i);
else
pthread_create(&thread[i], 0, pSUD, (void*)i);
}
for(i = 0; i < 10; i++)
pthread_join(thread[i], 0);
return 0;
}
| 1
|
#include <pthread.h>
void *produce(void *resource)
{
int valToAdd = 0,tasksProduced = 0;
while(resource->tasksComplete < resource->NUM_TASKS)
{
valToAdd = rand() % 100;
pthread_mutex_lock(resource->m);
if(resource->totElem > resource->BUFFER_SIZE)
{
exit(1);
}
while(resource->totElem == BUFFER_SIZE)
{
pthread_cond_wait(resource->condBoss,resource->m);
}
resource->numList[resource->addrAdd] = valToAdd;
resource->addrAdd = (resource->addrAdd + 1) % resource->BUFFER_SIZE;
resource->totElem++;
pthread_mutex_unlock(resource->m);
pthread_cond_broadcast(resource->condWorker);
printf("Boss produced: %i\\n",valToAdd);
}
printf("Boss quitting... goodbye!\\n");
fflush(stdout);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
static void *queue_fetch_or_alloc(struct ff_circular_queue *cq,
int index)
{
if (cq->slots[index] == 0)
cq->slots[index] = av_mallocz(cq->item_size);
return cq->slots[index];
}
static void queue_lock(struct ff_circular_queue *cq)
{
pthread_mutex_lock(&cq->mutex);
}
static void queue_unlock(struct ff_circular_queue *cq)
{
pthread_mutex_unlock(&cq->mutex);
}
static void queue_signal(struct ff_circular_queue *cq)
{
pthread_cond_signal(&cq->cond);
}
static void queue_wait(struct ff_circular_queue *cq)
{
pthread_cond_wait(&cq->cond, &cq->mutex);
}
bool ff_circular_queue_init(struct ff_circular_queue *cq, int item_size,
int capacity)
{
memset(cq, 0, sizeof(struct ff_circular_queue));
cq->item_size = item_size;
cq->capacity = capacity;
cq->abort = 0;
cq->slots = av_mallocz(capacity * sizeof(void *));
if (cq->slots == 0)
goto fail;
cq->size = 0;
cq->write_index = 0;
cq->read_index = 0;
if (pthread_mutex_init(&cq->mutex, 0) != 0)
goto fail1;
if (pthread_cond_init(&cq->cond, 0) != 0)
goto fail2;
return 1;
fail2:
pthread_mutex_destroy(&cq->mutex);
fail1:
av_free(cq->slots);
fail:
return 0;
}
void ff_circular_queue_abort(struct ff_circular_queue *cq)
{
queue_lock(cq);
cq->abort = 1;
queue_signal(cq);
queue_unlock(cq);
}
void ff_circular_queue_free(struct ff_circular_queue *cq)
{
ff_circular_queue_abort(cq);
if (cq->slots != 0)
av_free(cq->slots);
pthread_mutex_destroy(&cq->mutex);
pthread_cond_destroy(&cq->cond);
}
void ff_circular_queue_wait_write(struct ff_circular_queue *cq)
{
queue_lock(cq);
while (cq->size >= cq->capacity && !cq->abort)
queue_wait(cq);
queue_unlock(cq);
}
void *ff_circular_queue_peek_write(struct ff_circular_queue *cq)
{
return queue_fetch_or_alloc(cq, cq->write_index);
}
void ff_circular_queue_advance_write(struct ff_circular_queue *cq, void *item)
{
cq->slots[cq->write_index] = item;
cq->write_index = (cq->write_index + 1) % cq->capacity;
queue_lock(cq);
++cq->size;
queue_unlock(cq);
}
void *ff_circular_queue_peek_read(struct ff_circular_queue *cq)
{
return queue_fetch_or_alloc(cq, cq->read_index);
}
void ff_circular_queue_advance_read(struct ff_circular_queue *cq)
{
cq->read_index = (cq->read_index + 1) % cq->capacity;
queue_lock(cq);
--cq->size;
queue_signal(cq);
queue_unlock(cq);
}
| 1
|
#include <pthread.h>
pthread_mutex_t downloader_mutex, parser_mutex;
unsigned long downloaders[MAX_THREADS];
unsigned long parsers[MAX_THREADS];
int downloader_threads = 0;
int parser_threads = 0;
char *fetch(char *link) {
int fd = open(link, O_RDONLY);
if (fd < 0) {
fprintf(stderr, "failed to open file: %s", link);
return 0;
}
int size = lseek(fd, 0, 2);
assert(size >= 0);
char *buf = Malloc(size+1);
buf[size] = '\\0';
assert(buf);
lseek(fd, 0, 0);
char *pos = buf;
while(pos < buf+size) {
int rv = read(fd, pos, buf+size-pos);
assert(rv > 0);
pos += rv;
}
int i = 0;
unsigned long current_id = (unsigned long) pthread_self();
pthread_mutex_lock(&downloader_mutex);
for(i = 0; i < MAX_THREADS; ++i)
{
if(downloaders[i] == -1)
{
downloader_threads++;
downloaders[i] = current_id;
break;
}
else if(downloaders[i] == current_id)
{
break;
}
}
pthread_mutex_unlock(&downloader_mutex);
sleep(1);
close(fd);
return buf;
}
void edge(char *from, char *to) {
int i = 0;
unsigned long current_id = (unsigned long) pthread_self();
pthread_mutex_lock(&parser_mutex);
for(i = 0; i < MAX_THREADS; ++i)
{
if(parsers[i] == -1)
{
parser_threads++;
parsers[i] = current_id;
break;
}
else if(parsers[i] == current_id)
{
break;
}
}
pthread_mutex_unlock(&parser_mutex);
sleep(1);
}
int main(int argc, char *argv[]) {
pthread_mutex_init(&downloader_mutex, 0);
pthread_mutex_init(&parser_mutex, 0);
int i = 0;
for(i = 0; i < MAX_THREADS; ++i)
{
downloaders[i] = -1;
parsers[i] = -1;
}
int rc = crawl("/u/c/s/cs537-1/ta/tests/4a/tests/files/too_many_threads/pagea", 15, 15, 15, fetch, edge);
assert(rc == 0);
printf("\\ndownloader_threads : %d\\n", downloader_threads);
check(downloader_threads <= 7, "Not more than 7 downloader threads should have run as there are only 7 pages to fetch\\n");
printf("\\nparser_threads : %d\\n", parser_threads);
check(parser_threads <= 1, "Not more than 1 parser threads should have called edge function as only 1 page has link\\n");
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t sig_ops_mutex;
static void sig_utils_init(void)
{
pthread_mutex_init(&sig_ops_mutex, 0);
}
int sig_has_no_handler(int sig)
{
struct sigaction sa;
sigaction(sig, 0, &sa);
if (sa.sa_flags & SA_SIGINFO)
{
return sa.sa_sigaction==(void *)SIG_IGN ||
sa.sa_sigaction==(void *)SIG_DFL;
}
return sa.sa_handler==(void *)SIG_IGN ||
sa.sa_handler==(void *)SIG_DFL;
}
int register_sig_proc(int sig, void *sig_handler)
{
struct sigaction sa;
sigemptyset(&sa.sa_mask);;
sa.sa_sigaction = sig_handler;
sa.sa_flags = SA_SIGINFO;
return sigaction(sig, &sa, 0);
}
int ignore_sig(int sig)
{
return register_sig_proc(sig, SIG_IGN);
}
int restore_sig_default_proc(int sig)
{
return register_sig_proc(sig, SIG_DFL);
}
int get_a_free_sig_and_register_proc(void *sig_handler)
{
int i;
int ret = -1;
pthread_mutex_lock(&sig_ops_mutex);
for (i=RT_SIG_FOR_APP_MIN; i<=RT_SIG_FOR_APP_MAX; i++)
{
if (!sig_has_no_handler(i))
continue;
if (0==register_sig_proc(i, sig_handler))
{
ret = i;
goto EXIT;
}
}
EXIT:
pthread_mutex_unlock(&sig_ops_mutex);
return ret;
}
| 1
|
#include <pthread.h>
struct http_procotol
{
char *header;
char *body;
};
{
int curcount;
pthread_mutex_t count_mutex;
} c_client;
struct http_procotol server_answer;
char msg[99999];
char path[99999];
char html[1024];
char *ROOT, *req_params[2];
int shmid;
void *shared_memory = (void *)0;
void close_server(int sig);
int main()
{
int server_sockfd, client_sockfd;
int server_len, client_len;
int res;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
struct sigaction act;
c_client *shared_limit;
act.sa_handler = close_server;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGINT, &act, 0);
shmid = shmget((key_t)123,sizeof(c_client),0666 | IPC_CREAT);
if (shmid == -1)
{
fprintf(stderr,"shmget failed\\n");
exit(1);
}
shared_memory = shmat(shmid,(void *)0,0);
if (shared_memory == (void *)-1)
{
fprintf(stderr,"shmat failed\\n");
exit(1);
}
shared_limit = (c_client *)shared_memory;
res = pthread_mutex_init(&shared_limit->count_mutex, 0);
if(res != 0)
{
perror("Mutex init failed\\n");
exit(1);
}
server_sockfd = socket(AF_INET,SOCK_STREAM,0);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
server_address.sin_port = htons(6565);
server_len = sizeof(server_address);
bind(server_sockfd, (struct sockaddr *)&server_address, server_len);
listen(server_sockfd, 5);
signal(SIGCHLD,SIG_IGN);
while(1)
{
int bytes, fd;
printf("server waititng \\n");
client_len = sizeof(client_address);
client_sockfd = accept(server_sockfd,(struct sockaddr *)&client_address,&client_len);
if(shared_limit->curcount >= 10)
{
printf("============server clients limit is exceeded! socket will be closed=============\\n");
close(client_sockfd);
}
else
if (fork() == 0)
{
pthread_mutex_lock(&shared_limit->count_mutex);
shared_limit->curcount++;
printf("clients count = %d\\n", shared_limit->curcount);
pthread_mutex_unlock(&shared_limit->count_mutex);
printf("connection is init\\n");
memset((void *)msg,(int)'\\0',99999);
read(client_sockfd, msg, sizeof(msg));
printf("server get this:\\n%s\\n", msg);
req_params[0] = strtok(msg, " ");
if (strncmp(req_params[0], "GET", 4) == 0)
{
printf("this is GET query\\n");
req_params[1] = strtok(0," ");
if (strncmp(req_params[1],"/", 2) == 0)
req_params[1] = "/index.html";
if (strstr(req_params[1], "..") != 0)
req_params[1] = "/index.html";
if ((fd = open(req_params[1] + 1, O_RDONLY)) != -1)
{
server_answer.header = "HTTP/1.1 200 OK\\n\\n";
send(client_sockfd, server_answer.header, strlen(server_answer.header), 0);
while((bytes = read(fd, html, 1024)) > 0)
{
write(client_sockfd, html, bytes);
}
close(fd);
}
else
{
server_answer.header = "HTTP/1.1 404 Not Found\\n\\n";
server_answer.body = "<html><body><h1>404 Not Found</h1></body></html>";
send(client_sockfd, server_answer.header, strlen(server_answer.header), 0);
send(client_sockfd, server_answer.body, strlen(server_answer.body), 0);
}
close(client_sockfd);
pthread_mutex_lock(&shared_limit->count_mutex);
shared_limit->curcount--;
printf("clients count = %d\\n", shared_limit->curcount);
pthread_mutex_unlock(&shared_limit->count_mutex);
exit(0);
}
}
else
{
close(client_sockfd);
}
}
}
void close_server(int sig)
{
printf("server closing...\\n");
if(shmdt(shared_memory) == -1)
{
fprintf(stderr,"shmdt failed\\n");
exit(1);
}
if(shmctl(shmid,IPC_RMID,0) == -1)
{
fprintf(stderr,"shmctl(IPC_RMID) failed\\n");
exit(1);
}
exit(0);
}
| 0
|
#include <pthread.h>
struct foo * fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo {
int f_count;
pthread_mutex_t f_lock;
struct foo * f_next;
int f_id;
};
struct foo *
foo_alloc(void) {
struct foo * fp = (struct foo *)malloc(sizeof(struct foo));
if (fp != 0) {
fp -> f_count = 1;
if (pthread_mutex_init(&fp -> f_lock, 0) != 0) {
free(fp);
return(0);
}
idx = (((unsigned long)fp) % 29);
pthread_mutex_lock(&hashlock);
fp -> f_next = fh[idx];
fh[idx] = fp -> f_next;
pthread_mutex_lock(&fp -> f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp -> f_lock);
}
return(fp);
}
void
foo_hold(struct foo * fp) {
pthread_mutex_lock(&fp -> f_lock);
fp -> f_count++;
pthread_mutex_unlock(&fp -> f_lock);
}
struct foo *
foo_find(int id) {
struct foo * fp = 0;
int idx;
idx = (((unsigned long)fp) % 29);
pthread_mutex_lock(&hashlock);
for (fp = fh[idx]; fp != 0; fp = fp -> f_next) {
if (fp -> f_id == id) {
fp -> f_count++;
break;
}
}
pthread_mutex_unlock(&hashlock);
return(fp);
}
void
foo_rele(struct foo * fp) {
struct foo * tfp;
int idx;
pthread_mutex_lock(&hashlock);
if (--fp -> f_count == 0) {
idx = (((unsigned long)fp) % 29);
tfp = fh[idx];
if (tfp == fp) {
fh[idx] == fp -> f_next;
}
else {
while (tfp -> f_next != fp) {
tfp = tfp -> f_next;
}
}
tfp -> f_next = fp -> f_next;
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp -> f_lock);
free(fp);
}
else {
pthread_mutex_unlock(&hashlock);
}
}
| 1
|
#include <pthread.h>
int antall;
void *spise(void *);
pthread_t *filosofer;
pthread_mutex_t *gaffler;
struct ider {
int id;
};
int main(void)
{
printf("Type a number: ");
scanf("%d", &antall);
struct ider *send[antall];
pthread_t *filosofer = malloc(sizeof(pthread_t)*antall);
gaffler = (pthread_mutex_t**)malloc(sizeof(pthread_mutex_t)*antall);
int i;
while (0 < 1) {
for (i = 0; i < antall; i++)
{
send[i] = (struct ider*) malloc(sizeof(struct ider));
send[i]->id = i;
}
for (i = 0; i < antall; i++)
{
pthread_mutex_init(&gaffler[i], 0);
}
for (i = 0; i < antall; i++)
{
pthread_create(&filosofer[i], 0,(void *)spise,(void *)send[i]);
}
for (i =0; i < antall; i++)
{
pthread_join(filosofer[i], 0);
}
for (i = 0; i < antall; i++)
{
pthread_mutex_destroy(&gaffler[i]);
}
}
return 0;
}
void *spise(void *arg)
{
struct ider *send=arg;
printf ("Filosof %d tenker\\n",send->id+1);
pthread_mutex_lock(&gaffler[send->id]);
pthread_mutex_lock(&gaffler[(send->id+1)%5]);
printf ("Filosof %d spiser!\\n", send->id+1);
sleep(1);
pthread_mutex_unlock(&gaffler[send->id]);
pthread_mutex_unlock(&gaffler[(send->id+1)%5]);
printf ("Filosof %d er ferdig å spise\\n", send->id+1);
return 0;
}
| 0
|
#include <pthread.h>
int total_words ;
pthread_mutex_t counter_lock = PTHREAD_MUTEX_INITIALIZER;
main(int ac, char *av[])
{
pthread_t t1, t2;
void *count_words(void *);
if ( ac != 3 ){
printf("usage: %s file1 file2\\n", av[0]);
exit(1);
}
total_words = 0;
pthread_create(&t1, 0, count_words, (void *) av[1]);
pthread_create(&t2, 0, count_words, (void *) av[2]);
pthread_join(t1, 0);
pthread_join(t2, 0);
printf("%5d: total words\\n", total_words);
}
void *count_words(void *f)
{
char *filename = (char *) f;
FILE *fp;
int c, prevc = '\\0';
if ( (fp = fopen(filename, "r")) != 0 ){
while( ( c = getc(fp)) != EOF ){
if ( !isalnum(c) && isalnum(prevc) ){
pthread_mutex_lock(&counter_lock);
total_words++;
pthread_mutex_unlock(&counter_lock);
}
prevc = c;
}
fclose(fp);
} else
perror(filename);
return 0;
}
| 1
|
#include <pthread.h>
static char _szFileBuffer[100 + 1];
static int _nBufferPointer;
pthread_mutex_t _muxLock;
void* WriterFunction(void* pvData);
void* ReaderFunction(void* pvData);
void WriteFile(const char * psz, char * pszNumber);
void ReadFile(char * pszBuffer, char * pszNumber);
int main (int argc, char *argv[])
{
pthread_t tWriter1, tWriter2, tWriter3, tReader1, tReader2, tReader3;
char szFirst[10] = "[1st]";
char szSecond[10] = "[2nd]";
char szThird[10] = "[3rd]";
char cInput;
memset(&_szFileBuffer, '\\0', 100 + 1);
_nBufferPointer = 0;
pthread_mutex_init(&_muxLock, 0);
pthread_create(&tWriter1, 0, WriterFunction, (void*)&szFirst);
pthread_create(&tWriter2, 0, WriterFunction, (void*)&szSecond);
pthread_create(&tWriter3, 0, WriterFunction, (void*)&szThird);
pthread_create(&tReader1, 0, ReaderFunction, (void*)&szFirst);
pthread_create(&tReader2, 0, ReaderFunction, (void*)&szSecond);
pthread_create(&tReader3, 0, ReaderFunction, (void*)&szThird);
printf("\\r\\nPress any key to exit...");
cInput = getchar();
pthread_mutex_destroy(&_muxLock);
return 0;
}
void* WriterFunction(void* pvData)
{
char* pszNumber = (char *)pvData;
char szData[50] = "|abcdefghijklmnopqrstuvwxyz-";
strcat((char *)&szData, pszNumber);
while(1)
{
WriteFile((const char *)&szData, pszNumber);
usleep(0);
}
return 0;
}
void* ReaderFunction(void* pvData)
{
char* pszNumber = (char *)pvData;
char szData[100 + 1];
while(1)
{
memset(&szData, '\\0', 100 + 1);
ReadFile((char *)&szData, pszNumber);
usleep(0);
}
return 0;
}
void WriteFile(const char * pszBuffer, char * pszNumber)
{
int i;
int nLenPsz = strlen(pszBuffer);
pthread_mutex_lock(&_muxLock);
printf("\\r\\n\\r\\n-------------------------------\\r\\nSTART WRITING: %s\\r\\n-------------------------------\\r\\n", pszNumber);
printf("\\r\\n\\r\\n%s File buffer before write:\\r\\n%s\\r\\n\\r\\nWriting:\\r\\n", pszNumber, _szFileBuffer);
for (i = 0; i < nLenPsz; i++)
{
printf("%c", pszBuffer[i]);
usleep(0);
_nBufferPointer = (_nBufferPointer >= 100) ? 0 : _nBufferPointer;
_szFileBuffer[_nBufferPointer] = pszBuffer[i];
if ((_nBufferPointer + 1) < 100)
{
_szFileBuffer[_nBufferPointer + 1] = '@';
}
else
{
_szFileBuffer[0] = '@';
}
_nBufferPointer++;
}
printf("\\r\\n\\r\\n%s File buffer after write:\\r\\n%s", pszNumber, _szFileBuffer);
printf("\\r\\n\\r\\n-------------------------------\\r\\nSTOP WRITING: %s\\r\\n-------------------------------\\r\\n", pszNumber);
pthread_mutex_unlock(&_muxLock);
}
void ReadFile(char * pszBuffer, char * pszNumber)
{
int i;
int nLenBuffer = strlen(_szFileBuffer);
pthread_mutex_lock(&_muxLock);
printf("\\r\\n\\r\\n-------------------------------\\r\\nSTART READING: %s\\r\\n-------------------------------\\r\\n", pszNumber);
for (i = 0; i < nLenBuffer; i++)
{
usleep(0);
pszBuffer[i] = _szFileBuffer[i];
}
printf("\\r\\n\\r\\n%s File buffer read:\\r\\n%s", pszNumber, _szFileBuffer);
printf("\\r\\n\\r\\n%s Returned buffer after read:\\r\\n%s", pszNumber, pszBuffer);
printf("\\r\\n\\r\\n-------------------------------\\r\\nSTOP READING: %s\\r\\n-------------------------------\\r\\n", pszNumber);
pthread_mutex_unlock(&_muxLock);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct glob{
int a;
int b;
}obj;
void *updater(void *arg){
printf("child thread has created for updating\\n");
pthread_mutex_lock(&mutex);
obj.a=10;
sleep(1);
obj.b=20;
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void *reader(void *arg){
printf("child thread has created for reading\\n");
pthread_mutex_lock(&mutex);
printf("mem1:%d\\n",obj.a);
printf("mem2:%d\\n",obj.b);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void main(void){
pthread_t tid1,tid2;
pthread_create(&tid1,0,updater,0);
sleep(1);
pthread_create(&tid2,0,reader,0);
pthread_join(tid1,0);
pthread_join(tid2,0);
}
| 1
|
#include <pthread.h>
int thread_count;
double a, b, h;
int n, local_n;
pthread_mutex_t mutex;
double total;
void *Thread_work(void* rank);
double Trap(double local_a, double local_b, int local_n,
double h);
double f(double x);
int main(int argc, char** argv) {
long i;
pthread_t* thread_handles;
total = 0.0;
if (argc != 2) {
fprintf(stderr, "usage: %s <number of threads>\\n", argv[0]);
exit(0);
}
thread_count = strtol(argv[1], 0, 10);
printf("Enter a, b, n\\n");
scanf("%lf %lf %d", &a, &b, &n);
h = (b-a)/n;
local_n = n/thread_count;
thread_handles = malloc (thread_count*sizeof(pthread_t));
pthread_mutex_init(&mutex, 0);
for (i = 0; i < thread_count; i++) {
pthread_create(&thread_handles[i], 0, Thread_work,
(void*) i);
}
for (i = 0; i < thread_count; i++) {
pthread_join(thread_handles[i], 0);
}
printf("With n = %d trapezoids, our estimate\\n",
n);
printf("of the integral from %f to %f = %19.15e\\n",
a, b, total);
pthread_mutex_destroy(&mutex);
free(thread_handles);
return 0;
}
void *Thread_work(void* rank) {
double local_a;
double local_b;
double my_int;
long my_rank = (long) rank;
local_a = a + my_rank*local_n*h;
local_b = local_a + local_n*h;
my_int = Trap(local_a, local_b, local_n, h);
pthread_mutex_lock(&mutex);
total += my_int;
pthread_mutex_unlock(&mutex);
return 0;
}
double Trap(
double local_a ,
double local_b ,
int local_n ,
double h ) {
double integral;
double x;
int i;
integral = (f(local_a) + f(local_b))/2.0;
x = local_a;
for (i = 1; i <= local_n-1; i++) {
x = local_a + i*h;
integral += f(x);
}
integral = integral*h;
return integral;
}
double f(double x) {
double return_val;
return_val = x*x;
return return_val;
}
| 0
|
#include <pthread.h>
struct arg_set {
char *fname;
int count;
};
struct arg_set *mailbox = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t flag = PTHREAD_COND_INITIALIZER;
main(int ac, char *av[])
{
pthread_t t1, t2;
struct arg_set args1, args2;
void *count_words(void *);
int reports_in = 0;
int total_words = 0;
if (ac != 3) {
printf("usage: %s file1 file2\\n", av[0]);
exit(1);
}
pthread_mutex_lock(&lock);
args1.fname = av[1];
args1.count = 0;
pthread_create(&t1, 0, count_words, (void *) &args1);
args2.fname = av[2];
args2.count = 0;
pthread_create(&t2, 0, count_words, (void *) &args2);
while (reports_in < 2) {
printf("MAIN: waiting for flag to go up\\n");
pthread_cond_wait(&flag, &lock2);
printf("MAIN: Wow! flag was raised, I have the lock\\n");
printf("%7d: %s\\n", mailbox->count, mailbox->fname);
total_words += mailbox->count;
if (mailbox == &args1)
pthread_join(t1, 0);
if (mailbox == &args2)
pthread_join(t2, 0);
mailbox = 0;
pthread_cond_signal(&flag);
reports_in++;
}
printf("%7d: total words\\n", total_words);
}
void *count_words(void *a)
{
struct arg_set *args = a;
FILE *fp;
int c, prevc = '\\0';
if ((fp = fopen(args->fname, "r")) != 0) {
while ((c = getc(fp)) != EOF) {
if (!isalnum(c) && isalnum(prevc))
args->count++;
prevc = c;
}
fclose(fp);
} else
perror(args->fname);
printf("COUNT: waiting to get lock\\n");
pthread_mutex_lock(&lock);
printf("COUNT: have lock, storing data\\n");
if (mailbox != 0) {
printf("COUNT: oops..mailbox not empty. wait for signal\\n");
pthread_cond_wait(&flag, &lock);
}
mailbox = args;
printf("COUNT: raising flag\\n");
pthread_cond_signal(&flag);
printf("COUNT: unlocking box\\n");
pthread_mutex_unlock(&lock);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock1;
void add_log_record_entry(char operation[], char state[], char filename[], int tid)
{
pthread_mutex_lock(&lock1);
FILE *fd = 0;
fd = fopen("journal.txt", "a");
fprintf(fd, "%d, %s, %s, %s\\n", tid, operation, filename, state);
fclose(fd);
pthread_mutex_unlock(&lock1);
}
void add_recovery_entry(int state)
{
pthread_mutex_lock(&lock1);
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
FILE *fd = 0;
fd = fopen("journal.txt", "a");
if(state == 7)
{
fprintf(fd, "RECOVERY START, %s", asctime (timeinfo));
}
else if(state == 8)
{
fprintf(fd, "RECOVERY END, %s", asctime (timeinfo));
}
fclose(fd);
pthread_mutex_unlock(&lock1);
}
struct last_transaction search_log_record_entry(char filename[])
{
struct last_transaction lt;
FILE* fd = 0;
long sz;
fd = fopen("journal.txt", "rb");
sz = fsize(fd);
if (sz > 0)
{
char buf[MAX];
char tmp[MAX];
char *token;
fseek(fd, sz, 0);
while (fgetsr(buf, sizeof(buf), fd) != 0)
{
if(strstr(buf, filename) != 0)
{
printf("%s\\n", buf);
strcpy(tmp,buf);
token = strtok(tmp,",");
while(isspace(*token)) token++;
printf("!%s\\n", token);
lt.tid = atoi(token);
token = strtok(0,",");
while(isspace(*token)) token++;
printf("!%s\\n", token);
strcpy(lt.operation, token);
token = strtok(0,",");
while(isspace(*token)) token++;
printf("!%s\\n", token);
strcpy(lt.fname, token);
token = strtok(0,",");
while(isspace(*token)) token++;
printf("!%s\\n", token);
size_t ln = strlen(token) - 1;
if(token[ln] == '\\n')
token[ln] = '\\0';
strcpy(lt.status, token);
break;
}
}
}
fclose(fd);
return lt ;
}
char* fgetsr(char* buf, int n, FILE* binaryStream)
{
long fpos;
int cpos;
int first = 1;
if (n <= 1 || (fpos = ftell(binaryStream)) == -1 || fpos == 0)
return 0;
cpos = n - 1;
buf[cpos] = '\\0';
for (;;)
{
int c;
if (fseek(binaryStream, --fpos, 0) != 0 || (c = fgetc(binaryStream)) == EOF)
return 0;
if (c == '\\n' && first == 0)
break;
first = 0;
if (c != '\\r')
{
unsigned char ch = c;
if (cpos == 0)
{
memmove(buf + 1, buf, n - 2);
++cpos;
}
memcpy(buf + --cpos, &ch, 1);
}
if (fpos == 0)
{
fseek(binaryStream, 0, 0);
break;
}
}
memmove(buf, buf + cpos, n - cpos);
return buf;
}
long fsize(FILE* binaryStream)
{
long ofs, ofs2;
int result;
if (fseek(binaryStream, 0, 0) != 0 || fgetc(binaryStream) == EOF)
return 0;
ofs = 1;
while ((result = fseek(binaryStream, ofs, 0)) == 0 && (result = (fgetc(binaryStream) == EOF)) == 0 && ofs <= LONG_MAX / 4 + 1)
ofs *= 2;
if (result != 0)
ofs /= 2;
for (ofs2 = ofs / 2; ofs2 != 0; ofs2 /= 2)
if (fseek(binaryStream, ofs + ofs2, 0) == 0 && fgetc(binaryStream) != EOF)
ofs += ofs2;
if (ofs == LONG_MAX)
return -1;
return ofs + 1;
}
void create_tid(struct operation *op1)
{
pthread_mutex_lock(&lock1);
time_t t;
srand((unsigned) time(&t));
op1->tid = rand() % 40000;
pthread_mutex_unlock(&lock1);
}
| 0
|
#include <pthread.h>
int buf[4];
int first_occupied_slot = 0;
int first_empty_slot = 4;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;;
int count;
int pending_posts;
} sem_t;
sem_t sem_prod;
sem_t sem_cons;
void sem_init(sem_t *sem, int new_count) {
pthread_mutex_lock(&mut);
sem->count = new_count;
sem->pending_posts = new_count;
pthread_mutex_unlock(&mut);
}
void sem_post(sem_t *sem) {
pthread_mutex_lock(&mut);
sem->count = sem->count + 1;
sem->pending_posts = sem->pending_posts + 1;
pthread_mutex_unlock(&mut);
}
void sem_wait(sem_t *sem) {
printf("In sem_wait...\\n");
int done;
pthread_mutex_lock(&mut);
sem_t mysem = *(sem);
sem->count = sem->count - 1;
if (sem->count < 0) {
SLEEP:
pthread_mutex_unlock(&mut);
while (sem->pending_posts <= 0) { printf(""); }
pthread_mutex_lock(&mut);
if (sem->pending_posts <= 0) { goto SLEEP; }
}
if (sem->pending_posts > 0) {
sem->pending_posts = sem->pending_posts - 1;
}
else { goto SLEEP; }
pthread_mutex_unlock(&mut);
return;
}
void add(int val) {
if (first_empty_slot >= 4) { first_empty_slot = 0; }
buf[first_empty_slot] = val;
first_empty_slot++;
if (first_empty_slot >= 4) { first_empty_slot = 0; }
return;
}
int rem() {
if (first_occupied_slot >= 4) { first_occupied_slot = 0; }
int val = buf[first_occupied_slot];
first_occupied_slot++;
if (first_occupied_slot >= 4) { first_occupied_slot = 0; }
return val;
}
void *consumer(void *arg) {
int i ;
sem_wait(&sem_cons);
i = rem();
printf("CONSUMER REMOVED %d\\n", i);
sleep( rand() % 5 );
sem_post(&sem_prod);
}
void *producer(void *arg) {
int i;
for(i = 0; i < 4; i++) {
sem_wait(&sem_prod);
printf("ADDING %d!!!\\n",i);
add(i);
sleep( rand() % 5 );
sem_post(&sem_cons);
}
}
int main() {
sem_init(&sem_prod, 4);
sem_init(&sem_cons, 0);
pthread_t producer_t;
pthread_t consumer_t;
pthread_create(&producer_t, 0, producer, 0);
pthread_create(&consumer_t, 0, consumer, 0);
pthread_join(producer_t, 0);
pthread_join(consumer_t, 0);
int i = 0;
return 0;
}
| 1
|
#include <pthread.h>
char shared[10000];
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
void* producer (void* a)
{
int i,j;
pthread_mutex_lock(&mutex);
for (i=0; i<10000-1; i++)
{
shared[i]='p';
for(j=0;j<10000;j++) ;
}
shared[i] = '\\0';
pthread_mutex_unlock(&mutex);
}
void* consumer(void* a)
{
int i,j;
pthread_mutex_lock(&mutex);
for (i=0; i<10000-1; i++)
{
shared[i]='c';
for(j=0;j<10000;j++) ;
}
shared[i] = '\\0';
pthread_mutex_unlock(&mutex);
}
int main()
{
pthread_t pid;
pthread_t cid;
int count=0, corrupt, i;
pthread_mutex_init(&mutex,0);
int j=0;
while(j<10) {
pthread_create(&pid, 0, producer, 0);
pthread_create(&cid, 0, consumer, 0);
pthread_join(pid, 0);
pthread_join(cid, 0);
corrupt = 0;
for (i=1; i<10000-1; i++)
{
if (shared[i] != shared[i-1])
{
corrupt = 1;
break;
}
}
if (corrupt)
printf("Memory corruption happened: %d\\n", count);
else
printf("Coding is fun...No corruption\\n");
count++;
j++;
}
}
| 0
|
#include <pthread.h>
static int incCount = 0;
static int decCount = 0;
int count;
int incCount;
int decCount;
pthread_mutex_t lock;
int id;
} foo_t;
foo_t *fooInit(int id)
{
foo_t *foo = (foo_t *) malloc(sizeof(foo_t));
if (foo) {
foo->id = id;
foo->count = 1;
pthread_mutex_init(&foo->lock, 0);
}
return foo;
}
void fooInc(foo_t *foo)
{
if (foo) {
pthread_mutex_lock(&foo->lock);
printf("+");
foo->count++;
incCount++;
pthread_mutex_unlock(&foo->lock);
}
}
void fooDec(foo_t *foo)
{
if (foo) {
pthread_mutex_lock(&foo->lock);
printf("-");
foo->count--;
decCount++;
pthread_mutex_unlock(&foo->lock);
}
}
int fooCount(foo_t *foo)
{
int count = 0;
if (foo) {
pthread_mutex_lock(&foo->lock);
count = foo->count;
pthread_mutex_unlock(&foo->lock);
}
return count;
}
void fooDestroy(foo_t *foo)
{
if (foo) {
pthread_mutex_unlock(&foo->lock);
pthread_mutex_destroy(&foo->lock);
free(foo);
}
}
static foo_t *globalFoo;
void *addThread(void *arg)
{
while (fooCount(globalFoo) < 10) {
fooInc(globalFoo);
}
pthread_exit((void *) 0);
}
void *subThread(void *arg)
{
while (fooCount(globalFoo) > 0) {
fooDec(globalFoo);
}
pthread_exit((void *) 0);
}
int main(void)
{
pthread_t addThreadId;
pthread_t subThreadId;
void *retval;
globalFoo = fooInit(1);
pthread_create(&addThreadId, 0, addThread, 0);
pthread_create(&subThreadId, 0, subThread, 0);
pthread_join(addThreadId, &retval);
pthread_join(subThreadId, &retval);
printf("\\nFinal tally:\\n");
printf("Inc Count = %d\\n", incCount);
printf("Dec Count = %d\\n", decCount);
fooDestroy(globalFoo);
exit((long) retval);
}
| 1
|
#include <pthread.h>
static int busy_wait_on_fence(int fence)
{
int error, active;
do {
error = sync_fence_count_with_status(fence, FENCE_STATUS_ERROR);
ASSERT(error == 0, "Error occurred on fence\\n");
active = sync_fence_count_with_status(fence,
FENCE_STATUS_ACTIVE);
} while (active);
return 0;
}
static struct {
int iterations;
int threads;
int counter;
int consumer_timeline;
int *producer_timelines;
pthread_mutex_t lock;
} test_data_mpsc;
static int mpsc_producer_thread(void *d)
{
int id = (long)d;
int fence, valid, i;
int *producer_timelines = test_data_mpsc.producer_timelines;
int consumer_timeline = test_data_mpsc.consumer_timeline;
int iterations = test_data_mpsc.iterations;
for (i = 0; i < iterations; i++) {
fence = sw_sync_fence_create(consumer_timeline, "fence", i);
valid = sw_sync_fence_is_valid(fence);
ASSERT(valid, "Failure creating fence\\n");
if ((iterations + id) % 8 != 0) {
ASSERT(sync_wait(fence, -1) > 0,
"Failure waiting on fence\\n");
} else {
ASSERT(busy_wait_on_fence(fence) == 0,
"Failure waiting on fence\\n");
}
pthread_mutex_lock(&test_data_mpsc.lock);
test_data_mpsc.counter++;
pthread_mutex_unlock(&test_data_mpsc.lock);
ASSERT(sw_sync_timeline_inc(producer_timelines[id], 1) == 0,
"Error advancing producer timeline\\n");
sw_sync_fence_destroy(fence);
}
return 0;
}
static int mpcs_consumer_thread(void)
{
int fence, merged, tmp, valid, it, i;
int *producer_timelines = test_data_mpsc.producer_timelines;
int consumer_timeline = test_data_mpsc.consumer_timeline;
int iterations = test_data_mpsc.iterations;
int n = test_data_mpsc.threads;
for (it = 1; it <= iterations; it++) {
fence = sw_sync_fence_create(producer_timelines[0], "name", it);
for (i = 1; i < n; i++) {
tmp = sw_sync_fence_create(producer_timelines[i],
"name", it);
merged = sync_merge("name", tmp, fence);
sw_sync_fence_destroy(tmp);
sw_sync_fence_destroy(fence);
fence = merged;
}
valid = sw_sync_fence_is_valid(fence);
ASSERT(valid, "Failure merging fences\\n");
if (iterations % 8 != 0) {
ASSERT(sync_wait(fence, -1) > 0,
"Producers did not increment as expected\\n");
} else {
ASSERT(busy_wait_on_fence(fence) == 0,
"Producers did not increment as expected\\n");
}
ASSERT(test_data_mpsc.counter == n * it,
"Counter value mismatch!\\n");
ASSERT(sw_sync_timeline_inc(consumer_timeline, 1) == 0,
"Failure releasing producer threads\\n");
sw_sync_fence_destroy(fence);
}
return 0;
}
int test_consumer_stress_multi_producer_single_consumer(void)
{
int iterations = 1 << 12;
int n = 5;
long i, ret;
int producer_timelines[n];
int consumer_timeline;
pthread_t threads[n];
consumer_timeline = sw_sync_timeline_create();
for (i = 0; i < n; i++)
producer_timelines[i] = sw_sync_timeline_create();
test_data_mpsc.producer_timelines = producer_timelines;
test_data_mpsc.consumer_timeline = consumer_timeline;
test_data_mpsc.iterations = iterations;
test_data_mpsc.threads = n;
test_data_mpsc.counter = 0;
pthread_mutex_init(&test_data_mpsc.lock, 0);
for (i = 0; i < n; i++) {
pthread_create(&threads[i], 0, (void * (*)(void *))
mpsc_producer_thread, (void *)i);
}
ret = mpcs_consumer_thread();
for (i = 0; i < n; i++)
pthread_join(threads[i], 0);
return ret;
}
| 0
|
#include <pthread.h>
int num_of_threads = 5;
int end = 0;
pthread_barrier_t barrier;
pthread_mutex_t mut;
int dif = 10000;
struct helper {
int rank;
double localPi;
};
int max = 0;
void* calculate(void *arg) {
int rank = (*((struct helper*)arg)).rank;
(*((struct helper*)arg)).localPi = 0;
double localPi = 0;
int total_iter = 0;
int check_num = dif * num_of_threads;
int i = rank;
while (end != 1) {
for (; i < check_num ; i += num_of_threads) {
total_iter++;
localPi += (((i % 2) == 0)?(1.0):(-1.0)) / (2. * i + 1.);
}
check_num += dif * num_of_threads;
}
pthread_mutex_lock(&mut);
if (total_iter >= max)
max = total_iter;
pthread_mutex_unlock(&mut);
pthread_barrier_wait(&barrier);
for (; total_iter < max; i += num_of_threads) {
total_iter++;
localPi += (((i % 2) == 0)?(1.0):(-1.0)) / (2. * i + 1.);
}
((struct helper*)arg)->localPi = localPi;
printf("local Pi %f in rank %d iter: %d\\n", localPi, rank, total_iter);
return 0;
}
void handler(int sig) {
printf("\\n-----eeeendn-----\\n");
end = 1;
}
int main(int argc, char *argv[]) {
if (argc > 1) num_of_threads = atoi(argv[1]);
pthread_barrier_init(&barrier, 0, num_of_threads);
pthread_mutex_init(&mut, 0);
struct helper* help = (struct helper*)malloc(sizeof(struct helper) * num_of_threads);
signal(SIGINT, handler);
double pi = 0;
for (int i = 0; i < num_of_threads; i++) {
help[i].rank = i;
}
pthread_t* threads = (pthread_t*)malloc(sizeof(pthread_t) * num_of_threads);
for (int i = 0; i < num_of_threads; i++)
pthread_create(&threads[i], 0, calculate, &help[i]);
for (int i = 0; i < num_of_threads; i++) {
pthread_join(threads[i], 0);
pi += help[i].localPi;
}
pi *= 4.;
printf("PI: %.8f\\n", pi);
pthread_barrier_destroy(&barrier);
free(help);
free(threads);
return 0;
}
| 1
|
#include <pthread.h>
static int x = 0;
static pthread_mutex_t mlock;
void th1_count();
void th2_count();
void delay( long nanosec );
int main(int argc, char** argv ) {
pthread_t thread1, thread2;
pthread_mutex_init(&mlock, 0);
if (pthread_create(&thread1,
0,
(void *) th1_count,
0 ) != 0)
perror("pthread_create"), exit(1);
if (pthread_create(&thread2,
0,
(void *) th2_count,
0 ) != 0)
perror("pthread_create"), exit(1);
if (pthread_join(thread1, 0) != 0)
perror("pthread_join"),exit(1);
if (pthread_join(thread2, 0) != 0)
perror("pthread_join"),exit(1);
return 0;
}
void th1_count() {
int i;
for (i = 0; i < 30; i++) {
pthread_mutex_lock( &mlock );
printf("thread[1,%d]: x = %d\\n", i, x );
x += 1;
pthread_mutex_unlock( &mlock );
delay( 3000 );
}
}
void th2_count() {
int i;
for (i = 0; i < 30; i++) {
pthread_mutex_lock( &mlock );
printf("thread[2,%d]: x = %d\\n", i, x );
x+= 1;
pthread_mutex_unlock( &mlock );
delay( 1000 );
}
}
void delay( long nanosec ) {
struct timespec t_spec;
t_spec.tv_sec = 0;
t_spec.tv_nsec = nanosec;
nanosleep( &t_spec, 0 );
}
| 0
|
#include <pthread.h>
pthread_mutex_t beers_lock = PTHREAD_MUTEX_INITIALIZER;
void error(char *msg)
{
fprintf(stderr, "%s, %s\\n", msg, strerror(errno));
exit(1);
}
int beers = 2000000;
void* drink_lots(void *a)
{
int i;
for (i = 0; i < 100000; i++) {
pthread_mutex_lock(&beers_lock);
beers--;
pthread_mutex_unlock(&beers_lock);
}
printf("beers = %i \\n", beers);
return 0;
}
int main()
{
pthread_t threads[20];
int t;
printf("%i bottles of beer on the wall\\n%i bottles of beer\\n", beers, beers);
for (t = 0; t < 20; t++) {
if(pthread_create(&threads[t], 0, drink_lots, 0))
error("Can't create thread");
}
void* result;
for (t = 0; t < 20; t++) {
if(pthread_join(threads[t], &result))
error("cant join thread");
}
printf("There are now %i bottels of beer on the wall\\n", beers);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t space_available = PTHREAD_COND_INITIALIZER;
pthread_cond_t data_available = PTHREAD_COND_INITIALIZER;
int b[10];
int size = 0;
int front = 0, rear = 0;
void add_buffer(int i) {
b[rear] = i;
rear = (rear + 1) % 10;
size++;
}
int get_buffer(){
int v;
v = b[front];
front= (front+1) % 10;
size--;
return v ;
}
void* producer(void *arg) {
int i = 0;
printf("producter starting...\\n");
while (1) {
pthread_mutex_lock(&mutex);
if (size == 10) {
pthread_cond_wait(&space_available, &mutex);
}
printf("producer adding %i...\\n", i);
add_buffer(i);
pthread_cond_signal(&data_available);
pthread_mutex_unlock(&mutex);
i = i + 1;
}
pthread_exit(0);
}
void* consumer(void *arg) {
int i,v;
printf("consumer starting...\\n");
for (i=0;i<100;i++) {
pthread_mutex_lock(&mutex);
if (size == 0) {
pthread_cond_wait(&data_available, &mutex);
}
v = get_buffer();
printf("consumer getting %i...\\n", v);
pthread_cond_signal(&space_available);
pthread_mutex_unlock(&mutex);
}
printf("consuming finishing...\\n");
pthread_exit(0);
}
int main(int argc, char* argv[]) {
pthread_t producer_thread;
pthread_t consumer_thread;
pthread_create(&consumer_thread, 0, consumer, 0);
pthread_create(&producer_thread, 0, producer, 0);
pthread_join(consumer_thread, 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_t g_thread[8];
pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
int g_mode = -1;
FILE* g_f = 0;
char* g_line = 0;
int g_index = 0;
static void runcmd(char* cmd)
{
while(system(cmd) != 0)
{
LOGE("%s failed", cmd);
usleep(1000000);
}
}
static void setacl(int index, int zoom, int x, int y)
{
LOGI("%i: zoom=%i, x=%i, y=%i", index, zoom, x, y);
char cmd[256];
if(g_mode == 0)
{
snprintf(cmd, 256, "gsutil acl set -a public-read gs://goto/ned/%i/%i_%i.nedgz", zoom, x, y);
runcmd(cmd);
}
else if(g_mode == 1)
{
snprintf(cmd, 256, "gsutil acl set -a public-read gs://goto/osm/%i/%i_%i.pak", zoom, x, y);
runcmd(cmd);
}
else if(g_mode == 2)
{
snprintf(cmd, 256, "gsutil acl set -a public-read gs://goto/hillshade/%i/%i_%i.pak", zoom, x, y);
runcmd(cmd);
}
else if(g_mode == 3)
{
int month;
for(month = 1; month <= 12; ++month)
{
snprintf(cmd, 256, "gsutil acl set -a public-read gs://goto/bluemarble/%i/%i/%i_%i.pak", month, zoom, x, y);
runcmd(cmd);
}
}
}
static int getnode(int* index, int* zoom, int* x, int* y)
{
pthread_mutex_lock(&g_mutex);
int ret = 0;
size_t n = 0;
ret = getline(&g_line, &n, g_f);
if(ret <= 0)
{
goto fail_getline;
}
if(sscanf(g_line, "%i %i %i", zoom, x, y) != 3)
{
LOGE("invalid line=%s", g_line);
ret = 0;
goto fail_sscanf;
}
*index = g_index;
++g_index;
pthread_mutex_unlock(&g_mutex);
return 1;
fail_sscanf:
fail_getline:
pthread_mutex_unlock(&g_mutex);
return 0;
}
static void* run_thread(void* arg)
{
int index;
int zoom;
int x;
int y;
while(getnode(&index, &zoom, &x, &y))
{
setacl(index, zoom, x, y);
}
return 0;
}
int main(int argc, char** argv)
{
if(argc != 2)
{
LOGE("usage: %s [data]", argv[0]);
return 1;
}
if(strncmp(argv[1], "ned", 256) == 0)
{
g_mode = 0;
}
else if(strncmp(argv[1], "osm", 256) == 0)
{
g_mode = 1;
}
else if(strncmp(argv[1], "hillshade", 256) == 0)
{
g_mode = 2;
}
else if(strncmp(argv[1], "bluemarble", 256) == 0)
{
g_mode = 3;
}
else
{
LOGE("invalid data=%s", argv[1]);
return 1;
}
char fname[256];
snprintf(fname, 256, "%s/%s.list", argv[1], argv[1]);
g_f = fopen(fname, "r");
if(g_f == 0)
{
LOGE("failed to open %s", fname);
return 1;
}
int i;
for(i = 0; i < 8; ++i)
{
if(pthread_create(&g_thread[i], 0, run_thread, (void*) 0) != 0)
{
LOGW("pthread_create failed");
}
}
for(i = 0; i < 8; ++i)
{
if(g_thread[i])
{
pthread_join(g_thread[i], 0);
}
}
free(g_line);
fclose(g_f);
return 0;
}
| 1
|
#include <pthread.h>
static int N = 4;
int M = 10;
int X = 50;
int Y = 2;
int Z = 5;
int cantPersonas;
sem_t sem_cajeros_disponibles;
sem_t sem_personas_en_fila;
pthread_mutex_t mutex;
bool cajerosMaximo;
void *persona(void *param);
void *cajero(void *param);
void *generarPersona(void *param);
void crearCajero();
int main(){
cajerosMaximo = 0;;
cantPersonas = 0;
sem_init(&sem_cajeros_disponibles, 0, N);
sem_init(&sem_personas_en_fila, 0, 0);
pthread_mutex_init(&mutex, 0);
printf("Atendiendo con %d Cajeros\\n", N/2);
int i;
for(i = 0; i < N/2; i++){
crearCajero();
}
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tid, &attr, generarPersona, 0);
sleep (120);
}
void* generarPersona(void *param){
unsigned int seed = time(0);
int seconds;
while (1) {
int value = rand_r(&seed);
int length = Z - Y + 1;
seconds = Y + (value % length);
sleep(seconds);
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tid, &attr, persona, 0);
}
}
void crearCajero(){
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tid, &attr, cajero, 0);
}
void *persona(void *param) {
unsigned int seed = time(0);
int seconds;
if(cantPersonas < M){
sem_post(&sem_personas_en_fila);
printf("Persona entro a fila\\n");
cantPersonas++;
}else{
printf("Persona se fue\\n");
}
if((cantPersonas *100) / M > 50 && !cajerosMaximo){
cajerosMaximo = 1;
int i;
for(i = 0; i < N/2; i++){
crearCajero();
}
printf("Cantidad de personas en fila: %d\\n", cantPersonas);
printf("Atendiendo con %d Cajeros\\n", N);
}
}
void *cajero(void *param) {
unsigned int seed = time(0);
int seconds;
while (1) {
sem_wait(&sem_cajeros_disponibles);
sem_wait(&sem_personas_en_fila);
pthread_mutex_lock(&mutex);
cantPersonas--;
pthread_mutex_unlock(&mutex);
int value = rand_r(&seed);
int length = X - 1 + 1;
seconds = 1 + (value % length);
printf("Cajero Atendiendo nevo Cliente\\n");
sleep (seconds);
printf("Cajero termino de atender en %d segundos\\n", seconds);
sem_post(&sem_cajeros_disponibles);
}
}
| 0
|
#include <pthread.h>
int global_count = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *customer_routine(void *arg)
{
while (1) {
pthread_mutex_lock(&mutex);
while (global_count == 0) {
printf("customer %d wait.\\n", (int)arg);
pthread_cond_wait(&cond, &mutex);
printf("customer %d wakeup.\\n", (int)arg);
}
global_count--;
printf("cusotmer %d custom.\\n", (int)arg);
pthread_mutex_unlock(&mutex);
}
sleep(1);
pthread_exit(0);
}
void *product_routine(void *arg)
{
while (1) {
pthread_mutex_lock(&mutex);
printf("producter %d product %d start.\\n", (int)arg, global_count);
global_count++;
printf("producter %d product %d end.\\n", (int)arg, global_count);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int thread_customer_count = 10;
printf("please enter thread customer count:");
scanf("%d", &thread_customer_count);
int thread_product_count = 10;
printf("please enter thread prodecter count:");
scanf("%d", &thread_product_count);
pthread_t tidarr[200];
int index = 0;
for (; index < thread_customer_count; ++index) {
pthread_create(&tidarr[index], 0, customer_routine, (void *)index);
}
for (index = 0; index < thread_product_count; ++index) {
pthread_create(&tidarr[index + thread_customer_count], 0, product_routine, (void *)index);
}
for (index = 0; index < thread_customer_count + thread_product_count; ++index) {
pthread_join(tidarr[index], 0);
}
printf("main exited.\\n");
return 0;
}
| 1
|
#include <pthread.h>
static int n;
static pthread_mutex_t* locks;
void cudaMemcpy()
{
sleep(500);
}
int compute_sums()
{
cudaMemcpy();
}
void* prefix_sum(void* p)
{
int self = * ((int*) p);
printf ("I, %d, have just woken from contemplating existence\\n", self);
pthread_mutex_lock(locks + self);
printf ("I, %d, have picked up my left fork. I must have another nap\\n", self);
usleep(rand() % (n * 100));
pthread_mutex_lock(locks + ((self + 1) % n));
printf ("I, %d, have picked up my right fork\\n", self);
pthread_mutex_unlock(locks + ((self + 1) % n));
pthread_mutex_unlock(locks + self);
sleep(1000);
printf ("I have dined spendidly this evening %d\\n", self);
return 0;
}
int main(int argc, char** argv)
{
int i;
pthread_t* threads;
pthread_attr_t* thread_attrs;
int *data;
if (argc > 1)
{
n = atoi(argv[1]);
}
else n = 5;
printf ("Creating %d hungry philosophers\\n", n);
threads = calloc(sizeof(pthread_t), n);
thread_attrs = calloc(sizeof(pthread_attr_t), n);
data = calloc(sizeof(int), n);
locks = calloc(sizeof(pthread_mutex_t), n);
for (i = 0; i < n ; i++)
{
pthread_attr_init(thread_attrs + i);
pthread_mutex_init(locks + i, 0);
data[i] = i;
}
for (i = 0; i < n ; i++)
{
pthread_create(threads + i, thread_attrs + i, &prefix_sum, data + i);
}
compute_sums();
while (--i > 0)
{
pthread_join(threads[i], 0);
}
}
| 0
|
#include <pthread.h>
extern int makethread(void *(*) (void *), void *);
struct to_info {
void (*to_fn) (void *);
void *to_arg;
struct timespec to_wait;
};
void
clock_gettime(int fd, struct timespec *tsp)
{
struct timeval tv;
gettimeofday(&tv, 0);
tsp->tv_sec = tv.tv_sec;
tsp->tv_nsec = tv.tv_usec * 1000;
}
void *
timeout_helper(void *arg)
{
struct to_info *tip;
tip = (struct to_info *) arg;
printf("in timeout_helper\\n");
nanosleep((&tip->to_wait), (0));
(*tip->to_fn)(tip->to_arg);
free(arg);
return(0);
}
void
timeout(const struct timespec *when, void (*func)(void *), void *arg)
{
struct timespec now;
struct to_info *tip;
int err;
clock_gettime(0, &now);
if ((when->tv_sec) > now.tv_sec ||
(when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec))
{
tip = malloc(sizeof(struct to_info));
if (tip != 0)
{
tip->to_fn = func;
tip->to_arg = arg;
tip->to_wait.tv_sec = when->tv_sec - now.tv_sec;
if (when->tv_nsec >= now.tv_nsec)
{
tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec;
}
else
{
tip->to_wait.tv_sec--;
tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec;
}
err = makethread(timeout_helper, (void *)tip);
if (err == 0)
{
printf("makethread success");
return;
}
else
free(tip);
}
}
(*func)(arg);
}
pthread_mutexattr_t attr;
pthread_mutex_t mutex;
void
retry(void *arg)
{
pthread_mutex_lock(&mutex);
printf("retry function\\n");
pthread_mutex_unlock(&mutex);
}
int
main(void)
{
int err, condition = 1, arg;
struct timespec when;
if ((err = pthread_mutexattr_init(&attr)) != 0)
err_exit(err, "pthread_mutexattr_init failed");
if ((err = pthread_mutexattr_settype(&attr,
PTHREAD_MUTEX_RECURSIVE)) != 0)
err_exit(err, "can't set recursive type");
if ((err = pthread_mutex_init(&mutex, &attr)) != 0)
err_exit(err, "can't create recursive mutex");
pthread_mutex_lock(&mutex);
if (condition) {
clock_gettime(0, &when);
when.tv_sec += 10;
timeout(&when, retry, (void *)((unsigned long)arg));
}
pthread_mutex_unlock(&mutex);
exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t adz_mutex = PTHREAD_MUTEX_INITIALIZER;
int adz_updated = 0;
char adz_current_text[ADZ_LENGTH];
pthread_mutex_t bookz_mutex = PTHREAD_MUTEX_INITIALIZER;
int bookz_done = 0;
void
display_adz(int fdout)
{
char text[ADZ_LENGTH];
pthread_mutex_lock(&adz_mutex);
strncpy(text, adz_current_text, ADZ_LENGTH);
adz_updated = 0;
pthread_mutex_unlock(&adz_mutex);
write(fdout, "\\n", 1);
write(fdout, text, ADZ_LENGTH);
write(fdout, "\\n\\n", 2);
}
long
start_adz(char id, int fdout)
{
char name[] = "?.adz";
char delay_field[3], line[ADZ_LENGTH];
int delay, fdin, keep_going;
long count;
ssize_t n;
count = 0;
name[0] = id;
fdin = open(name, O_RDONLY);
if (fdin >= 0)
{
keep_going = 1;
while (keep_going &&
((n = read(fdin, line, ADZ_LENGTH)) == ADZ_LENGTH))
{
delay_field[0] = line[0];
delay_field[1] = line[1];
delay_field[2] = '\\0';
delay = atoi(delay_field);
printf("delay %d\\n",delay);
pthread_mutex_lock(&adz_mutex);
strncpy(adz_current_text, line+2, ADZ_LENGTH-2);
adz_updated = 1;
pthread_mutex_unlock(&adz_mutex);
++count;
sleep(delay);
pthread_mutex_lock(&bookz_mutex);
keep_going = !bookz_done;
pthread_mutex_unlock(&bookz_mutex);
}
}else printf("unable to open file\\n");
close(fdin);
return count;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t _lock = PTHREAD_MUTEX_INITIALIZER;
static void cmd_queue_cleanup(struct cmd_queue *q);
int
cmd_queue_init(struct cmd_queue *queue)
{
int err = 0;
pthread_mutex_lock(&_lock);
TAILQ_INIT(&queue->cmdq_head);
err = pthread_mutex_init(&queue->cmdq_lock, 0);
if (err != 0) {
printf("%s pthread_mutex_init fail : sys %d \\n", __func__, err);
}
err = pthread_cond_init(&queue->cmdq_cond, 0);
if (err != 0) {
printf("%s pthread_cond_init fail : sys %d \\n", __func__, err);
}
pthread_mutex_unlock(&_lock);
return err;
}
void
cmd_queue_finish(struct cmd_queue *queue)
{
int err = 0;
pthread_mutex_lock(&_lock);
cmd_queue_cleanup(queue);
err = pthread_mutex_destroy(&queue->cmdq_lock);
if (err != 0) {
printf("%s pthread_mutex_destroy fail : sys %d\\n",__func__, err);
}
err = pthread_cond_destroy(&queue->cmdq_cond);
if (err != 0) {
printf("%s pthread_cond_destroy fail : sys %d\\n",__func__, err);
}
memset(queue, 0, sizeof(*queue));
pthread_mutex_unlock(&_lock);
}
static void
cmd_queue_cleanup(struct cmd_queue *q)
{
struct cmd_item *cmd;
while(!TAILQ_EMPTY(&q->cmdq_head)) {
cmd = TAILQ_FIRST(&q->cmdq_head);
cmd_destroy(cmd);
TAILQ_REMOVE(&q->cmdq_head, cmd, cmdi_link);
}
}
void cmd_enqueue(struct cmd_queue *q, struct cmd_item *cmd)
{
int is_empty = 0;
pthread_mutex_lock(&(q)->cmdq_lock);;
if (TAILQ_EMPTY(&q->cmdq_head))
is_empty = 1;
TAILQ_INSERT_TAIL(&q->cmdq_head, cmd, cmdi_link);
if (is_empty)
pthread_cond_signal(&q->cmdq_cond);
pthread_mutex_unlock(&(q)->cmdq_lock);;
}
struct cmd_item *
cmd_dequeue(struct cmd_queue *q)
{
int err;
struct cmd_item *cmd;
pthread_mutex_lock(&(q)->cmdq_lock);;
while (TAILQ_EMPTY(&q->cmdq_head))
pthread_cond_wait(&q->cmdq_cond, &q->cmdq_lock);
if (TAILQ_EMPTY(&q->cmdq_head)) {
cmd = 0;
} else {
cmd = TAILQ_FIRST(&q->cmdq_head);
TAILQ_REMOVE(&q->cmdq_head, cmd, cmdi_link);
}
pthread_mutex_unlock(&(q)->cmdq_lock);;
return cmd;
}
int
cmd_create(int sid, int flags, enum cmd_num cmdno, union cmd_arg arg, struct cmd_item **cmd0)
{
struct cmd_item *cmd;
if (flags & CMD_IFLAG_ASYNC) {
cmd = calloc(1, sizeof(*cmd));
if (cmd == 0) {
return -1;
}
*cmd0 = cmd;
} else {
if (*cmd0 == 0) {
return -2;
}
cmd = *cmd0;
memset(cmd, 0, sizeof(*cmd));
}
cmd->cmdi_flags = flags;
cmd->cmdi_sid = sid;
cmd->cmdi_error = 0;
cmd->cmdi_cmdno = cmdno;
cmd->cmdi_arg = arg;
return 0;
}
void
cmd_destroy(struct cmd_item *cmd)
{
if (cmd == 0) {
return ;
}
if (cmd->cmdi_flags & CMD_IFLAG_FREEARG){
free(cmd->cmdi_arg.cmda_ptr);
cmd->cmdi_arg.cmda_ptr = 0;
}
if (cmd->cmdi_flags & CMD_IFLAG_ASYNC) {
free(cmd);
}
}
| 1
|
#include <pthread.h>
int count[] = {0, 0};
pthread_mutex_t waiting[2];
pthread_mutex_t mutex, busy;
void arrive(int direction){
pthread_mutex_lock(&waiting[direction]);
pthread_mutex_lock(&mutex);
count[direction] += 1;
if (count[direction] == 1){
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&busy);
}
else {
pthread_mutex_unlock(&mutex);
}
pthread_mutex_unlock(&waiting[direction]);
}
void leave(int direction){
pthread_mutex_lock(&mutex);
count[direction] -= 1;
if (count[direction] == 0){
pthread_mutex_unlock(&busy);
}
pthread_mutex_unlock(&mutex);
}
int id_count = 0;
void* vehicle1(void* args) {
pthread_mutex_lock(&mutex);
int id = id_count++;
pthread_mutex_unlock(&mutex);
int i;
for (i = 0; i < 1; i++) {
printf("%d arrive from direction 0\\n",id);
arrive(0);
printf("%d in the tunnel\\n",id);
leave(0);
printf("%d leave from direction 0\\n",id);
}
pthread_exit(0);
}
void* vehicle2(void* args) {
pthread_mutex_lock(&mutex);
int id = id_count++;
pthread_mutex_unlock(&mutex);
int i;
for (i = 0; i < 1; i++) {
printf("%d arrive from direction 1\\n",id);
arrive(1);
printf("%d in the tunnel\\n",id);
leave(1);
printf("%d leave from direction 1\\n",id);
}
pthread_exit(0);
}
int main() {
pthread_mutex_init(&mutex, 0);
pthread_mutex_init(&busy, 0);
pthread_mutex_init(&waiting[0], 0);
pthread_mutex_init(&waiting[1], 0);
pthread_t vehicles1[100];
pthread_t vehicles2[100];
int i;
for (i = 0; i < 100; i++) {
pthread_create(&vehicles1[i], 0, vehicle1, 0);
pthread_create(&vehicles2[i], 0, vehicle2, 0);
}
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t check_init_lock = PTHREAD_MUTEX_INITIALIZER;
static int
mutex_pthread_init(void **priv, int just_check)
{
int err = 0;
if(just_check)
pthread_mutex_lock(&check_init_lock);
if(!*priv || !just_check)
{
pthread_mutex_t *lock = malloc(sizeof(pthread_mutex_t));
if(!lock)
err = ENOMEM;
if(!err)
{
err = pthread_mutex_init(lock, 0);
if(err)
free(lock);
else
*priv = lock;
}
}
if(just_check)
pthread_mutex_unlock(&check_init_lock);
return err;
}
static int
mutex_pthread_destroy(void *priv)
{
int err = pthread_mutex_destroy((pthread_mutex_t *) priv);
free(priv);
return err;
}
static struct ath_ops ath_pthread_ops =
{
mutex_pthread_init,
mutex_pthread_destroy,
(int (*)(void *)) pthread_mutex_lock,
(int (*)(void *)) pthread_mutex_unlock,
0,
0,
0,
0,
0,
0,
0,
0
};
struct ath_ops *
ath_pthread_available(void)
{
if(pthread_create
&& pthread_mutex_init && pthread_mutex_destroy
&& pthread_mutex_lock && pthread_mutex_unlock)
return &ath_pthread_ops;
else
return 0;
}
| 1
|
#include <pthread.h>
int fd;
pthread_mutex_t mutex;
void *fun(void *arg)
{
int i=1000;
int n=0;
while(i--)
{
lseek(fd, n, 0);
write(fd, "-", 1);
pthread_mutex_unlock(&mutex);
n+=2;
printf("sls\\n");
}
}
int main(int argc, char* argv[])
{
int i=1000;
int n=1;
pthread_t pthid;
fd = open("tmp", O_RDWR | O_CREAT | O_TRUNC, 0644);
if(fd < 3)
{
perror("open");
return -1;
}
pthread_mutex_init(&mutex, 0);
pthread_create(&pthid, 0, fun, 0);
while(i--)
{
pthread_mutex_lock(&mutex);
lseek(fd, n, 0);
write(fd, "*", 1);
n+=2;
printf("ls\\n");
}
printf("ssss\\n");
pthread_join(pthid, 0);
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
extern pthread_mutex_t seq_mutex;
extern int seq_control;
char * createAT_PCMD(int flag, float roll, float pitch, float gaz, float yaw){
char * command = (char*) calloc(64, sizeof(char));
printf("CREATE PCMD : %d/ (%f)%d /(%f)%d /(%f)%d /(%f)%d\\n",
flag,
roll, *(int*)&roll,
pitch, *(int*)&pitch,
gaz, *(int*)&gaz,
yaw, *(int*)&yaw);
pthread_mutex_lock(&seq_mutex);
if(flag == FLAG_HOVER || flag == FLAG_PROG || flag == FLAG_PROGWITHYAW){
snprintf(command,
64 * sizeof(char),
"AT*PCMD=%d,%d,%d,%d,%d,%d\\r",
seq_control,
flag,
*(int*) &roll,
*(int*) &pitch,
*(int*) &gaz,
*(int*) &yaw);
}
else{
perror("Creating command AT_PCMD :: Flag not allowed");
}
seq_control++;
pthread_mutex_unlock(&seq_mutex);
return command;
}
char * createAT_REF(int startBit, int emergency){
char * command = (char*) calloc(32, sizeof(char));
int arg = DEF_ATREF;
if(startBit == TAKEOFF)
arg = setBitToOne(arg, 9);
if(emergency == EMERGENCY_CHANGE)
arg = setBitToOne(arg, 8);
pthread_mutex_lock(&seq_mutex);
snprintf(command,
32 * sizeof(char),
"AT*REF=%d,%d\\r",
seq_control,
arg);
seq_control++;
pthread_mutex_unlock(&seq_mutex);
return command;
}
char * createAT_FTRIM(){
char * command = (char*) calloc(32, sizeof(char));
pthread_mutex_lock(&seq_mutex);
snprintf(command, 32 * sizeof(char), "AT*FTRIM=%d\\r", seq_control);
seq_control++;
pthread_mutex_unlock(&seq_mutex);
return command;
}
char * createAT_CALIB(int id_device){
char * command = (char*) calloc(32, sizeof(char));
pthread_mutex_lock(&seq_mutex);
snprintf(command,
32 * sizeof(char),
"AT*CALIB=%d,%d\\r",
seq_control,
id_device);
seq_control++;
pthread_mutex_unlock(&seq_mutex);
return command;
}
char * createAT_CONFIG(char * opt_name, char * opt_value){
char * command = (char*) calloc(1024, sizeof(char));
pthread_mutex_lock(&seq_mutex);
snprintf(command,
1024 * sizeof(char),
"AT*CONFIG=%d,\\"%s\\",\\"%s\\"\\r",
seq_control,
opt_name,
opt_value);
seq_control ++;
pthread_mutex_unlock(&seq_mutex);
return command;
}
char * createAT_CONFIG_IDS(){
char * command = (char*) calloc(256, sizeof(char));
pthread_mutex_lock(&seq_mutex);
snprintf(command,
256 * sizeof(char),
"AT*CONFIG_IDS=%d,\\"%s\\",\\"%s\\",\\"%s\\"\\r",
seq_control,
SESSION_ID,
USER_ID,
APP_ID);
seq_control++;
pthread_mutex_unlock(&seq_mutex);
return command;
}
char * createAT_COMWDG(){
char * command = (char*) calloc(32, sizeof(char));
pthread_mutex_lock(&seq_mutex);
snprintf(command,
32 * sizeof(char),
"AT*COMWDG=%d\\r",
seq_control);
seq_control++;
pthread_mutex_unlock(&seq_mutex);
return command;
}
char * createAT_CTRL(){
char * command = (char*) calloc(32, sizeof(char));
pthread_mutex_lock(&seq_mutex);
snprintf(command,
32 * sizeof(char),
"AT*CTRL=%d,0,0\\r",
seq_control);
seq_control++;
printf("%s\\n",command);
pthread_mutex_unlock(&seq_mutex);
return command;
}
char * createAT_LED(int color, float freq, int duration){
char * command = (char*) calloc(64, sizeof(char));
int animation_number = 0;
pthread_mutex_lock(&seq_mutex);
snprintf(command,
64 * sizeof(char),
"AT*LED=%d,%d,%d,%d\\r",
seq_control,
animation_number,
*(int*)&freq,
duration);
seq_control++;
printf("%s\\n",command);
pthread_mutex_unlock(&seq_mutex);
return command;
}
| 1
|
#include <pthread.h>
int id;
pthread_t threadConsumidor;
}t_consumidor;
int in;
int out;
int buf[5];
sem_t empty;
sem_t full;
pthread_mutex_t mutex;
}BUFFER;
BUFFER sc;
int fibo[25];
int QTD_CONSUMERS;
int cont = 0;
void* consumer(void* thread);
void* producer();
void primo(int primo);
void geraFibo(int* vetor);
int main(int argc, char const *argv[]){
int i;
if( argc < 2 || argc > 2){
printf("\\033[1m\\033[31m""Passe a qtd de Consumidores!\\n""\\033[0m");
exit(-1);
}else{
sscanf(argv[1], "%d", &QTD_CONSUMERS);
t_consumidor* consumers = (t_consumidor*) calloc (QTD_CONSUMERS,sizeof(t_consumidor));
pthread_t threadProdutor;
sem_init(&sc.empty,0,5);
sem_init(&sc.full,0,0);
pthread_mutex_init(&sc.mutex,0);
for(i=0; i < QTD_CONSUMERS; i++){
consumers[i].id = i+1;
if(pthread_create(&consumers[i].threadConsumidor, 0, consumer, &consumers[i]) != 0){
printf("Erro ao criar a thread\\n");
exit(1);
}
}
if (pthread_create(&threadProdutor, 0, producer, 0) != 0){
printf("Erro ao criar a thread\\n");
exit(1);
}
for(i = 0; i < QTD_CONSUMERS; i++){
if(pthread_join(consumers[i].threadConsumidor, 0) != 0){
printf("Erro ao finalizar a thread %d\\n", i);
exit(1);
}
}
if(pthread_join(threadProdutor, 0) != 0){
printf("Erro ao finalizar a thread\\n");
exit(1);
}
}
return(0);
}
void *consumer(void* thread){
int pos;
t_consumidor* con = (t_consumidor*) thread;
int i, item;
for(;;){
sem_wait(&sc.full);
pthread_mutex_lock(&sc.mutex);
item = sc.buf[sc.out];
printf("\\033[1m\\033[31m""Consumidor %d: ""\\033[0m""consumindo item buffer[%d] = %d\\n",con->id ,sc.out, item);
sc.out = (sc.out+1)%5;
primo(item);
cont++;
pthread_mutex_unlock(&sc.mutex);
sem_post(&sc.empty);
sleep(rand() % 3);
if(cont == 25 -1){
printf("Buffer vazio, acabou o consumo!!\\n");
pthread_exit(0);
}
}
return 0;
}
void* producer(){
geraFibo(fibo);
int i;
for(i=0; i < 25; i++){
sem_wait(&sc.empty);
pthread_mutex_lock(&sc.mutex);
sc.buf[sc.in] = fibo[i];
printf("\\033[1m\\033[36m""Produtor: ""\\033[0m""Inseri o item buffer[%d] = %d\\n", sc.in, sc.buf[sc.in]);
sc.in = (sc.in+1)%5;
pthread_mutex_unlock(&sc.mutex);
sem_post(&sc.full);
sleep(rand() % 3);
}
exit(0);
}
void primo(int primo){
int i, count = 0;
for(i=1; i <= primo; i++){
if(primo%i == 0)
count++;
}
if(count == 2 && primo != 1)
printf("--> O número %d eh primo!\\n", primo);
}
void geraFibo(int* vetor){
int i, atual = 0, anterior = 1, fibo = 0;
for(i=0; i < 25; i++){
fibo = anterior + atual;
vetor[i] = fibo;
anterior = atual;
atual = fibo;
}
}
| 0
|
#include <pthread.h>
int process_request ( struct client_node *client, char *msg_buffer )
{
int request = * ( ( int * ) msg_buffer + 1 );
switch ( request )
{
case REQUEST_EXIT:
close ( client->sockfd );
remove_client ( client );
pthread_kill ( pthread_self(), SIGKILL );
break;
case REQUEST_USERS:
;
struct client_node *cur = clients;
char buffer[BUFFER_SIZE];
memset ( buffer, 0, BUFFER_SIZE );
strncpy ( buffer, "Current users:\\n", BUFFER_SIZE );
pthread_mutex_lock ( &clients_lock );
while ( cur )
{
strncat ( buffer, cur->username, BUFFER_SIZE );
strncat ( buffer, "\\n", BUFFER_SIZE );
cur = cur->next_client;
}
pthread_mutex_unlock ( &clients_lock );
send ( client->sockfd, buffer, BUFFER_SIZE, 0 );
break;
case REQUEST_VERSION:
break;
case REQUEST_WHISPER:
break;
default:
return 1;
}
return 0;
}
| 1
|
#include <pthread.h>
extern int makethread(void *(*)(void *), void *);
struct to_info {
void (*to_fn)(void *);
void *to_arg;
struct timespec to_wait;
};
void clock_gettime(int id, struct timespec *tsp) {
struct timeval tv;
gettimeofday(&tv, 0);
tsp->tv_sec = tv.tv_sec;
tsp->tv_nsec = tv.tv_usec * 1000;
}
void *timeout_helper(void *arg) {
struct to_info *tip;
tip = (struct to_info *)arg;
nanosleep((&tip->to_wait), (0));
(*tip->to_fn)(tip->to_arg);
free(arg);
return(0);
}
void timeout(const struct timespec *when, void (*func)(void *), void *arg) {
struct timespec now;
struct to_info *tip;
int err;
clock_gettime(0, &now);
if ((when->tv_sec > now.tv_sec) || (when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) {
tip = malloc(sizeof(struct to_info));
if (tip != 0) {
tip->to_fn = func;
tip->to_arg = arg;
tip->to_wait.tv_sec = when->tv_sec - now.tv_sec;
if (when->tv_nsec >= now.tv_nsec) {
tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec;
} else {
tip->to_wait.tv_sec--;
tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec;
}
err = makethread(timeout_helper, (void *)tip);
if (err = 0) {
return;
} else {
free(tip);
}
}
}
}
pthread_mutexattr_t attr;
pthread_mutex_t mutex;
void retry(void *arg) {
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
}
int main(void) {
int err, condition, arg;
struct timespec when;
if ((err = pthread_mutexattr_init(&attr)) != 0) {
err_exit(err, "pthread_mutexattr_init error");
}
if ((err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) != 0) {
err_exit(err, "can't set recursive type");
}
if ((err = pthread_mutex_init(&mutex, &attr)) != 0) {
err_exit(err, "can't create recursive mutex");
}
pthread_mutex_lock(&mutex);
if (condition) {
clock_gettime(0, &when);
when.tv_sec += 10;
timeout(&when, retry, (void *)((unsigned long) arg));
}
pthread_mutex_unlock(&mutex);
exit(0);
}
| 0
|
#include <pthread.h>
void displayTurn_action(){
pthread_mutex_lock(shm.tableResourcesMutex);
int turn=getTurn(shm.t);
pthread_mutex_unlock(shm.tableResourcesMutex);
printf("\\nThe current turn is: %d\\n",turn);
}
void playCard_action(){
printf("Your Cards: \\n");
printHandCards(player);
printf("\\n Choose the index of the card you want to play: \\n");
int cardIndex;
scanf("%i",&cardIndex);
while(!isValidCard(getHandCard(player,cardIndex))){
printf("\\n Invalid Index. Please enter another one\\n");
scanf("%i",&cardIndex);
}
pthread_mutex_lock(&internalMut);
cardToPlayIndex=cardIndex;
pthread_cond_broadcast(&cardPlayedCond);
pthread_mutex_unlock(&internalMut);
}
void displayTableCards_action(){
pthread_mutex_lock(shm.tableResourcesMutex);
printTableCards(shm.t);
pthread_mutex_unlock(shm.tableResourcesMutex);
}
void displayUsedCards_action(){
pthread_mutex_lock(shm.tableResourcesMutex);
printUsedCards(shm.t);
pthread_mutex_unlock(shm.tableResourcesMutex);
}
void displayElapsedTime_action(){
if(isOurTurn()){
time_t now=time(0);
printf("Time Elapsed: %d\\n",(int)(now-turnStartTime));
}
else{
printf("Time Elapsed: 0\\n");
return;
}
}
| 1
|
#include <pthread.h>
void alu_control(void *not_used){
pthread_barrier_wait(&threads_creation);
char alu_op;
char alu_control_sign = 0;
char cfuncao;
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);
}
alu_op = (((separa_ALUOp0 | separa_ALUOp1) & cs.value) >> ALUOp0_POS) & 0x03;
cfuncao = (ir & separa_cfuncao);
if (alu_op == 0x00)
alu_control_sign = ativa_soma;
if (alu_op == 0x01)
alu_control_sign = ativa_subtracao;
if (alu_op == 0x02){
cfuncao = cfuncao & zera_2bits_cfuncao;
if (cfuncao == 0x00)
alu_control_sign = ativa_soma;
if (cfuncao == 0x02)
alu_control_sign = ativa_subtracao;
if (cfuncao == 0x04)
alu_control_sign = ativa_and;
if (cfuncao == 0x05)
alu_control_sign = ativa_or;
if (cfuncao == 0x0a)
alu_control_sign = ativa_slt;
}
alu_s.value = alu_control_sign;
pthread_mutex_lock(&alu_sign);
alu_s.isUpdated = 1;
pthread_cond_signal(&alu_sign_wait);
pthread_mutex_unlock(&alu_sign);
pthread_barrier_wait(¤t_cycle);
alu_s.isUpdated = 0;
pthread_barrier_wait(&update_registers);
}
}
| 0
|
#include <pthread.h>
void *producer1(void *arg);
void *producer2(void *arg);
void *consumer(void *arg);
char buffer[5];
sem_t empty,full;
pthread_mutex_t prod,cons;
int main() {
int res,i;
pthread_t a_thread,b_thread,c_thread;
void *thread_result;
int print_count1 = 0;
sem_init(&full, 0, 0);
sem_init(&empty, 0, 5);
res = pthread_create(&a_thread, 0, producer1, 0 );
if (res != 0) {
perror("Thread creation failed");
exit(1);
}
res = pthread_create(&b_thread, 0, producer2, 0 );
if (res != 0) {
perror("Thread creation failed");
exit(1);
}
res = pthread_create(&c_thread, 0, consumer, 0);
if (res != 0) {
perror("Thread creation failed");
exit(1);
}
printf("Wait for pthread_join\\n");
res = pthread_join(a_thread, &thread_result);
if (res != 0) {
perror("Thread join failed");
exit(1);
}
res = pthread_join(b_thread, &thread_result);
if (res != 0) {
perror("Thread join failed");
exit(1);
}
printf("Thread joined\\n");
exit(0);
}
void *producer1(void *arg) {
int in = 0,value;
char ch='A';
while(1)
{
sem_wait(&empty);
pthread_mutex_lock(&prod);
buffer[in]=ch;
in = (in+1)% 5;
ch++;
if (in == 0)
{
ch='A';
printf("p1:%s\\n",buffer);
}
pthread_mutex_unlock(&prod);
sem_post(&full);
}
pthread_exit("exit");
}
void *producer2(void *arg) {
int in = 0,value;
char ch='a';
while(1)
{
sem_wait(&empty);
pthread_mutex_lock(&prod);
buffer[in]=ch;
in = (in+1)% 5;
ch++;
if (in == 0)
{
ch='a';
printf("p2:%s\\n",buffer);
}
pthread_mutex_unlock(&prod);
sem_post(&full);
}
pthread_exit("exit");
}
void *consumer(void *arg) {
int out = 0, value;
char temp[5];
while(1)
{
sem_wait(&full);
pthread_mutex_lock(&prod);
temp[out] = buffer[out];
out = (out+1)% 5;
if (out == 0)
{
printf("\\t%s\\n",temp);
}
pthread_mutex_unlock(&prod);
sem_post(&empty);
}
pthread_exit("exit");
}
| 1
|
#include <pthread.h>
void print_matrix(char* label, double **m);
void print_matrix(char* label, double **m) {
int i, j;
printf("%s:\\n", label);
for (i = 0; i < ((((1 << 5)) < (4)) ? ((1 << 5)) : (4)); i++) {
for (j = 0; j < ((((1 << 5)) < (4)) ? ((1 << 5)) : (4)); j++) {
printf("%d ", (int)m[i][j]);
}
printf("\\n");
}
}
void consume_tasks() {
while(has_task()) {
dequeue_and_run_task();
}
}
int main(int argc, char *argv[]) {
time_t start;
double **a, **b, **c;
int id, master = 0;
if (argc != 2) {
printf("Usage: %s id\\n", argv[0]);
exit(1);
}
id = atoi(argv[1]);
printf("id is %d\\n", id);
dsm_init(id);
dsm_reserve(SCHED_PAGE, 0x2000);
DEBUG_LOG("GETTING %d SPACE", DATA_SIZE);
dsm_open(DATA_SPACE, DATA_SIZE);
dsm_lock_init(MASTER_LOCK);
DEBUG_LOG("init'd masterlock");
dsm_lock_init(SCHED_LOCK);
DEBUG_LOG("init'd schedlock");
while (pthread_mutex_trylock(MASTER_LOCK) == EBUSY);
DEBUG_LOG("locked masterlock");
master = !(WORKER_TALLY++);
DEBUG_LOG("Tally incremented to %d", WORKER_TALLY);
if (master) {
printf("I'm master. Setting up arrays.\\n");
master = 1;
MASTER_FINISHED = 0;
int i = 0, j = 0;
srand(123);
a = (double**) dsm_malloc(sizeof(double*) * (1 << 5));
b = (double**) dsm_malloc(sizeof(double*) * (1 << 5));
c = (double**) dsm_malloc(sizeof(double*) * (1 << 5));
for (i = 0; i < (1 << 5); i++) {
a[i] = (double*) dsm_malloc(sizeof(double) * (1 << 5));
b[i] = (double*) dsm_malloc(sizeof(double) * (1 << 5));
c[i] = (double*) dsm_malloc(sizeof(double) * (1 << 5));
for (j = 0; j < (1 << 5); j++) {
a[i][j] = rand() % 5;
b[i][j] = rand() % 5;
}
}
start = time(0);
printf("Queueing up strassens\\n");
strassen(a, b, c, (1 << 5), 0);
}
pthread_mutex_unlock(MASTER_LOCK);
printf("Consuming tasks\\n");
consume_tasks(0);
printf("Finished with tasks\\n");
while (pthread_mutex_trylock(MASTER_LOCK) == EBUSY);
WORKER_TALLY--;
DEBUG_LOG("Tally is %d", WORKER_TALLY);
pthread_mutex_unlock(MASTER_LOCK);
while(WORKER_TALLY || (!master && !MASTER_FINISHED)) {
DEBUG_LOG("Tally: %d, master: %d, master_finished: %d",
WORKER_TALLY, master, MASTER_FINISHED);
pthread_yield();
}
if (master) {
time_t end = time(0);
print_matrix("a", a);
print_matrix("b", b);
print_matrix("c", c);
printf("Elapsed time: %ld seconds\\n", end - start);
MASTER_FINISHED = 1;
}
dsm_release(&MASTER_FINISHED);
printf("finished.\\n");
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static void die_with_error(char *message)
{
perror(message);
exit(1);
}
static void radix_tree_init(struct radix_tree *tree, int bits, int radix)
{
if (radix < 1) {
perror("Invalid radix\\n");
return;
}
if (bits < 1) {
perror("Invalid number of bits\\n");
return;
}
unsigned long n_slots = 1L << radix;
tree->radix = radix;
tree->max_height = (((bits) + (radix) - 1) / (radix));
tree->node = calloc(sizeof(struct radix_node) +
(n_slots * sizeof(void *)), 1);
if (!tree->node)
die_with_error("failed to create new node.\\n");
}
static int find_slot_index(unsigned long key, int levels_left, int radix)
{
return key >> ((levels_left - 1) * radix) & ((1 << radix) - 1);
}
static void *radix_tree_find_alloc(struct radix_tree *tree, unsigned long key,
void *(*create)(unsigned long))
{
int levels_left = tree->max_height;
int radix = tree->radix;
int n_slots = 1 << radix;
int index;
struct radix_node *current_node = tree->node;
void **next_slot = 0;
void *slot;
pthread_mutex_lock(&lock);
while (levels_left) {
index = find_slot_index(key, levels_left, radix);
next_slot = ¤t_node->slots[index];
slot = *next_slot;
if (slot) {
current_node = slot;
} else if (create) {
void *new;
if (levels_left != 1)
new = calloc(sizeof(struct radix_node) +
(n_slots * sizeof(void *)), 1);
else
new = create(key);
if (!new)
die_with_error("failed to create new node.\\n");
*next_slot = new;
current_node = new;
} else {
pthread_mutex_unlock(&lock);
return 0;
}
levels_left--;
}
pthread_mutex_unlock(&lock);
return current_node;
}
static void *radix_tree_find(struct radix_tree *tree, unsigned long key)
{
return radix_tree_find_alloc(tree, key, 0);
}
struct radix_tree_desc sequential_desc = {
.name = "sequential",
.init = radix_tree_init,
.find_alloc = radix_tree_find_alloc,
.find = radix_tree_find,
};
| 1
|
#include <pthread.h>
static const int debug = 1;
static uint8_t _bus = 1;
static int _i2cFile = -1000;
static pthread_mutex_t _lock;
static int _mutex_created = 0;
static void getLock() {
if (!_mutex_created) {
pthread_mutex_init(&_lock, 0);
_mutex_created = 1;
}
pthread_mutex_lock(&_lock);
}
static void releaseLock() {
if (_mutex_created) {
pthread_mutex_unlock(&_lock);
}
}
int i2cInit() {
if (_i2cFile < 0) {
char i2cBusName[12];
sprintf(i2cBusName, "/dev/i2c-%d", _bus);
_i2cFile = open(i2cBusName, O_RDWR);
if (_i2cFile < 0)
goto init_error;
}
return 0;
init_error:
printf("Error opening i2c file for bus %i\\n", _bus);
return -1;
}
void i2cClose() {
getLock();
close(_i2cFile);
_i2cFile = -1000;
releaseLock();
pthread_mutex_destroy(&_lock);
_mutex_created = 0;
}
static uint8_t _tenbit_enabled = 0;
static int i2cSetAddress(uint16_t address) {
i2cInit();
uint8_t isTenBit = (address - 127 > 0) ? 1 : 0;
if (_tenbit_enabled != isTenBit && ioctl(_i2cFile, I2C_TENBIT, isTenBit))
goto ioctl_error;
if(ioctl(_i2cFile, I2C_SLAVE, address))
goto ioctl_error;
return 0;
ioctl_error:
printf("Failed to set i2c slave address to %x with tenbit set to %i\\n", address, isTenBit);
return -1;
}
void i2cSetBus(uint8_t bus) {
i2cClose();
getLock();
_bus = bus;
i2cInit();
releaseLock();
}
int i2c_read(uint16_t address, uint8_t reg, uint8_t *data, uint8_t count) {
getLock();
if (i2cSetAddress(address))
goto read_error;
if (write(_i2cFile, ®, 1) < 1)
goto read_error;
if (read(_i2cFile, data, count) < count)
goto read_error;
releaseLock();
return 0;
read_error:
releaseLock();
printf("failed to read %i bytes from device %x\\n", count, address);
return -1;
}
int i2c_write(uint16_t address, const uint8_t *data, uint8_t count) {
getLock();
if (i2cSetAddress(address))
goto write_error;
if (write(_i2cFile, data, count) < count)
goto write_error;
releaseLock();
return 0;
write_error:
releaseLock();
printf("failed to write %i bytes to device %x\\n", count, address);
return -1;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
struct node {
int number;
struct node *next;
} *head = 0;
static void cleanup_handler(void *arg)
{
printf("Cleanup handler of second thread.\\n");
pthread_mutex_unlock(&mtx);
}
static void *thread_func(void *arg)
{
struct node *p = 0;
pthread_cleanup_push(cleanup_handler,p);
while(1) {
pthread_mutex_lock(&mtx);
while(head == 0)
pthread_cond_wait(&cond,&mtx);
p = head;
head = head->next;
printf("Go %d front of queue\\n",p->number);
free(p);
pthread_mutex_unlock(&mtx);
}
pthread_cleanup_pop(0);
return 0;
}
int main(int argc,char *argv[])
{
pthread_t tid;
int i;
struct node *p;
pthread_create(&tid,0,thread_func,0);
for(i = 0 ; i < 10 ; i++) {
p = malloc(sizeof(struct node));
p->number = i;
pthread_mutex_lock(&mtx);
p->next = head;
head = p;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mtx);
sleep(1);
}
printf("thread 1 wanna end the line.So cancel therad 2.\\n");
pthread_cancel(tid);
pthread_join(tid,0);
printf("All done -- exiting\\n");
return 0;
}
| 1
|
#include <pthread.h>
void *sorting_thread(void *threadNumber);
void writeTimestamp()
{
long time_now = clock();
printf("%ld ", time_now);
}
char *readFileAsString(char* filepath)
{
int fileSize = 0;
FILE *pFile = fopen(filepath, "rb");
if (pFile == 0)
{
puts("error opening file");
}
fseek(pFile,0,2);
fileSize = ftell(pFile);
rewind(pFile);
char *data = (char*) calloc (sizeof(char), fileSize + 20);
fread(data, 1, fileSize, pFile);
fclose(pFile);
return data;
}
int countCommas(char* str)
{
int count = 0;
int pos = 0;
while (str[pos] != '\\0')
{
if (str[pos] == ',')
{
count++;
}
pos++;
}
return count;
}
void splitStringIntoArray(char* str, int* arr, int count)
{
char* tok;
int i = 0;
tok = strtok(str,",\\0");
while (tok != 0)
{
if (i < count)
{
arr[i] = atoi(tok);
}
else
{
puts("Index out of bounds");
}
tok = strtok(0, ",\\0");
i++;
}
}
void crapSort(int* arr, int count)
{
int i, j;
for (i = 0; i < count; i++)
{
for (j = i; j < count; j++)
{
if (arr[j] > arr[i])
{
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
}
}
void printIntArray(int* arr, int size)
{
int i;
for (i = 0; i < size; i++)
{
printf("%d\\n", arr[i]);
}
}
void writeCDF(int*arr, int size, char* path)
{
FILE *file;
file = fopen(path, "w");
int i;
for (i=0; i<size-1; i++)
{
fprintf(file, "%d,", arr[i]);
}
fprintf(file, "%d", arr[size-1]);
fclose(file);
}
{
int chuckNumber;
struct chuck_data_t* next;
} chuck_data_t;
int* sortArray;
int sortArray_size;
int readElementsCount;
chuck_data_t* chucks;
int chucks_size;
pthread_mutex_t chucks_lock;
int initArrayAndChuckTbl(int itemsCount)
{
int i;
int chuckCount;
readElementsCount = itemsCount;
if (itemsCount % 1024 == 0)
{
chuckCount = itemsCount / 1024;
}
else
{
chuckCount = (itemsCount / 1024) + 1;
}
chucks_size = chuckCount;
sortArray_size = chuckCount * 1024;
sortArray = (int*) calloc (sizeof(int), chuckCount * 1024);
chucks = (chuck_data_t*) calloc (sizeof(chuck_data_t), chuckCount);
pthread_mutex_init(&chucks_lock, 0);
for (i = 0; i < chuckCount; i++)
{
chucks[i].chuckNumber = i;
chucks[i].next = (chuck_data_t*)(chucks + i + 1);
}
chucks[chuckCount-1].next = 0;
printf("Read %d data chucks...\\n", chuckCount);
return chuckCount;
}
pthread_barrier_t sortSync;
int* mergeAlgo(char* filepath1, char* filepath2)
{
char* data1 = readFileAsString(filepath1);
char* data2 = readFileAsString(filepath2);
int count1 = countCommas(data1)+1;
int count2 = countCommas(data2)+1;
int* arr1 = (int*) calloc(sizeof(int),count1);
int* arr2 = (int*) calloc(sizeof(int),count2);
splitStringIntoArray(data1, arr1, count1);
splitStringIntoArray(data2, arr2, count2);
int arraySize = count1 + count2;
int* arr3 = (int*)calloc(sizeof(int), arraySize);
int i = 0;
int index1 = 0;
int index2 = 0;
for(i = 0; i < arraySize; ++i){
if((arr1[index1] >= arr2[index2])||(index2==count2)){
arr3[i] = arr1[index1];
++index1;
}
else if ((arr2[index2] > arr1[index1])||(index1==count1)){
arr3[i] = arr2[index2];
++index2;
};
};
return arr3;
}
int celDivide(int num, int den){
if (num % den == 0)
{return num / den;}
else
{return num / den + 1;}
}
int* mergeThread(int i, int p){
char* chunkName1 = (char*) calloc (sizeof(char), 15);
char* chunkName2 = (char*) calloc (sizeof(char), 15);
char* tempName = (char*) calloc (sizeof(char), 15);
sprintf(chunkName1, "chuck%d", i);
sprintf(chunkName2, "chuck%d", i+1);
sprintf(tempName, "chuck%d", i/2);
int* temp = mergeAlgo(chunkName1, chunkName2);
remove(chunkName1);
remove(chunkName2);
writeCDF(temp, 1024*p, tempName);
return temp;
}
void oddChunkCorrection(int chunkCount){
if (chunkCount % 2 != 0 ){
char* tempName = (char*) calloc (sizeof(char), 15);
sprintf(tempName, "chuck%d", chunkCount);
FILE *fp = fopen(tempName, "w");
fclose(fp);
};
}
void merge(int mergeCount){
int i = 0;
int j = 0;
int p = 2;
for(j = mergeCount; j>1 ;j=celDivide(j,2)){
oddChunkCorrection(j);
for(i = 0; i<j; i += 2){
mergeThread(i, p);
};
p = p*2;
};
oddChunkCorrection(j);
int* result = mergeThread(0, mergeCount);
writeCDF(result, sortArray_size, "data.out");
remove("chuck0");
}
int main(void) {
int numOfThreads = 5;
int i;
int count = 0;
char* data = readFileAsString("data.in");
count = countCommas(data) + 1;
int chunkCount = initArrayAndChuckTbl(count);
splitStringIntoArray(data, sortArray, count);
pthread_barrier_init(&sortSync, 0, numOfThreads + 1);
pthread_t threads[numOfThreads];
writeTimestamp();
printf("Create %d threads\\n", numOfThreads);
for (i = 0; i < numOfThreads; i++)
{
pthread_create(&threads[i], 0, sorting_thread, (void *)i);
}
pthread_barrier_wait(&sortSync);
puts("All Threads Done");
puts("\\nStart of merge\\n");
merge(chunkCount);
puts("End of merge\\n");
return 0;
}
chuck_data_t* getNextChuck()
{
chuck_data_t* temp;
pthread_mutex_lock(&chucks_lock);
temp = chucks;
if (temp != 0)
{
chucks = temp->next;
}
pthread_mutex_unlock(&chucks_lock);
return temp;
}
void *sorting_thread(void *threadNumber)
{
int thread_num = (int)(threadNumber);
printf("Thread %d starting\\n", thread_num);
chuck_data_t* chuck = getNextChuck();
while (chuck != 0)
{
writeTimestamp();
printf("Thread %d starts work on chuck %d\\n", thread_num, chuck->chuckNumber);
char* fileName = (char*) calloc (sizeof(char), 15);
sprintf(fileName, "chuck%d", chuck->chuckNumber);
crapSort((int*)(sortArray + 1024*chuck->chuckNumber), 1024);
writeCDF((int*)(sortArray + 1024*chuck->chuckNumber), 1024, fileName);
chuck = getNextChuck();
}
pthread_barrier_wait(&sortSync);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_key_t index_ips(struct ip_pair **p)
{
pthread_key_t key;
pthread_key_create(&key, 0);
register int8_t i;
for (i = 0; i <= p[0]->total; i++) {
if (pthread_equal(pthread_self(), p[i]->thread)) {
pthread_setspecific(key, p[i]->d_ip);
return key;
}
}
return 0;
}
void *func_probe(void *vd)
{
struct pkt_info_t *syn = (struct pkt_info_t *)vd;
pthread_key_t i;
pthread_mutex_lock(&syn->mutex);
while (syn->tcm < syn->p_dst_ip[0]->total) {
i = index_ips(syn->p_dst_ip);
char *ip = pthread_getspecific(i);
(void *)pthread_self(), syn->tcm);
pthread_cond_wait(&syn->cond, &syn->mutex);
}
pthread_mutex_unlock(&syn->mutex);
syn->p_seq = (int)(arc4random() % MAX_SEQ);
syn->p_ack = 0;
syn->p_flags = TH_SYN;
syn->p_tsval = 0;
syn->p_tsecr = 0;
uni_raw_send(syn);
pack_parse(syn);
syn->p_flags = TH_ACK;
uni_raw_send(syn);
pack_parse(syn);
pthread_exit(0);
}
void p_connect(struct pkt_info_t *pass)
{
register int tc = 0;
register int tp = pass->p_dst_ip[0]->total;
pthread_mutex_init(&pass->mutex, 0);
pthread_cond_init(&pass->cond, 0);
for (pass->tcm = 0; pass->tcm < tp; pass->tcm++) {
pthread_create(&pass->p_dst_ip[pass->tcm]->thread,
0, func_probe, (void *)pass);
(void *)pass->p_dst_ip[pass->tcm]->thread, pass->tcm);
}
pthread_cond_broadcast(&pass->cond);
for (tc = 0; tc < tp; tc++) {
pthread_join(pass->p_dst_ip[tc]->thread, 0);
}
printf("\\nDONE |: "
"\\n.......(seq %d) (ack %d)"
"\\n.......(ports %d -> %d) (val/secr: %d %d )\\n",
(pass->p_seq), (pass->p_ack),
(pass->p_src_port), (pass->p_dst_port),
pass->p_tsval, pass->p_tsecr);
pthread_mutex_destroy(&pass->mutex);
pthread_cond_destroy(&pass->cond);
}
| 1
|
#include <pthread.h>
void *philosopher (void *id);
pthread_mutex_t *chopstick;
int numOfSeats, numOfTurns;
int main (int argc, char **argv)
{
if (argc < 3)
{
printf("Usage: philosophers <number of seats> <number of turns>");
return 1;
}
numOfSeats = atoi(argv[1]);
numOfTurns = atoi(argv[2]);
chopstick = calloc(numOfSeats, sizeof(pthread_mutex_t));
srand(time(0));
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
printf ("Start a dinner for %d diners\\n", numOfSeats );
pthread_t philosopher_tid[numOfSeats];
long i;
for (i = 0; i < numOfSeats; i++)
pthread_mutex_init (chopstick + i, 0);
for (i = 0; i < numOfSeats; i++)
pthread_create (&philosopher_tid[i], 0, philosopher, (void *) i);
for (i = 0; i < numOfSeats; i++)
pthread_join (philosopher_tid[i], 0);
for (i = 0; i < numOfSeats; i++)
pthread_mutex_destroy (chopstick + i);
printf ("Dinner is no more.\\n");
return 0;
}
void *philosopher (void *num)
{
int fVar = 0;
int id = (long)num;
printf ("Philsopher no. %d sits at the table.\\n", id);
usleep (( (rand() % 5 + 1) * 1000));
int i;
for (i = 0; i < numOfTurns; i++)
{
while(fVar == 0)
{
printf("Philsopher no. %d gets hungry for the %d time!\\n", id, i + 1);
printf("Philsopher no. %d tries to grab chopstick %d\\n", id, id);
usleep(( (rand() % 5 + 1) * 1000) * 2);
if (pthread_mutex_trylock(chopstick) == 0)
{
printf("Philsopher no. %d has grabbed chopstick %d\\n", id, id);
printf("Philsopher no. %d tries to grab chopstic %d\\n", id, (id + 1) % numOfSeats);
if (pthread_mutex_trylock(chopstick) == 0)
{
printf("Philsopher no. %d grabbed chopstick %d\\n", id, (id + 1) % numOfSeats);
printf("Philsopher no. %d eating\\n", id);
usleep(( (rand() % 5 + 1) * 1000) * 2);
printf("Philsopher no. %d stopped eating\\n", id);
pthread_mutex_unlock(&(chopstick[id]));
usleep(( (rand() % 5 + 1) * 1000) * 4);
fVar = 0;
}
printf("Philsopher no. %d has returned chopstick %d\\n", id, id);
pthread_mutex_unlock(&(chopstick[(id + 1) % numOfSeats]));
}
else
{
printf("Philsopher no. %d has returned chopstick %d\\n", id, (id + 1) % numOfSeats);
}
printf("Philsopher no. %d finished turn %d\\n", id, i + 1);
fVar = 1;
}
}
printf (">>>>>> Philsopher no. %d finished meal. <<<<<<\\n", id);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t count_mutex;
pthread_cond_t count_empty_cond;
int count = 20;
const int MAX_LEN = 64;
const int INC_RATE = 2;
enum THREAD_ENUM{
FILL_THREAD=0,
EMPTY_THREAD=1,
ALL_THREADS
};
char THREAD_NAMES[ALL_THREADS][MAX_LEN]={
"FILL",
"EMPTY"
};
void *inc_count(void *id)
{
long thread_id = (long)id;
printf("%s::%d thread %ld, count: %d\\n", __FUNCTION__, 35, thread_id, count);
pthread_mutex_lock(&count_mutex);
while(0 != count){
printf("%s::%d thread %ld count: %d, going to wait\\n", __FUNCTION__, 38, thread_id, count);
pthread_cond_wait(&count_empty_cond, &count_mutex);
printf("%s::%d thread %ld count: %d, receive signal\\n", __FUNCTION__, 40, thread_id, count);
}
printf("%s::%d thread %ld count: %d, going to increse count\\n", __FUNCTION__, 42, thread_id, count);
count += INC_RATE;
printf("%s::%d thread %ld count: %d, increse count\\n", __FUNCTION__, 44, thread_id, count);
pthread_mutex_unlock(&count_mutex);
printf("%s::%d thread %ld count: %d, going to exit thread\\n", __FUNCTION__, 47, thread_id, count);
pthread_exit(0);
}
void *dec_count(void *id)
{
long thread_id = (long)id;
printf("%s::%d thread %ld, count: %d\\n", __FUNCTION__, 56, thread_id, count);
pthread_mutex_lock(&count_mutex);
while(0 != count){
printf("%s::%d thread %ld count: %d, going to decrease\\n", __FUNCTION__, 59, thread_id, count);
count--;
printf("%s::%d thread %ld count: %d, decrease one\\n", __FUNCTION__, 61, thread_id, count);
if(0 == count){
printf("%s::%d thread %ld count: %d, going to broadcast\\n", __FUNCTION__, 63, thread_id, count);
pthread_cond_broadcast(&count_empty_cond);
}
}
pthread_mutex_unlock(&count_mutex);
printf("%s::%d thread %ld count: %d, going to exit thread\\n", __FUNCTION__, 69, thread_id, count);
pthread_exit(0);
}
int main(int argc, char *argv[]){
long t1=1, t2=2;
pthread_t fillThread, emptyThread;
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init(&count_empty_cond, 0);
pthread_attr_init(&attr);
pthread_create(&fillThread, &attr, inc_count, (void *)t1);
pthread_create(&emptyThread, &attr, dec_count, (void *)t2);
pthread_join(fillThread, 0);
pthread_join(emptyThread, 0);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_empty_cond);
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo {
int f_count;
pthread_mutex_t f_lock;
struct foo *f_next;
int f_id;
};
struct foo *
foo_alloc(void)
{
struct foo *fp;
int idx;
if ((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 1;
if (pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return(0);
}
idx = (((unsigned long)fp)%29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp->f_next;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
}
return(fp);
}
void
foo_hold(struct foo *fp)
{
pthread_mutex_lock(&hashlock);
fp->f_count++;
pthread_mutex_unlock(&hashlock);
}
struct foo *
foo_find(int id)
{
struct foo *fp;
int idx;
idx = (((unsigned long)fp)%29);
pthread_mutex_lock(&hashlock);
for (fp = fh[idx]; fp != 0; fp = fp->f_next) {
if (fp->f_id == id) {
fp->f_count++;
break;
}
}
pthread_mutex_unlock(&hashlock);
return(fp);
}
void
foo_rele(struct foo *fp)
{
struct foo *tfp;
int idx;
pthread_mutex_lock(&hashlock);
if (--fp->f_count == 0) {
idx = (((unsigned long)fp)%29);
tfp = fh[idx];
if (tfp == fp) {
fh[idx] = fp->f_next;
} else {
while (tfp->f_next != fp)
tfp = tfp->f_next;
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
} else {
pthread_mutex_unlock(&hashlock);
}
}
| 0
|
#include <pthread.h>
void mai_print_pagenodes(unsigned long *pageaddrs,int size)
{
int pagenodes[MAXPAGES];
int i;
int err;
printf("Must update Linux Kernel to get this information\\n");
}
double mai_get_time_pmigration()
{
return time_last_pmig;
}
void mai_print_threadcpus()
{
int i;
for(i=0;i<sinfo.nthreads;i++)
printf("\\nThread id %d - CPU/CORE %d",thread_id[i],sinfo.cpus[i]);
}
double mai_get_time_tmigration()
{
return time_last_tmig;
}
void mai_get_log()
{
char temp[10],dir[100];
char command[100],filename[100];
char command1[] = "numactl --show > log_numactl.txt";
unsigned int pid = getpid();
int resp;
DIR *d;
FILE *fp,*fpf;
command[0]='\\0';
fp=popen("pwd","r");
fscanf(fp,"%s",dir);
fclose(fp);
sprintf(temp,"%i",pid);
strcpy(filename,"/proc/");
strcat(filename,temp);
strcat(filename,"/numa_maps");
fpf = fopen(filename,"r");
if(fpf!=0){
strcat(command,"cp /proc/");
strcat(command,temp);
strcat(command,"/numa_maps ");
strcat(command,dir);
fp=popen(command,"r");
fscanf(fp,"%d",&resp);
fclose(fp);
rename("numa_maps","log_numamaps.txt");
}
fp=popen(command1,"r");
fscanf(fp,"%d",&resp);
fclose(fp);
strcpy(command1,"numactl --hardware >> log_numactl.txt");
fp=popen(command1,"r");
fscanf(fp,"%d",&resp);
fclose(fp);
}
void mai_mempol(void* ph)
{
int mpol=-1;
pthread_mutex_lock(&mai_mutex);
mpol = get_var_policy(ph);
pthread_mutex_unlock(&mai_mutex);
switch(mpol)
{
case CYCLIC:
printf("CYCLIC\\n");
break;
case CYCLIC_B:
printf("CYCLIC_BLOCK\\n");
break;
case SKEW:
printf("SKEW_MAPP\\n");
break;
case SKEW_B:
printf("SKEW_MAPP_BLOCK\\n");
break;
case PRIME:
printf("PRIME_MAPP\\n");
break;
case PRIME_B:
printf("PRIME_MAPP_BLOCK\\n");
break;
case BIND:
printf("BIND\\n");
break;
case BIND_B:
printf("BIND_BLOCK\\n");
break;
case RANDOM:
printf("RANDOM\\n");
break;
case RANDOM_B:
printf("RANDOM_BLOCK\\n");
break;
case OWN:
printf("OWN\\n");
break;
default:
printf("NO MEM POLICY\\n");
break;
}
}
void mai_arraynodes(void* ph)
{
int nnodes=0,*nodes=0,i;
pthread_mutex_lock(&mai_mutex);
nodes = get_var_nodes(ph,&nnodes);
pthread_mutex_unlock(&mai_mutex);
if(nodes!=0){
printf("\\n");
for(i=0;i<nnodes;i++);
printf("\\n");
}
}
| 1
|
#include <pthread.h>
int ticketcount = 10;
pthread_mutex_t lock;
pthread_cond_t cond;
void* salewinds1(void* args)
{
while(1)
{
pthread_mutex_lock(&lock);
if(ticketcount > 0)
{
printf("windows1 start sale ticket!the ticket is:%d\\n",ticketcount);
ticketcount --;
if(ticketcount == 0)
pthread_cond_signal(&cond);
printf("sale ticket finish!,the last ticket is:%d\\n",ticketcount);
}
else
{
pthread_mutex_unlock(&lock);
break;
}
pthread_mutex_unlock(&lock);
sleep(1);
}
}
void* salewinds2(void* args)
{
while(1)
{
pthread_mutex_lock(&lock);
if(ticketcount > 0)
{
printf("windows2 start sale ticket!the ticket is:%d\\n",ticketcount);
ticketcount --;
if(ticketcount == 0)
pthread_cond_signal(&cond);
printf("sale ticket finish!,the last ticket is:%d\\n",ticketcount);
}
else
{
pthread_mutex_unlock(&lock);
break;
}
pthread_mutex_unlock(&lock);
sleep(1);
}
}
void *setticket(void *args)
{
pthread_mutex_lock(&lock);
if(ticketcount > 0)
pthread_cond_wait(&cond,&lock);
ticketcount = 10;
pthread_mutex_unlock(&lock);
sleep(1);
pthread_exit(0);
}
main()
{
pthread_t pthid1,pthid2,pthid3;
pthread_mutex_init(&lock,0);
pthread_cond_init(&cond,0);
pthread_create(&pthid1,0, salewinds1,0);
pthread_create(&pthid2,0, salewinds2,0);
pthread_create(&pthid3,0, setticket,0);
pthread_join(pthid1,0);
pthread_join(pthid2,0);
pthread_join(pthid3,0);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
}
| 0
|
#include <pthread.h>
static union free_packet *free_packets;
static union free_packet *next_free_packet;
static size_t count_free_packets;
static pthread_mutex_t mem_lock = PTHREAD_MUTEX_INITIALIZER;
struct packet *playrtp_new_packet(void) {
struct packet *p;
pthread_mutex_lock(&mem_lock);
if(free_packets) {
p = &free_packets->p;
free_packets = free_packets->next;
} else {
if(!count_free_packets) {
next_free_packet = xcalloc(1024, sizeof (union free_packet));
count_free_packets = 1024;
}
p = &(next_free_packet++)->p;
--count_free_packets;
}
pthread_mutex_unlock(&mem_lock);
return p;
}
void playrtp_free_packet(struct packet *p) {
union free_packet *u = (union free_packet *)p;
pthread_mutex_lock(&mem_lock);
u->next = free_packets;
free_packets = u;
pthread_mutex_unlock(&mem_lock);
}
| 1
|
#include <pthread.h>
int contador_global = 0;
pthread_mutex_t lock;
void *exercicio1e2(){
pthread_t tid = pthread_self();
printf("Nova thread criada. TID = %d!\\n",(unsigned int)tid);
pthread_exit(0);
}
void *exercicio3(){
for(int i = 0; i < 100; i++)
contador_global++;
pthread_exit(0);
}
void *exercicio4(){
pthread_mutex_lock(&lock);
for(int i = 0; i < 100; i++)
contador_global++;
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
int main(int argc, char **argv)
{
int a = 0;
while(1){
printf("Digite o exercício requisitado: \\n1,2, 3 ou 4 para exercicios \\n5 para sair \\n");
scanf("%d",&a);
if(a == 1){
pthread_t thread;
pthread_create(&thread,0,exercicio1e2,0);
pthread_join(thread,0);
}
if(a == 2){
pthread_t thread[512];
for(int i = 0; i<512; i++){
pthread_create(&thread[i],0,exercicio1e2,0);
}
for(int i = 0; i<512; i++){
pthread_join(thread[i],0);
}
}
if(a == 3){
pthread_t thread[512];
for(int i = 0; i<512; i++){
pthread_create(&thread[i],0,exercicio3,0);
}
for(int i = 0; i<512; i++){
pthread_join(thread[i],0);
}
printf("Contador: %d\\n", contador_global);
}
if(a == 4){
pthread_t thread[512];
for(int i = 0; i<512; i++){
pthread_create(&thread[i],0,exercicio4,0);
}
for(int i = 0; i<512; i++){
pthread_join(thread[i],0);
}
pthread_mutex_destroy(&lock);
printf("Contador: %d\\n", contador_global);
}
if(a == 5){
return 0;
}
}
}
| 0
|
#include <pthread.h>
static struct timeval start_time;
pthread_mutex_t wait_time_mutex = PTHREAD_MUTEX_INITIALIZER;
double overall_waiting_time;
double getCurrentSimulationTime(){
struct timeval cur_time;
double cur_secs, init_secs;
init_secs = (start_time.tv_sec + (double) start_time.tv_usec / 1000000);
gettimeofday(&cur_time, 0);
cur_secs = (cur_time.tv_sec + (double) cur_time.tv_usec / 1000000);
return cur_secs - init_secs;
}
void initAcsTime() {
gettimeofday(&start_time, 0);
}
void updateOverAllWaitingTime(double wait_time) {
pthread_mutex_lock(&wait_time_mutex);
overall_waiting_time += wait_time;
pthread_mutex_unlock(&wait_time_mutex);
}
double getOverallWaitTime() {
return overall_waiting_time;
}
| 1
|
#include <pthread.h>
int makethread(void *(*fn)(void *), void *arg)
{
int err;
pthread_t tid;
pthread_attr_t attr;
err = pthread_attr_init(&attr);
if(err != 0) {
return err;
}
err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
if(err == 0) {
pthread_create(&tid, &attr, fn, arg);
}
pthread_attr_destroy(&attr);
return err;
}
struct to_info {
void (*to_fn)(void *);
void *to_arg;
struct timespec to_wait;
};
void *timeout_helper(void *arg)
{
struct to_info *tip;
tip = (struct to_info *)arg;
nanosleep(&tip->to_wait, 0);
(*tip->to_fn)(tip->to_arg);
return 0;
}
void timeout(const struct timespec *when, void (*func)(void *), void *arg)
{
struct timespec now;
struct timeval tv;
struct to_info *tip;
int err;
gettimeofday(&tv, 0);
now.tv_sec = tv.tv_sec;
now.tv_nsec = tv.tv_usec * 1000;
if((when->tv_sec > now.tv_sec) ||
(when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) {
tip = malloc(sizeof(struct to_info));
if(tip != 0) {
tip->to_fn = func;
tip->to_arg = arg;
tip->to_wait.tv_sec = when->tv_sec - now.tv_nsec;
if(when->tv_nsec >= now.tv_nsec) {
tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec;
}
else {
tip->to_wait.tv_sec--;
tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec;
}
err = makethread(timeout_helper, (void *)tip);
if(err == 0) {
return;
}
}
}
(*func)(arg);
}
pthread_mutexattr_t attr;
pthread_mutex_t mutex;
void retry(void *arg)
{
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
}
int main(int argc, char const *argv[])
{
int err, condition, arg;
struct timespec when;
if((err = pthread_mutexatrr_init(&attr)) != 0) {
printf("pthread_mutexattr_init failed\\n");
}
if((err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) != 0) {
printf("can't set recursive type\\n");
}
if((err = pthread_mutex_init(&mutex, &attr)) != 0) {
printf("can't create recursive mutex\\n");
}
pthread_mutex_lock(&mutex);
if(condition) {
timout(&when, retry, (void *)arg);
}
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);
pthread_mutexattr_destroy(&attr);
return 0;
}
| 0
|
#include <pthread.h>
extern int idx, sink;
extern double dsink;
extern void *psink;
void bit_shift_main (void);
void dynamic_buffer_overrun_main (void);
void dynamic_buffer_underrun_main (void);
void cmp_funcadr_main (void);
void conflicting_cond_main (void);
void data_lost_main (void);
void data_overflow_main (void);
void data_underflow_main (void);
void dead_code_main (void);
void dead_lock_main (void);
void deletion_of_data_structure_sentinel_main (void);
void double_free_main (void);
void double_lock_main (void);
void double_release_main (void);
void endless_loop_main (void);
void free_nondynamic_allocated_memory_main (void);
void free_null_pointer_main (void);
void func_pointer_main (void);
void function_return_value_unchecked_main (void);
void improper_termination_of_block_main (void);
void insign_code_main (void);
void invalid_extern_main (void);
void invalid_memory_access_main (void);
void littlemem_st_main (void);
void livelock_main (void);
void lock_never_unlock_main (void);
void memory_allocation_failure_main(void);
void memory_leak_main (void);
void not_return_main (void);
void null_pointer_main (void);
void overrun_st_main (void);
void ow_memcpy_main (void);
void pow_related_errors_main (void);
void ptr_subtraction_main (void);
void race_condition_main (void);
void redundant_cond_main (void);
void return_local_main (void);
void sign_conv_main (void);
void sleep_lock_main (void);
void st_cross_thread_access_main (void);
void st_overflow_main (void);
void st_underrun_main (void);
void underrun_st_main (void);
void uninit_memory_access_main (void);
void uninit_pointer_main (void);
void uninit_var_main (void);
void unlock_without_lock_main (void);
void unused_var_main (void);
void wrong_arguments_func_pointer_main (void);
void zero_division_main (void);
pthread_mutex_t livelock_001_glb_A;
pthread_mutex_t livelock_001_glb_B;
int x,y;
void *mythreadA(void *pram)
{
while(1)
{
pthread_mutex_lock(&livelock_001_glb_A);
x=x+1;
pthread_mutex_unlock(&livelock_001_glb_A);
int status=pthread_mutex_trylock(&livelock_001_glb_B);
if(status==0)
{
continue;
}
}
return 0;
}
void* mythreadB()
{
while(1)
{
pthread_mutex_lock(&livelock_001_glb_B);
y=y+1;
pthread_mutex_unlock(&livelock_001_glb_B);
int status=pthread_mutex_trylock(&livelock_001_glb_A);
if(status==0)
{
continue;
}
}
return 0;
}
void livelock_001()
{
pthread_t pthreadA,pthreadB;
pthread_mutex_init(&livelock_001_glb_A,0);
pthread_mutex_init(&livelock_001_glb_B,0 );
pthread_create(&pthreadA,0,mythreadA,0);
pthread_create(&pthreadB,0,(void *) &mythreadB,0);
pthread_join(pthreadA,0);
pthread_join(pthreadB,0);
}
extern volatile int vflag;
void livelock_main ()
{
if (vflag> 0)
{
livelock_001 ();
}
}
| 1
|
#include <pthread.h>
void CONSUMO_ALEATORIO_DE_TIEMPO_DE_CPU(void)
{
static int veces = 0;
veces += getpid() + 1;
veces ^= times(0);
veces %= 8 * 8;
usleep(veces*10);
}
volatile int RECURSO_COMPARTIDO = 0;
pthread_mutex_t mutex;
pthread_cond_t a_leer, a_escribir;
int leyendo, escribiendo;
void Lector(void)
{
int i;
pthread_mutex_lock(&mutex);
while (escribiendo)
pthread_cond_wait(&a_leer, &mutex);
leyendo++;
pthread_mutex_unlock(&mutex);
for (i = 0; i < 100; i++) {
printf(" %d \\n", RECURSO_COMPARTIDO);
fflush(stdout);
CONSUMO_ALEATORIO_DE_TIEMPO_DE_CPU();
}
pthread_mutex_lock(&mutex);
leyendo--;
if (!leyendo)
pthread_cond_signal(&a_escribir);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void Escritor(void)
{
int i;
pthread_mutex_lock(&mutex);
while (leyendo || escribiendo)
pthread_cond_wait(&a_escribir, &mutex);
escribiendo++;
pthread_mutex_unlock(&mutex);
for (i = 0; i < 100; i++) {
printf("\\r %d ", i);
fflush(stdout);
RECURSO_COMPARTIDO++;
CONSUMO_ALEATORIO_DE_TIEMPO_DE_CPU();
}
pthread_mutex_lock(&mutex);
escribiendo--;
pthread_cond_signal(&a_escribir);
pthread_cond_broadcast(&a_leer);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main_(void)
{
pthread_t th1, th2, th3, th4;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&a_leer, 0);
pthread_cond_init(&a_escribir, 0);
pthread_create(&th1, 0, (void*)Lector, 0);
pthread_create(&th2, 0, (void*)Escritor, 0);
pthread_create(&th3, 0, (void*)Lector, 0);
pthread_create(&th4, 0, (void*)Escritor, 0);
pthread_join(th1, 0);
pthread_join(th2, 0);
pthread_join(th3, 0);
pthread_join(th4, 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&a_leer);
pthread_cond_destroy(&a_escribir);
return 0;
}
int main(void)
{
pthread_t rds[300];
pthread_t wrs[10];
int i;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&a_leer, 0);
pthread_cond_init(&a_escribir, 0);
for (i = 0; (i < 300) || (i < 10); i++) {
if (i < 10)
pthread_create(&(wrs[i]), 0, (void*)Escritor, 0);
if (i < 300)
pthread_create(&(rds[i]), 0, (void*)Lector, 0);
}
CONSUMO_ALEATORIO_DE_TIEMPO_DE_CPU();
for (i = 0; (i < 300) || (i < 10); i++) {
if (i < 300)
pthread_join(rds[i], 0);
if (i < 10)
pthread_join(wrs[i], 0);
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&a_leer);
pthread_cond_destroy(&a_escribir);
printf("\\n");
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
int sum=0;
pthread_mutex_t lock;
pthread_t *rowthread,*colthread,*calculationthread;
int nRows,nCols,nThread;
int **MatrixA,**MatrixB,**MatrixC;
int offsetR,offsetC;
void * MultiplyandAdd(void *arg)
{
int sum=0;
int *a=(int *)arg;
int i=*a;
int j=*++a;
int offset=*++a;
int offsetc=nCols/nThread;
int k;
pthread_mutex_lock(&lock);
for(k=0;k<offsetc;k++)
sum+=MatrixA[i][offset*nThread+k]*MatrixB[offset*nThread+k][j];
printf("\\n sum %d \\n",sum);
pthread_mutex_unlock(&lock);
pthread_exit(&sum);
}
void * ColMultiply(void *arg)
{
int y;
int *a=(int *)arg;
int i=*a;
int j=*(++a);
int k;
struct identification
{
int a,b,c;
}id;
calculationthread=(pthread_t *)malloc(sizeof(pthread_t)*nThread);
if(calculationthread==0)
{
printf("\\n Malloc Error \\n");
exit(1);
}
for(k=0;k<nThread;k++)
{
id.a=i;
id.b=j*nThread+k;
id.c=k;
int x=pthread_create(&calculationthread[k],0,MultiplyandAdd,&id);
if(x!=0)
{
printf("\\n Pthread_Creat Error \\n");
exit(1);
}
}
int sum=0,status=0;
for(k=0;k<nThread;k++)
{
pthread_join(calculationthread[k],(void *)&status);
printf("\\n ))))))))))\\n");
pthread_mutex_lock(&lock);
printf("\\n the Sum is %d \\n",sum);
MatrixC[i][j*nThread+k]=sum;
pthread_mutex_unlock(&lock);
}
}
void * RowMultiply(void *arg)
{
int i=*(int*)arg;
printf("\\n %d \\n",i);
int j;
struct identity
{
int a;
int b;
}id;
offsetR=nRows/nThread;
colthread=(pthread_t*)malloc(sizeof(pthread_t)*offsetR);
if(colthread==(void *)-1)
{
perror("Malloc\\n");
exit(1);
}
for(j=0;j<offsetR;j++)
{
id.a=i*offsetR+j;
id.b=j;
int x=pthread_create(&colthread[i],0,ColMultiply,&id);
if(x!=0)
{
perror("Thread not Created \\n");
exit(1);
}
}
while(1);
}
void fillMatrix(int **a,int row,int col)
{
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
a[i][j]=2;
}
}
}
printf_matrix(int **a,int row ,int col)
{
int i, j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d ",a[i][j]);
}
printf("\\n");
}
}
int main(int argc,char *argv[])
{
pthread_mutex_init(&lock,0);
if(argc==1)
{
nRows=nCols=1000;
nThread=100;
}
if(argc==2)
{
nRows=nCols=atoi(argv[1]);
nThread=100;
}
if(argc==4)
{
nRows=atoi(argv[1]);
nCols=atoi(argv[2]);
nThread=atoi(argv[3]);
}
int i,j;
MatrixA=(int **)malloc(sizeof(int*)*nRows);
for(i=0;i<nRows;i++)
MatrixA[i]=(int *)malloc(sizeof(int)*nCols);
MatrixB=(int **)malloc(sizeof(int*)*nCols);
for(i=0;i<nCols;i++)
MatrixB[i]=(int *)malloc(sizeof(int)*nRows);
MatrixC=(int **)malloc(sizeof(int*)*nRows);
for(i=0;i<nRows;i++)
MatrixC[i]=(int *)malloc(sizeof(int)*nRows);
fillMatrix(MatrixA,nRows,nCols);
fillMatrix(MatrixB,nCols,nRows);
rowthread=(pthread_t*)malloc(sizeof(pthread_t)*nThread);
printf_matrix(MatrixA,nRows,nCols);
printf_matrix(MatrixB,nRows,nCols);
for(i=0;i<nThread;i++)
{
printf("\\n created ---\\n");
int a=pthread_create(&rowthread[i],0,RowMultiply,&i);
if(a!=0)
{
printf("Thread Creation Error..\\n");exit(1);
}
}
for(i=0;i<nThread;i++)
pthread_join(rowthread[i],0);
printf_matrix(MatrixC,nRows,nRows);
free(MatrixA);
free(MatrixB);
free(MatrixC);
return 0;
}
| 1
|
#include <pthread.h>
static int logged = 0;
pthread_mutex_t lock;
void original_log(char * str)
{
if (logged) return;
debug_log(str);
logged = 1;
}
void debug_log(char * str)
{
printf("%s : %s\\n", __func__, str);
}
void log(char * str)
{
pthread_mutex_lock(&lock);
if (!logged) {
debug_log(str);
logged = 1;
}
pthread_mutex_unlock(&lock);
}
void *func(void *p)
{
log("from thread");
return 0;
}
int main()
{
int i;
pthread_t thread[20];
if (pthread_mutex_init(&lock, 0) != 0)
{
fprintf(stderr, "mutex init failed\\n");
return 1;
}
for (i = 0; i < 20; i++) {
if (pthread_create(&thread[i], 0, func, 0)) {
fprintf(stderr, "Error creating thread\\n");
return 1;
}
}
for (i = 0; i < 20; i++)
if(pthread_join(thread[i], 0)) {
fprintf(stderr, "Error joining thread\\n");
return 2;
}
pthread_mutex_destroy(&lock);
}
| 0
|
#include <pthread.h>
void pickup(int j);
void putdown(int i);
void test(int k);
void philosopher(int * id);
pthread_mutex_t lock;
char state[50];
pthread_cond_t self;
int num_phil;
int main(int argc,char *argv[]){
int n, *who;
pthread_t phils[50];
void * retval;
if(argc != 2) {
printf("error!!!!\\n");
puts("usage: phil number_of_philosophers, ex phil 5\\n");
exit(0);
}
num_phil = atoi(argv[1]);
pthread_mutex_init(&lock, 0);
for (n = 0;n<num_phil;n++){
state[n] = 't';
}
pthread_cond_init(&self, 0);
for (n = 0;n<num_phil;n++){
who = (int *)malloc(sizeof(int));
*who = n;
if (pthread_create(&(phils[n]), 0, (void *)philosopher, who) != 0) {
perror("pthread_create");
exit(1);
}
}
pthread_join(phils[0],0);
return 0;
}
void pickup(int j){
printf("phil %d is trying to pickup\\n",j);
pthread_mutex_lock(&lock);
state[j] = 'h';
test(j);
while( state[j] != 'e'){
pthread_cond_wait(&self, &lock);
test(j);
}
pthread_mutex_unlock(&lock);
return;
}
void putdown(int i){
printf("phil %d is putting down\\n",i);
state[i] = 't';
pthread_cond_broadcast(&self);
}
void test(int k){
if( (state[(k+(num_phil-1)) % num_phil] != 'e') && ( state[k] == 'h') && (state[(k+1) % num_phil] != 'e') ){
state[k] = 'e';
}
}
void philosopher(int * id){
int n=0;
printf("i am phil %d\\n",*id);
sleep(1);
while(n < 10){
pickup(*id);
printf("Philosopher %d is eating\\n",*id);
sleep(1);
putdown(*id);
printf("Philosopher %d is thinking\\n",*id);
sleep(1);
n++;
}
return;
}
| 1
|
#include <pthread.h>
struct record{
int count;
pthread_mutex_t mutex;
};
struct record *mutex_init()
{
struct record *fp;
fp = malloc(sizeof(struct record));
if(fp != 0)
{
fp->count = 100;
if(pthread_mutex_init(&fp->mutex, 0)!=0)
{
free(fp);
return 0;
}
return fp;
}
printf("malloc failed\\n");
return 0;
}
void *thread_add(void *arg)
{
pthread_mutex_lock(&((struct record *)arg)->mutex);
((struct record *)arg)->count ++;
pthread_mutex_unlock(&((struct record *)arg)->mutex);
return arg;
}
void *thread_del(void *arg)
{
pthread_mutex_lock(&((struct record *)arg)->mutex);
if(((struct record *)arg)->count == 0)
{
pthread_mutex_unlock(&((struct record *)arg)->mutex);
pthread_mutex_destroy(&((struct record *)arg)->mutex);
printf("haha\\n");
free((struct record *)arg);
}
((struct record *)arg)->count--;
pthread_mutex_unlock(&((struct record *)arg)->mutex);
return arg;
}
int main()
{
pthread_t tid1, tid2, tid3;
void *rval1, *rval2;
struct record *foo = mutex_init();
pthread_create(&tid1, 0, thread_add, (void *)(foo));
pthread_create(&tid2, 0, thread_del, (void *)(foo));
pthread_join(tid1, &rval1);
pthread_join(tid2, &rval2);
printf("%d\\n", foo->count);
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() {
return (unsigned long) pthread_self();
}
void init_locks() {
lockarray = (pthread_mutex_t *) OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
int i;
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() {
CRYPTO_set_locking_callback(0);
int i;
for (i = 0; i < CRYPTO_num_locks(); i++)
pthread_mutex_destroy(&(lockarray[i]));
OPENSSL_free(lockarray);
}
| 1
|
#include <pthread.h>
extern int g_mid;
extern pthread_mutex_t g_cmap_lock;
extern struct cmap *g_cmap;
extern struct msgr *g_msgr[];
int mds_send_hb_thread(struct redfish_thread *rt)
{
struct mtran *tr;
struct bsend *ctx;
int succ, i, num_mds, ret, first, use_timer_a, num_sent;
struct mmm_heartbeat resp;
struct msg *r;
time_t cur_time, until;
timer_t timer_a, timer_b;
struct daemon_info *di;
char buf[128];
resp.ty = RF_ENTITY_TY_MDS;
resp.id = g_mid;
r = MSG_XDR_ALLOC(mmm_resp, &resp);
if (IS_ERR(r)) {
abort();
}
ctx = bsend_init(rt->fb, RF_MAX_MDS);
if (IS_ERR(ctx)) {
glitch_log("mds_send_hb_thread: failed to allocate "
"an RPC context for the heartbeat thread: "
"error %d\\n", PTR_ERR(ctx));
abort();
}
until = mt_time() + 5;
first = 1;
use_timer_a = 1;
while (1) {
mt_sleep_until(until);
cur_time = mt_time();
until = cur_time + 5;
ret = mt_set_alarm(cur_time + 40,
"mds_send_hb_thread timeout",
use_timer_a ? &timer_a : &timer_b);
if (ret) {
glitch_log("mds_send_hb_thread: failed to set "
"timer: error %d\\n", ret);
abort();
}
if (!first)
mt_deactivate_alarm(use_timer_a ? timer_b : timer_a);
first = 0;
use_timer_a = !use_timer_a;
pthread_mutex_lock(&g_cmap_lock);
num_mds = g_cmap->num_mds;
for (i = 0; i < num_mds; ++i) {
if (i == g_mid)
continue;
di = &g_cmap->minfo[i];
if (!di->in)
continue;
msg_addref(r);
bsend_add(ctx, g_msgr[RF_ENTITY_TY_MDS], 0, r,
di->ip, di->port[RF_ENTITY_TY_MDS], 2,
(void*)(uintptr_t)i);
}
pthread_mutex_unlock(&g_cmap_lock);
num_sent = bsend_join(ctx);
if (num_sent < 0)
return num_sent;
succ = 0;
for (i = 0; i < num_sent; ++i) {
tr = bsend_get_mtran(ctx, i);
if (tr->m && IS_ERR(tr->m)) {
mtran_ep_to_str(tr, buf, sizeof(buf));
glitch_log("mds_send_hb_thread: failed to "
"send heartbeat to %s: error %d\\n",
buf, PTR_ERR(tr->m));
}
else
++succ;
}
glitch_log("mds_send_hb_thread: successfully sent %d "
"heartbeats out of %d\\n", succ, num_sent);
bsend_reset(ctx);
}
msg_release(r);
bsend_free(ctx);
return 0;
}
| 0
|
#include <pthread.h>
int fd;
int ini;
int fin;
} arg;
pthread_mutex_t mx;
int codeF[256] = {0};
void codes (arg *args) {
int i, j, l, code[256] = {0};
unsigned char c[65536];
if (lseek (args->fd, args->ini, 0)<0) {printf ("LSEEK...\\n"); exit(1);}
for (i = args->ini + 65536; i < args->fin; i+=65536) {
l = read (args->fd, c, 65536);
for (j=0; j<l; j++)
code[c[j]]++;
}
l = read (args->fd, c, args->fin - i + 65536);
for (j=0; j<l; j++)
code[c[j]]++;
pthread_mutex_lock(&mx);
for (i=0; i<256; i++)
codeF[i] += code[i];
pthread_mutex_unlock(&mx);
}
main (int argc, char *argv[]) {
struct timeval ts, tf;
int i, j, T, N, cl, fr;
pthread_t *th;
arg *args;
struct stat stats;
if (argc != 3) {printf ("USO: %s <fname> <Ths>\\n", argv[0]); exit (1);}
stat (argv[1], &stats);
N = stats.st_size;
T = atoi(argv[2]);
th = malloc (T * sizeof (pthread_t));
args = malloc (T * sizeof (arg));
if (th == 0||args == 0) { printf ("Memoria\\n"); exit (1);}
(void) pthread_mutex_init(&mx, 0);
cl = (int)ceil((float)N/(float)T);
fr = (int)floor((float)N/(float)T);
for (i=0;i<N%T;i++){
args[i].fd = open (argv[1], O_RDONLY);
if (args[i].fd < 0) {printf ("OPEN...\\n"); exit (1);}
args[i].ini = i*cl;
args[i].fin = (i+1)*cl;
}
for (i=N%T;i<T;i++){
args[i].fd = open (argv[1], O_RDONLY);
if (args[i].fd < 0) {printf ("OPEN...\\n"); exit (1);}
args[i].ini =(N%T)*cl + (i-(N%T))*fr;
args[i].fin =(N%T)*cl + (i-(N%T)+1)*fr;
}
gettimeofday (&ts, 0);
for (i=0; i<T; i++)
pthread_create (&th[i], 0, (void *) codes, &args[i]);
for (i=0; i<T; i++)
if (pthread_join (th[i], 0)) {printf ("PJOIN (%d)\\n", i); exit (1);};
gettimeofday (&tf, 0);
printf ("LOCAL: %f secs\\n", ((tf.tv_sec - ts.tv_sec)*1000000u +
tf.tv_usec - ts.tv_usec)/ 1.e6);
for (i=0; i<256; i++)
exit (0);
}
| 1
|
#include <pthread.h>
int nextid;
pthread_mutex_t nextid_mutex;
int* array;
int* sum;
int num_threads;
int nums_per_thread;
int counter;
pthread_mutex_t counter_mutex;
sem_t* barrier_sem;
} Shared;
int sem_post_n(sem_t *sem, int n) {
int i, ret;
for (i = 0; i<n; i++) {
ret = sem_post(sem);
if (ret) exit(-1);
}
return ret;
}
void synch(Shared *state, int num_threads) {
pthread_mutex_lock(&(state->counter_mutex));
if(state->counter == (num_threads)-1) {
state->counter = 0;
int i;
for (i = 0; i < (num_threads - 1); i++) {
sem_post(state->barrier_sem);
}
pthread_mutex_unlock(&(state->counter_mutex));
} else {
++(state->counter);
pthread_mutex_unlock(&(state->counter_mutex));
sem_wait(state->barrier_sem);
}
}
void * kernel( void* state_param ) {
Shared *state = (Shared*) state_param;
pthread_mutex_lock(&(state->nextid_mutex));
int pn = state->nextid++;
pthread_mutex_unlock(&(state->nextid_mutex));
struct timeval tv1, tv2;
if (pn == 0) {
gettimeofday(&tv1, 0);
}
state->sum[pn] = 0;
int i=0;
for (i = state->nums_per_thread * pn; i < state->nums_per_thread * (pn+1); i++) {
state->sum[pn] += state->array[i];
}
int half = state->num_threads;
int synch_i = 1;
while (half > 1) {
synch(state, half);
if (half%2 != 0 && pn == 0) {
state->sum[0] = state->sum[0] + state->sum[half-1];
}
half = half/2;
if (pn < half) {
state->sum[pn] = state->sum[pn] + state->sum[pn+half];
} else {
break;
}
}
if (pn == 0) {
gettimeofday(&tv2, 0);
printf (";%f",
(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
(double) (tv2.tv_sec - tv1.tv_sec));
fprintf(stderr,"Sum = %d\\n", state->sum[0]);
}
return 0;
}
int genval(int seed) {
switch(seed % 3) {
case 0: return (seed%2 ? seed%5 : 5-(seed%5))+seed/100;
case 1: return (seed%2 ? 7-(seed%7) : seed%7)+seed/1000;
case 2: return (seed%2 ? seed%11 : -(11-(seed%11)))+seed/10000;
}
return 0;
}
int is_base_two(int num) {
int cmp = 1;
while (cmp <= num) {
if (cmp == num) return 1;
cmp <<= 1;
}
return 0;
}
int main(int argc, char** argv) {
int* array = malloc(1000000000 * sizeof(int));
int i;
for (i=0; i < 1000000000; i++) {
array[i] = genval(i);
}
int num_threads;
for (num_threads = 1; num_threads<=128; num_threads++) {
if ((num_threads%10) != 0 && !is_base_two(num_threads)) {
continue;
}
fprintf(stderr, "%d threads\\n", num_threads);
printf("%d;", num_threads);
int run;
for (run=0; run < 10; run++) {
fprintf(stderr, "run %d\\n", run);
Shared shared_state;
shared_state.array = array;
shared_state.nextid = 0;
pthread_mutex_init(&(shared_state.nextid_mutex), 0);
shared_state.nums_per_thread = (1000000000 + (num_threads-1))/num_threads;
shared_state.num_threads = num_threads;
shared_state.counter = 0;
pthread_mutex_init(&(shared_state.counter_mutex), 0);
shared_state.barrier_sem = sem_open("/barrier_sem", O_CREAT|O_EXCL, S_IRWXU , 0);
shared_state.sum = malloc(num_threads * sizeof(int));
pthread_t* children = malloc(num_threads * sizeof(pthread_t));
for (i=0; i < num_threads; i++) {
pthread_create (&children[i], 0, kernel, (void *) &shared_state) ;
}
for (i=num_threads-1; i >= 0; i--) {
pthread_join(children[i], 0) ;
}
free(shared_state.sum);
sem_close(shared_state.barrier_sem);
sem_unlink("/barrier_sem");
}
printf("\\n");
}
free(array);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
void *
threadA(void *param )
{
int i;
for (i = 0; i < 5; i++) {
pthread_mutex_lock(&mutex1);
printf("threadA --> %d iteration\\n", i);
sleep(rand() % 3);
pthread_mutex_unlock(&mutex2);
}
pthread_exit(0);
}
void *
threadB(void *param )
{
int i;
for (i = 0; i < 5; i++) {
pthread_mutex_lock(&mutex2);
printf("threadB --> %d iteration\\n", i);
sleep(rand() % 3);
pthread_mutex_unlock(&mutex1);
}
pthread_exit(0);
}
int
main()
{
pthread_t tidA, tidB;
srand(time(0));
pthread_setconcurrency(3);
if (pthread_create(&tidA, 0, threadA, 0) ||
pthread_create(&tidB, 0, threadB, 0)) {
perror("pthread_create");
abort();
}
if (pthread_join(tidA, 0) != 0 ||
pthread_join(tidB, 0) != 0) {
perror("pthread_join");
abort();
}
return 0;
}
| 1
|
#include <pthread.h>
int buffer[100];
int nextp, nextc;
int count=0;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
void printfunction(void * ptr)
{
int count = *(int *) ptr;
if (count==0)
{
printf("All items produced are consumed by the consumer \\n");
}
else
{
for (int i=0; i<=count; i=i+1)
{
printf("%d, \\t",buffer[i]);
}
printf("\\n");
}
}
void *producer(void *ptr)
{
int item, flag=0;
int in = *(int *) ptr;
do
{
item = (rand()%7)%10;
flag=flag+1;
nextp=item;
buffer[in]=nextp;
in=((in+1)%100);
while(count <= 100)
{
pthread_mutex_lock(&mutex);
count=count+1;
pthread_mutex_unlock(&mutex);
printf("Count = %d in produced at Iteration = %d\\n", count, flag);
break;
}
} while (flag<=100);
pthread_exit(0);
}
void *consumer(void *ptr)
{
int item, flag=100;
int out = *(int *) ptr;
do
{
while (count >0)
{
nextc = buffer[out];
out=(out+1)%100;
printf("\\t\\tCount = %d in consumer at Iteration = %d\\n", count,flag);
pthread_mutex_lock(&mutex);
count = count-1;
pthread_mutex_unlock(&mutex);
flag=flag-1;
}
if (count <= 0)
{
printf("consumer made to wait...faster than producer.\\n");
}
}while (flag>=0);
pthread_exit(0);
}
int main(void)
{
int in=0, out=0;
pthread_t pro, con;
pthread_create(&pro, 0, producer, &count);
pthread_create(&con, 0, consumer, &count);
pthread_join(pro, 0);
pthread_join(con, 0);
printfunction(&count);
}
| 0
|
#include <pthread.h>
int
pthread_rwlock_tryrdlock (pthread_rwlock_t * rwlock)
{
int result;
pthread_rwlock_t rwl;
if (rwlock == 0 || *rwlock == 0)
{
return EINVAL;
}
if (*rwlock == PTHREAD_RWLOCK_INITIALIZER)
{
result = pte_rwlock_check_need_init (rwlock);
if (result != 0 && result != EBUSY)
{
return result;
}
}
rwl = *rwlock;
if (rwl->nMagic != PTE_RWLOCK_MAGIC)
{
return EINVAL;
}
if ((result = pthread_mutex_trylock (&(rwl->mtxExclusiveAccess))) != 0)
{
return result;
}
if (++rwl->nSharedAccessCount == 32767)
{
if ((result =
pthread_mutex_lock (&(rwl->mtxSharedAccessCompleted))) != 0)
{
(void) pthread_mutex_unlock (&(rwl->mtxExclusiveAccess));
return result;
}
rwl->nSharedAccessCount -= rwl->nCompletedSharedAccessCount;
rwl->nCompletedSharedAccessCount = 0;
if ((result =
pthread_mutex_unlock (&(rwl->mtxSharedAccessCompleted))) != 0)
{
(void) pthread_mutex_unlock (&(rwl->mtxExclusiveAccess));
return result;
}
}
return (pthread_mutex_unlock (&rwl->mtxExclusiveAccess));
}
| 1
|
#include <pthread.h>
pthread_mutex_t value_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t value2_lock = PTHREAD_MUTEX_INITIALIZER;
int value = 0;
int value2 = 0;
void* thread_func1(void *arg)
{
pthread_mutex_lock(&value_lock);
int count = 1;
while (count++ <= 5) {
value += 1;
printf("thread 1: value = %d\\n", value);
}
pthread_mutex_lock(&value2_lock);
count = 1;
while (count++ <= 5) {
value2 += 1;
printf("thread 1: value2= %d\\n", value2);
}
pthread_mutex_unlock(&value_lock);
pthread_mutex_unlock(&value2_lock);
pthread_exit((void*)1);
}
void* thread_func2(void *arg)
{
pthread_mutex_lock(&value2_lock);
int count = 1;
while (count++ <= 5) {
value += 10;
printf("thread 2: value = %d\\n", value);
}
pthread_mutex_lock(&value_lock);
count = 1;
while (count++ <= 5) {
value2 += 10;
printf("thread 2: value2= %d\\n", value2);
}
pthread_mutex_unlock(&value_lock);
pthread_mutex_unlock(&value2_lock);
pthread_exit((void*)1);
}
int main(void)
{
int err;
pthread_t tid1, tid2;
err = pthread_create(&tid1, 0, thread_func1, 0);
if (0 != err) {
printf("can't create thread 1: %s\\n", strerror(err));
abort();
}
err = pthread_create(&tid2, 0, thread_func2, 0);
if (0 != err) {
printf("can't create thread 2: %s\\n", strerror(err));
abort();
}
sleep(1);
printf("main thread end\\n");
exit(0);
}
| 0
|
#include <pthread.h>
struct valueset {
int min;
int max;
int next_size;
int next_off;
uint8_t *buf;
pthread_mutex_t lock;
int seq;
};
struct valueset *
valueset_init(int min, int max)
{
struct valueset *vs;
int i;
vs = malloc(sizeof(*vs));
memset(vs, 0, sizeof(*vs));
pthread_mutex_init(&vs->lock, 0);
vs->min = min;
vs->max = max;
vs->buf = malloc(max);
for (i = 0; i < max; i++) {
vs->buf[i] = (uint8_t)i;
}
valueset_reset(vs);
return vs;
}
void
valueset_reset(struct valueset *vs)
{
vs->next_size = vs->min;
vs->next_off = 0;
vs->seq = 0;
}
int
valueset_get_value(struct valueset *vs, uint8_t **ptr)
{
int size, rem, seq;
uint8_t *c;
pthread_mutex_lock(&vs->lock);
size = vs->next_size;
vs->next_size += 10;
if (vs->next_size >= vs->max)
vs->next_size = vs->min;
seq = vs->seq++;
pthread_mutex_unlock(&vs->lock);
c = malloc(size);
*ptr = c;
rem = size;
while (rem >= 4) {
*(int*)c = seq;
c += 4;
seq += 4;
rem -= 4;
}
while (rem > 0) {
*c = (uint8_t)seq;
c++;
seq++;
rem--;
}
return size;
}
void
valueset_return_value(struct valueset *vs, uint8_t *ptr)
{
free((void*)ptr);
}
| 1
|
#include <pthread.h>
struct aqueue {
size_t length, offset;
unsigned pos;
bool closed;
pthread_cond_t pushwait, popwait;
pthread_mutex_t mutex;
void *buffer[];
};
struct aqueue *aqueue_create(size_t length)
{
struct aqueue *q = xmalloc(sizeof *q + length * sizeof *q->buffer);
*q = (struct aqueue) { .length = length };
for (size_t i = 0; i < length; i++)
q->buffer[i] = 0;
CHECK(!pthread_mutex_init(&q->mutex, 0));
CHECK(!pthread_cond_init(&q->pushwait, 0));
CHECK(!pthread_cond_init(&q->popwait, 0));
return q;
}
void aqueue_delete(struct aqueue *q, void (*destructor)(void*))
{
if (destructor)
for (size_t i = 0; i < q->length; i++)
if (q->buffer[i])
destructor(q->buffer[i]);
pthread_cond_destroy(&q->pushwait);
pthread_cond_destroy(&q->popwait);
pthread_mutex_destroy(&q->mutex);
free(q);
}
bool aqueue_push(struct aqueue *q, void *item, unsigned pos)
{
assert(item);
CHECK(!pthread_mutex_lock(&q->mutex));
while (!q->closed && (pos - q->pos >= q->length))
CHECK(!pthread_cond_wait(&q->pushwait, &q->mutex));
bool success = !q->closed;
if (!q->closed) {
void **slot = q->buffer + (pos - q->pos + q->offset) % q->length;
assert(!*slot);
*slot = item;
CHECK(!pthread_cond_signal(&q->popwait));
}
pthread_mutex_unlock(&q->mutex);
return success;
}
void *aqueue_pop(struct aqueue *q, unsigned *pos)
{
CHECK(!pthread_mutex_lock(&q->mutex));
while (!q->closed && !q->buffer[q->offset])
CHECK(!pthread_cond_wait(&q->popwait, &q->mutex));
void *item = q->buffer[q->offset];
if (item) {
q->buffer[q->offset] = 0;
q->offset++;
if (q->offset == q->length) q->offset = 0;
if (pos) *pos = q->pos;
q->pos++;
CHECK(!pthread_cond_broadcast(&q->pushwait));
}
pthread_mutex_unlock(&q->mutex);
return item;
}
void aqueue_close(struct aqueue *q)
{
CHECK(!pthread_mutex_lock(&q->mutex));
q->closed = 1;
pthread_cond_broadcast(&q->pushwait);
pthread_cond_broadcast(&q->popwait);
pthread_mutex_unlock(&q->mutex);
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.