text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int buffer = 0;
void* producer(void* arg)
{
for(int i = 0; i < 5; ++i) {
pthread_mutex_lock(&mutex);
buffer = buffer + 1;
printf("Buffer value in PRODUCER is : %d\\n", buffer);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
printf("Producer finished\\n");
}
void* consumer(void* arg)
{
for (int i = 0; i < 5; ++i) {
pthread_mutex_lock(&mutex);
if (buffer == 0) {
printf("Consumer waiting!\\n");
pthread_cond_wait(&cond, &mutex);
}
printf("Buffer value in CONSUMER is : %d\\n", buffer);
pthread_mutex_unlock(&mutex);
}
printf("Consumer finished\\n");
}
int main()
{
pthread_t producer_thread, consumer_thread;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
pthread_create(&producer_thread, 0, producer, 0);
pthread_create(&consumer_thread, 0, consumer, 0);
pthread_join(producer_thread, 0);
pthread_join(consumer_thread, 0);
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
void exec(char * source, size_t len, char * cmd)
{
FILE * fp;
fp = popen(cmd, "r");
char * buffer = malloc(len * sizeof(char));
while (fgets(buffer, len - 1, fp) != 0);
pclose(fp);
strcpy(source, buffer);
free(buffer);
}
void query(char * dest, char * cmd, size_t len, int index)
{
char * buffer = malloc(len * sizeof(char));
exec(buffer, len, cmd);
char * str = strdup(buffer);
int pos = -1;
char * token = str, * buff = str;
while (token != 0)
{
strsep(&buff, " ");
if (strcmp(token, "") != 0)
pos++;
if (pos >= index)
{
strcpy(dest, token);
break;
}
token = buff;
}
free(buffer);
free(str);
}
unsigned long long millis()
{
struct timeval tv;
gettimeofday(&tv, 0);
unsigned long long millisecondsSinceEpoch =
(unsigned long long)(tv.tv_sec) * 1000 +
(unsigned long long)(tv.tv_usec) / 1000;
return millisecondsSinceEpoch;
}
float bandwidth = 0;
pthread_mutex_t lock;
void * netinfo(void * arg)
{
while(1)
{
FILE * fp;
fp = fopen("/sys/class/net/wlp2s0/statistics/rx_bytes", "r");
float rx_start = 0;
fscanf(fp, "%f", &rx_start);
fclose(fp);
usleep(250000);
fp = fopen("/sys/class/net/" "wlp2s0" "/statistics/rx_bytes", "r");
float rx_end = 0;
fscanf(fp, "%f", &rx_end);
fclose(fp);
pthread_mutex_lock(&lock);
bandwidth = (rx_end - rx_start) / 250;
pthread_mutex_unlock(&lock);
}
}
int main(int argc, char const *argv[])
{
setlocale(LC_ALL, "fr_FR.UTF-8");
assert(pthread_mutex_init(&lock, 0) == 0);
pthread_t netstat;
pthread_create(&netstat, 0, netinfo, 0);
printf("{ \\"version\\": 1 } \\n");
printf("[ \\n");
printf("[] \\n");
fflush(stdout);
unsigned long long T1 = 0;
unsigned long DELTA_TIME;
struct tm now;
time_t secondsSinceEpoch;
int SLEEP_SCHEDULED;
while (1)
{
T1 = millis();
char date[64] = "";
char clock[16] = "";
char freespace[16] = "";
char volume[16] = "";
char meta[132] = "";
char song[64 + 5] = "";
time(&secondsSinceEpoch);
now = *localtime(&secondsSinceEpoch);
strftime(date, 64, "%a %d %B", &now);
strftime(clock, 16, "%H:%M", &now);
char totalspace[16];
query(totalspace, "df -h " "/dev/sda2", 256, 1);
query(freespace, "df -h " "/dev/sda2", 256, 2);
float total, used;
char * pend;
total = strtof(totalspace, &pend);
char * send;
used = strtof(freespace, &send);
query(volume, "pactl list sinks | grep \\"Volume :\\"", 256, 4);
exec(meta, 132, "mpc current -f \\"%artist% - %title%\\"");
meta[strlen(meta) - 1] = '\\0';
if (strlen(meta) > 64 )
{
char buffer[140] = "";
strcat(buffer, meta);
strcat(buffer, " - ");
int pos_start = (int) ( (unsigned long long) 2 * T1 / 1000 ) % strlen(buffer);
for (int i = 0;i < 64; i++)
song[i] = buffer[ (pos_start + i) % strlen(buffer) ];
}
else if (strlen(meta) < 6)
strcpy(song, "");
else
strcpy(song, meta);
printf(",[{\\"full_text\\":\\"%s %3.1f Ko/s %s %3.1fG %s %s \\"}] \\n",
song, bandwidth, volume, (total - used), date, clock);
fflush(stdout);
DELTA_TIME = (unsigned long) millis() - T1;
SLEEP_SCHEDULED = 250 - DELTA_TIME;
if (SLEEP_SCHEDULED > 0)
usleep(SLEEP_SCHEDULED * 1000);
}
pthread_mutex_destroy(&lock);
return 0;
}
| 0
|
#include <pthread.h>
int velkost;
} Dlazdica;
int pocetDlazdic = 0;
int pozicia_na_umiestnenie = 0;
int pozicia_na_zobratie = 0;
Dlazdica *kopa[10];
int ulozeneDlazdiceMale = 0, ulozeneDlazdiceVelke = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condPomocnici = PTHREAD_COND_INITIALIZER;
pthread_cond_t condDlazdici = PTHREAD_COND_INITIALIZER;
int stoj = 0;
void uloz(int dlazdic) {
pthread_mutex_lock(&mutex);
printf("Robotnik %d zaciatok UKLADANIA \\n", dlazdic);
while(pocetDlazdic == 0){
pthread_cond_wait(&condDlazdici, &mutex);
}
Dlazdica *dlazdica = kopa[pozicia_na_zobratie];
int casSpania = dlazdica->velkost;
pozicia_na_zobratie = (pozicia_na_zobratie + 1) % 10;
pocetDlazdic--;
printf("Robotnik %d spracoval som DLAZDICU [%d] \\n", dlazdic, dlazdica->velkost);
pthread_cond_signal(&condPomocnici);
pthread_mutex_unlock(&mutex);
sleep((unsigned int)casSpania);
printf("Robotnik %d ukoncil som UKLADANIE dlazdice [%d]\\n", dlazdic, dlazdica->velkost);
free(dlazdica);
}
void *dlazdic(void *ptr) {
int dlazdic = (int) ptr;
while(!stoj) {
uloz(dlazdic);
}
return 0;
}
void poloz_malu(int pomocnik) {
sleep(1);
pthread_mutex_unlock(&mutex);
printf("Pomocnik %d idem polozit MALU\\n", pomocnik);
while(pocetDlazdic == 10){
pthread_cond_wait(&condPomocnici, &mutex);
}
kopa[pozicia_na_umiestnenie] = malloc(sizeof(Dlazdica));
kopa[pozicia_na_umiestnenie]->velkost = 2;
pozicia_na_umiestnenie = (pozicia_na_umiestnenie + 1) % 10;
pocetDlazdic++;
pthread_cond_signal(&condDlazdici);
pthread_mutex_unlock(&mutex);
}
void poloz_velku(int pomocnik) {
sleep(2);
pthread_mutex_unlock(&mutex);
printf("Pomocnik %d idem polozit VELKU\\n", pomocnik);
while(pocetDlazdic == 10){
pthread_cond_wait(&condPomocnici, &mutex);
}
kopa[pozicia_na_umiestnenie] = malloc(sizeof(Dlazdica));
kopa[pozicia_na_umiestnenie]->velkost = 3;
pozicia_na_umiestnenie = (pozicia_na_umiestnenie + 1) % 10;
pocetDlazdic++;
pthread_cond_signal(&condDlazdici);
pthread_mutex_unlock(&mutex);
}
void *pomocnik1(void *ptr) {
int pomocnik = (int) ptr;
while(!stoj) {
poloz_malu(pomocnik);
}
return 0;
}
void *pomocnik2(void *ptr) {
int pomocnik = (int) ptr;
while(!stoj) {
poloz_velku(pomocnik);
}
return 0;
}
int main(void) {
int i;
pthread_t robotnici[4 + 2];
for (i=0;i<4;i++) pthread_create(&robotnici[i], 0, &dlazdic, (void *)i);
pthread_create(&robotnici[4], 0, &pomocnik1, (void *)i);
pthread_create(&robotnici[5], 0, &pomocnik2, (void *)i);
sleep(30);
stoj = 1;
for (i=0;i<4 + 2;i++) pthread_join(robotnici[i], 0);
printf("Pocet dlazdic: VELKE %d | MALE %d\\n", pocetDlazdic);
exit(0);
}
| 1
|
#include <pthread.h>
FILE *CreateReceiveFile(char *fileName, const char *folderName)
{
char filePath[4096];
struct stat st = { 0 };
if (stat(folderName, &st) == -1) {
if (mkdir(folderName, 0777) == -1)
return 0;
}
strcpy(filePath, folderName);
strcat(filePath, "/");
strcat(filePath, fileName);
if (access(filePath, F_OK) != -1) {
char time_buf[30];
time_t now;
time(&now);
strftime(time_buf, sizeof(time_buf), "_%Y-%m-%d_%H-%M-%S", localtime(&now));
strcat(filePath, time_buf);
}
return fopen(filePath, "wb");
}
long GetFileSize(FILE * file)
{
long pos = ftell(file);
fseek(file, 0L, 2);
long fileSize = ftell(file);
fseek(file, pos, 0);
return fileSize;
}
uint64_t IpPortToNumber(uint32_t IPv4, uint16_t port)
{
return (((uint64_t) IPv4) << 16) | (uint64_t) port;
}
char *getFileSizePTR(char *str, int size)
{
for (int i = 0; i < size; i++) {
if (str[i] == ':') {
str[i] = 0;
return &str[i + 1];
}
}
return 0;
}
void safe_print(pthread_mutex_t* mutex, const char* message, ...)
{
va_list args;
__builtin_va_start((args));
pthread_mutex_lock(mutex);
vprintf(message, args);
pthread_mutex_unlock(mutex);
;
}
| 0
|
#include <pthread.h>
const char *names[5] = { "Aristotle", "Kant", "Spinoza", "Marx", "Russell" };
pthread_mutex_t forks[5];
const char *topic[5] = { "Spaghetti!", "Life", "Universe", "Everything", "Bathroom" };
void print(int y, int x, const char *fmt, ...)
{
static pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER;
va_list ap;
__builtin_va_start((ap));
pthread_mutex_lock(&screen);
printf("\\033[%d;%dH", y + 1, x), vprintf(fmt, ap);
printf("\\033[%d;%dH", 5 + 1, 1), fflush(stdout);
pthread_mutex_unlock(&screen);
}
void eat(int id)
{
int f[2], ration, i;
f[0] = f[1] = id;
f[id & 1] = (id + 1) % 5;
print(id, 12, "\\033[K");
print(id, 12, "..oO (forks, need forks)");
for (i = 0; i < 2; i++) {
pthread_mutex_lock(forks + f[i]);
if (!i) print(id, 12, "\\033[K");
print(id, 12 + (f[i] != id) * 6, "fork%d", f[i]);
sleep(1);
}
for (i = 0, ration = 3 + rand() % 8; i < ration; i++)
print(id, 24 + i * 4, "nom"), sleep(1);
for (i = 0; i < 2; i++) pthread_mutex_unlock(forks + f[i]);
}
void think(int id)
{
int i, t;
char buf[64] = {0};
do {
print(id, 12, "\\033[K");
sprintf(buf, "..oO (%s)", topic[t = rand() % 5]);
for (i = 0; buf[i]; i++) {
print(id, i+12, "%c", buf[i]);
if (i < 5) usleep(200000);
}
usleep(500000 + rand() % 1000000);
} while (t);
}
void* philosophize(void *a)
{
int id = *(int*)a;
print(id, 1, "%10s", names[id]);
while(1) think(id), eat(id);
}
int main()
{
int i, id[5];
pthread_t tid[5];
for (i = 0; i < 5; i++)
pthread_mutex_init(forks + (id[i] = i), 0);
for (i = 0; i < 5; i++)
pthread_create(tid + i, 0, philosophize, id + i);
return pthread_join(tid[0], 0);
}
| 1
|
#include <pthread.h>
pthread_t *tab;
int val;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *funcThread(void *arg){
pthread_mutex_lock(&mutex);
free(arg);
srand((unsigned int ) pthread_self());
val += (int) (10*((double)rand())/ 32767);
printf("Valeur de val : %d\\n",val);
pthread_mutex_unlock(&mutex);
pthread_exit((void*)0); return 0;
}
int main(int argc, char *argv[]) {
int i = 0;
int *pi;
int *valeur;
val = 0;
if(argc != 2)
return 1;
tab = malloc(atoi(argv[1])*sizeof(pthread_t));
for (i =0;i<atoi(argv[1]);i++) {
pi = malloc(sizeof(int));
*pi = (int) (10*((double)rand())/ 32767);
pthread_create(&tab[i],0,funcThread,pi);
}
for (i =0;i<atoi(argv[1]);i++) {
if(pthread_join(tab[i],(void**)&valeur) !=0){
printf("pthread_join\\n");
exit(1);
}
}
printf("Valeur finale : %d",val);
}
| 0
|
#include <pthread.h>
static long sum = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void thread_clean(void* arg)
{
pthread_mutex_unlock(&mutex);
}
void* thread_func(void* arg)
{
for (int i = 1; i <= 1000000; ++i)
{
pthread_cleanup_push(thread_clean,0);
pthread_mutex_lock(&mutex);
sum = sum +i;
pthread_mutex_unlock(&mutex);
pthread_cleanup_pop(0);
}
pthread_exit(0);
}
int main(void)
{
pthread_t thread_id[2];
for (int i = 0 ;i < 2; ++i)
{
pthread_create(&thread_id[i],0,thread_func,0);
}
for (int i = 0 ;i < 2; ++i)
{
pthread_join(thread_id[i],0);
}
printf("sum = %ld", sum);
return 0;
}
| 1
|
#include <pthread.h>
struct lidar_data lidar_data;
pthread_mutex_t lidar_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_t lidarthread;
const int capture_frames = 15;
struct xv11lidar_data xv11_data;
struct laser_frame *frames;
void process_frame(struct laser_frame frame) {
pthread_mutex_lock(&lidar_lock);
lidar_data.speed = frame.speed;
uint16_t index = frame.index - 0xA0;
if (!(index >= 0 && index < 360)) {
slog(300, SLOG_WARN, "Bad lidar index %d", index);
} else {
for (int i = 0; i < 4; i++) {
if (frame.readings[i].distance > 10)
lidar_data.dist[index * 4 + i] =
frame.readings[i].distance;
}
}
pthread_mutex_unlock(&lidar_lock);
}
void *lidar_loop(void *td) {
int stat;
while (1) {
stat = ReadLaser(&xv11_data, frames);
if (stat)
continue;
for (int i = 0; i < capture_frames; i++) {
process_frame(frames[i]);
}
}
return 0;
}
void init_lidar() {
memset(&lidar_data, 0, sizeof(lidar_data));
pthread_mutex_lock(&lidar_lock);
frames = calloc(capture_frames, sizeof(struct laser_frame));
if (!frames)
slog(100, SLOG_FATAL, "Can't allocate laser_frames");
int stat = InitLaser(&xv11_data, "/dev/ttyAMA0", capture_frames);
if (stat != SUCCESS) {
slog(100, SLOG_FATAL, "Failed to InitLaser");
exit(1);
}
stat = pthread_create(&lidarthread, 0, lidar_loop, 0);
if (stat) {
slog(100, SLOG_FATAL, "Can't create lidar thread");
}
pthread_mutex_unlock(&lidar_lock);
}
void close_lidar() {
pthread_cancel(lidarthread);
CloseLaser(&xv11_data);
}
| 0
|
#include <pthread.h>
static struct node * root;
pthread_mutex_t listlock = PTHREAD_MUTEX_INITIALIZER;
char * get_work(void){
pthread_mutex_lock(&listlock);
char * dirr = 0;
if(root != 0){
if(root->next != 0){
dirr = root->directory;
struct node * tempNode = root;
root = root->next;
free(tempNode);
tempNode = 0;
} else {
dirr = root->directory;
free(root);
root = 0;
}
}
pthread_mutex_unlock(&listlock);
return dirr;
}
void add_work(char * directory){
if(directory == 0 || strlen(directory) == 0)
return;
pthread_mutex_lock(&listlock);
if(root == 0){
root = (struct node *) malloc(sizeof(struct node));
root->directory = directory;
root->next = 0;
} else {
struct node * tempNode;
tempNode = (struct node *) malloc(sizeof(struct node));
tempNode->next = root;
tempNode->directory = directory;
root = tempNode;
}
pthread_mutex_unlock(&listlock);
}
bool work_queue_empty(){
pthread_mutex_lock(&listlock);
if(root == 0){
pthread_mutex_unlock(&listlock);
return 1;
}
pthread_mutex_unlock(&listlock);
return 0;
}
void freeList(){
if(root != 0){
struct node * linkedList;
struct node * tempNode;
linkedList = root;
while(linkedList->next != 0){
tempNode = linkedList->next;
free(linkedList->directory);
free(linkedList);
linkedList = tempNode;
}
free(linkedList->directory);
free(linkedList);
}
}
| 1
|
#include <pthread.h>
int g = 0;
pthread_mutex_t mutex;
void *ThreadProc(void *arg){
int i;
int l;
printf("Thread %d starting to execute\\n", *((int *)arg));
for (i=0; i < 10000000; i++){
pthread_mutex_lock(&mutex);
l = g;
l = l + 1;
g = l;
pthread_mutex_unlock(&mutex);
}
printf("Thread %d done\\n", *((int *)arg));
}
int main(int argc,char *argv[]){
pthread_t threadIds[5];
int id[5];
int i;
pthread_mutex_init(&mutex,0);
printf("Creating %d concurrent threads all changing global variable g...\\n", 5);
for(i=0; i < 5; i++){
id[i] = i+1;
pthread_create(&threadIds[i], 0, ThreadProc, &id[i]);
}
for(i=0; i < 5; i++) pthread_join(threadIds[i], 0);
pthread_mutex_destroy(&mutex);
printf("Final value of g: %d.. should be: %d\\n", g, 10000000*5);
return 0;
}
| 0
|
#include <pthread.h>
unsigned long Flag_Count;
unsigned long Flag_Threads;
unsigned long Threads_Completed;
pthread_mutex_t Lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t Job_Done = PTHREAD_COND_INITIALIZER;
long double *Thread_Rates;
void emit_help(void);
void *worker(void *ratearg);
int main(int argc, char *argv[])
{
int ch;
pthread_t *tids;
struct timespec wait;
while ((ch = getopt(argc, argv, "c:h?t:")) != -1) {
switch (ch) {
case 'c':
Flag_Count = flagtoul(ch, optarg, 1UL, ULONG_MAX);
break;
case 't':
Flag_Threads = flagtoul(ch, optarg, 1UL, ULONG_MAX);
break;
case 'h':
case '?':
default:
emit_help();
}
}
argc -= optind;
argv += optind;
if (Flag_Count == 0 || Flag_Threads == 0)
emit_help();
jkiss64_init(0);
if ((tids = calloc(sizeof(pthread_t), Flag_Threads)) == 0)
err(EX_OSERR, "could not calloc() threads list");
if ((Thread_Rates = calloc(sizeof(long double), Flag_Threads)) == 0)
err(EX_OSERR, "could not calloc() thread rates list");
for (unsigned long i = 0; i < Flag_Threads; i++) {
if (pthread_create(&tids[i], 0, worker, &Thread_Rates[i]) != 0)
err(EX_OSERR, "could not pthread_create() thread %lu", i);
}
wait.tv_sec = 3;
wait.tv_nsec = 2500000;
for (;;) {
pthread_mutex_lock(&Lock);
if (Threads_Completed == Flag_Threads)
break;
pthread_cond_timedwait(&Job_Done, &Lock, &wait);
pthread_mutex_unlock(&Lock);
}
for (unsigned long i = 0; i < Flag_Threads; i++) {
printf("thread[%lu] %.6Lf\\n", i, Thread_Rates[i]);
}
exit(0);
}
void emit_help(void)
{
fprintf(stderr, "Usage: threadrate -c count -t threads\\n");
exit(EX_USAGE);
}
void *worker(void *ratearg)
{
struct timespec before, after;
long double delta_t, *ratep;
uint64_t r;
jkiss64_init_thread();
ratep = ratearg;
if (clock_gettime(CLOCK_REALTIME, &before) == -1)
err(EX_OSERR, "clock_gettime() failed");
for (unsigned long c = 0; c < Flag_Count; c++) {
r = jkiss64_rand();
}
if (clock_gettime(CLOCK_REALTIME, &after) == -1)
err(EX_OSERR, "clock_gettime() failed");
delta_t =
(after.tv_sec - before.tv_sec) + (after.tv_nsec -
before.tv_nsec) /
(long double) 1000000000;
*ratep = Flag_Count / delta_t;
pthread_mutex_lock(&Lock);
Threads_Completed++;
pthread_mutex_unlock(&Lock);
pthread_cond_signal(&Job_Done);
return (void *) 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t m;
struct param{
char *frase;
int numero;
};
void hiloMensaje(struct param *mensa){
printf("%s %d \\n", mensa->frase, mensa->numero);
}
void tablas(int num){
int i=0;
pthread_mutex_lock(&m);
while(i<6)
{
printf("%d * %d = %d \\n",num,i,(i*i));
i++;
}
float a = 254 , b =65651,c=484515;
int cont=0;
while (cont<100000000 ){
a=b*c;
b=(c*c*c + a)/365 ;
cont++;
}
char str[200] = "ps -aux | grep mutex_hilos ";
system(str);
pthread_mutex_unlock(&m);
}
int main(){
system("clear");
pthread_t tid[2];
struct param parametro1 ={"I am the thread number ",1 };
struct param parametro2 ={"I am other thread, I am the ",2 };
int p1= 14;
int p3 = 7;
pthread_create(&(tid[0]) ,0,(void*)tablas, (void*) p1 );
pthread_create(&(tid[1]) ,0,(void*)tablas, (void*) p3 );
pthread_join(tid[0],0 );
pthread_join(tid[1], 0);
return 0;
}
| 0
|
#include <pthread.h>
int count = 0 , flag = 0 ;
pthread_mutex_t mutex ;
pthread_cond_t cond ;
void *window1_sell(void *arg)
{
printf("thd1 :\\n");
while(1)
{
pthread_mutex_lock(&mutex);
if(count > 0)
{
flag = 1 ;
count-- ;
printf("thd1 sold 1 , left :%d\\n ",count);
pthread_mutex_unlock(&mutex) ;
sleep(1);
}
else if(flag == 0 && count == 0)
{
pthread_cond_wait(&cond , &mutex);
pthread_mutex_unlock(&mutex);
sleep(1);
printf("thd1 begin :\\n");
}
else if(flag ==1 && count == 0)
{
pthread_cond_wait(&cond , &mutex);
pthread_mutex_unlock(&mutex);
}
}
pthread_exit((void *)1);
}
void *window2_sell(void *arg)
{
printf("thd2 :\\n");
while(1)
{
pthread_mutex_lock(&mutex);
if(count > 0)
{
flag = 1 ;
count-- ;
printf("thd2 sold 1 , left :%d\\n ",count);
pthread_mutex_unlock(&mutex) ;
sleep(1);
}
else if(flag == 0 && count == 0)
{
pthread_cond_wait(&cond , &mutex);
pthread_mutex_unlock(&mutex);
sleep(1);
printf("thd2 begin :\\n");
}
else if(flag ==1 && count == 0)
{
pthread_cond_wait(&cond , &mutex);
pthread_mutex_unlock(&mutex);
}
}
pthread_exit((void *)2);
}
int main(int argc , char *argv[])
{
pthread_t thd1 , thd2 ;
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond , 0);
pthread_create(&thd1 , 0 , window1_sell , 0);
pthread_create(&thd2 , 0 , window2_sell , 0);
sleep(5);
while(1)
{
pthread_mutex_lock(&mutex);
if(flag == 0 && count == 0)
{
printf("Begin :\\n");
count = 20 ;
}
else if(flag == 1 && count == 0)
{
printf("Begin again :\\n");
count = 10 ;
}
pthread_mutex_unlock(&mutex);
pthread_cond_broadcast(&cond);
sleep(2);
}
int status1 , status2 ;
pthread_join(thd1 , (void *)&status1);
pthread_join(thd2 , (void *)&status2);
printf("%d %d\\n",status1 , status2);
return 0 ;
}
| 1
|
#include <pthread.h>
static struct {
pthread_mutex_t mutex;
struct tcp_server server;
} house;
static void new_session(struct tcp_client *s_client, void *data)
{
struct command cmd;
if (!tcp_client_recv(s_client, (void *)&cmd, sizeof(struct command))) {
pthread_mutex_lock(&house.mutex);
log_local("Fail receiving command.", LOG_ERROR);
pthread_mutex_unlock(&house.mutex);
return;
}
switch (cmd.code) {
case TERMO_ON: {
pthread_mutex_lock(&house.mutex);
if (!termo_control_on())
log_local("Termocontrol: fail switching on", LOG_ERROR);
else
puts("Termocontrol: switching on [OK]");
pthread_mutex_unlock(&house.mutex);
break;
}
case TERMO_OFF: {
pthread_mutex_lock(&house.mutex);
if (!termo_control_off())
log_local("Termocontrol: fail switching off", LOG_ERROR);
else
puts("Termocontrol: switching off [OK]");
pthread_mutex_unlock(&house.mutex);
break;
}
case TERMO_GET_TEMP: {
struct termo_temp_answ answ;
termo_get_temp(&answ.temp);
if (!tcp_client_send(s_client, (const void *)&answ, sizeof(struct termo_temp_answ))) {
pthread_mutex_lock(&house.mutex);
log_local("Fail sending termo temp answ.", LOG_ERROR);
pthread_mutex_unlock(&house.mutex);
return;
}
break;
}
case TERMO_SET_TEMP: {
struct termo_temp_answ ttemp;
if (!tcp_client_recv(s_client, (void *)&ttemp, sizeof(struct termo_temp_answ))) {
pthread_mutex_lock(&house.mutex);
log_local("Fail receiving new termo temperature.", LOG_ERROR);
pthread_mutex_unlock(&house.mutex);
return;
}
pthread_mutex_lock(&house.mutex);
if (!termo_set_temp(ttemp.temp))
log_local("Termocontrol: fail changing temperature.", LOG_ERROR);
pthread_mutex_unlock(&house.mutex);
break;
}
case TERMO_GET_STATUS: {
struct termo_stat_answ answ;
termo_get_status(&answ.status, &answ.heater_status);
if (!tcp_client_send(s_client, (const void *)&answ, sizeof(struct termo_stat_answ))) {
pthread_mutex_lock(&house.mutex);
log_local("Fail sending termo status answ.", LOG_ERROR);
pthread_mutex_unlock(&house.mutex);
return;
}
break;
}
case SECURITY_SET_ON: {
security_set_on();
break;
}
case SECURITY_SET_OFF: {
security_set_off();
break;
}
case SECURITY_GET_STATUS: {
struct sec_stat_answ answ;
security_get_status(&answ.status);
if (!tcp_client_send(s_client, (const void *)&answ, sizeof(struct sec_stat_answ))) {
pthread_mutex_lock(&house.mutex);
log_local("Fail sending security status answ.", LOG_ERROR);
pthread_mutex_unlock(&house.mutex);
return;
}
break;
}
case GET_METEO: {
struct meteo_answ answ;
meteo_get_street_data(&answ.street_temp, &answ.street_hum);
meteo_get_room_data(&answ.room_temp, &answ.room_hum);
meteo_get_veranda_data(&answ.veranda_temp, &answ.veranda_hum);
meteo_get_2nd_data(&answ.second_temp, &answ.second_hum);
if (!tcp_client_send(s_client, (const void *)&answ, sizeof(struct meteo_answ))) {
pthread_mutex_lock(&house.mutex);
log_local("Fail sending meteo answ.", LOG_ERROR);
pthread_mutex_unlock(&house.mutex);
return;
}
break;
}
case GET_CAM_PHOTO: {
struct command answ;
if (!tcp_client_recv(s_client, (void *)&cmd, sizeof(struct command))) {
pthread_mutex_lock(&house.mutex);
log_local("Fail receiving cam number.", LOG_ERROR);
pthread_mutex_unlock(&house.mutex);
return;
}
if (!cam_get_photo(s_client, cmd.code, &house.mutex))
return;
answ.code = PHOTO_OK;
if (!tcp_client_send(s_client, &answ, sizeof(struct command))) {
pthread_mutex_lock(&house.mutex);
log_local("Fail sending answ.", LOG_ERROR);
pthread_mutex_unlock(&house.mutex);
return;
}
break;
}
}
}
bool house_server_start(void)
{
const struct server_cfg *sc = configs_get_server();
puts("Starting House server...");
pthread_mutex_init(&house.mutex, 0);
if (!meteo_sensors_init()) {
log_local("Fail initialization GPIO ports.", LOG_ERROR);
return 0;
}
meteo_sensors_start_timer(&house.mutex);
if (!security_start()) {
log_local("Fail loading security extended configs.", LOG_ERROR);
return 0;
}
if (!termo_start()) {
log_local("Fail loading termo extended configs.", LOG_ERROR);
return 0;
}
tcp_server_set_newsession_cb(&house.server, new_session, 0);
if (!tcp_server_bind(&house.server, sc->port, sc->max_users)) {
log_local("Fail binding House server.", LOG_ERROR);
return 0;
}
pthread_mutex_destroy(&house.mutex);
return 1;
}
| 0
|
#include <pthread.h>
pthread_mutex_t m;
int seed;
int PseudoRandomUsingAtomic_nextInt(int n) {
int read, nexts, nextInt_return;
pthread_mutex_lock(&m);
read = seed;
do {
nexts = __nondet_int();
} while(nexts == read || nexts == 0);
assert(nexts != read);
seed = nexts;
pthread_mutex_unlock(&m);
return nexts % n;
}
void PseudoRandomUsingAtomic_monitor(){
while(1) {
assert(seed != 0);
}
}
void PseudoRandomUsingAtomic_constructor(int init){
seed = init;
}
void PseudoRandomUsingAtomic__threadmain(){
int myrand;
myrand = PseudoRandomUsingAtomic_nextInt(10);
assert(myrand <= 10);
}
int state = 0;
void* thr1(void* arg)
{
pthread_mutex_lock(&m);
switch(state) {
case 0:
PseudoRandomUsingAtomic_constructor(1);
state = 1;
pthread_mutex_unlock(&m);
PseudoRandomUsingAtomic_monitor();
break;
case 1:
pthread_mutex_unlock(&m);
PseudoRandomUsingAtomic__threadmain();
break;
}
return 0;
}
int main()
{
pthread_t t1,t2,t3;
pthread_create(&t1, 0, thr1, 0);
pthread_create(&t2, 0, thr1, 0);
pthread_create(&t3, 0, thr1, 0);
return 0;
}
| 1
|
#include <pthread.h>
int g_buffer[10];
unsigned short in = 0;
unsigned short out = 0;
unsigned short produce_id = 0;
unsigned short consume_id = 0;
sem_t g_sem_full;
sem_t g_sem_empty;
pthread_mutex_t g_mutex;
pthread_t g_thread[1 + 1];
void *consume(void *arg) {
int inx = *((int *) arg);
free(arg);
int i;
while (1) {
printf("%d wait buffer empty\\n", inx);
sem_wait(&g_sem_empty);
pthread_mutex_lock(&g_mutex);
for (i = 0; i < 10; ++i) {
printf("%02d ", i);
if (-1==g_buffer[i]) {
printf("null");
} else {
printf("%d ", g_buffer[i]);
}
if (i==in) {
printf("\\t<--consume");
}
printf("\\n");
}
consume_id = g_buffer[out];
printf("%d begin consume product %d\\n", inx, consume_id);
g_buffer[out] = -1;
out = (out + 1)%10;
printf("%d end consume product %d\\n", inx, consume_id);
pthread_mutex_unlock(&g_mutex);
sem_post(&g_sem_full);
sleep(1);
}
return 0;
}
void *produce(void *arg) {
int inx = *((int *) arg);
free(arg);
int i;
while (1) {
printf("%d wait buffer full\\n", inx);
sem_wait(&g_sem_full);
pthread_mutex_lock(&g_mutex);
for (i = 0; i < 10; ++i) {
printf("%02d ", i);
if (-1==g_buffer[i]) {
printf("null");
} else {
printf("%d ", g_buffer[i]);
}
if (i==in) {
printf("\\t<--produce");
}
printf("\\n");
}
printf("%d begin produce product %d\\n", inx, produce_id);
g_buffer[in] = produce_id;
in = (in + 1)%10;
printf("%d end produce product %d\\n", inx, produce_id++);
pthread_mutex_unlock(&g_mutex);
sem_post(&g_sem_empty);
sleep(1);
}
return 0;
}
int main(int argc, char *argv[]) {
sem_init(&g_sem_full, 0, 10);
sem_init(&g_sem_empty, 0, 0);
pthread_mutex_init(&g_mutex, 0);
int ret, i, *p;
for (i = 0; i < 10; ++i) {
g_buffer[i] = -1;
}
for (i = 0; i < 1; ++i) {
p = (int *) malloc(sizeof(int));
*p = i;
ret = pthread_create(&g_thread[i], 0, consume, p);
if (ret!=0) {
fprintf(stderr, "pthread_create:%s\\n", strerror(ret));
exit(1);
}
}
for (i = 0; i < 1; ++i) {
p = (int *) malloc(sizeof(int));
*p = i;
ret = pthread_create(&g_thread[1 + i],
0, produce, p);
if (ret!=0) {
fprintf(stderr, "pthread_create:%s\\n", strerror(ret));
exit(1);
}
}
for (i = 0; i < 1 + 1; ++i) {
ret = pthread_join(g_thread[i], 0);
if (ret!=0) {
fprintf(stderr, "pthread_join:%s\\n", strerror(ret));
exit(1);
}
}
sem_destroy(&g_sem_full);
sem_destroy(&g_sem_empty);
pthread_mutex_destroy(&g_mutex);
return 0;
}
| 0
|
#include <pthread.h>
int controladora = 0;
pthread_mutex_t x_mutex;
pthread_cond_t x_cond;
void barreira(int nthreads)
{
pthread_mutex_lock(&x_mutex);
controladora++;
if(controladora < nthreads){
pthread_cond_wait(&x_cond, &x_mutex);
} else {
controladora = 0;
pthread_cond_broadcast(&x_cond);
}
pthread_mutex_unlock(&x_mutex);
}
void * A (void * arg) {
int tid = * (int *) arg, i;
int cont = 0, boba1, boba2;
for (i=0; i < 5; i++) {
cont++;
printf("Thread %d: cont=%d, passo=%d\\n", tid, cont, i);
barreira(5);
boba1=100; boba2=-100; while (boba2 < boba1) boba2++;
}
free(arg);
pthread_exit(0);
}
int main(int argc, char *argv[]) {
int i, * tid;
pthread_t threads[5];
pthread_mutex_init(&x_mutex, 0);
pthread_cond_init (&x_cond, 0);
for (i = 0; i < 5; i++) {
tid = (int *) malloc(sizeof(int));
*tid = i;
pthread_create(&threads[i], 0, A,(void *) tid); }
for (i = 0; i < 5; i++) {
pthread_join(threads[i], 0);
}
printf ("*\\nFIM\\n");
pthread_mutex_destroy(&x_mutex);
pthread_cond_destroy(&x_cond);
pthread_exit (0);
}
| 1
|
#include <pthread.h>
void *hilo1(void *p);
void *hilo2(void *p);
void *hilo3(void *p);
void *hilo4(void *p);
int flag = 0;
pthread_cond_t v1;
pthread_cond_t v2;
pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER ;
pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER ;
int main(int argc, char **argv){
pthread_cond_init(&v1, 0);
pthread_t h1;
pthread_t h2;
pthread_create(&h2, 0, hilo2, 0);
pthread_create(&h1, 0, hilo1, 0);
pthread_join(h2, 0);
printf("fin main\\n");
return 0;
}
void *hilo1(void *p){
pthread_mutex_lock(&m1);
printf("Soy el hilo1, señalizo v1..\\n");
flag = 1;
pthread_cond_broadcast(&v1);
printf("Termino hilo1 \\n");
pthread_mutex_unlock(&m1);
pthread_exit(0);
}
void *hilo2(void *p){
printf("Soy el hilo2, muestro flag %i\\n", flag);
pthread_mutex_lock(&m2);
if ( !flag ) printf("esperando v1..\\n");
pthread_cond_wait(&v1, &m2);
sleep(3);
printf("Me desperte! (hilo2), muestro flag %i\\n", flag);
pthread_mutex_unlock(&m2);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int mdlist_pqueue_coarse_enq
(struct mdlist_pqueue_head_coarse *mdlist_queue_coarse_head,
struct mdlist_pqueue_node *node)
{
int retval;
if (!mdlist_queue_coarse_head || !node)
return -EINVAL;
pthread_mutex_lock(&mdlist_queue_coarse_head->lock);
retval = mdlist_pqueue_enq(&mdlist_queue_coarse_head->head, node);
pthread_mutex_unlock(&mdlist_queue_coarse_head->lock);
return retval;
}
struct mdlist_pqueue_node *mdlist_pqueue_coarse_contains(
struct mdlist_pqueue_head_coarse *mdlist_queue_coarse_head, uint32_t key)
{
struct mdlist_pqueue_node *node;
if (!mdlist_queue_coarse_head)
return 0;
pthread_mutex_lock(&mdlist_queue_coarse_head->lock);
node = mdlist_pqueue_contains(&mdlist_queue_coarse_head->head, key);
pthread_mutex_unlock(&mdlist_queue_coarse_head->lock);
return node;
}
struct mdlist_pqueue_node *mdlist_pqueue_coarse_deq(
struct mdlist_pqueue_head_coarse *mdlist_queue_coarse_head)
{
struct mdlist_pqueue_node *node;
if (!mdlist_queue_coarse_head)
return 0;
pthread_mutex_lock(&mdlist_queue_coarse_head->lock);
node = mdlist_pqueue_deq(&mdlist_queue_coarse_head->head);
pthread_mutex_unlock(&mdlist_queue_coarse_head->lock);
return node;
}
struct mdlist_pqueue_node *mdlist_pqueue_coarse_deq_key(
struct mdlist_pqueue_head_coarse *mdlist_queue_coarse_head, uint32_t key)
{
struct mdlist_pqueue_node *node;
if (!mdlist_queue_coarse_head)
return 0;
pthread_mutex_lock(&mdlist_queue_coarse_head->lock);
node = mdlist_pqueue_deq_key(&mdlist_queue_coarse_head->head, key);
pthread_mutex_unlock(&mdlist_queue_coarse_head->lock);
return node;
}
struct mdlist_pqueue_head_coarse *mdlist_pqueue_coarse_alloc(void)
{
struct mdlist_pqueue_head_coarse *mdlist_coarse;
mdlist_coarse = (struct mdlist_pqueue_head_coarse *)
malloc(sizeof(*mdlist_coarse));
if (!mdlist_coarse)
return 0;
pthread_mutex_init(&mdlist_coarse->lock, 0);
mdlist_pqueue_init_head(&mdlist_coarse->head);
return mdlist_coarse;
}
void mdlist_pqueue_coarse_dealloc
(struct mdlist_pqueue_head_coarse *mdlist_pqueue_coarse)
{
pthread_mutex_destroy(&mdlist_pqueue_coarse->lock);
free(mdlist_pqueue_coarse);
}
void mdlist_pqueue_coarse_init
(struct mdlist_pqueue_head_coarse *mdlist_pqueue_coarse)
{
if (!mdlist_pqueue_coarse)
return;
pthread_mutex_init(&mdlist_pqueue_coarse->lock, 0);
}
| 1
|
#include <pthread.h>
static struct rsocket *sockets = 0;
static int64_t num_rsockets = 0;
static int64_t new_rsockets = 0;
static int server_port = 0;
static int hard_fail = 0;
static char *hostname = 0;
pthread_t server_thread;
static pthread_mutex_t socket_lock = PTHREAD_MUTEX_INITIALIZER;
void ignore_error_cb(int ignore) { }
int64_t _find_socket_from_magic(uint64_t magic, int lock) {
int64_t i;
if (lock) pthread_mutex_lock(&socket_lock);
for (i=0; i<num_rsockets; i++)
if (sockets[i].magic == magic) break;
if (lock) pthread_mutex_unlock(&socket_lock);
return i;
}
void *server_pthread(void *args) {
int64_t i;
int portnum, s=-1;
char port[20];
struct rsocket r;
pthread_mutex_lock(&socket_lock);
for (i=0; i<5000&&s<0; i+=29) {
portnum = server_port + i;
snprintf(port, 10, "%d", portnum);
s = listen_at_addr(hostname, port);
}
if (i>=5000) {
if (hard_fail>0) {
fprintf(stderr, "[Error] Couldn't start server at %s:%d-%d!\\n",
hostname, server_port, portnum);
exit(1);
} else {
hard_fail = -1;
pthread_mutex_unlock(&socket_lock);
pthread_exit(0);
}
}
server_port = portnum;
pthread_mutex_unlock(&socket_lock);
r.address = 0;
r.flags = RECEIVER_FLAG | NEW_FLAG;
while (1) {
r.fd = accept_connection(s, &r.address, &r.port);
recv_from_socket(r.fd, &r.magic, sizeof(uint64_t));
pthread_mutex_lock(&socket_lock);
i = _find_socket_from_magic(r.magic, 0);
if (i<num_rsockets) {
close(sockets[i].fd);
free(sockets[i].address);
sockets[i] = r;
sockets[i].flags -= sockets[i].flags & NEW_FLAG;
} else {
if (!(num_rsockets%10))
sockets = socket_check_realloc(sockets, (num_rsockets+10)*
sizeof(struct rsocket), "Rsockets");
sockets[num_rsockets] = r;
num_rsockets++;
new_rsockets++;
}
pthread_mutex_unlock(&socket_lock);
}
pthread_exit(0);
}
int start_server(char *host, int port, int fail) {
pthread_mutex_lock(&socket_lock);
hostname = host;
server_port = port;
hard_fail = fail;
pthread_mutex_unlock(&socket_lock);
set_network_io_error_cb(ignore_error_cb, 0);
return pthread_create(&server_thread, 0, server_pthread, 0);
}
struct rsocket refresh_rsocket(struct rsocket r)
{
int64_t i = _find_socket_from_magic(r.magic, 1);
if (i<num_rsockets) return sockets[i];
return r;
}
struct rsocket connect_rsocket(char *address, int portnum) {
struct rsocket r;
char port[10];
r.address = 0;
r.port = portnum;
snprintf(port, 10, "%d", r.port);
r.flags = 0;
r.magic = ((uint64_t)rand()) << (uint64_t)32;
r.magic += rand();
r.fd = connect_to_addr(address, port);
if (r.fd < 0) return r;
r.address = strdup(address);
pthread_mutex_lock(&socket_lock);
if (!(num_rsockets%10))
sockets = socket_check_realloc(sockets, (num_rsockets+10)*
sizeof(struct rsocket), "Rsockets");
sockets[num_rsockets] = r;
num_rsockets++;
pthread_mutex_unlock(&socket_lock);
return r;
}
struct rsocket reconnect_rsocket(struct rsocket r)
{
char port[10];
struct rsocket new_rsocket;
if (r.flags & RECEIVER_FLAG) return refresh_rsocket(r);
int64_t i = _find_socket_from_magic(r.magic, 1);
snprintf(port, 10, "%d", r.port);
if (i==num_rsockets) {
new_rsocket = connect_rsocket(r.address, r.port);
free(r.address);
r = new_rsocket;
} else {
r.fd = connect_to_addr(r.address, port);
pthread_mutex_lock(&socket_lock);
sockets[i].fd = r.fd;
pthread_mutex_unlock(&socket_lock);
if (r.fd > -1) send_to_socket(r.fd, &r.magic, sizeof(uint64_t));
}
return r;
}
void close_rsocket(struct rsocket r) {
int64_t i = _find_socket_from_magic(r.magic, 1);
if (i<num_rsockets) {
pthread_mutex_lock(&socket_lock);
if (sockets[i].address) free(sockets[i].address);
if (sockets[i].fd > -1) close(sockets[i].fd);
sockets[i] = sockets[num_rsockets-1];
num_rsockets--;
pthread_mutex_unlock(&socket_lock);
}
}
int64_t send_to_rsocket(struct rsocket *r, void *data, int64_t length) {
int64_t sent;
assert(r->fd >= 0);
while (r->fd < 0 || ((sent = send_to_socket(r->fd, data, length)) < 0)) {
select_fd(-1, 0, 0);
*r = reconnect_rsocket(*r);
}
return sent;
}
int64_t recv_from_rsocket(struct rsocket *r, void *data, int64_t length) {
int64_t recvd;
assert(r->fd >= 0);
while (r->fd < 0 || ((recvd = recv_from_socket(r->fd, data, length)) < 0)) {
select_fd(-1, 0, 0);
*r = reconnect_rsocket(*r);
}
return recvd;
}
void *recv_and_alloc_r(struct rsocket *r, void *data, int64_t length) {
data = socket_check_realloc(data, length, "receive buffer");
assert(data != 0 || length <= 0);
recv_from_rsocket(r, data, length);
return data;
}
int64_t send_msg_r(struct rsocket *r, void *data, int64_t length) {
send_to_rsocket(r, &length, sizeof(int64_t));
return send_to_rsocket(r, data, length);
}
void *recv_msg_r(struct rsocket *r, void *data, int64_t *length, int64_t offset) {
int64_t incoming;
if (recv_from_rsocket(r, &incoming, sizeof(int64_t))<0) return data;
if (*length < (offset + incoming)) {
data = socket_check_realloc(data, offset + incoming, "receive buffer");
assert(data != 0);
*length = offset+incoming;
}
recv_from_rsocket(r, data+offset, incoming);
return data;
}
void *recv_msg_nolength_r(struct rsocket *r, void *data) {
int64_t length = 0;
return(recv_msg_r(r, data, &length, 0));
}
| 0
|
#include <pthread.h>
int producir();
void * productor();
void * consumidor();
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cp = PTHREAD_COND_INITIALIZER,
cc = PTHREAD_COND_INITIALIZER;
int in = 0,
out = 0,
buffer_elements = 0,
buffer [10];
int main(){
pthread_t prod, cons;
pthread_create(&prod, 0, productor, 0);
pthread_create(&cons, 0, consumidor, 0);
pthread_join(prod, 0);
pthread_join(cons, 0);
exit(0);
};
void * productor(){
int newProduct;
while(1){
newProduct = producir();
pthread_mutex_lock(&m);
if (buffer_elements == 10) {
pthread_cond_wait(&cp, &m);
};
buffer [in] = newProduct;
in = (in + 1) % 10;
buffer_elements ++;
printf("productor(): agregué %c\\n", newProduct);
pthread_cond_signal(&cc);
pthread_mutex_unlock(&m);
};
};
void * consumidor(){
int auxProduct;
sleep(12);
while(1){
pthread_mutex_lock(&m);
if (buffer_elements == 0) {
pthread_cond_wait(&cc, &m);
};
auxProduct = buffer [out];
out = (out + 1) % 10;
buffer_elements --;
printf("consumidor(): saqué %c\\n", auxProduct);
pthread_cond_signal(&cp);
pthread_mutex_unlock(&m);
};
};
int producir(){
static int letra = 'A'-1 ;
if (letra == 'Z') {
letra = 'A';
} else {
letra++ ;
};
sleep(1);
return letra ;
};
| 1
|
#include <pthread.h>
void * readFunc(void * myvar);
void * writeFunc(void * myvar);
pthread_mutex_t lock;
int a[500];
int main (int argc, char * argv[])
{
pthread_t thread1, thread2;
char * msg1 = "First thread";
char * msg2 = "Second thread";
int ret1, ret2;
memset(a, 0, sizeof(a));
ret1 = pthread_create(&thread1, 0, writeFunc, (void *) msg1);
ret2 = pthread_create(&thread2, 0, readFunc, (void *) msg2);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
printf("First thread ret1 = %d\\n", ret1);
printf("Second thread ret2 = %d\\n", ret2);
return 0;
}
void * writeFunc(void * myvar){
char * msg;
msg = (char *) myvar;
int i;
printf("msg: %s\\n", msg);
pthread_mutex_lock(&lock);
for (i = 0; i < 500; i++){
printf("X");
a[i] = i;
}
pthread_mutex_unlock(&lock);
}
void * readFunc(void * myvar){
char * msg;
msg = (char *) myvar;
int i;
printf("msg: %s\\n", msg);
pthread_mutex_lock(&lock);
for (i = 0; i < 500; i++){
printf("%d, ", a[i]);
}
pthread_mutex_unlock(&lock);
}
| 0
|
#include <pthread.h>
int klvanc_cache_alloc(struct klvanc_context_s *ctx)
{
ctx->cacheLines = calloc(0x10000, sizeof(struct klvanc_cache_s));
if (!ctx->cacheLines)
return -1;
return 0;
}
void klvanc_cache_free(struct klvanc_context_s *ctx)
{
klvanc_cache_reset(ctx);
if (ctx->cacheLines) {
free(ctx->cacheLines);
ctx->cacheLines = 0;
}
}
struct klvanc_cache_s * klvanc_cache_lookup(struct klvanc_context_s *ctx, uint8_t didnr, uint8_t sdidnr)
{
if (!ctx)
return 0;
if (!ctx->cacheLines)
return 0;
return &ctx->cacheLines[ (((didnr) << 8) | (sdidnr)) ];
};
int klvanc_cache_update(struct klvanc_context_s *ctx, struct klvanc_packet_header_s *pkt)
{
if (!ctx)
return -1;
if (!ctx->cacheLines)
return -1;
if (pkt->did > 0xff)
return -1;
if (pkt->dbnsdid > 0xff)
return -1;
if (pkt->lineNr >= 2048)
return -1;
struct klvanc_cache_s *s = klvanc_cache_lookup(ctx, pkt->did, pkt->dbnsdid);
if (s->activeCount == 0) {
s->did = pkt->did;
s->sdid = pkt->dbnsdid;
s->desc = klvanc_lookupDescriptionByType(pkt->type);
s->spec = klvanc_lookupSpecificationByType(pkt->type);
}
gettimeofday(&s->lastUpdated, 0);
struct klvanc_cache_line_s *line = &s->lines[ pkt->lineNr ];
line->active = 1;
s->activeCount++;
pthread_mutex_lock(&line->mutex);
if (line->pkt) {
klvanc_packet_free(line->pkt);
line->pkt = 0;
}
klvanc_packet_copy(&line->pkt, pkt);
pthread_mutex_unlock(&line->mutex);
line->count++;
return 0;
}
void klvanc_cache_reset(struct klvanc_context_s *ctx)
{
if (!ctx)
return;
if (!ctx->cacheLines)
return;
for (int d = 0; d <= 0xff; d++) {
for (int s = 0; s <= 0xff; s++) {
struct klvanc_cache_s *e = klvanc_cache_lookup(ctx, d, s);
e->activeCount = 0;
for (int l = 0; l < 2048; l++) {
struct klvanc_cache_line_s *line = &e->lines[ l ];
if (!line->active)
continue;
line->active = 0;
line->count = 0;
pthread_mutex_lock(&line->mutex);
if (line->pkt) {
klvanc_packet_free(line->pkt);
line->pkt = 0;
}
pthread_mutex_unlock(&line->mutex);
}
}
}
}
| 1
|
#include <pthread.h>
struct {
int status;
char buffer[65];
} data;
pthread_t tid_1, tid_2;
pthread_mutex_t mutex_x = PTHREAD_MUTEX_INITIALIZER;
void *thread_1(void *arg) {
char filename[20];
FILE *fp;
memset(filename, '\\0', 20);
strcpy(filename, arg);
strcat(filename, ".1");
fp = fopen(filename, "w");
while (1) {
pthread_mutex_lock(&mutex_x);
if (data.status != 0) {
pthread_mutex_unlock(&mutex_x);
if (data.status == 3)
break;
else
continue;
}
fprintf(fp, "%s\\n", data.buffer);
data.status = 4;
pthread_mutex_unlock(&mutex_x);
}
fclose(fp);
return ((void *)0);
}
void *thread_2(void *arg) {
char filename[20];
FILE *fp;
memset(filename, '\\0', 20);
strcpy(filename, arg);
strcat(filename, ".2");
fp = fopen(filename, "w");
while (1) {
pthread_mutex_lock(&mutex_x);
if (data.status != 1) {
pthread_mutex_unlock(&mutex_x);
if (data.status == 3)
break;
else
continue;
}
fprintf(fp, "%s\\n", data.buffer);
data.status = 4;
pthread_mutex_unlock(&mutex_x);
}
fclose(fp);
return ((void *)0);
}
int main(int argc, char *argv[]) {
FILE *fp = fopen(argv[1], "r");
void *status;
int temp;
int i;
char ch;
int line_no = 1;
if (argc != 2)
exit(0);
if ((temp = pthread_create(&tid_1, 0, thread_1, argv[1])) != 0) {
printf("can't create thread\\n");
return 1;
}
if ((temp = pthread_create(&tid_2, 0, thread_2, argv[1])) != 0) {
printf("can't create thread\\n");
return 1;
}
data.status = 4;
while (1) {
if (feof(fp))
break;
while (data.status != 4);
i = 0;
while ((ch = fgetc(fp)) != '\\n' && !feof(fp))
data.buffer[i++] = ch;
data.buffer[i] = '\\0';
data.status = line_no % 2 == 0 ? 1 : 0;
line_no++;
}
data.status = 3;
fclose(fp);
pthread_join(tid_1, &status);
pthread_join(tid_2, &status);
return 0;
}
| 0
|
#include <pthread.h>
int producer(void * args);
int consumer(void * args);
pthread_mutex_t mutex;
sem_t product;
sem_t warehouse;
char buffer[8][4];
int bp=0;
main(int argc,char** argv)
{
pthread_mutex_init(&mutex,0);
sem_init(&product,0,0);
sem_init(&warehouse,0,8);
int clone_flag,arg,retval;
char * stack;
clone_flag=CLONE_VM|CLONE_SIGHAND|CLONE_FS|CLONE_FILES;
int i;
for(i=0;i<2;i++)
{
arg=i;
stack=(char *)malloc(4096);
retval=clone((void *)producer,&(stack[4095]),clone_flag,(void *)&arg);
stack=(char *)malloc(4096);
retval=clone((void *)consumer,&(stack[4095]),clone_flag,(void *)&arg);
sleep(1);
}
exit(1);
}
int producer(void * args)
{
int id=*((int *)args);
int i;
for(i=0;i<10;i++)
{
sleep(i+1);
sem_wait(&warehouse);
pthread_mutex_lock(&mutex);
if(id==0)
strcpy(buffer[bp],"aaa\\0");
else
strcpy(buffer[bp],"bbb\\0");
bp++;
printf("producer%d producer %s in %d\\n",id,buffer[bp-1],bp-1);
pthread_mutex_unlock(&mutex);
sem_post(&product);
}
printf("producer%d is over! \\n",id);
}
int consumer(void * args)
{
int id=*((int *)args);
int i;
for(i=0;i<10;i++)
{
sleep(10-i);
sem_wait(&product);
pthread_mutex_lock(&mutex);
bp--;
printf("consumer%d get %s in %d\\n",id,buffer[bp],bp);
strcpy(buffer[bp],"zzz\\0");
pthread_mutex_unlock(&mutex);
sem_post(&warehouse);
}
printf("consumer%d is over! \\n",id);
}
| 1
|
#include <pthread.h>
void test_queue_push_pop_order(void **state){
struct fsm_queue queue = create_fsm_queue();
int valueRand1 = rand();
int valueRand2 = rand();
int valueRand3 = rand();
while (valueRand1 == valueRand2){
valueRand2 = rand();
}
while (valueRand3 == valueRand1 || valueRand3 == valueRand2){
valueRand3 = rand();
}
int * pValue1 = fsm_queue_push_back(&queue, (void *) &valueRand1, sizeof(int));
int * pValue2 = fsm_queue_push_back(&queue, (void *) &valueRand2, sizeof(int));
int * pValue3 = fsm_queue_push_back(&queue, (void *) &valueRand3, sizeof(int));
int * pValuePop1 = fsm_queue_pop_front(&queue);
assert_int_equal(*pValue1, *pValuePop1);
assert_ptr_equal(pValue1, pValuePop1);
int * pValuePop2 = fsm_queue_pop_front(&queue);
assert_int_equal(*pValue2, *pValuePop2);
assert_ptr_equal(pValue2, pValuePop2);
int * pValuePop3 = fsm_queue_pop_front(&queue);
assert_int_equal(*pValue3, *pValuePop3);
assert_ptr_equal(pValue3, pValuePop3);
assert_int_not_equal(*pValuePop1, *pValuePop2);
assert_int_not_equal(*pValuePop1, *pValuePop3);
assert_int_not_equal(*pValuePop2, *pValuePop3);
free(pValue1);
free(pValue2);
free(pValue3);
fsm_queue_cleanup(&queue);
}
void * _test_queue_signal_producer(void * _queue){
struct fsm_queue *queue = _queue;
int value = 42;
fsm_queue_push_back(queue, (void *) &value, sizeof(int));
pthread_cond_signal(&queue->cond);
return 0;
}
void test_queue_signal(void **state){
struct fsm_queue queue = create_fsm_queue();
int wait = 0;
pthread_t thread;
for(int i=0; i<100; i++) {
pthread_create(&thread, 0, _test_queue_signal_producer, (void *) &queue);
pthread_mutex_lock(&queue.mutex);
while (queue.first == 0) {
pthread_cond_wait(&queue.cond, &queue.mutex);
wait++;
}
pthread_mutex_unlock(&queue.mutex);
int *pValue = fsm_queue_pop_front(&queue);
assert_int_equal(42, *pValue);
free(pValue);
fsm_queue_cleanup(&queue);
while(pthread_join(thread, 0) != 0){
debug("Error on loop %d joining thread ", i);
}
}
assert_int_not_equal(wait, 0);
}
int main(void)
{
srand ((unsigned int) time(0));
const struct CMUnitTest tests[2] = {
cmocka_unit_test(test_queue_push_pop_order),
cmocka_unit_test(test_queue_signal)
};
return cmocka_run_group_tests(tests, 0, 0);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t g_glitch_log_lock = PTHREAD_MUTEX_INITIALIZER;
static int g_configured = 0;
static int g_use_syslog = 0;
static int g_glitch_log_fd = -1;
static char g_glitch_log_fname[PATH_MAX] = { 0 };
void regurgitate_fd(char *line, size_t max_line, int ifd, int ofd,
int use_syslog)
{
int ret;
size_t bidx;
ret = lseek(ifd, 0, 0);
if (ret)
return;
memset(line, 0, max_line);
bidx = 0;
while (1) {
char b[1] = { 0 };
int tmp, res = read(ifd, b, 1);
if ((bidx == max_line - 2) || (res <= 0) || (b[0] == '\\n')) {
if (use_syslog) {
syslog(LOG_ERR | LOG_USER, "%s", line);
}
if (b[0] == '\\n')
line[bidx++] = '\\n';
tmp = safe_write(STDERR_FILENO, line, bidx);
if (ofd != -1)
tmp = safe_write(ofd, line, bidx);
if (res <= 0)
break;
memset(line, 0, max_line);
bidx = 0;
}
else {
line[bidx++] = b[0];
}
}
}
static void glitch_log_to_syslog_and_stderr(const char *buf, size_t buf_sz)
{
int res;
if (g_use_syslog)
syslog(LOG_ERR | LOG_USER, "%s", buf);
res = safe_write(STDERR_FILENO, buf, buf_sz);
}
static void glitch_log_impl(const char *fmt, va_list ap)
{
char *buf;
va_list ap2;
va_copy(ap2, ap);
int ret, txt_sz = vsnprintf(0, 0, fmt, ap);
buf = malloc(txt_sz + 1);
if (!buf) {
static const char OOM_MSG[] = "error writing to log: "
"out of memory\\n";
glitch_log_to_syslog_and_stderr(OOM_MSG, sizeof(OOM_MSG) - 1);
return;
}
vsnprintf(buf, txt_sz + 1, fmt, ap2);
if (g_glitch_log_fd != -1) {
ret = safe_write(g_glitch_log_fd, buf, txt_sz);
if (ret != 0) {
char err[512];
snprintf(err, sizeof(err), "error writing to log "
"file '%s': error %d\\n",
g_glitch_log_fname, ret);
glitch_log_to_syslog_and_stderr(err, strlen(err));
g_glitch_log_fd = -1;
g_glitch_log_fname[0] = '\\0';
RETRY_ON_EINTR(ret, close(g_glitch_log_fd));
}
}
glitch_log_to_syslog_and_stderr(buf, txt_sz);
free(buf);
}
static void open_temp_glitch_log(void)
{
int ret;
char tempdir[PATH_MAX];
ret = get_tempdir(tempdir, PATH_MAX, 0755);
if (ret)
return;
snprintf(g_glitch_log_fname, PATH_MAX, "%s/glitch_log.tmp.txt",
tempdir);
RETRY_ON_EINTR(g_glitch_log_fd, open(g_glitch_log_fname,
O_CREAT | O_RDWR, 0644));
if (g_glitch_log_fd == -1) {
g_glitch_log_fname[0] = '\\0';
remove_tempdir(tempdir);
return;
}
register_tempdir_for_cleanup(tempdir);
}
void glitch_log(const char *fmt, ...)
{
va_list ap;
pthread_mutex_lock(&g_glitch_log_lock);
if ((g_glitch_log_fd == -1) && (g_configured == 0)) {
open_temp_glitch_log();
}
__builtin_va_start((ap));
glitch_log_impl(fmt, ap);
;
pthread_mutex_unlock(&g_glitch_log_lock);
}
void close_glitch_log(void)
{
pthread_mutex_lock(&g_glitch_log_lock);
if (g_glitch_log_fd != -1) {
int res;
RETRY_ON_EINTR(res, close(g_glitch_log_fd));
g_glitch_log_fd = -1;
}
g_configured = 0;
pthread_mutex_unlock(&g_glitch_log_lock);
}
void configure_glitch_log(const struct log_config *lc)
{
int ret;
int nfd = -1;
pthread_mutex_lock(&g_glitch_log_lock);
if (g_configured) {
pthread_mutex_unlock(&g_glitch_log_lock);
glitch_log("glitch log already configured.\\n");
return;
}
g_use_syslog = lc->use_syslog;
if (lc->glitch_log) {
RETRY_ON_EINTR(nfd, open(lc->glitch_log,
O_WRONLY | O_CREAT | O_TRUNC, 0644));
if (nfd == -1) {
char err[512];
ret = errno;
snprintf(err, sizeof(err), "configure_glitch_log: "
"error opening '%s': error %d\\n",
lc->glitch_log, ret);
glitch_log_to_syslog_and_stderr(err, strlen(err));
}
}
if (g_glitch_log_fd != -1) {
char line[512], *last_slash;
regurgitate_fd(line, sizeof(line), g_glitch_log_fd,
nfd, g_use_syslog);
RETRY_ON_EINTR(ret, close(g_glitch_log_fd));
unlink(g_glitch_log_fname);
last_slash = rindex(g_glitch_log_fname, '/');
if (last_slash) {
*last_slash = '\\0';
remove_tempdir(g_glitch_log_fname);
unregister_tempdir_for_cleanup(g_glitch_log_fname);
}
}
if (lc->glitch_log) {
g_glitch_log_fd = nfd;
snprintf(g_glitch_log_fname, PATH_MAX, lc->glitch_log);
}
else {
g_glitch_log_fd = -1;
g_glitch_log_fname[0] = '\\0';
}
pthread_mutex_unlock(&g_glitch_log_lock);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mm_mutex;
void qemu_free(void *ptr)
{
trace_qemu_free(ptr);
if ( pthread_mutex_trylock(&mm_mutex) == 0 ){
free(ptr);
pthread_mutex_unlock(&mm_mutex);
}
else
free(ptr);
}
static int allow_zero_malloc(void)
{
return 0;
}
void *qemu_malloc(size_t size)
{
void *ptr;
if (!size && !allow_zero_malloc()) {
abort();
}
pthread_mutex_lock(&mm_mutex);
ptr = qemu_oom_check(malloc(size ? size : 1));
pthread_mutex_unlock(&mm_mutex);
trace_qemu_malloc(size, ptr);
return ptr;
}
void *qemu_realloc(void *ptr, size_t size)
{
void *newptr;
if (!size && !allow_zero_malloc()) {
abort();
}
pthread_mutex_lock(&mm_mutex);
newptr = qemu_oom_check(realloc(ptr, size ? size : 1));
pthread_mutex_unlock(&mm_mutex);
trace_qemu_realloc(ptr, size, newptr);
return newptr;
}
void *qemu_mallocz(size_t size)
{
void *ptr;
if (!size && !allow_zero_malloc()) {
abort();
}
pthread_mutex_lock(&mm_mutex);
ptr = qemu_oom_check(calloc(1, size ? size : 1));
pthread_mutex_unlock(&mm_mutex);
trace_qemu_malloc(size, ptr);
return ptr;
}
char *qemu_strdup(const char *str)
{
char *ptr;
size_t len = strlen(str);
ptr = qemu_malloc(len + 1);
memcpy(ptr, str, len + 1);
return ptr;
}
char *qemu_strndup(const char *str, size_t size)
{
const char *end = memchr(str, 0, size);
char *new;
if (end) {
size = end - str;
}
new = qemu_malloc(size + 1);
new[size] = 0;
return memcpy(new, str, size);
}
| 0
|
#include <pthread.h>
static sem_t cesta_libera_per_inserimento;
static sem_t inserimento_del_produttore;
pthread_mutex_t mut;
pthread_cond_t avvio;
int ceste_fatte=0;
int prod_in_cesta=0;
void* produttore(void* arg)
{
int id = (int)arg;
while(1) {
pthread_mutex_lock(&mut);
pthread_cond_wait(&avvio,&mut);
if (ceste_fatte<CS)
{
pthread_mutex_unlock(&mut);
sem_wait (&cesta_libera_per_inserimento);
sleep(rand()%5);
pthread_mutex_lock(&mut);
prod_in_cesta++;
printf("produttore [%d] inserita spec in cesta\\n",id);
pthread_mutex_unlock(&mut);
sem_post (&inserimento_del_produttore);
}
else {
printf("produttore [%d] termina\\n",id);
pthread_mutex_unlock(&mut);
break;
}
}
pthread_exit(0);
}
void* cesta(void* arg)
{
int id = (int)arg;
printf("cesta [%d] creato\\n",id);
while(1) {
pthread_mutex_lock(&mut);
printf("cesta [%d] start:%d\\n",id);
pthread_cond_broadcast(&avvio);
if (ceste_fatte<CS)
{
pthread_mutex_unlock(&mut);
for (int i = 0; i < N; ++i)
{
sem_post(&cesta_libera_per_inserimento);
sem_wait(&inserimento_del_produttore);
}
printf("cesta [%d] tutte le spec inserite nella cesta\\n",id);
sleep(rand()%5);
pthread_mutex_lock(&mut);
ceste_fatte++;
prod_in_cesta=0;
pthread_mutex_unlock(&mut);
}
else {
printf("cesta [%d] termina\\n",id);
pthread_mutex_unlock(&mut);
break;
}
}
pthread_exit(0);
}
int main(int argc, char *argv[])
{
pthread_t produttori[N];
pthread_t pc;
sem_init(&inserimento_del_produttore,0,0);
sem_init(&cesta_libera_per_inserimento,0,0);
pthread_mutex_init(&mut,0);
pthread_cond_init(&avvio_confezione,0);
if(pthread_create(&pc,0,cesta,(void *)0)<0)
{
fprintf(stderr, "errore creazione thread cesta\\n");
exit(1);
}
for (int i = 0; i < N; ++i)
{
if(pthread_create(&produttori[i],0,produttore,(void *)i)<0)
{
fprintf(stderr, "errore creazione thread produttore [%d]\\n",i);
exit(1);
}
}
for (int i = 0; i < N; ++i)
{
if(pthread_join(produttori[i],0)){
fprintf(stderr, "errore terminazione thread produttore [%d]\\n",i);
exit(1);
}
else {
printf("thread produttore [%d] termiato con successo\\n", i);
}
}
if(pthread_join(pc,0)){
fprintf(stderr, "errore terminazione thread cesta [%d]\\n");
exit(1);
}
else {
printf("pthread cesta termiato con successo\\n");
}
printf("----- fine------\\n");
}
| 1
|
#include <pthread.h>
void* merge(void *args);
void* quicksort(void *args);
int compare(const void *a, const void *b);
int* listnum = 0;
int segment_count;
int thread_count;
int remain;
pthread_mutex_t m;
pthread_cond_t cv;
{
size_t start, start2, end, num,size1,size2;
} Parameter;
int main(int argc, char **argv)
{
if(argc<=1)
return -1;
segment_count = atoi(argv[1]);
pthread_t *tid=malloc(segment_count*sizeof(pthread_t));
char* buffer = malloc(1024);
size_t n = 60;
int count = 0;
while(getline(&buffer,&n,stdin)!=-1){
count++;
listnum = realloc(listnum,count*sizeof(int));
listnum[count-1] = atoi(buffer);
}
free(buffer);
int values_per_segment;
if (count % segment_count == 0)
values_per_segment = count / segment_count;
else
values_per_segment = (count / segment_count) + 1;
Parameter *vars=malloc(segment_count*sizeof(Parameter));
remain = 0;
pthread_mutex_init(&m,0);
pthread_cond_init(&cv,0);
int i;
for(i=0; i<segment_count-1; i++)
{
int start=i*values_per_segment;
int end=(i+1)*values_per_segment-1;
int num=values_per_segment;
vars[i].start = start;
vars[i].end = end;
vars[i].num = num;
pthread_create(&tid[i], 0, quicksort, &vars[i]);
}
vars[i].start=i*values_per_segment;
vars[i].end=count-1;
vars[i].num=vars[i].end-vars[i].start+1;
pthread_create(&tid[i], 0, quicksort, &vars[i]);
for(i=0; i<segment_count; i++)
pthread_join(tid[i], 0);
free(tid);
size_t round = (size_t)segment_count;
while(round>1)
{
tid=malloc((round/2)*sizeof(pthread_t));
for(i=1;(size_t)i<round;i+=2)
{
vars[i/2].size1 = vars[i-1].end-vars[i-1].start+1;
vars[i/2].size2 = vars[i].end-vars[i].start+1;
vars[i/2].start=vars[i-1].start;
vars[i/2].start2=vars[i].start;
vars[i/2].end=vars[i].end;
vars[i/2].num=vars[i/2].end-vars[i/2].start+1;
pthread_create(&tid[i/2], 0, merge, &vars[i/2]);
}
if(round%2!=0 && round>2)
{
vars[i/2].start=vars[round-1].start;
vars[i/2].end=vars[round-1].end;
vars[i/2].num=vars[round-1].num;
}
for(i=0; (size_t)i<round/2;i++)
{pthread_join(tid[i], 0);}
if(round%2==0)
round=round/2;
else
round=round/2+1;
free(tid);
}
for(i=0;(size_t)i<vars[0].num;i++){
printf("%d\\n", listnum[i]);
}
free(vars);
free(listnum);
return 0;
}
void* quicksort(void *args)
{
remain++;
Parameter *temp=(Parameter*)args;
qsort(&listnum[temp->start], temp->num, sizeof(int), compare);
fprintf(stderr, "Sorted %d elements.\\n", (int)temp->num);
pthread_mutex_lock(&m);
remain--;
if (remain == 0) pthread_cond_broadcast(&cv);
else
{
while (remain != 0) pthread_cond_wait(&cv, &m);
}
pthread_mutex_unlock(&m);
return 0;
}
void* merge(void *args)
{
Parameter *temp=(Parameter*)args;
int* sorted = malloc(sizeof(int)*(temp->num));
int dupes=0;
pthread_mutex_lock(&m);
remain++;
pthread_mutex_unlock(&m);
size_t i=temp->start, j=0, k=temp->start2;
while(i<temp->start2 && k<=temp->end)
{
if(listnum[i]==listnum[k])
{
dupes++;
sorted[j]=listnum[i];
i++;
}
else if(listnum[i]<listnum[k])
{
sorted[j]=listnum[i];
i++;
}
else
{
sorted[j]=listnum[k];
k++;
}
j++;
}
while((size_t)i<temp->start2)
{
sorted[j]=listnum[i];
i++;
j++;
}
while((size_t)k<=temp->end)
{
sorted[j]=listnum[k];
k++;
j++;
}
int xx;
for(xx=0; (size_t)xx<temp->num; xx++)
{
listnum[temp->start+xx]=sorted[xx];
}
fprintf(stderr, "Merged %d and %d elements with %d duplicates.\\n", (int)temp->size1, (int)temp->size2, (int)dupes);
pthread_mutex_lock(&m);
remain--;
if (remain == 0) pthread_cond_broadcast(&cv);
else
{
while (remain != 0) pthread_cond_wait(&cv, &m);
}
pthread_mutex_unlock(&m);
free(sorted);
return 0;
}
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
| 0
|
#include <pthread.h>
int capacity = 0;
pthread_mutex_t mylockA = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mylockB = PTHREAD_MUTEX_INITIALIZER;
void *produce(void *args)
{
int i = 0;
for (; i < 10;) {
pthread_mutex_lock(&mylockA);
if (capacity >= 5)
{
printf("缓冲区已满,无法放入产品\\n");
} else {
++capacity;
printf("生产者存入一个产品, 缓冲区大小为:%d\\n",capacity);
i++;
}
pthread_mutex_unlock(&mylockB);
}
return ((void *) 0);
}
void *consume(void *args)
{
int i = 0;
for (; i < 10;) {
pthread_mutex_lock(&mylockB);
if (capacity > 0) {
--capacity;
printf("消费者消耗一个产品,缓冲区大小为:%d\\n",capacity);
i++;
} else {
printf("缓冲区已空,无法消耗产品\\n");
}
pthread_mutex_unlock(&mylockA);
}
return ((void *) 0);
}
int main(int argc, char **argv)
{
int err;
pthread_t produce_tid, consume_tid;
void *ret;
err = pthread_create(&produce_tid, 0, produce, 0);
if (err != 0) {
printf("线程创建失败:%s\\n", strerror(err));
exit(-1);
}
err = pthread_create(&consume_tid, 0, consume, 0);
if (err != 0) {
printf("线程创建失败:%s\\n", strerror(err));
exit(-1);
}
err = pthread_join(produce_tid, &ret);
if (err != 0) {
printf("生产着线程分解失败:%s\\n", strerror(err));
exit(-1);
}
err = pthread_join(consume_tid, &ret);
if (err != 0) {
printf("消费者线程分解失败:%s\\n", strerror(err));
exit(-1);
}
return (0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t passwdstruct_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t groupstruct_mutex = PTHREAD_MUTEX_INITIALIZER;
char *getUsername(uid_t uid) {
pthread_mutex_lock(&passwdstruct_mutex);
struct passwd *userinfo = getpwuid(uid);
char * ret = userinfo && userinfo->pw_name ? strdup(userinfo->pw_name) : 0;
pthread_mutex_unlock(&passwdstruct_mutex);
return ret;
}
void freeGroups(char **groups, int numgroups) {
if (groups == 0) {
return;
}
int i ;
for (i = 0; i < numgroups; i++) {
free(groups[i]);
}
free(groups);
}
char *getGroup(gid_t gid) {
pthread_mutex_lock(&groupstruct_mutex);
struct group* grp = getgrgid(gid);
char * ret = grp && grp->gr_name ? strdup(grp->gr_name) : 0;
pthread_mutex_unlock(&groupstruct_mutex);
return ret;
}
char *getGroupUid(uid_t uid) {
pthread_mutex_lock(&passwdstruct_mutex);
pthread_mutex_lock(&groupstruct_mutex);
char *ret = 0;
struct passwd *userinfo = getpwuid(uid);
if (0 != userinfo) {
struct group* grp = getgrgid( userinfo->pw_gid);
ret = grp && grp->gr_name ? strdup(grp->gr_name) : 0;
}
pthread_mutex_unlock(&groupstruct_mutex);
pthread_mutex_unlock(&passwdstruct_mutex);
return ret;
}
gid_t getGidUid(uid_t uid) {
pthread_mutex_lock(&passwdstruct_mutex);
struct passwd *userinfo = getpwuid(uid);
gid_t gid = userinfo == 0 ? 0 : userinfo->pw_gid;
pthread_mutex_unlock(&passwdstruct_mutex);
return gid;
}
char ** getGroups(uid_t uid, int *num_groups)
{
char *user = getUsername(uid);
if (user == 0)
return 0;
char **groupnames = 0;
int i = 0;
assert(user != 0);
groupnames[i] = user;
i++;
groupnames[i] = getGroupUid(uid);
if (groupnames[i]) {
i++;
}
*num_groups = i;
return groupnames;
}
| 0
|
#include <pthread.h>
static void sensor_nano_sleep(int64_t utime)
{
struct timespec t;
if (utime <= 0)
return;
t.tv_sec = (time_t)(utime / 1e9);
t.tv_nsec = (long)(utime % 1000000000L);
nanosleep(&t, 0);
}
static void *sensors_worker_internal_worker(void *arg)
{
struct sensors_worker_t* worker = (struct sensors_worker_t*) arg;
enum sensors_worker_mode mode;
while (1) {
pthread_mutex_lock(&worker->mode_mutex);
mode = worker->mode;
pthread_mutex_unlock(&worker->mode_mutex);
switch (mode) {
case SENSOR_DESTROY:
goto exit;
case SENSOR_SLEEP:
pthread_mutex_lock(&worker->mode_mutex);
pthread_cond_wait(&worker->suspend_cond, &worker->mode_mutex);
pthread_mutex_unlock(&worker->mode_mutex);
break;
default:
worker->poll_callback(worker->arg);
break;
}
if (worker->delay_ns)
sensor_nano_sleep(worker->delay_ns);
}
exit:
return 0;
}
static void sensors_worker_set_delay(struct sensors_worker_t* worker, int64_t ns)
{
pthread_mutex_lock(&worker->mode_mutex);
worker->delay_ns = ns;
pthread_mutex_unlock(&worker->mode_mutex);
}
static void sensors_worker_suspend(struct sensors_worker_t* worker)
{
enum sensors_worker_mode prev_mode;
pthread_mutex_lock(&worker->mode_mutex);
prev_mode = worker->mode;
worker->mode = SENSOR_SLEEP;
pthread_mutex_unlock(&worker->mode_mutex);
}
static void sensors_worker_resume(struct sensors_worker_t* worker)
{
enum sensors_worker_mode prev_mode;
pthread_mutex_lock(&worker->mode_mutex);
prev_mode = worker->mode;
worker->mode = SENSOR_RUNNING;
if (prev_mode == SENSOR_SLEEP)
pthread_cond_broadcast(&worker->suspend_cond);
pthread_mutex_unlock(&worker->mode_mutex);
}
static void sensors_worker_destroy(struct sensors_worker_t* worker)
{
enum sensors_worker_mode prev_mode;
pthread_mutex_lock(&worker->mode_mutex);
prev_mode = worker->mode;
worker->mode = SENSOR_DESTROY;
if (prev_mode == SENSOR_SLEEP)
pthread_cond_broadcast(&worker->suspend_cond);
pthread_mutex_unlock(&worker->mode_mutex);
pthread_join(worker->worker_thread_id, 0);
}
void sensors_worker_init(struct sensors_worker_t* worker,
void* (*work_func)(void *arg), void* arg)
{
worker->mode = SENSOR_SLEEP;
worker->poll_callback = work_func;
worker->suspend = sensors_worker_suspend;
worker->resume = sensors_worker_resume;
worker->destroy = sensors_worker_destroy;
worker->set_delay = sensors_worker_set_delay;
worker->delay_ns = 200000000L;
worker->arg = arg;
pthread_mutex_init (&worker->mode_mutex, 0);
pthread_cond_init (&worker->suspend_cond, 0);
pthread_create(&worker->worker_thread_id, 0,
sensors_worker_internal_worker, (void*) worker);
}
| 1
|
#include <pthread.h>
void *customerMaker();
void *barberShop();
void *waitingRoom();
void checkQueue();
pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t wait_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t sleep_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t barberSleep_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t barberWorking_cond = PTHREAD_COND_INITIALIZER;
int returnTime=5,current=0, sleeping=0, iseed;
int main(int argc, char *argv[])
{
iseed=time(0);
srand(iseed);
pthread_t barber,customerM,timer_thread;
pthread_attr_t barberAttr, timerAttr;
pthread_attr_t customerMAttr;
pthread_attr_init(&timerAttr);
pthread_attr_init(&barberAttr);
pthread_attr_init(&customerMAttr);
printf("\\n");
pthread_create(&customerM,&customerMAttr,customerMaker,0);
pthread_create(&barber,&barberAttr,barberShop,0);
pthread_join(barber,0);
pthread_join(customerM,0);
return 0;
}
void *customerMaker()
{
int i=0;
printf("*Customer Maker Created*\\n\\n");
fflush(stdout);
pthread_t customer[6 +1];
pthread_attr_t customerAttr[6 +1];
while(i<(6 +1))
{
i++;
pthread_attr_init(&customerAttr[i]);
while(rand()%2!=1)
{
sleep(1);
}
pthread_create(&customer[i],&customerAttr[i],waitingRoom,0);
}
pthread_exit(0);
}
void *waitingRoom()
{
pthread_mutex_lock(&queue_mutex);
checkQueue();
sleep(returnTime);
waitingRoom();
}
void *barberShop()
{
int loop=0;
printf("The barber has opened the store.\\n");
fflush(stdout);
while(loop==0)
{
if(current==0)
{
printf("\\tThe shop is empty, barber is sleeping.\\n");
fflush(stdout);
pthread_mutex_lock(&sleep_mutex);
sleeping=1;
pthread_cond_wait(&barberSleep_cond,&sleep_mutex);
sleeping=0;
pthread_mutex_unlock(&sleep_mutex);
printf("\\t\\t\\t\\tBarber wakes up.\\n");
fflush(stdout);
}
else
{
printf("\\t\\t\\tBarber begins cutting hair.\\n");
fflush(stdout);
sleep((rand()%20)/5);
current--;
printf("\\t\\t\\t\\tHair cut complete, customer leaving store.\\n");
pthread_cond_signal(&barberWorking_cond);
}
}
pthread_exit(0);
}
void checkQueue()
{
current++;
printf("\\tCustomer has arrived in the waiting room.\\t\\t\\t\\t\\t\\t\\t%d Customers in store.\\n",current);
fflush(stdout);
printf("\\t\\tCustomer checking chairs.\\n");
fflush(stdout);
if(current<6)
{
if(sleeping==1)
{
printf("\\t\\t\\tBarber is sleeping, customer wakes him.\\n");
fflush(stdout);
pthread_cond_signal(&barberSleep_cond);
}
printf("\\t\\tCustomer takes a seat.\\n");
fflush(stdout);
pthread_mutex_unlock(&queue_mutex);
pthread_mutex_lock(&wait_mutex);
pthread_cond_wait(&barberWorking_cond,&wait_mutex);
pthread_mutex_unlock(&wait_mutex);
return;
}
if(current>=6)
{
printf("\\t\\tAll chairs full, leaving store.\\n");
fflush(stdout);
current--;
pthread_mutex_unlock(&queue_mutex);
return;
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t verrou = PTHREAD_MUTEX_INITIALIZER ;
pthread_cond_t condition = PTHREAD_COND_INITIALIZER ;
void * monthread (void * arg){
int n = *(int *) arg ;
int condition_insatisfaite = 0 ;
printf("le thread (%d) attend \\n",(int)pthread_self());
pthread_mutex_lock(&verrou);
while(condition_insatisfaite){
pthread_cond_wait(&condition,&verrou);
condition_insatisfaite = 1 ;
}
printf("le thread (%d) travaille \\n",(int)pthread_self());
sleep(1);
pthread_cond_broadcast(&condition);
pthread_mutex_unlock(&verrou);
printf("le thread (%d) rend les ressources \\n",(int)pthread_self());
pthread_exit(0);
}
int main (){
pthread_t id1 ;
pthread_t id2 ;
int arg1 =0 ;
int arg2 = 0 ;
pthread_create(&id1,0,monthread,&arg2);
pthread_create(&id1,0,monthread,&arg1);
pthread_exit(0);
return 0 ;
}
| 1
|
#include <pthread.h>
int q[4];
int qsiz;
pthread_mutex_t mq;
void queue_init ()
{
pthread_mutex_init (&mq, 0);
qsiz = 0;
}
void queue_insert (int x)
{
int done = 0;
printf ("prod: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz < 4)
{
done = 1;
q[qsiz] = x;
qsiz++;
}
pthread_mutex_unlock (&mq);
}
}
int queue_extract ()
{
int done = 0;
int x = -1, i = 0;
printf ("consumer: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz > 0)
{
done = 1;
x = q[0];
qsiz--;
for (i = 0; i < qsiz; i++) q[i] = q[i+1];
__VERIFIER_assert (qsiz < 4);
q[qsiz] = 0;
}
pthread_mutex_unlock (&mq);
}
return x;
}
void swap (int *t, int i, int j)
{
int aux;
aux = t[i];
t[i] = t[j];
t[j] = aux;
}
int findmaxidx (int *t, int count)
{
int i, mx;
mx = 0;
for (i = 1; i < count; i++)
{
if (t[i] > t[mx]) mx = i;
}
__VERIFIER_assert (mx >= 0);
__VERIFIER_assert (mx < count);
t[mx] = -t[mx];
return mx;
}
int source[6];
int sorted[6];
void producer ()
{
int i, idx;
for (i = 0; i < 6; i++)
{
idx = findmaxidx (source, 6);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 6);
queue_insert (idx);
}
}
void consumer ()
{
int i, idx;
for (i = 0; i < 6; i++)
{
idx = queue_extract ();
sorted[i] = idx;
printf ("m: i %d sorted = %d\\n", i, sorted[i]);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 6);
}
}
void *thread (void * arg)
{
(void) arg;
producer ();
return 0;
}
int main ()
{
pthread_t t;
int i;
__libc_init_poet ();
for (i = 0; i < 6; i++)
{
source[i] = __VERIFIER_nondet_int(0,20);
printf ("m: init i %d source = %d\\n", i, source[i]);
__VERIFIER_assert (source[i] >= 0);
}
queue_init ();
pthread_create (&t, 0, thread, 0);
consumer ();
pthread_join (t, 0);
return 0;
}
| 0
|
#include <pthread.h>
void* estimate_pi(void* rank);
long long int num_tosses;
long long int num_in_circle;
int num_threads;
int sums_per_thread;
double pi_estimate;
pthread_mutex_t lock;
int main(int argc, char* argv[])
{
num_tosses = strtoll(argv[1], 0, 10);
num_in_circle = 0;
num_threads = 8;
sums_per_thread = num_tosses/num_threads;
pthread_mutex_init(&lock, 0);
pthread_t* thread_handles = malloc(num_threads * sizeof(pthread_t));
long i;
for(i = 0; i < num_threads; i++)
{
pthread_create(&thread_handles[i], 0, estimate_pi, (void *) i);
}
for(i = 0; i < num_threads; i++)
{
pthread_join(thread_handles[i], 0);
}
pi_estimate = 4*num_in_circle/((double) num_tosses);
printf("%f\\n", pi_estimate);
free(thread_handles);
}
void* estimate_pi(void* rank)
{
long my_rank = (long) rank;
int start = my_rank * sums_per_thread;
int end = start + sums_per_thread;
struct drand48_data rand_buff;
srand48_r(time(0), &rand_buff);
long my_num_in_circle = 0;
long i;
double x = 0;
double y = 0;
double distance_squared = 0;
for(i = start; i < end; i++)
{
drand48_r(&rand_buff, &x);
x = (x - .5) * 2;
drand48_r(&rand_buff, &y);
y = (y - .5) * 2;
distance_squared = x*x + y*y;
if(distance_squared <= 1)
my_num_in_circle++;
}
pthread_mutex_lock(&lock);
num_in_circle += my_num_in_circle;
pthread_mutex_unlock(&lock);
}
| 1
|
#include <pthread.h>
int R[MAX_N+1][MAX_C+1];
int progress[MAX_N+1] = {-1};
pthread_mutex_t mut[MAX_N+1] = {PTHREAD_MUTEX_INITIALIZER};
pthread_cond_t cond[MAX_N+1] = {PTHREAD_COND_INITIALIZER};
int wait_progress(int i,int j){
int prg = -1;
pthread_mutex_lock(&mut[i]);
while(j > (prg=progress[i]))
pthread_cond_wait(&cond[i],&mut[i]);
pthread_mutex_unlock(&mut[i]);
return prg;
}
int signal_progress(int i,int j){
pthread_mutex_lock(&mut[i]);
progress[i] = j;
pthread_cond_signal(&cond[i]);
pthread_mutex_unlock(&mut[i]);
}
int thread_create(void * (*start_func)(void *), void *arg){
int status = 0;
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
status = pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
if(status == 0) status = pthread_create(&tid, &attr, start_func, arg);
if(status != 0) status = pthread_create(&tid, 0, start_func, arg);
return status;
}
int sync_progress = 0;
pthread_mutex_t sync_mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t sync_cond = PTHREAD_COND_INITIALIZER;
void barrier_sync(int num_process,int pid){
pthread_mutex_lock(&sync_mut);
if(sync_progress + 1 < num_process){
++sync_progress;
pthread_cond_wait(&sync_cond,&sync_mut);
}
else{
pthread_cond_broadcast(&sync_cond);
}
pthread_mutex_unlock(&sync_mut);
}
int max(int i,int j){
return i>=j ? i : j;
}
void t_knapsack(int num_thread,int tid,int *P,int *W,int N,int C){
int i,j,prg;
--W;--P;
for(i=tid+1;i<=N;i+=num_thread){
prg = -1;
for(j=1;j<W[i];++j){
if(j > prg)prg = wait_progress(i-1,j);
R[i][j]= R[i-1][j];
if(j % 400 == 0)signal_progress(i,j);
}
signal_progress(i,j);
for(;j<=C;++j){
if(j > prg)prg = wait_progress(i-1,j);
R[i][j] = max(R[i-1][j],P[i] + R[i-1][j-W[i]]);
if(j % 400 == 0)signal_progress(i,j);
}
signal_progress(i,j);
}
barrier_sync(num_thread,tid);
}
struct ThreadParams{
int num_thread;
int tid;
int *P;
int *W;
int N;
int C;
};
void *exec_thread(void *param){
struct ThreadParams *p = param;
t_knapsack(p->num_thread,p->tid,p->P,p->W,p->N,p->C);
return 0;
}
int p_knapsack(int num_thread,int *P,int *W,int N,int C){
int i;
for(i=0;i<=C;++i)R[0][i] = 0;
for(i=1;i<=N;++i)R[i][0] = 0;
progress[0] = C;
for(i=1;i<=N;++i)progress[i] = -1;
struct ThreadParams *p = (struct ThreadParams*)malloc(sizeof(struct ThreadParams) * num_thread);
sync_progress = 0;
for(i=0;i<num_thread;++i){
p[i].num_thread = num_thread;
p[i].tid = i;
p[i].P = P;
p[i].W = W;
p[i].N = N;
p[i].C = C;
}
for(i=0;i<num_thread-1;++i)
thread_create(exec_thread,&p[i]);
exec_thread(&p[num_thread-1]);
return R[N][C];
}
double elapsed_time(struct timeval start,struct timeval end)
{
return end.tv_sec-start.tv_sec + 1e-6*(end.tv_usec-start.tv_usec);
}
main(){
struct timeval start,end;
gettimeofday(&start, 0);
int t,i,T,N,C,*P,*W;
const int num_thread = 2;
scanf("%d",&T);
for(t=0;t<T;++t){
scanf("%d",&C);
scanf("%d",&N);
P = (int*)malloc(sizeof(int) * N);
W = (int*)malloc(sizeof(int) * N);
for(i=0;i<N;++i){
scanf("%d %d",&W[i],&P[i]);
}
printf("%d\\n",p_knapsack(num_thread,P,W,N,C));
}
gettimeofday(&end, 0);
printf("%lf\\n", elapsed_time(start,end));
}
| 0
|
#include <pthread.h>
int *histogramVals;
float binSize;
int calcHistogram (float* data, int numDataPoints, int numBins);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main(void) {
float rawData[1000000];
pthread_mutex_lock(&mutex);
histogramVals = malloc(1000 * sizeof(int));
pthread_mutex_unlock(&mutex);
FILE *fileIn = fopen("numbers.bin", "rb");
if (fileIn == 0){
printf("File not opened\\n");
return 0;
}
int cnt = 1000000;
int resultCode;
resultCode = fread(rawData, sizeof(rawData[0]), sizeof(rawData)/sizeof(rawData[0]), fileIn);
fclose(fileIn);
calcHistogram (rawData, cnt, 1000);
for (int cnt1 = 0; cnt1 < 1000; cnt1++){
printf("bin: %d binStart: %f binEnd: %f Histogram Value: %d\\n", cnt1, binSize*(float)cnt1, binSize*(float)(cnt1+1), histogramVals[cnt1]);
}
return 0;
}
int calcHistogram (float* data, int numDataPoints, int numBins) {
float maxVal = FLT_MIN;
float minVal = FLT_MAX;
for(int cnt = 0; cnt < numDataPoints; cnt++ ) {
if ( data[cnt] > maxVal ) maxVal = data[cnt];
if ( data[cnt] < minVal ) minVal = data[cnt];
}
binSize = (maxVal-minVal)/(float)numBins;
printf("minVal: %f maxVal: %f binSize: %f\\n", minVal, maxVal, binSize);
for (int i = 0; i < numDataPoints; i++){
int binNum = (int)((data[i] - minVal) / binSize);
pthread_mutex_lock(&mutex);
histogramVals[binNum]++;
pthread_mutex_unlock(&mutex);
}
return 0;
}
| 1
|
#include <pthread.h>
extern int pthread_setconcurrency(int);
void *child_out(void *);
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int service_count;
int main()
{
service_count = 0;
int sock_server;
if(0 > (sock_server = socket(AF_INET, SOCK_STREAM, 0))){
fprintf(stderr,"server: can't open stream socket\\n"), exit(0);
}
struct sockaddr_in addr_server;
memset((char *) &addr_server, 0, sizeof(addr_server));
addr_server.sin_family = AF_INET;
addr_server.sin_addr.s_addr = htonl(INADDR_ANY);
addr_server.sin_port = htons(6500);
if(0 > bind(sock_server, (struct sockaddr *) &addr_server, sizeof(addr_server))){
fprintf(stderr,"server: can't bind local address\\n"), exit(0);
}
pthread_setconcurrency(5);
listen(sock_server, 5);
int sock_client;
struct sockaddr_in addr_client;
pthread_t thr_child;
pthread_attr_t attr_child;
while(1){
unsigned int client_addr_len;
client_addr_len = sizeof(addr_client);
if(0 > (sock_client = accept(sock_server, (struct sockaddr *) &addr_client, &client_addr_len))){
fprintf(stderr,"server: accept error\\n"), exit(0);
}
pthread_attr_init(&attr_child);
pthread_attr_setdetachstate(&attr_child, PTHREAD_CREATE_DETACHED);
if(0 != pthread_create(&thr_child, &attr_child, child_out, (void*) &sock_client)){
perror("pthread create failed");
break;
}
sleep(1);
pthread_mutex_lock(&lock);
if(0 < service_count) break;
pthread_mutex_unlock(&lock);
}
pthread_attr_destroy(&attr_child);
puts("READY");
return(0);
}
void *child_out(void *arg)
{
pthread_mutex_lock(&lock);
service_count = 1;
pthread_mutex_unlock(&lock);
int mysocfd = (int) arg;
printf("Child thread [%lu]: Socket number = %d\\n", (unsigned long) pthread_self(), mysocfd);
char data[100];
read(mysocfd, data, 40);
printf("Child thread [%lu]: My data = %s\\n", (unsigned long) pthread_self(), data);
sleep(2);
printf("Child thread [%lu]: Done Processing...\\n", (unsigned long) pthread_self());
pthread_mutex_lock(&lock);
service_count = 0;
pthread_mutex_unlock(&lock);
close(mysocfd);
pthread_exit((void *)0);
}
| 0
|
#include <pthread.h>
static int append_rdma_buffer_pool(struct rdma_buffer_pool *rbp, uint32_t size);
int init_rdma_buffer_pool(struct rdma_buffer_pool *rbp, struct ibv_pd *pd) {
memset(rbp, 0, sizeof(struct rdma_buffer_pool));
rbp->pd = pd;
pthread_mutex_init(&rbp->lock, 0);
return append_rdma_buffer_pool(rbp, RDMA_BUFFER_SIZE);
}
void destroy_rdma_buffer_pool(struct rdma_buffer_pool *rbp) {
struct link_node *p, *tmp;
p = rbp->link_head;
while(p) {
ibv_dereg_mr(p->buffer->mr);
free(p->buffer);
tmp = p;
p = p->next;
free(tmp);
}
rbp->free_list = 0;
rbp->free_size = rbp->total_size = 0;
pthread_mutex_destroy(&rbp->lock);
LOG(INFO, "destroy buffer pool");
}
struct rdma_chunk *get_rdma_chunk_from_pool(struct rdma_buffer_pool *rbp) {
struct rdma_chunk *chunk;
pthread_mutex_lock(&rbp->lock);
uint32_t free_size = rbp->free_size;
pthread_mutex_unlock(&rbp->lock);
if (free_size == 0) {
if (append_rdma_buffer_pool(rbp, RDMA_BUFFER_SIZE) < 0) {
LOG(ERROR, "when get chunk from pool, the free list is null, and append failed.");
return 0;
}
}
pthread_mutex_lock(&rbp->lock);
chunk = rbp->free_list;
rbp->free_list = rbp->free_list->next;
chunk->next = 0;
rbp->free_size --;
pthread_mutex_unlock(&rbp->lock);
return chunk;
}
struct rdma_chunk *get_rdma_chunk_list_from_pool(struct rdma_buffer_pool *rbp, uint32_t count) {
if (count == 0) {
return 0;
}
pthread_mutex_lock(&rbp->lock);
uint32_t free_size = rbp->free_size;
pthread_mutex_unlock(&rbp->lock);
if (free_size < count) {
if (append_rdma_buffer_pool(rbp, count - free_size) < 0) {
LOG(ERROR, "when get chunk from pool, the free list is null, and append failed.");
return 0;
}
}
pthread_mutex_lock(&rbp->lock);
struct rdma_chunk *chunk = rbp->free_list;
struct rdma_chunk *now = chunk;
for (uint32_t i = 0; i < count - 1; i++) {
if (now == 0) {
LOG(ERROR, "get rdma buffer list failed");
pthread_mutex_unlock(&rbp->lock);
return 0;
}
now = now->next;
}
rbp->free_list = now->next;
now->next = 0;
rbp->free_size -= count;
pthread_mutex_unlock(&rbp->lock);
return chunk;
}
void release_rdma_chunk_to_pool(struct rdma_buffer_pool *rbp, struct rdma_chunk *chunk) {
if (chunk == 0) {
return;
}
pthread_mutex_lock(&rbp->lock);
chunk->next = rbp->free_list;
rbp->free_list = chunk;
rbp->free_size ++;
pthread_mutex_unlock(&rbp->lock);
}
static int append_rdma_buffer_pool(struct rdma_buffer_pool *rbp, uint32_t size) {
uint32_t buffer_cnt = (size / RDMA_BUFFER_SIZE) + ((size % RDMA_BUFFER_SIZE == 0)? 0: 1);
size = buffer_cnt * RDMA_BUFFER_SIZE;
LOG(DEBUG, "append rdma buffer pool: %u", size);
if (size == 0) {
return -1;
}
struct link_node *node = (struct link_node *)calloc(1, sizeof(struct link_node));
node->buffer = (struct rdma_chunk *)malloc(size * sizeof(struct rdma_chunk));
if (node->buffer == 0) {
free(node);
LOG(ERROR, "malloc buffer failed.");
return -1;
}
struct ibv_mr *mr = ibv_reg_mr(rbp->pd, node->buffer, sizeof(struct rdma_chunk) * size, RDMA_BUF_FLAG);
if (mr == 0) {
LOG(ERROR, "failed to register memory region");
return -1;
}
for (int i = 0; i < size - 1; i++) {
node->buffer[i].mr = mr;
node->buffer[i].next = &node->buffer[i+1];
}
node->buffer[size - 1].mr = mr;
node->mr = mr;
pthread_mutex_lock(&rbp->lock);
node->buffer[size - 1].next = rbp->free_list;
rbp->free_list = node->buffer;
node->next = rbp->link_head;
rbp->link_head = node;
rbp->total_size += size;
rbp->free_size += size;
pthread_mutex_unlock(&rbp->lock);
return 0;
}
| 1
|
#include <pthread.h>extern int __VERIFIER_nondet_int(void);
extern void __VERIFIER_error() ;
int element[(20)];
int head;
int tail;
int amount;
} QType;
pthread_mutex_t m;
int __VERIFIER_nondet_int();
int stored_elements[(20)];
_Bool enqueue_flag, dequeue_flag;
QType queue;
int init(QType *q)
{
q->head=0;
q->tail=0;
q->amount=0;
}
int empty(QType * q)
{
if (q->head == q->tail)
{
printf("queue is empty\\n");
return (-1);
}
else
return 0;
}
int full(QType * q)
{
if (q->amount == (20))
{
printf("queue is full\\n");
return (-2);
}
else
return 0;
}
int enqueue(QType *q, int x)
{
q->element[q->tail] = x;
q->amount++;
if (q->tail == (20))
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == (20))
{
q->head = 1;
}
else
q->head++;
return x;
}
void *t1(void *arg)
{
int value, i;
pthread_mutex_lock(&m);
value = __VERIFIER_nondet_int();
if (enqueue(&queue,value)) {
goto ERROR;
}
stored_elements[0]=value;
if (empty(&queue)) {
goto ERROR;
}
pthread_mutex_unlock(&m);
for(i=0; i<((20)-1); i++)
{
pthread_mutex_lock(&m);
if (enqueue_flag)
{
value = __VERIFIER_nondet_int();
enqueue(&queue,value);
stored_elements[i+1]=value;
enqueue_flag=(0);
dequeue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
ERROR: __VERIFIER_error();
}
void *t2(void *arg)
{
int i;
for(i=0; i<(20); i++)
{
pthread_mutex_lock(&m);
if (dequeue_flag)
{
if (!dequeue(&queue)==stored_elements[i]) {
ERROR: __VERIFIER_error();
}
dequeue_flag=(0);
enqueue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
}
int main(void)
{
pthread_t id1, id2;
enqueue_flag=(1);
dequeue_flag=(0);
init(&queue);
if (!empty(&queue)==(-1)) {
ERROR: __VERIFIER_error();
}
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, &queue);
pthread_create(&id2, 0, t2, &queue);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 0
|
#include <pthread.h>
struct Data *table[ 29 ];
pthread_mutex_t tablelock = PTHREAD_MUTEX_INITIALIZER;
struct Data {
int count;
pthread_mutex_t lock;
struct Data *next;
int id;
int number;
};
struct Data *data_alloc( void ) {
struct Data *data;
int index;
if ( (data = malloc( sizeof( struct Data ) )) != 0 ) {
data->count = 1;
if ( pthread_mutex_init( &data->lock, 0 ) != 0 ) {
free( data );
return 0;
}
index = ( ((unsigned long) data) % 29 );
pthread_mutex_lock( &tablelock );
data->next = table[ index ];
table[ index ] = data->next;
pthread_mutex_lock( &data->lock );
pthread_mutex_unlock( &tablelock );
data->number = -9999;
pthread_mutex_unlock( data->lock );
}
return data;
}
void data_hold( struct Data *data ) {
pthread_mutex_lock( &data->lock );
data->count++;
pthread_mtex_unlock( &data->lock );
}
struct Data *data_find( int id ) {
struct Data *data;
int index = ( ((unsigned long) data) % 29 );
pthread_mutex_lock( &tablelock );
for ( data = table[index]; data != 0; data = data->next ) {
if ( data->id == id ) {
data_hold( data );
break;
}
}
pthread_mutex_unlock( &tablelock );
return data;
}
void data_release( struct Data *data ) {
struct Data *tmp;
int index;
pthread_mutex_lock( &tablelock );
if ( --data->count == 0 ) {
index = ( ((unsigned long) data) % 29 );
tmp = table[ index ];
if ( tmp == data ) {
table[ index ] = data->next;
} else {
while ( tmp->next != data ) {
tmp = data->next;
}
tmp->next = data->next;
}
pthread_mutex_unlock( &tablelock );
pthread_mutex_destroy( &data->lock );
free( data );
} else {
data->count--;
pthread_mutex_unlock( &tablelock );
}
}
void *thread_run( void *arg ) {
return (void *) 0;
}
void *thread2_run( void *arg ) {
return (void *) 0;
}
int main( int argc, char **argv ) {
pthread_t tid, tid2;
int err;
if ( (err = pthread_create( &tid, 0, thread_run, 0 )) != 0 ) {
err_quit( "error on creating first thread: %s\\n", strerror( err ) );
}
if ( (err = pthread_create( &tid2, 0, thread2_run, 0 )) != 0 ) {
err_quit( "error on creating second thread: %s\\n", strerror( err ) );
}
return 0;
}
| 1
|
#include <pthread.h>
int quit,sum;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc =PTHREAD_COND_INITIALIZER;
void *thr_fn(void *arg)
{
int i = *(int *)arg;
printf("thr_fn\\n");
if (i==0){
printf("the transfer the param success\\n");
while(i<=100){
pthread_mutex_lock(&lock);
sum += i;
pthread_mutex_unlock(&lock);
i++;
}
printf("the sum:%d\\n", sum);
}
pthread_exit((void *)0);
}
int main(int argc, char **argv) {
int i,err,num =0;
pthread_t tid[i];
pthread_attr_t attr;
err = pthread_attr_init(&attr);
if (err)
return(err);
err = pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
if (err==0){
for (int i = 0; i < 5; ++i)
{
err = pthread_create(&tid[i],&attr,thr_fn,(void *)&num);
if (err) {
printf("craete err\\n");
}
}
}else
printf("set pthread detach failed\\n");
pthread_attr_destroy(&attr);
sleep(1);
for (int i = 5; i >0; --i)
{
printf("wait the thread:%d\\n", i);
err = pthread_join(tid[i],(void *)&err);
if (!err)
{
printf("wait success thread :%d\\n",i);
}
}
return 0;
}
| 0
|
#include <pthread.h>
static pthread_cond_t sCond = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t sCondMutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t sMutexes[20];
volatile static int sTotal[20] = { 0 };
volatile static int sThreadCount = 0;
volatile static int sMutexCount;
volatile static int sCycle = 0;
static int total()
{
int result = 0, i;
for(i = 0; i < 20; i++)
result += sTotal[i];
return result;
}
static void *threadProc(void *arg)
{
int id = (int)arg;
unsigned seed = id;
pthread_mutex_lock(&sCondMutex);
for(;;)
{
__sync_fetch_and_add(&sCycle, 1);
pthread_cond_wait(&sCond, &sCondMutex);
if(sThreadCount < 0)
break;
if(id < sThreadCount)
{
int i;
for(i = 0; i < 4000; i++)
{
int ln = rand_r(&seed) % sMutexCount;
pthread_mutex_lock(sMutexes + ln);
sTotal[ln]++;
pthread_mutex_unlock(sMutexes + ln);
}
}
}
pthread_mutex_unlock(&sCondMutex);
return 0;
}
static void *dummyThreadProc(void *arg)
{
return 0;
}
int main()
{
pthread_mutex_t minit = PTHREAD_MUTEX_INITIALIZER;
pthread_t threads[15];
int i, j, n;
for(j = 0; j < 20; j++)
sMutexes[j] = minit;
for(i = 0; i < 15; i++)
pthread_create(threads + i, 0, threadProc, (void *)i);
while(sCycle < 15);
pthread_mutex_lock(&sCondMutex);
pthread_mutex_unlock(&sCondMutex);
for(i = 1; i <= 15; i++)
for(j = 1; j <= 20; j++)
{
int nextCycle = sCycle + 15;
printf("%d threads %d mutexes %d total\\n", i, j, total());
sThreadCount = i;
sMutexCount = j;
pthread_cond_broadcast(&sCond);
while(sCycle != nextCycle)
{
}
pthread_mutex_lock(&sCondMutex);
pthread_mutex_unlock(&sCondMutex);
}
sThreadCount = -1;
pthread_cond_broadcast(&sCond);
{
int k;
for(k = 0; k < 15; k++)
pthread_join(threads[k], 0);
}
printf("%d total\\n", total());
if(i - 1 == 15 && j - 1 == 20)
printf("RESULT=PASS");
else
printf("RESULT=FAIL");
return 0;
}
| 1
|
#include <pthread.h>
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo {
int f_count;
pthread_mutex_t f_lock;
int f_id;
struct foo *f_next;
};
struct foo *foo_alloc(int id) {
struct foo *fp;
int idx;
if ((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 1;
fp->f_id = id;
if (pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return 0;
}
idx = (((unsigned long) id) % 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;
}
void foo_hold(struct foo *fp) {
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
struct foo *foo_find(int id) {
struct foo *fp;
pthread_mutex_lock(&hashlock);
for (fp = fh[(((unsigned long) id) % 29)]; fp != 0; fp = fp->f_next) {
if (fp->f_id == id) {
foo_hold(fp);
break;
}
}
pthread_mutex_unlock(&hashlock);
return fp;
}
void foo_rele(struct foo *fp) {
struct foo *tfp;
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 = (((unsigned long) fp->f_id) % 29);
tfp = fh[idx];
if (tfp == fp) {
fh[idx] = fp->f_next;
} else {
while (tfp->f_next != fp) {
tfp = tfp->f_next;
}
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
} else {
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
}
}
| 0
|
#include <pthread.h>
void pqsort(void*);
struct TaskQueue queue;
pthread_mutex_t qmutex;
int *a, rec_limit;
struct TaskArgs
{
int l, r, depth;
struct ThreadPool *pool;
};
void targs_set(struct TaskArgs *targs, int l, int r, int depth, struct ThreadPool *pool)
{
targs->l = l;
targs->r = r;
targs->depth = depth;
targs->pool = pool;
}
int cmp(const void *op1, const void *op2)
{
int x, y;
x = *((int*) op1);
y = *((int*) op2);
return (x < y ? -1 : (x == y ? 0 : 1));
}
void add_qsort_task(int l, int r, int depth, struct ThreadPool *pool)
{
struct TaskArgs *new_targs;
struct Task *new_task;
new_targs = (struct TaskArgs*) malloc(sizeof(struct TaskArgs));
targs_set(new_targs, l, r, depth, pool);
new_task = (struct Task*) malloc(sizeof(struct Task));
task_init(new_task, pqsort, (void*) new_targs);
pthread_mutex_lock(&qmutex);
qpush(&queue, new_task);
pthread_mutex_unlock(&qmutex);
thpool_submit(pool, new_task);
}
void pqsort(void *args)
{
struct TaskArgs *targs = args;
int l, r, tmp;
l = targs->l;
r = targs->r;
if (targs->depth > rec_limit)
qsort(a + l, r - l, sizeof(int), cmp);
else
{
int x, i, j;
x = a[l + rand() % (r - l)];
i = l;
j = r;
while (i < j)
{
for (; a[i] < x; i++);
for (; a[j - 1] > x; j--);
if (i < j)
{
tmp = a[i];
a[i] = a[j - 1];
a[j - 1] = tmp;
i++;
j--;
}
}
for (; i < r && a[i] == x; i++);
for (; j > l && a[j - 1] == x; j--);
if (j > l)
add_qsort_task(l, j, targs->depth + 1, targs->pool);
if (i < r)
add_qsort_task(i, r, targs->depth + 1, targs->pool);
}
}
int main(int argc, char **argv)
{
int i, n, sorted;
unsigned threads_nm;
struct ThreadPool pool;
struct Task *task;
srand(42);
if (argc != 4)
{
fprintf(stderr, "wrong number of arguments");
exit(1);
}
threads_nm = atoi(argv[1]);
n = atoi(argv[2]);
rec_limit = atoi(argv[3]);
a = (int*) malloc(n * sizeof(int));
for (i = 0; i < n; i++)
a[i] = rand();
pthread_mutex_init(&qmutex, 0);
thpool_init(&pool, threads_nm);
add_qsort_task(0, n, 0, &pool);
pthread_mutex_lock(&qmutex);
task = qpop(&queue);
pthread_mutex_unlock(&qmutex);
while (task)
{
thpool_wait(task);
task_finit(task);
free(task);
pthread_mutex_lock(&qmutex);
task = qpop(&queue);
pthread_mutex_unlock(&qmutex);
}
thpool_finit(&pool);
pthread_mutex_destroy(&qmutex);
sorted = 1;
for (i = 1; i < n; i++)
sorted &= a[i - 1] <= a[i];
printf("array is ");
if (!sorted)
printf("not ");
printf("sorted\\n");
free(a);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
void *threaded(void *accountPtr)
{
pthread_mutex_lock(&lock);
int amount = 0;
printf("Please Enter an amount to be added:");
scanf("%d", &amount);
if(amount > 1000000000 || amount < 0)
{
printf("Number entered is too large / small for it to be accepted as an integer and will cause problems");
return 0;
}
int *amountptr = (int *)accountPtr;
for(int i = 0; i < amount; i++)
{
++(*amountptr);
}
pthread_mutex_unlock(&lock);
printf ("Account balance after adding: %d\\n", *amountptr);
return 0;
}
void first(int *accountPtr)
{
pthread_mutex_lock(&lock);
int amount = 0;
printf("Please Enter an amount to be subtracted:");
scanf("%d", &amount);
if(amount > 1000000000 || amount < 0)
{
printf("Number entered is too large / small for it to be accepted as an integer and will cause problems");
return;
}
int *amountptr = (int *)accountPtr;
for(int i = 0; i < amount; i++)
{
--(*amountptr);
}
pthread_mutex_unlock(&lock);
printf("Account balance after subtraction: %d\\n", *accountPtr);
}
int main()
{
int accessedVar = 1000;
printf("Initial Value: %d \\n", accessedVar);
pthread_t thread2;
if(pthread_create(&thread2, 0, threaded, &accessedVar))
{
fprintf(stderr, "Error creating thread\\n");
return 1;
}
first(&accessedVar);
if(pthread_join(thread2, 0))
{
fprintf(stderr, "Error joining thread\\n");
return 2;
}
return 0;
}
| 0
|
#include <pthread.h>
static uint8_t flagCollect[2];
static FILE *fp;
void *RunDataService( void* );
void clearFlag( uint8_t );
void *RunDataService( void *arg )
{
fp = fopen("data/test_data.csv", "w");
while (1) {
for (int i=0; i< (sizeof(flagCollect)/sizeof(flagCollect[0])); i++) {
if (flagCollect[i]) {
char stringResp[MAX_STR_RESP_LEN];
uint8_t ValResp;
lockExperimentThread();
pthread_mutex_lock(&data_lock);
switch (i) {
case 0:
strcpy(stringResp, getStringResp());
fprintf(fp, "%s\\n", stringResp);
clearFlag(i);
break;
case 1:
ValResp = getValResp();
fprintf(fp, "%d\\n", ValResp);
clearFlag(i);
break;
}
pthread_mutex_unlock(&data_lock);
unlockExperimentThread();
}
}
}
}
void *getDataThreadHandler( void )
{
return RunDataService;
}
void setFlag ( uint8_t whichFlag )
{
if (whichFlag < 2) {
flagCollect[whichFlag] = 1;
}
}
void clearFlag ( uint8_t whichFlag )
{
if (whichFlag < 2) {
flagCollect[whichFlag] = 0;
}
}
void close_file( void )
{
printf("\\r\\nClosed data file\\n\\r");
fclose(fp);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t mlock;
void th1_count( int* x );
void th2_count( int* x );
void delay( long nanosec );
int main(int argc, char** argv ) {
int x = 0;
pthread_mutex_init( &mlock, 0 );
pthread_t thread1, thread2;
if (pthread_create(&thread1,
0,
(void *) th1_count,
(void *) &x ) != 0)
perror("pthread_create"), exit(1);
if (pthread_create(&thread2,
0,
(void *) th2_count,
(void *) &x ) != 0)
perror("pthread_create"), exit(1);
if (pthread_join(thread1, 0) != 0)
perror("pthread_join"),exit(1);
if (pthread_join(thread2, 0) != 0)
perror("pthread_join"),exit(1);
return 0;
}
void th1_count(int* x ) {
int i;
for (i = 0; i < 30; i++) {
pthread_mutex_lock( &mlock );
printf("thread[1,%d]: x = %d\\n", i, (*x) );
(*x) += 1;
pthread_mutex_unlock( &mlock );
delay( 3000 );
}
}
void th2_count(int* x ) {
int i;
for (i = 0; i < 30; i++) {
pthread_mutex_lock( &mlock );
printf("thread[2,%d]: x = %d\\n", i, (*x) );
(*x) += 1;
pthread_mutex_unlock( &mlock );
delay( 1000 );
}
}
void delay( long nanosec ) {
struct timespec t_spec;
t_spec.tv_sec = 0;
t_spec.tv_nsec = nanosec;
nanosleep( &t_spec, 0 );
}
| 0
|
#include <pthread.h>
static pthread_key_t key;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;
extern char **environ;
static void
thread_init(void)
{
pthread_key_create(&key, free);
}
char *
getenv(const char *name)
{
int i, len;
char *envbuf;
pthread_once(&init_done, thread_init);
pthread_mutex_lock(&env_mutex);
envbuf = (char *)pthread_getspecific(key);
if (envbuf == 0) {
envbuf = malloc(1024);
if (envbuf == 0) {
pthread_mutex_unlock(&env_mutex);
return(0);
}
pthread_setspecific(key, envbuf);
}
len = strlen(name);
for (i = 0; environ[i] != 0; i++) {
if ((strncmp(name, environ[i], len) == 0) &&
(environ[i][len] == '=')) {
strcpy(envbuf, &environ[i][len+1]);
pthread_mutex_unlock(&env_mutex);
return(envbuf);
}
}
pthread_mutex_unlock(&env_mutex);
return(0);
}
int main(void)
{
printf("%s\\n", getenv("JAVA_HOME"));
exit(0);
}
| 1
|
#include <pthread.h>
int g_flag = 0;
pthread_mutex_t glock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;
void *thr_fn1(void *arg)
{
printf("this is thread1.\\n");
pthread_mutex_lock(&glock);
if (g_flag == 2)
pthread_cond_signal(&gcond);
g_flag = 1;
pthread_mutex_unlock(&glock);
pthread_join(*(pthread_t *)arg, 0);
printf("thread 1 leave.\\n");
pthread_exit((void *)1);
}
void *thr_fn2(void *arg)
{
printf("this is thread2.\\n");
pthread_mutex_lock(&glock);
if (g_flag == 1)
pthread_cond_signal(&gcond);
g_flag = 2;
pthread_mutex_unlock(&glock);
printf("thread 2 leave.\\n");
pthread_exit((void *)2);
}
int main(void)
{
int err;
pthread_t tid1, tid2;
err = pthread_create(&tid2, 0, thr_fn2, 0);
if (err != 0)
{
printf("%s : %s.\\n", __func__, strerror(err));
exit(err);
}
err = pthread_create(&tid1, 0, thr_fn1, (void *)&tid2);
if (err != 0)
{
printf("%s : %s.\\n", __func__, strerror(err));
exit(err);
}
pthread_cond_wait(&gcond, &glock);
sleep(1);
printf("main function, %s\\n", __func__);
exit(0);
}
| 0
|
#include <pthread.h>
struct dpado_range_t
{
struct list_head entry;
unsigned int conn_cnt;
int pado_delay;
};
static pthread_mutex_t dpado_range_lock = PTHREAD_MUTEX_INITIALIZER;
static LIST_HEAD(dpado_range_list);
static struct dpado_range_t *dpado_range_next;
static struct dpado_range_t *dpado_range_prev;
int pado_delay;
void dpado_check_next(int conn_cnt)
{
pthread_mutex_lock(&dpado_range_lock);
if (dpado_range_next && conn_cnt == dpado_range_next->conn_cnt) {
pado_delay = dpado_range_next->pado_delay;
dpado_range_prev = dpado_range_next;
if (dpado_range_next->entry.next != &dpado_range_list)
dpado_range_next = list_entry(dpado_range_next->entry.next, typeof(*dpado_range_next), entry);
else
dpado_range_next = 0;
}
pthread_mutex_unlock(&dpado_range_lock);
}
void dpado_check_prev(int conn_cnt)
{
pthread_mutex_lock(&dpado_range_lock);
if (dpado_range_prev && conn_cnt == dpado_range_prev->conn_cnt) {
dpado_range_next = dpado_range_prev;
dpado_range_prev = list_entry(dpado_range_prev->entry.prev, typeof(*dpado_range_prev), entry);
pado_delay = dpado_range_prev->pado_delay;
}
pthread_mutex_unlock(&dpado_range_lock);
}
static void strip(char *str)
{
char *ptr = str;
char *endptr = strchr(str, 0);
while (1) {
ptr = strchr(ptr, ' ');
if (ptr)
memmove(ptr, ptr + 1, endptr - ptr - 1);
else
break;
}
}
int dpado_parse(const char *str)
{
char *str1 = _strdup(str);
char *ptr1, *ptr2, *ptr3, *endptr;
LIST_HEAD(range_list);
struct dpado_range_t *r;
strip(str1);
ptr1 = str1;
while (1) {
ptr2 = strchr(ptr1, ',');
if (ptr2)
*ptr2 = 0;
ptr3 = strchr(ptr1, ':');
if (ptr3)
*ptr3 = 0;
r = _malloc(sizeof(*r));
memset(r, 0, sizeof(*r));
r->pado_delay = strtol(ptr1, &endptr, 10);
if (*endptr)
goto out_err;
if (list_empty(&range_list))
r->conn_cnt = 32767;
else {
if (!ptr3)
goto out_err;
r->conn_cnt = strtol(ptr3 + 1, &endptr, 10);
if (*endptr)
goto out_err;
}
list_add_tail(&r->entry, &range_list);
if (!ptr2)
break;
ptr1 = ptr2 + 1;
}
pthread_mutex_lock(&dpado_range_lock);
while (!list_empty(&dpado_range_list)) {
r = list_entry(dpado_range_list.next, typeof(*r), entry);
list_del(&r->entry);
_free(r);
}
dpado_range_next = 0;
dpado_range_prev = 0;
while (!list_empty(&range_list)) {
r = list_entry(range_list.next, typeof(*r), entry);
list_del(&r->entry);
list_add_tail(&r->entry, &dpado_range_list);
if (!dpado_range_prev || stat_active >= r->conn_cnt)
dpado_range_prev = r;
else if (!dpado_range_next)
dpado_range_next = r;
}
pado_delay = dpado_range_prev->pado_delay;
if (conf_pado_delay)
_free(conf_pado_delay);
conf_pado_delay = _strdup(str);
pthread_mutex_unlock(&dpado_range_lock);
_free(str1);
return 0;
out_err:
_free(str1);
log_emerg("pppoe: pado_delay: invalid format\\n");
return -1;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t mutex;
char listeNomFichier[30][100];
unsigned longueur = 30;
void* afficheDossier(void* nom){
char* nameC = malloc(strlen((char*)nom)*sizeof(char));
stpcpy(nameC, (char*)nom);
char* nameO = malloc(strlen(nameC)*sizeof(char));
stpcpy(nameO, nameC);
nameO[strlen(nameO)-1] = 'o';
struct stat statC;
struct stat statO;
struct stat statErreur;
char commandAjout[100];
strcpy(commandAjout, "gcc -Wall -c ");
strcat(commandAjout, nameC);
char commandRetire[100];
strcpy(commandRetire, "rm ");
strcat(commandRetire, nameO);
while(1){
if(stat(nameC, &statC) >= 0){
if(stat(nameO, &statO) < 0){
pthread_mutex_lock(&mutex);
system(commandAjout);
pthread_mutex_unlock(&mutex);
if(stat(nameO, &statO) < 0){
statErreur.st_mtime = statC.st_mtime;
while(statC.st_mtime == statErreur.st_mtime){
usleep(1000000);
if(stat(nameC, &statC) < 0){
break;
}
}
}
}else if(statC.st_mtime > statO.st_mtime){
pthread_mutex_lock(&mutex);
system(commandAjout);
pthread_mutex_unlock(&mutex);
}
}else{
break;
}
usleep(1000000);
}
unsigned i = 0;
while(strcmp(listeNomFichier[i], nameC) != 0){
i++;
if(i == longueur){
return 0;
}
}
int j;
for(j = 0 ; j < 100 ; j++){
listeNomFichier[i][j] = '\\0';
}
pthread_mutex_lock(&mutex);
if( access( nameO, F_OK ) != -1 ){
system(commandRetire);
}
pthread_mutex_unlock(&mutex);
free(nameO);
free(nameC);
return 0;
}
int startChild(char * path) {
DIR *dir;
struct dirent *ent;
int listeVide;
pthread_t pth[30] = {0};
unsigned i = 0;
unsigned j = 0;
int placeDansFichier = 0;
for(i = 0 ; i < 30 ; i++){
for(j = 0 ; j < 100 ; j++){
listeNomFichier[i][j] = '\\0';
}
}
if ((dir = opendir (path)) != 0) {
chdir(path);
while(1){
while ((ent = readdir (dir)) != 0) {
if(strlen(ent->d_name) >= 3 && ent->d_name[strlen(ent->d_name)-1] == 'c' && ent->d_name[strlen(ent->d_name)-2] == '.'){
j = 0;
placeDansFichier = -1;
while(1){
if(listeNomFichier[j][0] == '\\0' && placeDansFichier == -1){
placeDansFichier = j;
}
if(j == longueur){
if(placeDansFichier != -1){
strcpy(listeNomFichier[placeDansFichier], ent->d_name);
pthread_create(&pth[placeDansFichier], 0, afficheDossier, (void*) ent->d_name);
}
break;
}
if(strcmp(listeNomFichier[j], ent->d_name) == 0){
break;
}
j++;
}
}
}
listeVide = 0;
for(j = 0 ; j < longueur ; j++){
if(listeNomFichier[j][0] != '\\0'){
listeVide = 1;
break;
}
}
if(!listeVide){
return 0;
}
pthread_mutex_lock(&mutex);
rewinddir(dir);
pthread_mutex_unlock(&mutex);
usleep(1000000);
}
for(i = 0 ; i < 30 ; i++){
if(pth[i] == 1){
pthread_join(pth[i], 0);
}
}
closedir (dir);
} else {
perror ("");
printf("Fin Execution");
return 1;
}
}
| 0
|
#include <pthread.h>
int count = 0;
int c = 0;
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *
inc_count (void* arg)
{
count++;
pthread_mutex_lock (&count_mutex);
c = 1;
pthread_cond_signal (&count_threshold_cv);
pthread_mutex_unlock (&count_mutex);
return 0;
}
void *
watch_count (void *idp)
{
pthread_mutex_lock (&count_mutex);
while (c == 0)
pthread_cond_wait (&count_threshold_cv, &count_mutex);
pthread_mutex_unlock (&count_mutex);
count++;
return 0;
}
int
main (int argc, char *argv[])
{
int i;
pthread_t a,b;
pthread_mutex_init (&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_create (&a, 0, watch_count, 0);
pthread_create (&b, 0, inc_count, 0);
pthread_join (a, 0);
pthread_join (b, 0);
pthread_mutex_destroy (&count_mutex);
return 0;
}
| 1
|
#include <pthread.h>
int find = 0;
int element;
int * vector;
int sizeVector,start;
}infos_search;
int initialise_vector(int * vector){
char buffer[50];
char * token;
int sizeVector =0;
if(fgets(buffer, sizeof(buffer), stdin)==0){printf("Erreur de lecture");exit(0);};
token = strtok(buffer," ");
while( token != 0 ) {
vector[sizeVector] = atoi(token);
sizeVector++;
token = strtok(0, " ");
}
return sizeVector;
}
void searched_element(int element,int * vector,int sizeVector){
int i = 0;
while(i < sizeVector && vector[i] != element){
i++;
}
printf("Element find at postion %i in vector\\n",i);
}
void * searched_element_threads(void * arg){
pthread_mutex_t mutex_stock;
infos_search * infos = (infos_search *) arg;
int i = infos->start;
while(i < infos->sizeVector && find!=1 &&(infos->vector)[i] != infos->element){
i++;
}
if((infos->vector)[i] == infos->element){
pthread_mutex_lock (&mutex_stock);
find = 1;
printf("Element find at postion %i in vector\\n",i);
pthread_mutex_unlock (&mutex_stock);
}
free(infos);
return 0;
}
int main (int argc, char **argv){
int * vector = malloc(sizeof(int)*1024);
int sizeVector,nb_threads,i;
pthread_t *tids ;
if (argc != 3){
fprintf(stderr, "usage : %s nbThreads searched_Element \\n", argv[0]) ;
exit (-1) ;
}
nb_threads = atoi(argv[1]);
tids = malloc (nb_threads*sizeof(pthread_t));
sizeVector = initialise_vector(vector);
for (i = 0 ; i < nb_threads; i++){
infos_search * infos = malloc(sizeof(infos_search));
infos->vector = vector;
infos->element = atoi(argv[2]);
if(i == 0){
infos->start = 0;
infos->sizeVector = floor(sizeVector/nb_threads);
}else{
infos->start = floor(sizeVector/nb_threads)*i+1;
infos->sizeVector = infos->start + floor(sizeVector/nb_threads);
}
pthread_create (&tids[i],0,searched_element_threads,infos) ;
}
for (i = 0; i < nb_threads; i++){
pthread_join (tids[i], 0) ;
}
if(find ==0){
printf("L'élément n'a pas été trouvé\\n");
}
free (tids) ;
free(vector);
return 0;
}
| 0
|
#include <pthread.h>
int g = 0;
pthread_mutex_t mutex1;
pthread_mutex_t mutex2;
void *myThreadFun1(void *vargp)
{
int i = (int)vargp;
pthread_mutex_lock (&mutex1);
pthread_mutex_lock (&mutex2);
printf("1 Global: %d\\n", ++g);
pthread_mutex_lock (&mutex2);
pthread_mutex_unlock (&mutex1);
}
void *myThreadFun2(void *vargp)
{
int i = (int)vargp;
pthread_mutex_lock (&mutex2);
pthread_mutex_lock (&mutex1);
printf("2 Global: %d\\n", ++g);
pthread_mutex_lock (&mutex1);
pthread_mutex_unlock (&mutex2);
}
int threadCount(int num_threads)
{
int i;
pthread_t tid;
pthread_t threads[2];
pthread_attr_t attr;
pthread_mutex_init(&mutex1, 0);
pthread_mutex_init(&mutex2, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
i = 0;
pthread_create(&threads[0], &attr, myThreadFun1, (void *)i);
pthread_create(&threads[1], &attr, myThreadFun2, (void *)i);
pthread_attr_destroy(&attr);
pthread_join(threads[0],0);
pthread_join(threads[1],0);
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
return g;
pthread_exit(0);
}
| 1
|
#include <pthread.h>
void *arr[32];
int rd;
int wr;
} queue_t;
static pthread_mutex_t lock_x;
static pthread_cond_t count_consumer, count_producer;
static queue_t q;
int enqueue(void *addr)
{
if (!addr)
return -1;
if (((q.wr + 1) % 32) == q.rd)
return -1;
q.arr[q.wr] = addr;
q.wr = (q.wr + 1) % 32;
return 0;
}
int dequeue(unsigned long *addr)
{
if (q.rd == q.wr)
return -1;
*addr = (unsigned long) q.arr[q.rd];
q.rd = (q.rd + 1) % 32;
return 0;
}
void *thr_func_1(void *arg)
{
printf("Producer thread\\n");
void *addr;
do {
addr = malloc(1024);
if (!addr)
break;
printf("Alloc at %p\\n", addr);
pthread_mutex_lock(&lock_x);
while (enqueue(addr) != 0) {
pthread_cond_wait(&count_producer, &lock_x);
}
pthread_cond_signal(&count_consumer);
pthread_mutex_unlock(&lock_x);
} while (1);
pthread_exit(0);
}
void *thr_func_2(void *arg)
{
printf("Consumer thread\\n");
unsigned long addr;
do {
pthread_mutex_lock(&lock_x);
while (dequeue(&addr) != 0) {
pthread_cond_wait(&count_consumer, &lock_x);
}
pthread_cond_signal(&count_producer);
pthread_mutex_unlock(&lock_x);
printf("Free at %p\\n", (void *) addr);
free((void *) addr);
} while (1);
pthread_exit(0);
}
int main(void)
{
pthread_t thr[2];
int i, rc;
pthread_mutex_init(&lock_x, 0);
pthread_cond_init(&count_consumer, 0);
pthread_cond_init(&count_producer, 0);
if ((rc = pthread_create(&thr[0], 0, thr_func_1, 0))) {
fprintf(stderr, "error: pthread_create, rc: %d\\n", rc);
return 1;
}
if ((rc = pthread_create(&thr[1], 0, thr_func_2, 0))) {
fprintf(stderr, "error: pthread_create, rc: %d\\n", rc);
return 1;
}
for (i = 0; i < 2; ++i) {
pthread_join(thr[i], 0);
}
pthread_mutex_destroy(&lock_x);
pthread_cond_destroy(&count_consumer);
pthread_cond_destroy(&count_producer);
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
void *thread_a(void *arg);
void *thread_b(void *arg);
int main(){
int shmid = shmget(IPC_PRIVATE, sizeof(int), S_IRUSR | S_IWUSR);
if (shmid==-1){
perror("Error creating shared memory!\\n");
return 0;
}
int *pointer = (int *) shmat(shmid, 0, 0);
pthread_mutex_lock(&lock1);
pthread_mutex_lock(&lock2);
pthread_t thread_1, thread_2;
pthread_create(&thread_1, 0, thread_a, pointer);
pthread_create(&thread_2, 0, thread_b, pointer);
pthread_join(thread_1, 0);
pthread_join(thread_2, 0);
printf("Terminating process...\\n");
pthread_mutex_destroy(&lock1);
pthread_mutex_destroy(&lock2);
shmctl(shmid, IPC_RMID, 0);
pthread_exit(0);
return 0;
}
void *thread_a(void *arg){
int number_father = 5;
int response;
do{
printf("[Father] Try to guess the number is: %d\\n", number_father);
*((int *) arg) = number_father;
pthread_mutex_unlock(&lock2);
pthread_mutex_lock(&lock1);
response = *((int *) arg);
if(response == 1)
number_father--;
else if (response == -1)
number_father++;
else if(response != 0)
perror("Error occured in father!\\n");
sleep(1);
}while(response!=0);
printf("[Father] The guess number was: %d\\n", number_father);
pthread_exit(0);
return 0;
}
void *thread_b(void *arg){
int randn_child = rand() % 10;
int response;
do{
pthread_mutex_lock(&lock2);
response = *((int *) arg);
if(response > randn_child){
printf("[Child] Wrong! The number is smaller than attempt.\\n");
response = 1;
}
else if(response < randn_child){
printf("[Child] Wrong! The number is bigger than attempt.\\n");
response = -1;
}else{
printf("[Child] Yeeh! The number is equal to attempt.\\n");
response = 0;
}
*((int *) arg) = response;
pthread_mutex_unlock(&lock1);
sleep(1);
}while(response!=0);
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock_x;
void *connection_handler(void *socket_desc) {
int sock = *(int*)socket_desc;
int read_size, bytes;
char *message, client_message[100], client_filename[100],
client_filepath[100], server_filepath[500], file_buffer[512],
username[50], password[50];
while((read_size = recv(sock, client_message, 100, 0)) > 0) {
if (strcmp(client_message, "INIT_LOGIN") == 0) {
puts("\\nLogin started");
int found = 0;
char user_auth[50], pass_auth[50];
recv(sock, username, 50, 0);
recv(sock, password, 50, 0);
pthread_mutex_lock(&lock_x);
FILE *auth_file = fopen("/home/alex/Coding/systems-software/file-transfer/server/storage/auth.txt", "r");
char line[80];
while(fgets(line, 80, auth_file)) {
sscanf(line, "username: %s password: %s", user_auth, pass_auth);
if((strcmp(username, user_auth) == 0) && (strcmp(password, pass_auth) == 0)) {
found = 1;
}
}
fclose(auth_file);
pthread_mutex_unlock(&lock_x);
if (found == 1) {
send(sock, "200", sizeof("200"), 0);
} else {
send(sock, "401", sizeof("401"), 0);
puts("Login aborted");
free(socket_desc);
pthread_exit(0);
}
puts("Login completed\\n");
}
if (strcmp(client_message, "INIT_TRANSFER") == 0) {
puts("Transfer started");
if ((bytes = recv(sock, client_filename, 100, 0)) == 0){
puts("No data recieved");
free(socket_desc);
pthread_exit(0);
}
if ((bytes = recv(sock, client_filepath, 100, 0)) == 0) {
puts("No data recieved");
free(socket_desc);
pthread_exit(0);
}
strcpy(server_filepath, "/home/alex/Coding/systems-software/file-transfer/server/website");
strcat(server_filepath, "/");
strcat(server_filepath, client_filepath);
strcat(server_filepath, "/");
strcat(server_filepath, client_filename);
puts(server_filepath);
pthread_mutex_lock(&lock_x);
FILE *file_open = fopen(server_filepath, "w");
memset(file_buffer, 0, sizeof(file_buffer));
int bytes_recv = 0;
int i = 0;
while((bytes_recv = recv(sock, file_buffer, 512, 0)) > 0) {
printf("Data Received %d = %d\\n", i, bytes_recv);
int write_sz = fwrite(file_buffer, sizeof(char), bytes_recv, file_open);
memset(file_buffer, 0, sizeof(file_buffer));
i++;
if (write_sz == 0 || write_sz != 512) {
break;
}
}
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
openlog("file_changer", LOG_PID|LOG_CONS, LOG_USER);
syslog(LOG_INFO, "User: %s modified %s at %s", username, client_filename, asctime (timeinfo));
puts("Transfer completed\\n");
send(sock, "OK", sizeof("OK"), 0);
fclose(file_open);
pthread_mutex_unlock(&lock_x);
}
}
if(read_size == 0) {
puts("Client disconnected");
fflush(stdout);
}
else if(read_size == -1) {
perror("recv failed");
}
free(socket_desc);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
static char* resbuffer_result_string = 0;
static int resbuffer_num_lines = 0;
static int resbuffer_current_bufsize = 0;
static int resbuffer_current_ressize = 0;
static int resbuffer_async_mode = 0;
static int resbuffer_async_notify = 0;
static pthread_mutex_t resbuffer_lock = PTHREAD_MUTEX_INITIALIZER;
const char line_sep[] = BLAHPD_CRLF;
int
init_resbuffer(void)
{
pthread_mutex_init(&resbuffer_lock, 0);
return (0);
}
int
set_async_mode(int mode)
{
if (resbuffer_async_mode == mode) return(1);
pthread_mutex_lock(&resbuffer_lock);
resbuffer_async_mode = mode;
resbuffer_async_notify = mode;
pthread_mutex_unlock(&resbuffer_lock);
return(0);
}
int
push_result(const char *res)
{
int reslen;
int required_bytes;
int required_chunks;
int async_notify = 0;
reslen = strlen(res) + sizeof(line_sep) - 1;
pthread_mutex_lock(&resbuffer_lock);
if ((required_bytes = (reslen + resbuffer_current_ressize - resbuffer_current_bufsize)) > 0)
{
required_chunks = required_bytes / ALLOC_CHUNKS + 1;
resbuffer_result_string = (char *)realloc(resbuffer_result_string, resbuffer_current_bufsize + ALLOC_CHUNKS * required_chunks);
if (resbuffer_result_string == 0)
{
fprintf(stderr, "Out of memory! Cannot allocate result buffer\\n");
exit(MALLOC_ERROR);
}
resbuffer_current_bufsize += (ALLOC_CHUNKS * required_chunks);
}
memcpy(resbuffer_result_string + resbuffer_current_ressize, line_sep, sizeof(line_sep) - 1);
strcpy(resbuffer_result_string + resbuffer_current_ressize + sizeof(line_sep) - 1, res);
resbuffer_current_ressize += reslen;
resbuffer_num_lines++;
if (resbuffer_async_notify == ASYNC_MODE_ON && resbuffer_async_mode == ASYNC_MODE_ON)
{
async_notify = 1;
resbuffer_async_notify = ASYNC_MODE_OFF;
}
pthread_mutex_unlock(&resbuffer_lock);
return(async_notify);
}
char *
get_lines(void)
{
char *res_lines = 0;
pthread_mutex_lock(&resbuffer_lock);
res_lines = (char *)malloc(resbuffer_current_ressize + 16);
if (res_lines == 0)
{
fprintf(stderr, "Out of memory! Cannot allocate result buffer\\n");
exit(MALLOC_ERROR);
}
sprintf(res_lines, "S %d", resbuffer_num_lines);
if (resbuffer_result_string)
{
strcat(res_lines, resbuffer_result_string);
free(resbuffer_result_string);
resbuffer_result_string = 0;
resbuffer_num_lines = 0;
resbuffer_current_ressize = 0;
resbuffer_current_bufsize = 0;
resbuffer_async_notify = resbuffer_async_mode;
}
pthread_mutex_unlock(&resbuffer_lock);
return(res_lines);
}
| 1
|
#include <pthread.h>
void log_info(const char* fmt, ...)
{
va_list va;
__builtin_va_start((va));
vprintf(fmt, va);
;
}
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer = 0;
void* producer(void* ptr)
{
int i;
for (i=0; i<=1000; ++i)
{
pthread_mutex_lock(&the_mutex);
while (0 != buffer)
{
pthread_cond_wait(&condp, &the_mutex);
}
buffer = i;
log_info("%ld buffer %d\\n", pthread_self(), buffer);
pthread_cond_signal(&condc);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
void* consumer(void* ptr)
{
int i;
for (i=0; i<1000; ++i)
{
pthread_mutex_lock(&the_mutex);
while (0 == buffer)
{
pthread_cond_wait(&condc, &the_mutex);
}
buffer = 0;
log_info("%ld buffer %d\\n", pthread_self(), buffer);
pthread_cond_signal(&condp);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
int main(int argc, char** argv)
{
int sig;
int numSigs;
int j;
int sigData;
union sigval sv;
if (5 != argc)
{
log_info("usage:%s pid sig-num data [num-sigs]\\n", argv[0]);
return -1;
}
log_info("%s: pid is %ld, uid is %ld\\n", argv[0], getpid(), getuid());
sig = atoi(argv[2]);
sigData = atoi(argv[3]);
numSigs = atoi(argv[4]);
pid_t pid = atoi(argv[1]);
for (j=0; j<numSigs; ++j)
{
sv.sival_int = sigData + 1;
if (sigqueue(pid, sig, sv) < 0)
{
log_info("sigqueue fail\\n");
return -1;
}
}
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER;
void output_init()
{
return;
}
void output( char * string, ... )
{
va_list ap;
char *ts="[??:??:??]";
struct tm * now;
time_t nw;
pthread_mutex_lock(&m_trace);
nw = time(0);
now = localtime(&nw);
if (now == 0)
printf(ts);
else
printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec);
__builtin_va_start((ap));
vprintf(string, ap);
;
pthread_mutex_unlock(&m_trace);
}
void output_fini()
{
return;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_mutexattr_t lockattr;
int x;
void* t1(void *arg) {
int err = __SMACK_nondet();
pthread_mutex_lock(&lock);
err = pthread_mutex_lock(&lock);
assert(35 == err);
x++;
pthread_mutex_unlock(&lock);
err = pthread_mutex_unlock(&lock);
assert(1 == err);
}
int main() {
x = 0;
lock.attr.type = PTHREAD_MUTEX_ERRORCHECK;
int err = pthread_mutex_lock(&lock);
assert(err = 22);
err = 0;
err = pthread_mutex_unlock(&lock);
assert(err = 22);
pthread_mutexattr_init(&lockattr);
pthread_mutexattr_settype(&lockattr, PTHREAD_MUTEX_ERRORCHECK);
pthread_mutex_init(&lock, &lockattr);
pthread_t t;
pthread_create(&t, 0, t1, 0);
pthread_join(t, 0);
assert(x==1);
}
| 0
|
#include <pthread.h>
void scan()
{
if(file->nbExtension == 0 || file->premier == 0 || file->dernier == 0)
return;
FILE *fichier;
fichier = fopen("data.dbf", "rb+");
FNode *fn;
fn = malloc(sizeof(FNode));
extension *pE;
pE = malloc(sizeof(extension));
fn = file->dernier;
int compteur = 0;
while(fn != 0)
{
if(fn->e.altered)
{
pthread_mutex_lock(&fn->lock);
pE = &fn->e;
pE->altered = 0;
if(pE->id == -1)
{
fseek(fichier, 0L, 2);
unsigned long sz = ftell(fichier);
pE->id = sz/sizeof(extension);
}
fseek(fichier, pE->id*sizeof(extension), 0);
fwrite(pE, sizeof(extension), 1, fichier);
compteur++;
pthread_mutex_unlock(&fn->lock);
}
fn = fn->prev;
} ;
fseek(fichier, 0L, 2);
unsigned long sz = ftell(fichier);
file->nbExtInFichier = sz/sizeof(extension);
fclose(fichier);
free(fn);
}
void startDbwr()
{
while(1)
{
sleep(3);
scan();
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t print_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t print_request_lock = PTHREAD_MUTEX_INITIALIZER;
int print_request,want_exit;
void print_pthread_internal(struct pthread_internal_t * p) {
pthread_mutex_lock(&print_lock);
printf("\\n\\n%s called by %p\\n", __func__, (struct pthread_internal_t *)pthread_self());
printf("p=%p\\n",p);
printf("p->next=%p\\n", p->next);
printf("p->prev=%p\\n", p->prev);
printf("p->tid=%d\\n", p->tid);
printf("p->attr.flags=%04x\\n", p->attr.flags);
printf("p->attr.stack_base=%p\\n", p->attr.stack_base);
printf("p->attr.stack_size=%d\\n", p->attr.stack_size);
printf("p->attr.guard_size=%d\\n", p->attr.guard_size);
printf("p->attr.sched_policy=%d\\n", p->attr.sched_policy);
printf("p->attr.sched_priority=%d\\n", p->attr.sched_priority);
printf("p->cleanup_stack=%p\\n", p->cleanup_stack);
printf("p->start_routine=%p\\n", p->start_routine);
printf("p->return_value=%p\\n", p->return_value);
printf("p->alternate_signal_stack=%p\\n", p->alternate_signal_stack);
pthread_mutex_unlock(&print_lock);
}
void *child(void *arg) {
pthread_t id = pthread_self();
struct pthread_internal_t * p = (struct pthread_internal_t *)id;
int print,run;
printf("child=%p\\n", p);
for(run=1;run;) {
pthread_mutex_lock(&print_request_lock);
if(print_request) {
print_pthread_internal(p);
print_request = 0;
}
run=!want_exit;
pthread_mutex_unlock(&print_request_lock);
usleep(100);
}
}
void set_print(void) {
pthread_mutex_lock(&print_request_lock);
print_request = 1;
pthread_mutex_unlock(&print_request_lock);
}
void wait_print(void) {
int has_printed;
do {
usleep(100);
pthread_mutex_lock(&print_request_lock);
has_printed = (print_request==0);
pthread_mutex_unlock(&print_request_lock);
}while(!has_printed);
}
int main(int argc, char **argv) {
pthread_t id,child_id;
struct pthread_internal_t *p, *child_p;
p=(struct pthread_internal_t *)(id=pthread_self());
printf("main=%p\\n", p);
print_request = 1;
want_exit = 0;
pthread_create(&child_id, 0, &child, 0);
child_p = (struct pthread_internal_t *)child_id;
wait_print();
printf("setting cancel enable on %p\\n", child_p);
child_p->attr.flags |= PTHREAD_ATTR_FLAG_CANCEL_ENABLE;
print_pthread_internal(child_p);
set_print();
wait_print();
printf("setting cancel async on %p\\n", child_p);
child_p->attr.flags |= PTHREAD_ATTR_FLAG_CANCEL_ASYNCRONOUS;
print_pthread_internal(child_p);
set_print();
wait_print();
printf("setting cancel pending on %p\\n", child_p);
child_p->attr.flags |= PTHREAD_ATTR_FLAG_CANCEL_PENDING;
print_pthread_internal(child_p);
pthread_mutex_lock(&print_request_lock);
print_request=want_exit=1;
pthread_mutex_unlock(&print_request_lock);
pthread_join(child_id, 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutexid;
pthread_mutex_t mutexres;
int idcount = 0;
pthread_mutex_t joinmutex[6];
int join[6];
int result[6];
int target;
int sequence[(6 * 30)];
void *thread (void *arg)
{
int id, i, from, count, l_target;
pthread_mutex_lock (&mutexid);
l_target = target;
id = idcount;
idcount++;
pthread_mutex_unlock (&mutexid);
__VERIFIER_assert (id >= 0);
__VERIFIER_assert (id <= 6);
from = id * 30;
count = 0;
for (i = 0; i < 30; i++)
{
if (sequence[from + i] == l_target)
{
count++;
}
if (count > 30)
{
count = 30;
}
}
printf ("t: id %d from %d count %d\\n", id, from, count);
pthread_mutex_lock (&mutexres);
result[id] = count;
pthread_mutex_unlock (&mutexres);
pthread_mutex_lock (&joinmutex[id]);
join[id] = 1;
pthread_mutex_unlock (&joinmutex[id]);
return 0;
}
int main ()
{
int i;
pthread_t t[6];
int count;
for (i = 0; i < (6 * 30); i++)
{
sequence[i] = __VERIFIER_nondet_int (0, 3);
printf ("m: init i %d seq %d\\n", i, sequence[i]);
}
target = __VERIFIER_nondet_int (0, 3);
printf ("m: target %d\\n", target);
pthread_mutex_init (&mutexid, 0);
pthread_mutex_init (&mutexres, 0);
for (i = 0; i < 6; i++)
{
pthread_mutex_init (&joinmutex[i], 0);
result[i] = 0;
join[i] = 0;
}
i = 0;
pthread_create (&t[i], 0, thread, 0); i++;
pthread_create (&t[i], 0, thread, 0); i++;
pthread_create (&t[i], 0, thread, 0); i++;
pthread_create (&t[i], 0, thread, 0); i++;
pthread_create (&t[i], 0, thread, 0); i++;
pthread_create (&t[i], 0, thread, 0); i++;
__VERIFIER_assert (i == 6);
int j;
i = 0;
pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; }
pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; }
pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; }
pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; }
pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; }
pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; }
if (i != 6)
{
return 0;
}
__VERIFIER_assert (i == 6);
count = 0;
for (i = 0; i < 6; i++)
{
count += result[i];
printf ("m: i %d result %d count %d\\n", i, result[i], count);
}
printf ("m: final count %d\\n", count);
__VERIFIER_assert (count >= 0);
__VERIFIER_assert (count <= (6 * 30));
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t cond_produce;
pthread_cond_t cond_consume;
item_t buffer[4];
volatile int counter=0;
volatile int out=0;
volatile int in=0;
void *producerWork(void* args)
{
item_t item;
size_t latency = (size_t)args;
static int item_count = 0;
int i; for(i=0; i<10; i++) {
pthread_mutex_lock(&lock);
while( counter == 4 ) {
printf("[producer] buffer is FULL, I am waiting for SLOT.\\n");
pthread_cond_wait(&cond_consume, &lock);
}
item = ++item_count;
printf("[producer] I am producing item %d...\\n", item);
buffer[in] = item;
in = (in+1) % 4;
counter++;
pthread_mutex_unlock(&lock);
printf("[producer] Hey! I was produced item %d.\\n", item);
pthread_cond_signal(&cond_produce);
usleep((latency)*1000);
}
return 0;
}
void *consumerWork(void* args)
{
item_t item;
size_t latency = (size_t)args;
int i; for(i=0; i<10; i++) {
pthread_mutex_lock(&lock);
while( counter == 0 ) {
printf(" [CONSUMER] buffer is EMPTY, I am waiting for ITEM.\\n");
pthread_cond_wait(&cond_produce, &lock);
}
item = buffer[out];
out = (out+1) % 4;
counter--;
pthread_mutex_unlock(&lock);
printf(" [CONSUMER] I am consumming item %d...\\n", item);
printf(" [CONSUMER] Hey! I was consumed item %d.\\n", item);
pthread_cond_signal(&cond_consume);
usleep((latency)*1000);
}
return 0;
}
int main(int argc, char *argv[])
{
pthread_t consumer;
pthread_t producer;
pthread_mutex_init(&lock, 0);
pthread_cond_init(&cond_consume, 0);
pthread_cond_init(&cond_produce, 0);
memset(buffer, -1, sizeof(buffer));
pthread_create(&producer, 0, producerWork, (void*)200);
pthread_create(&consumer, 0, consumerWork, (void*)1000);
usleep((100)*1000);
pthread_join(producer, 0);
pthread_join(consumer, 0);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond_consume);
pthread_cond_destroy(&cond_produce);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
sem_t full;
sem_t empty;
int pro = 0;
int pro_id = 0;
int con = 0;
int con_id = 0;
void *producer();
void *consumer();
void print_buff();
int main(){
return 0;
}
void *producer(){
int id = ++ pro_id;
while(1){
sleep(1);
sem_wait(&empty);
pthread_mutex_lock(&mutex);
pro = pro % 32;;
printf("Producer %d in %d.", id, pro);
++pro;
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
| 1
|
#include <pthread.h>
struct{
int file_descript;
char* url[15];
char buffer[10];
int bytes_read_form_file;
int bytes_write_in_file;
}file_structure;
int bytes_write = 0;
int bytes_read = 0;
int fd[2];
int eof = -1;
pthread_mutex_t mutex;
sem_t empty, full;
pthread_t t_A,t_B;
pthread_attr_t attr;
void *runnerThreadA();
void *runnerThreadB();
void initializeData();
void initializeData() {
pthread_mutex_init(&mutex, 0);
sem_init(&empty, 0, 0);
sem_init(&full, 0, 0);
pthread_attr_init(&attr);
}
int main(void){
if(pipe(fd) < 0)
{
perror("pipe error");
exit(1);
}
printf("pipe() was successful, fds are %d, %d\\n", fd[0], fd[1]);
initializeData();
sem_post(&full);
pthread_create(&t_A,&attr,runnerThreadA, 0);
pthread_create(&t_B,&attr,runnerThreadB, 0);
pthread_join(t_A,(void **)0);
pthread_join(t_B,(void **)0);
printf("Finish\\n");
}
void *runnerThreadA(){
char url[]="1.txt";
char buffer[10];
int arq = open(url, O_RDONLY);
int bytes_read_from_file = -1;
int bytes_write_in_file = 0;
if(arq < 0)
{
perror("Impossible open the file");
exit(1);
}
while(bytes_read_from_file !=0)
{
bytes_read_from_file = read(arq, buffer, 10);
if(bytes_read_from_file !=0){
bytes_write_in_file = write(fd[1], buffer, bytes_read_from_file);
sem_post(&empty);
pthread_mutex_lock(&mutex);
bytes_write += bytes_write_in_file;
pthread_mutex_unlock(&mutex);
printf("Thread_A wrote %d bytes into the pipe\\n", bytes_write);
}
}
eof = 0;
sem_post(&empty);
close(arq);
}
void *runnerThreadB(){
char collectFromPipe[10];
char last = 'a';
int receive;
int bytes = 0;
int bytes_read = 0;
int bytes_read_from_file = 0;
receive = open("receive.txt", O_CREAT|O_RDWR, 0666);
if(receive < 0)
{
perror("Impossible to open the receive file");
exit(1);
}
sem_wait(&empty);
while(bytes_read != bytes_write || bytes_read_from_file == 10){
bytes_read_from_file = read(fd[0], collectFromPipe, 10);
pthread_mutex_lock(&mutex);
bytes_read += bytes_read_from_file;
pthread_mutex_unlock(&mutex);
bytes = write(receive, collectFromPipe, bytes_read_from_file);
if(bytes_read < 500)
printf("Thread_B read %d bytes from the pipe\\n",bytes_read);
}
close(receive);
}
| 0
|
#include <pthread.h>
struct msg {
struct msg *m_next;
};
struct msg *workq;
pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;
void
process_msg(void)
{
struct msg *mp;
for (;;) {
pthread_mutex_lock(&qlock);
while (workq == 0)
pthread_cond_wait(&qready, &qlock);
mp = workq;
workq = mp->m_next;
pthread_mutex_unlock(&qlock);
}
}
void
enqueue_msg(struct msg *mp)
{
pthread_mutex_lock(&qlock);
mp->m_next = workq;
workq = mp;
pthread_mutex_unlock(&qlock);
pthread_cond_signal(&qready);
}
| 1
|
#include <pthread.h>
extern unsigned volatile int *lock;
FILE *fileout_basicmath;
FILE *fileout_qsort;
FILE *fileout_susancorners;
FILE *fileout_dijkstra;
FILE *filein_qsort;
FILE *filein_susancorners;
FILE *filein_dijkstra;
volatile int procCounter = 0;
volatile int barrier_in = 0;
volatile int procsFinished = 0;
extern pthread_mutex_t mutex_print;
extern pthread_mutex_t mutex_malloc;
int NSOFTWARES = 4;
void open_files();
void close_files();
int main(int argc, char *argv[])
{
register int procNumber;
AcquireGlobalLock();
procNumber = procCounter++;
ReleaseGlobalLock();
if (procNumber == 0){
printf("\\n");
printf("--------------------------------------------------------------------\\n");
printf("------------------------- MPSoCBench -----------------------------\\n");
printf("-----------------Running: multi_network_automotive -----------------\\n");
printf("------------Basicmath, Susan-corners, Dijkstra, Qsort---------------\\n");
printf("--------------------------------------------------------------------\\n");
printf("\\n");
open_files();
pthread_mutex_init(&mutex_print,0);
pthread_mutex_init(&mutex_malloc,0);
AcquireGlobalLock();
barrier_in = 1;
ReleaseGlobalLock();
main_basicmath();
pthread_mutex_lock(&mutex_print);
printf("\\nBasicmath finished.\\n");
pthread_mutex_unlock(&mutex_print);
}
else if (procNumber == 1)
{
while(barrier_in == 0);
main_dijkstra();
pthread_mutex_lock(&mutex_print);
printf("\\nDijkstra finished.\\n");
pthread_mutex_unlock(&mutex_print);
}
else if (procNumber == 2)
{
while(barrier_in == 0);
main_qsort();
pthread_mutex_lock(&mutex_print);
printf("\\nQsort finished.\\n");
pthread_mutex_unlock(&mutex_print);
}
else if (procNumber == 3)
{
while(barrier_in == 0);
main_susancorners();
pthread_mutex_lock(&mutex_print);
printf("\\nSusan corners finished.\\n");
pthread_mutex_unlock(&mutex_print);
}
else
{
printf("\\nERROR!\\n");
}
AcquireGlobalLock();
procsFinished++;
if(procsFinished == NSOFTWARES)
{
close_files();
}
ReleaseGlobalLock();
_exit(0);
return 0;
}
void close_files ()
{
fclose(fileout_basicmath);
fclose(fileout_susancorners);
fclose(fileout_qsort);
fclose(fileout_dijkstra);
}
void open_files ()
{
fileout_basicmath = fopen("output_basicmath","w");
if (fileout_basicmath == 0){
printf("Error: fopen() fileout_basicmath\\n");
exit(1);
}
fileout_susancorners = fopen("output_susancorners","w");
if (fileout_susancorners == 0){
printf("Error: fopen() fileout_susancorners\\n");
exit(1);
}
fileout_qsort = fopen("output_qsort","w");
if (fileout_qsort == 0){
printf("Error: fopen() fileout_qsort\\n");
exit(1);
}
fileout_dijkstra = fopen("output_dijkstra","w");
if (fileout_dijkstra == 0){
printf("Error: fopen() fileout_dijkstra\\n");
exit(1);
}
filein_qsort = fopen("input_small.dat","r");
if (filein_qsort == 0){
printf("Error: fopen() filein_qsort\\n");
exit(1);
}
filein_susancorners = fopen("input_large2.pgm","r");
if (filein_susancorners == 0){
printf("Error: fopen() filein_susancorners\\n");
exit(1);
}
filein_dijkstra = fopen("input.dat","r");
if (filein_dijkstra == 0){
printf("Error: fopen() filein_dijkstra\\n");
exit(1);
}
}
| 0
|
#include <pthread.h>
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo{
int f_count;
pthread_mutex_t f_lock;
struct foo *f_next;
int f_id;
};
struct foo* foo_alloc(void)
{
struct foo *fp;
int idx;
if((fp = malloc(sizeof(struct foo))) != 0)
{
fp->f_count = 1;
if(pthread_mutex_init(&fp->f_lock, 0) != 0)
{
free(fp);
return 0;
}
idx = (((unsigned long) fp)%29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
}
return fp;
}
void foo_hold(struct foo* fp)
{
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
struct foo* foo_find(int id)
{
struct foo *fp;
int idx;
idx =(((unsigned long) fp)%29);
pthread_mutex_lock(&hashlock);
for(fp = fh[idx]; fp != 0; fp = fp->f_next)
{
if(fp->f_id == id)
{
foo_hold(fp);
break;
}
}
pthread_mutex_unlock(&hashlock);
return fp;
}
void foo_rele(struct foo* fp)
{
struct foo *tfp;
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 = (((unsigned long) fp)%29);
tfp = fh[idx];
if(tfp == fp)
{
fh[idx] = fp->f_next;
}
else
{
while(tfp->f_next != fp)
tfp = tfp->f_next;
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
}
else
{
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
}
}
| 1
|
#include <pthread.h>
int fnLoadWeights( void )
{
return TRUE;
}
int fnStockCompare( const void* p1, const void* p2 )
{
return strcmp( (char *)p1, (char *)p2 );
}
int fnLoadStocks( void )
{
char szBuffer[LINE_BUFFER_SIZE];
char szListFile[BUFFER_SIZE];
char szStock[BUFFER_SIZE];
int iStockCount=0;
int iSkip=FALSE;
FILE *fpListFile;
int i;
fnDebug( "Loading Stock List" );
pthread_mutex_lock( &config_mutex );
fnGetConfigSetting( szListFile, "STOCKLISTFILE", DEFAULT_STOCK_LIST );
pthread_mutex_unlock( &config_mutex );
fpListFile = fopen( szListFile, "r" );
if( fpListFile == 0 )
return 0;
while ( fgets(szBuffer, LINE_BUFFER_SIZE-2, fpListFile) != 0)
{
bzero( szStock, sizeof(szStock) );
strcpy( szStock, szBuffer );
if( szStock[strlen(szStock)-1] == 0x0A || szStock[strlen(szStock)-1] == 0x0D )
szStock[strlen(szStock)-1] = 0x00;
iSkip=FALSE;
for( i=0; i<iStockCount; i++ )
{
if( strcmp( szStock, gszStocks[i] ) == 0 )
{
iSkip=TRUE;
break;
}
}
if( iSkip )
{
snprintf( szBuffer, sizeof(szBuffer), "Skipping duplicate %s", szStock );
fnDebug( szBuffer );
}
else
{
strcpy( gszStocks[iStockCount], szStock );
snprintf( szBuffer, sizeof(szBuffer), "%d Loaded stock %s", iStockCount, gszStocks[iStockCount] );
fnDebug( szBuffer );
iStockCount++;
if (iStockCount == MAXIMUM_STOCKS )
{
fnHandleError( "fnLoadStocks", "Maximum stocks reached" );
break;
}
}
}
fclose(fpListFile);
iStocksLoaded = iStockCount;
QQQQ = fnStockFilter( "QQQQ" );
if( QQQQ == STOCK_NOT_FOUND )
fnHandleError( "fnLoadStocks", "QQQQ Index tracking stock not found" );
else
{
snprintf( szBuffer, sizeof(szBuffer), "Found QQQQ Index tracking Stock %d", QQQQ );
fnDebug( szBuffer );
}
snprintf( szBuffer, sizeof(szBuffer), "%i stocks loaded", iStockCount );
fnDebug( szBuffer );
return iStockCount;
}
double fnLoadDivisor( void )
{
return 0.00;
}
int fnStockFilter( char * szStock )
{
int i;
for( i=0; i<iStocksLoaded; i++ )
if( strcmp( szStock, gszStocks[i] ) == 0 )
return i;
return STOCK_NOT_FOUND;
}
int fnCalculateIndex( void )
{
return TRUE;
}
int fnCalculateBidAskIndex( void )
{
return TRUE;
}
void fnCalculateFV( void )
{
}
| 0
|
#include <pthread.h>
int cuenta = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cuenta_ok = PTHREAD_COND_INITIALIZER;
int thread_ids[4] = {0,1,2,3};
int usa_timed;
int usa_broad;
void *inc_cuenta(void *idp)
{
int i=0;
int *my_id = idp;
struct timespec tim = {0, 1000000L};
printf("inc_cuenta: thread %d\\n", *my_id);
for (i=0; i<10; i++)
{
pthread_mutex_lock(&lock);
cuenta++;
printf("inc_cuenta: thread %d, cuenta = %d\\n",
*my_id, cuenta);
if(cuenta == 12)
{
printf("inc_cuenta: Thread %d, cuenta %d; alcanzado nivel.\\n",
*my_id, cuenta);
if(usa_broad) pthread_cond_broadcast(&cuenta_ok);
else pthread_cond_signal(&cuenta_ok);
}
pthread_mutex_unlock(&lock);
nanosleep(&tim, 0);
}
return(0);
}
void *mira_cuenta(void *idp)
{
int i=0;
int *my_id = idp;
struct timespec timout;
struct timespec tim = {0, 1000000L};
int res;
int cuenta_leida;
printf("mira_cuenta: thread %d\\n", *my_id);
pthread_mutex_lock(&lock);
while (cuenta < 12)
{
printf("thread %d esperando.\\n", *my_id);
if(usa_timed)
{
clock_gettime(CLOCK_REALTIME, &timout);
timout.tv_sec += 1;
res = pthread_cond_timedwait(&cuenta_ok, &lock, &timout);
if(res)
{
printf("%s\\n", strerror(res));
printf("Soy %d; ya me he hartado de esperar.\\n", *my_id);
pthread_mutex_unlock(&lock);
pthread_exit((void *)res);
}
}
else res = pthread_cond_wait(&cuenta_ok, &lock);
}
cuenta_leida = cuenta;
pthread_mutex_unlock(&lock);
printf("mira_cuenta: thread %d, cuenta leida %d\\n", *my_id, cuenta_leida);
return(0);
}
void prueba(void);
int main(void)
{
printf("\\nPrueba sin broadcast y sin temporizador\\n");
usa_broad = 0;
usa_timed = 0;
prueba();
printf("\\nPrueba con broadcast y sin temporizador\\n");
usa_broad = 1;
usa_timed = 0;
prueba();
printf("\\nPrueba sin broadcast y con temporizador\\n");
usa_broad = 0;
usa_timed = 1;
prueba();
printf("\\nPrueba con broadcast y con temporizador\\n");
usa_broad = 1;
usa_timed = 1;
prueba();
}
void prueba(void)
{
int i;
pthread_t threads[4];
cuenta = 0;
pthread_create(&threads[2], 0, mira_cuenta, (void *)&thread_ids[2]);
pthread_create(&threads[3], 0, mira_cuenta, (void *)&thread_ids[3]);
pthread_create(&threads[0], 0, inc_cuenta, (void *)&thread_ids[0]);
pthread_create(&threads[1], 0, inc_cuenta, (void *)&thread_ids[1]);
sleep(2);
printf("prueba: esperando terminacion de los hilos\\n");
for (i = 0; i < 4; i++)
{
pthread_cond_signal(&cuenta_ok);
pthread_join(threads[i], 0);
}
printf("prueba: han terminado todos\\n");
}
| 1
|
#include <pthread.h>
pthread_mutex_t *lvls;
pthread_cond_t *cond_lvls;
int dronWeight[5];
int floorWeight[5];
int totalWeight[5];
void *dron(void *arg)
{
int cont = 0;
while(cont < 5)
{
pthread_mutex_lock(lvls+cont);
if(dronWeight[(int)arg]+totalWeight[cont] > floorWeight[cont])
{
pthread_cond_wait(cond_lvls+cont, lvls+cont);
pthread_mutex_unlock(lvls+cont);
}
else
{
totalWeight[cont] += dronWeight[(int)arg];
pthread_mutex_unlock(lvls+cont);
int buy = rand()%3;
sleep(buy);
pthread_mutex_lock(lvls+cont);
totalWeight[cont] -= dronWeight[(int)arg];
pthread_cond_broadcast(cond_lvls+cont);
pthread_mutex_unlock(lvls+cont);
cont++;
}
}
pthread_exit(0);
}
int main(int argc, char *argv[])
{
pthread_t *drons = (pthread_t*)malloc(sizeof(pthread_t)*5*2);
lvls = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t)*5);
cond_lvls = (pthread_cond_t*)malloc(sizeof(pthread_cond_t)*5);
srand(time(0));
int i = 0;
for(i; i < 5; ++i)
{
floorWeight[i] = rand()% 10+5;
totalWeight[i] = 0;
printf("The section %d, had a weight of %d\\n", i, floorWeight[i
]);
}
for(i = 0; i < 5; ++i)
{
pthread_mutex_init(lvls+i, 0);
pthread_cond_init(cond_lvls+i, 0);
}
for(i = 0; i < 5; ++i)
{
dronWeight[i] = rand() % 4+1;
pthread_create(drons+i, 0, dron, (i));
}
for(i = 0; i < 5; ++i)
pthread_join(*(drons), 0);
free(lvls);
free(cond_lvls);
free(drons);
return 0;
}
| 0
|
#include <pthread.h>
int buf[5], f, index1 = 0;
pthread_mutex_t mutex;
pthread_cond_t full, empty;
int cntr = 0, i = 0, cntr1 = 0;
void *producer (void *arg)
{
for (cntr = 0; cntr < 10; cntr++)
{
printf ("\\n\\tProducer: Checking if buffer has some space");
pthread_mutex_lock (&mutex);
while (index1 == 5)
{
printf
("\\n\\n\\tProducer: buffer already full, will block until signalled");
pthread_cond_wait (&empty, &mutex);
}
buf[index1] = i;
index1++;
printf ("\\nProducer: Produced item is %d\\n", i);
i++;
pthread_cond_signal (&full);
pthread_mutex_unlock (&mutex);
}
pthread_exit (0);
}
void *consumer (void *arg)
{
int item;
for (cntr1 = 0; cntr1 < 10; cntr1++)
{
printf ("\\n\\tConsumer: Checking if buffer has some item");
pthread_mutex_lock (&mutex);
while (index1 == 0)
{
printf ("\\n\\n\\tConsumer: buffer empty, will block until signalled");
pthread_cond_wait (&full, &mutex);
}
item = buf[index1 - 1];
index1--;
printf ("\\n\\t\\t\\tConsumer: Consumed item is %d\\n", item);
pthread_cond_signal (&empty);
pthread_mutex_unlock (&mutex);
sleep (1);
}
pthread_exit (0);
}
void
main ()
{
int i;
pthread_t tid1, tid2;
pthread_mutex_init (&mutex, 0);
pthread_cond_init (&full, 0);
pthread_cond_init (&empty, 0);
pthread_create (&tid1, 0, producer, 0);
pthread_create (&tid2, 0, consumer, 0);
pthread_join (tid1, 0);
pthread_join (tid2, 0);
pthread_mutex_destroy (&mutex);
pthread_cond_destroy (&full);
pthread_cond_destroy (&empty);
}
| 1
|
#include <pthread.h>
static void eatIfOk(int i);
static int leftNghbr(int i);
static int rightNghbr(int i);
static pthread_mutex_t dpMutex;
static pthread_cond_t okToEat[N_PHIL];
static state_t state[N_PHIL];
void dpPickup(int i) {
pthread_mutex_lock(&dpMutex);
state[i] = HUNGRY;
eatIfOk(i);
while (state[i] != EATING) {
pthread_cond_wait(&okToEat[i], &dpMutex);
}
pthread_mutex_unlock(&dpMutex);
}
void dpPutdown(int i) {
pthread_mutex_lock(&dpMutex);
state[i] = THINKING;
eatIfOk(rightNghbr(i));
eatIfOk(leftNghbr(i));
pthread_mutex_unlock(&dpMutex);
}
void dpPrintstate(int i){
static char stat[] = "THE";
pthread_mutex_lock(&dpMutex);
printf("%d:", i);
for (int i=0; i<N_PHIL; i++) {
printf("%c", stat[(int)(state[i])]);
}
printf("\\n");
pthread_mutex_unlock(&dpMutex);
}
void dpInit(void) {
int rc;
rc = pthread_mutex_init(&dpMutex, 0);
assert(rc == 0);
for (int i=0; i<N_PHIL; i+=1) {
state[i] = THINKING;
rc = pthread_cond_init(&okToEat[i], 0);
assert(rc == 0);
}
}
static void eatIfOk (int i) {
if ((state[i] == HUNGRY) &&
(state[rightNghbr(i)] != EATING) &&
(state[leftNghbr(i)] != EATING)) {
state[i] = EATING;
pthread_cond_signal(&okToEat[i]);
}
}
static int leftNghbr(int i) {
return ((i+(N_PHIL-1)) % N_PHIL);
}
static int rightNghbr(int i) {
return ((i+1) % N_PHIL);
}
| 0
|
#include <pthread.h>
char **buffer1;
char **buffer2;
pthread_mutex_t mutex, mutex2;
pthread_cond_t spaceAvailable, itemAvailable;
int count1, count2;
int in1, in2, out1, out2;
int fp_green, fp_black, fp_output;
void produce( void *ptr );
void consume( void *ptr );
void main()
{
buffer1 = malloc(4 * sizeof(char*));
buffer2 = malloc(4 * sizeof(char*));
int i;
for (i = 0; i < 4; i++) {
buffer1[i] = malloc(50 * sizeof(char));
}
int j;
for (j = 0; j < 4; j++) {
buffer2[j] = malloc(50 * sizeof(char));
}
int perms = 0740;
if ((fp_green = open("prod_green.txt", (O_WRONLY | O_CREAT), perms)) == -1) {
perror("Failed to open file:");
}
if ((fp_black = open("prod_black.txt", (O_WRONLY | O_CREAT), perms)) == -1) {
perror("Failed to open file:");
}
if ((fp_output = open("output.txt", (O_WRONLY | O_CREAT), perms)) == -1) {
perror("Failed to open file:");
}
char* id_green = (char *) malloc(100);
char* id_black = (char *) malloc(100);
strcpy(id_green, "GREEN");
strcpy(id_black, "BLACK");
count1 = count2 = in1 = in2 = out1 = out2 = 0;
pthread_mutex_init(&mutex, 0);
pthread_mutex_init(&mutex2, 0);
pthread_t producer_green;
pthread_t producer_black;
pthread_t consumer;
pthread_create(&producer_green, 0, (void *) &produce, (void *) id_green);
pthread_create(&producer_black, 0, (void *) &produce, (void *) id_black);
pthread_create(&consumer, 0, (void *) &consume, 0);
pthread_join(producer_green, 0);
pthread_join(producer_black, 0);
pthread_join(consumer, 0);
pthread_mutex_destroy(&mutex);
free(id_green);
free(id_black);
for (i = 0; i < 4; i++) {
free( buffer1[i] );
}
for (j = 0; i < 4; j++) {
free( buffer2[j] );
}
free( buffer1[1] );
free( buffer2[2] );
exit(0);
}
void produce( void *ptr ){
char *item = (char *) ptr;
char *time = malloc(50 * sizeof(char));
char *message = malloc(50 * sizeof(char));
struct timeval tv;
int fwrite;
struct timespec tim, tim2;
tim.tv_sec = 0;
tim.tv_nsec = 100000000L;
int i;
for(i = 1; i <= 50; i++) {
pthread_mutex_lock(&mutex);
while (count1 + count2 == 8){
while ( pthread_cond_wait(&spaceAvailable, &mutex) != 0);
}
gettimeofday(&tv, 0);
sprintf(time, " %ld", tv.tv_usec);
strcat(message, item);
strcat(message, time);
strcat(message, "\\n");
if(count1 < 4) {
strcpy(buffer1[in1], message);
fwrite = write(fp_green, message, strlen(message));
in1 = (in1 + 1) % 4;
count1++;
}else {
strcpy(buffer2[in2], message);
fwrite = write(fp_black, message, strlen(message));
in2 = (in2 + 1) % 4;
count2++;
}
printf("%s items produced: %d\\n",item, i);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&itemAvailable);
memset(time,0, 50);
memset(message,0, 50);
nanosleep(&tim , &tim2);
}
printf("%s Producer exiting!\\n", item);
fflush(0);
free(item);
exit(0);
}
void consume( void *ptr){
char *message = (char *) malloc(50 * sizeof(char));
char *reportFile = (char*) malloc(50 * sizeof(char));
int fwrite;
int i = 1;
while (i <= 200) {
pthread_mutex_lock( &mutex );
while (count1 + count2 == 0){
while( pthread_cond_wait(&itemAvailable, &mutex) != 0 );
}
if(count1 > 0) {
count1--;
fwrite = write(fp_output, buffer1[out1], strlen(buffer1[out1]));
out1 = (out1 + 1) % 4;
}else {
count2--;
fwrite = write(fp_output, buffer2[out2], strlen(buffer2[out2]));
out2 = (out2 + 1) % 4;
}
printf("Consumer: items consumed: %d\\n", i);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&spaceAvailable);
i++;
}
free(message);
free(reportFile);
printf("Consumer exiting\\n");
exit(0);
}
| 1
|
#include <pthread.h>
int q[2];
int qsiz;
pthread_mutex_t mq;
void queue_init ()
{
pthread_mutex_init (&mq, 0);
qsiz = 0;
}
void queue_insert (int x)
{
int done = 0;
printf ("prod: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz < 2)
{
done = 1;
q[qsiz] = x;
qsiz++;
}
pthread_mutex_unlock (&mq);
}
}
int queue_extract ()
{
int done = 0;
int x = -1, i = 0;
printf ("consumer: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz > 0)
{
done = 1;
x = q[0];
qsiz--;
for (i = 0; i < qsiz; i++) q[i] = q[i+1];
__VERIFIER_assert (qsiz < 2);
q[qsiz] = 0;
}
pthread_mutex_unlock (&mq);
}
return x;
}
void swap (int *t, int i, int j)
{
int aux;
aux = t[i];
t[i] = t[j];
t[j] = aux;
}
int findmaxidx (int *t, int count)
{
int i, mx;
mx = 0;
for (i = 1; i < count; i++)
{
if (t[i] > t[mx]) mx = i;
}
__VERIFIER_assert (mx >= 0);
__VERIFIER_assert (mx < count);
t[mx] = -t[mx];
return mx;
}
int source[4];
int sorted[4];
void producer ()
{
int i, idx;
for (i = 0; i < 4; i++)
{
idx = findmaxidx (source, 4);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 4);
queue_insert (idx);
}
}
void consumer ()
{
int i, idx;
for (i = 0; i < 4; i++)
{
idx = queue_extract ();
sorted[i] = idx;
printf ("m: i %d sorted = %d\\n", i, sorted[i]);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 4);
}
}
void *thread (void * arg)
{
(void) arg;
producer ();
return 0;
}
int main ()
{
pthread_t t;
int i;
__libc_init_poet ();
for (i = 0; i < 4; i++)
{
source[i] = __VERIFIER_nondet_int(0,20);
printf ("m: init i %d source = %d\\n", i, source[i]);
__VERIFIER_assert (source[i] >= 0);
}
queue_init ();
pthread_create (&t, 0, thread, 0);
consumer ();
pthread_join (t, 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t locks[1];
int x = 0;
void *thread0(void *arg)
{
pthread_mutex_lock(locks + 0);
pthread_mutex_unlock(locks + 0);
x = 1;
pthread_exit(0);
}
void *thread1(void *arg)
{
x = 0;
pthread_mutex_lock(locks + 0);
x = 2;
pthread_mutex_unlock(locks + 0);
pthread_exit(0);
}
int main()
{
pthread_t thr[2];
int tids[2];
for (int i = 0; i < 2; ++i) {
tids[i] = i;
}
pthread_create(thr + 0, 0, thread0, tids + 0);
pthread_create(thr + 1, 0, thread1, tids + 1);
pthread_join(thr[0], 0);
pthread_join(thr[1], 0);
return(0);
}
| 1
|
#include <pthread.h>
void *(*process) (void *arg);
void *arg;
struct worker *next;
} CThread_workder;
pthread_mutex_t queue_lock;
pthread_cond_t queue_ready;
CThread_workder *queue_head;
int shutdown;
pthread_t *thread_id;
int max_thread_num;
int cur_queue_size;
} CThread_pool;
CThread_pool *Pool_init(int max_thread_num);
int Pool_add_worker (CThread_pool *pool, void *(*process)(void *arg), void *arg );
int Pool_destroy(CThread_pool *pool);
static void *Pool_thread_routine(void *arg);
CThread_pool *Pool_init(int max_thread_num) {
CThread_pool *pool = (CThread_pool*)malloc(sizeof (CThread_pool));
if (pool == 0 ) {
return 0;
}
pthread_mutex_init(&(pool->queue_lock), 0);
pthread_cond_init(&(pool->queue_ready), 0);
pool->queue_head = 0;
pool->max_thread_num = max_thread_num;
pool->cur_queue_size = 0;
pool->shutdown = 0;
pool->thread_id = (pthread_t *) malloc (max_thread_num * sizeof (pthread_t));
int i = 0;
for (i = 0; i < max_thread_num; i++) {
pthread_create(&(pool->thread_id[i]), 0, Pool_thread_routine, pool);
}
return pool;
}
int Pool_add_worker(CThread_pool *pool, void *(*process)(void *arg), void *arg) {
CThread_workder *new_worker = (CThread_workder *)malloc(sizeof(CThread_workder));
new_worker->process = process;
new_worker->arg = arg;
new_worker->next = 0;
pthread_mutex_lock(&(pool->queue_lock));
CThread_workder *item = pool->queue_head;
if (item != 0){
while (item->next != 0) {
item = item->next;
}
item->next = new_worker;
} else {
pool->queue_head = new_worker;
}
assert(pool->queue_head != 0);
pool->cur_queue_size++;
pthread_mutex_unlock(&(pool->queue_lock));
pthread_cond_signal(&(pool->queue_ready));
return 0;
}
int Pool_destroy(CThread_pool *pool) {
if (pool->shutdown) {
return -1;
}
pool->shutdown = 1;
pthread_cond_broadcast(&(pool->queue_ready));
int i;
for (i = 0; i < pool->max_thread_num; i++) {
pthread_join(pool->thread_id[i], 0);
printf("release the thread worker 0x%x\\n", pool->thread_id[i]);
}
free(pool->thread_id);
CThread_workder *head = 0;
while (pool->queue_head != 0) {
head = pool->queue_head;
pool->queue_head = pool->queue_head->next;
free(head);
}
pthread_mutex_destroy(&(pool->queue_lock));
pthread_cond_destroy(&(pool->queue_ready));
free(pool);
return 0;
}
static void *Pool_thread_routine(void *arg) {
printf("starting thread 0x%x\\n", pthread_self());
CThread_pool *pool = (CThread_pool *)arg;
while(1) {
pthread_mutex_lock(&(pool->queue_lock));
while(pool->cur_queue_size == 0 && !pool->shutdown) {
printf("thread 0x%x is waiting\\n", pthread_self());
pthread_cond_wait(&(pool->queue_ready), &(pool->queue_lock));
}
if (pool->shutdown) {
pthread_mutex_unlock(&(pool->queue_lock));
printf("thread 0x%x will exit!\\n", pthread_self());
pthread_exit(0);
}
printf("thread 0x%x is starting to work\\n", pthread_self());
assert(pool->cur_queue_size != 0);
assert(pool->queue_head != 0);
pool->cur_queue_size--;
CThread_workder *worker = pool->queue_head;
pool->queue_head = worker->next;
pthread_mutex_unlock(&(pool->queue_lock));
worker->process(worker->arg);
free(worker);
worker = 0;
}
pthread_exit(0);
}
void *my_process(void *arg) {
printf("thread_id is 0x%x, working on task %d\\n", pthread_self(), *(int*)arg);
sleep(1);
return 0;
}
main(void)
{
CThread_pool *rpool = Pool_init(3);
CThread_pool *wpool = Pool_init(3);
int workingnum[10];
int i;
for (i = 0; i < 10; i++) {
workingnum[i] = i * 2;
Pool_add_worker(pool, my_process, &workingnum[i]);
}
sleep(5);
printf("\\nbegin to release sources\\n");
Pool_destroy(pool);
printf("\\nend");
}
| 0
|
#include <pthread.h>
struct thread_args {
int tid;
int inc;
int loop;
};
int count = 0;
pthread_mutex_t count_mutex;
void *inc_count(void *arg)
{
int i,loc;
struct thread_args *my_args = (struct thread_args*) arg;
loc = 0;
for (i = 0; i < my_args->loop; i++) {
pthread_mutex_lock(&count_mutex);
count = count + my_args->inc;
pthread_mutex_unlock(&count_mutex);
loc = loc + my_args->inc;
}
printf("Thread: %d finished. Counted: %d\\n", my_args->tid, loc);
free(my_args);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int i, loop, inc;
struct thread_args *targs;
pthread_t threads[3];
pthread_attr_t attr;
if (argc != 3) {
printf("Usage: PTCOUNT LOOP_BOUND INCREMENT\\n");
exit(0);
}
loop = atoi(argv[1]);
inc = atoi(argv[2]);
pthread_mutex_init(&count_mutex, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (i = 0; i < 3; i++) {
targs = malloc(sizeof(targs));
targs->tid = i;
targs->loop = loop;
targs->inc = inc;
pthread_create(&threads[i], &attr, inc_count, targs);
}
for (i = 0; i < 3; i++) {
pthread_join(threads[i], 0);
}
printf ("Final value of count = %d.\\n", count);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_exit (0);
}
| 1
|
#include <pthread.h>
int buffer=0;
pthread_mutex_t mutex;
void delay(int secs) {
time_t beg = time(0), end = beg + secs;
do {
} while (time(0) < end);
}
void *read(void *i){
long identify=(long)i;
int flag;
for(flag=0;flag<4;flag++){
pthread_mutex_lock(&mutex);
delay(rand()%2);
printf("l %ld %d\\n",identify,buffer);
delay(rand()%2);
pthread_mutex_unlock(&mutex);
delay(rand()%4);
}
}
void *write(void *i){
long identify=(long)i;
int flag;
for(flag=0;flag<4;flag++){
pthread_mutex_lock(&mutex);
delay(rand()%2);
printf("%ld quer escrever...\\n", identify);
delay(rand()%2);
buffer=random()%20;
delay(rand()%2);
printf("e %ld %d\\n",identify,buffer);
delay(rand()%2);
pthread_mutex_unlock(&mutex);
delay(rand()%4);
}
}
int main(){
int status=0;
long laco;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
pthread_mutex_init(&mutex, 0);
pthread_t threadWriter[10],threadReader[10];
for(laco=0;laco<10;laco++){
pthread_create(&threadWriter[laco],&attr,write,(void *)laco);
pthread_create(&threadReader[laco],&attr,read,(void *)laco);
}
for(laco=0;laco<10;laco++){
pthread_join(threadReader[laco], (void **)&status);
pthread_join(threadWriter[laco], (void **)&status);
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
static int gDone = 0;
static int kMaxIterations = 10;
struct thread_closure {
int tid;
int nice;
int iters;
};
static pthread_mutex_t gTheBigLock;
static pthread_cond_t gDoneCond;
static void Report(struct thread_closure *tc) {
pthread_mutex_lock(&gTheBigLock);
printf("thread %d: nice %d; %d iterations\\n",
tc->tid, tc->nice, tc->iters);
pthread_mutex_unlock(&gTheBigLock);
}
volatile int gDoNotOptimize = 0;
static void DoNothing() {
gDoNotOptimize += 1;
}
void* wWorkerThreadEntry(void *args) {
struct thread_closure *tc = (struct thread_closure *)args;
int i;
nacl_thread_nice(tc->nice);
pthread_mutex_lock(&gTheBigLock);
printf("thread %d starting.\\n", tc->tid);
pthread_mutex_unlock(&gTheBigLock);
do {
for (i = 0; i < 0x10000000; i++) DoNothing();
tc->iters += 1;
if (gDone) break;
Report(tc);
} while (tc->iters < kMaxIterations);
gDone = 1;
Report(tc);
pthread_cond_broadcast(&gDoneCond);
return 0;
}
static pthread_t gThreads[12];
static struct thread_closure gTClosure[12] =
{ { 0, NICE_BACKGROUND, 0 },
{ 1, NICE_NORMAL, 0 },
{ 2, NICE_REALTIME, 0 },
{ 3, NICE_REALTIME, 0 },
{ 4, NICE_REALTIME, 0 },
{ 5, NICE_REALTIME, 0 },
{ 6, NICE_REALTIME, 0 },
{ 7, NICE_REALTIME, 0 },
{ 8, NICE_REALTIME, 0 },
{ 9, NICE_REALTIME, 0 },
{ 10, NICE_REALTIME, 0 },
{ 11, NICE_REALTIME, 0 },
};
int CreateWorkerThreads() {
int i;
for (i = 0; i < 12; i++) {
if (0 != pthread_create(&(gThreads[i]), 0,
wWorkerThreadEntry, &(gTClosure[i]))) {
fprintf(stderr, "pthread_create() failed\\n");
return 0;
}
}
return 1;
}
void RunDemo() {
pthread_mutex_init(&gTheBigLock, 0);
pthread_cond_init(&gDoneCond, 0);
pthread_mutex_lock(&gTheBigLock);
if (CreateWorkerThreads()) {
nacl_thread_nice(NICE_BACKGROUND);
while (gDone == 0) pthread_cond_wait(&gDoneCond, &gTheBigLock);
}
pthread_mutex_unlock(&gTheBigLock);
}
int main(int argc, char **argv) {
RunDemo();
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t *mptr;
int g_LockFileFd = -1;
int ProcessMutex_file_init(char * pathname)
{
int fd = -1;
fd = open(pathname, O_RDWR | O_CREAT, 0666);
if(fd < 0)
{
perror("open error");
exit(-1);
}
return fd;
}
int ProcessMutex_wr_lock(int fd)
{
if(fd < 0)
{
return -1;
}
struct flock stLock;
stLock.l_type = F_WRLCK;
stLock.l_whence = 0;
stLock.l_start = 0;
stLock.l_len = 1;
if(fcntl(fd, F_SETLKW, &stLock) < 0)
{
exit(-1);
}
return 0;
}
int ProcessMutex_rd_lock(int fd)
{
if(fd < 0)
{
return -1;
}
struct flock stLock;
stLock.l_type = F_RDLCK;
stLock.l_whence = 0;
stLock.l_start = 0;
stLock.l_len = 1;
if(fcntl(fd, F_SETLKW, &stLock) < 0)
{
return -1;
}
return 0;
}
int ProcessMutex_file_unlock(int fd)
{
if(fd < 0)
{
return -1;
}
struct flock stLock;
stLock.l_type = F_UNLCK;
stLock.l_whence = 0;
stLock.l_start = 0;
stLock.l_len = 1;
if(fcntl(fd, F_SETLKW, &stLock) < 0)
{
return -1;
}
return 0;
}
void ProcessMutex_init(void)
{
pthread_mutexattr_t mattr;
int shmid = shmget((key_t)1234, sizeof(pthread_mutex_t), IPC_CREAT | 0666);
if(shmid < 0)
{
perror("shmget error");
log_printf(LOG_LEVEL_ERROR, LOG_MODULE_AUDIO,"shmget error\\n");
exit(-1);
}
mptr = (pthread_mutex_t *)shmat(shmid, 0, 0);
if(mptr < 0)
{
perror("shmat error");
log_printf(LOG_LEVEL_ERROR, LOG_MODULE_AUDIO,"shmat error\\n");
exit(-1);
}
pthread_mutexattr_init(&mattr);
pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(mptr, &mattr);
}
void ProcessMutex_lock(void)
{
pthread_mutex_lock(mptr);
}
void ProcessMutex_unlock(void)
{
pthread_mutex_unlock(mptr);
}
| 0
|
#include <pthread.h>
pthread_mutex_t account_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_mutex = PTHREAD_COND_INITIALIZER;
void add_money (int *account) {
int i = 0;
for (i = 0; i < 5; i++) {
pthread_mutex_lock(&(account_mutex));
(*account) += 10;
printf("[Add %d] We just added %dUSD! Now you have %dUSD!\\n", i + 1, 10, *account);
pthread_cond_broadcast(&(condition_mutex));
pthread_mutex_unlock(&(account_mutex));
}
}
void withdraw_money(int *account) {
int i;
for (i = 0; i < 5; i++) {
pthread_mutex_lock(&(account_mutex));
while ((*account)-7 < 0) {
printf("[Remove] Ops! You seem to have no cash!\\n");
pthread_cond_wait(&condition_mutex, &account_mutex);
printf("[Remove] Someone Added something! let's see if it's enough\\n");
}
(*account) -= 7;
printf("[Remove %d] We just withdrew %dUSD! You still have %dUSD!\\n", i + 1, 7, (*account));
pthread_mutex_unlock(&(account_mutex));
}
}
int main(int argc, const char *argv[]) {
int account = 0;
printf("Welcome! you have an initial amount of %dUSD!\\n", account);
pthread_t adder, withdrawer;
pthread_create(&withdrawer, 0, (void *) withdraw_money, (void *) &account);
pthread_create(&adder, 0, (void *) add_money, (void *) &account);
pthread_join(withdrawer, 0);
pthread_join(adder, 0);
printf("Done! Thank you for using our service!\\n");
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
int max_clients = 100;
pthread_t thread[5];
pthread_mutex_t mut;
const int LISTEN_BACKLOG = 50;
char msg[100];
int clients[100];
int setnonblocking(int sock) {
int opts;
opts = fcntl(sock, F_GETFL);
if (opts < 0) {
return 0;
}
opts = opts | O_NONBLOCK;
if (fcntl(sock, F_SETFL, opts) < 0) {
return 0;
}
return 0;
}
void* thread_connect() {
int listenfd, connfd;
listenfd = create_conn(10023);
if (listenfd <= 0) {
printf("create listenfd failed\\n");
exit(0);
}
bzero(clients, sizeof(clients));
int epollfd;
epollfd = epoll_create(101);
if (epollfd == -1) {
exit(0);
}
struct epoll_event ev, events[150];
ev.events = EPOLLIN;
ev.data.fd = listenfd;
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, listenfd, &ev) == -1) {
exit(0);
}
for ( ; ; ) {
int nfds;
nfds = epoll_wait(epollfd, events, sizeof(events), -1);
if (nfds == -1)
exit(0);
int i;
for (i = 0; i < nfds; ++i) {
int currfd = events[i].data.fd;
if (currfd == listenfd) {
int conn_sock;
conn_sock = accept(listenfd,
(struct sockaddr *)0, 0);
if (conn_sock == -1)
exit(0);
int n, saved;
saved = 0;
for (n = 0; n < sizeof(clients); ++n) {
if (clients[n] == 0) {
clients[n] = conn_sock;
saved = 1;
break;
}
}
if (saved == 0) {
close(conn_sock);
continue;
}
setnonblocking(conn_sock);
ev.events = EPOLLIN | EPOLLET;
ev.data.fd = conn_sock;
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, conn_sock, &ev) == -1)
exit(0);
} else {
int n;
char str[50];
n = read(currfd, str, sizeof(str));
if (n == 0) {
int i;
for (i = 0; i < sizeof(clients); ++i) {
if (clients[i] == currfd) {
clients[i] = 0;
break;
}
}
close(currfd);
epoll_ctl(epollfd, EPOLL_CTL_DEL, currfd, 0);
} else {
strncpy(msg, str, n);
}
}
}
}
}
void *thread_proc() {
while (1) {
pthread_mutex_lock(&mut);
int len;
len = strlen(msg);
if (len > 0) {
int i;
for (i = 0; i < 100; ++i) {
if (clients[i] > 0) {
write(clients[i], msg, len);
}
}
bzero(msg, sizeof(msg));
}
usleep(200);
pthread_mutex_unlock(&mut);
}
}
void *thread_proc2() {
while (1) {
pthread_mutex_lock(&mut);
int len;
len = strlen(msg);
if (len > 0) {
int i;
for (i = 0; i < 100; ++i) {
if (clients[i] > 0) {
write(clients[i], msg, len);
}
}
bzero(msg, sizeof(msg));
}
usleep(200);
pthread_mutex_unlock(&mut);
}
}
void *thread_route() {
long long now = 0;
long long pref = 0;
while (1) {
pthread_mutex_lock(&mut);
if (strlen(msg) > 0) {
printf("msg %s\\n", msg);
}
usleep(200000);
pthread_mutex_unlock(&mut);
}
}
int thread_create() {
int temp;
memset(&thread, 0, sizeof(thread));
if ((temp = pthread_create(&thread[0], 0, thread_connect, 0)) != 0) {
return -1;
}
if ((temp = pthread_create(&thread[1], 0, thread_proc, 0)) != 0) {
return -1;
}
if ((temp = pthread_create(&thread[2], 0, thread_proc2, 0)) != 0) {
return -1;
}
if ((temp = pthread_create(&thread[3], 0, thread_route, 0)) != 0) {
return -1;
}
return 0;
}
void thread_wait() {
if (thread[0] != 0) {
pthread_join(thread[0], 0);
printf("thread connect end\\n");
}
if (thread[1] != 0) {
pthread_join(thread[1], 0);
printf("thread proc end\\n");
}
if (thread[2] != 0) {
pthread_join(thread[2], 0);
printf("thread proc end\\n");
}
if (thread[3] != 0) {
pthread_join(thread[3], 0);
printf("thread proc end\\n");
}
}
int port;
} server;
int create_conn(int port) {
struct sockaddr_in servaddr;
int listenfd;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd < 0) {
return -1;
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(port);
int errno;
errno = bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
if (errno < 0) {
return errno;
}
if (listen(listenfd, LISTEN_BACKLOG) == -1) {
return -1;
}
return listenfd;
}
int main(int argc, char** argv) {
pthread_mutex_init(&mut, 0);
thread_create();
thread_wait();
printf("start main thread\\n");
return 0;
}
| 0
|
#include <pthread.h>
pthread_t threads[2];
pthread_mutex_t mutexsum;
int thread_data_count;
{
int send_ready;
char *mystring;
}thread_data;
thread_data thread_data_array[128];
int call_socket(char *hostname, char *portnum)
{
struct addrinfo hints, *res;
int sockfd;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
getaddrinfo(hostname, portnum, &hints, &res);
sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
connect(sockfd, res->ai_addr, res->ai_addrlen);
return (sockfd);
}
void * Read_Thread(void* arg)
{
int num_bytes_read;
int nbytes = 128;
char *my_string;
int count;
while(1)
{
my_string = (char *) malloc (nbytes + 1);
num_bytes_read = getline (&my_string, &nbytes, stdin);
if (num_bytes_read == -1)
{
puts ("ERROR!");
}
else
{
pthread_mutex_lock (&mutexsum);
thread_data_array[thread_data_count].mystring = my_string;
thread_data_count++;
pthread_mutex_unlock (&mutexsum);
}
}
}
void * Send_Thread(void* arg)
{
int socketfd = (int)(arg);
while(1)
{
while(thread_data_count)
{
char* input = thread_data_array[0].mystring;
unsigned int input_len = strlen(input);
unsigned int buffersize = 4+2+input_len;
char* buffer = (char*)malloc(buffersize+1);
strncpy(buffer, (char*)(&input_len), 4);
*(buffer + 4) = ',';
*(buffer + 5) = ' ';
strcpy(buffer + 6, input);
*(buffer+buffersize-1)='\\0';
send(socketfd, buffer, buffersize, 0);
free(buffer);
free(thread_data_array[0].mystring);
pthread_mutex_lock (&mutexsum);
thread_data_count--;
int i;
for(i=0; i< thread_data_count;i++)
{
thread_data_array[i] = thread_data_array[i+1];
}
pthread_mutex_unlock (&mutexsum);
char* stringfromserver = malloc(buffersize+1);
recv(socketfd, stringfromserver, buffersize, 0);
printf("Server: %s\\n", stringfromserver+6);
free(stringfromserver);
sleep(2);
}
}
}
int main()
{
setbuf(stdout, 0);
char* server_address = getenv("SERVER_ADDRESS");
char* server_port = getenv("SERVER_PORT");
pthread_mutex_init(&mutexsum, 0);
thread_data_count = 0;
int socketfd=call_socket(server_address, server_port);
if(pthread_create(&threads[0], 0, Read_Thread, 0))
{
printf("ERROR creating thread %d", 0);
exit(-1);
}
if(pthread_create(&threads[1], 0, Send_Thread, (void*)socketfd))
{
printf("ERROR creating thread %d", 1);
exit(-1);
}
pthread_exit(0);
pthread_mutex_destroy(&mutexsum);
}
| 1
|
#include <pthread.h>
char Buffer1[4][20];
char Buffer2[4][20];
int in1 = 0;
int in2 = 0;
int count1 = 0;
int count2 = 0;
int end = 2;
pthread_mutex_t lock, lock2;
pthread_cond_t SpaceAvailable, ItemAvailable;
void copytoBuffers(char writing[]){
if (count1 == 4) {
strcpy (Buffer2[in2], writing);
in2 = (in2 + 1) % 4;
count2++;
} else {
strcpy (Buffer1[in1], writing);
in1 = (in1 + 1) % 4;
count1++;
}
}
void * pBlack(void *arg) {
int file, i;
struct timeval tv;
struct timespec tim, tim2;
char writing[12];
char Stringtime[4];
if ((file = open("prod_black.txt", O_WRONLY)) <= -1)
exit(1);
for(i = 0 ; i < 1000 ; i++){
pthread_mutex_lock(&lock);
while (count1 == 4 && count2 == 4)
while (pthread_cond_wait(&SpaceAvailable, &lock) != 0);
gettimeofday(&tv, 0);
sprintf(writing, "Black %d \\n", tv.tv_usec);
tim.tv_sec = 0;
tim.tv_nsec = (rand() % 101) * 100;
nanosleep(&tim, &tim2);
write(file, writing, strlen(writing));
copytoBuffers(writing);
writing[0] = '\\0';
pthread_mutex_unlock(&lock);
pthread_cond_signal(&ItemAvailable);
}
pthread_mutex_lock(&lock2);
end--;
pthread_mutex_unlock(&lock2);
close(file);
}
void * pGreen(void *arg) {
int file, i;
struct timeval tv;
struct timespec tim, tim2;
char writing[12];
char Stringtime[4];
if ((file = open("prod_green.txt", O_WRONLY)) <= -1)
exit(1);
for(i = 0; i < 1000; i++){
pthread_mutex_lock(&lock);
while (count1 == 4 && count2 == 4)
while (pthread_cond_wait(&SpaceAvailable, &lock) != 0);
gettimeofday(&tv, 0);
sprintf(writing, "Green %d \\n", tv.tv_usec);
tim.tv_sec = 0;
tim.tv_nsec = (rand() % 101) * 100;
nanosleep(&tim, &tim2);
write(file, writing, strlen(writing));
copytoBuffers(writing);
writing[0] = '\\0';
pthread_mutex_unlock(&lock);
pthread_cond_signal(&ItemAvailable);
}
pthread_mutex_lock(&lock2);
end--;
pthread_mutex_unlock(&lock2);
close(file);
}
void * consumer(void *arg) {
int file;
int out1 = 0;
int out2 = 0;
if ((file = open("output.txt", O_WRONLY)) <= -1)
exit(1);
int i = -1;
do {
pthread_mutex_lock(&lock);
while (count1 == 0 && count2 == 0)
while (pthread_cond_wait(&ItemAvailable, &lock) != 0);
if (count1 > 0) {
write(file, Buffer1[out1], strlen(Buffer1[out1]));
out1 = (out1 + 1) % 4;
count1--;
} else if (count2 > 0) {
write(file, Buffer2[out2], strlen(Buffer2[out2]));
out2 = (out2 + 1) % 4;
count2--;
}
i = count1 + count2;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&SpaceAvailable);
pthread_mutex_lock(&lock2);
if(i == 0)
i = end;
pthread_mutex_unlock(&lock2);
} while (i != 0);
close(file);
}
int main(int argc, char* argv[]) {
pthread_t pG, cons, pB;
pthread_attr_t attr;
int n;
srand(time(0));
pthread_mutex_init(&lock, 0);
pthread_cond_init(&SpaceAvailable, 0);
pthread_cond_init(&ItemAvailable, 0);
if (n = pthread_create(&pB, 0, pBlack, 0)) {
fprintf(stderr, "pthread_create :%s\\n", strerror(n));
exit(1);
}
if (n = pthread_create(&pG, 0, pGreen, 0)) {
fprintf(stderr, "pthread_create :%s\\n", strerror(n));
exit(1);
}
if (n = pthread_create(&cons, 0, consumer, 0)) {
fprintf(stderr, "pthread_create :%s\\n", strerror(n));
exit(1);
}
if (n = pthread_join(cons, 0)) {
fprintf(stderr, "pthread_join:%s\\n", strerror(n));
exit(1);
}
printf("Finished execution \\n");
return 0;
}
| 0
|
#include <pthread.h>
struct node {
int datum;
struct node *next;
};
struct head {
pthread_mutex_t lock;
struct node *first;
struct head *next;
} *list;
pthread_mutex_t list_lock = PTHREAD_MUTEX_INITIALIZER;
void init_node (struct node *p, int x) {
p->datum = x;
p->next = 0;
}
void init_head (struct head *p) {
pthread_mutex_init(&p->lock, 0);
p->first = 0;
p->next = 0;
}
void *t_fun(void *arg) {
struct node *tmp;
struct head *h;
int elems = 0;
while (1) {
pthread_mutex_lock(&list_lock);
if (list) {
h = list;
pthread_mutex_unlock(&list_lock);
} else {
pthread_mutex_unlock(&list_lock);
sleep(1);
continue;
}
tmp = malloc(sizeof(struct node));
init_node(tmp, ++elems);
pthread_mutex_lock(&h->lock);
tmp->next = h->first;
h->first = tmp;
pthread_mutex_unlock(&h->lock);
printf("Inserted element %d.\\n", elems);
sleep(1);
}
return 0;
}
void *counter(void *arg) {
struct node *tmp;
struct head *h;
int bucket, elem;
while (1) {
bucket = 0;
printf("Counting: ");
pthread_mutex_lock(&list_lock);
h = list;
while (h) {
bucket++;
elem = 0;
tmp=h->first;
while (tmp) {
elem++;
tmp = tmp->next;
}
printf(" %d", elem);
h = h->next;
}
pthread_mutex_unlock(&list_lock);
printf("\\nCounted %d buckets.\\n\\n", bucket);
sleep(10);
}
return 0;
}
int main () {
pthread_t t1, t2;
struct head *tmp;
int i;
pthread_create(&t1, 0, t_fun, 0);
pthread_create(&t2, 0, counter, 0);
while (1) {
getchar();
printf("Creating new bucket!\\n");
tmp = malloc(sizeof(struct head));
init_head(tmp);
pthread_mutex_lock(&list_lock);
tmp->next = list;
list = tmp;
pthread_mutex_unlock(&list_lock);
}
return 0;
}
| 1
|
#include <pthread.h>
static int reset_timer (struct thread_data *, const int, const int);
void
on_motion_detect (void *arg)
{
int b;
ssize_t s;
uint64_t u;
struct thread_data *tdata = arg;
pthread_mutex_lock (&tdata->wiring_mutex);
b = digitalRead (tdata->pir_pin) == HIGH;
pthread_mutex_unlock (&tdata->wiring_mutex);
_log_debug ("isr %s\\n", atomic_load (&tdata->fake_isr) ? "fake" : b ?
"rising" :
"falling");
if (b || atomic_compare_exchange_weak (&tdata->fake_isr, (_Bool[])
{ 1 }, 0))
{
reset_timer (tdata, 5, 0);
if (atomic_compare_exchange_weak (&tdata->is_recording, (_Bool[])
{ 0 }, 1))
{
pthread_mutex_lock (&tdata->record_mutex);
u = 1;
s = write (tdata->record_eventfd, &u, sizeof (uint64_t));
if (s < 0)
{
log_error ("write failed");
atomic_store (&tdata->is_recording, 0);
}
pthread_mutex_unlock (&tdata->record_mutex);
}
}
else if (atomic_load (&tdata->is_recording))
reset_timer (tdata, 5, 0);
}
int
check_sensor_active (struct thread_data *tdata)
{
int b;
pthread_mutex_lock (&tdata->wiring_mutex);
b = digitalRead (tdata->pir_pin) == HIGH;
pthread_mutex_unlock (&tdata->wiring_mutex);
if (b != 0)
reset_timer (tdata, 5, 0);
return b;
}
static int
reset_timer(struct thread_data *tdata, const int secs, const int isecs)
{
ssize_t s;
struct itimerspec timer_value;
_log_debug ("resetting timer (is_recording = %s)\\n",
atomic_load (&tdata->is_recording) ? "true" : "false");
memset (&timer_value, 0, sizeof(timer_value));
timer_value.it_value.tv_sec = secs;
timer_value.it_value.tv_nsec = 0;
timer_value.it_interval.tv_sec = isecs;
timer_value.it_interval.tv_nsec = 0;
s = timerfd_settime (tdata->timerfd, 0, &timer_value, 0);
if (s < 0)
log_error ("timerfd_settime failed");
return s;
}
| 0
|
#include <pthread.h>
int depth = 1;
pthread_mutex_t depthlock;
void *md(void *thid)
{
int cur_dir = 0;
int me = *(int *) thid;
int ret = 0;
char dname[10];
char dirpath[16000];
while (depth <= 1000) {
pthread_mutex_lock (&depthlock);
cur_dir = depth++;
sprintf (dname, "%d", cur_dir);
mkdir (dname, 0777);
chdir (dname);
getcwd (dirpath, 16000);
pthread_mutex_unlock(&depthlock);
subdir (dirpath);
printf ("depth is %d from thread %d\\n", cur_dir, me);
}
return thid;
}
int
subdir (char *dname)
{
int i;
char subd[16000];
char file[16000];
int re;
struct timeval *time_val;
time_val = (struct timeval *) malloc (sizeof (struct timeval));
for (i = 1001; i <= 2000; i++) {
sprintf (subd, "%s/%d",dname, i);
mkdir(subd,0777);
gettimeofday (time_val, 0);
sprintf (file, "%s/%zu", dname, time_val->tv_usec);
re = mknod (file, S_IFREG, 0);
if (re == -1) {
printf ("mknod failed for %s", file);
}
}
return;
}
int main(int argc, char *argv[])
{
pthread_t thread[10];
int rc;
int t;
int *status;
for (t = 0; t < 10; t++) {
printf ("main thread creating the thread %d \\n", t);
rc = pthread_create (&thread[t],0, md, (void *) &t);
if (rc) {
printf ("ERROR, ret from pthread_create is %d", rc);
exit (-1);
}
}
for (t = 0; t < 10; t++) {
if (rc = pthread_join (thread[t], (void *)&status)) {
printf ("ERROR , ret frin pthread_join is %d", rc);
exit (-1);
}
}
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
int element[(20)];
int head;
int tail;
int amount;
} QType;
pthread_mutex_t m;
int __VERIFIER_nondet_int();
int stored_elements[(20)];
_Bool enqueue_flag, dequeue_flag;
QType queue;
int init(QType *q)
{
q->head=0;
q->tail=0;
q->amount=0;
}
int empty(QType * q)
{
if (q->head == q->tail)
{
printf("queue is empty\\n");
return (-1);
}
else
return 0;
}
int full(QType * q)
{
if (q->amount == (20))
{
printf("queue is full\\n");
return (-2);
}
else
return 0;
}
int enqueue(QType *q, int x)
{
q->element[q->tail] = x;
q->amount++;
if (q->tail == (20))
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == (20))
{
q->head = 1;
}
else
q->head++;
return x;
}
void *t1(void *arg)
{
int value, i;
pthread_mutex_lock(&m);
value = __VERIFIER_nondet_int();
if (enqueue(&queue,value)) {
goto ERROR;
}
stored_elements[0]=value;
if (empty(&queue)) {
goto ERROR;
}
pthread_mutex_unlock(&m);
for(
i=0; i<((20)-1); i++)
{
__CPROVER_assume(19-i >= 0 &&
i >= 0);
pthread_mutex_lock(&m);
if (enqueue_flag)
{
value = __VERIFIER_nondet_int();
enqueue(&queue,value);
stored_elements[i+1]=value;
enqueue_flag=(0);
dequeue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
ERROR:
__VERIFIER_error();
}
void *t2(void *arg)
{
int i;
for(
i=0; i<(20); i++)
{
__CPROVER_assume(20-i >= 0 &&
i >= 0);
pthread_mutex_lock(&m);
if (dequeue_flag)
{
if (!dequeue(&queue)==stored_elements[i]) {
ERROR:
__VERIFIER_error();
}
dequeue_flag=(0);
enqueue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
}
int main(void)
{
pthread_t id1, id2;
enqueue_flag=(1);
dequeue_flag=(0);
init(&queue);
if (!empty(&queue)==(-1)) {
ERROR:
__VERIFIER_error();
}
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, &queue);
pthread_create(&id2, 0, t2, &queue);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 0
|
#include <pthread.h>
struct shm
{
pthread_mutex_t gprs_mutex_start;
pthread_cond_t gprs_cond_start;
pthread_mutex_t gprs_mutex_end;
pthread_cond_t gprs_cond_end;
pthread_mutex_t beep_mutex_start;
pthread_cond_t beep_cond_start;
pthread_mutex_t beep_mutex_end;
pthread_cond_t beep_cond_end;
pthread_mutex_t beep_mutex_status;
pthread_mutex_t led_mutex_start;
pthread_cond_t led_cond_start;
pthread_mutex_t led_mutex_end;
pthread_cond_t led_cond_end;
pthread_mutex_t led_mutex_status;
pthread_mutex_t cgi_mutex_start;
pthread_cond_t cgi_cond_start;
pthread_mutex_t status_mutex_temperature;
int gprs_emit_start;
int gprs_emit_end;
int led_emit_start;
int led_emit_end;
int led_emit_status;
int beep_emit_start;
int beep_emit_end;
int beep_emit_status;
int cgi_emit_start;
char cgi_cmd[256];
int status_temperature;
}*SHM;
key_t key;
int shmid;
int main()
{
int i, n;
int cgi_flag;
char data[100];
printf("Content-Type:text/html;charset=utf-8\\n\\n");
key = 0x34567890;
if (-1 == (shmid = shmget(key, 8192, IPC_CREAT | IPC_EXCL | 0666)))
{
if (EEXIST == errno)
{
shmid = shmget(key, 8192, 0666);
SHM = shmat(shmid, 0, 0);
}
else
{
perror("fail to shmget");
exit(-1);
}
}
else
{
SHM = shmat(shmid, 0, 0);
}
if (getenv("CONTENT_LENGTH"))
{
n = atoi(getenv("CONTENT_LENGTH"));
}
for (i = 0; i < n; i++)
{
data[i] = getc(stdin);
if (data[i] == '=')
{
data[i] = '\\0';
}
}
if (!strcmp(data, "LED_ON"))
{
pthread_mutex_lock(&SHM->cgi_mutex_start);
cgi_flag = (0 == SHM->cgi_emit_start);
if (0 == SHM->cgi_emit_start)
{
SHM->cgi_emit_start++;
}
memset(SHM->cgi_cmd, 0, sizeof(SHM->cgi_cmd));
strcpy(SHM->cgi_cmd, data);
pthread_mutex_unlock(&SHM->cgi_mutex_start);
if (1 == cgi_flag)
{
pthread_cond_signal(&SHM->cgi_cond_start);
}
printf ("<meta http-equiv=\\"refresh\\" content=\\"0;URL=ioctl.html\\"/>");
}
if (!strcmp(data, "LED_OFF"))
{
pthread_mutex_lock(&SHM->cgi_mutex_start);
cgi_flag = (0 == SHM->cgi_emit_start);
if (0 == SHM->cgi_emit_start)
{
SHM->cgi_emit_start++;
}
memset(SHM->cgi_cmd, 0, sizeof(SHM->cgi_cmd));
strcpy(SHM->cgi_cmd, data);
pthread_mutex_unlock(&SHM->cgi_mutex_start);
if (1 == cgi_flag)
{
pthread_cond_signal(&SHM->cgi_cond_start);
}
printf ("<meta http-equiv=\\"refresh\\" content=\\"0;URL=ioctl.html\\"/>");
}
if (!strcmp(data, "BEEP_ON"))
{
pthread_mutex_lock(&SHM->cgi_mutex_start);
cgi_flag = (0 == SHM->cgi_emit_start);
if (0 == SHM->cgi_emit_start)
{
SHM->cgi_emit_start++;
}
memset(SHM->cgi_cmd, 0, sizeof(SHM->cgi_cmd));
strcpy(SHM->cgi_cmd, data);
pthread_mutex_unlock(&SHM->cgi_mutex_start);
if (1 == cgi_flag)
{
pthread_cond_signal(&SHM->cgi_cond_start);
}
printf ("<meta http-equiv=\\"refresh\\" content=\\"0;URL=ioctl.html\\"/>");
}
if (!strcmp(data, "BEEP_OFF"))
{
pthread_mutex_lock(&SHM->cgi_mutex_start);
cgi_flag = (0 == SHM->cgi_emit_start);
if (0 == SHM->cgi_emit_start)
{
SHM->cgi_emit_start++;
}
memset(SHM->cgi_cmd, 0, sizeof(SHM->cgi_cmd));
strcpy(SHM->cgi_cmd, data);
pthread_mutex_unlock(&SHM->cgi_mutex_start);
if (1 == cgi_flag)
{
pthread_cond_signal(&SHM->cgi_cond_start);
}
printf ("<meta http-equiv=\\"refresh\\" content=\\"0;URL=ioctl.html\\"/>");
}
if (!strcmp(data, "CAM_ON"))
{
printf ("<meta http-equiv=\\"refresh\\" content=\\"0;URL=ioctll.html\\"/>");
}
if (!strcmp(data, "CAM_OFF"))
{
printf ("<meta http-equiv=\\"refresh\\" content=\\"0;URL=ioctl.html\\"/>");
}
return 0;
}
| 1
|
#include <pthread.h>
int contador;
pthread_mutex_t mutex;
sem_t semaforo_productor;
void agregar(char c);
void quitar();
void * productor()
{
while(1)
{
char c = 'a' + rand()%24;
agregar(c);
usleep(1000);
}
}
void * consumidor()
{
while(1)
{
quitar();
usleep(1000);
}
}
void * imprimir()
{
while(1){
int i;
printf("%d",contador);
printf("\\n");
usleep(1000);
}
}
int main()
{
pthread_t thread_consumidor;
pthread_t thread_productor;
contador = 0;
pthread_mutex_init(&mutex, 0);
sem_init(&semaforo_productor, 0, 10);
pthread_create(&thread_consumidor, 0, consumidor, 0 );
pthread_create(&thread_productor, 0, productor, 0 );
pthread_join(thread_consumidor, 0);
return 0;
}
void agregar(char c)
{
sem_wait(&semaforo_productor);
pthread_mutex_lock(&mutex);
contador++;
printf("%d\\n",contador);
pthread_mutex_unlock(&mutex);
}
void quitar()
{
if(contador>0)
{
pthread_mutex_lock(&mutex);
contador--;
printf("%d\\n",contador);
pthread_mutex_unlock(&mutex);
sem_post(&semaforo_productor);
}
}
| 0
|
#include <pthread.h>
int nitems;
struct
{
pthread_mutex_t mutex;
int buff[MAXNITEMS];
int nput;
int nval;
} shared = {PTHREAD_MUTEX_INITIALIZER};
void *produce(void *);
void *consume(void *);
int main(int argc, char **argv)
{
int i, nthreads, count[MAXNTHREADS];
pthread_t tid_produce[MAXNTHREADS], tid_consume;
if (argc != 3)
{
exit(-1);
}
nitems = MIN(atoi(argv[1]), MAXNITEMS);
nthreads = MIN(atoi(argv[2]), MAXNTHREADS);
for (i=0; i<nthreads; i++)
{
count[i] = 0;
pthread_create(&tid_produce[i], 0, produce, &count[i]);
}
pthread_create(&tid_consume, 0, consume, 0);
for (i=0; i<nthreads; i++)
{
pthread_join(tid_produce[i], 0);
printf("count[%d] = %d\\n", i, count[i]);
}
pthread_join(tid_consume, 0);
exit(0);
}
void *produce(void *arg)
{
for (;;)
{
pthread_mutex_lock(&shared.mutex);
if (shared.nput >= nitems)
{
pthread_mutex_unlock(&shared.mutex);
return 0;
}
shared.buff[shared.nput] = shared.nval;
shared.nput++;
shared.nval++;
pthread_mutex_unlock(&shared.mutex);
*((int *)arg) += 1;
}
}
static void consume_wait(int i)
{
for (;;)
{
pthread_mutex_lock(&shared.mutex);
if (i < shared.nput)
{
pthread_mutex_unlock(&shared.mutex);
return ;
}
pthread_mutex_unlock(&shared.mutex);
}
}
void *consume(void *arg)
{
int i;
for (i=0; i<nitems; i++)
{
consume_wait(i);
if (shared.buff[i] != i)
{
printf("buff[%d] = %d\\n", i, shared.buff[i]);
}
}
return 0;
}
| 1
|
#include <pthread.h>
static dev_t __ashmem_rdev;
static pthread_mutex_t __ashmem_lock = PTHREAD_MUTEX_INITIALIZER;
static int __ashmem_open_locked()
{
int ret;
struct stat st;
int fd = TEMP_FAILURE_RETRY(open("/dev/ashmem", O_RDWR));
if (fd < 0) {
return fd;
}
ret = TEMP_FAILURE_RETRY(fstat(fd, &st));
if (ret < 0) {
int save_errno = errno;
close(fd);
errno = save_errno;
return ret;
}
if (!S_ISCHR(st.st_mode) || !st.st_rdev) {
close(fd);
errno = ENOTTY;
return -1;
}
__ashmem_rdev = st.st_rdev;
return fd;
}
static int __ashmem_open()
{
int fd;
pthread_mutex_lock(&__ashmem_lock);
fd = __ashmem_open_locked();
pthread_mutex_unlock(&__ashmem_lock);
return fd;
}
static int __ashmem_is_ashmem(int fd)
{
dev_t rdev;
struct stat st;
if (TEMP_FAILURE_RETRY(fstat(fd, &st)) < 0) {
return -1;
}
rdev = 0;
if (S_ISCHR(st.st_mode) && st.st_rdev) {
pthread_mutex_lock(&__ashmem_lock);
rdev = __ashmem_rdev;
if (rdev) {
pthread_mutex_unlock(&__ashmem_lock);
} else {
int fd = __ashmem_open_locked();
if (fd < 0) {
pthread_mutex_unlock(&__ashmem_lock);
return -1;
}
rdev = __ashmem_rdev;
pthread_mutex_unlock(&__ashmem_lock);
close(fd);
}
if (st.st_rdev == rdev) {
return 0;
}
}
if (rdev) {
LOG_ALWAYS_FATAL("illegal fd=%d mode=0%o rdev=%d:%d expected 0%o %d:%d",
fd, st.st_mode, major(st.st_rdev), minor(st.st_rdev),
S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IRGRP,
major(rdev), minor(rdev));
} else {
LOG_ALWAYS_FATAL("illegal fd=%d mode=0%o rdev=%d:%d expected 0%o",
fd, st.st_mode, major(st.st_rdev), minor(st.st_rdev),
S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IRGRP);
}
errno = ENOTTY;
return -1;
}
int ashmem_create_region(const char *name, size_t size)
{
int ret, save_errno;
int fd = __ashmem_open();
if (fd < 0) {
return fd;
}
if (name) {
char buf[ASHMEM_NAME_LEN] = {0};
strlcpy(buf, name, sizeof(buf));
ret = TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_SET_NAME, buf));
if (ret < 0) {
goto error;
}
}
ret = TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_SET_SIZE, size));
if (ret < 0) {
goto error;
}
return fd;
error:
save_errno = errno;
close(fd);
errno = save_errno;
return ret;
}
int ashmem_set_prot_region(int fd, int prot)
{
int ret = __ashmem_is_ashmem(fd);
if (ret < 0) {
return ret;
}
return TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_SET_PROT_MASK, prot));
}
int ashmem_pin_region(int fd, size_t offset, size_t len)
{
struct ashmem_pin pin = { offset, len };
int ret = __ashmem_is_ashmem(fd);
if (ret < 0) {
return ret;
}
return TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_PIN, &pin));
}
int ashmem_unpin_region(int fd, size_t offset, size_t len)
{
struct ashmem_pin pin = { offset, len };
int ret = __ashmem_is_ashmem(fd);
if (ret < 0) {
return ret;
}
return TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_UNPIN, &pin));
}
int ashmem_get_size_region(int fd)
{
int ret = __ashmem_is_ashmem(fd);
if (ret < 0) {
return ret;
}
return TEMP_FAILURE_RETRY(ioctl(fd, ASHMEM_GET_SIZE, 0));
}
| 0
|
#include <pthread.h>
pthread_mutex_t seconds_mutex = PTHREAD_MUTEX_INITIALIZER;
unsigned int seconds_remaining = 0;
unsigned int clock_active = 0;
void *clock_thread_start(void *arg);
int main (int argc, char **argv, char **envp) {
pthread_t server, acceptor, clock;
int s, child_pid;
child_pid = fork();
if (child_pid != 0) {
exit(0);
}
umask(0);
setsid();
setlogmask(setlogmask(0) & ~LOG_MASK(LOG_INFO));
syslog(LOG_NOTICE, "CoinOp started");
s = pthread_create( &server, 0, &server_thread_start, 0);
if (s!=0) { errno = s; perror("Server creation failed."); exit(1); }
s = pthread_create( &acceptor, 0, &acceptor_thread_start, 0);
if (s!=0) { errno = s; perror("Accepter creation failed."); exit(1); }
s = pthread_create( &clock, 0, &clock_thread_start, 0);
if (s!=0) { errno = s; perror("Clock creation failed."); exit(1); }
while (1) {
s = pthread_tryjoin_np( server, 0);
if (s != EBUSY) {
printf("Server thread exited.\\n");
exit(0);
}
s = pthread_tryjoin_np( acceptor, 0);
if (s != EBUSY) {
printf("Acceptor thread exited.\\n");
exit (0);
}
s = pthread_tryjoin_np( clock, 0);
if (s != EBUSY) {
printf("Clock thread exited.\\n");
exit(0);
}
}
}
void set_time(unsigned int seconds) {
syslog(LOG_INFO, "set_time: %d seconds", seconds);
pthread_mutex_lock( &seconds_mutex );
seconds_remaining = seconds;
pthread_mutex_unlock( &seconds_mutex );
}
void add_time(unsigned int seconds) {
syslog(LOG_INFO, "add_time: %d seconds", seconds);
pthread_mutex_lock( &seconds_mutex );
seconds_remaining+=seconds;
pthread_mutex_unlock( &seconds_mutex );
}
int get_time_remaining() {
int remaining;
pthread_mutex_lock( &seconds_mutex );
remaining = seconds_remaining;
pthread_mutex_unlock( &seconds_mutex);
return remaining;
}
int is_active() {
int active;
pthread_mutex_lock( &seconds_mutex );
get_switcher( &active );
active = (active == 1);
pthread_mutex_unlock( &seconds_mutex );
return active;
}
void force_on() {
pthread_mutex_lock( &seconds_mutex );
seconds_remaining = 0;
clock_active = 0;
set_switcher(1);
pthread_mutex_unlock( &seconds_mutex);
}
void force_off() {
pthread_mutex_lock( &seconds_mutex );
seconds_remaining = 0;
clock_active = 0;
set_switcher(2);
pthread_mutex_unlock( &seconds_mutex);
}
void tick() {
pthread_mutex_lock( &seconds_mutex );
if (seconds_remaining > 0) {
seconds_remaining--;
}
if (clock_active && seconds_remaining == 0) {
clock_active = 0;
set_switcher(2);
}
if (!clock_active && seconds_remaining != 0) {
clock_active = 1;
set_switcher(1);
}
pthread_mutex_unlock( &seconds_mutex );
}
void *clock_thread_start(void *arg) {
syslog(LOG_INFO, "clock thread started");
while(1) {
usleep(1000000);
tick();
}
}
| 1
|
#include <pthread.h>
int i = 0;
pthread_mutex_t lock;
void *thread_1(){
pthread_mutex_lock(&lock);
for (int count = 0; count < 1000001; count++)
{
i++;
}
printf("%s\\n", "Done incrementing");
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
void *thread_2(){
pthread_mutex_lock(&lock);
for (int count = 0; count < 1000000; count++){
i--;
}
printf("%s\\n", "Done decrementing");
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
int main(void){
if(pthread_mutex_init(&lock, 0) != 0){
printf("%s\\n", "Error initializing mutex" );
return 1;
}
pthread_t thr[2];
pthread_create(&thr[0], 0, thread_1, 0);
pthread_create(&thr[1], 0, thread_2, 0);
printf("%s\\n", "Waiting to join threads" );
for (int count = 0; count < 2; count++) {
pthread_join(thr[count], 0);
}
pthread_mutex_destroy(&lock);
printf("%i\\n",i);
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.