text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
pthread_mutex_t mutex1, mutex2, mutex3;
int l1=0, l2=0, l3=0, l4=0, l5=0, l6=0;
void *trilho(void* x_void_ptr);
int main(){
int n_trens = 3;
pthread_t trem[n_trens];
int i,j, trem_id[n_trens];
for (i=0; i<n_trens; i++){
trem_id[i] = i+1;
if (pthread_create(&trem[i], 0, trilho, &trem_id[i]) != 0){
perror("Thread creation fail");
exit(1);
}
}
for (j=0; j<n_trens; j++){
if(pthread_join(trem[j], 0)) {
perror("Thread join fail");
exit(1);
}
}
printf("main: End of threads!\\n");
}
void *trilho(void* x_void_ptr){
int x = *((int *)x_void_ptr);
int t[3];
pthread_mutex_t mut[2];
printf("sou o trem %d\\n", x);
if (x==1){
t[0] = l1;
t[1] = l2;
t[2] = l3;
mut[0] = mutex1;
mut[1] = mutex3;
}
else if (x==2){
t[0] = l4;
t[1] = l5;
t[2] = l2;
mut[0] = mutex2;
mut[1] = mutex1;
}
else if (x==3){
t[0] = l6;
t[1] = l3;
t[2] = l5;
mut[0] = mutex3;
mut[1] = mutex2;
}
else{
perror("Trem id invalido!");
exit(1);
}
while(1){
t[0] = 1;
sleep(2);
t[0] = 0;
printf("sou o trem %d e estou esperando o meu trilho 1 \\n", x);
pthread_mutex_lock(&mut[0]);
printf("sou o trem %d e entrei no meu trilho 1 \\n", x);
t[1] = 1;
sleep(2);
t[1] = 0;
pthread_mutex_unlock(&mut[0]);
printf("sou o trem %d e sai do meu trilho 1, o proximo pode pegar... \\n", x);
printf("sou o trem %d e estou esperando o meu trilho 2 \\n", x);
pthread_mutex_lock(&mut[1]);
printf("sou o trem %d e entrei no meu trilho 2 \\n", x);
t[2] = 1;
sleep(2);
t[2] = 0;
pthread_mutex_unlock(&mut[1]);
printf("sou o trem %d e sai do meu trilho 2, o proximo pode pegar... \\n", x);
printf("sou o trem %d JA RODEI MAIS UMA VEZ\\n", x);
}
return 0;
}
| 1
|
#include <pthread.h>
int voti[5];
int votazioni_terminate[5];
pthread_mutex_t mutex_voti[5];
sem_t barriera_sondaggi_terminati;
int numero_sondaggi_terminati;
pthread_mutex_t mutex_numero_sondaggi_terminati;
void inizializza_voti() {
int i;
for (i = 0; i < 5; i++) {
voti[i] = 0;
votazioni_terminate[i] = 0;
}
}
void inizializza_mutex_voti() {
int i;
for (i = 0; i < 5; i++) {
pthread_mutex_init(&mutex_voti[i], 0);
}
}
void stampa_voti_finali_film() {
int k;
for (k = 0; k < 5; k++) {
float voto_medio_film = (float)voti[k] / 10;
int film_id = k + 1;
printf("%d => %.1f", film_id, voto_medio_film);
if (k < 5 - 1) {
printf(" - ");
}
}
}
int get_id_film_vincitore() {
int indice_film_vincitore = -1;
float voto_film_vincitore = -1;
int k;
for (k = 0; k < 5; k++) {
float voto_medio_film = (float)voti[k] / 10;
if (voto_medio_film > voto_film_vincitore) {
voto_film_vincitore = voto_medio_film;
indice_film_vincitore = k;
}
}
int id_film_vincitore = indice_film_vincitore + 1;
return id_film_vincitore;
}
void *vota_e_guarda_vincitore(void *thread_id_ptr) {
long thread_id = (long)thread_id_ptr;
if (0) printf("Thread %ld: partito...\\n", thread_id);
int k;
for (k = 0; k < 5; k++) {
int film_id = k + 1;
if (0) printf("Thread %ld: attendo accesso a voto film %d\\n", thread_id, film_id);
pthread_mutex_lock(&mutex_voti[k]);
if (0) printf("Thread %ld: accedo a voto film %d\\n", thread_id, film_id);
int voto = (rand() % 10) + 1;
voti[k] += voto;
votazioni_terminate[k]++;
float voto_medio_film = (float)voti[k] / (float)votazioni_terminate[k];
printf("Thread %ld: punteggio attuale film %d: %.1f\\n", thread_id, film_id, voto_medio_film);
pthread_mutex_unlock(&mutex_voti[k]);
}
pthread_mutex_lock(&mutex_numero_sondaggi_terminati);
numero_sondaggi_terminati++;
if (numero_sondaggi_terminati == 10) {
sem_post(&barriera_sondaggi_terminati);
}
pthread_mutex_unlock(&mutex_numero_sondaggi_terminati);
sem_wait(&barriera_sondaggi_terminati);
sem_post(&barriera_sondaggi_terminati);
int id_film_vincitore = get_id_film_vincitore();
printf("Thread %ld: guardo film vincitore %d\\n", thread_id, id_film_vincitore);
pthread_exit(0);
}
int main (int argc, char *argv[]) {
srand(time(0));
if (0) printf("Inizializzo voti e relativi mutex\\n");
inizializza_voti();
inizializza_mutex_voti();
pthread_t thread_persone[10];
pthread_mutex_init(&mutex_numero_sondaggi_terminati, 0);
numero_sondaggi_terminati = 0;
sem_init(&barriera_sondaggi_terminati, 0, 0);
int i;
for (i = 0; i < 10; i++) {
if (0) printf("Main: creazione thread %d\\n", i);
long thread_id = i;
int result = pthread_create(&thread_persone[i], 0, vota_e_guarda_vincitore, (void *)thread_id);
if (result) {
printf("Main: ERRORE - creazione thread %d: %d\\n", i, result);
exit(-1);
}
}
for (i = 0; i < 10; i++) {
int result = pthread_join(thread_persone[i], 0);
if (result) {
if (0) printf("Main: ERRORE - attesa thread %d: %d\\n", i, result);
} else {
if (0) printf("Main: Thread %d terminato\\n", i);
}
}
if (0) printf("Main: Tutti i thread terminati\\n\\n\\n");
printf("Main: Risultato finale sondaggio\\n");
stampa_voti_finali_film();
printf("\\n\\n\\n");
return 0;
}
| 0
|
#include <pthread.h>
{
pthread_mutex_t mutex;
int index;
int buffer[8];
} Buffer;
void * add_val (void *ptr) {
Buffer *b = (Buffer *) ptr;
int tmp;
while (1) {
pthread_mutex_lock (&b->mutex);
if (b->index < 8) {
tmp = random();
b->buffer[b->index++] = tmp;
printf ("add: %d\\n", tmp);
}
pthread_mutex_unlock (&b->mutex);
usleep (10000);
}
return 0;
}
void * remove_val (void *ptr) {
Buffer *b = (Buffer *) ptr;
while (1) {
pthread_mutex_lock (&b->mutex);
while (b->index > 0) {
printf ("remove: %d\\n", b->buffer[--b->index]);
}
pthread_mutex_unlock (&b->mutex);
sleep (1);
}
return 0;
}
int main ()
{
pthread_t read_thread, write_thread;
Buffer *b = (Buffer *) malloc (sizeof (Buffer));
b->index = 0;
b->buffer[0] = 0;
pthread_create (&read_thread, 0, remove_val, (void *) b);
pthread_create (&write_thread, 0, add_val, (void *) b);
pthread_join (read_thread, 0);
pthread_join (write_thread, 0);
return 0;
}
| 1
|
#include <pthread.h>
int * px = 0;
int * py = 0;
pthread_mutex_t mutex_px = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_py = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_finx = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_finy = PTHREAD_COND_INITIALIZER;
void * mon_thread1 (void * arg){
int i;
printf("[Thread1] Deb\\n");
for (i=0;i<*(int*)arg;i++){
pthread_mutex_lock(&mutex_px);
printf("[Thread1] Valeur px: %d\\n", *px);
pthread_mutex_unlock(&mutex_px);
usleep(100);
}
printf("[Thread1]Fin\\n");
pthread_exit(0);
return 0;
}
void * mon_thread2 (void * arg){
int i;
printf("[Thread2] Deb\\n");
for (i=0;i<*(int*)arg;i++){
pthread_mutex_lock(&mutex_py);
printf("[Thread2] Valeur py: %d\\n", *py);
pthread_mutex_unlock(&mutex_py);
usleep(100);
}
printf("[Thread2] Fin\\n");
pthread_exit(0);
return 0;
}
int main(){
int x = 1;
int y = 2;
pthread_t tid1,tid2;
int max = 5;
int i = 0;
px = &x;
py = &y;
pthread_create(&tid1, 0, mon_thread1, &max);
pthread_create(&tid2, 0, mon_thread2, &max);
usleep(100);
while(i<max){
pthread_mutex_lock(&mutex_px);
if (pthread_mutex_trylock(&mutex_py) != 0){
printf("[Thread main] Lock py\\n");
px = 0;
py = 0;
printf("[Thread main] Valeur i: %d\\n", i);
px = &x;
py = &y;
i++;
pthread_mutex_unlock(&mutex_py);
printf("[Thread main] Unlock py\\n");
}
pthread_mutex_unlock(&mutex_px);
usleep(100);
}
pthread_exit(0) ;
printf("Fin main\\n");
return 0;
}
| 0
|
#include <pthread.h>
int head_index = 0;
int tail_index = 0;
int hw_buffer[1000];
pthread_t p1, p2, p3;
pthread_t k1, k2, k3;
pthread_mutex_t p_lock;
pthread_mutex_t k_lock;
int get_zufallszahl(int max_randomnummer){
int randomnummer = rand() % max_randomnummer + 1;
return randomnummer;
}
void put_rand_in_hw_buffer(int rand_nr){
hw_buffer[head_index] = rand_nr;
head_index = (head_index + 1) % 1000;
}
int get_rand_from_hw_buffer(){
int temp_index = tail_index;
tail_index = (tail_index + 1) % 1000;
return hw_buffer[temp_index];
}
void *produzent (){
while(1){
pthread_mutex_lock(&p_lock);
if (tail_index - head_index != 1 && tail_index - head_index != 999 ){
put_rand_in_hw_buffer(get_zufallszahl(1000));
}
pthread_mutex_unlock(&p_lock);
sleep(get_zufallszahl(5));
}
return 0;
}
void *konsument (){
while(1){
pthread_mutex_lock(&k_lock);
if (head_index - tail_index != 0){
printf("Auslesen aus Puffer: %d\\n", get_rand_from_hw_buffer());
}
pthread_mutex_unlock(&k_lock);
sleep(get_zufallszahl(5));
}
return 0;
}
int main(int argc, char *argv[]) {
srand(time(0));
pthread_create (&p1, 0, produzent, 0);
pthread_create (&p2, 0, produzent, 0);
pthread_create (&p3, 0, produzent, 0);
sleep(10);
pthread_create (&k1, 0, konsument, 0);
pthread_create (&k2, 0, konsument, 0);
pthread_create (&k3, 0, konsument, 0);
pthread_join (p1, 0);
pthread_join (p2, 0);
pthread_join (p3, 0);
pthread_join (k1, 0);
pthread_join (k2, 0);
pthread_join (k3, 0);
pthread_mutex_destroy(&p_lock);
pthread_mutex_destroy(&k_lock);
return 0;
}
| 1
|
#include <pthread.h>
const int PRODUCT_NUM = 10;
pthread_mutex_t mutex;
sem_t sem_empty, sem_full;
int g_idx;
void ConsumerFunc(void) {
volatile int flag = 1;
while (flag) {
sem_wait(&sem_full);
pthread_mutex_lock(&mutex);
printf(" ===>%d\\n", g_idx);
if (g_idx == PRODUCT_NUM) {
flag = 0;
}
sleep(rand()%3);
pthread_mutex_unlock(&mutex);
sem_post(&sem_empty);
}
}
void ProducerFunc(void) {
int i;
for (i = 1; i <= PRODUCT_NUM; i++) {
sem_wait(&sem_empty);
pthread_mutex_lock(&mutex);
g_idx = i;
printf("%d===>\\n", g_idx);
sleep(rand()%3);
pthread_mutex_unlock(&mutex);
sem_post(&sem_full);
}
}
int main(void) {
pthread_t p_tid, c_tid;
g_idx = 0;
pthread_mutex_init(&mutex, 0);
sem_init(&sem_empty, 0, 1);
sem_init(&sem_full, 0, 0);
pthread_create(&p_tid, 0, (void*)ProducerFunc, 0);
pthread_create(&c_tid, 0, (void*)ConsumerFunc, 0);
pthread_join(p_tid, 0);
pthread_join(c_tid, 0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
sem_t client_request, server_response;
pthread_mutex_t clients_me, finished_barrier_me;
volatile int val, n_finished;
void server();
void *client_thread(void *);
int main(int argc, char *argv[]) {
pthread_t t1, t2;
sem_init(&client_request, 0, 0);
sem_init(&server_response, 0, 0);
pthread_mutex_init(&clients_me, 0);
pthread_mutex_init(&finished_barrier_me, 0);
if(pthread_create(&t1, 0, client_thread, "1") != 0) {
fprintf(stderr, "Error creating client thread 1\\n");
return 1;
}
if(pthread_create(&t2, 0, client_thread, "2") != 0) {
fprintf(stderr, "Error creating client thread 2\\n");
return 1;
}
server();
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_mutex_destroy(&clients_me);
pthread_mutex_destroy(&finished_barrier_me);
sem_destroy(&server_response);
sem_destroy(&client_request);
return 0;
}
void server() {
int n_processed = 0;
while(1) {
sem_wait(&client_request);
if(n_finished == 2) {
printf("Server processed %d requests\\n.", n_processed);
return;
}
val *= 2;
sem_post(&server_response);
n_processed++;
}
}
void *client_thread(void *arg) {
char *filename;
char id;
int fd;
int val_private;
id = ((char *)arg)[0];
if(id == '1') {
filename = "fv1.b";
} else if(id == '2') {
filename = "fv2.b";
} else {
fprintf(stderr, "Wrong parameter to client thread\\n");
exit(1);
}
fd = open(filename, O_RDONLY);
if(fd == -1) {
perror("error opening file");
exit(2);
}
while(read(fd, &val_private, sizeof(int)) == sizeof(int)) {
printf("client %d read value %d\\n", id, val_private);
pthread_mutex_lock(&clients_me);
val = val_private;
sem_post(&client_request);
sem_wait(&server_response);
val_private = val;
pthread_mutex_unlock(&clients_me);
printf("client %d new value %d\\n", id, val_private);
}
pthread_mutex_lock(&finished_barrier_me);
val_private = ++n_finished;
pthread_mutex_unlock(&finished_barrier_me);
if(val_private == 2) {
sem_post(&client_request);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer = 0;
void *producer(void *ptr)
{
int i;
for (i = 1; i <= 300000; i++)
{
pthread_mutex_lock(&the_mutex);
if (buffer != 0)
pthread_cond_wait(&condp, &the_mutex);
buffer = i;
pthread_cond_signal(&condc);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
void *consumer(void *ptr)
{
int i;
for (i = 1; i <= 300000; i++)
{
pthread_mutex_lock(&the_mutex);
if (buffer == 0)
pthread_cond_wait(&condc, &the_mutex);
buffer = 0;
pthread_cond_signal(&condp);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
int main(int argc, char **argv)
{
pthread_t pro, con;
pthread_mutex_init(&the_mutex, 0);
pthread_cond_init(&condc, 0);
pthread_cond_init(&condp, 0);
pthread_create(&con, 0, consumer, 0);
pthread_create(&pro, 0, producer, 0);
pthread_join(pro, 0);
pthread_join(con, 0);
return 0;
}
| 0
|
#include <pthread.h>
void timediff(const char * s) {
static struct timeval tv;
struct timeval tmp;
gettimeofday(&tmp, 0);
int sec = (tmp.tv_sec - tv.tv_sec)*1000000;
int msec = (tmp.tv_usec - tv.tv_usec);
printf("%20.20s diff = %12.dusec\\n", s, sec + msec);
tv = tmp;
}
void addThree(int * l)
{
*l += 3;
}
int main()
{
struct timeval now;
gettimeofday(&now, 0);
srand(now.tv_usec);
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, 0);
int s = 0;
int l = 0;
timediff("start");
s = 0;
for(int i = 0; i < 1<<24; i++) {
s +=3;
}
timediff("row adding");
l = 0;
for(int i = 0; i < 1<<24; i++) {
addThree(&l);
}
assert(l == s);
timediff("function");
l = 0;
for(int i = 0; i < 1<<24; i++) {
pthread_mutex_lock(&mutex);
l +=3;
pthread_mutex_unlock(&mutex);
}
assert(l == s);
timediff("mutex");
l = 0;
for(int i = 0; i < 1<<24; i++) {
__atomic_add_fetch(&l, 3, 5);
}
assert(l == s);
timediff("atomic addfetch");
l = 0;
for(int i = 0; i < 1<<24; i++) {
int old;
int new;
do {
old = l;
new = l + 3;
} while(!__atomic_compare_exchange(&l, &old, &new, 0, 5, 5));
}
assert(l == s);
timediff("atomic cmpxchng");
l = 0;
for(int i = 0; i < 1<<24; i++) {
int old;
int new;
do {
old = l;
new = l + 3;
} while(!__sync_bool_compare_and_swap(&l, old, new));
}
assert(l == s);
timediff("sync cmpxchng");
printf("l=%d\\n",l);
return 0;
}
void do_some_work(int a)
{
}
| 1
|
#include <pthread.h>
int dprintf(int, const char*, ...);
static pthread_mutex_t name_service_mutex = PTHREAD_MUTEX_INITIALIZER;
static int ns_channel_initialized = 0;
static struct NaClSrpcChannel ns_channel;
static int prepare_nameservice(void) {
int ns = -1;
int connected_socket;
int error;
if (ns_channel_initialized)
return 0;
nacl_nameservice(&ns);
if (-1 == ns) {
error = errno;
dprintf(2, "IRT: nacl_nameservice failed: %s\\n", strerror(error));
return error;
}
connected_socket = imc_connect(ns);
error = errno;
close(ns);
if (-1 == connected_socket) {
dprintf(2, "IRT: imc_connect to nameservice failed: %s\\n", strerror(error));
return error;
}
if (!NaClSrpcClientCtor(&ns_channel, connected_socket)) {
dprintf(2, "IRT: NaClSrpcClientCtor failed for nameservice\\n");
return EIO;
}
ns_channel_initialized = 1;
return 0;
}
int irt_nameservice_lookup(const char *name, int oflag, int *out_fd) {
int error;
int status = -1;
pthread_mutex_lock(&name_service_mutex);
error = prepare_nameservice();
if (0 == error) {
if (NACL_SRPC_RESULT_OK != NaClSrpcInvokeBySignature(
&ns_channel, NACL_NAME_SERVICE_LOOKUP, name, oflag,
&status, out_fd)) {
dprintf(2, "IRT: SRPC failure for NACL_NAME_SERVICE_LOOKUP: %s\\n",
strerror(errno));
}
}
pthread_mutex_unlock(&name_service_mutex);
return status;
}
| 0
|
#include <pthread.h>
{
pthread_mutex_t *lock;
int id;
int size;
int iterations;
char *s;
} Thread_struct;
void *infloop(void *x)
{
int i, j, k;
Thread_struct *t;
t = (Thread_struct *) x;
for (i = 0; i < t->iterations; i++)
{
pthread_mutex_lock(t->lock);
for (j = 0; j < t->size-1; j++)
{
t->s[j] = 'A'+t->id;
for(k=0; k < 80000; k++);
}
t->s[j] = '\\0';
printf("Thread %d: %s\\n", t->id, t->s);
pthread_mutex_unlock(t->lock);
}
return(0);
}
int
main(int argc, char **argv)
{
pthread_mutex_t lock;
pthread_t *tid;
pthread_attr_t *attr;
Thread_struct *t;
void *retval;
int nthreads, size, iterations, i;
char *s;
if (argc != 4)
{
fprintf(stderr, "usage: race nthreads stringsize iterations\\n");
exit(1);
}
pthread_mutex_init(&lock, 0);
nthreads = atoi(argv[1]);
size = atoi(argv[2]);
iterations = atoi(argv[3]);
tid = (pthread_t *) malloc(sizeof(pthread_t) * nthreads);
attr = (pthread_attr_t *) malloc(sizeof(pthread_attr_t) * nthreads);
t = (Thread_struct *) malloc(sizeof(Thread_struct) * nthreads);
s = (char *) malloc(sizeof(char *) * size);
for (i = 0; i < nthreads; i++)
{
t[i].id = i;
t[i].size = size;
t[i].iterations = iterations;
t[i].s = s;
t[i].lock = &lock;
pthread_attr_init(&(attr[i]));
pthread_attr_setscope(&(attr[i]), PTHREAD_SCOPE_SYSTEM);
pthread_create(&(tid[i]), &(attr[i]), infloop, (void *)&(t[i]));
}
for (i = 0; i < nthreads; i++)
{
pthread_join(tid[i], &retval);
}
return(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER;
int term_lines;
int term_cols;
int fd;
int current_term_lines;
} data_t;
void *recieve_message(void *arg) {
char buf[1024];
data_t *data;
data = (data_t*) arg;
int rdbytes;
int line=1;
char user_limit_exceeded[] = "User limit exceeded! Try again later.";
while ((rdbytes = read(data->fd, buf, 1024 -1)) > 0) {
buf[rdbytes] = 0;
if (!strcmp(buf, user_limit_exceeded)) {
writestr_raw(buf, 0, line);
return 0;
}
pthread_mutex_lock(&screen);
writestr_raw(buf, 0, line);
if (line == (term_lines-1)) {
scroll_up(0, data->current_term_lines);
line--;
}
else {
line++;
}
pthread_mutex_unlock(&screen);
}
return 0;
}
int send_message(int fd, char *message) {
size_t len = strlen(message) + 1;
if (write(fd, message, len) != len) {
return -1;
}
return 0;
}
int main(int argc, char **argv)
{
int sock_fd;
int err;
pthread_t thr_id;
char *srv_addr;
char username[32 +1];
char buf[1024];
struct sockaddr_in client_sock;
if(argc != 3) {
printf("usage: client <ip address> <username>\\n");
exit(1);
}
srv_addr = argv[1];
if(strlen(argv[2]) > 32) {
fprintf(stderr, "Max. username length is %d.\\n", 32);
exit(1);
}
strcpy(username, argv[2]);
username[strlen(argv[2])] = '\\0';
if ( (sock_fd=socket(AF_INET,SOCK_STREAM, 0)) == -1)
{
perror("socket");
exit(1);
}
printf("Socket created!\\n");
memset(&client_sock, 0, sizeof(client_sock));
client_sock.sin_family = AF_INET;
err = inet_aton(srv_addr, &client_sock.sin_addr);
if(err < 0) {
printf("No valid IPv4 address!\\n");
exit(1);
}
client_sock.sin_port = htons(SRV_PORT);
if ( err = connect(sock_fd, (struct sockaddr *)&client_sock, sizeof(client_sock )) < 0)
{
perror("connect");
exit(1);
}
write(sock_fd, username, strlen(username)+1);
printf("connected to %s:%d as %s\\n", srv_addr, SRV_PORT, username);
memset(buf, 0, 1024);
err = pthread_create(&thr_id, 0, recieve_message, (void*) &sock_fd);
if (err) {
printf("Threaderzeugung: %s\\n", strerror(err));
}
printf("Current Term lines: %d\\n", term_lines);
clearscr();
term_cols = get_cols();
term_lines = get_lines();
for (;;) {
int i;
pthread_mutex_lock(&screen);
writestr_raw("Say something: ", 0, term_lines-1);
pthread_mutex_unlock(&screen);
gets_raw(buf, 1024, strlen("Say something: "), term_lines);
pthread_mutex_lock(&screen);
writestr_raw("Say something: ", 0, term_lines-1);
pthread_mutex_unlock(&screen);
for (i = 0; i < term_cols; i++) {
writestr_raw(" ", i, term_lines-1);
}
if (!strcmp(buf, "/quit")) {
break;
}
if (strlen(buf) > 0 && send_message(sock_fd, buf) == -1) {
fprintf(stderr, "could not end message \\n");
break;
}
}
close(sock_fd);
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t cache_thread_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_key_t cache_stats_thread_curr;
int thread_num = 0;
void cache_stats_process_init() {
pthread_key_create(&cache_stats_thread_curr, 0);
thread_num = mk_api->config->workers;
thread_stats = calloc(thread_num, sizeof(struct cache_stats_thread));
}
static int wid = 0;
void cache_stats_thread_init() {
pthread_mutex_lock(&cache_thread_mutex);
mk_bug(wid >= thread_num);
struct cache_stats_thread *stats = &thread_stats[wid];
stats->index = wid;
stats->reqs_per_sec = 0;
stats->reqs_served = 0;
gettimeofday(&stats->start, 0);
pthread_setspecific(cache_stats_thread_curr, (void *) stats);
wid++;
pthread_mutex_unlock(&cache_thread_mutex);
}
void cache_stats_thread_process(struct cache_stats_thread *stats) {
struct timeval tmp;
gettimeofday(&tmp, 0);
int ms = get_time_diff_ms(stats->start, tmp);
if (ms > 1000) {
stats->start = tmp;
stats->reqs_per_sec = stats->reqs_served / (ms / 1000.0);
stats->reqs_served = 0;
}
}
void cache_stats_tick() {
int reqs_per_sec = 0;
for (int i = 0; i < thread_num; i++) {
cache_stats_thread_process(&thread_stats[i]);
reqs_per_sec += thread_stats[i].reqs_per_sec;
}
cache_stats.reqs_per_sec = reqs_per_sec;
}
void cache_stats_req_new() {
struct cache_stats_thread *stats = pthread_getspecific(cache_stats_thread_curr);
stats->reqs_served++;
}
| 1
|
#include <pthread.h>
pthread_t tid[2];
pthread_mutex_t lock;
int sockfd = -1;
void error(char *msg)
{
perror(msg);
exit(0);
}
void ExitHandler()
{
char input[1000]="exit";
int len= strlen(input);
if (sockfd != -1)
{
write(sockfd, &len, sizeof(int));
write(sockfd, input, len);
}
exit(0);
}
void* inputer(void* args){
char buffer[256];
int n = -1;
while(1)
{
sleep(2);
pthread_mutex_lock(&lock);
bzero(buffer,256);
fgets(buffer,255,stdin);
if((strcmp(buffer,"exit\\n")) == 0){
write(sockfd,buffer,strlen(buffer));
exit(0);
break;
}
n = write(sockfd,buffer,strlen(buffer));
if(n <0){
error("Didn't Write");
}
pthread_mutex_unlock(&lock);
}
return 0;
}
void* outputer(void* args){
char buffer[256];
int n = -1;
while(1)
{
pthread_mutex_lock(&lock);
bzero(buffer,256);
n = read(sockfd,buffer,255);
if(n<=0)
{
printf("Lost Connection to the server :/\\n");
exit(0);
}
if(strlen(buffer)>1){
printf("%s\\n",buffer);
}
pthread_mutex_unlock(&lock);
}
return 0;
}
int main(int argc, char *argv[])
{
while(1)
{
printf("Attempting to connect to the server...\\n");
sleep(3);
int portno = -1;
int n = -1;
char buffer[256];
struct sockaddr_in serverAddressInfo;
struct hostent *serverIPAddress;
if (argc < 3)
{
fprintf(stderr,"usage %s hostname port\\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
serverIPAddress = gethostbyname(argv[1]);
if (serverIPAddress == 0)
{
fprintf(stderr,"ERROR, no such host\\n");
exit(0);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
error("ERROR creating socket");
}
bzero((char *) &serverAddressInfo, sizeof(serverAddressInfo));
serverAddressInfo.sin_family = AF_INET;
serverAddressInfo.sin_port = htons(portno);
bcopy((char *)serverIPAddress->h_addr, (char *)&serverAddressInfo.sin_addr.s_addr, serverIPAddress->h_length);
if (connect(sockfd,(struct sockaddr *)&serverAddressInfo,sizeof(serverAddressInfo)) < 0)
{
printf("ERROR connecting\\n");
}
else
{
break;
}
}
printf("WELCOME TO OUR BANK!\\n");
printf("Please press enter\\n");
pthread_create(&(tid[0]),0,&inputer,0);
pthread_create(&(tid[1]),0,&outputer,0);
pthread_join(tid[0],0);
pthread_join(tid[1],0);
pthread_mutex_destroy(&lock);
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER;
void *
thr_fn() {
int err, signo;
for (;;) {
err = sigwait(&mask, &signo);
if (err != 0) {
printf("sigwait failed");
exit (-1);
}
switch (signo) {
case SIGINT:
printf("\\n interrupt \\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&waitloc);
return (0);
default:
printf("unexpected signal &d\\n", signo);
exit(1);
}
}
}
int
main(void) {
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) {
printf(err, "SIG_BLOCK error");
exit (-1);
}
err = pthread_create(&tid, 0, thr_fn, 0);
err = pthread_create(&tid, 0, thr_fn, 0);
if (err != 0) {
printf(err, "can't create thread");
exit (-1);
}
pthread_mutex_lock(&lock);
while (quitflag == 0) {
pthread_cond_wait(&waitloc, &lock);
}
pthread_mutex_unlock(&lock);
quitflag = 0;
if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) {
printf(err, "SIG_SETMASK error");
exit (-1);
}
exit (0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
int currState = -1;
void *CreateDrone(void *);
void funcDroneInit(int *);
void funcDroneEnRoute(int *);
void funcDroneAddressReached(int *);
void funcDroneTaskFin(int *);
void *CreateDrone(void *arg)
{
int *data = (int *) arg;
funcDroneInit(data);
pthread_exit(0);
}
void funcDroneInit(int *data)
{
if (currState == 0) {
sleep(1);
} else {
sleep(1);
currState = 0;
pthread_mutex_unlock(&lock);
printf("> A drone from DECOY %ld is taking off for its destination address.\\n", data[1] + 1);
pthread_mutex_lock(&lock);
funcDroneEnRoute(data);
}
}
void funcDroneEnRoute(int *data)
{
if (currState == 1) {
sleep(2);
} else {
currState = 1;
pthread_mutex_unlock(&lock);
printf("> Drone from DECOY %ld is on route to its designated delivery address. Collision Detection - ON.\\n", data[1] + 1);
pthread_mutex_lock(&lock);
funcDroneAddressReached(data);
}
}
void funcDroneAddressReached(int *data)
{
if (currState == 2) {
sleep(1);
} else {
currState = 2;
pthread_mutex_unlock(&lock);
int x = rand() % 100;
int y = rand() % 100;
printf("> Drone from DECOY %ld has reached his destination coordinates(%d, %d). Delivering payload now...\\n", data[1] + 1,x,y);
pthread_mutex_lock(&lock);
funcDroneTaskFin(data);
}
}
void funcDroneTaskFin(int *data)
{
if (currState == 3) {
sleep(2);
} else {
currState = 3;
pthread_mutex_unlock(&lock);
printf("> Drone from DECOY %ld delivered payload, returning back to base.\\n", data[1] + 1);
}
}
int main (int argc, char *argv[])
{
char line[256];
printf("%s", "> Please enter number of drones (threads) for the DECOY simulation: ");
int numDrone = atoi(fgets(line, sizeof(line), stdin));
if (numDrone > 1){
printf("> Since multiple drones are delivering in the air simultaneously, the order of delivery may appear to be arbitrary.\\n>\\n");
}
int rc, a, b, currDrone, numDecoy;
numDecoy = 0;
pid_t p;
pthread_t thread[numDrone];
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
currDrone = 0;
a = 1;
b = 1;
while(currDrone<numDrone) {
printf("> Initializing delivery sequence for Drone %ld from DECOY %ld. Current location of the drone (%d,%d)\\n", currDrone + 1, numDecoy + 1, a, b);
int droneData[2] = {currDrone, numDecoy};
pthread_mutex_lock(&lock);
rc = pthread_create(&thread[currDrone], 0, CreateDrone, (void *)droneData);
if (rc) {
printf("> ERROR; return code from pthread_create()is %d\\n", rc);
exit(-1);
}
currDrone++;
}
pthread_mutexattr_destroy(&attr);
currDrone = 0;
while(currDrone<numDrone) {
rc = pthread_join(thread[currDrone], 0);
if (rc) {
printf("> ERROR; return code from pthread_join() is %d\\n", rc);
exit(-1);
}
printf("> Drone %ld returned to DECOY %d. Ready for next assignment.\\n", currDrone + 1, numDecoy + 1);
currDrone++;
}
printf("> All payload deliveries have been completed by the drone for DECOY %d. Location: Base - (%d,%d)\\n", numDecoy + 1, a, b);
pthread_exit(0);
pthread_mutex_destroy(&lock);
return 0;
}
| 0
|
#include <pthread.h>
static
struct urcu_game_config *current_config;
static
pthread_mutex_t config_mutex = PTHREAD_MUTEX_INITIALIZER;
struct urcu_game_config *urcu_game_config_get(void)
{
assert(rcu_read_ongoing());
return rcu_dereference(current_config);
}
struct urcu_game_config *urcu_game_config_update_begin(void)
{
struct urcu_game_config *new_config;
new_config = malloc(sizeof(*new_config));
if (!new_config) {
return 0;
}
pthread_mutex_lock(&config_mutex);
if (current_config)
memcpy(new_config, current_config, sizeof(*new_config));
else
memset(new_config, 0, sizeof(*new_config));
return new_config;
}
void urcu_game_config_update_end(struct urcu_game_config *new_config)
{
struct urcu_game_config *old_config;
old_config = current_config;
rcu_set_pointer(¤t_config, new_config);
pthread_mutex_unlock(&config_mutex);
if (old_config) {
synchronize_rcu();
free(old_config);
}
}
void urcu_game_config_update_abort(struct urcu_game_config *new_config)
{
pthread_mutex_unlock(&config_mutex);
free(new_config);
}
void init_game_config(void)
{
struct urcu_game_config *new_config;
new_config = urcu_game_config_update_begin();
new_config->island_size = DEFAULT_ISLAND_SIZE;
new_config->step_delay = DEFAULT_STEP_DELAY;
new_config->gerbil.max_birth_stamina =
DEFAULT_GERBIL_MAX_BIRTH_STAMINA;
new_config->gerbil.animal = GERBIL;
new_config->gerbil.diet = DIET_FLOWERS | DIET_TREES;
new_config->gerbil.max_pregnant = 10;
new_config->cat.max_birth_stamina =
DEFAULT_CAT_MAX_BIRTH_STAMINA;
new_config->cat.animal = CAT;
new_config->cat.diet = DIET_GERBIL | DIET_FLOWERS;
new_config->cat.max_pregnant = 4;
new_config->snake.max_birth_stamina =
DEFAULT_SNAKE_MAX_BIRTH_STAMINA;
new_config->snake.animal = SNAKE;
new_config->snake.diet = DIET_GERBIL | DIET_CAT;
new_config->snake.max_pregnant = 1;
urcu_game_config_update_end(new_config);
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t index_lock = PTHREAD_MUTEX_INITIALIZER;
int * counters;
int index = 0;
bool stop = 0;
static void * locking(void * arg) {
int my_index;
pthread_mutex_lock(&index_lock);
my_index = index++;
pthread_mutex_unlock(&index_lock);
while(!stop) {
pthread_mutex_lock(&lock);
counters[my_index]++;
pthread_mutex_unlock(&lock);
}
return 0;
}
int main(int argc, char ** argv) {
int NTHREADS = strtol(argv[1], 0, 10);
printf("Threads: %d\\n", NTHREADS);
counters = malloc(sizeof(int) * NTHREADS);
pthread_t threads[NTHREADS];
for (int i = 0; i < NTHREADS; i++) {
pthread_create(&threads[i], 0, locking, 0);
}
sleep(1);
pthread_mutex_lock(&lock);
for (int i = 0; i < NTHREADS; i++) {
counters[i] = 0;
}
pthread_mutex_unlock(&lock);
sleep(3);
pthread_mutex_lock(&lock);
double max = 0;
double min = counters[0]/3;
int total = 0;
for (int i = 0; i < NTHREADS; i++) {
total += counters[i];
double lock_p_sec = (double)counters[i]/3;
if (min > lock_p_sec) {
min = lock_p_sec;
}
if (max < lock_p_sec) {
max = lock_p_sec;
}
printf("[%2d] %'12.2f\\n", i, lock_p_sec);
}
printf("Total locks: %'12d\\n", total);
printf("Per second: %'12d\\n", total/3);
printf("Perc. diff.:\\t %'6.2f%%\\n", ((max - min)/((max + min)/2)) * 100);
stop = 1;
pthread_mutex_unlock(&lock);
for (int i = 0; i < NTHREADS; i++) {
pthread_join(threads[i], 0);
}
free(counters);
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t spi_lock;
int ipc_spi_read(unsigned char *data,int len,unsigned char mode)
{
int ret_val,data_counter=0;
wait_for_gpio_interrupt_spi();
pthread_mutex_lock(&spi_lock);
switch(mode)
{
case EIGHT_BIT:
if(data != 0)
{
while(len != 0)
{
if(read_spi_8bit(&data[data_counter]) < 0)
{
printf("\\n Data Read Failed");
fflush(stdout);
ret_val = -1;
break;
}
}
len--;
data_counter++;
}
break;
case SIXTEEN_BIT:
break;
default:
printf("\\n Wrong mode passed: Possible values are 8BIT, 16BIT");
break;
}
pthread_mutex_unlock(&spi_lock);
return ret_val;
}
int ipc_spi_write (unsigned char *data,int len,const unsigned char mode)
{
int ret_val=0;
int data_counter=0;
pthread_mutex_lock(&spi_lock);
switch(mode)
{
case EIGHT_BIT:
if(data != 0)
{
while(len != 0)
{
if(write_spi_8bit(data[data_counter]) < 0)
{
printf("\\n Data Written Failed at index %d", data_counter);
fflush(stdout);
ret_val = -1;
break;
}
len--;
data_counter++;
}
}
break;
case SIXTEEN_BIT:
break;
}
pthread_mutex_unlock(&spi_lock);
return ret_val;
}
| 1
|
#include <pthread.h>
struct ws2801_kernel {
int fd_commit;
int fd_refresh_rate;
int fd_set_raw;
int fd_num_leds;
struct led *leds_packed;
};
static void ws2801_kernel_commit(struct ws2801_driver *ws_driver)
{
struct ws2801_kernel *ws = ws_driver->drv_data;
unsigned int i;
struct led *dst = ws->leds_packed;
struct led *src = ws_driver->leds;
pthread_mutex_lock(&ws_driver->data_lock);
for (i = 0; i < ws_driver->num_leds; i++, dst++, src++) {
dst->r = src->r;
dst->g = src->g;
dst->b = src->b;
}
pthread_mutex_unlock(&ws_driver->data_lock);
if (write(ws->fd_set_raw, ws->leds_packed,
ws_driver->num_leds * sizeof(*dst)) == -1) {
fprintf(stderr, "ws2801: error during set_raw\\n");
exit(-errno);
}
if (write(ws->fd_commit, "", 1) == -1) {
fprintf(stderr, "ws2801: error during commit\\n");
exit(-errno);
}
}
static int ws2801_kernel_set_refresh_rate(struct ws2801_driver *ws_driver,
unsigned int refresh_rate)
{
struct ws2801_kernel *ws = ws_driver->drv_data;
char buffer[16];
int bytes;
bytes = snprintf(buffer, sizeof(buffer), "%u\\n", refresh_rate);
if (write(ws->fd_refresh_rate, buffer, bytes) == -1)
return -errno;
return 0;
}
static inline void __close_handle(int handle)
{
if (handle > 0)
close(handle);
}
static void __ws2801_kernel_free(struct ws2801_kernel *ws)
{
__close_handle(ws->fd_commit);
__close_handle(ws->fd_refresh_rate);
__close_handle(ws->fd_set_raw);
__close_handle(ws->fd_num_leds);
if (ws->leds_packed)
free(ws->leds_packed);
free(ws);
}
static void ws2801_kernel_free(struct ws2801_driver *ws_driver)
{
struct ws2801_kernel *ws = ws_driver->drv_data;
__ws2801_kernel_free(ws);
ws2801_free(ws_driver);
}
static int ws2801_kernel_set_num_leds(struct ws2801_driver *ws_driver,
unsigned int num_leds)
{
struct ws2801_kernel *ws = ws_driver->drv_data;
char buffer[16];
int bytes;
ws_driver->num_leds = num_leds;
bytes = snprintf(buffer, sizeof(buffer), "%u\\n", num_leds);
if (write(ws->fd_num_leds, buffer, bytes) == -1)
return -errno;
return 0;
}
int ws2801_kernel_init(unsigned int num_leds, const char *device_name,
struct ws2801_driver *ws_driver)
{
struct ws2801_kernel *ws;
char buffer[1024];
int err;
ws = calloc(1, sizeof(*ws));
if (!ws)
return -ENOMEM;
ws->leds_packed = malloc(num_leds * sizeof(*ws->leds_packed));
if (!ws->leds_packed) {
err = -ENOMEM;
goto free_out;
}
err = ws2801_init(ws_driver, num_leds);
if (err)
goto free_out;
ws_driver->drv_data = ws;
snprintf(buffer, sizeof(buffer), "/sys/devices/ws2801/devices/" "%s/" "commit", device_name); ws->fd_commit = open(buffer, O_WRONLY); if (ws->fd_commit < 0) { fprintf(stderr, "unable to open %s\\n", buffer); err = -errno; goto free_out; };
snprintf(buffer, sizeof(buffer), "/sys/devices/ws2801/devices/" "%s/" "refresh_rate", device_name); ws->fd_refresh_rate = open(buffer, O_WRONLY); if (ws->fd_refresh_rate < 0) { fprintf(stderr, "unable to open %s\\n", buffer); err = -errno; goto free_out; };
snprintf(buffer, sizeof(buffer), "/sys/devices/ws2801/devices/" "%s/" "set_raw", device_name); ws->fd_set_raw = open(buffer, O_WRONLY); if (ws->fd_set_raw < 0) { fprintf(stderr, "unable to open %s\\n", buffer); err = -errno; goto free_out; };
snprintf(buffer, sizeof(buffer), "/sys/devices/ws2801/devices/" "%s/" "num_leds", device_name); ws->fd_num_leds = open(buffer, O_WRONLY); if (ws->fd_num_leds < 0) { fprintf(stderr, "unable to open %s\\n", buffer); err = -errno; goto free_out; };
err = ws2801_kernel_set_num_leds(ws_driver, num_leds);
if (err)
goto free_out;
ws_driver->set_auto_commit = ws2801_set_auto_commit;
ws_driver->clear = ws2801_clear;
ws_driver->commit = ws2801_kernel_commit;
ws_driver->set_refresh_rate = ws2801_kernel_set_refresh_rate;
ws_driver->set_led = ws2801_set_led;
ws_driver->set_leds = ws2801_set_leds;
ws_driver->full_on = ws2801_full_on;
ws_driver->free = ws2801_kernel_free;
return 0;
free_out:
__ws2801_kernel_free(ws);
return err;
}
| 0
|
#include <pthread.h>
int count = 0;
int in = 0;
int out = 0;
item buff[5];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t full;
sem_t empty;
void *producer();
void *consumer();
int main(){
int i;
pthread_t pthread[4];
sem_init(&full,0,0);
sem_init(&empty,0,5 -1);
for(i=0;i<2;i++){
pthread_create(&pthread[i],0,producer,0);
}
for(i=2;i<4;i++){
pthread_create(&pthread[i],0,consumer,0);
}
for(i=0;i<4;i++){
pthread_join(pthread[i],0);
}
return 0;
}
void *producer(){
item next_Produced;
int temp;
printf("Producer is Created!\\n");
while(1){
next_Produced++;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
buff[in] = next_Produced;
in = (in+1) % 5;
sleep(1);
temp = count;
printf("producer produced, counter : %d -> %d\\n", temp, temp+1);
count++;
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void *consumer(){
item next_Consumed;
int temp;
printf("Consumer is Created!\\n");
while(1){
sem_wait(&full);
pthread_mutex_lock(&mutex);
next_Consumed = buff[out];
out = (out+1) % 5;
sleep(1);
temp = count;
printf("consumer consumed, counter : %d -> %d\\n", temp, temp-1);
pthread_mutex_unlock(&mutex);
sem_post(&empty);
count--;
}
}
| 1
|
#include <pthread.h>
int glab = 1;
void *r1(void *arg)
{
pthread_mutex_t* mutex = (pthread_mutex_t *)arg;
static int cnt = 10;
while(cnt--)
{
pthread_mutex_lock(mutex);
glab++;
printf("I am in r1. cnt = %d\\n", glab);
pthread_mutex_unlock(mutex);
sleep(1);
}
return "r1 over";
}
void *r2(void *arg)
{
pthread_mutex_t* mutex = (pthread_mutex_t *)arg;
static int cnt = 10;
while(cnt--)
{
pthread_mutex_lock(mutex);
glab++;
printf("I am in r2. cnt = %d\\n", glab);
pthread_mutex_unlock(mutex);
sleep(1);
}
return "r2 over";
}
int main(void)
{
pthread_mutex_t mutex;
pthread_t t1, t2;
char* p1 = 0;
char* p2 = 0;
if(pthread_mutex_init(&mutex, 0) < 0)
do { perror("sem_init error"); exit(-1); } while(0);
pthread_create(&t1, 0, r1, &mutex);
pthread_create(&t2, 0, r2, &mutex);
pthread_join(t1, (void **)&p1);
pthread_join(t2, (void **)&p2);
pthread_mutex_destroy(&mutex);
printf("s1: %s\\n", p1);
printf("s2: %s\\n", p2);
return 0;
}
| 0
|
#include <pthread.h>
int counter=0;
pthread_mutex_t mutex;
void * thrfunc(void *thread){
int i;
for(i=0;i<10;i++){
pthread_mutex_lock(&mutex);
counter++;
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void * thrfunc1(void *thread){
int i;
for(i=0;i<10;i++){
printf ("%d\\n", counter);
sleep(1);
}
}
int main (){
pthread_t threads[2];
int thr, thr1;
long tmp;
printf ("Starting thread 0\\n");
thr = pthread_create(&threads[0],0,thrfunc, (void *)0);
if (thr){
printf("error in thread 0 %d\\n",thr);
exit(-1);
}
printf ("Starting thread 1\\n");
thr1 = pthread_create(&threads[1],0,thrfunc1, (void *)1);
if (thr1){
printf("error in thread 1 %d\\n",thr);
exit(-1);
}
for (tmp=0;tmp <2;tmp++){
pthread_join(threads[tmp],0);
}
return 0;
}
| 1
|
#include <pthread.h>
struct list_item
{
struct list_item *next;
unsigned int size;
unsigned char inuse;
};
struct heap_t
{
void *base;
unsigned int size;
struct list_item *first_ptr;
pthread_mutex_t mutex;
FILE * pFile;
} heap;
int heap_init(unsigned int heap_size)
{
heap.pFile = fopen ("myfile.txt","w");
heap.base = malloc(heap_size);
if (0==heap.base)
{
fprintf(stderr, "Allocation memory failed.\\n");
return -1;
}
pthread_mutex_init(&heap.mutex, 0);
heap.size = heap_size;
heap.first_ptr = heap.base;
heap.first_ptr->next = 0;
heap.first_ptr->size = heap.size - sizeof(struct list_item);
heap.first_ptr->inuse = 0;
return 0;
}
void heap_close(void)
{
free(heap.base);
pthread_mutex_destroy(&heap.mutex);
fclose (heap.pFile);
}
void *_myalloc(size_t size)
{
struct list_item *hole = heap.first_ptr;
while ( hole != 0 )
{
if (hole->inuse == 0)
{
if (hole->size == size)
{
hole->inuse = 1;
return (void *)hole + sizeof(struct list_item);
}
else if (hole->size > (size + sizeof(struct list_item)))
{
struct list_item *new_hole;
new_hole = (void *)hole + size + sizeof(struct list_item);
new_hole->next = hole->next;
new_hole->size = hole->size - size - sizeof(struct list_item);
new_hole->inuse = 0;
hole->next = new_hole;
hole->size = size;
hole->inuse = 1;
return (void *)hole + sizeof(struct list_item);
}
}
hole = hole->next;
}
return 0;
}
void *myalloc(size_t size)
{
void *ptr;
pthread_mutex_lock(&heap.mutex);
ptr = _myalloc(size);
fprintf(heap.pFile, "myalloc(PID %d) Allocated memory at 0x%x, size: %d\\n", (unsigned int)pthread_self(), ptr, size);
pthread_mutex_unlock(&heap.mutex);
return ptr;
}
void _myfree(void *ptr)
{
struct list_item
*alloc,
*hole,
*free_before = 0,
*free_after = 0;
if(0 == ptr)
return;
alloc = ptr - sizeof(struct list_item);
hole = heap.first_ptr;
while (hole != 0)
{
if ( hole->next == alloc && hole->inuse == 0)
{
free_before = hole;
}
if ( alloc->next == hole && hole->inuse == 0)
{
free_after = hole;
}
hole = hole->next;
}
if ( free_before != 0 )
{
free_before->next = alloc->next;
free_before->size += alloc->size + sizeof(struct list_item);
alloc = free_before;
}
if ( free_after != 0 )
{
alloc->next = free_after->next;
alloc->size += free_after->size + sizeof(struct list_item);
}
alloc->inuse = 0;
return;
}
void myfree(void *ptr)
{
struct list_item *current_item_ptr;
pthread_mutex_lock(&heap.mutex);
current_item_ptr = ptr - sizeof(struct list_item);
fprintf(heap.pFile, "myfree(PID %d) Free memory at 0x%x, size: %d\\n", (unsigned int)pthread_self(), ptr, current_item_ptr->size);
_myfree(ptr);
pthread_mutex_unlock(&heap.mutex);
}
void print_mem(void)
{
struct list_item *item_ptr = heap.first_ptr;
printf("/********************/\\n");
do
{
printf("item_ptr: %x\\n", (unsigned int)item_ptr);
printf("item_ptr data: %x\\n", (unsigned int)item_ptr + sizeof(struct list_item));
printf("item_ptr->next_ptr: %x\\n", (unsigned int)item_ptr->next);
printf("item_ptr->size: %i\\n", item_ptr->size);
printf("item_ptr->inuse: %x\\n", item_ptr->inuse);
printf("\\n");
item_ptr = item_ptr->next;
}while(item_ptr);
}
| 0
|
#include <pthread.h>
sem_t sem_agent;
sem_t sem_tobacco;
sem_t sem_paper;
sem_t sem_match;
sem_t tobacco;
sem_t match;
sem_t paper;
sem_t sem_mutex;
bool tobFree = 0;
bool paperFree = 0;
bool matchesFree = 0;
void *agentA(void *);
void *agentB(void *);
void *agentC(void *);
void *pusherA(void *);
void *pusherB(void *);
void *pusherC(void *);
void *smoker1(void *);
void *smoker2(void *);
void *smoker3(void *);
pthread_mutex_t print_mutex;
int main( int argc, char *argv[] ) {
pthread_t a1, a2, a3, p1, p2, p3, s1, s2, s3;
sem_init(&sem_agent, 0, 1);
sem_init(&sem_tobacco, 0, 0);
sem_init(&sem_paper, 0, 0);
sem_init(&sem_match, 0, 0);
sem_init(&tobacco, 0, 0);
sem_init(&paper, 0, 0);
sem_init(&match, 0, 0);
sem_init(&sem_mutex, 0, 1);
pthread_mutex_init(&print_mutex, 0);
pthread_create(&a1, 0, agentA, 0);
pthread_create(&a2, 0, agentB, 0);
pthread_create(&a3, 0, agentC, 0);
pthread_create(&s1, 0, smoker1, 0);
pthread_create(&s2, 0, smoker2, 0);
pthread_create(&s3, 0, smoker3, 0);
pthread_create(&p1, 0, pusherA, 0);
pthread_create(&p2, 0, pusherB, 0);
pthread_create(&p3, 0, pusherC, 0);
while(1){
}
}
void *agentA(void *a){
while(1){
sem_wait(&sem_agent);
sem_post(&sem_tobacco);
sem_post(&sem_paper);
}
}
void *agentB(void *b){
while(1){
sem_wait(&sem_agent);
sem_post(&sem_tobacco);
sem_post(&sem_match);
}
}
void *agentC(void *c){
while(1){
sem_wait(&sem_agent);
sem_post(&sem_paper);
sem_post(&sem_match);
}
}
void *smoker1(void *a){
while(1){
pthread_mutex_lock(&print_mutex);
printf("S1 needs tobacco\\n");
pthread_mutex_unlock(&print_mutex);
sem_wait(&tobacco);
pthread_mutex_lock(&print_mutex);
printf("S1 gets tobacco, roll cig\\n");
pthread_mutex_unlock(&print_mutex);
sem_post(&sem_agent);
pthread_mutex_lock(&print_mutex);
printf("S1 rolls one and drops the tabacco\\n" );
pthread_mutex_unlock(&print_mutex);
sleep(4);
}
}
void *smoker2(void *b){
while(1){
pthread_mutex_lock(&print_mutex);
printf("S2 needs Paper\\n");
pthread_mutex_unlock(&print_mutex);
sem_wait(&paper);
pthread_mutex_lock(&print_mutex);
printf("S2 gets paper, roll cig\\n");
pthread_mutex_unlock(&print_mutex);
sem_post(&sem_agent);
pthread_mutex_lock(&print_mutex);
printf("S2 rolls one and drops papers\\n" );
pthread_mutex_unlock(&print_mutex);
sleep(4);
}
}
void *smoker3(void *c){
while(1){
pthread_mutex_lock(&print_mutex);
printf("S3 needs matches\\n");
pthread_mutex_unlock(&print_mutex);
sem_wait(&match);
pthread_mutex_lock(&print_mutex);
printf("S3 gets matches, roll cig\\n");
pthread_mutex_unlock(&print_mutex);
sem_post(&sem_agent);
pthread_mutex_lock(&print_mutex);
printf("S3 rolls one and drops matches\\n" );
pthread_mutex_unlock(&print_mutex);
sleep(4);
}
}
void *pusherA(void *a){
while(1){
sem_wait(&sem_tobacco);
pthread_mutex_lock(&print_mutex);
printf("Tobacco is on the table.\\n");
pthread_mutex_unlock(&print_mutex);
sem_wait(&sem_mutex);
if(paperFree){
paperFree = 0;
sem_post(&paper);
}else if(matchesFree){
matchesFree = 0;
sem_post(&match);
}else{
tobFree = 1;
}
sem_post(&sem_mutex);
}
}
void *pusherB(void *b){
while(1){
sem_wait(&sem_match);
pthread_mutex_lock(&print_mutex);
printf("Matches are on the table.\\n");
pthread_mutex_unlock(&print_mutex);
sem_wait(&sem_mutex);
if(paperFree){
paperFree = 0;
sem_post(&match);
}else if(tobFree){
tobFree = 0;
sem_post(&tobacco);
}else{
matchesFree = 1;
}
sem_post(&sem_mutex);
}
}
void *pusherC(void *c){
while(1){
sem_wait(&sem_paper);
pthread_mutex_lock(&print_mutex);
printf("Paper is on the table.\\n");
pthread_mutex_unlock(&print_mutex);
sem_wait(&sem_mutex);
if(tobFree){
tobFree = 0;
sem_post(&tobacco);
}else if(matchesFree){
matchesFree = 0;
sem_post(&match);
}else{
paperFree = 1;
}
sem_post(&sem_mutex);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t theMutex;
pthread_cond_t condc, condp;
int buffer=0;
void* producer(void* ptr)
{
int x;
for(x=0; x<=4; x++)
{
pthread_mutex_lock(&theMutex);
printf("Producer Locked\\n");
while(buffer!=0)
{
printf("Producer waiting\\n");
pthread_cond_wait(&condp, &theMutex);
}
printf("Producer creating widget %d\\n", x);
buffer=x;
printf("Signaling Consumer\\n");
pthread_cond_signal(&condc);
pthread_mutex_unlock(&theMutex);
printf("Producer unlocked\\n");
}
pthread_exit(0);
}
void* consumer(void* ptr)
{
int x;
for(x=1; x<=4; x++)
{
pthread_mutex_lock(&theMutex);
printf("Consumer locked\\n");
while(buffer==0)
{
printf("Consumer waiting\\n");
pthread_cond_wait(&condc, &theMutex);
}
printf("Consumer consuming widget %d\\n", x);
buffer=0;
printf("Signaling Producer\\n");
pthread_cond_signal(&condp);
pthread_mutex_unlock(&theMutex);
printf("Consumer unlocked\\n");
}
pthread_exit(0);
}
int main()
{
pthread_t pro1, con1, pro2, con2, pro3, con3, pro4, con4, pro5, con5;
pthread_mutex_init(&theMutex, 0);
pthread_cond_init(&condc, 0);
pthread_cond_init(&condp, 0);
printf("Creating Consumer1\\n");
pthread_create(&con1, 0, consumer, 0);
printf("Creating Producer1\\n");
pthread_create(&pro1, 0, producer, 0);
printf("Creating Consumer2\\n");
pthread_create(&con2, 0, consumer, 0);
printf("Creating Producer2\\n");
pthread_create(&pro2, 0, producer, 0);
printf("Creating Consumer3\\n");
pthread_create(&con3, 0, consumer, 0);
printf("Creating Producer3\\n");
pthread_create(&pro3, 0, producer, 0);
printf("Creating Consumer4\\n");
pthread_create(&con4, 0, consumer, 0);
printf("Creating Producer4\\n");
pthread_create(&pro4, 0, producer, 0);
printf("Creating Consumer5\\n");
pthread_create(&con5, 0, consumer, 0);
printf("Creating Producer5\\n");
pthread_create(&pro5, 0, producer, 0);
printf("Executing Producer1\\n");
pthread_join(pro1, 0);
printf("Executing Consumer1\\n");
pthread_join(con1, 0);
printf("Executing Producer2\\n");
pthread_join(pro2, 0);
printf("Executing Consumer2\\n");
pthread_join(con2, 0);
printf("Executing Producer3\\n");
pthread_join(pro3, 0);
printf("Executing Consumer3\\n");
pthread_join(con3, 0);
printf("Executing Producer4\\n");
pthread_join(pro4, 0);
printf("Executing Consumer4\\n");
pthread_join(con4, 0);
printf("Executing Producer5\\n");
pthread_join(pro5, 0);
printf("Executing Consumer5\\n");
pthread_join(con5, 0);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
pthread_mutex_destroy(&theMutex);
return 0;
}
| 0
|
#include <pthread.h>
int N=100;
int T=4;
pthread_mutex_t count_lock;
pthread_cond_t ok_to_proceed;
int count;
} barrier;
double escalar;
barrier *barrera;
double max, min, suma;
double *R;
double* M[3];
pthread_mutex_t mutexMax;
pthread_mutex_t mutexMin;
pthread_mutex_t mutexAvg;
void printMatrix(double* M, char* c, int ord){
int i,j;
printf("Matriz %s:\\n", c);
if(ord==1){
for (i=0;i<N;i++){
for(j=0;j<N;j++){
printf("%f ",M[i+j*N]);
}
printf("\\n");
}
} else {
for (i=0;i<N;i++){
for(j=0;j<N;j++){
printf("%f ",M[i*N+j]);
}
printf("\\n");
}
}
}
double dwalltime(){
double sec;
struct timeval tv;
gettimeofday(&tv,0);
sec = tv.tv_sec + tv.tv_usec/1000000.0;
return sec;
}
void *hilar(void *s){
int i,k,j,c;
int tid = *((int*)s);
int cant=0;
int inicio=tid*(N/T);
int fin=inicio+N/T;
double minLocal, maxLocal, sumaLocal;
minLocal=9999;
maxLocal=-999;
sumaLocal=0;
for(i=inicio;i<fin;++i){
for(j=0;j<N;++j){
R[i*N+j]=0;
if(M[0][i*N+j] < minLocal) minLocal=M[0][i*N+j];
if(M[0][i*N+j] > maxLocal) maxLocal=M[0][i*N+j];
if(M[1][i*N+j] < minLocal) minLocal=M[1][i*N+j];
if(M[1][i*N+j] > maxLocal) maxLocal=M[1][i*N+j];
sumaLocal+=M[0][i*N+j]+M[1][i*N+j];
for(c=0;c<N;++c){
R[i*N+j]+=M[0][i*N+c]*M[1][c+j*N];
}
}
}
for(k=2;k<3;++k){
if(k%2==1){
for(i=inicio;i<fin;++i){
for(j=0;j<N;++j){
R[i*N+j]=0;
if(M[k][i*N+j] < minLocal) minLocal=M[k][i*N+j];
if(M[k][i*N+j] > maxLocal) maxLocal=M[k][i*N+j];
sumaLocal+=M[k][i*N+j];
for(c=0;c<N;++c){
R[i*N+j]+=M[0][i*N+c]*M[k][c+j*N];
}
}
}
} else {
for(i=inicio;i<fin;++i){
for(j=0;j<N;++j){
M[0][i*N+j]=0;
if(M[k][i*N+j] < minLocal) minLocal=M[k][i*N+j];
if(M[k][i*N+j] > maxLocal) maxLocal=M[k][i*N+j];
sumaLocal+=M[k][i*N+j];
for(c=0;c<N;++c){
M[0][i*N+j]+=R[i*N+c]*M[k][c+j*N];
}
}
}
}
}
pthread_mutex_lock(&mutexMax);
if(maxLocal>max)
max=maxLocal;
pthread_mutex_unlock(&mutexMax);
pthread_mutex_lock(&mutexMin);
if(minLocal<min)
min=minLocal;
pthread_mutex_unlock(&mutexMin);
pthread_mutex_lock(&mutexAvg);
suma+=sumaLocal;
pthread_mutex_unlock(&mutexAvg);
pthread_mutex_lock(&(barrera -> count_lock));
barrera -> count ++;
if (barrera -> count == T){
barrera -> count = 0;
escalar=pow(((max-min)/(suma/(N*N*3))),3);
if(3%2 == 1){
free(R);
R=M[0];
}
pthread_cond_broadcast(&(barrera -> ok_to_proceed));
}else{
pthread_cond_wait(&(barrera -> ok_to_proceed),&(barrera -> count_lock));
}
pthread_mutex_unlock(&(barrera -> count_lock));
for(i=inicio;i<fin;++i){
for(j=0;j<N;++j){
R[i*N+j] *= escalar;
}
}
}
int main(int argc,char*argv[]){
int i,j,k;
double timetick;
if ((argc != 3) || ((N = atoi(argv[1])) <= 0) || ((T = atoi(argv[2])) <= 0))
{
printf("\\nUsar: %s n t\\n n: Dimension de la matriz (nxn X nxn)\\n t: Cantidad de threads\\n", argv[0]);
exit(1);
}
R=(double*)malloc(sizeof(double)*N*N);
for(i=0;i<3;i++){
M[i]=(double*)malloc(sizeof(double)*N*N);
}
M[0][0]=1;
M[0][1]=2;
M[0][2]=3;
M[0][3]=4;
M[0][4]=5;
M[0][5]=6;
M[0][6]=7;
M[0][7]=8;
M[0][8]=9;
M[0][9]=10;
M[0][10]=11;
M[0][11]=12;
M[0][12]=13;
M[0][13]=14;
M[0][14]=15;
M[0][15]=16;
M[1][0]=17;
M[1][1]=21;
M[1][2]=25;
M[1][3]=29;
M[1][4]=18;
M[1][5]=22;
M[1][6]=26;
M[1][7]=30;
M[1][8]=19;
M[1][9]=23;
M[1][10]=27;
M[1][11]=31;
M[1][12]=20;
M[1][13]=24;
M[1][14]=28;
M[1][15]=32;
M[2][0]=33;
M[2][1]=37;
M[2][2]=41;
M[2][3]=45;
M[2][4]=34;
M[2][5]=38;
M[2][6]=42;
M[2][7]=46;
M[2][8]=35;
M[2][9]=39;
M[2][10]=43;
M[2][11]=47;
M[2][12]=36;
M[2][13]=40;
M[2][14]=44;
M[2][15]=48;
pthread_t p_threads[T];
pthread_attr_t attr;
pthread_attr_init (&attr);
int id[T];
pthread_mutex_init(&mutexMax, 0);
pthread_mutex_init(&mutexMin, 0);
pthread_mutex_init(&mutexAvg, 0);
barrera = (barrier*)malloc(sizeof(barrier));
barrera -> count = 0;
pthread_mutex_init(&(barrera -> count_lock), 0);
pthread_cond_init(&(barrera -> ok_to_proceed), 0);
min=9999;
max=-999;
suma=0;
timetick = dwalltime();
for(i=0;i<T;i++){
id[i]=i;
pthread_create(&p_threads[i], &attr, hilar, (void *) &id[i]);
}
for(i=0;i<T;i++){
pthread_join(p_threads[i],0);
}
printf("\\nTiempo en segundos %f\\n", dwalltime() - timetick);
printMatrix(R,"R",0);
free(barrera);
free(R);
for(i=1;i<3;i++){
free(M[i]);
}
return(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t rw_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t reader_mutex = PTHREAD_MUTEX_INITIALIZER;
int num_readers = 0;
int main()
{
pthread_t subscriber_thread1;
pthread_t publisher_thread1;
void *publish();
void *subscribe();
pthread_create(&subscriber_thread1,0,subscribe,0);
pthread_create(&publisher_thread1,0,subscribe,0);
pthread_join(subscriber_thread1,0);
pthread_join(publisher_thread1,0);
}
void *subscribe()
{
struct timespec t;
int i = 0;
while (1) {
pthread_mutex_lock(&reader_mutex);
num_readers++;
if (num_readers == 1) pthread_mutex_lock(&rw_mutex);
pthread_mutex_unlock(&reader_mutex);
printf("start reading\\n");
t.tv_sec = 0;
t.tv_nsec = 1;
nanosleep (&t, 0);
printf("finish reading\\n");
pthread_mutex_lock(&reader_mutex);
num_readers--;
if (num_readers == 0) pthread_mutex_unlock(&rw_mutex);
pthread_mutex_unlock(&reader_mutex);
t.tv_sec = 0;
t.tv_nsec = i%3;
nanosleep (&t, 0);
i++;
}
pthread_exit(0);
}
void *publish()
{ int i;
struct timespec t;
for (i=0;i<100;i++) {
pthread_mutex_lock(&rw_mutex);
printf("start writing \\n");
t.tv_sec = 0;
t.tv_nsec = 1;
nanosleep (&t, 0);
printf("finish writing \\n");
pthread_mutex_unlock(&rw_mutex);
t.tv_sec = 0;
t.tv_nsec = i%2;
nanosleep (&t, 0);
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_t handles[16];
int nprimes = 0;
int lower = 0;
int biggest = 10000000;
int chunk_size = 1000;
pthread_mutex_t prime_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lower_lock = PTHREAD_MUTEX_INITIALIZER;
void * func(void* s)
{
struct subrange range;
int fd, n;
fd = *(int*)s;
while(1)
{
pthread_mutex_lock(&lower_lock);
range.min = lower;
range.max = lower + chunk_size;
lower += chunk_size;
pthread_mutex_unlock(&lower_lock);
if(range.min >= biggest)
pthread_exit(0);
write(fd, &range, sizeof range);
read(fd, &n, sizeof(int));
pthread_mutex_lock(&prime_lock);
nprimes += n;
pthread_mutex_unlock(&prime_lock);
}
}
int main(int argc, char*argv[])
{
int i, sock, nsrv = 0;
struct hostent *host_info;
struct sockaddr_in server;
int opt;
while(( opt = getopt(argc, argv, "n:c:")) != -1)
{
switch(opt)
{
case 'n':
biggest = atoi(optarg);
break;
case 'c':
chunk_size = atoi(optarg);
break;
}
}
argc -= optind;
argv += optind;
printf("biggest = %d, chunk_size = %d\\n", biggest, chunk_size);
if(argc == 0)
{
printf("no servers specified -- giving up!\\n");
exit(1);
}
for(i=0; i< argc; i++)
{
host_info = gethostbyname(argv[i]);
if(host_info == 0)
{
printf("cannot resolve %s -- ignoring\\n", argv[i]);
continue;
}
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0)
{
perror("creating stream socket");
exit(1);
}
server.sin_family = AF_INET;
memcpy(&server.sin_addr, host_info->h_addr, host_info->h_length);
server.sin_port = htons(PRIME_PORT);
if(connect(sock, (struct sockaddr*)&server, sizeof server) < 0)
{
printf("cannot connect to server %s -- ignoring\\n", argv[i]);
continue;
}
printf("connected to %s\\n", argv[i]);
pthread_create(&handles[nsrv], 0, func, &sock);
nsrv++;
}
if(nsrv == 0)
{
printf("no servers found -- giving up!\\n");
exit(3);
}
printf("using %d servers\\n", nsrv);
for(i=0; i<nsrv; i++)
{
pthread_join(handles[i], 0);
}
printf("found %d primes\\n", nprimes);
}
| 1
|
#include <pthread.h>
char *pSou_arr[THREADNUM];
char *pTar_arr[THREADNUM];
int file_size;
pthread_mutex_t lock;
pthread_cond_t cond;
void *thread_func(void *arg)
{
long num = (long)arg;
printf("child thread %ld is ready\\n", num);
pthread_mutex_lock(&lock);
pthread_cond_wait(&cond, &lock);
pthread_mutex_unlock(&lock);
if(num < THREADNUM-1)
{
memcpy(pTar_arr[num], pSou_arr[num], file_size/THREADNUM);
}
else if(num == THREADNUM -1)
{
memcpy(pTar_arr[num], pSou_arr[num], file_size - (THREADNUM-1)*(file_size/THREADNUM));
}
pthread_exit(0);
}
int main(int argc, char *argv[])
{
char sou_name[NAMELEN],tar_name[NAMELEN];
if(argc < 3)
{
printf("error args\\n");
exit(-1);
}
else
{
strcpy(sou_name, argv[1]);
strcpy(tar_name, argv[2]);
}
int ret;
struct stat sou_inf;
ret = stat(sou_name, &sou_inf);
if(-1 == ret)
{
perror("stat");
exit(-1);
}
file_size = sou_inf.st_size;
int fd_sou = open(sou_name, O_RDWR);
if(-1 == fd_sou)
{
perror("open source");
exit(-1);
}
char *pSou =0;
pSou = (char *)mmap(0, file_size, PROT_READ, MAP_SHARED, fd_sou, 0);
if((char *)-1 == pSou)
{
perror("mmap source");
exit(-1);
}
int i;
int single_size = file_size/THREADNUM;
for(i=0; i<THREADNUM; i++)
{
pSou_arr[i] = pSou + single_size*(i);
}
int fd_tar = open(tar_name, O_CREAT|O_EXCL|O_RDWR, 0664);
if(-1 == fd_tar)
{
perror("open target");
exit(-1);
}
ret = ftruncate(fd_tar, file_size);
if(-1 == ret)
{
perror("ftruncate");
exit(-1);
}
char *pTar = 0;
pTar = (char *)mmap(0, file_size, PROT_WRITE, MAP_SHARED, fd_tar, 0);
if((char *)-1 == pTar)
{
perror("mmap target");
exit(-1);
}
int j;
for(j=0; j<THREADNUM; j++)
{
pTar_arr[j] = pTar + single_size*(j);
}
long k;
pthread_t pthid[THREADNUM];
for(k=0; k<THREADNUM; k++)
{
pthread_create(&pthid[k], 0, thread_func, (void *)k);
}
pthread_mutex_init(&lock, 0);
pthread_cond_init(&cond, 0);
sleep(2);
printf("Ready?GO!\\n");
pthread_cond_broadcast(&cond);
for(k=0; k<THREADNUM; k++)
{
pthread_join(pthid[k], 0);
}
close(fd_sou);
close(fd_tar);
ret = munmap(pSou, file_size);
if(-1 == ret)
{
perror("munmap source");
exit(-1);
}
ret = munmap(pTar, file_size);
if(-1 == ret)
{
perror("munmap target");
exit(-1);
}
printf("copy success!\\n");
return 0;
}
| 0
|
#include <pthread.h>
int phylo_pop = 0;
int pyDE_pop = 0;
int pyDEwait_pop = 0;
int phylowait_pop = 0;
int sign = 0;
pthread_cond_t phylo_wait;
pthread_cond_t pyDE_wait;
pthread_mutex_t room_lock;
void phyloArrive(){
pthread_mutex_lock(&room_lock);
while (sign == 2){
phylowait_pop++;
pthread_cond_wait(&phylo_wait, &room_lock);
phylowait_pop--;
sign = 1;
}
printf("Member of phylo entered room\\n");
fflush(stdout);
phylo_pop++;
sign = 1;
pthread_mutex_unlock(&room_lock);
}
void phyloLeave(){
pthread_mutex_lock(&room_lock);
phylo_pop--;
printf("Member of phylo left room\\n");
fflush(stdout);
if (phylowait_pop > 0){
pthread_cond_signal(&phylo_wait);
}
else if (phylo_pop == 0){
sign = 0;
if (pyDEwait_pop > 0){
pthread_cond_signal(&pyDE_wait);
}
}
pthread_mutex_unlock(&room_lock);
}
void pyDEArrive(){
pthread_mutex_lock(&room_lock);
while (sign == 1){
pyDEwait_pop++;
pthread_cond_wait(&pyDE_wait, &room_lock);
pyDEwait_pop--;
sign = 2;
}
printf("Member of pyDE entered room\\n");
fflush(stdout);
pyDE_pop++;
sign = 2;
pthread_mutex_unlock(&room_lock);
}
void pyDELeave(){
pthread_mutex_lock(&room_lock);
pyDE_pop--;
printf("Member of pyDE left room\\n");
fflush(stdout);
if (pyDEwait_pop >0){
pthread_cond_signal(&pyDE_wait);
}
else if (pyDE_pop == 0){
sign = 0;
if (phylowait_pop > 0){
pthread_cond_signal(&phylo_wait);
}
}
pthread_mutex_unlock(&room_lock);
}
void *phylo(void *t){
phyloArrive();
phyloLeave();
}
void *pyDE(void *t){
pyDEArrive();
fflush(stdout);
pyDELeave();
fflush(stdout);
}
void begin(int nphylo, int npyDE){
int i;
pthread_t phyloThread[nphylo];
for (i=0; i<nphylo; i++) {
pthread_create(&phyloThread[i], 0, phylo, 0);
}
pthread_t pyDEThread[npyDE];
for (i=0; i<npyDE; i++) {
pthread_create(&pyDEThread[i], 0, pyDE, 0);
}
for (i=0; i< nphylo; i++) {
pthread_join(phyloThread[i], 0);
}
for (i=0; i<npyDE; i++) {
pthread_join(pyDEThread[i], 0);
}
}
int main(){
printf("ksjhdkjh\\n");
fflush(stdout);
pthread_mutex_init(&room_lock, 0);
pthread_cond_init(&phylo_wait, 0);
pthread_cond_init(&pyDE_wait, 0);
int phylo = 6;
int pyDE = 4;
begin(phylo, pyDE);
pthread_mutex_destroy(&room_lock);
pthread_cond_destroy(&phylo_wait);
pthread_cond_destroy(&pyDE_wait);
return 0;
}
| 1
|
#include <pthread.h>
struct YYY_Monitor {
pthread_cond_t cv;
pthread_mutex_t mutex;
};
unsigned YYY_MonitorSize(){
return sizeof(struct YYY_Monitor);
}
void YYY_InitMonitor(struct YYY_Monitor *monitor){
int err;
pthread_condattr_t cv_attr;
pthread_mutexattr_t mx_attr;
err = pthread_condattr_init(&cv_attr);
err |= pthread_mutexattr_init(&mx_attr);
assert(err==0);
err = pthread_cond_init(&(monitor->cv), &cv_attr);
err |= pthread_mutex_init(&(monitor->mutex), &mx_attr);
assert(err==0);
err = pthread_condattr_destroy(&cv_attr);
err |= pthread_mutexattr_destroy(&mx_attr);
assert(err==0);
(void)err;
}
void YYY_DestroyMonitor(struct YYY_Monitor *monitor){
int err;
err = pthread_cond_destroy(&(monitor->cv));
err |= pthread_mutex_destroy(&(monitor->mutex));
assert(err==0);
(void)err;
}
void YYY_LockMonitor(struct YYY_Monitor *monitor){
pthread_mutex_lock(&(monitor->mutex));
}
void YYY_UnlockMonitor(struct YYY_Monitor *monitor){
pthread_mutex_unlock(&(monitor->mutex));
}
void YYY_WaitMonitor(struct YYY_Monitor *monitor){
const int err = pthread_cond_wait(&(monitor->cv), &(monitor->mutex));
assert(err==0);
(void)err;
}
void YYY_NotifyMonitor(struct YYY_Monitor *monitor){
const int err = pthread_cond_signal(&(monitor->cv));
assert(err==0);
(void)err;
}
void YYY_NotifyAllMonitor(struct YYY_Monitor *monitor){
const int err = pthread_cond_broadcast(&(monitor->cv));
assert(err==0);
(void)err;
}
| 0
|
#include <pthread.h>
int gnut_mprobe(void *d)
{
return 0;
}
char *xmalloc(int size)
{
char *ptr;
ptr=malloc(size);
if (!ptr) { g_debug(0,"malloc(%d) failed!\\n", size); exit(1); }
return ptr;
}
char *expand_path(char *a)
{
char *b;
if (strncmp(a,"~/", 2)==0) {
char *c;
c=getenv("HOME");
b=(char *)xmalloc(strlen(a)+strlen(c)+1);
strcpy(b, c);
strcat(b, &a[1]);
return b;
}
b=(char *) xmalloc(strlen(a)+1);
strcpy(b,a);
return b;
}
int gnut_lib_debug=0;
pthread_mutex_t _g_debug_mutex=PTHREAD_MUTEX_INITIALIZER;
void _g_debug(char *file, int line, int num, char *format, ...)
{
va_list argp;
if (gnut_lib_debug>=num) {
pthread_mutex_lock(&_g_debug_mutex);
fprintf(stderr,"%i %s:%i > ",
getpid(),file,line);
fflush(stdout);
__builtin_va_start((argp));
vfprintf(stderr,format,argp);
;
pthread_mutex_unlock(&_g_debug_mutex);
}
}
char *gnut_strdelimit(char *string, char *delim, char new_delim)
{
char *c;
for (c=string;*c;c++) {
if (strchr(delim,*c)) *c=new_delim;
}
return string;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex_lock;
pthread_mutexattr_t attr;
pthread_cond_t cond_lock;
int cond_counter = 0;
void down(char*);
void up(char *);
void lock_init(void)
{
pthread_mutex_init(&mutex_lock, 0);
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_cond_init(&cond_lock, 0);
cond_counter = 1;
}
void down(char *buf)
{
printf("DOWN: %s\\n", buf);
pthread_mutex_lock(&mutex_lock);
while(cond_counter == 0)
pthread_cond_wait(&cond_lock, &mutex_lock);
cond_counter--;
pthread_mutex_unlock(&mutex_lock);
}
void up(char *buf)
{
pthread_mutex_lock(&mutex_lock);
cond_counter++;
pthread_mutex_unlock(&mutex_lock);
printf("UP: %s\\n", buf);
pthread_cond_signal(&cond_lock);
}
void down2(char * buf)
{
printf("DOWN: %s\\n", buf);
pthread_mutex_lock(&mutex_lock);
}
void up2(char * buf)
{
pthread_mutex_unlock(&mutex_lock);
printf("UP: %s\\n", buf);
}
void *thread_routine (void *arg)
{
int status;
down("proc_0 | thread_1");
printf("proc_0 | thread_1: lock got\\n");
sleep(5);
up("proc_0 | thread_1");
printf("proc_0 | thread_1: unlock\\n");
return 0;
}
int main (int argc, char *argv[])
{
pthread_t thread_1_to_fork;
pid_t proc_1_to_fork;
int status;
lock_init();
status = pthread_create(&thread_1_to_fork, 0, thread_routine, 0);
if(status != 0)
err_exit(status, "cant create new thread: thread_1");
if((proc_1_to_fork = fork()) < 0)
err_sys("fork error");
else if(proc_1_to_fork == 0)
{
down("proc_1 | thread_0");
printf("proc_1 | thread_0: lock got\\n");
up("proc_1 | thread_0");
printf("proc_1 | thread_0: unlock\\n");
}
else
{
down("proc_0 | thread_0");
printf("proc_0 | thread_0: lock got\\n");
up("proc_0 | thread_0");
printf("proc_0 | thread_0: unlock\\n");
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
struct msg *prev;
struct msg *next;
int num;
} *pMsg;
pMsg head;
pMsg tail;
pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void printList();
void *consumer(void *p)
{
struct msg *mp = 0;
for (;;) {
pthread_mutex_lock(&lock);
while (head == 0 && tail == 0) {
printf("head is: %p, tail is: %p\\n", head, tail);
pthread_cond_wait(&has_product, &lock);
}
mp = tail;
tail = tail->prev;
if (tail) {
tail->next = 0;
}
else
head = 0;
pthread_mutex_unlock(&lock);
printf("Consume\\t%d\\n", mp->num);
free(mp);
sleep(rand() % (5));
}
}
void *producer(void *p)
{
struct msg *mp;
for (;;) {
mp = malloc(sizeof(struct msg));
mp->num = rand() % 1000 + 1;
printf("Produce\\t%d\\n", mp->num);
pthread_mutex_lock(&lock);
mp->prev = 0;
mp->next = head;
if (tail == 0) {
tail = mp;
}
if (head)
head->prev = mp;
head = mp;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&has_product);
sleep(rand() % (5));
}
}
int main(int argc, char *argv[])
{
head = tail = 0;
pthread_t pid, cid;
srand(time(0));
pthread_create(&pid, 0, producer, 0);
pthread_create(&cid, 0, consumer, 0);
pthread_join(pid, 0);
pthread_join(cid, 0);
return 0;
}
void printList()
{
pMsg mp=0;
printf("------------List Start ----------\\n");
mp = head;
while (mp) {
printf
("element: mp - %p, mp->prev - %p, mp->num - %d, mp->next - %p;\\n",
mp, mp->prev, mp->num, mp->next);
printf("head: %p, tail: %p\\n", head, tail);
mp = mp->next;
}
printf("------------List End ----------\\n");
}
| 1
|
#include <pthread.h>
pthread_mutex_t chopsticks[5] = {PTHREAD_MUTEX_INITIALIZER};
pthread_mutex_t room = PTHREAD_MUTEX_INITIALIZER;
int room_people=0;
time_t first,second;
void think(int i)
{
usleep(2);
printf("%d am thinking!\\n", i);
}
void wait_room(int i)
{
if(room_people==4)
pthread_mutex_lock(&room);
room_people++;
printf("%d is going into the room!\\n",i);
}
void wait_cho(pthread_mutex_t t, int i)
{
pthread_mutex_lock(&t);
printf("%d is locked\\n", i);
}
void eat(int i){
sleep(2);
second = time(0);
printf("time: %f seconds",difftime(second,first));
printf("%d am eatting!\\n", i);
}
void signal_room(int i)
{
if(room_people==4)
pthread_mutex_unlock(&room);
room_people--;
printf("%d is going out from the room\\n",i);
}
void signal_cho(pthread_mutex_t t,int i){
pthread_mutex_unlock(&t);
printf("%d is unlocked\\n",i);
}
void philosopher(void* id)
{
int i = *((int*)id);
printf("i is %d\\n",i);
printf("%d philosopher_pthread creat!\\n",i);
first = time(0);
while(1){
think(i);
wait_room(i);
wait_cho(chopsticks[i],i);
wait_cho(chopsticks[(i+1)%5],(i+1)%5);
eat(i);
signal_cho(chopsticks[i],i);
signal_cho(chopsticks[(i+1)%5],(i+1)%5);
signal_room(i);
break;
}
}
int main()
{
int i;
srand(time(0));
pthread_t philosopher_ptd[5];
int id[] = {0,1,2,3,4};
for(i=0;i<5;i++){
pthread_create(&philosopher_ptd[i],0,(void *)philosopher,(void*)(&id[i]));
}
while(1){
usleep(1200);
break;
}
return 0;
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error() ;
unsigned int __VERIFIER_nondet_uint();
static int top=0;
static unsigned int arr[(800)];
pthread_mutex_t m;
_Bool flag=(0);
void error(void)
{
ERROR: __VERIFIER_error(); return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
return (top==0) ? (1) : (0);
}
int push(unsigned int *stack, int x)
{
if (top==(800))
{
printf("stack overflow\\n");
return (-1);
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (top==0)
{
printf("stack underflow\\n");
return (-2);
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for(i=0; i<(800); i++)
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint()%(800);
if ((push(arr,tmp)==(-1)))
error();
pthread_mutex_unlock(&m);
}
return 0;
}
void *t2(void *arg)
{
int i;
for(i=0; i<(800); i++)
{
pthread_mutex_lock(&m);
if (top>0)
{
if ((pop(arr)==(-2)))
error();
}
pthread_mutex_unlock(&m);
}
return 0;
}
int main(void)
{
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 1
|
#include <pthread.h>
void initializeVariables(int x, int y) {
pthread_mutexattr_t attributes;
pthread_mutexattr_init(&attributes);
pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_NORMAL);
pthread_mutex_init(&alienThreads_mutex, &attributes);
pthread_mutex_init(&bulletThreads_mutex, &attributes);
pthread_mutex_init(&player_mutex, &attributes);
p_coordX = 0;
p_coordY = 0;
alienThreads = malloc(sizeof(LList));
alienThreads->head = 0;
bulletThreads = malloc(sizeof(LList));
bulletThreads->head = 0;
int i;
bool flip = 0;
for (i = 0; i < COORD_Y; i++) {
image[i] = malloc(sizeof(char)* COORD_X);
int j;
for (j = 0; j < COORD_X; j++) {
image[i][j] = ' ';
}
}
gameOver = malloc(sizeof(bool));
*gameOver = 0;
}
void detectScreenDim(int *x, int *y) {
*x = COORD_X;
*y = COORD_Y;
}
void *screenRefresher() {
while (*gameOver != 1) {
pthread_mutex_lock(&image_mutex);
screenRefresh();
pthread_mutex_unlock(&image_mutex);
sleepTicks(1);
}
pthread_exit(0);
}
void invadersRun() {
pthread_t screenRefreshThread;
pthread_t acThread;
pthread_t pcThread;
int rc;
int screenX;
int screenY;
detectScreenDim(&screenX, &screenY);
initializeVariables(screenX, screenY);
if (!screenInit(screenY, screenX, image)) {
printf("Screen dim wrong. Exiting game.\\n");
}
rc = pthread_create(&screenRefreshThread, 0, screenRefresher, 0);
if (rc) {
printf("ERROR. Return code from invadersRun() pthread_create() is %d\\n", rc);
exit(-1);
}
rc = pthread_create(&pcThread, 0, playerControllerThread, 0);
if (rc) {
printf("ERROR. Return code from invadersRun() pthread_create() is %d\\n", rc);
exit(-1);
}
rc = pthread_create(&acThread, 0, alienControllerThread, 0);
if (rc) {
printf("ERROR. Return code from invadersRun() pthread_create() is %d\\n", rc);
exit(-1);
}
pthread_join(acThread, 0);
}
| 0
|
#include <pthread.h>
FILE *f;
char **queue;
int *lens;
int *counts;
int comp_count;
int offset = 0;
pthread_mutex_t mutex_count;
int MCSLength(char *str1, int len1, char* str2, int len2) {
int** arr = malloc(sizeof(int*)*(len1+1));
if ( arr == 0 ) {
printf("Couldn't allocate memory for the MCS array\\n");
exit(-1);
}
int i, j, local_max = 0;
for (i = 0; i <= len1; i++) {
arr[i] = calloc(len2+1, sizeof(int));
if ( arr[i] == 0 ) {
printf("Couldn't allocate memory for the MCS subarray\\n");
exit(-1);
}
}
for (i = 1; i <= len1; i++) {
for (j = 1; j <= len2; j++) {
if (str1[i-1] == str2[j-1]) {
arr[i][j] = arr[i-1][j-1] + 1;
if (arr[i][j] > local_max)
local_max = arr[i][j];
}
}
}
for (i = 0; i <= len1; i++)
free(arr[i]);
free(arr);
return local_max;
}
int readLine(char **buff, int i) {
int readchars = 0;
int commentline = 0, startedgene = 0;
int buffStepSize = 4000;
int buffSize = 4000;
buff[i] = malloc(sizeof(char)*buffSize);
char c;
do {
if (((readchars) >= buffSize) && (buffSize != 0)) {
buffSize += buffStepSize;
char* temp_buff = realloc(buff[i],sizeof(char)*buffSize);
buff[i] = temp_buff;
}
if (buff[i] == 0) {
printf("Couldn't allocate memory for the buffer\\n");
exit(-2);
}
c = fgetc(f);
switch (c) {
case '\\n':
commentline = 0;
break;
case ';':
case '>':
commentline = 1;
if (startedgene == 1) {
long curr = ftell(f);
fseek(f, curr-1, 0);
return readchars;
}
break;
default:
if ( commentline == 0 ) {
startedgene = 1;
if (c != EOF)
buff[i][readchars++] = c;
}
}
} while (c != EOF);
return readchars;
}
void *threaded_count(void* myId) {
int local_counts[8*4800/8/2];
int local_count = 0;
int startPos = ((int) myId) * (8*4800/8);
int endPos = startPos + (8*4800/8);
int i, j;
for (i = 0; i < 8*4800/8/2; i++) {
local_counts[i] = 0;
j = startPos + (i*2);
if ((lens[j] != 0) && (lens[j+1] != 0)) {
local_counts[i] = MCSLength(queue[j], lens[j], queue[j+1], lens[j+1]);
local_count++;
}
else
break;
}
pthread_mutex_lock (&mutex_count);
for (i = 0; i < 8*4800/8/2; i++) {
counts[(offset/2) + (startPos/2) + i] = local_counts[i];
}
comp_count += local_count;
pthread_mutex_unlock(&mutex_count);
return (void *) 0;
}
int main(int argc, char* argv[]) {
if (argc != 2 ) {
printf("Please specify a file on the command line\\n");
exit(-1);
}
f = fopen(argv[1],"r");
if ( f == 0 ) {
printf("Couldn't open file\\n");
exit(-1);
}
int i, rc;
pthread_t threads[8];
pthread_attr_t attr;
void *status;
do {
queue = malloc(sizeof(char*)*8*4800);
lens = calloc(sizeof(int),8*4800);
int *temp_counts = (int*) realloc(counts, (8*4800 + offset)/2 * sizeof(int));
if (( queue == 0 ) || (lens == 0) || (temp_counts == 0)) {
printf("Couldn't allocate memory for the work queues\\n");
exit(-1);
}
counts = temp_counts;
for (i = 0; i < 8*4800; i++) {
lens[i] = readLine(queue, i);
if (( queue[i] == 0 )) {
printf("Couldn't allocate memory for the work subqueues\\n");
exit(-1);
}
}
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_mutex_init(&mutex_count, 0);
for (i = 0; i < 8; i++) {
rc = pthread_create(&threads[i], &attr, threaded_count, (void *) i);
if (rc) {
printf("Error creating threads\\n");
exit(-1);
}
}
pthread_attr_destroy(&attr);
for (i = 0; i < 8; i++) {
rc = pthread_join(threads[i], &status);
if (rc) {
printf("Error Joining threads\\n");
exit(-1);
}
}
pthread_mutex_destroy(&mutex_count);
for (i = 0; i < 8*4800; i++) {
free(queue[i]);
}
free(queue);
free(lens);
offset += 8*4800;
} while (!feof(f));
unsigned long total = 0;
int longest = 0, longest_loc = -1;
for (i = 0; i < comp_count; i++) {
total += counts[i];
if (counts[i] > longest) {
longest = counts[i];
longest_loc = i;
}
}
printf("Longest LCS: %d, is the %dth pair in the file\\n", longest, longest_loc);
printf("Average: %Lf\\n",((long double) total)/comp_count);
fclose(f);
free(counts);
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
int quitflag;
sigset_t newmask,oldmask;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *
thr_func( void *arg)
{
int err;
int signo;
for (;;){
err = sigwait(&newmask,&signo);
if ( err != 0 )
return;
switch (signo){
case SIGINT:
printf("Interrupted\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&mutex);
quitflag = 1;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
sleep(2);
pthread_sigmask(0,0,&oldmask);
if (sigismember(&oldmask,SIGUSR1))
printf("mask changed in other thread also\\n");
else
printf("pthread_sigmask just changed mask in called thread\\n");
pthread_exit(0);
default:
printf("unexpected signal\\n");
exit(1);
}
}
}
int
main(void)
{
int err;
pthread_t tid;
sigemptyset(&newmask);
sigaddset(&newmask,SIGINT);
sigaddset(&newmask,SIGQUIT);
err = pthread_sigmask(SIG_BLOCK,&newmask,&oldmask);
if (err != 0)
exit(-1);
err = pthread_create(&tid,0,thr_func,0);
if (err != 0)
exit(-1);
pthread_mutex_lock(&mutex);
while ( quitflag == 0)
pthread_cond_wait(&cond,&mutex);
pthread_mutex_unlock(&mutex);
printf("wake up\\n");
quitflag = 0;
sigaddset(&newmask,SIGUSR1);
pthread_sigmask(SIG_SETMASK,&newmask,0);
pthread_sigmask(0,0,&oldmask);
if (sigismember(&oldmask,SIGUSR1))
printf("mask changed in the caller thread\\n");
sleep(5);
exit(0);
}
| 0
|
#include <pthread.h>
int ps_list_devices(struct ps_device *devices)
{
struct ps_handle handle;
int ret;
if (ps_init_handle(&handle))
return -1;
ret = ioctl(handle.fd, PS_IOC_LIST_DEVICES, devices);
ps_close_handle(&handle);
return ret;
}
int ps_init_handle(struct ps_handle *handle)
{
memset(handle, 0, sizeof(struct ps_handle));
handle->fd = open("/dev/packet_shader", O_RDWR);
if (handle->fd == -1)
return -1;
return 0;
}
void ps_close_handle(struct ps_handle *handle)
{
close(handle->fd);
handle->fd = -1;
}
int ps_attach_rx_device(struct ps_handle *handle, struct ps_queue *queue)
{
return ioctl(handle->fd, PS_IOC_ATTACH_RX_DEVICE, queue);
}
int ps_detach_rx_device(struct ps_handle *handle, struct ps_queue *queue)
{
return ioctl(handle->fd, PS_IOC_DETACH_RX_DEVICE, queue);
}
int ps_alloc_chunk(struct ps_handle *handle, struct ps_chunk *chunk)
{
memset(chunk, 0, sizeof(*chunk));
chunk->info = (struct ps_pkt_info *)malloc(
sizeof(struct ps_pkt_info) * MAX_CHUNK_SIZE);
if (!chunk->info)
return -1;
chunk->buf = (char *)mmap(0, MAX_PACKET_SIZE * MAX_CHUNK_SIZE,
PROT_READ | PROT_WRITE, MAP_SHARED,
handle->fd, 0);
if ((long)chunk->buf == -1)
return -1;
return 0;
}
void ps_free_chunk(struct ps_chunk *chunk)
{
free(chunk->info);
munmap(chunk->buf, MAX_PACKET_SIZE * MAX_CHUNK_SIZE);
chunk->info = 0;
chunk->buf = 0;
}
int ps_alloc_chunk_buf(struct ps_handle *handle,
int ifidx, int qidx, struct ps_chunk_buf *c_buf)
{
memset(c_buf, 0, sizeof(*c_buf));
c_buf->info = (struct ps_pkt_info *)malloc(
sizeof(struct ps_pkt_info) * ENTRY_CNT);
if (!c_buf->info)
return -1;
c_buf->buf = (char *)mmap(0, MAX_PACKET_SIZE * ENTRY_CNT,
PROT_READ | PROT_WRITE, MAP_SHARED,
handle->fd, 0);
if ((long)c_buf->buf == -1)
return -1;
c_buf->lock = (pthread_mutex_t *) malloc(
sizeof(pthread_mutex_t));
c_buf->queue.ifindex = ifidx;
c_buf->queue.qidx = qidx;
c_buf->cnt = 0;
c_buf->next_to_use = 0;
c_buf->next_to_send = 0;
c_buf->next_offset = 0;
if (pthread_mutex_init(c_buf->lock, 0)) {
perror("pthread_mutex_init of c_buf->lock\\n");
return -1;
}
return 0;
}
void ps_free_chunk_buf(struct ps_chunk_buf *c_buf)
{
free(c_buf->info);
munmap(c_buf->buf, MAX_PACKET_SIZE * ENTRY_CNT);
c_buf->info = 0;
c_buf->buf = 0;
}
char* ps_assign_chunk_buf(struct ps_chunk_buf *c_buf, int len) {
int w_idx;
if (c_buf->cnt >= ENTRY_CNT)
return 0;
pthread_mutex_lock(c_buf->lock);
w_idx = c_buf->next_to_use;
c_buf->cnt++;
c_buf->info[w_idx].len = len;
c_buf->info[w_idx].offset = c_buf->next_offset;
c_buf->next_offset += (len + 63) / 64 * 64;
c_buf->next_to_use = (w_idx + 1) % ENTRY_CNT;
if(c_buf->next_to_use == 0)
c_buf->next_offset = 0;
pthread_mutex_unlock(c_buf->lock);
return c_buf->buf + c_buf->info[w_idx].offset;
}
int ps_recv_chunk(struct ps_handle *handle, struct ps_chunk *chunk)
{
int cnt;
cnt = ioctl(handle->fd, PS_IOC_RECV_CHUNK, chunk);
if (cnt > 0) {
int i;
int ifindex = chunk->queue.ifindex;
handle->rx_chunks[ifindex]++;
handle->rx_packets[ifindex] += cnt;
for (i = 0; i < cnt; i++)
handle->rx_bytes[ifindex] += chunk->info[i].len;
}
return cnt;
}
int ps_recv_chunk_ifidx(struct ps_handle *handle, struct ps_chunk *chunk, int ifidx)
{
int cnt;
chunk->queue.ifindex = ifidx;
cnt = ioctl(handle->fd, PS_IOC_RECV_CHUNK_IFIDX, chunk);
if (cnt > 0) {
int i;
int ifindex = chunk->queue.ifindex;
handle->rx_chunks[ifindex]++;
handle->rx_packets[ifindex] += cnt;
for (i = 0; i < cnt; i++)
handle->rx_bytes[ifindex] += chunk->info[i].len;
}
return cnt;
}
int ps_send_chunk(struct ps_handle *handle, struct ps_chunk *chunk)
{
int cnt;
cnt = ioctl(handle->fd, PS_IOC_SEND_CHUNK, chunk);
if (cnt > 0) {
int i;
int ifindex = chunk->queue.ifindex;
handle->tx_chunks[ifindex]++;
handle->tx_packets[ifindex] += cnt;
for (i = 0; i < cnt; i++)
handle->tx_bytes[ifindex] += chunk->info[i].len;
}
return cnt;
}
int ps_send_chunk_buf(struct ps_handle *handle, struct ps_chunk_buf *c_buf)
{
int cnt;
if(c_buf->cnt <= 0)
return 0;
pthread_mutex_lock(c_buf->lock);
cnt = ioctl(handle->fd, PS_IOC_SEND_CHUNK_BUF, c_buf);
if (cnt > 0) {
int i;
int ifindex = c_buf->queue.ifindex;
handle->tx_chunks[ifindex]++;
handle->tx_packets[ifindex] += cnt;
for (i = 0; i < cnt; i++)
handle->tx_bytes[ifindex] += c_buf->info[i].len;
c_buf->cnt -= cnt;
c_buf->next_to_send = (c_buf->next_to_send + cnt) % ENTRY_CNT;
}
pthread_mutex_unlock(c_buf->lock);
return cnt;
}
int ps_select(struct ps_handle *handle, struct ps_event * event)
{
return ioctl(handle->fd, PS_IOC_SELECT, event);
}
int ps_get_txentry(struct ps_handle *handle, struct ps_queue *queue)
{
return ioctl(handle->fd, PS_IOC_GET_TXENTRY, queue);
}
int ps_slowpath_packet(struct ps_handle *handle, struct ps_packet *packet)
{
return ioctl(handle->fd, PS_IOC_SLOWPATH_PACKET, packet);
}
| 1
|
#include <pthread.h>
pthread_cond_t cond;
pthread_mutex_t mutex;
void* p_func(void* p)
{
pthread_mutex_lock(&mutex);
int ret;
printf(" i am child ,this is wait entrance\\n" );
ret=pthread_cond_wait(&cond,&mutex);
if(0!=ret)
{
printf("pthread_cond_wait ret is %d\\n" ,ret);
}
printf(" i am child thread,i am wake\\n" );
pthread_mutex_unlock(&mutex);
pthread_exit( 0);
}
int main( )
{
int ret;
ret=pthread_cond_init(&cond,0);
if( 0!=ret)
{
printf("pthread_cond_init ret is %d\\n" ,ret);
return -1;
}
ret=pthread_mutex_init(&mutex,0);
if( 0!=ret)
{
printf("pthread_mutex_init ret is %d\\n" ,ret);
return -1;
}
pthread_t thid;
pthread_create( &thid,0,p_func,0);
sleep( 1);
pthread_mutex_lock(&mutex);
printf("i am father thread,i can lock\\n" );
pthread_mutex_unlock( &mutex);
ret=pthread_join(thid,0);
if( 0!=ret)
{
printf("pthread_join ret is %d\\n" ,ret);
return -1;
}
ret=pthread_cond_destroy(&cond);
if( 0!=ret)
{
printf("pthread_cond_destroy ret is %d\\n" ,ret);
return -1;
}
ret=pthread_mutex_destroy(&mutex);
if( 0!=ret)
{
printf("pthread_mutex_destroy ret is %d\\n" ,ret);
return -1;
}
return 0;
}
| 0
|
#include <pthread.h>
int in = 0;
int out = 0;
int buff[10] = {0};
sem_t empty_sem;
sem_t full_sem;
pthread_mutex_t mutex;
int product_id = 0;
int prochase_id = 0;
void print()
{
int i;
for(i = 0; i < 10; i++)
printf("%d ", buff[i]);
printf("\\n");
}
void *product()
{
int id = ++product_id;
while(1)
{
sleep(1);
sem_wait(&empty_sem);
pthread_mutex_lock(&mutex);
in = in % 10;
printf("product%d in %d. like: \\t", id, in);
buff[in] = 1;
print();
++in;
pthread_mutex_unlock(&mutex);
sem_post(&full_sem);
}
}
void *prochase()
{
int id = ++prochase_id;
while(1)
{
sleep(1);
sem_wait(&full_sem);
pthread_mutex_lock(&mutex);
out = out % 10;
printf("prochase%d in %d. like: \\t", id, out);
buff[out] = 0;
print();
++out;
pthread_mutex_unlock(&mutex);
sem_post(&empty_sem);
}
}
int main()
{
pthread_t id1;
pthread_t id2;
int ini1 = sem_init(&empty_sem, 0, 10);
int ini2 = sem_init(&full_sem, 0, 0);
if(ini1 && ini2 != 0)
{
printf("sem init failed \\n");
exit(1);
}
int ini3 = pthread_mutex_init(&mutex, 0);
if(ini3 != 0)
{
printf("mutex init failed \\n");
exit(1);
}
if((pthread_create(&id1, 0, product, 0))!=0)
{
printf("product creation failed \\n");
exit(1);
}
if((pthread_create(&id2, 0, prochase, 0))!=0)
{
printf("prochase creation failed \\n");
exit(1);
}
sleep(2);
}
| 1
|
#include <pthread.h>
static int count = 0;
struct sockaddr_in srv_addr;
int listen_fd;
pthread_mutex_t pth_mutex = PTHREAD_MUTEX_INITIALIZER;
void * pth_handle_conn_func(void *args);
int main(void)
{
pthread_t pth[50];
bzero(&srv_addr, sizeof(struct sockaddr_in));
srv_addr.sin_family = AF_INET;
srv_addr.sin_port = htons(54929);
srv_addr.sin_addr.s_addr=INADDR_ANY;
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if(listen_fd < 0){
printf("[\\033[31mERR INFO\\033[0m]\\033[31mfunc\\033[0m: %s \\033[31mline\\033[0m: %d :""Open socket error\\n", __func__, 74);
return -1;
}
int opt = 1;
setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
if(bind(listen_fd, (struct sockaddr *)&srv_addr, sizeof(struct sockaddr)) < 0){
printf("[\\033[31mERR INFO\\033[0m]\\033[31mfunc\\033[0m: %s \\033[31mline\\033[0m: %d :""Bind error\\n", __func__, 82);
close(listen_fd);
return -1;
}
listen(listen_fd, 3);
printf("[\\033[33mDEBUG INFO\\033[0m]\\033[33mfunc\\033[0m: %s \\033[33mline\\033[0m: %d :""Now we are listenning client\\n", __func__, 88);
int i = 0;
for(; i < 50; i++){
pthread_create(&pth[i], 0, pth_handle_conn_func, 0);
}
while(1);
server_err_exit:
close(listen_fd);
pthread_mutex_destroy(&pth_mutex);
return 0;
}
void * pth_handle_conn_func(void *args)
{
char rcv_buf[7000], snd_buf[7000];
int conn_fd, ret = 0;
struct sockaddr_in cli_addr;
int addr_size, i, err_flag = 0;
while(1){
bzero(&cli_addr, sizeof(struct sockaddr_in));
addr_size = sizeof(struct sockaddr);
pthread_mutex_lock(&pth_mutex);
conn_fd = accept(listen_fd, (struct sockaddr *)&cli_addr, &addr_size);
pthread_mutex_unlock(&pth_mutex);
if(conn_fd < 0){
printf("[\\033[31mERR INFO\\033[0m]\\033[31mfunc\\033[0m: %s \\033[31mline\\033[0m: %d :""Accept error.\\n", __func__, 121);
continue;
}
i = 0;
while(1){
i++;
if(i == 20)
break;
memset(rcv_buf, 0, 7000);
if((ret = read(conn_fd, rcv_buf, 7000)) <= 0){
printf("[\\033[31mERR INFO\\033[0m]\\033[31mfunc\\033[0m: %s \\033[31mline\\033[0m: %d :""Recv info error!\\n", __func__, 133);
}
printf("[\\033[33mDEBUG INFO\\033[0m]\\033[33mfunc\\033[0m: %s \\033[33mline\\033[0m: %d :""recv info, len = %d\\n", __func__, 136, ret);
if(strcmp(rcv_buf, "OVER") == 0)
break;
}
close(conn_fd);
}
return 0;
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error() ;
int block;
int busy;
int inode;
pthread_mutex_t m_inode;
pthread_mutex_t m_busy;
void *allocator(){
pthread_mutex_lock(&m_inode);
if(inode == 0){
pthread_mutex_lock(&m_busy);
busy = 1;
pthread_mutex_unlock(&m_busy);
inode = 1;
}
block = 1;
if (!(block == 1)) ERROR: __VERIFIER_error();;
pthread_mutex_unlock(&m_inode);
return 0;
}
void *de_allocator(){
pthread_mutex_lock(&m_busy);
if(busy == 0){
block = 0;
if (!(block == 0)) ERROR: __VERIFIER_error();;
}
pthread_mutex_unlock(&m_busy);
return ((void *)0);
}
int main() {
pthread_t t1, t2;
__VERIFIER_assume(inode == busy);
pthread_mutex_init(&m_inode, 0);
pthread_mutex_init(&m_busy, 0);
pthread_create(&t1, 0, allocator, 0);
pthread_create(&t2, 0, de_allocator, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_mutex_destroy(&m_inode);
pthread_mutex_destroy(&m_busy);
return 0;
}
| 1
|
#include <pthread.h>
int table[5] = {0,0,0,0,0};
pthread_mutex_t lock;
pthread_cond_t cond_thread;
int current_cakes = 0;
void* baking_cakes(void* arg){
while(1){
if(current_cakes == 5){
printf("Mum is watching AliRaza\\n");
pthread_cond_signal(&cond_thread);
while(current_cakes > 0){
pthread_cond_wait(&cond_thread, &lock);
}
}
pthread_mutex_lock(&lock);
++current_cakes;
pthread_mutex_unlock(&lock);
printf("Mum made a cake: %d\\n", current_cakes);
sleep(1);
if(current_cakes >= 1){
pthread_cond_signal(&cond_thread);
}
pthread_mutex_unlock(&lock);
}
}
void* eating_cakes(void* arg){
while(1){
if(current_cakes < 1){
printf("Ivancho is playing outside\\n");
pthread_cond_wait(&cond_thread, &lock);
}
while(current_cakes > 0){
pthread_mutex_lock(&lock);
printf("Ivancho ate an cake: %d\\n", current_cakes);
--current_cakes;
pthread_mutex_unlock(&lock);
sleep(2);
}
if(current_cakes == 0){
pthread_cond_signal(&cond_thread);
}
}
}
int main(){
pthread_t ivancho;
pthread_t mum;
pthread_cond_init(&cond_thread, 0);
pthread_mutex_init(&lock, 0);
pthread_create(&ivancho, 0, eating_cakes, 0);
pthread_create(&mum, 0, baking_cakes, 0);
pthread_join(ivancho, 0);
pthread_join(mum, 0);
pthread_cond_destroy(&cond_thread);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex[3] = {
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER
};
int backoff = 1;
int yield_flag = 0;
void * lock_forward(void *arg)
{
int i,iterate,backoffs;
int status;
for (iterate = 0; iterate < 30;iterate++) {
backoffs = 0;
for (i = 0 ; i < 3; i++)
{
if (i == 0)
{
status = pthread_mutex_lock(&mutex[i]);
if (status != 0)
perror("pthread_mutex_lock");
printf("lock_forward lock got %d\\n",i);
}
else {
if(backoff)
status = pthread_mutex_trylock(&mutex[i]);
else
status = pthread_mutex_lock(&mutex[i]);
if (status == EBUSY) {
backoffs++;
printf("lock_forward lock back off at %d\\n",i);
for (; i >= 0; i--) {
status = pthread_mutex_unlock(&mutex[i]);
if (status != 0)
printf("backoff\\n");
}
} else {
if (status != 0)
printf("lock mutex\\n");
printf("lock_forward lock got %d\\n",i);
}
}
if (yield_flag) {
if (yield_flag > 0)
sched_yield();
else
sleep(1);
}
}
printf("lock_forward lock backward got all locks, %d backoffs\\n",backoffs);
pthread_mutex_unlock(&mutex[0]);
pthread_mutex_unlock(&mutex[1]);
pthread_mutex_unlock(&mutex[2]);
sched_yield();
}
return 0;
}
void * lock_backward(void *arg)
{
int i,iterate,backoffs;
int status;
for (iterate = 0; iterate < 30;iterate++) {
backoffs = 0;
for (i = 2 ; i >= 0; i--)
{
if (i == 2)
{
status = pthread_mutex_lock(&mutex[i]);
if (status != 0)
perror("first lock");
printf("lock_backward backward lock got %d\\n",i);
}
else {
if(backoff)
status = pthread_mutex_trylock(&mutex[i]);
else
status = pthread_mutex_lock(&mutex[i]);
if (status == EBUSY) {
backoffs++;
printf("lock_backward lock back off at %d\\n",i);
for (; i < 3; i++) {
status = pthread_mutex_unlock(&mutex[i]);
if (status != 0)
printf("backoff\\n");
}
} else {
if (status != 0)
printf("lock mutex\\n");
printf("lock_backward backward lock got %d\\n",i);
}
}
if (yield_flag) {
if (yield_flag > 0)
sched_yield();
else
sleep(1);
}
}
printf("lock_backward lock backward got all locks, %d backoffs\\n",backoffs);
pthread_mutex_unlock(&mutex[0]);
pthread_mutex_unlock(&mutex[1]);
pthread_mutex_unlock(&mutex[2]);
sched_yield();
}
return 0;
}
int main()
{
pthread_t forward,backward;
int status;
status = pthread_create(&forward,0,lock_forward,0);
status = pthread_create(&backward,0,lock_backward,0);
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
double ncircle_pts = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
double rand_double(double min, double max)
{
double scale = rand() / (double) 32767;
return min + scale * (max - min);
}
void *generate_points(void *param)
{
double x, y;
for (int i = 0; i < 1000; i++) {
x = rand_double(0, 1);
y = rand_double(0, 1);
if ((pow(x, 2) + pow(y, 2)) >= (pow(0.5, 2))){
pthread_mutex_lock(&lock);
ncircle_pts++;
pthread_mutex_unlock(&lock);
}
}
return 0;
}
int main(void)
{
pthread_t workers[20];
int i;
for(i = 0; i < 20; i++) {
pthread_create(&workers[i], 0, generate_points, 0);
}
for(i = 0; i < 20; i++) {
pthread_join(workers[i], 0);
}
printf("pi: %.2f\\n", 4 * ncircle_pts / (1000*20));
return 0;
}
| 0
|
#include <pthread.h>
struct synch_queue {
struct q_node * head;
struct q_node * tail;
pthread_mutex_t * lock;
int size;
};
struct q_node {
struct q_node * next;
void * data;
};
struct synch_queue * synch_queue_init()
{
struct synch_queue * queue = (struct synch_queue * )
malloc(sizeof(struct synch_queue));
if (!queue)
return 0;
queue->lock = malloc(sizeof(pthread_mutex_t));
if (!queue->lock) {
free(queue);
return 0;
}
pthread_mutex_init(queue->lock, 0);
queue->head = queue->tail = 0;
queue->size = 0;
return queue;
}
void synch_queue_delete(struct synch_queue * q)
{
if (!q) return;
pthread_mutex_destroy(q->lock);
free(q->lock);
}
int synch_enqueue(struct synch_queue * queue, void * data)
{
if (!queue || !data) return -1;
struct q_node * node = (struct q_node * ) malloc(sizeof(struct q_node));
if (!node) return -1;
node->data = data;
node->next = 0;
pthread_mutex_lock(queue->lock);
if (!queue->head) {
queue->head = node;
} else {
queue->tail->next = node;
}
queue->tail = node;
queue->size++;
pthread_mutex_unlock(queue->lock);
return 0;
}
void * synch_dequeue(struct synch_queue * queue)
{
void * data;
struct q_node * first;
if (!queue) return 0;
pthread_mutex_lock(queue->lock);
first = queue->head;
if (!first) {
pthread_mutex_unlock(queue->lock);
return 0;
}
queue->head = first->next;
queue->size--;
pthread_mutex_unlock(queue->lock);
data = first->data;
free(first);
return data;
}
int synch_len(struct synch_queue * q)
{
if (!q)
return 0;
int len = 0;
pthread_mutex_lock(q->lock);
len = q->size;
pthread_mutex_unlock(q->lock);
return len;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex_lock;
pthread_mutexattr_t mutexattr_lock;
pthread_t *tid;
int run = (0==0);
void END(int sig)
{
run = (0==1);
}
Boolean pthread_mutex_set(pthread_mutex_t *mutex,pthread_mutexattr_t *mutexattr)
{
Boolean rst = (0==0);
if(0 == mutex || 0 == mutexattr){
rst = (0==1);
}
if(rst && pthread_mutexattr_init(mutexattr)){
rst = (0==1);
}
if(rst && pthread_mutexattr_settype(mutexattr,PTHREAD_MUTEX_NORMAL)){
rst = (0==1);
}
if(rst && pthread_mutex_init(mutex,mutexattr)){
rst = (0==1);
}
return rst;
}
void *thfun(void *id)
{
while(run){
while(pthread_mutex_trylock(&mutex_lock)){
usleep(10);
continue;
}
printf("lock\\n");
printf("i'm %d\\n",(int *)id);
printf("other thread can't visit me\\n");
sleep(1);
pthread_mutex_unlock(&mutex_lock);
usleep(1);
}
pthread_exit(0);
return 0;
}
void test()
{
pthread_mutex_lock(&mutex_lock);
pthread_mutex_unlock(&mutex_lock);
pthread_mutexattr_destroy(&mutexattr_lock);
pthread_mutex_destroy(&mutex_lock);
return ;
}
int main()
{
int loop = 0;
void *id;
int value;
id = malloc(4);
tid = (pthread_t *)malloc(sizeof(int) * 3);
if(SIG_ERR == signal(SIGINT,END)){
return 1;
}
value = pthread_mutex_set(&mutex_lock,&mutexattr_lock);
if(!value){
return 2;
}
for(loop = 0; loop < 3; ++loop){
printf("running loop\\n");
memcpy(&id,&loop,sizeof(int));
pthread_create(&tid[loop],0,thfun,id);
}
for(loop = 0; loop < 3; ++loop){
pthread_join(tid[loop],0);
}
test();
return 0;
}
| 0
|
#include <pthread.h>
void push(struct caminfo *cam, struct imagequeue *new)
{
struct imagequeue *ptr;
int count = 0;
ptr = cam->queue;
while(ptr)
{
if(ptr->next == 0)
break;
ptr = ptr->next;
count++;
}
if(ptr)
{
ptr->next = new;
new->prev = ptr;
}
else
{
cam->queue = new;
new->prev = 0;
}
}
int clean(struct caminfo *cam)
{
struct imagequeue *ptr, *tmp;
int count = 0;
ptr = cam->queue;
while(ptr)
{
tmp = ptr->next;
pthread_mutex_lock(&ptr->lock_ref);
if(ptr->ref == 0 && ptr->id != cam->s.id_newest_img)
{
if(ptr == cam->queue)
cam->queue = tmp;
if(ptr->prev)
ptr->prev->next = ptr->next;
if(ptr->next)
ptr->next->prev = ptr->prev;
free(ptr->jpeg_data);
pthread_mutex_unlock(&ptr->lock_ref);
pthread_mutex_destroy(&ptr->lock_ref);
free(ptr);
count++;
}
else
pthread_mutex_unlock(&ptr->lock_ref);
ptr = tmp;
}
return count;
}
struct imagequeue *peek(struct caminfo *cam)
{
struct imagequeue *ptr;
int count = 0, id;
pthread_mutex_lock(&cam->lock_id);
id = cam->s.id_newest_img;
pthread_mutex_unlock(&cam->lock_id);
ptr = cam->queue;
while(ptr)
{
if(ptr->id == id)
break;
ptr = ptr->next;
count++;
}
return ptr;
}
| 1
|
#include <pthread.h>
void TunnelController()
{
northBoundCount = 0;
southBoundCount = 0;
northBound = 0;
southBound = 0;
}
void enterTunnelNorthBound(int t) {
pthread_mutex_lock(&lock);
while (southBound == 1) {
printf("Northbound Train %d must block\\n",t);
pthread_cond_wait(&self, &lock);
}
++northBoundCount;
if (northBoundCount == 1)
northBound = 1;
pthread_mutex_unlock(&lock);
}
void enterTunnelSouthBound(int t) {
pthread_mutex_lock(&lock);
while (northBound == 1) {
printf("Southbound Train %d must block\\n",t);
pthread_cond_wait(&self, &lock);
}
++southBoundCount;
if (southBoundCount == 1)
southBound = 1;
pthread_mutex_unlock(&lock);
}
void exitTunnelNorthBound(int t) {
pthread_mutex_lock(&lock);
--northBoundCount;
if (northBoundCount == 0){
northBound = 0;
printf("LAST Northbound Train gone\\n");
}
pthread_cond_broadcast(&self);
pthread_mutex_unlock(&lock);
}
void exitTunnelSouthBound(int t) {
pthread_mutex_lock(&lock);
--southBoundCount;
if (southBoundCount == 0){
southBound = 0;
printf("LAST Southbound Train gone\\n");
}
pthread_cond_broadcast(&self);
pthread_mutex_unlock(&lock);
}
| 0
|
#include <pthread.h>
static unsigned long event_get(struct usbip_device *ud)
{
unsigned long event;
pthread_mutex_lock(&ud->lock);
event = ud->event;
ud->event = 0;
pthread_mutex_unlock(&ud->lock);
return event;
}
static int event_handler(struct usbip_device *ud)
{
unsigned long event = event_get(ud);
usbip_dbg_eh("enter event_handler\\n");
usbip_dbg_eh("pending event %lx\\n", event);
if (event & USBIP_EH_SHUTDOWN)
ud->eh_ops.shutdown(ud);
if (event & USBIP_EH_RESET)
ud->eh_ops.reset(ud);
if (event & USBIP_EH_UNUSABLE)
ud->eh_ops.unusable(ud);
if (event & USBIP_EH_BYE)
return -1;
return 0;
}
static void *event_handler_loop(void *data)
{
struct usbip_device *ud = (struct usbip_device *)data;
while (!ud->eh_should_stop) {
pthread_mutex_lock(&ud->eh_waitq);
usbip_dbg_eh("wakeup\\n");
if (event_handler(ud) < 0)
break;
}
return 0;
}
int usbip_start_eh(struct usbip_device *ud)
{
pthread_mutex_init(&ud->eh_waitq, 0);
ud->eh_should_stop = 0;
ud->event = 0;
if (pthread_create(&ud->eh, 0, event_handler_loop, ud)) {
pr_warn("Unable to start control thread\\n");
return -1;
}
return 0;
}
void usbip_stop_eh(struct usbip_device *ud)
{
usbip_dbg_eh("finishing usbip_eh\\n");
ud->eh_should_stop = 1;
pthread_mutex_unlock(&ud->eh_waitq);
}
void usbip_join_eh(struct usbip_device *ud)
{
pthread_join(ud->eh, 0);
pthread_mutex_destroy(&ud->eh_waitq);
}
void usbip_event_add(struct usbip_device *ud, unsigned long event)
{
pthread_mutex_lock(&ud->lock);
ud->event |= event;
pthread_mutex_unlock(&ud->lock);
pthread_mutex_unlock(&ud->eh_waitq);
}
int usbip_event_happened(struct usbip_device *ud)
{
int happened = 0;
pthread_mutex_lock(&ud->lock);
if (ud->event != 0)
happened = 1;
pthread_mutex_unlock(&ud->lock);
return happened;
}
| 1
|
#include <pthread.h>
char *c;
pthread_mutex_t *mutex;
pthread_cond_t *cond;
} ab_arguments_t;
void *mythread(void* arguments) {
ab_arguments_t *args = (ab_arguments_t*)arguments;
pthread_mutex_lock(args->mutex);
if (args->c[0] == 'B') {
pthread_cond_wait(args->cond, args->mutex);
}
printf("%s\\n", args->c);
pthread_cond_signal(args->cond);
pthread_mutex_unlock(args->mutex);
return 0;
}
int main(int argc, char *argv[]) {
pthread_t p1, p2;
int rc;
printf("main: begin\\n");
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, 0);
pthread_cond_t cond;
pthread_cond_init(&cond, 0);
ab_arguments_t args_a = {.c = "A", .mutex = &mutex, .cond = &cond};
rc = pthread_create(&p1, 0, mythread, &args_a);
assert(rc == 0);
ab_arguments_t args_b = {.c = "B", .mutex = &mutex, .cond = &cond};
rc = pthread_create(&p2, 0, mythread, &args_b);
assert(rc == 0);
rc = pthread_join(p1, 0); assert(rc == 0);
rc = pthread_join(p2, 0); assert(rc == 0);
printf("main: end\\n");
return 0;
}
| 0
|
#include <pthread.h>
static INITIALIZE_PARSER pf_initialize_parser = 0;
static RELEASE_PARSER pf_release_parser = 0;
static PARSER_CONTROL_EVENT pf_parse_control_event = 0;
static PARSER_SERIAL_RECV pf_parse_serial_recv = 0;
static PARSER_CONNECT_RECV pf_parse_connect_recv = 0;
static void *g_hLibrary = 0;
static char *g_dl_filename = 0;
static pthread_mutex_t lib_mutex = PTHREAD_MUTEX_INITIALIZER;
static void ui_library_lock()
{
pthread_mutex_lock(&lib_mutex);
}
static void ui_library_unlock()
{
pthread_mutex_unlock(&lib_mutex);
}
static int save_dl_filename(const char *ui_event_so_filename)
{
int len = strlen(ui_event_so_filename);
if(!ui_event_so_filename || len <= 0)
{
CCC_LOG_OUT("save_dl_filename() invalid filename\\n");
return 0;
}
if(g_dl_filename) free(g_dl_filename);
g_dl_filename = (char *)malloc(len + 1 + 10);
if(!g_dl_filename)
{
CCC_LOG_OUT("save_dl_filename() malloc error\\n");
return 0;
}
sprintf(g_dl_filename, "./%s", ui_event_so_filename);
return 1;
}
static int check_loadlib_error()
{
char *error;
if ((error = dlerror()) != 0)
{
CCC_LOG_OUT("%s check_loadlib_error : %s\\n", g_dl_filename, error);
return 0;
}
return 1;
}
static int load_ui_library(const char *ui_event_so_filename)
{
g_hLibrary = 0;
if(!save_dl_filename(ui_event_so_filename))
return 0;
g_hLibrary = dlopen(g_dl_filename, RTLD_LAZY);
if(0 == g_hLibrary)
{
CCC_LOG_OUT("%s dlopen error.\\n %s \\n", g_dl_filename, dlerror());
return 0;
}
pf_parse_serial_recv = dlsym(g_hLibrary, "dealwithSerialportData");
if (0 == pf_parse_serial_recv){if (!check_loadlib_error()) return 0;}
pf_initialize_parser = dlsym(g_hLibrary, "InitializeControls");
if (0 == pf_initialize_parser){if (!check_loadlib_error()) return 0;}
pf_release_parser = dlsym(g_hLibrary, "ReleaseControls");
if (0 == pf_release_parser){if (!check_loadlib_error()) return 0;}
pf_parse_control_event = dlsym(g_hLibrary, "ProcessEvent");
if (0 == pf_parse_control_event){if (!check_loadlib_error()) return 0;}
CCC_LOG_OUT("load library %s success\\n", g_dl_filename);
return 1;
}
static int interval_initialize_parser()
{
if(!pf_initialize_parser)
{
CCC_LOG_OUT("pf_initialize_parser = NULL\\n");
return 0;
}
if(pf_initialize_parser() != 0)
{
CCC_LOG_OUT("initialize_parser error\\n");
return 0;
}
return 1;
}
static int interval_release_parser()
{
if(!pf_release_parser)
{
CCC_LOG_OUT("pf_release_parser = NULL\\n");
return 0;
}
if(pf_release_parser() != 0)
{
CCC_LOG_OUT("release_parser error\\n");
return 0;
}
return 1;
}
static int unload_ui_library()
{
pf_parse_control_event = 0;
pf_parse_serial_recv = 0;
pf_release_parser = 0;
pf_initialize_parser = 0;
if(g_hLibrary)
{
while(dlclose(g_hLibrary));
g_hLibrary = 0;
CCC_LOG_OUT("unload %s success\\n", g_dl_filename);
if(g_dl_filename)
{
free(g_dl_filename);
g_dl_filename = 0;
}
}
return 1;
}
static int interval_parse_control_event(int senderId, int event, char *data, int dataLen)
{
if(!pf_parse_control_event)
{
CCC_LOG_OUT("pf_parse_control_event = NULL\\n");
return 0;
}
if(pf_parse_control_event(senderId, event, data, dataLen) != 0)
{
CCC_LOG_OUT("parse_control_event error\\n");
return 0;
}
return 1;
}
static int interval_parse_serial_recv(int serial_no, unsigned char *data, int dataLen)
{
if(!pf_parse_serial_recv)
{
CCC_LOG_OUT("pf_parse_serial_recv = NULL\\n");
return 0;
}
if(pf_parse_serial_recv(serial_no, data, dataLen) != 0)
{
CCC_LOG_OUT("parse_serial_recv error\\n");
return 0;
}
return 1;
}
static int interval_parse_connect_recv(int controlId, unsigned char *data, int dataLen)
{
if(!pf_parse_connect_recv)
{
CCC_LOG_OUT("pf_parse_connect_recv = NULL\\n");
return 0;
}
if(pf_parse_connect_recv(controlId, data, dataLen) != 0)
{
CCC_LOG_OUT("parse_connect_recv error\\n");
return 0;
}
return 1;
}
int parse_connect_recv(int controlId, unsigned char *data, int dataLen)
{
int result;
ui_library_lock();
result = interval_parse_connect_recv(controlId, data, dataLen);
ui_library_unlock();
return result;
}
int parse_serial_recv(int serial_no, unsigned char *data, int dataLen)
{
int result;
ui_library_lock();
result = interval_parse_serial_recv(serial_no, data, dataLen);
ui_library_unlock();
return result;
}
int parse_control_event(int senderId, int event, char *data, int dataLen)
{
int result;
ui_library_lock();
result = interval_parse_control_event(senderId, event, data, dataLen);
ui_library_unlock();
return result;
}
int initialize_ui_library(const char *ui_event_so_filename)
{
ui_library_lock();
if(!load_ui_library(ui_event_so_filename))
{
ui_library_unlock();
CCC_LOG_OUT("load_ui_library() %s error\\n", ui_event_so_filename);
return 0;
}
if(!interval_initialize_parser())
{
ui_library_unlock();
return 0;
}
ui_library_unlock();
return 1;
}
int release_ui_library()
{
ui_library_lock();
if(!interval_release_parser())
{
ui_library_unlock();
return 0;
}
if(!unload_ui_library())
{
ui_library_unlock();
return 0;
}
ui_library_unlock();
return 1;
}
| 1
|
#include <pthread.h>
int bucket;
struct chunk_t *next;
} chunk_t;
static int is_init;
static pthread_mutex_t mem_lock;
static int alloc = 0;
static chunk_t *buckets[256];
static int
get_bucket(int size)
{
size += sizeof(chunk_t);
if (size <= 65536)
return (size + 255) / 256;
else
return -1;
}
static int
get_chunk_size(int size)
{
if (size + sizeof(chunk_t) < 65536)
return 256 * ((size + sizeof(chunk_t) + 255) / 256);
else
return 0;
}
static void
cse_init_bucket(int size, int alloc_size)
{
char *data;
int bucket = get_bucket(size);
int chunk_size = get_chunk_size(size);
int i;
if (bucket < 0) {
fprintf(stderr, "illegal call to cse_init_bucket size=%d\\n", size);
return;
}
data = malloc(alloc_size);
bucket = get_bucket(size);
chunk_size = get_chunk_size(size);
if (bucket >= 1024)
fprintf(stderr, "bad bucket size:%d bucket:%d\\n", size, bucket);
for (i = 0; i < alloc_size; i += chunk_size) {
chunk_t *chunk = (chunk_t *) (data + i);
chunk->bucket = bucket;
chunk->next = buckets[bucket];
buckets[bucket] = chunk;
}
}
void *
cse_malloc(int size)
{
int bucket;
chunk_t *chunk = 0;
void *data;
bucket = get_bucket(size);
if (bucket < 0) {
chunk = (chunk_t *) malloc(size + sizeof(chunk_t));
chunk->bucket = -1;
data = ((char *) chunk) + sizeof(chunk_t);
return data;
}
pthread_mutex_lock(&mem_lock);
chunk = buckets[bucket];
if (chunk)
buckets[bucket] = chunk->next;
pthread_mutex_unlock(&mem_lock);
if (chunk) {
}
else if (size + sizeof(chunk_t) <= 4096) {
pthread_mutex_lock(&mem_lock);
cse_init_bucket(size, 65536);
chunk = buckets[bucket];
buckets[bucket] = chunk->next;
pthread_mutex_unlock(&mem_lock);
}
else {
chunk = (chunk_t *) malloc(get_chunk_size(size));
if (chunk == 0)
return 0;
chunk->bucket = bucket;
}
chunk->next = 0;
data = ((char *) chunk) + sizeof(chunk_t);
return data;
}
void
cse_free(void *v_data)
{
chunk_t *chunk = (chunk_t *) (((char *) v_data) - sizeof(chunk_t));
int bucket = chunk->bucket;
if (bucket == -1) {
free(chunk);
}
else if (bucket < 256) {
pthread_mutex_lock(&mem_lock);
chunk->next = buckets[bucket];
buckets[bucket] = chunk;
pthread_mutex_unlock(&mem_lock);
}
else
fprintf(stderr, "no bucket\\n");
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error() ;
static int iTThreads = 2;
static int iRThreads = 1;
static int data1Value = 0;
static int data2Value = 0;
pthread_mutex_t *data1Lock;
pthread_mutex_t *data2Lock;
void lock(pthread_mutex_t *);
void unlock(pthread_mutex_t *);
void *funcA(void *param) {
pthread_mutex_lock(data1Lock);
data1Value = 1;
pthread_mutex_unlock(data1Lock);
pthread_mutex_lock(data2Lock);
data2Value = data1Value + 1;
pthread_mutex_unlock(data2Lock);
return 0;
}
void *funcB(void *param) {
int t1 = -1;
int t2 = -1;
pthread_mutex_lock(data1Lock);
if (data1Value == 0) {
pthread_mutex_unlock(data1Lock);
return 0;
}
t1 = data1Value;
pthread_mutex_unlock(data1Lock);
pthread_mutex_lock(data2Lock);
t2 = data2Value;
pthread_mutex_unlock(data2Lock);
if (t2 != (t1 + 1)) {
fprintf(stderr, "Bug found!\\n");
ERROR:
__VERIFIER_error();
;
}
return 0;
}
int main(int argc, char *argv[]) {
int i,err;
if (
argc != 1) {
if (argc != 3) {
fprintf(stderr, "./twostage <param1> <param2>\\n");
exit(-1);
} else {
sscanf(argv[1], "%d", &iTThreads);
sscanf(argv[2], "%d", &iRThreads);
}
}
data1Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
data2Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
if (0 != (err = pthread_mutex_init(data1Lock, 0))) {
fprintf(stderr, "pthread_mutex_init error: %d\\n", err);
exit(-1);
}
if (0 != (err = pthread_mutex_init(data2Lock, 0))) {
fprintf(stderr, "pthread_mutex_init error: %d\\n", err);
exit(-1);
}
pthread_t tPool[iTThreads];
pthread_t rPool[iRThreads];
for (
i = 0; i < iTThreads; i++) {
if (0 != (err = pthread_create(&tPool[i], 0, &funcA, 0))) {
fprintf(stderr, "Error [%d] found creating 2stage thread.\\n", err);
exit(-1);
}
}
for (
i = 0; i < iRThreads; i++) {
if (0 != (err = pthread_create(&rPool[i], 0, &funcB, 0))) {
fprintf(stderr, "Error [%d] found creating read thread.\\n", err);
exit(-1);
}
}
for (
i = 0; i < iTThreads; i++) {
if (0 != (err = pthread_join(tPool[i], 0))) {
fprintf(stderr, "pthread join error: %d\\n", err);
exit(-1);
}
}
for (
i = 0; i < iRThreads; i++) {
if (0 != (err = pthread_join(rPool[i], 0))) {
fprintf(stderr, "pthread join error: %d\\n", err);
exit(-1);
}
}
return 0;
}
void lock(pthread_mutex_t *lock) {
int err;
if (0 != (err = pthread_mutex_lock(lock))) {
fprintf(stderr, "Got error %d from pthread_mutex_lock.\\n", err);
exit(-1);
}
}
void unlock(pthread_mutex_t *lock) {
int err;
if (0 != (err = pthread_mutex_unlock(lock))) {
fprintf(stderr, "Got error %d from pthread_mutex_unlock.\\n", err);
exit(-1);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
const char *msg = "Hello World";
{
char *data;
int len;
}pthread_data_t;
pthread_data_t d;
static void *thread_wait( void *argv)
{
printf("%s - start\\n", __func__);
pthread_mutex_lock(&mutex);
while(strlen(d.data) > 0)
if(pthread_cond_wait(&cond, &mutex) != 0)
break;
printf("%s - continue\\n", __func__);
pthread_mutex_unlock(&mutex);
return 0;
}
static void *thread_run( void *argv)
{
printf("%s - start\\n", __func__);
pthread_mutex_lock(&mutex);
while(d.len > 0)
{
d.len--;
printf("d.data[%d]\\t= %c\\n", d.len, d.data[d.len]);
d.data[d.len] = '\\0';
sleep(1);
}
printf("%s - signal\\n", __func__);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
return 0;
}
void free_data()
{
free(d.data);
}
int main(void)
{
printf("%s - start\\n", __func__);
int data_len = strlen(msg);
if((d.data = (char *)calloc(data_len + 1, sizeof(*d.data))) == 0)
err(1, 0);
strcpy(d.data, msg);
d.len = data_len;
pthread_t thread[2];
if(pthread_create(&thread[0], 0, thread_wait, 0) != 0)
goto failure;
if(pthread_create(&thread[1], 0, thread_run, 0) != 0)
goto failure;
for(int i=0; i<2; i++)
if(pthread_join(thread[i], 0) != 0)
goto failure;
printf("%s - continue\\n", __func__);
free_data();
return 0;
failure:
free_data();
err(1, 0);
}
| 0
|
#include <pthread.h>
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t cond_mutex = PTHREAD_MUTEX_INITIALIZER;
int cond_var=0;
void *hilo_dispara(void *data)
{
while(1) {
pthread_mutex_lock(&cond_mutex);
cond_var++;
pthread_mutex_unlock(&cond_mutex);
pthread_cond_signal(&cond);
fprintf(stderr, "TICK: cond_var=%d -> ", cond_var);
usleep(1000000/5);
}
return 0;
}
void *hilo_espera(void *data)
{
pthread_mutex_lock(&cond_mutex);
while (cond_var < 10) {
fprintf(stderr, ".\\n");
pthread_cond_wait(&cond, &cond_mutex);
}
pthread_mutex_unlock(&cond_mutex);
fprintf(stderr, "LISTO\\n");
return 0;
}
int main(void) {
pthread_t tid_espera, tid_dispara;
pthread_create ( &tid_espera, 0, hilo_espera, 0);
pthread_create ( &tid_dispara, 0, hilo_dispara, 0);
pthread_join ( tid_espera, 0);
return 0;
}
| 1
|
#include <pthread.h>
sem_t block;
sem_t CountNum;
pthread_mutex_t mutex;
pthread_mutex_t mutex1;
int Count[64];
void *Con_Run(void *arg)
{
static int i=0;
while(1)
{
sleep(1);
pthread_mutex_lock(&mutex);
sem_wait(&CountNum);
printf("Con::%d\\n",Count[i]);
i++;
i%=64;
sem_post(&block);
pthread_mutex_unlock(&mutex);
}
}
void *Pro_Run(void *arg)
{
static int i=0;
while(1)
{
sleep(2);
pthread_mutex_lock(&mutex1);
sem_wait(&block);
int Data = rand()%45;
Count[i++]=Data;
printf("PRO::%d\\n",Data);
i%=64;
sem_post(&CountNum);
pthread_mutex_unlock(&mutex1);
}
}
int main()
{
sem_init(&CountNum,0,0);
sem_init(&block,0,64);
pthread_t Pro_1;
pthread_t Pro;
pthread_t Con;
pthread_t Con_1;
pthread_create(&Pro_1,0,Pro_Run,0);
pthread_create(&Pro,0,Pro_Run,0);
pthread_create(&Con_1,0,Con_Run,0);
pthread_create(&Con,0,Con_Run,0);
pthread_join(Pro_1,0);
pthread_join(Con_1,0);
pthread_join(Pro,0);
pthread_join(Con,0);
sem_destroy(&block);
sem_destroy(&CountNum);
return 0;
}
| 0
|
#include <pthread.h>
static inline char receive_byte(void){
char gps_date = '\\0';
if(read(BDfd,&gps_date,1) == -1)
perror("Read Error:");
return gps_date;
}
inline void gps_receive(void)
{
char c,gps_type;
int i =0,j=0;
int timeout =30;
int obdtime = 0;
int sum = 0,gps_flag = 0;
char buf[128] = "",buff[128] = "";
char str[256] = "";
while(1){
if(sum > 255)
sum = 0;
c = receive_byte();
buf[sum++] = c;
switch(gps_flag){
case 0:
if(buf[0] == '$')
gps_flag = 1;
else
sum = 0;
break;
case 1:
if (sum == 7)
{
if(!strncmp(buf,"$GNRMC,",7))
gps_flag = 2,gps_type = 0;
else
gps_flag = 0,sum = 0,gps_type = 0;
}
break;
case 2:
buff[sum - 8] = c;
if(c == '\\n')
{
sum = 0;
gps_flag = 0;
printf("%s",buff);
printf("timeout=%d\\n",timeout);
printf("obdtime=%d\\n",obdtime);
if(timeout == TIMEOUT)
{
pthread_mutex_lock(&mtx);
thread_flag = 0;
pthread_mutex_unlock(&mtx);
command_80(buff,&timeout);
}
else if(buff[10] == 'V')
{
j++;
printf("j=%d\\n",j);
if(j > 350)
{ j=0;
td3020c_power_on();
}
}
else if(obdtime > 150)
{
obdtime = 0;
}
else if (obdtime == (OBDTIME - 87))
{
command_B3();
usleep(800);
command_B4();
usleep(800);
command_B7();
}
else if (obdtime == (OBDTIME - 55))
{
command_B5();
usleep(800);
command_B6();
usleep(800);
command_B9();
}
else if (obdtime == (OBDTIME-3))
{
command_B0();
usleep(800);
command_B1();
usleep(800);
command_B2();
usleep(800);
command_B8();
usleep(800);
command_C0();
usleep(800);
command_C1();
usleep(800);
command_C2();
usleep(800);
command_C3();
usleep(800);
command_A7();
obdtime = 0;
}
if(fcntl(gprs_fd,F_SETFL,FNDELAY) < 0)
{
printf("fcntl fatil \\n");
}
i = read(gprs_fd, str, 256);
if(i < 0)
{
printf("%d\\n",145);
perror("read");
}
if(fcntl(gprs_fd,F_SETFL,0) < 0)
{
printf("fcntl fatil \\n");
}
printf("%dstr=%s\\n",152,str);
memset(buf,0,sizeof(buf));
memset(buff,0,sizeof(buff));
memset(str,0,sizeof(str));
timeout++;
obdtime++;
}
break;
default:
break;
}
}
}
| 1
|
#include <pthread.h>
static pthread_t threadTickGenerator;
static pthread_t threadFIFO2DA[MAX_CHANNEL];
static pthread_mutex_t mutexTick[MAX_CHANNEL];
static pthread_cond_t condTick[MAX_CHANNEL];
int readAChar( int fifoFD )
{
char aChar;
int err = read( fifoFD , &aChar , 1);
if ( err < 0 )
{
perror("read");
return -1;
}
else if ( err == 0 )
{
sleep(1);
return -2;
}
return (int)aChar;
}
void waitTick( int Channel )
{
pthread_mutex_lock( &mutexTick[Channel] );
pthread_cond_wait( &condTick[Channel] , &mutexTick[Channel] );
pthread_mutex_unlock( &mutexTick[Channel] );
}
void *functionTickGenerator( void *param )
{
int Channel;
for( Channel=0 ;Channel<MAX_CHANNEL;Channel++)
{
pthread_mutex_init( &mutexTick[Channel] , 0 );
pthread_cond_init( &condTick[Channel] , 0 );
}
while(1)
{
double lastTick;
double presentTick;
struct timeval tv;
struct timezone tz;
gettimeofday( &tv , &tz );
presentTick=tv.tv_sec+tv.tv_usec*0.000001;
lastTick=presentTick;
for( Channel=0 ;Channel<MAX_CHANNEL;Channel++)
{
pthread_mutex_lock( &mutexTick[Channel] );
pthread_cond_signal( &condTick[Channel] );
pthread_mutex_unlock( &mutexTick[Channel] );
}
struct timespec remainTime;
bzero( &remainTime , sizeof(struct timespec) );
while(1)
{
struct timespec sleepTime;
sleepTime.tv_nsec=40*1000000;
sleepTime.tv_sec=0;
if ( nanosleep(&sleepTime , &remainTime ) == 0 )
break;
}
}
}
void *functionFIFO2DA( void *param )
{
char stringFIFO[32];
int fifoFD;
int channel=(int)param;
pthread_detach( pthread_self() );
sprintf( stringFIFO , "/tmp/FIFO_CHANNEL%d" , channel );
fifoFD = open( stringFIFO , O_RDONLY );
if ( fifoFD < 0 )
{
printf_error("open %s error , try to create\\n" , stringFIFO );
perror("open");
if ( mkfifo( stringFIFO , 0777 ) )
{
printf_error("create %s error , exit\\n" , stringFIFO );
perror("mkfifo");
goto threadError;
}
}
while(1)
{
char readBuffer[512*1024];
char *walkInBuffer=readBuffer;
int readSize;
int stringIndex;
int readInt;
char *toNullPos;
readSize = read( fifoFD , readBuffer , sizeof(readBuffer));
if ( readSize <=0 )
{
struct timespec remainTime;
struct timespec sleepTime;
sleepTime.tv_nsec=40*100000;
sleepTime.tv_sec=0;
nanosleep( &sleepTime , &remainTime );
continue;
}
if ( debug ) printf( "ch%d:" , channel );
do
{
toNullPos = strchr( walkInBuffer , ',');
if ( toNullPos )
*toNullPos=0;
stringIndex=sscanf( walkInBuffer , "0x%x" , &readInt );
if ( stringIndex == 0 )
{
stringIndex=sscanf( walkInBuffer , "%d" , &readInt );
if ( stringIndex == 0 )
{
printf_error("an invalid number %s\\n" , walkInBuffer );
if ( toNullPos )
{
walkInBuffer=toNullPos+1;
continue;
}
else
break;
}
}
writeDAC( channel , readInt );
waitTick( channel );
if ( toNullPos )
walkInBuffer=toNullPos+1;
else
break;
}while( strlen(walkInBuffer) );
if ( debug ) printf( "\\n" );
}
threadError:
printf( "Channel %d exit\\n" , channel );
return 0;
}
static const int maxValue[MAX_CHANNEL]={
120,
240,
60,
30,
30,
30
};
int cpap2psg( int rs232_descriptor , char *cmdBuffer , int cmdSize , char checkedXor )
{
int expectedLength=5;
if ( sendCPAPCmd( rs232_descriptor , cmdBuffer , cmdSize , checkedXor ) )
return -1;
unsigned char responseBuffer[1024];
int responseSize;
responseSize = recvCPAPResponse( rs232_descriptor , responseBuffer , sizeof(responseBuffer) , expectedLength );
if ( responseSize < 0 )
{
return responseSize;
}
int adjustedValue;
adjustedValue = (65535.0/maxValue[0])*responseBuffer[2];
printf_debug( "cpap:%d -> da:%d\\n" , responseBuffer[2] , adjustedValue );
writeDAC( 0 , adjustedValue );
return 0;
}
int debug=0;
int main( int argc , char **argv )
{
if ( access( "/etc/debug" , 0 ) == 0 )
debug=1;
int rs232_descriptor;
char cmdBuffer[2]={ 0x93,0xCB };
int cmdSize=sizeof(cmdBuffer);
int checkedXor;
initDAC();
int deviceDesc;
deviceDesc = openCPAPDevice();
checkedXor = getCheckedXor( cmdBuffer , cmdSize );
pthread_create( &threadTickGenerator , 0 , functionTickGenerator , 0 );
while(1)
{
int err=cpap2psg( deviceDesc , cmdBuffer , cmdSize , checkedXor );
if ( err == -2 )
{
deviceDesc = openCPAPDevice();
}
sleep(1);
int channel;
for( channel=0 ; channel<MAX_CHANNEL ; channel++ )
{
if ( threadFIFO2DA[channel] == 0 )
pthread_create( &threadFIFO2DA[channel] ,0 , functionFIFO2DA , (void *)channel );
}
}
rs232_close( rs232_descriptor );
return 0;
}
| 0
|
#include <pthread.h>
volatile int cat_plays,dog_plays,bird_plays,cats,dogs,birds,n_cats,n_dogs,n_birds;
volatile int err;
struct monitor
{
pthread_mutex_t mutex;
pthread_cond_t is_occupied_cat;
pthread_cond_t is_occupied_dog;
pthread_cond_t is_occupied_bird;
};
MONITOR *monitorObj;
void cat_enter(void)
{
err=pthread_mutex_lock(&monitorObj->mutex);
if(err)
printf("Failed in mutex lock");
while(dogs>0 || birds>0)
{
err=pthread_cond_wait(&monitorObj->is_occupied_cat, &monitorObj->mutex);
if(err)
printf("Failed in cond wait");
};
cats++;
err=pthread_mutex_unlock(&monitorObj->mutex);
if(err)
printf("Failed in mutex unlock");
}
void cat_exit(void)
{
err=pthread_mutex_lock(&monitorObj->mutex);
if(err)
printf("Failed in mutex lock");
err=pthread_cond_signal(&monitorObj->is_occupied_cat);
if(err)
printf("Failed in cond signal");
cats--;
err=pthread_mutex_unlock(&monitorObj->mutex);
if(err)
printf("Failed in mutex unlock");
}
void dog_enter(void)
{
pthread_mutex_lock(&monitorObj->mutex);
while(cats>0)
{
pthread_cond_wait(&monitorObj->is_occupied_dog, &monitorObj->mutex);
};
dogs++;
pthread_mutex_unlock(&monitorObj->mutex);
}
void dog_exit(void)
{
pthread_mutex_lock(&monitorObj->mutex);
pthread_cond_signal(&monitorObj->is_occupied_dog);
dogs--;
pthread_mutex_unlock(&monitorObj->mutex);
}
void bird_enter(void)
{
pthread_mutex_lock(&monitorObj->mutex);
while(cats>0)
{
pthread_cond_wait(&monitorObj->is_occupied_bird, &monitorObj->mutex);
}
birds++;
pthread_mutex_unlock(&monitorObj->mutex);
}
void bird_exit(void)
{
pthread_mutex_lock(&monitorObj->mutex);
pthread_cond_signal(&monitorObj->is_occupied_bird);
birds--;
pthread_mutex_unlock(&monitorObj->mutex);
}
void play(void) {
for (int i=0; i<10; i++) {
assert(cats >= 0 && cats <= n_cats);
assert(dogs >= 0 && dogs <= n_dogs);
assert(birds >= 0 && birds <= n_birds);
assert(cats == 0 || dogs == 0);
assert(cats == 0 || birds == 0);
}
}
void * catThread(void * threadId)
{
while(1)
{
cat_enter();
cat_plays=cat_plays+1;
play();
cat_exit();
}
exit(0);
}
void * dogThread(void * threadId)
{
while(1)
{
dog_enter();
dog_plays=dog_plays+1;
play();
dog_exit();
}
exit(0);
}
void * birdThread(void * threadId)
{
while(1)
{
bird_enter();
bird_plays=bird_plays+1;
play();
bird_exit();
}
exit(0);
}
int main(int argc, char* argv[])
{
if(argc!=4)
{
printf("Invalid number of arguments.");
return -1;
}
printf("Cats = %s, Dogs = %s, Birds = %s", argv[1], argv[2], argv[3]);
n_cats=atoi(argv[1]);
n_dogs=atoi(argv[2]);
n_birds=atoi(argv[3]);
int flag;
long i;
dog_plays=0;
cat_plays=0;
bird_plays=0;
cats=0;
birds=0;
dogs=0;
monitorObj= (MONITOR *) malloc(sizeof(MONITOR));
pthread_mutex_init(&monitorObj->mutex, 0);
pthread_cond_init(&monitorObj->is_occupied_cat, 0);
pthread_cond_init(&monitorObj->is_occupied_dog, 0);
pthread_cond_init(&monitorObj->is_occupied_bird, 0);
pthread_t *catThreads, *dogThreads, *birdThreads;
catThreads=(pthread_t*) malloc(sizeof(pthread_t) * n_cats);
dogThreads=(pthread_t*) malloc(sizeof(pthread_t) * n_dogs);
birdThreads=(pthread_t*) malloc(sizeof(pthread_t) * n_birds);
for(i=0;i<n_cats;i++)
{
flag=pthread_create(&catThreads[i], 0, catThread,(void *)i);
if(flag)
{
printf("Error creating a thread.");
return -1;
}
}
for(i=0;i<n_dogs;i++)
{
flag=pthread_create(&dogThreads[i], 0, dogThread,(void *)i);
if(flag)
{
printf("Error creating a thread.");
return -1;
}
}
for(i=0;i<n_birds;i++)
{
flag=pthread_create(&birdThreads[i], 0, birdThread,(void *)i);
if(flag)
{
printf("Error creating a thread.");
return -1;
}
}
flag=usleep(1000000);
if(flag)
{
printf("\\n Failed in usleep");
return -1;
}
printf("\\nCat Plays = %d\\nDog Plays = %d\\nBird Plays = %d",cat_plays,dog_plays,bird_plays);
pthread_mutex_destroy(&monitorObj->mutex);
pthread_cond_destroy(&monitorObj->is_occupied_cat);
pthread_cond_destroy(&monitorObj->is_occupied_dog);
pthread_cond_destroy(&monitorObj->is_occupied_bird);
free(catThreads);
free(dogThreads);
free(birdThreads);
}
| 1
|
#include <pthread.h>
int get_id(void)
{
static int id = 59000;
int current_id = 0;
pthread_mutex_lock(&globals->id_lock);
current_id = id++;
pthread_mutex_unlock(&globals->id_lock);
return (current_id);
}
| 0
|
#include <pthread.h>
int row, col,total_threads;
double* mat;
double* vec;
double* result;
pthread_mutex_t pthread;
void *matrix_multiplication(void* rank) {
double t;
long local_rank = (long) rank;
int sz = row/total_threads;
int z=local_rank*sz*col;
int start_i = local_rank*sz;
int end_i = start_i + sz - 1;
pthread_mutex_lock(&pthread);
for (int i = start_i; i <= end_i; i++) {
t = 0.0;
for (int j = 0; j < col; j++){
t += mat[z++]*vec[j];
}
result[i]=t;
}
pthread_mutex_unlock(&pthread);
return 0;
}
int main(int argc, char* argv[]) {
long th;
pthread_t* thread_handles;
total_threads = strtol(argv[1], 0, 10);
thread_handles = malloc(total_threads*sizeof(pthread_t));
printf("Enter matrix size \\n");
scanf("%d%d", &row, &col);
vec = malloc(sizeof(double)*col);
result = malloc(sizeof(double)*row);
mat = malloc(sizeof(double)*row*col);
printf("Enter Matrix Elements\\n");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
scanf("%lf", &mat[i*col+j]);
}
}
printf("Enter Vector Elements\\n");
for (int i = 0; i < col; i++) {
scanf("%lf", &vec[i]);
}
printf("Matix Elements\\n");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++){
printf("%2.1f ", mat[i*col + j]);
}
printf("\\n");
}
printf("Vector Elements\\n");
for (int i = 0; i < col; i++){
printf("%2.5f\\n", vec[i]);
}
printf("\\n");
pthread_mutex_init(&pthread, 0);
for (th = 0; th < total_threads; th++)
{
pthread_create(&thread_handles[th], 0, matrix_multiplication, (void*) th);
}
for (th = 0; th < total_threads; th++)
{
pthread_join(thread_handles[th], 0);
}
printf("Result\\n");
for (int i = 0; i < col; i++){
printf("%2.5f\\n", result[i]);
}
printf("\\n");
free(mat);
free(vec);
free(result);
free(thread_handles);
return 0;
}
| 1
|
#include <pthread.h>
uint32_t inode[16];
uint32_t time[16];
uint8_t* path[16];
} hashbucket;
static hashbucket *symlinkhash = 0;
static pthread_mutex_t slcachelock = PTHREAD_MUTEX_INITIALIZER;
enum {
INSERTS = 0,
SEARCH_HITS,
SEARCH_MISSES,
LINKS,
STATNODES
};
static uint64_t *statsptr[STATNODES];
static inline void symlink_cache_statsptr_init(void) {
void *s;
s = stats_get_subnode(0,"symlink_cache",0);
statsptr[INSERTS] = stats_get_counterptr(stats_get_subnode(s,"inserts",0));
statsptr[SEARCH_HITS] = stats_get_counterptr(stats_get_subnode(s,"search_hits",0));
statsptr[SEARCH_MISSES] = stats_get_counterptr(stats_get_subnode(s,"search_misses",0));
}
static inline void symlink_cache_stats_inc(uint8_t id) {
if (id<STATNODES) {
stats_lock();
(*statsptr[id])++;
stats_unlock();
}
}
static inline void symlink_cache_stats_dec(uint8_t id) {
if (id<STATNODES) {
stats_lock();
(*statsptr[id])--;
stats_unlock();
}
}
void symlink_cache_insert(uint32_t inode,const uint8_t *path) {
uint32_t primes[4] = {1072573589U,3465827623U,2848548977U,748191707U};
hashbucket *hb,*fhb;
uint8_t h,i,fi;
uint32_t now;
uint32_t mints;
now = time(0);
mints = UINT32_MAX;
fi = 0;
fhb = 0;
symlink_cache_stats_inc(INSERTS);
pthread_mutex_lock(&slcachelock);
for (h=0 ; h<4 ; h++) {
hb = symlinkhash + ((inode*primes[h])%6257);
for (i=0 ; i<16 ; i++) {
if (hb->inode[i]==inode) {
if (hb->path[i]) {
free(hb->path[i]);
}
hb->path[i]=(uint8_t*)strdup((const char *)path);
hb->time[i]=now;
pthread_mutex_unlock(&slcachelock);
return;
}
if (hb->time[i]<mints) {
fhb = hb;
fi = i;
mints = hb->time[i];
}
}
}
if (fhb) {
if (fhb->time[fi]==0) {
symlink_cache_stats_inc(LINKS);
}
if (fhb->path[fi]) {
free(fhb->path[fi]);
}
fhb->inode[fi]=inode;
fhb->path[fi]=(uint8_t*)strdup((const char *)path);
fhb->time[fi]=now;
}
pthread_mutex_unlock(&slcachelock);
}
int symlink_cache_search(uint32_t inode,const uint8_t **path) {
uint32_t primes[4] = {1072573589U,3465827623U,2848548977U,748191707U};
hashbucket *hb;
uint8_t h,i;
uint32_t now;
now = time(0);
pthread_mutex_lock(&slcachelock);
for (h=0 ; h<4 ; h++) {
hb = symlinkhash + ((inode*primes[h])%6257);
for (i=0 ; i<16 ; i++) {
if (hb->inode[i]==inode) {
if (hb->time[i]+MFS_INODE_REUSE_DELAY<now) {
if (hb->path[i]) {
free(hb->path[i]);
hb->path[i]=0;
}
hb->time[i]=0;
hb->inode[i]=0;
pthread_mutex_unlock(&slcachelock);
symlink_cache_stats_dec(LINKS);
symlink_cache_stats_inc(SEARCH_MISSES);
return 0;
}
*path = hb->path[i];
pthread_mutex_unlock(&slcachelock);
symlink_cache_stats_inc(SEARCH_HITS);
return 1;
}
}
}
pthread_mutex_unlock(&slcachelock);
symlink_cache_stats_inc(SEARCH_MISSES);
return 0;
}
void symlink_cache_init(void) {
symlinkhash = malloc(sizeof(hashbucket)*6257);
memset(symlinkhash,0,sizeof(hashbucket)*6257);
symlink_cache_statsptr_init();
}
void symlink_cache_term(void) {
hashbucket *hb;
uint8_t i;
uint32_t hi;
pthread_mutex_lock(&slcachelock);
for (hi=0 ; hi<6257 ; hi++) {
hb = symlinkhash + hi;
for (i=0 ; i<16 ; i++) {
if (hb->path[i]) {
free(hb->path[i]);
}
}
}
free(symlinkhash);
pthread_mutex_unlock(&slcachelock);
}
| 0
|
#include <pthread.h>
void *consumeTen();
void *consumeFifteen();
struct data
{
pthread_t threadID;
char name;
int pearlsTaken;
int *pearls;
};
int pearls = 1000;
pthread_mutex_t mutex;
pthread_cond_t full_cond;
pthread_cond_t empty_cond;
struct data threadData[4];
int main()
{
int i, j;
threadData[0].name = 'A';
threadData[0].pearlsTaken = 0;
threadData[1].name = 'B';
threadData[1].pearlsTaken = 0;
threadData[2].name = 'C';
threadData[2].pearlsTaken = 0;
threadData[3].name = 'D';
threadData[3].pearlsTaken = 0;
pthread_setconcurrency(4);
pthread_create(&threadData[0].threadID, 0, (void *(*)(void *))consumeTen, &threadData[0]);
pthread_create(&threadData[1].threadID, 0, (void *(*)(void *))consumeTen, &threadData[1]);
pthread_create(&threadData[2].threadID, 0, (void *(*)(void *))consumeFifteen, &threadData[2]);
pthread_create(&threadData[3].threadID, 0, (void *(*)(void *))consumeFifteen, &threadData[3]);
pthread_exit(0);
}
void *consumeTen()
{
double pearlsToTake = 0;
while(pearls != 0)
{
pthread_mutex_lock(&mutex);
pearlsToTake = (.10) * pearls;
pearlsToTake = ceil(pearlsToTake);
printf("Pirate %c took %d pearls from the chest \\n", threadData->name, pearlsToTake);
pearls -= pearlsToTake;
threadData->pearlsTaken += pearlsToTake;
pthread_mutex_unlock(&mutex);
}
}
void *consumeFifteen()
{
double pearlsToTake = 0;
while(pearls != 0)
{
pthread_mutex_lock(&mutex);
pearlsToTake = (.15) * pearls;
pearlsToTake = ceil(pearlsToTake);
printf("Pirate %c took %d pearls from the chest \\n", threadData->name, pearlsToTake);
pearls -= pearlsToTake;
threadData->pearlsTaken += pearlsToTake;
pthread_mutex_unlock(&mutex);
}
}
| 1
|
#include <pthread.h>
static pthread_mutex_t astCount_lock;
static pthread_mutex_t first_lock;
static pthread_mutex_t second_lock;
static int astCount = 0;
void eventAst(void *arg, int len , char *buf ) {
printf("received event in thread %ld, name=%s\\n",
syscall(__NR_gettid),
(char *)arg);
pthread_mutex_lock(&astCount_lock);
astCount++;
pthread_mutex_unlock(&astCount_lock);
}
static int first = 0,second = 0;
void eventAstFirst(void *arg, int len , char *buf ) {
printf("received event in thread %ld, name=%s\\n",
syscall(__NR_gettid),
(char *)arg);
pthread_mutex_lock(&first_lock);
first=1;
pthread_mutex_unlock(&first_lock);
}
void eventAstSecond(void *arg, int len , char *buf ) {
printf("received event in thread %ld, name=%s\\n",
syscall(__NR_gettid),
(char *)arg);
pthread_mutex_lock(&second_lock);
second=1;
pthread_mutex_unlock(&second_lock);
}
static void wait() {
static const struct timespec tspec = {0,100000000};
nanosleep(&tspec,0);
}
int main(int argc, char **args)
{
int status=0;
int i,iterations,ev_id;
char *eventname = alloca(100);
pthread_mutex_init(&astCount_lock, 0);
pthread_mutex_init(&first_lock, 0);
pthread_mutex_init(&second_lock, 0);
BEGIN_TESTING(UdpEvents);
if (argc < 2) {
iterations=3;
} else {
iterations=atoi(args[1]);
printf("Doing %d iterations\\n",iterations);
}
for (i=0;i<iterations;i++) {
sprintf(eventname,"ev_test_%d_%d",i,getpid());
status = MDSEventAst(eventname, eventAst, eventname, &ev_id);
TEST0( status%1 );
wait();
status = MDSEvent(eventname,0,0);
TEST0( status%1 );
status = MDSEvent(eventname,0,0);
TEST0( status%1 );
wait();
status = MDSEventCan(ev_id);
TEST0( status%1 );
wait();
}
pthread_mutex_lock(&astCount_lock);
TEST1(astCount == 2*iterations);
pthread_mutex_unlock(&astCount_lock);
int id1,id2;
sprintf(eventname, "test_event_%d", getpid());
status = MDSEventAst(eventname, eventAstFirst, "first", &id1);
status = MDSEventAst(eventname, eventAstSecond, "second", &id2);
wait();
status = MDSEvent(eventname,0,0);
wait();
pthread_mutex_lock(&first_lock);
pthread_mutex_lock(&second_lock);
printf("first = %d, second = %d\\n",first,second);
TEST1(first);
TEST1(second);
pthread_mutex_unlock(&first_lock);
pthread_mutex_unlock(&second_lock);
status = MDSEventCan(id1);
status = MDSEventCan(id2);
END_TESTING;
return (status & 1)==0;
}
| 0
|
#include <pthread.h>
int map_minerals = 5000;
int minerals = 0;
int n = 0;
int m = 0;
int k = -1;
int command_centers_minerals[12] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
pthread_mutex_t mutex_workers;
pthread_mutex_t mutex_map_minerals;
pthread_mutex_t mutex_minerals;
pthread_mutex_t mutex_solders;
pthread_mutex_t mutex_command_center;
pthread_mutex_t mutex_command_centers[12];
void* worker (void) {
pthread_mutex_lock(&mutex_workers);
n++;
pthread_mutex_unlock(&mutex_workers);
char* name = "SVC " + (n + 49);
int worker_minerals = 0;
printf("SCV good to go, sir.");
while (m < 20) {
printf("%s", name);
printf(" is mining\\n");
pthread_mutex_lock(&mutex_map_minerals);
map_minerals -= 8;
pthread_mutex_unlock(&mutex_map_minerals);
worker_minerals += 8;
while (worker_minerals > 0) {
}
printf("%s", name);
printf(" is transporting minerals\\n ");
}
}
void* command_center (void) {
pthread_mutex_lock(&mutex_command_center);
command_centers_minerals[++k] = 0;
pthread_mutex_unlock(&mutex_command_center);
if (pthread_mutex_init(&mutex_command_centers[k], 0) != 0) {
perror("Fail to initialize mutex: workers!");
}
}
void* solder (void) {
}
int return_all_minerals (void) {
int all = minerals;
int i;
for (i = 0; i <= k; i++) {
all += command_centers_minerals[i];
}
return all;
}
int main (void) {
char command;
int all = 0;
pthread_t workers[100];
pthread_t solders[20];
pthread_t centers[12];
if (pthread_mutex_init(&mutex_workers, 0) != 0) {
perror("Fail to initialize mutex: workers!");
}
if (pthread_mutex_init(&mutex_command_center, 0) != 0) {
perror("Fail to initialize mutex: command_center!");
}
if (pthread_mutex_init(&mutex_solders, 0) != 0) {
perror("Fail to initialize mutex: solders!");
}
if (pthread_mutex_init(&mutex_map_minerals, 0) != 0) {
perror("Fail to initialize mutex: minerals!");
}
while(m < 20) {
command = getchar();
if ((command == 'm') || (command == 's') || (command == 'c')) {
pthread_mutex_lock(&mutex_minerals);
all = return_all_minerals();
}
if (command == 'm') {
if (all > 50) {
minerals -= 50;
}
}
if (command == 's') {
if (all > 50) {
minerals -= 50;
}
}
if (command == 'c') {
if (all > 400) {
minerals -= 400;
}
}
}
return 0;
}
| 1
|
#include <pthread.h>
int g = 0;
pthread_mutex_t mutexsum;
void *myThreadFun(void *vargp)
{
int i = (int)vargp;
pthread_mutex_lock (&mutexsum);
printf("%i Global: %d\\n", i, ++g);
pthread_mutex_unlock (&mutexsum);
}
int threadCount(int num_threads)
{
int i;
pthread_t tid;
pthread_t threads[num_threads];
pthread_attr_t attr;
pthread_mutex_init(&mutexsum, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (i = 0; i < num_threads; i++)
myThreadFun((void *)i);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&mutexsum);
return g;
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int count = 0;
pthread_mutex_t mutex;
void* asyncFn(void* arg){
pthread_mutex_lock(&mutex);
printf("Hello!! %d\\n", count);
count++;
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main(int argc, const char* argv[]){
pthread_t tid[20];
pthread_mutex_init(&mutex, 0);
int i;
printf("\\n");
for ( i = 0; i < 20; ++i){
pthread_create(&tid[i], 0, asyncFn, 0);
}
for ( i = 0; i < 20; ++i)
{
pthread_join(tid[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
void calcula_hash_senha(const char *senha, char *hash);
char* incrementa_senha(char *senha);
void* testa_senha (void *arg);
char hash_alvo[50];
char senha[1000][30];
} thread_arg, *ptr_thread_arg;
int num_pthread;
pthread_mutex_t bloqueio;
pthread_attr_t ttr;
pthread_cond_t nao_vazio;
int main(int argc, char *argv[]) {
int i;
char senha[4 + 1];
if (argc != 2) {
printf("Uso: %s <hash>", argv[0]);
return 1;
}
for (i = 0; i < 4; i++) {
senha[i] = 'a';
}
senha[4] = '\\0';
num_pthread = 0;
pthread_mutex_init(&bloqueio, 0);
pthread_attr_init(&ttr);
pthread_cond_init(&nao_vazio, 0);
pthread_attr_setdetachstate(&ttr, PTHREAD_CREATE_DETACHED);
while (1) {
ptr_thread_arg args = malloc(sizeof(thread_arg));
pthread_mutex_lock(&bloqueio);
while(num_pthread > 400){
pthread_cond_wait(&nao_vazio, &bloqueio);
}
pthread_mutex_unlock(&bloqueio);
strcpy(args->hash_alvo,argv[1]);
int i;
for(i = 0;i < 1000; i++){
strcpy( args->senha[i],incrementa_senha(senha));
}
pthread_t *thr_testa_senha = malloc(sizeof(pthread_t));
}
return 0;
}
void* testa_senha (void *arg) {
char hash_calculado[256 + 1];
pthread_mutex_lock(&bloqueio);
num_pthread++;
pthread_mutex_unlock(&bloqueio);
int i;
for(i=0;i<1000;i++){
ptr_thread_arg testasenha = (ptr_thread_arg) arg;
calcula_hash_senha(testasenha->senha[i], hash_calculado);
if (!strcmp(testasenha->hash_alvo, hash_calculado)) {
printf("Achou! %s\\n", testasenha->senha[i]);
exit(0);
}
}
pthread_mutex_lock(&bloqueio);
num_pthread--;
pthread_cond_signal(&nao_vazio);
pthread_mutex_unlock(&bloqueio);
return 0;
}
char* incrementa_senha(char *senha) {
int i;
i = 4 - 1;
while (i >= 0) {
if (senha[i] != 'z') {
senha[i]++;
i = -2;
} else {
senha[i] = 'a';
i--;
}
}
if (i == -1 && num_pthread == 0) {
printf("Não achou!\\n");
exit(1);
return 0;
}
return senha;
}
void calcula_hash_senha(const char *senha, char *hash) {
struct crypt_data data;
data.initialized = 0;
strcpy(hash, crypt_r(senha, "aa", &data));
}
| 0
|
#include <pthread.h>
pthread_mutex_t mt1, mt2;
int ok = 0;
void* first(void* param){
int i;
for(i =0 ; i<10 ;i++)
{
pthread_mutex_lock(&mt1);
printf("First thread: %d\\n", (int)pthread_self());
pthread_mutex_unlock(&mt2);
}
return 0;
}
void* second(void* param) {
int i;
for( i = 0; i<10; i++) {
pthread_mutex_lock(&mt2);
printf("Second thread: %d\\n", (int)pthread_self());
pthread_mutex_unlock(&mt1);
}
return 0;
}
int main(){
pthread_t t1, t2;
int ret1, ret2;
pthread_mutex_init(&mt1, 0);
pthread_mutex_init(&mt2, 0);
pthread_mutex_lock(&mt2);
ret1 = pthread_create(&t1, 0, first, 0);
ret2 = pthread_create(&t2, 0, second, 0);
if(ret1){
printf("Error at creating thread: %d\\n", ret1);
}
if( ret2 ){
printf("Error at creating thread: %d\\n", ret2);
}
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_mutex_destroy(&mt1);
pthread_mutex_destroy(&mt2);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static int avail = 0;
static void *threadFunc(void *arg)
{
int cnt = *((int *)arg);
int j, ret;
for (j = 0; j < cnt; j++) {
pthread_mutex_lock(&mtx);
avail++;
pthread_mutex_unlock(&mtx);
ret = pthread_cond_signal(&cond);
if (ret != 0)
perror("pthread_cond_signal");
}
return 0;
}
int main()
{
pthread_t tid;
int ret, j;
int totRequired;
int numConsumed = 0;
Boolean done = FALSE;
totRequired = 10;
ret = pthread_create(&tid, 0, threadFunc, &totRequired);
if (ret != 0)
perror("pthread_create: ");
for (;;) {
pthread_mutex_lock(&mtx);
while (avail == 0) {
ret = pthread_cond_wait(&cond, &mtx);
if (ret != 0)
perror("pthread_cond_wait");
}
while (avail > 0) {
numConsumed++;
avail--;
printf("numConsumed=%d\\n", numConsumed);
done = numConsumed >= totRequired;
}
pthread_mutex_unlock(&mtx);
if (done)
break;
}
pthread_exit(0);
exit(0);
}
| 0
|
#include <pthread.h>
static int noItemsToProduce = 10;
static int totalItemsToProduce = 100;
static int noItemsConsumed = 0;
static int done = 0;
static int queueEmpty = 0;
void *res;
static int *queueArray;
int front = 0;
int back = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void enqueue(int item)
{
pthread_mutex_lock(&mutex);
queueArray[back] = item;
back++;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}
void dequeue()
{
if(front<back)
{
if(queueArray[front]>0)
{
noItemsConsumed++;
}
front++;
}
else{
if(noItemsConsumed<totalItemsToProduce)
pthread_cond_wait(&cond,&mutex2);
}
}
static void *producer(void *arg)
{
int i;
int id = strtol(arg,0,0);
for(i=0;i<noItemsToProduce;i++)
{
enqueue(id);
}
}
static void *consumer(void *arg)
{
while(!done || front<totalItemsToProduce)
{
dequeue();
}
}
int main(int argc,char *argv[])
{
if (argc!=2)
{
return -1;
}
else
{
noItemsToProduce = strtol(argv[1],0,0);
totalItemsToProduce = 10*noItemsToProduce;
queueArray = (int *)malloc(sizeof(int)*totalItemsToProduce);
}
pthread_t p1;
pthread_t p2;
pthread_t p3;
pthread_t p4;
pthread_t p5;
pthread_t p6;
pthread_t p7;
pthread_t p8;
pthread_t p9;
pthread_t p10;
pthread_t c;
struct timeval start, finish;
long timeTaken;
gettimeofday(&start,0);
pthread_create(&p1,0,producer,"1");
pthread_create(&p2,0,producer,"2");
pthread_create(&p3,0,producer,"3");
pthread_create(&p4,0,producer,"4");
pthread_create(&p5,0,producer,"5");
pthread_create(&p6,0,producer,"6");
pthread_create(&p7,0,producer,"7");
pthread_create(&p8,0,producer,"8");
pthread_create(&p9,0,producer,"9");
pthread_create(&p10,0,producer,"10");
pthread_create(&c, 0, consumer,"");
pthread_join(p1,&res);
pthread_join(p2,&res);
pthread_join(p3,&res);
pthread_join(p4,&res);
pthread_join(p5,&res);
pthread_join(p6,&res);
pthread_join(p7,&res);
pthread_join(p8,&res);
pthread_join(p9,&res);
pthread_join(p10,&res);
done = 1;
pthread_join(c,&res);
gettimeofday(&finish,0);
timeTaken = (finish.tv_sec - start.tv_sec)*1000*1000;
printf("Total time time in non synchronized case is: %ld us.\\n",timeTaken);
printf("Total items produced = %d.\\n",totalItemsToProduce);
printf("Total items consumed = %d.\\n",noItemsConsumed);
return 0;
}
| 1
|
#include <pthread.h>
extern FILE *fileout_basicmath_cubic;
extern pthread_mutex_t mutex_print;
int main_basicmath_cubic(void)
{
double a1 = 1.0, b1 = -10.5, c1 = 32.0, d1 = -30.0;
double a2 = 1.0, b2 = -4.5, c2 = 17.0, d2 = -30.0;
double a3 = 1.0, b3 = -3.5, c3 = 22.0, d3 = -31.0;
double a4 = 1.0, b4 = -13.7, c4 = 1.0, d4 = -35.0;
double x[3];
double X;
int solutions;
int i;
unsigned long l = 0x3fed0169L;
struct int_sqrt q;
long n = 0;
pthread_mutex_lock(&mutex_print);
fprintf(fileout_basicmath_cubic,"********* CUBIC FUNCTIONS ***********\\n");
pthread_mutex_unlock(&mutex_print);
SolveCubic(a1, b1, c1, d1, &solutions, x);
pthread_mutex_lock(&mutex_print);
for(i=0;i<solutions;i++)
fprintf(fileout_basicmath_cubic," %f",x[i]);
fprintf(fileout_basicmath_cubic,"\\n");
pthread_mutex_unlock(&mutex_print);
SolveCubic(a2, b2, c2, d2, &solutions, x);
pthread_mutex_lock(&mutex_print);
for(i=0;i<solutions;i++)
fprintf(fileout_basicmath_cubic," %f",x[i]);
fprintf(fileout_basicmath_cubic,"\\n");
pthread_mutex_unlock(&mutex_print);
SolveCubic(a3, b3, c3, d3, &solutions, x);
pthread_mutex_lock(&mutex_print);
for(i=0;i<solutions;i++)
fprintf(fileout_basicmath_cubic," %f",x[i]);
fprintf(fileout_basicmath_cubic,"\\n");
pthread_mutex_unlock(&mutex_print);
SolveCubic(a4, b4, c4, d4, &solutions, x);
pthread_mutex_lock(&mutex_print);
for(i=0;i<solutions;i++)
fprintf(fileout_basicmath_cubic," %f",x[i]);
fprintf(fileout_basicmath_cubic,"\\n");
pthread_mutex_unlock(&mutex_print);
pthread_mutex_lock(&mutex_print);
fprintf(fileout_basicmath_cubic,"********* ANGLE CONVERSION ***********\\n");
pthread_mutex_unlock(&mutex_print);
double res;
for (X = 0.0; X <= 360.0; X += 1.0)
{
res = deg2rad(X);
pthread_mutex_lock(&mutex_print);
fprintf(fileout_basicmath_cubic,"%3.0f degrees = %.12f radians\\n", X, res);
pthread_mutex_unlock(&mutex_print);
}
for (X = 0.0; X <= (2 * PI + 1e-6); X += (PI / 180))
{
res = rad2deg(X);
pthread_mutex_lock(&mutex_print);
fprintf(fileout_basicmath_cubic,"%.12f radians = %3.0f degrees\\n", X, res);
pthread_mutex_unlock(&mutex_print);
}
return 0;
}
| 0
|
#include <pthread.h>
struct int_channel{
int queue[100];
int front;
int back;
int MAX_SIZE;
int size;
bool poisoned;
pthread_mutex_t lock;
pthread_cond_t write_ready;
pthread_cond_t read_ready;
};
int init_int_channel(struct int_channel *channel){
if(pthread_mutex_init(&channel->lock, 0) != 0){
printf("Mutex init failed");
return 1;
}
if(pthread_cond_init(&channel->write_ready, 0) +
pthread_cond_init(&channel->read_ready, 0 ) != 0){
printf("Cond init failed");
return 1;
}
channel->MAX_SIZE = 100;
channel->front = 0;
channel->back = 0;
channel->poisoned = 0;
return 0;
}
void enqueue_int(int element, struct int_channel *channel){
pthread_mutex_lock(&channel->lock);
while(channel->size >= channel->MAX_SIZE)
pthread_cond_wait(&channel->write_ready, &channel->lock);
assert(channel->size < channel->MAX_SIZE);
assert(!(channel->poisoned));
channel->queue[channel->back] = element;
channel->back = (channel->back + 1) % channel->MAX_SIZE;
channel->size++;
pthread_cond_signal(&channel->read_ready);
pthread_mutex_unlock(&channel->lock);
}
int dequeue_int(struct int_channel *channel){
pthread_mutex_lock(&channel->lock);
assert(channel->size != 0);
int result = channel->queue[channel->front];
channel->front = (channel->front + 1) % channel->MAX_SIZE;
channel->size--;
pthread_cond_signal(&channel->write_ready);
pthread_mutex_unlock(&channel->lock);
return result;
}
void poison(struct int_channel *channel) {
pthread_mutex_lock(&channel->lock);
channel->poisoned = 1;
pthread_cond_signal(&channel->read_ready);
pthread_mutex_unlock(&channel->lock);
}
bool wait_for_more(struct int_channel *channel) {
pthread_mutex_lock(&channel->lock);
while(channel->size == 0) {
if(channel->poisoned){
pthread_mutex_unlock(&channel->lock);
return 0;
}
else {
pthread_cond_wait(&channel->read_ready, &channel->lock);
}
}
pthread_mutex_unlock(&channel->lock);
return 1;
}
| 1
|
#include <pthread.h>
static pthread_t thread;
static pthread_mutex_t delayMutex;
static int reading;
struct timespec delay;
static _Bool continueWatching = 1;
static void *watchPOT(void *args);
static struct timespec calculateDelay(void);
static const float PIECEWISE_READING[] = { 0, 500, 1000, 1500, 2000, 2500, 3000,
3500, 4000, 4100 };
static const float PIECEWISE_DELAY[] =
{ 0, 2, 6, 12, 25, 30, 50, 100, 500, 1500 };
static void *watchPOT(void *args) {
int oldValue;
int newValue;
while (continueWatching) {
oldValue = PrimeFinder_getNumPrimesFound();
reading = A2D_getReading();
pthread_mutex_lock(&delayMutex);
delay = calculateDelay();
pthread_mutex_unlock(&delayMutex);
sleep(1);
newValue = PrimeFinder_getNumPrimesFound();
DigitDisplayer_setValue(newValue - oldValue);
}
return 0;
}
static struct timespec calculateDelay(void) {
struct timespec tempDelay;
if (reading <= PIECEWISE_READING[0]) {
tempDelay.tv_sec = 0;
tempDelay.tv_nsec = 0;
return tempDelay;
} else if (reading >= PIECEWISE_READING[PIECEWISE_NUM_POINTS - 1]) {
tempDelay.tv_sec = 1;
tempDelay.tv_nsec = TO_MILLISECONDS(500);
return tempDelay;
}
for (int i = 0; i < PIECEWISE_NUM_POINTS - 1; i++) {
if (reading > PIECEWISE_READING[i]
&& reading < PIECEWISE_READING[i + 1]) {
float s, a, b, m, n;
long fs;
s = reading;
a = PIECEWISE_READING[i];
b = PIECEWISE_READING[i + 1];
m = PIECEWISE_DELAY[i];
n = PIECEWISE_DELAY[i + 1];
fs = ((s - a) / (b - a)) * (n - m) + m;
if (fs >= 1000) {
tempDelay.tv_sec = 1;
tempDelay.tv_nsec = TO_MILLISECONDS((fs-1000));
} else {
tempDelay.tv_sec = 0;
tempDelay.tv_nsec = TO_MILLISECONDS(fs);
}
}
}
return tempDelay;
}
void DelayManager_launchThread(void) {
pthread_mutex_init(&delayMutex, 0);
pthread_create(&thread, 0, watchPOT, 0);
}
pthread_t DelayManager_getThreadID(void) {
return thread;
}
void DelayManager_sleep(void) {
pthread_mutex_lock(&delayMutex);
struct timespec tempDelay = delay;
pthread_mutex_unlock(&delayMutex);
nanosleep(&tempDelay, (struct timespec *) 0);
}
void DelayManager_stopWatching(void) {
continueWatching = 0;
}
| 0
|
#include <pthread.h>
int GLOBAL = 0;
int NB_AFFICHAGE = 0;
int NB_THREAD;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condFinAffichage = PTHREAD_COND_INITIALIZER;
void* attendre(void* arg) {
pthread_mutex_lock(&mutex);
while(NB_AFFICHAGE < NB_THREAD)
pthread_cond_wait(&condFinAffichage, &mutex);
printf("GLOBAL: %d\\n", GLOBAL);
pthread_mutex_unlock(&mutex);
pthread_exit(arg);
}
void* affiche(void* arg) {
int* num = (int*) arg;
int random = (int) (10*((double)rand())/ 32767);
printf("THREAD %d ; Random: %d\\n", *num, random);
*num *= 2;
pthread_mutex_lock(&mutex);
GLOBAL+=random;
NB_AFFICHAGE++;
if(NB_AFFICHAGE == NB_THREAD)
pthread_cond_signal(&condFinAffichage);
pthread_mutex_unlock(&mutex);
pthread_exit(arg);
}
int main(int argc, char* argv[]) {
pthread_t* tids;
pthread_t afficheurDeFin;
int i;
int* dup_i;
if(argc != 2)
{
printf("Bad args\\n");
return 1;
}
NB_THREAD = atoi(argv[1]);
tids = malloc(sizeof(pthread_t)*NB_THREAD);
if(pthread_create(&afficheurDeFin, 0, attendre, 0) != 0) {
perror("error p_create");
return 1;
}
for(i = 0; i < NB_THREAD; i++) {
dup_i = malloc(sizeof(int));
*dup_i = i;
if(pthread_create(&tids[i], 0, affiche, dup_i) != 0) {
perror("error p_create");
return 1;
}
}
for(i = 0; i < NB_THREAD; i++) {
if(pthread_join(tids[i], (void**) &dup_i) != 0) {
perror("error p_join");
return 1;
}
printf("Retour mult: %d\\n", *((int*)(int*)dup_i));
}
if(pthread_join(afficheurDeFin, 0) != 0) {
perror("error p_join");
return 1;
}
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
int resource_count;
pthread_mutex_t resource_mutex;
void * handler()
{
while(1){
if (resource_count == 3)
pthread_mutex_unlock(&resource_mutex);
}
}
void * customer(void* arg)
{
int cust_no = *((int*)arg);
while(1){
if (resource_count>0)
{
resource_count--;
fprintf(stdout,"customer No.%d using resource \\n",cust_no);
sleep(rand()%3);
resource_count++;
return 0;
}
else
{
fprintf(stdout,"customer No.%d blocked because lack of resource.\\n",cust_no);
pthread_mutex_lock(&resource_mutex);
}
}
}
int main(int argc, char *argv[])
{
srand(time(0));
pthread_mutex_init(&resource_mutex, 0);
int num_customers;
if( argc != 2 ) {
printf("usage: %s NUM_CUSTOMERS\\n(1 integer arg)\\n%s 30 is a good default\\n", argv[0],argv[0]);
exit(0);
}
num_customers = atoi(argv[1]);
resource_count = 3;
pthread_t thread_handler;
pthread_t thread_customers[num_customers];
int args[num_customers];
for (int i=0; i<num_customers; i++)
args[i] = i;
pthread_create(&thread_handler, 0, handler, 0);
int rd_cus = 0;
for(int i=0;i<num_customers;i=i+rd_cus)
{
rd_cus= rand()%5;
sleep(1);
if (i+rd_cus >= num_customers)
rd_cus = num_customers-i;
for (int j=1; j<=rd_cus; j++)
pthread_create(&thread_customers[i+j-1], 0, customer, (void *)&args[i+j-1]);
}
void* status;
for (int i=0; i<num_customers; i++)
pthread_join(thread_customers[i], &status);
pthread_join(thread_handler, &status);
pthread_mutex_destroy(&resource_mutex);
return 0;
}
| 0
|
#include <pthread.h>
static int uimled_uim_fd = -1;
static pthread_t uimled_uim_read_id = 0;
static char* uimled_uim_text = 0;
static pthread_mutex_t uimled_uim_text_mut = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t uimled_uim_text_cond = PTHREAD_COND_INITIALIZER;
void* uimled_uim_read_thread(void* data)
{
char* s;
char* s1;
char* s2;
char c;
int fd = *((int*)data);
while (1)
{
recv(fd, &c, 1, MSG_PEEK);
uim_helper_read_proc(fd);
while ((s = uim_helper_get_message()))
{
if (strncmp(s, "prop_list_update", sizeof("prop_list_update") - 1))
goto endloop;
s1 = s;
while (1)
{
s1 = strstr(s1, "\\nbranch\\t");
if (!s1)
break;
s1 += sizeof("\\nbranch\\t") - 1;
s2 = strchr(s1, '\\t');
s2[0] = 0;
pthread_mutex_lock(&uimled_uim_text_mut);
uimled_uim_text = s1;
pthread_mutex_unlock(&uimled_uim_text_mut);
pthread_cond_signal(&uimled_uim_text_cond);
s1 = s2 + 1;
}
endloop:
free(s);
}
}
return 0;
}
char* uimled_uim_getcurrent_lock(void)
{
pthread_mutex_lock(&uimled_uim_text_mut);
pthread_cond_wait(&uimled_uim_text_cond, &uimled_uim_text_mut);
return uimled_uim_text;
}
void uimled_uim_getcurrent_unlock(void)
{
pthread_mutex_unlock(&uimled_uim_text_mut);
}
void uimled_uim_connect(void)
{
if (uimled_uim_fd >= 0)
return;
uimled_uim_fd = uim_helper_init_client_fd(uimled_uim_disconnect);
if (uimled_uim_fd < 0)
return;
if (!uimled_uim_read_id)
{
if (pthread_create(&uimled_uim_read_id, 0,
uimled_uim_read_thread,
&uimled_uim_fd) == -1)
{
perror("pthread_create");
return;
}
}
}
void uimled_uim_disconnect(void)
{
uimled_uim_fd = -1;
}
void uimled_uim_init(void)
{
uim_init();
pthread_mutex_init(&uimled_uim_text_mut, 0);
pthread_cond_init(&uimled_uim_text_cond, 0);
uimled_uim_connect();
}
void uimled_uim_proplist(void)
{
uim_helper_send_message(uimled_uim_fd, "prop_list_get\\n");
}
| 1
|
#include <pthread.h>
int main_ConditionVariable();
static void* ConditionVariable_funcThread(void* a_pArg);
static void ConditionVariable_wait(int timeoutMs);
static int ConditionVariable_CreateThread();
static pthread_mutex_t m_mutex;
static pthread_cond_t mCondition;
static pthread_t vTreadID = 0;
int ConditionVariable_CreateThread()
{
int vRetcode = 0;
PrintfLn("CreateThread");
vRetcode = pthread_create(&vTreadID,0,ConditionVariable_funcThread,0);
return vRetcode;
}
void* ConditionVariable_funcThread(void* a_pArg)
{
PrintfLn("funcThread_1 ");
do
{
PrintfLn("funcThread_2");
ConditionVariable_wait( 20 * 1000);
PrintfLn("funcThread_3");
}
while(1);
PrintfLn("funcThread_5");
return 0;
}
void ConditionVariable_wait(int timeoutMs)
{
struct timespec absTimeToWait;
struct timeval now;
int status = 0;
gettimeofday(&now, 0);
absTimeToWait.tv_sec = now.tv_sec + (timeoutMs/1000);
absTimeToWait.tv_nsec = now.tv_usec*1000L + 1000000L*(timeoutMs%1000);
if (absTimeToWait.tv_nsec > 1000000000) {
++absTimeToWait.tv_sec;
absTimeToWait.tv_nsec -= 1000000000;
}
pthread_mutex_lock(&m_mutex);
PrintfLn("ConditionVariable_wait_1");
status = pthread_cond_timedwait(&mCondition, &m_mutex, &absTimeToWait);
PrintfLn("ConditionVariable_wait_2");
pthread_mutex_unlock(&m_mutex);
}
int main_ConditionVariable()
{
int ii = 0;
char vBuffer[1024];
pthread_mutex_init(&m_mutex, 0);
ConditionVariable_CreateThread();
usleep(100*100);
for(ii = 0; ii < 60 ; ii++)
{
sprintf(vBuffer,"ConditionVariable_main : ii = %d",ii);
PrintfLn(vBuffer);
sleep(1);
}
PrintfLn("ConditionVariable_main_1 : ");
pthread_cond_signal(&mCondition);
PrintfLn("ConditionVariable_main_2 : ");
return 0;
}
| 0
|
#include <pthread.h>
pthread_t filosofos[5];
int pratos[5];
pthread_mutex_t palitos[5];
void *filosofo(void *args) {
int *ptr = (int*) (args);
int N = (*ptr);
printf("Entrando no filosofo %d\\n", N);
while (pratos[N] < 5) {
usleep(rand()%10000);
pthread_mutex_lock(& (palitos[N]) );
pthread_mutex_lock(& (palitos[(N+1)%5]) );
pratos[N] += 1;
printf("Filosofo %d: prato %d\\n", N, pratos[N]);
sleep(1);
pthread_mutex_unlock(& (palitos[N]) );
pthread_mutex_unlock(& (palitos[(N+1)%5]) );
}
return 0;
}
int main() {
int k;
int idx[5];
for (int i=0; i<5; i++) {
idx[i] = i;
pthread_create(& (filosofos[i]), 0, filosofo, &(idx[i]) );
}
while (1) {
sleep(1);
k=0;
for (int i=0; i<5; i++)
if (pratos[i] < 5) k++;
printf("Thread principal esta viva! Faltam %d filosofos\\n", k);
if (k==0) break;
}
}
| 1
|
#include <pthread.h>
NEW,
PROCESSING,
DONE
}statuses;
int duration;
int id;
statuses status;
pthread_t worker;
} task_t;
pthread_mutex_t lock;
task_t tasks[100];
void* my_thread(void* var){
task_t * vart= (task_t*)var;
int frag = 0, k = vart->id;
long long unsigned worker =vart->worker;
while(k <= 100){
pthread_mutex_lock(&lock);
while(vart->status != NEW){
var += sizeof(task_t);
k++;
vart = (task_t*)var;
}
vart->status = PROCESSING;
pthread_mutex_unlock(&lock);
if (k >= 100){
break;
}
printf("Task %d is putting thread No %llu to sleep for %d mks\\n", vart->id, worker, *((int*)var));
usleep(*((int*)var));
frag++;
pthread_mutex_lock(&lock);
vart->status = DONE;
pthread_mutex_unlock(&lock);
}
printf("Worker %llu has fragged %d tasks\\n",worker,frag);
return 0;
}
int main(){
statuses status;
int result , i;
void* arg[2];
for (i = 0; i < 100; i++){
tasks[i].id = i;
tasks[i].duration = abs(random() % 1000);
}
for (i = 0; i < 10; i++){
pthread_create(&(tasks[i].worker), 0, my_thread, (void*)(tasks));
}
for(i = 0; i < 10; i++){
pthread_join((tasks[i].worker),0);
}
printf("END\\n");
pthread_mutex_destroy(&lock);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t console_mutex = PTHREAD_MUTEX_INITIALIZER;
int mallocNsetInt(int **toSet, int value) {
if((*toSet = (int *)malloc(sizeof(int))) != 0) {
**toSet = value;
return 0;
} else {
return 1;
}
}
int mtPrintf(const char* format, ...) {
va_list arg;
int theReturn;
__builtin_va_start((arg));
pthread_mutex_lock(&console_mutex);
theReturn = vprintf(format, arg);
pthread_mutex_unlock(&console_mutex);
;
return theReturn;
}
| 1
|
#include <pthread.h>
int count[4];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t can_produce = PTHREAD_COND_INITIALIZER;
pthread_cond_t can_consume = PTHREAD_COND_INITIALIZER;
int buffer_len = 0;
char buffer[5000][1000 +1];
FILE *file;
int state = 0;
unsigned int total_count = 0;
int index;
char str[100];
} tdata;
void* producer ()
{
while (1) {
pthread_mutex_lock(&mutex);
while (buffer_len == 5000) {
pthread_cond_wait(&can_produce, &mutex);
}
char data[1000 +1];
int read_size = fread(data, 1, 1000, file);
data[1000] = '\\0';
if (read_size < 1000) {
state = 2;
pthread_cond_signal(&can_consume);
pthread_mutex_unlock(&mutex);
return 0;
}
strcpy(buffer[buffer_len], data);
buffer_len++;
pthread_cond_signal(&can_consume);
pthread_mutex_unlock(&mutex);
}
return 0;
}
void* consumer (void* param)
{
while (1) {
pthread_mutex_lock(&mutex);
tdata* thread_data = (tdata*) param;
while (buffer_len == 0) {
if (state == 2) {
pthread_cond_signal(&can_consume);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
} else {
pthread_cond_wait(&can_consume, &mutex);
}
}
char *tmp = buffer[buffer_len-1];
while ((tmp = strstr(tmp, "ell")) != 0) {
count[thread_data->index]++;
tmp++;
}
--buffer_len;
pthread_cond_signal(&can_produce);
pthread_mutex_unlock(&mutex);
}
return 0;
}
int main (int argc, char *argv[]) {
if (argc < 2) {
printf("Please pass an input file.\\n");
return 0;
}
file = fopen(argv[1], "r");
if (!file) {
printf("Could not open %s for reading.\\n", argv[1]);
return 0;
}
char str[100];
int i;
pthread_t prod, cons[4];
struct tdata data[4];
time_t start = time(0);
pthread_create(&prod, 0, producer, 0);
for (i = 0; i < 4; ++i) {
data[i].index = i;
strcpy(data[i].str, str);
pthread_create(&cons[i], 0, consumer, (void*) &data[i]);
}
pthread_join(prod, 0);
for (i = 0; i < 4; ++i) pthread_join(cons[i], 0);
time_t end = time(0);
printf("Searching took: %lf seconds.\\n", difftime(end, start));
for (i = 0; i < 4; ++i) {
total_count += count[i];
}
printf("Found it: %d times\\n", total_count);
return 0;
}
| 0
|
#include <pthread.h>
int i = 0;
double x;
double y;
double z;
double acc;
double roll;
double pitch;
double yaw;
timespec_t time;
} attitude_t;
attitude_t attitude;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *read_attitude(void *ptr) {
pthread_mutex_lock(&mutex);
printf("reading attitude\\n");
printf("x:\\t\\t%f\\n", attitude.x);
printf("y:\\t\\t%f\\n", attitude.y);
printf("z:\\t\\t%f\\n", attitude.z);
printf("acc:\\t\\t%f\\n", attitude.acc);
printf("roll:\\t\\t%f\\n", attitude.roll);
printf("pitch:\\t\\t%f\\n", attitude.pitch);
printf("yaw:\\t\\t%f\\n", attitude.yaw);
printf("timestamp:\\t%ld\\n", attitude.time.tv_nsec);
printf("\\n");
pthread_mutex_unlock(&mutex);
usleep(3300000);
}
void *write_attitude(void *ptr) {
i++;
pthread_mutex_lock(&mutex);
attitude.x = i;
attitude.y = i;
attitude.z = i;
attitude.acc = 5.0*i;
attitude.roll = 10.0/i;
attitude.pitch = 5.0/i;
attitude.yaw = 2.0/i;
clock_gettime(0, &(attitude.time));
printf("writing attitude\\n\\n");
printf("x:\\t\\t%f\\n", attitude.x);
printf("y:\\t\\t%f\\n", attitude.y);
printf("z:\\t\\t%f\\n", attitude.z);
printf("acc:\\t\\t%f\\n", attitude.acc);
printf("roll:\\t\\t%f\\n", attitude.roll);
printf("pitch:\\t\\t%f\\n", attitude.pitch);
printf("yaw:\\t\\t%f\\n", attitude.yaw);
printf("timestamp:\\t%ld\\n", attitude.time.tv_nsec);
printf("\\n");
pthread_mutex_unlock(&mutex);
sleep(3);
}
int main() {
pthread_t thread_read, thread_write;
pthread_mutex_init(&mutex, 0);
for (int j = 0; j < 100; j++) {
pthread_create(&thread_read, 0, read_attitude, 0);
pthread_create(&thread_write, 0, write_attitude, 0);
pthread_join(thread_read, 0);
pthread_join(thread_write, 0);
}
exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t rcv_list_mutex;
struct list_head rcv_list;
pthread_mutex_t snd_list_mutex;
struct list_head snd_list;
pthread_cond_t snd_cond;
pthread_cond_t rcv_cond;
extern int quit;
void *handle_snd_pkt(void *arg)
{
enter_func();
int i = 0;
while (!quit) {
pthread_mutex_lock(&snd_list_mutex);
while (list_entry_count(&snd_list) == 0 && quit != 1) {
DBG(D_INFO, "handle_snd_pkt wait\\n");
pthread_cond_wait(&snd_cond, &snd_list_mutex);
}
DBG(D_INFO, "do something in handle_snd_pkt\\n");
if (quit) {
pthread_mutex_unlock(&snd_list_mutex);
DBG(D_INFO, "thread handle_snd_pkt exit\\n");
return (0);
}
pthread_mutex_unlock(&snd_list_mutex);
}
return (0);
}
void *handle_rcv_pkt(void *arg)
{
enter_func();
while (!quit) {
pthread_mutex_lock(&rcv_list_mutex);
while (list_entry_count(&rcv_list) == 0 && quit != 1) {
DBG(D_INFO, "handle_snd_pkt wait\\n");
pthread_cond_wait(&rcv_cond, &rcv_list_mutex);
}
DBG(D_INFO, "do something in handle_rcv_pkt\\n");
if (quit) {
pthread_mutex_unlock(&rcv_list_mutex);
DBG(D_INFO, "thread handle_rcv_pkt exit\\n");
return (0);
}
pthread_mutex_unlock(&rcv_list_mutex);
}
return (0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mt;
pthread_mutex_t wrt;
int readcount=0;
int val=0;
void *reader(int rn)
{
pthread_mutex_lock(&mt);
readcount++;
if(readcount==1)
pthread_mutex_lock(&wrt);
pthread_mutex_unlock(&mt);
printf("\\n==========================================\\n");
printf("\\nReader %d has arrived",rn);
printf("\\nReader %d is reading %d",rn,val);
pthread_mutex_lock(&mt);
readcount--;
if(readcount==0)
pthread_mutex_unlock(&wrt);
pthread_mutex_unlock(&mt);
}
void *writer(void *wno)
{
int wn=*(int*)wno;
pthread_mutex_lock(&wrt);
printf("\\n==========================================\\n");
printf("\\nWriter %d has arrived",wn);
printf("\\nWriter %d is entering in critical section",wn);
val++;
pthread_mutex_unlock(&wrt);
printf("\\nWriter Left");
printf("\\n==========================================\\n");
}
void main()
{
pthread_t rdr[5];
pthread_t wrtr[5];
int i=0;
int j=0;
int choice;
pthread_mutex_init(&mt,0);
pthread_mutex_init(&wrt,0);
while(1){
for(j=0;j<2;j++)
{
pthread_create(&rdr[j],0,reader,j);
}
for(j=0;j<2;j++)
{
pthread_join(rdr[i],0);
}
pthread_create(&wrtr[i],0,writer,&i);
for(j=2;j<4;j++)
{
pthread_create(&rdr[j],0,reader,j);
}
for(j=2;j<4;j++)
{
pthread_join(rdr[i],0);
}
pthread_join(wrtr[0],0);
sleep(2);
printf("\\n Want to repeat?(1/0)");
scanf("%d",&choice);
if(choice==0)
break;
}
}
| 1
|
#include <pthread.h>
void usage(){
fprintf(stderr,"Usage: ./make_threads <no_threads> <sum_up_to>\\n");
}
volatile unsigned long long global_sum;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
void * up_to_n(void *args){
int *n = args;
int i;
for (i =1 ; i <= *n; i++){
pthread_mutex_lock(&mut);
global_sum += i;
pthread_mutex_unlock(&mut);
}
return 0;
}
int main(int argc, char ** argv){
int t, n, i, s;
pthread_t* threads;
pthread_attr_t attr;
void * res;
if (argc < 2) {
fprintf(stderr,"Need to specify two arguments to the command line\\n");
usage();
exit(1);
}
t = atoi(argv[1]);
n = atoi(argv[2]);
threads = calloc(t,sizeof(*threads));
global_sum = 0;
s= pthread_attr_init(&attr);
if ( s != 0)
do { errno = s; perror("pthread_attr_init"); exit(1); } while (0);
s = pthread_attr_destroy(&attr);
if (s != 0)
do { errno = s; perror("pthread_attr_destroy"); exit(1); } while (0);
for (i = 0; i < t; i ++){
pthread_create(&threads[i], &attr, &up_to_n, (void *) &n);
}
for (i = 0; i < t; i++){
s = pthread_join(threads[i], &res);
if ( s != 0 )
do { errno = s; perror("pthread_join"); exit(1); } while (0);
}
printf("%lld\\n", global_sum);
free(threads);
exit(0);
}
| 0
|
#include <pthread.h>
int
pthread_setcanceltype (int type, int *oldtype)
{
struct pthread_internal_t *p = (struct pthread_internal_t*)pthread_self();
int newflags;
pthread_init();
switch (type)
{
default:
return EINVAL;
case PTHREAD_CANCEL_DEFERRED:
case PTHREAD_CANCEL_ASYNCHRONOUS:
break;
}
pthread_mutex_lock (&p->cancel_lock);
if (oldtype)
*oldtype = p->attr.flags & PTHREAD_ATTR_FLAG_CANCEL_ASYNCRONOUS;
if(type == PTHREAD_CANCEL_ASYNCHRONOUS)
p->attr.flags |= PTHREAD_ATTR_FLAG_CANCEL_ASYNCRONOUS;
else
p->attr.flags &= ~PTHREAD_ATTR_FLAG_CANCEL_ASYNCRONOUS;
newflags=p->attr.flags;
pthread_mutex_unlock (&p->cancel_lock);
if((newflags & PTHREAD_ATTR_FLAG_CANCEL_PENDING) && (newflags & PTHREAD_ATTR_FLAG_CANCEL_ENABLE) && (newflags & PTHREAD_ATTR_FLAG_CANCEL_ASYNCRONOUS))
__pthread_do_cancel(p);
return 0;
}
| 1
|
#include <pthread.h>
struct queue {
int *array;
int head;
int tail;
};
struct queue message_queue;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
sem_t message_count;
sem_t consumed_messages_count;
sem_t empty_space;
int producer_count;
int total_number_of_messages;
int message_queue_size;
void init_message_queue(){
message_queue.array = (int*) malloc (sizeof(int) * message_queue_size);
message_queue.tail = 0;
message_queue.head = 0;
sem_init(&message_count, 0,0);
sem_init(&consumed_messages_count,0,total_number_of_messages);
sem_init(&empty_space, 0, message_queue_size);
}
double time_in_seconds(){
struct timeval tv;
double t1;
gettimeofday(&tv, 0);
t1 = tv.tv_sec + tv.tv_usec/1000000.0;
return t1;
}
void* dequeue_message(void* arg){
int c_id = (int) arg;
while(1){
if(sem_trywait(&consumed_messages_count)){
break;
}
sem_wait(&message_count);
pthread_mutex_lock (&lock);
int value, sqrt_val;
message_queue.head++;
if (message_queue.head == message_queue_size){
message_queue.head = 0;
}
value = message_queue.array[message_queue.head];
sqrt_val = sqrt(value);
if (value == (sqrt_val * sqrt_val)){
printf("%d %d %d\\n", c_id, value, sqrt_val);
}
pthread_mutex_unlock(&lock);
sem_post(&empty_space);
}
return 0;
}
void* enqueue_message (void* arg){
int p_id = (int) arg;
int i;
for(i = p_id; i < total_number_of_messages; i += producer_count){
sem_wait(&empty_space);
pthread_mutex_lock(&lock);
message_queue.tail++;
if (message_queue.tail == message_queue_size){
message_queue.tail = 0;
}
message_queue.array[message_queue.tail] = i;
pthread_mutex_unlock(&lock);
sem_post(&message_count);
}
return 0;
}
int main(int argc, char *argv[0]){
if (argc < 5){
printf("Invalid number of inputs\\n");
exit(0);
}
int consumer_count;
total_number_of_messages = atoi(argv[1]);
message_queue_size = atoi(argv[2]);
producer_count = atoi(argv[3]);
consumer_count = atoi(argv[4]);
if (total_number_of_messages < 0 || message_queue_size < 0 || producer_count < 0 || consumer_count < 0){
printf("all args must be positive integers");
exit(1);
}
init_message_queue();
double starting_time;
double ending_time;
double total_time;
pthread_t producer_thread_id[producer_count];
pthread_t consumer_thread_id[consumer_count];
starting_time = time_in_seconds();
int i;
for(i = 0; i < producer_count; i++){
pthread_create(&(producer_thread_id[i]), 0, &enqueue_message, (void*)(i));
}
for(i=0; i < consumer_count; i++){
pthread_create(&(consumer_thread_id[i]), 0, &dequeue_message, (void*)(i));
}
for(i=0; i < producer_count; i++){
pthread_join(producer_thread_id[i], 0);
}
for(i=0; i < consumer_count; i++){
pthread_join(consumer_thread_id[i], 0);
}
ending_time = time_in_seconds();
total_time = ending_time - starting_time;
printf("System execution time: %f seconds\\n", total_time);
sem_destroy(&message_count);
sem_destroy(&consumed_messages_count);
sem_destroy(&empty_space);
return 0;
}
| 0
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER;
void*
thr_fn(void* arg)
{
int ret, signo;
for(;;)
{
ret = sigwait(&mask, &signo);
if(ret!=0)
{
perror("sigwait failed\\n");
exit(1);
}
switch(signo)
{
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&waitloc);
return 0;
default:
printf("unexpected signal %d\\n", signo);
exit(1);
}
}
}
int
main(int argc, char** argv)
{
int ret;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&oldmask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if((ret=pthread_sigmask(SIG_BLOCK, &mask, &oldmask))!=0)
{
perror("SIG_BLOCK error");
exit(1);
}
ret = pthread_create(&tid, 0, thr_fn, 0);
if(ret!=0)
{
perror("cannot create thread");
exit(1);
}
pthread_mutex_lock(&lock);
while(quitflag==0)
pthread_cond_wait(&waitloc, &lock);
pthread_mutex_unlock(&lock);
quitflag = 0;
if(sigprocmask(SIG_SETMASK, &oldmask, 0)<0)
{
perror("SIG_SETMASK error");
exit(1);
}
return 0;
}
| 1
|
#include <pthread.h>
struct foo * fh[29] = {0};
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 = (struct foo *)malloc(sizeof(struct foo))) != 0)
{
fp->f_count = 1;
if(pthread_mutex_init(&fp->f_lock, 0) != 0)
{
free(fp);
return 0;
}
idx = ((uintptr_t)fp % 29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
return fp;
}
else
{
return 0;
}
}
void foo_hold(struct foo *fp)
{
int idx;
pthread_mutex_lock(&fp->f_lock);
idx = ((uintptr_t)fp % 29);
fp->f_count++;
printf("on fh[%d]:%d\\n", idx, fp->f_count);
pthread_mutex_unlock(&fp->f_lock);
}
void foo_release(struct foo *fp)
{
struct foo *head;
int idx;
pthread_mutex_lock(&fp->f_lock);
if(fp->f_count == 1)
{
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_lock(&hashlock);
pthread_mutex_lock(&fp->f_lock);
if(fp->f_count != 1)
{
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
return;
}
idx = ((uintptr_t)fp % 29);
head = fh[idx];
if(head == fp)
{
fh[idx] = fp->f_next;
}
else
{
while(head->f_next != fp)
{
head = head->f_next;
}
head->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
}
else
{
fp->f_count--;
idx = ((uintptr_t)fp % 29);
printf("on fh[%d]:%d\\n", idx, fp->f_count);
pthread_mutex_unlock(&fp->f_lock);
}
}
void print_foos(void)
{
int i;
int count = 0;
struct foo *head;
for(i = 0; i < 29; i++)
{
count = 0;
head = fh[i];
while(head != 0)
{
count++;
head = head->f_next;
}
printf("fh[%d]:%d\\n", i, count);
}
}
void * thread_fun(void *arg)
{
struct foo *fp = (struct foo *)arg;
printf("In thread: %u\\n", pthread_self());
foo_hold(fp);
foo_release(fp);
pthread_exit((void *)0);
}
int main(int argc, char *argv[])
{
struct foo *fps[100];
pthread_t tids[100];
int i;
int j;
int err;
void *tret;
print_foos();
for(i = 0; i < 100; i++)
{
fps[i] = foo_alloc();
}
print_foos();
for(i = 0; i < 100; i++)
{
for(j = 0; j < 100; j++)
{
err = pthread_create(&tids[j], 0, thread_fun, (void *)fps[i]);
if(err)
{
printf("error while creating thread : %d in fh[%d]\\n", j, ((uintptr_t)fps[i] % 29));
}
}
for(j = 0; j < 100; j++)
{
err = pthread_join(tids[j], (void *)&tret);
if(err)
{
printf("error while joining thread : %d in fh[%d]\\n", j, ((uintptr_t)fps[i] % 29));
}
printf("thread :%d in fh[%d]\\n", j, ((uintptr_t)fps[i] % 29));
}
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t main_chair, waiting_chair, checking_state;
pthread_mutex_t serving_chair;
int fre;
void *define_client(void* p){
printf("The client started\\n");
if(pthread_mutex_trylock(&main_chair) == 0){
printf("The barber is sleeping\\n");
pthread_mutex_unlock(&main_chair);
printf("The client is served\\n");
pthread_mutex_lock(&serving_chair);
printf("The client was served\\n");
}
else{
printf("The client is checking the waiting room\\n");
pthread_mutex_lock(&checking_state);
if(fre > 0){
fre--;
printf("The client is waiting\\n");
pthread_mutex_lock(&waiting_chair);
printf("The client is served\\n");
pthread_mutex_unlock(&serving_chair);
}
else{
printf("The client is leaving\\n");
}
pthread_mutex_unlock(&checking_state);
}
return 0;
}
void *barberStuff(void *arg){
printf("The barber started\\n");
while(1){
if(pthread_mutex_trylock(&waiting_chair) == 0){
printf("Inviting a client to the main chair\\n");
pthread_mutex_unlock(&waiting_chair);
fre--;
pthread_mutex_unlock(&checking_state);
sleep(rand() % 2 + 1);
printf("Barber is done\\n");
pthread_mutex_unlock(&serving_chair);
}
else{
pthread_mutex_unlock(&waiting_chair);
printf("sleeps\\n");
pthread_mutex_lock(&main_chair);
printf("awaken\\n");
sleep(rand() % 2 + 1);
printf("barber done\\n");
pthread_mutex_unlock(&serving_chair);
}
}
return 0;
}
int main(){
fre = 10;
int i;
pthread_mutex_init(&main_chair, 0);
pthread_mutex_init(&waiting_chair, 0);
pthread_mutex_init(&serving_chair, 0);
pthread_mutex_init(&checking_state, 0);
pthread_t barber, client[200];
if(pthread_create(&barber, 0, barberStuff, 0) < 0){
perror("Can't create barber\\n");
exit(1);
}
for(i = 0 ; i < 200 ; i++){
if(pthread_create(&client[i], 0, define_client, 0) < 0){
perror("Can't create client\\n");
}
}
for(i = 0 ; i < 200 ; i++){
pthread_join(client[i], 0);
}
pthread_mutex_destroy(&main_chair);
pthread_mutex_destroy(&waiting_chair);
pthread_mutex_destroy(&serving_chair);
pthread_mutex_destroy(&checking_state);
return 0;
}
| 1
|
#include <pthread.h>
{
unsigned char r;
unsigned char g;
unsigned char b;
} rgb;
{
double r;
double i;
} complex;
rgb * rtex;
int w;
int h;
complex center;
double scale;
int startiter;
int enditer;
int maxiter;
double er;
double eg;
double eb;
int renderworking = 0;
int rendernextline = -1;
pthread_mutex_t mrenderline;
pthread_mutex_t mrenderworking;
complex f(complex x, complex c, double *sqr)
{
complex res;
double r2 = x.r * x.r;
double i2 = x.i * x.i;
res.r = r2 - i2 + c.r;
res.i = 2 * x.r * x.i + c.i;
*sqr = r2 + i2;
return res;
}
rgb color(double iter)
{
rgb res;
double r, g, b, c;
c = (iter - startiter) / (enditer - startiter);
r = pow(c, er);
g = pow(c, eg);
b = pow(c, eb);
res.r = ((r) > (1.0) ? (1.0) : (r) < (0.0) ? (0.0) : (r)) * 255;
res.g = ((g) > (1.0) ? (1.0) : (g) < (0.0) ? (0.0) : (g)) * 255;
res.b = ((b) > (1.0) ? (1.0) : (b) < (0.0) ? (0.0) : (b)) * 255;
return res;
}
void renderline(int y)
{
int x;
int index = y * w;
for(x = 0; x < w; x++)
{
int iter = 0;
complex c = center;
complex r = {0, 0};
c.r += (x - w / 2) * scale / h;
c.i += (y - h / 2) * scale / h;
while(iter < maxiter)
{
double sqr;
r = f(r, c, &sqr);
if(sqr >= 1e10)
{
rtex[index] = color(iter - log( 0.5 * log(sqr) / log(2) ) / log(2));
break;
}
iter++;
}
index++;
}
}
void * trender(void * a)
{
((a) = (a));
for(;;)
{
usleep((1)*1000);
pthread_mutex_lock(&mrenderline);
if(rendernextline < 0 || rendernextline >= h)
{
pthread_mutex_unlock(&mrenderline);
continue;
}
else
{
pthread_mutex_lock(&mrenderworking);
renderworking++;
pthread_mutex_unlock(&mrenderworking);
for(;;)
{
int line = rendernextline;
if(rendernextline < 0 || rendernextline >= h)
{
pthread_mutex_unlock(&mrenderline);
break;
}
rendernextline++;
pthread_mutex_unlock(&mrenderline);
renderline(line);
pthread_mutex_lock(&mrenderline);
}
}
pthread_mutex_lock(&mrenderworking);
renderworking--;
pthread_mutex_unlock(&mrenderworking);
}
}
void render(void)
{
char buffer[256];
FILE* out;
long t1, t2;
int perc = 0;
rtex = malloc(sizeof(rgb) * w * h);
memset(rtex, 0, sizeof(rgb) * w * h);
t1 = (long)time(0);
rendernextline = 0;
while(rendernextline < h || renderworking)
{
int percnew = rendernextline * 100 / h;
if(perc != percnew)
{
perc = percnew;
printf("Render: %3d%%\\n", perc);
fflush(stdout);
}
usleep((1)*1000);
}
t2 = (long)time(0);
rendernextline = -1;
printf("Done (%ld s).\\n", t2 - t1);
sprintf(buffer, "%ld.ppm", t2);
out = fopen(buffer, "wb");
fwrite(rtex, sizeof(rgb), w * h, out);
fclose(out);
free(rtex);
}
int main(int argc, char* argv[])
{
int i;
pthread_t thread;
((argc) = (argc));
pthread_mutex_init(&mrenderline, 0);
pthread_mutex_init(&mrenderworking, 0);
for(i = 0; i < atoi(argv[1]); ++i)
{
pthread_create(&thread, 0, trender, 0);
}
w = atoi(argv[2]);
h = atoi(argv[3]);
center.r = atof(argv[4]);
center.i = atof(argv[5]);
scale = atof(argv[6]);
startiter = atoi(argv[7]);
enditer = atoi(argv[8]);
maxiter = atoi(argv[9]);
er = atof(argv[10]);
eg = atof(argv[11]);
eb = atof(argv[12]);
render();
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t limite, verifica;
int counter=0;
int vetor[100];
void* imprime(void* p){
int i;
while(1){
pthread_mutex_lock(&mutex);
if(!counter || counter%10!=0){
printf("-------- AGUARDANDO ADICIONAR\\n");
pthread_cond_wait(&verifica, &mutex);
}
printf("=====================================\\n");
for(i=counter-10;i<counter;i++)
printf("vetor[%d]=%d\\n", i, vetor[i]);
printf("=====================================\\n");
counter -= 10;
pthread_cond_signal(&limite);
pthread_mutex_unlock(&mutex);
if(counter>=100)
pthread_exit(0);
}
}
void* adiciona(void *p){
while(1){
pthread_mutex_lock(&mutex);
vetor[counter] = rand()%100;
counter++;
if(counter && counter%10==0){
printf("+++++++ AGUARDANDO IMPRESSAO...\\n");
pthread_cond_signal(&verifica);
pthread_cond_wait(&limite, &mutex);
}
pthread_mutex_unlock(&mutex);
if(counter>=100)
pthread_exit(0);
}
}
int main(int argc, char **argv) {
int i;
pthread_t tid[100];
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&limite, 0);
pthread_cond_init(&verifica, 0);
srand(time(0));
pthread_create(&tid[0], 0, adiciona, (void *)(size_t) i);
pthread_create(&tid[1], 0, imprime, (void *)(size_t) i);
pthread_join(tid[0], 0);
pthread_join(tid[1], 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&limite);
pthread_cond_destroy(&verifica);
return 0;
}
| 1
|
#include <pthread.h>
struct node *next;
int refcount;
char *str;
} Node;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static Node *hashTable[32767] = {0};
static unsigned int hash(char *s) {
unsigned int ans = 0;
while (*s != '\\0')
ans = 101 * ans + *s++;
return ans % 32767;
}
char *strmalloc(char *s) {
unsigned int hval = hash(s);
Node *p;
char *ans;
pthread_mutex_lock(&lock);
for (p = hashTable[hval]; p != 0; p=p->next)
if (strcmp(s, p->str) == 0) {
ans = p->str;
p->refcount++;
pthread_mutex_unlock(&lock);
return ans;
}
p = (Node *)malloc(sizeof(Node));
if (! p) {
pthread_mutex_unlock(&lock);
return 0;
}
p->str = strdup(s);
if (! p->str) {
free(p);
pthread_mutex_unlock(&lock);
return 0;
}
ans = p->str;
p->refcount = 1;
p->next = hashTable[hval];
hashTable[hval] = p;
pthread_mutex_unlock(&lock);
return ans;
}
void strfree(char *s) {
unsigned int hval = hash(s);
Node *p, *q;
pthread_mutex_lock(&lock);
for (q = 0, p = hashTable[hval]; p != 0; q = p, p=q->next)
if (strcmp(s, p->str) == 0) {
if (--p->refcount <= 0) {
if (q == 0)
hashTable[hval] = p->next;
else
q->next = p->next;
free(p->str);
free(p);
break;
}
}
pthread_mutex_unlock(&lock);
}
void strdump(FILE *fd) {
int i;
pthread_mutex_lock(&lock);
for (i = 0; i < 32767; i++) {
Node *p;
for (p = hashTable[i]; p != 0; p = p->next)
fprintf(fd, "%8d %s\\n", p->refcount, p->str);
}
pthread_mutex_unlock(&lock);
}
| 0
|
#include <pthread.h>
static pthread_t lslogging_thread;
static pthread_mutex_t lslogging_mutex;
static pthread_cond_t lslogging_cond;
static FILE *lslogging_file;
struct timespec ltime;
char lmsg[2048];
} lslogging_queue_t;
static lslogging_queue_t lslogging_queue[8192];
static unsigned int lslogging_on = 0;
static unsigned int lslogging_off= 0;
void lslogging_init() {
pthread_mutex_init( &lslogging_mutex, 0);
pthread_cond_init( &lslogging_cond, 0);
lslogging_file = fopen( "/tmp/pgpmac.log", "w");
}
void lslogging_log_message( char *fmt, ...) {
char msg[2048];
struct timespec theTime;
va_list arg_ptr;
unsigned int on;
clock_gettime( CLOCK_REALTIME, &theTime);
__builtin_va_start((arg_ptr));
vsnprintf( msg, sizeof(msg)-1, fmt, arg_ptr);
;
msg[sizeof(msg)-1]=0;
pthread_mutex_lock( &lslogging_mutex);
on = (lslogging_on++) % 8192;
strncpy( lslogging_queue[on].lmsg, msg, 2048 - 1);
lslogging_queue[on].lmsg[2048 -1] = 0;
memcpy( &(lslogging_queue[on].ltime), &theTime, sizeof(theTime));
pthread_cond_signal( &lslogging_cond);
pthread_mutex_unlock( &lslogging_mutex);
}
void lslogging_event_cb( char *event) {
if( strcmp( event, "Timer Update KVs") != 0 && strstr( event, "accepted")==0 && strstr( event, "queued")==0) {
lslogging_log_message( "EVENT: %s", event);
}
}
void *lslogging_worker(
void *dummy
) {
struct tm coarsetime;
char tstr[64];
unsigned int msecs;
unsigned int off;
pthread_mutex_lock( &lslogging_mutex);
while( 1) {
while( lslogging_on == lslogging_off) {
pthread_cond_wait( &lslogging_cond, &lslogging_mutex);
}
off = (lslogging_off++) % 8192;
localtime_r( &(lslogging_queue[off].ltime.tv_sec), &coarsetime);
strftime( tstr, sizeof(tstr)-1, "%Y-%m-%d %H:%M:%S", &coarsetime);
tstr[sizeof(tstr)-1] = 0;
msecs = lslogging_queue[off].ltime.tv_nsec / 1000;
fprintf( lslogging_file, "%s.%.06u %s\\n", tstr, msecs, lslogging_queue[off].lmsg);
fflush( lslogging_file);
pgpmac_printf( "\\n%s", lslogging_queue[off].lmsg);
}
}
void lslogging_run() {
pthread_create( &lslogging_thread, 0, &lslogging_worker, 0);
lslogging_log_message( "Start up");
lsevents_add_listener( ".+", lslogging_event_cb);
}
| 1
|
#include <pthread.h>
int count;
int pending_posts;
} sem_t;
sem_t sem_producer;
sem_t sem_consumer;
pthread_mutex_t mut_buf = {0,0};
pthread_mutex_t mut = {0,0};
pthread_mutex_t mutp = {0,0};
void sem_init(sem_t *sem, int pshared, unsigned int value) {
sem->count = value;
sem->pending_posts = 0;
}
void sem_post(sem_t *sem) {
pthread_mutex_lock(&mut);
sem->count++;
if (sem->count <= 0) sem->pending_posts++;
pthread_mutex_unlock(&mut);
}
void sem_wait(sem_t *sem) {
pthread_mutex_lock(&mut);
int done;
sem->count--;
if (sem->count < 0) {
pthread_mutex_unlock(&mut);
sleep:
while (sem->pending_posts <= 0) {
sleep(1);
}
pthread_mutex_lock(&mutp);
if (sem->pending_posts > 0) {
done = 1;
sem->pending_posts--;
} else {
done = 0;
}
pthread_mutex_unlock(&mutp);
if (!done) {
goto sleep;
}
pthread_mutex_lock(&mut);
}
pthread_mutex_unlock(&mut);
}
int buf[4];
int first_occupied_slot = 0;
int first_empty_slot = 0;
void push_buf(int val) {
buf[first_empty_slot] = val;
first_empty_slot++;
if (first_empty_slot >= 4)
first_empty_slot = 0;
}
int take_from_buf() {
int val = buf[first_occupied_slot];
first_occupied_slot++;
if (first_occupied_slot >= 4)
first_occupied_slot = 0;
return val;
}
void *producer(void *arg) {
int work_item = 1;
while (1) {
sleep( rand() % 5 );
sem_wait(&sem_producer);
pthread_mutex_lock(&mut_buf);
push_buf(work_item++);
pthread_mutex_unlock(&mut_buf);
sem_post(&sem_consumer);
}
}
void *consumer(void *arg) {
while (1) {
int work_item;
sleep( rand() % 5 );
sem_wait(&sem_consumer);
pthread_mutex_lock(&mut_buf);
work_item = take_from_buf();
pthread_mutex_unlock(&mut_buf);
sem_post(&sem_producer);
printf("%d ", work_item);
fflush(stdout);
}
}
void run_threads(int count) {
sem_init(&sem_producer, 0, 4);
sem_init(&sem_consumer, 0, 0);
while (count > 0) {
count--;
pthread_t pp;
pthread_t cc;
int perr = pthread_create(&pp, 0, &producer, 0);
if (perr != 0) {
printf("Failed to create producer thread\\n");
}
int cerr = pthread_create(&cc, 0, &consumer, 0);
if (cerr != 0) {
printf("Failed to create consumer thread\\n");
}
}
while (1) sleep(1);
}
int main() {
run_threads(1);
return 0;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.