text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
pthread_mutex_t wd_news_mutex = PTHREAD_MUTEX_INITIALIZER;
void wd_send_news(void) {
FILE *fp;
char buffer[8192];
fp = fopen(wd_settings.news, "r");
if(!fp) {
wd_log(LOG_WARNING, "Could not open %s: %s", wd_settings.news);
goto end;
}
while((wd_getnewsline(fp, buffer, sizeof(buffer))) > 0)
wd_reply(320, "%s", buffer);
end:
wd_reply(321, "Done");
if(fp)
fclose(fp);
}
int wd_getnewsline(FILE *fp, char *line, size_t length) {
unsigned int i;
int ch;
for(i = 0; i < length && (ch = fgetc(fp)) != EOF && ch != 29; i++)
line[i] = ch;
line[i] = '\\0';
return i;
}
void wd_post_news(char *arg) {
struct wd_client *client = (struct wd_client *) pthread_getspecific(wd_client_key);
FILE *fp = 0, *temp = 0;
time_t clock;
size_t bytes, n;
char buffer[1024], now[26], *post = 0;
pthread_mutex_lock(&wd_news_mutex);
fp = fopen(wd_settings.news, "r");
if(!fp) {
wd_log(LOG_ERR, "Could not open %s: %s", wd_settings.news, strerror(errno));
goto end;
}
temp = tmpfile();
if(!temp) {
wd_log(LOG_ERR, "Could not create temporary file: %s", strerror(errno));
goto end;
}
clock = time(0);
wd_time_to_iso8601(localtime(&clock), now, sizeof(now));
bytes = strlen(client->nick) + strlen(now) + strlen(arg) + 86;
post = (char *) malloc(bytes);
snprintf(post, bytes, "%s%s%s%s%s",
client->nick,
WD_FIELD_SEPARATOR,
now,
WD_FIELD_SEPARATOR,
arg);
fprintf(temp, "%s%s", post, WD_GROUP_SEPARATOR);
while((n = fread(buffer, 1, sizeof(buffer), fp)))
fwrite(buffer, 1, n, temp);
fp = freopen(wd_settings.news, "w", fp);
if(!fp) {
wd_log(LOG_ERR, "Could not open %s: %s", wd_settings.news, strerror(errno));
goto end;
}
rewind(temp);
while((n = fread(buffer, 1, sizeof(buffer), temp)))
fwrite(buffer, 1, n, fp);
wd_broadcast(1, 322, post);
end:
if(fp)
fclose(fp);
if(temp)
fclose(temp);
if(post)
free(post);
pthread_mutex_unlock(&wd_news_mutex);
}
void wd_clear_news(void) {
FILE *fp = 0;
pthread_mutex_lock(&wd_news_mutex);
fp = fopen(wd_settings.news, "w");
if(!fp) {
wd_log(LOG_ERR, "Could not open %s: %s", wd_settings.news, strerror(errno));
goto end;
}
end:
if(fp)
fclose(fp);
pthread_mutex_unlock(&wd_news_mutex);
}
| 1
|
#include <pthread.h>
int pro_num=0;
int left_num=20;
pthread_mutex_t mutex_pro, mutex_left;
pthread_cond_t cond_pro, cond_left;
void *thd1_handle(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex_pro);
if(pro_num>0)
{
pthread_mutex_lock(&mutex_left);
pro_num--;
if(pro_num==19)
{
pthread_cond_signal(&cond_left);
}
left_num++;
printf("thd1 consume 1,pro_num:%d,left_num:%d\\n",pro_num,left_num);
pthread_mutex_unlock(&mutex_left);
pthread_mutex_unlock(&mutex_pro);
sleep(2);
}else
{
pthread_cond_wait(&cond_pro, &mutex_pro);
pthread_mutex_unlock( &mutex_pro);
sleep(2);
}
}
}
void *thd2_handle(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex_pro);
if(pro_num>0)
{
pthread_mutex_lock(&mutex_left);
pro_num--;
if(pro_num==19)
{
pthread_cond_signal(&cond_left);
}
left_num++;
printf("thd2 consume 1,pro_num:%d,left_num:%d\\n",pro_num,left_num);
pthread_mutex_unlock(&mutex_left);
pthread_mutex_unlock(&mutex_pro);
sleep(3);
}else
{
pthread_cond_wait(&cond_pro, &mutex_pro);
pthread_mutex_unlock( &mutex_pro);
sleep(3);
}
}
}
int main()
{
pthread_t thd1, thd2;
pthread_mutex_init(&mutex_pro, 0);
pthread_mutex_init(&mutex_left, 0);
pthread_cond_init(&cond_pro, 0);
pthread_cond_init(&cond_left, 0);
pthread_create(&thd1, 0, thd1_handle, 0);
pthread_create(&thd2, 0, thd2_handle, 0);
sleep(3);
while(1)
{
pthread_mutex_lock(&mutex_left);
if(left_num>0)
{
pthread_mutex_lock(&mutex_pro);
left_num--;
pro_num++;
printf("pro produce 1, pro_num:%d, left_num:%d\\n",pro_num,left_num);
if(pro_num==1)
{
printf("action,come on \\n");
pthread_mutex_unlock(&mutex_pro);
pthread_mutex_unlock(&mutex_left);
pthread_cond_broadcast(&cond_pro);
}else
{
pthread_mutex_unlock(&mutex_pro);
pthread_mutex_unlock(&mutex_left);
}
sleep(1);
}else if(left_num<=0)
{
pthread_cond_wait(&cond_left,&mutex_left);
pthread_mutex_unlock(&mutex_left);
sleep(1);
}
}
return 0;
}
| 0
|
#include <pthread.h>
char character_name[30];
char symbol;
int thread_num;
int position_xy[2];
int condition;
pthread_t thread_id;
}thread_data;
struct mutex_shared{
int BOARD[5][5];
int WINNER;
int FLAG[2];
int CONDITION;
char DUDE_WITH_FLAG;
} SHARED_DATA;
pthread_mutex_t object_mutex;
void magic(thread_data *objects);
void printGrid();
void init_data(thread_data *objects);
void place(thread_data *objects, int number);
void move_object(thread_data *objects);
int getRandom(int rangeLow, int rangeHigh, struct timeval time);
void move_object(thread_data *objects){
struct timeval time;
pthread_mutex_lock(&object_mutex);
int xcord = 0;
int ycord = 0;
int random_number = 0;
printGrid();
pthread_mutex_unlock(&object_mutex);
}
void *API(void *thread){
static int count = 0;
thread_data *objects = (thread_data *)thread;
while(count != 5){
move_object(objects);
sleep(2);
count++;
}
pthread_exit(0);
}
void place(thread_data *objects, int number){
struct timeval time;
int randx = getRandom(0,5 -1,time);
int randy = getRandom(0,5 -1,time);
int match = 0;
while(1){
for(int i=0; i<6; i++){
if(number != i){
if(randy == objects[i].position_xy[0] && randx == objects[i].position_xy[1]){
match = 1;
}
}
}
if(match == 1){
randx = getRandom(0,5 -1,time);
randy = getRandom(0,5 -1,time);
match = 0;
}else{
objects[number].position_xy[0] = randy;
objects[number].position_xy[1] = randx;
return;
}
}
}
void printGrid(){
for(int i=0; i<5; i++){
for(int j=0; j<5; j++){
printf("%c", SHARED_DATA.BOARD[i][j]);
}
printf("\\n");
}
}
int getRandom(int rangeLow, int rangeHigh, struct timeval time){
gettimeofday(&time, 0);
srandom((unsigned int) time.tv_usec);
double myRand = rand()/(1.0 + 32767);
int range = rangeHigh - rangeLow + 1;
int myRand_scaled = (myRand * range) + rangeLow;
return myRand_scaled;
}
void init_data(thread_data *objects){
struct timeval time;
for(int i=0; i<5; i++){
for(int j=0; j<5; j++){
SHARED_DATA.BOARD[i][j] = '-';
}
}
printGrid();
SHARED_DATA.CONDITION = 3;
objects[0].symbol = 'B';
objects[0].thread_num = 0;
objects[0].condition = 3;
strcpy(objects[0].character_name, "Bunny");
objects[1].symbol = 'D';
objects[1].thread_num = 1;
objects[1].condition = 0;
strcpy(objects[1].character_name, "Taz D");
objects[2].symbol = 'T';
objects[2].thread_num = 2;
objects[2].condition = 1;
strcpy(objects[2].character_name, "Tweety");
objects[3].symbol = 'M';
objects[3].thread_num = 3;
objects[3].condition = 2;
strcpy(objects[3].character_name, "Marvin");
objects[4].symbol = 'F';
objects[4].thread_num = 4;
objects[4].condition = 9999;
strcpy(objects[4].character_name, "Mountain");
objects[5].symbol = 'C';
objects[5].thread_num = 5;
objects[5].condition = 9999;
strcpy(objects[5].character_name, "Carrot");
for(int i=0; i<6; i++){
place(objects, objects[i].thread_num);
printf("name: %s, symbol: %c, thread_num: %d\\n", objects[i].character_name, objects[i].symbol, objects[i].thread_num);
printf("position 1=x = %d position 0=y = %d\\n", objects[i].position_xy[1], objects[i].position_xy[0]);
printf("-----------------------------------------------\\n");
}
for(int i=0; i<6; i++){
SHARED_DATA.BOARD[objects[i].position_xy[0]][objects[i].position_xy[1]] = objects[i].symbol;
}
SHARED_DATA.FLAG[0] = objects[5].position_xy[0];
SHARED_DATA.FLAG[1] = objects[5].position_xy[1];
printGrid();
}
int main(int argc, char *argv[]){
thread_data thread[6];
init_data(thread);
pthread_mutex_init(&object_mutex, 0);
for(int i=0; i<4; i++){
thread[i].thread_num = i;
pthread_create(&(thread[i].thread_id), 0, API,(void *)(&thread[i]));
}
for(int i=0; i<4; i++){
pthread_join(thread[i].thread_id, 0);
}
pthread_mutex_destroy(&object_mutex);
return 0;
}
| 1
|
#include <pthread.h>
int thread_count;
int barrier_thread_counts[100];
pthread_mutex_t barrier_mutex;
void Usage(char* prog_name);
void *Thread_work(void* rank);
int main(int argc, char* argv[]) {
long thread, i;
pthread_t* thread_handles;
double start, finish;
if (argc != 2)
Usage(argv[0]);
thread_count = strtol(argv[1], 0, 10);
thread_handles = malloc (thread_count*sizeof(pthread_t));
for (i = 0; i < 100; i++)
barrier_thread_counts[i] = 0;
pthread_mutex_init(&barrier_mutex, 0);
GET_TIME(start);
for (thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread], 0,
Thread_work, (void*) thread);
for (thread = 0; thread < thread_count; thread++) {
pthread_join(thread_handles[thread], 0);
}
GET_TIME(finish);
printf("Elapsed time = %e seconds\\n", finish - start);
pthread_mutex_destroy(&barrier_mutex);
free(thread_handles);
return 0;
}
void Usage(char* prog_name) {
fprintf(stderr, "usage: %s <number of threads>\\n", prog_name);
exit(0);
}
void *Thread_work(void* rank) {
int i;
for (i = 0; i < 100; i++) {
pthread_mutex_lock(&barrier_mutex);
barrier_thread_counts[i]++;
pthread_mutex_unlock(&barrier_mutex);
while (barrier_thread_counts[i] < thread_count);
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_cond_t exit_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t exit_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_t watcher_thr;
pthread_t cli_thr;
pthread_t daemon_thr;
int daemon_stopped;
char file_backend_prefix[1024];
int log_priority = LOG_ERR;
int use_syslog;
FILE *logfd;
char frontend_prefix[1024];
static void *
signal_set(int signo, void (*func) (int))
{
int r;
struct sigaction sig;
struct sigaction osig;
sig.sa_handler = func;
sigemptyset(&sig.sa_mask);
sig.sa_flags = 0;
r = sigaction(signo, &sig, &osig);
if (r < 0)
return (SIG_ERR);
else
return (osig.sa_handler);
}
static void sigend(int sig)
{
daemon_stopped = 1;
pthread_mutex_lock(&exit_mutex);
pthread_cond_signal(&exit_cond);
pthread_mutex_unlock(&exit_mutex);
}
int main(int argc, char **argv)
{
int i;
int fanotify_fd, ret;
struct backend *be = 0;
struct stat stbuf;
logfd = stdout;
memset(frontend_prefix, 0x0, 1024);
while ((i = getopt(argc, argv, "b:c:d:m:n:o:p:su:")) != -1) {
switch (i) {
case 'b':
be = new_backend(optarg);
if (!be) {
err("Invalid backend '%s'\\n", optarg);
return EINVAL;
}
break;
case 'd':
if (stat(optarg, &stbuf) < 0 ||
!S_ISDIR(stbuf.st_mode)) {
err("Frontend prefix %s is not a directory",
optarg);
return EINVAL;
}
strncpy(frontend_prefix, optarg, 1024);
break;
case 'c':
return cli_command(CLI_CHECK, optarg);
break;
case 'm':
ret = cli_command(CLI_CHECK, optarg);
if (ret)
return ret;
ret = cli_command(CLI_MIGRATE, optarg);
if (ret)
return ret;
case 'n':
return cli_command(CLI_MONITOR, optarg);
break;
case 'o':
if (!be) {
err("No backend selected");
return EINVAL;
}
if (parse_backend_options(be, optarg) < 0) {
err("Invalid backend option '%s'", optarg);
return EINVAL;
}
break;
case 'p':
log_priority = strtoul(optarg, 0, 10);
if (log_priority > LOG_DEBUG) {
err("Invalid logging priority %d (max %d)",
log_priority, LOG_DEBUG);
exit(1);
}
break;
case 's':
return cli_command(CLI_SHUTDOWN, 0);
break;
case 'u':
ret = cli_command(CLI_CHECK, optarg);
if (ret && ret != ENOENT)
return ret;
ret = cli_command(CLI_SETUP, optarg);
if (ret)
return ret;
return cli_command(CLI_MONITOR, optarg);
break;
default:
fprintf(stderr, "usage: %s [-d <dir>]\\n", argv[0]);
return EINVAL;
}
}
if (optind < argc) {
fprintf(stderr, "usage: %s [-b file] [-p <dir>]\\n", argv[0]);
return EINVAL;
}
signal_set(SIGINT, sigend);
signal_set(SIGTERM, sigend);
fanotify_fd = fanotify_init(FAN_CLASS_PRE_CONTENT, O_RDWR);
if (fanotify_fd < 0) {
fprintf(stderr, "cannot start fanotify, error %d\\n",
errno);
return errno;
}
daemon_thr = pthread_self();
watcher_thr = start_watcher(be, fanotify_fd);
if (!watcher_thr)
return errno;
cli_thr = start_cli(be, fanotify_fd);
if (!cli_thr) {
stop_watcher(watcher_thr);
return ENOMEM;
}
pthread_cond_wait(&exit_cond, &exit_mutex);
stop_cli(cli_thr);
stop_watcher(watcher_thr);
return 0;
}
| 1
|
#include <pthread.h>
extern pthread_mutex_t raspyMutex;
extern pthread_mutex_t timeMutex;
extern pthread_cond_t cond;
extern char gTimeStr[];
extern int gNextSwitchTime;
extern void fifoInit(void);
extern int putMessage(int, int);
extern enum globMode gMode;
struct switchTimes {
int switchOnTime;
int switchOffTime;
int nextDaySwitchOffTime;
};
int getIntVal(char *b, int digits)
{
int val=0;
char c;
int i;
for (i = 0; i < digits; i++) {
c = *(b+i);
if (c < '0' || c > '9') {
return -1;
}
val = val * 10 + (c - '0');
}
return val;
}
extern int getTimeByFile(time_t *t)
{
int input_fd;
char buffer[256];
struct tm tm;
input_fd = open ("./faketime.txt", O_RDONLY);
if (input_fd == -1) {
return FALSE;
}
if (read(input_fd, &buffer, 256) <= 0) {
return FALSE;
}
tm.tm_year = getIntVal(&buffer[0], 4) - 1900;
tm.tm_mon = getIntVal(&buffer[4], 2) - 1;
tm.tm_mday = getIntVal(&buffer[6], 2);
tm.tm_hour = getIntVal(&buffer[8], 2);
tm.tm_min = getIntVal(&buffer[10], 2);
tm.tm_sec = getIntVal(&buffer[12], 2);
tm.tm_isdst = 0;
*t = mktime(&tm);
printf("Time from faketime file: %04d-%02d-%02d %02d:%02d:%02d.\\n",
tm.tm_year + 1900,
tm.tm_mon + 1,
tm.tm_mday,
tm.tm_hour,
tm.tm_min,
tm.tm_sec);
return TRUE;
}
int calcSwitchTimes(int dayOfYear, struct switchTimes *swt)
{
int diffSec;
diffSec = (int)(9000.0 * sin((float)(dayOfYear - 80) * (2.0 * 3.1415926535897931) / 366.0));
swt->switchOnTime = 17 * 3600 + 1800 + diffSec;
swt->switchOffTime = 4 * 3600 + 1800 - diffSec;
swt->nextDaySwitchOffTime = 17 * 3600 + 1800 + (int)(9000.0 * sin((float)(dayOfYear - 79) * (2.0 * 3.1415926535897931) / 366.0));
}
void *timeControl(void *arg)
{
time_t t;
struct tm *tm;
struct switchTimes swt;
int timeNow;
int daySeconds;
char timeStr[18];
enum globMode tmpMode;
pthread_detach(pthread_self());
while(TRUE) {
sleep(1);
pthread_mutex_lock(&raspyMutex);
tmpMode = gMode;
pthread_mutex_unlock(&raspyMutex);
if (tmpMode != automaticMode)
continue;
if (!getTimeByFile(&t)) {
time(&t);
}
tm = gmtime(&t);
daySeconds = (int)(t) % (3600*24);
calcSwitchTimes(tm->tm_yday, &swt);
pthread_mutex_lock(&timeMutex);
sprintf(gTimeStr, "%04d-%02d-%02d %02d:%02d",
tm->tm_year + 1900,
tm->tm_mon + 1,
tm->tm_mday,
tm->tm_hour,
tm->tm_min);
if (daySeconds < swt.switchOffTime)
gNextSwitchTime = swt.switchOffTime;
else if (daySeconds < swt.switchOnTime)
gNextSwitchTime = swt.switchOnTime;
else
gNextSwitchTime = swt.nextDaySwitchOffTime;
pthread_mutex_unlock(&timeMutex);
timeNow = (tm->tm_hour * 60 + tm->tm_min) * 60 + tm->tm_sec;
if (timeNow > swt.switchOffTime && timeNow < swt.switchOnTime) {
pthread_mutex_lock(&raspyMutex);
putMessage(FF_SWITCH_OFF, 0);
putMessage(FF_SET_FREQUENCE, 1);
} else {
pthread_mutex_lock(&raspyMutex);
putMessage(FF_SWITCH_ON, 0);
putMessage(FF_SET_FREQUENCE, 5);
}
pthread_cond_signal(&cond);
pthread_mutex_unlock(&raspyMutex);
}
}
| 0
|
#include <pthread.h>
int clientCount = 0;
int byteCount = 0;
pthread_mutex_t lock;
struct serverParm{
int connectionfd;
int clientNO;
};
static int callback(void *data, int argc, char **argv, char **azColName) {
int *fileDesc;
fileDesc = (int *) data;
int i;
for (i = 0; i < argc; i++) {
byteCount += write(*fileDesc, azColName[i], strlen(azColName[i]));
byteCount += write(*fileDesc, " = ", 3);
byteCount += write(*fileDesc, argv[i], strlen(argv[i]));
byteCount += write(*fileDesc, "\\n", 1);
}
byteCount += write(*fileDesc, "\\n", 1);
return 0;
}
void sqlHandler(char cmd[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
char sql[1025];
int *fileDesc;
fileDesc = (int *) malloc(sizeof(fileDesc));
*fileDesc = open("result.txt", O_APPEND | O_WRONLY);
rc = sqlite3_open("book.db", &db);
if (rc) {
fprintf(stderr, "Can't open database\\n", sqlite3_errmsg(db));
exit(0);
}
else {
}
strcpy(sql, cmd);
printf("Statement: %s\\n", sql);
rc = sqlite3_exec(db, sql, callback, (void*)fileDesc, &zErrMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\\n", zErrMsg);
byteCount += write(*fileDesc, "SQL error: ", 11);
byteCount += write(*fileDesc, zErrMsg, strlen(zErrMsg));
byteCount += write(*fileDesc, "\\n", 1);
sqlite3_free(zErrMsg);
}
else {
fprintf(stdout, "Operation done successfully\\n");
}
sqlite3_close(db);
close(*fileDesc);
free(fileDesc);
}
void *threadFunction(void *parmPtr){
char cmd[1025];
int cmdLen;
char result[4096];
int readfd;
int writefd;
pthread_t tid;
tid = pthread_self();
time_t curtime;
struct tm *timestamp;
char timeHeading[100];
printf("Connection established: %d\\n", ((struct serverParm *) parmPtr)->connectionfd);
clientCount++;
((struct serverParm *) parmPtr)->clientNO = clientCount;
while((cmdLen = recv(((struct serverParm *) parmPtr)->connectionfd, cmd, 1025, 0)) > 0){
pthread_mutex_lock(&lock);
if(strcmp(cmd, "exit") == 0){
close(((struct serverParm *) parmPtr)->connectionfd);
free(((struct serverParm *) parmPtr));
clientCount--;
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
curtime = time(0);
timestamp = localtime(&curtime);
strftime(timeHeading, sizeof(timeHeading), "%c", timestamp);
writefd = open("result.txt", O_CREAT | O_TRUNC | O_WRONLY, 0644);
byteCount += write(writefd, timeHeading, strlen(timeHeading));
byteCount += write(writefd, " Thread ID: ", 12);
close(writefd);
FILE *file;
file = fopen("result.txt", "a");
byteCount += fprintf(file, "%lu (0x%lx)\\n", (unsigned long)tid, (unsigned long)tid);
fclose(file);
FILE *logfile;
logfile = fopen("a4p2ServerLog.txt", "a");
fclose(logfile);
sqlHandler(cmd);
recv(((struct serverParm *) parmPtr)->connectionfd, cmd, 1025, 0);
readfd = open("result.txt", O_RDONLY);
read(readfd, result, byteCount);
send(((struct serverParm *) parmPtr)->connectionfd, result, strlen(result), 0);
memset(&result, 0, sizeof(result));
send(((struct serverParm *) parmPtr)->connectionfd, result, 4096, 0);
byteCount = 0;
pthread_mutex_unlock(&lock);
}
close(((struct serverParm *) parmPtr)->connectionfd);
free(((struct serverParm *) parmPtr));
clientCount--;
pthread_exit(0);
}
int main(){
int listenSocket, acceptSocket, n;
struct sockaddr_in cliAddr, servAddr;
pthread_t threadID;
struct serverParm *parmPtr;
if(pthread_mutex_init(&lock, 0) != 0){
perror("Failed to initialize mutex");
exit(1);
}
listenSocket = socket(AF_INET, SOCK_STREAM, 0);
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(6000);
bind(listenSocket, (struct sockaddr *)&servAddr, sizeof(servAddr));
listen(listenSocket, 5);
printf("Starts listening...\\n");
while(1){
acceptSocket = accept(listenSocket, 0, 0);
printf("Client accepted!!! Assigning thread to serve client\\n");
parmPtr = (struct serverParm *) malloc(sizeof(struct serverParm));
parmPtr->connectionfd = acceptSocket;
if(pthread_create(&threadID, 0, threadFunction, (void *)parmPtr) != 0){
perror("Failed to create thread");
close(acceptSocket);
close(listenSocket);
exit(1);
}
printf("Server ready for another client\\n");
}
close(listenSocket);
}
| 1
|
#include <pthread.h>
int readers;
int writer;
pthread_cond_t readers_proceed;
pthread_cond_t writer_proceed;
int pending_writers;
pthread_mutex_t read_write_lock;
} mylib_rwlock_t;
mylib_rwlock_t read_write_lock;
void *find_min_rw(void *list_ptr);
void mylib_rwlock_init (mylib_rwlock_t *l);
void mylib_rwlock_rlock(mylib_rwlock_t *l);
void mylib_rwlock_wlock(mylib_rwlock_t *l);
void mylib_rwlock_unlock(mylib_rwlock_t *l);
int minimum_value, partial_list_size,list_elements_size;
int j=0;
main() {
int i,k;
minimum_value = 0;
int pthread_count;
printf("Enter the values for list size and thread count:");
scanf("%d %d",&list_elements_size,&pthread_count);
pthread_t thread[pthread_count];
static int list_elements[100000000];
for(i=0;i<list_elements_size;i++)
{
list_elements[i]=rand_r()%100000000 + (-99999999);
}
partial_list_size=list_elements_size/pthread_count;
for(k=0;k<pthread_count;k++)
{
pthread_create(&thread[k],0,(void *)&find_min_rw,(void *)&list_elements[j]);
j=j+partial_list_size;
}
for(i=0;i< pthread_count;i++)
{
pthread_join(thread[i],0);
}
printf("The minimum value in the list : %d",minimum_value);
}
void *find_min_rw(void *list_ptr) {
int *partial_list_pointer, my_min, i;
my_min = 0;
partial_list_pointer = (int *) list_ptr;
for (i = 0; i < partial_list_size; i++)
if (partial_list_pointer[i] < my_min)
my_min = partial_list_pointer[i];
mylib_rwlock_rlock(&read_write_lock);
if (my_min < minimum_value) {
mylib_rwlock_unlock(&read_write_lock);
mylib_rwlock_wlock(&read_write_lock);
minimum_value = my_min;
}
mylib_rwlock_unlock(&read_write_lock);
pthread_exit(0);
}
void mylib_rwlock_init (mylib_rwlock_t *l) {
l -> readers = l -> writer = l -> pending_writers = 0;
pthread_mutex_init(&(l -> read_write_lock), 0);
pthread_cond_init(&(l -> readers_proceed), 0);
pthread_cond_init(&(l -> writer_proceed), 0);
}
void mylib_rwlock_rlock(mylib_rwlock_t *l) {
pthread_mutex_lock(&(l -> read_write_lock));
while ((l -> pending_writers > 0) || (l -> writer > 0))
pthread_cond_wait(&(l -> readers_proceed),
&(l -> read_write_lock));
l -> readers ++;
pthread_mutex_unlock(&(l -> read_write_lock));
}
void mylib_rwlock_wlock(mylib_rwlock_t *l) {
pthread_mutex_lock(&(l -> read_write_lock));
while ((l -> writer > 0) || (l -> readers > 0)) {
l -> pending_writers ++;
pthread_cond_wait(&(l -> writer_proceed),
&(l -> read_write_lock));
}
l -> pending_writers --;
l -> writer ++;
pthread_mutex_unlock(&(l -> read_write_lock));
}
void mylib_rwlock_unlock(mylib_rwlock_t *l) {
pthread_mutex_lock(&(l -> read_write_lock));
if (l -> writer > 0)
l -> writer = 0;
else if (l -> readers > 0)
l -> readers --;
pthread_mutex_unlock(&(l -> read_write_lock));
if ((l -> readers == 0) && (l -> pending_writers > 0))
pthread_cond_signal(&(l -> writer_proceed));
else if (l -> readers > 0)
pthread_cond_broadcast(&(l -> readers_proceed));
}
| 0
|
#include <pthread.h>
int thread_count;
int barrier_thread_count = 0;
pthread_mutex_t barrier_mutex;
pthread_cond_t ok_to_proceed;
void Usage(char* prog_name);
void *Thread_work(void* rank);
int main(int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
double start, finish;
if (argc != 2) Usage(argv[0]);
thread_count = strtol(argv[1], 0, 10);
thread_handles = malloc (thread_count*sizeof(pthread_t));
pthread_mutex_init(&barrier_mutex, 0);
pthread_cond_init(&ok_to_proceed, 0);
GET_TIME(start);
for (thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread], (pthread_attr_t*) 0,
Thread_work, (void*) thread);
for (thread = 0; thread < thread_count; thread++)
pthread_join(thread_handles[thread], 0);
GET_TIME(finish);
printf("Elapsed time = %e seconds\\n", finish - start);
pthread_mutex_destroy(&barrier_mutex);
pthread_cond_destroy(&ok_to_proceed);
free(thread_handles);
return 0;
}
void Usage(char* prog_name) {
fprintf(stderr, "usage: %s <number of threads>\\n", prog_name);
exit(0);
}
void *Thread_work(void* rank) {
int i;
for (i = 0; i < 1000; i++) {
pthread_mutex_lock(&barrier_mutex);
barrier_thread_count++;
if (barrier_thread_count == thread_count) {
barrier_thread_count = 0;
pthread_cond_broadcast(&ok_to_proceed);
} else {
while (pthread_cond_wait(&ok_to_proceed,
&barrier_mutex) != 0);
}
pthread_mutex_unlock(&barrier_mutex);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t chops[5];
void *eat(void * arg);
int main()
{
int i;
pthread_t persons[5];
srand(time(0));
for (i = 0; i < 5; i++)
{
pthread_mutex_init(&chops[i], 0);
}
for (i = 0; i < 5; i++)
{
pthread_create(&persons[i], 0, eat, (void *)i);
}
for (i = 0; i < 5; i++)
{
pthread_join(persons[i], 0);
}
return 0;
}
void *eat(void *arg)
{
int index = (int)arg;
while (1)
{
pthread_mutex_lock(&chops[index]);
if (pthread_mutex_trylock(&chops[(index + 1) % 5]) != 0)
pthread_mutex_unlock(&chops[index]);
else
{
printf("person %d is eating...\\n", index);
sleep(rand() % 10 + 1);
printf("person %d is finish...\\n", index);
pthread_mutex_unlock(&chops[(index + 1) % 5]);
pthread_mutex_unlock(&chops[index]);
pthread_exit(0);
}
}
}
| 0
|
#include <pthread.h>
{
pthread_mutex_t mutex1;
pthread_mutex_t mutex2;
sem_t sem1;
sem_t sem2;
unsigned total;
unsigned arrived;
sem_t xxx;
} gomp_barrier_t;
void
gomp_barrier_init (gomp_barrier_t *bar, unsigned count)
{
pthread_mutex_init (&bar->mutex1, 0);
pthread_mutex_init (&bar->mutex2, 0);
sem_init (&bar->sem1, 0, 0);
sem_init (&bar->sem2, 0, 0);
sem_init (&bar->xxx, 0, 0);
bar->total = count;
bar->arrived = 0;
}
void
gomp_barrier_destroy (gomp_barrier_t *bar)
{
pthread_mutex_lock (&bar->mutex1);
pthread_mutex_unlock (&bar->mutex1);
pthread_mutex_destroy (&bar->mutex1);
pthread_mutex_destroy (&bar->mutex2);
sem_destroy (&bar->sem1);
sem_destroy (&bar->sem2);
sem_destroy(&bar->xxx);
}
void
gomp_barrier_reinit (gomp_barrier_t *bar, unsigned count)
{
pthread_mutex_lock (&bar->mutex1);
bar->total = count;
pthread_mutex_unlock (&bar->mutex1);
}
void
gomp_barrier_wait (gomp_barrier_t *bar)
{
unsigned int n;
pthread_mutex_lock (&bar->mutex1);
++bar->arrived;
if (bar->arrived == bar->total)
{
bar->arrived--;
n = bar->arrived;
if (n > 0)
{
{ unsigned int i;
for (i = 0; i < n; i++)
sem_wait(&bar->xxx);
}
do
sem_post (&bar->sem1);
while (--n != 0);
sem_wait (&bar->sem2);
}
pthread_mutex_unlock (&bar->mutex1);
}
else
{
pthread_mutex_unlock (&bar->mutex1);
sem_post(&bar->xxx);
sem_wait (&bar->sem1);
pthread_mutex_lock (&bar->mutex2);
n = --bar->arrived;
pthread_mutex_unlock (&bar->mutex2);
if (n == 0)
sem_post (&bar->sem2);
}
}
static gomp_barrier_t bar;
volatile static long unprotected = 0;
void* child ( void* argV )
{
long myid = (long)argV;
gomp_barrier_wait( &bar );
if (myid == 4) {
unprotected = 99;
}
gomp_barrier_wait( &bar );
if (myid == 3) {
unprotected = 88;
}
gomp_barrier_wait( &bar );
return 0;
}
int main (int argc, char *argv[])
{
long i; int res;
pthread_t thr[4];
fprintf(stderr, "starting\\n");
gomp_barrier_init( &bar, 4 );
for (i = 0; i < 4; i++) {
res = pthread_create( &thr[i], 0, child, (void*)(i+2) );
assert(!res);
}
for (i = 0; i < 4; i++) {
res = pthread_join( thr[i], 0 );
assert(!res);
}
gomp_barrier_destroy( &bar );
fprintf(stderr, "done, result is %ld, should be 88\\n", unprotected);
return 0;
}
| 1
|
#include <pthread.h>
void * simple(void *);
pthread_t tid[2];
int bignum = 0;
pthread_mutex_t mut;
main( int argc, char *argv[] )
{
int i, ret;
pthread_mutex_init(&mut, 0);
for (i=0; i<2; i++) {
pthread_create(&tid[i], 0, simple, 0);
}
for ( i = 0; i < 2; i++)
pthread_join(tid[i], 0);
printf("main() reporting that all %d threads have terminated\\n", i);
printf("I am main! bignum=%d\\n", bignum);
}
void * simple(void * parm)
{
int i;
for(i=0;i<10000;i++) {
pthread_mutex_lock(&mut);
bignum++;
pthread_mutex_unlock(&mut);
}
}
| 0
|
#include <pthread.h>
const static int n = 3;
static int m = 1;
static int l = 0;
static int first[n][n];
static int second[n][n];
static int result[n][n];
static pthread_mutex_t mutex;
void *crt(void *p) {
int k = 1;
while (1) {
if (k == m && (k - 1) == l) {
pthread_mutex_lock(&mutex);
l++;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
first[i][j] = rand() % 9 - 0;
second[i][j] = rand() % 9 - 0;
}
}
k++;
pthread_mutex_unlock(&mutex);
sleep(5);
}
}
}
void *sum(void *p) {
int k = 1;
while (1) {
if (k == m && k == l) {
pthread_mutex_lock(&mutex);
for (int i = 0; i < n ; ++i) {
for (int j = 0; j < n ; ++j) {
result[i][j]=first[i][j]+second[i][j];
}
}
k++;
pthread_mutex_unlock(&mutex);
sleep(5);
}
}
}
void *prt(void *p) {
int k = 1;
while (1) {
if (k == m && k == l) {
pthread_mutex_lock(&mutex);
for (int i = 0; i < n ; ++i) {
for (int j = 0; j < n ; ++j) {
printf("%i ", first[i][j]);
}
printf("\\n");
}
printf("+ \\n");
for (int i = 0; i < n ; ++i) {
for (int j = 0; j < n ; ++j) {
printf("%i ", second[i][j]);
}
printf("\\n");
}
printf("= \\n");
for (int i = 0; i < n ; ++i) {
for (int j = 0; j < n ; ++j) {
printf("%i ", result[i][j]);
}
printf("\\n");
}
printf("\\n\\n");
k++;
m++;
pthread_mutex_unlock(&mutex);
sleep(5);
}
}
}
int main() {
pthread_mutex_init(&mutex,0);
pthread_t thread_1;
pthread_t thread_2;
pthread_t thread_3;
pthread_create(&thread_1, 0, &crt, 0);
pthread_create(&thread_2, 0, &sum, 0);
pthread_create(&thread_3, 0, &prt, 0);
pthread_join(thread_1, 0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
extern int HELLO_INTERVAL;
extern int identifier;
extern int HELLO_INTERVAL;
extern int NUMBER_OF_ROUTERS;
extern int NUMBER_OF_EDGES;
extern int NUMBER_OF_NEIGHBORS;
extern int* NEIGHBOR_IDS;
extern int sock;
extern struct sockaddr_in my_addr;
extern struct hostent *host;
extern int MAX_POSSIBLE_DIST;
extern int** neighbor_link_details;
extern int** actual_link_costs;
extern int** practise_costs;
extern int*** every_node_lsa_details;
extern int* every_node_neighbors;
extern int* lsa_seq_num_det;
int helloTime;
extern pthread_mutex_t lock;
char exchange(int i){
switch(i){
case 0: return '0';
case 1: return '1';
case 2: return '2';
case 3: return '3';
case 4: return '4';
case 5: return '5';
case 6: return '6';
case 7: return '7';
case 8: return '8';
case 9: return '9';
}
}
void* sender(void* param){
int i = 0, peer_id;
char addr[10] = "node-";
addr[6] = '\\0';
struct sockaddr_in peer_addr;
peer_addr.sin_family = AF_INET;
peer_addr.sin_port = htons(20039);
bzero(&(peer_addr.sin_zero), 8);
char send_data[1024];
while(1){
sleep(HELLO_INTERVAL);
for(i = 0 ; i < NUMBER_OF_NEIGHBORS ; i++){
peer_id = NEIGHBOR_IDS[i];
addr[5] = exchange(peer_id);
host = (struct hostent *) gethostbyname(addr);
peer_addr.sin_addr = *((struct in_addr *) host->h_addr);
strncpy(send_data, "HELLO", 5);
strncpy(send_data + 5, (char *)&identifier, 4);
sendto(sock, send_data, 9, 0, (struct sockaddr *) &peer_addr, sizeof (struct sockaddr));
struct timeval timenow;
gettimeofday(&timenow, 0);
helloTime = ((timenow.tv_sec % 1000000)* 1000000 + (timenow.tv_usec));
}
}
}
void* receiver(void* param){
struct sockaddr_in peer_addr;
int addr_len = sizeof (struct sockaddr);
char recv_data[1024];
char send_data[1024];
int bytes_read;
char addr[10] = "node-";
addr[6] = '\\0';
int peer_id, i, cost, max, min, dummy, node_seq_num, node_id, num_of_entries, offset, j;
while(1){
bytes_read = recvfrom(sock, recv_data, 1024, 0, (struct sockaddr *) &peer_addr, &addr_len);
recv_data[bytes_read] = '\\0';
if(strncmp(recv_data, "HELLOREPLY", 10) == 0){
strncpy((char *)&peer_id, recv_data + 10, 4);
pthread_mutex_lock(&lock);
for(i = 0; i < NUMBER_OF_NEIGHBORS; i++){
if(actual_link_costs[i][0] == peer_id){
strncpy((char*)&dummy, recv_data + 18, 4);
struct timeval timenow;
gettimeofday(&timenow, 0);
actual_link_costs[i][1] = ((timenow.tv_sec % 1000000)* 1000000 + (timenow.tv_usec)) - helloTime;
break;
}
}
pthread_mutex_unlock(&lock);
}else if(strncmp(recv_data, "HELLO", 5) == 0){
strncpy((char *)&peer_id, recv_data + 5, 4);
cost = 0;
strncpy(send_data, "HELLOREPLY", 10);
strncpy(send_data + 10, (char *)&identifier, 4);
strncpy(send_data + 14, (char *)&peer_id, 4);
strncpy(send_data + 18, (char *)&cost, 4);
send_data[22] = '\\0';
sendto(sock, send_data, 22, 0, (struct sockaddr *) &peer_addr, sizeof (struct sockaddr));
}else if(strncmp(recv_data, "LSA", 3) == 0){
strncpy((char*)&node_id, recv_data + 3, 4);
strncpy((char*)&node_seq_num, recv_data + 7, 4);
if(node_id != identifier){
if(lsa_seq_num_det[node_id] < node_seq_num){
lsa_seq_num_det[node_id] = node_seq_num;
for(i = 0 ; i < NUMBER_OF_NEIGHBORS ; i++){
addr[5] = exchange(peer_id);
host = (struct hostent *) gethostbyname(addr);
peer_addr.sin_addr = *((struct in_addr *) host->h_addr);
peer_addr.sin_family = AF_INET;
peer_addr.sin_port = htons(20039);
bzero(&(peer_addr.sin_zero), 8);
sendto(sock, recv_data, bytes_read, 0, (struct sockaddr *) &peer_addr, sizeof (struct sockaddr));
}
strncpy((char*)&num_of_entries, recv_data + 11, 4);
offset = 15;
pthread_mutex_lock(&lock);
every_node_neighbors[node_id] = num_of_entries;
if(every_node_lsa_details[node_id] == 0){
every_node_lsa_details[node_id] = (int**)malloc(sizeof(int*) * num_of_entries);
for(j = 0 ; j < num_of_entries; j++){
every_node_lsa_details[node_id][j] = (int*)malloc(sizeof(int) * 2);
}
}
for(i = 0 ; i < num_of_entries ; i++){
strncpy((char*)&every_node_lsa_details[node_id][i][0], recv_data + offset, 4);
strncpy((char*)&every_node_lsa_details[node_id][i][1], recv_data + offset + 4, 4);
offset += 8;
}
pthread_mutex_unlock(&lock);
}
}
}
}
}
| 0
|
#include <pthread.h>
int id;
} philosopher;
int isFree;
pthread_mutex_t lock;
pthread_cond_t forkcond;
} chopstick;
chopstick f[5];
philosopher phil[5];
void init(void){
int i;
for(i=0; i<5; i++){
f[i].isFree = 1;
f[i].lock = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
f[i].forkcond = (pthread_cond_t)PTHREAD_COND_INITIALIZER;
phil[i].id = i;
}
}
int indexOfLfork(philosopher p){
return p.id;
}
int indexOfRfork(philosopher p){
return (p.id + 1) % 5;
}
void takeNap(void){
usleep(random() % 25000);
}
int pickup(int index){
pthread_mutex_lock(&(f[index].lock));
if(!f[index].isFree){
pthread_mutex_unlock(&(f[index].lock));
return 1;
}
f[index].isFree = 0;
pthread_mutex_unlock(&(f[index].lock));
return 0;
}
void putdown(int index){
pthread_mutex_lock(&(f[index].lock));
f[index].isFree = 1;
pthread_mutex_unlock(&(f[index].lock));
}
const long DOLOCK = 1;
void *activity(void *args){
int i;
philosopher p;
p.id = *(int *)args;
int randfork[2] = {indexOfLfork(p), indexOfRfork(p)};
int randnum, fork1, fork2;
for(i=0; i<3; i++) {
randnum = rand() % 2;
fork1 = randfork[randnum];
fork2 = randfork[(randnum + 1) % 2];
takeNap();
if(pickup(fork1) > 0){
i--;
continue;
}
printf("philosopher %d picked up fork %d\\n", p.id, fork1);
takeNap();
if(pickup(fork2) > 0){
putdown(fork1);
printf("philosopher %d gives up and tries again...\\n", p.id);
i--;
continue;
}
printf("philosopher %d picked up fork %d\\n", p.id, fork2);
printf("philosopher %d eats\\n", p.id);
takeNap();
putdown(fork1);
putdown(fork2);
printf("philosopher %d put down both forks and finishes meal %d\\n", p.id, i);
}
printf("philosopher %d exits\\n", p.id);
pthread_exit((void *)0);
}
int main(int argc, char **argv){
int i;
pthread_t threads[5];
srandom(time(0));
init();
for(i=0; i<5; i++){
pthread_create(&threads[i], 0, activity, &(phil[i].id));
}
for(i=0; i<5; i++){
pthread_join(threads[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
unsigned int times;
unsigned int width_bytes;
unsigned int id;
pthread_cond_t *signal;
pthread_cond_t *peersignal;
} info;
pthread_cond_t signals[((unsigned int)8)];
pthread_mutex_t lock;
FILE *output = 0;
int next_id = 0;
void *thread(void *param0)
{
info *param = (info *) param0;
unsigned int times = param->times;
unsigned int width_bytes = param->width_bytes;
unsigned int id = param->id;
const double inverse_n = 2.0 / (double) times;
const int r = times % ((unsigned int)8);
const int l = times / ((unsigned int)8);
const int myN = l + (id < r);
int gN = myN;
int lN = myN*width_bytes;
unsigned int *lengths = (unsigned int*)malloc(gN*sizeof(unsigned int));
unsigned char *data = (unsigned char *)malloc(lN*sizeof(unsigned char));
unsigned int y,tmp;
int i;
for (i=0; i<gN; i++) lengths[i]=0;
for (i=0; i<lN; i++) data[i]=0;
unsigned int byte_count = 0;
int bit_num = 0;
int byte_acc = 0;
double Civ;
double Crv;
double Zrv;
double Ziv;
double Trv;
double Tiv;
unsigned int offset;
int x;
for( y = 0 ; y < gN ; y++ ) {
byte_count = 0;
bit_num = 0;
byte_acc = 0;
unsigned int yy = y + id * l + (id < r ? id : r);
Civ = yy * inverse_n - 1.0;
offset = y * width_bytes;
for (x = 0; x < times ; x++) {
Crv = x * inverse_n - 1.5;
Zrv = Crv;
Ziv = Civ;
Trv = Crv * Crv;
Tiv = Civ * Civ;
i = 49;
do {
Ziv = (Zrv*Ziv) + (Zrv*Ziv) + Civ;
Zrv = Trv - Tiv + Crv;
Trv = Zrv * Zrv;
Tiv = Ziv * Ziv;
} while ( ((Trv + Tiv) <= 4.0) && (--i > 0) );
byte_acc <<= 1;
byte_acc |= (i == 0) ? 1 : 0;
if (++bit_num == 8)
{
tmp = offset + byte_count;
if (tmp<lN)
data[tmp] = (unsigned char) byte_acc;
byte_count++;
bit_num = byte_acc = 0;
}
}
if (bit_num != 0) {
byte_acc <<= (8 - (gN & 7));
tmp = offset + byte_count;
if( tmp < lN )
data[tmp] = (unsigned char) byte_acc;
byte_count++;
}
lengths[y] = byte_count;
}
unsigned char *ft = data;
pthread_cond_t*signal = param->signal;
pthread_cond_t*peersignal = param->peersignal;
pthread_mutex_lock(&lock);
int should_wait = next_id != id;
if(should_wait) {
pthread_cond_wait(signal,&lock);
}
for( y = 0, tmp = 0 ; y < gN && tmp < lN ;
y++,tmp+=width_bytes ) {
fwrite(&ft[tmp], lengths[y], 1, output);
}
next_id++;
pthread_mutex_unlock(&lock);
if(peersignal) {
pthread_cond_signal(peersignal);
}
if(!peersignal && output != stdout) fclose(output);
free(param);
free(lengths);
free(data);
return 0;
}
int main(int argc, char *argv[])
{
if (argc != 2) exit(255);
unsigned int width_bytes,n,i;
n = atoi(argv[1]);
if( n < 1 ) exit(255);
width_bytes = n/8;
if (width_bytes*8 < n)
width_bytes += 1;
output = stdout;
fprintf(output,"P4\\n%d %d\\n", n, n);
pthread_mutex_init (&lock, 0);
for (i=0; i<((unsigned int)8); i++)
pthread_cond_init (&signals[i], 0);
for (i = 0 ; i < ((unsigned int)8) -1 ; i++) {
info *param = (info *) calloc(1,sizeof(info));
param->times = n;
param->width_bytes = width_bytes;
param->id = i;
param->signal = &signals[i];
param->peersignal = &signals[i+1];
pthread_t tid;
pthread_create(&tid, 0, thread,param);
}
info *param0 = (info *) calloc(1,sizeof(info));
param0->times = n;
param0->width_bytes = width_bytes;
param0->id = ((unsigned int)8)-1;
param0->signal = &signals[((unsigned int)8)-1];
param0->peersignal = 0;
thread(param0);
return 0;
}
| 0
|
#include <pthread.h>
void *temperature_thread_entry()
{
int8_t temperature;
struct peer_net_params admin_addr;
admin_addr.ipstr[0] = '\\0';
while (1) {
temperature = get_temperature();
get_admin_params(&admin_addr);
if (admin_addr.ipstr[0] != '\\0') {
send_temperature(&admin_addr, temperature);
} else {
printf("[Temp] Admin address not know yet!\\r\\n");
}
sleep(SENSOR_SLEEP_INTERVAL);
}
pthread_exit(0);
}
int8_t get_temperature()
{
srand(time(0));
int32_t random_temp = rand() % 50;
return random_temp;
}
int8_t get_admin_params(struct peer_net_params *pnp)
{
pthread_mutex_lock (&mutex_adminp);
pnp->family = admin_net_params.family;
strcpy(pnp->ipstr, admin_net_params.ipstr);
printf("[Temp]DEBUG: Admin IP:%s\\r\\n", pnp->ipstr);
pthread_mutex_unlock (&mutex_adminp);
return 0;
}
int32_t get_time_offset()
{
int32_t timeoffset;
pthread_mutex_lock (&mutex_timeoffset);
timeoffset = node_admin_offset;
pthread_mutex_unlock (&mutex_timeoffset);
return timeoffset;
}
void send_temperature(struct peer_net_params *pnp,int8_t temperature)
{
printf("[Temp] Sending temperature \\"%d\\" to server \\"%s\\".\\r\\n",
temperature, pnp->ipstr);
int32_t sockfd, buflen, timenow, timeoffset, realtime;
char buffer[15];
struct node_message *node_msg = 0;
buflen = snprintf(buffer, 15, "%d", temperature);
add_node_msg (&node_msg, REPORT_TEMPERATURE, buflen, buffer);
timenow = time(0);
timeoffset = get_time_offset();
realtime = timenow + timeoffset;
printf("[Temp] Real time at admin node: %d\\r\\n", realtime);
buflen = snprintf(buffer, 15, "%d", realtime);
add_node_msg (&node_msg, TEMP_TIMESTAMP, buflen, buffer);
char *msg=0;
msg = serilization(node_msg);
int32_t len = strlen(msg);
sockfd = get_socket(&np, pnp, DATA_SUBMIT);
send(sockfd, msg, len, 0);
close(sockfd);
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
long counter = 0L;
pthread_barrier_t barrier;
void *thread_counting(void *ptr)
{
int fd;
int i;
long ending;
char buffer[16384];
char *filename = (char*) ptr;
pthread_mutex_lock(&lock);
ending = 0L;
fd = open(filename, O_RDONLY);
if (fd < 0)
{
printf("Error reading File\\n");
exit(1);
}
while(1)
{
ssize_t size_read = read(fd, buffer, 16384);
if (size_read == 0)
{
break;
}
for(i=0; i<size_read; i++)
{
unsigned char c = buffer[i];
ending = ending + (int) c;
}
}
printf("Summe für File %s ist gleich %ld\\n", filename, ending);
pthread_mutex_unlock(&lock);
printf("Thread wartet!\\n");
pthread_barrier_wait(&barrier);
pthread_mutex_lock(&lock);
counter = counter + ending;
pthread_mutex_unlock(&lock);
}
int main(int argc, char *argv[])
{
if (argc <= 1)
{
printf("Dateinamen als Parameter angeben: ./process1 dateiname1 dateiname2\\n");
exit(1);
}
int zaehler;
int retcode;
int ergebnis[argc-1];
pthread_t thread[argc-1];
pthread_barrier_init(&barrier, 0, argc-1);
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("Mutex init failed\\n");
exit(1);
}
printf("Starte Prozesse!\\n");
for(zaehler=1;zaehler<argc;zaehler++)
{
printf("Starte Thread %d\\n", zaehler);
retcode = pthread_create(&thread[zaehler], 0, thread_counting, argv[zaehler]);
if(retcode < 0)
{
printf("Error creating thread %d errno=%d, retcode=%d\\n", zaehler, errno, retcode);
exit(1);
}
}
for(zaehler=1;zaehler<argc;zaehler++)
{
pthread_join(thread[zaehler], 0);
printf("Joining Thread %d\\n", zaehler);
}
pthread_mutex_destroy(&lock);
printf("Summe allgemein: %ld\\n", counter);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
void* threadRead(void*);
void* threadWrite(void*);
int shmid;
char *buf[4092];
int main(int argc,char** argv)
{
printf("Enter main\\n");
printf("Create shared memory id\\n");
shmid=shmget(IPC_PRIVATE,sizeof(char)*4092,IPC_CREAT|0666);
printf("shmid:%d\\n",shmid);
int rt=0,wt=0;
pthread_t rtid,wtid;
wt=pthread_create(&wtid,0,threadWrite,0);
if(wt!=0)
{
printf("create Write Thread error:%s,errno:%d\\n",strerror(errno),errno);
exit(0);
}
rt=pthread_create(&rtid,0,threadRead,&wtid);
if(rt!=0)
{
printf("create Read Thread error:%s,errno:%d\\n",strerror(errno),errno);
exit(0);
}
pthread_cond_wait(&cond,&mutex);
printf("Leave main\\n");
exit(0);
}
void* threadRead(void* arg)
{
printf("Enter Read thread,start reading after Write thread finished!\\n");
char *shmptr;
int i=0;
char word;
if((int)(shmptr=shmat(shmid,0,0))==-1)
{
printf("The Read thread attach the shared memory failed!\\n");
exit(0);
}
printf("threadRead Attached successfully!\\n");
pthread_join(*(pthread_t*)arg,0);
printf("this is Read thread,thread id is %u,g_Flag:%d\\n",(unsigned int)pthread_self(),g_Flag);
pthread_mutex_lock(&mutex);
printf("Reading shared memory...\\n");
printf("Content:%s\\n",shmptr);
shmdt(shmptr);
pthread_mutex_unlock(&mutex);
printf("Read over,thread id is %u,g_Flag:%d\\n",(unsigned int)pthread_self(),g_Flag);
printf("Leave Read thread!\\n");
pthread_cond_signal(&cond);
pthread_exit(0);
}
void* threadWrite(void* arg)
{
printf("Enter Write thread,we'll write something\\n");
char *shmptr;
int i=0;
char word;
if((int)(shmptr=shmat(shmid,0,0))==-1)
{
printf("The Write thread attach the shared memory failed!\\n");
exit(0);
}
printf("threadWrite Attached successfully!\\n");
printf("this is Write thread,thread id is %u,g_Flag:%d\\n",(unsigned int)pthread_self(),g_Flag);
pthread_mutex_lock(&mutex);
printf("write a string into shared memory\\n");
while((word=getchar())!='\\n')
shmptr[i++]=word;
pthread_mutex_unlock(&mutex);
printf("Write over,thread id is %u,g_Flag:%d\\n",(unsigned int)pthread_self(),g_Flag);
printf("Leave Write thread!\\n");
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t fork_mutex[5];
pthread_mutex_t grab_mutex;
pthread_mutex_t drop_mutex;
pthread_cond_t eat_cond;
int num_eating;
int main()
{
int i;
pthread_t diner_thread[5];
int dn[5];
void *diner();
num_eating = 0;
for (i = 0; i < 5; i++)
pthread_mutex_init(&fork_mutex[i], 0);
pthread_mutex_init(&grab_mutex, 0);
pthread_mutex_init(&drop_mutex, 0);
pthread_cond_init(&eat_cond, 0);
for (i = 0; i < 5; i++)
{
dn[i] = i;
pthread_create(&diner_thread[i], 0, diner, &dn[i]);
}
for (i = 0; i < 5; i++)
pthread_join(diner_thread[i], 0);
pthread_exit(0);
}
void *diner(int *i)
{
int v;
int eating = 0;
printf("I'm diner %d\\n", *i);
v = *i;
while (eating < 5)
{
printf("%d is thinking\\n", v);
sleep(v / 2);
printf("%d is hungry\\n", v);
pthread_mutex_lock(&grab_mutex);
while (num_eating >= 3)
{
pthread_cond_wait(&eat_cond, &grab_mutex);
}
pthread_mutex_lock(&fork_mutex[v]);
pthread_mutex_lock(&fork_mutex[(v + 1) % 5]);
pthread_mutex_unlock(&grab_mutex);
printf("%d is eating\\n", v);
num_eating++;
eating++;
sleep(1);
printf("%d is done eating\\n", v);
pthread_mutex_lock(&drop_mutex);
num_eating--;
pthread_mutex_unlock(&fork_mutex[v]);
pthread_mutex_unlock(&fork_mutex[(v + 1) % 5]);
pthread_cond_broadcast(&eat_cond);
pthread_mutex_unlock(&drop_mutex);
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t my_mutex;
void *pthread_example(void *void_tid)
{
int status;
printf("[demo-pthread-mutex][thread1] Initialize thread1\\n");
printf("[demo-pthread-mutex][thread1] pthread_mutex_trylock() will instantly fail bc main has the lock\\n");
status = pthread_mutex_trylock(&my_mutex);
if (status != 0)
{
printf("[demo-pthread-mutex][thread1] Trylock failed!\\n");
}
printf("[demo-pthread-mutex][thread1] Now running mutex_lock- it will block until main releases it \\n");
pthread_mutex_lock(&my_mutex);
printf("[demo-pthread-mutex][thread1] Got the lock!\\n");
pthread_mutex_unlock(&my_mutex);
printf("[demo-pthread-mutex][thread1] Released the lock!\\n");
printf("[demo-pthread-mutex][thread1] Exiting!\\n");
return 0;
}
void *pthread_example_2(void *void_tid)
{
int status = 2;
printf("[demo-pthread-mutex][thread 2] Exiting with status %d \\n", status);
pthread_exit((void *)&status);
}
int main(void)
{
pthread_t my_thread_1;
printf("[demo-pthread-mutex][main] This program will demonstrate mutex_init, mutex_lock, mutex_destroy, mutex_lock, mutex_trylock, mutex_unlock\\n");
printf("[demo-pthread-mutex][main] initialize mutex w default parameters\\n");
pthread_mutex_init(&my_mutex, 0);
printf("[demo-pthread-mutex][main] now lock the mutex for 5 seconds before spawning threads\\n");
pthread_mutex_lock(&my_mutex);
if(pthread_create(&my_thread_1, 0, pthread_example, 0) != 0)
{
printf("[demo-pthread-mutex][main] failed to create pthread\\n");
return 1;
}
sleep(5);
printf("[demo-pthread-mutex][main] now releasing the mutex\\n");
pthread_mutex_unlock(&my_mutex);
if (pthread_join(my_thread_1, 0) != 0)
{
printf("[demo-pthread-mutex][main] failed to join with pthread\\n");
return 1;
}
printf("[demo-pthread-mutex][main] joined with thread1\\n");
printf("[demo-pthread-mutex][main] destroy mutex\\n");
pthread_mutex_destroy(&my_mutex);
printf("[demo-pthread-mutex] Complete- exiting!\\n");
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t gm;
struct node{
int id;
struct node *next;
unsigned long nextNodeInfo[3];
};
struct list
{
int head_id;
struct node *next;
unsigned long nextNodeInfo[3];
} list_t;
void *t(void *args){
nvcheckpoint();
pthread_exit(0);
}
int main(){
pthread_mutex_init(&gm, 0);
pthread_t tid1;
pthread_t tid2;
printf("CHECKING CRASH STATUS...\\n");
if ( isCrashed() ) {
printf("I NEED TO RECOVER!\\n");
void *ptr = malloc(sizeof(int));
nvrecover(ptr, sizeof(int), (char *)"c");
printf("RECOVERED c = %d WITH ADD %p\\n", *(int*)ptr, (int*)ptr);
free(ptr);
struct list *l = (struct list*)malloc(sizeof(struct list) );
nvrecover(l, sizeof(struct list), (char*)"z");
printf("Recovered l->head_id = %d\\n", l->head_id);
printf("list entry object address, l: %p\\n", l);
struct node *nd = (struct node*)malloc(sizeof(struct node) );
printf("sizeof node: %d, size in l->nextNodeInfo[2]: %d\\n",sizeof(struct node), l->nextNodeInfo[2]);
my_custom_nvrecover(nd, l->nextNodeInfo[0], l->nextNodeInfo[1], l->nextNodeInfo[2]);
printf("nd->id: %d\\n", nd->id);
}
else{
printf("PROGRAM DIDNOT CRASH BEFORE, CONTINUE NORMAL EXECUTION.\\n");
pthread_create(&tid1, 0, t, 0);
pthread_mutex_lock(&gm);
int *c = (int *)nvmalloc(sizeof(int), (char *)"c");
*c = 12345;
printf("c: %d ADD %p\\n", *c, c);
struct list *l = (struct list *)nvmalloc(sizeof(struct list), (char *)"z");
l->head_id = 99;
unsigned long *nextNodeInfo = (unsigned long *)malloc(3*sizeof(unsigned long));
struct node *nd1 = (struct node *)my_custom_nvmalloc(sizeof(struct node), (char *)"z", 1, nextNodeInfo);
nd1->id = 999;
nd1->next = 0;
l->next = nd1;
l->nextNodeInfo[0] = nextNodeInfo[0];
l->nextNodeInfo[1] = nextNodeInfo[1];
l->nextNodeInfo[2] = nextNodeInfo[2];
free(nextNodeInfo);
printf("addr l: %p\\n", l);
printf("addr nd1: %p\\n", nd1);
printf("l->next: %p\\n", l->next);
printf("l->head_id: %d\\n", l->head_id);
printf("l->next->id: %d\\n", l->next->id);
printf("pageNo, l->nextNodeInfo[0]: %zu\\n", l->nextNodeInfo[0]);
printf("pageOffset, l->nextNodeInfo[1]: %zu\\n", l->nextNodeInfo[1]);
printf("size, l->nextNodeInfo[2]: %zu\\n", l->nextNodeInfo[2]);
pthread_mutex_unlock(&gm);
printf("INTERNALLY ABORT!\\n");
abort();
}
printf("-------------MAIN EXITS-------------------\\n");
return 0;
}
| 0
|
#include <pthread.h>
int state[5];
int forks[5];
pthread_t p_thread[5];
pthread_mutex_t mutex[2] = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond[5] = PTHREAD_COND_INITIALIZER;
void *philosopher(void *num);
void get_forks(int phi, int l_fork, int r_fork);
void put_forks(int phi, int l_fork, int r_fork);
void get(int phi, int l_fork, int r_fork);
int main(int argc, char **argv)
{
int i;
for(i = 0; i < 5; i++){
forks[i] = 1;
}
for(i = 0; i < 5; i++){
pthread_create(&p_thread[i], 0, philosopher, (void *)(intptr_t)i);
}
for(i = 0; i < 5; i++){
pthread_join(p_thread[i], 0);
}
return 0;
}
void *philosopher(void *num)
{
int pos = (intptr_t)num;
int left_fork, right_fork;
int wait_think, wait_eat;
state[pos] = 0;
printf("Thinking... [%d]\\n", pos);
left_fork = pos;
right_fork = (pos + 1) % 5;
while(1){
wait_think = rand() % 20 + 1;
sleep(wait_think);
get_forks(pos, left_fork, right_fork);
if(state[pos] == 2){
printf("Eating... [%d]\\n", pos);
wait_eat = rand() % 8 + 2;
sleep(wait_eat);
put_forks(pos, left_fork, right_fork);
}
}
pthread_exit(0);
}
void get_forks(int phi, int l_fork, int r_fork)
{
int wait_eat;
pthread_mutex_lock(&mutex[0]);
state[phi] = 1;
get(phi, l_fork, r_fork);
if(state[phi] != 2){
printf("Waiting... [%d]\\n", phi);
while(1){
if(state[(phi+1)%5] == 2 && state[(phi+4)%5] == 2){
pthread_cond_wait(&cond[l_fork], &mutex[0]);
pthread_cond_wait(&cond[r_fork], &mutex[0]);
get(phi, l_fork, r_fork);
}
else if(state[(phi+1)%5] == 2){
pthread_cond_wait(&cond[r_fork], &mutex[0]);
get(phi, l_fork, r_fork);
}
else{
pthread_cond_wait(&cond[l_fork], &mutex[0]);
get(phi, l_fork, r_fork);
}
if(state[phi] == 2){
break;
}
}
}
pthread_mutex_unlock(&mutex[0]);
}
void put_forks(int phi, int l_fork, int r_fork)
{
pthread_mutex_lock(&mutex[0]);
pthread_mutex_lock(&mutex[1]);
forks[l_fork] = 1;
forks[r_fork] = 1;
printf("Forks: %d-%d-%d-%d-%d\\n", forks[0],forks[1],forks[2],forks[3],forks[4]);
state[phi] = 0;
printf("Thinking... [%d]\\n", phi);
pthread_mutex_unlock(&mutex[1]);
pthread_mutex_unlock(&mutex[0]);
pthread_cond_signal(&cond[l_fork]);
pthread_cond_signal(&cond[r_fork]);
}
void get(int phi, int l_fork, int r_fork)
{
if(state[(phi+1)%5] != 2 && state[(phi+4)%5] != 2 && state[phi] == 1){
state[phi] = 2;
pthread_mutex_lock(&mutex[1]);
forks[l_fork] = 0;
forks[r_fork] = 0;
printf("Forks: %d-%d-%d-%d-%d\\n", forks[0],forks[1],forks[2],forks[3],forks[4]);
pthread_mutex_unlock(&mutex[1]);
pthread_cond_signal(&cond[l_fork]);
pthread_cond_signal(&cond[r_fork]);
}
}
| 1
|
#include <pthread.h>
int total = 0;
pthread_mutex_t *lock;
void *tfn(void *arg)
{
int num = *((int *)arg);
long d2num = 2*num;
pthread_mutex_lock(lock);
total+=num;
pthread_mutex_unlock(lock);
printf("num=%d total=%d\\n",num,total);
return (void*)(d2num);
}
int main(int argc,char *argv[])
{
pthread_t tid;
int num;
lock=(pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
pthread_mutex_init(lock,0);
while(scanf("%d",&num)==1)
{
pthread_create(&tid,0,tfn,(void*)&num);
printf("total = %d\\n",total);
}
pthread_mutex_destroy(lock);
free(lock);
return 0;
}
| 0
|
#include <pthread.h>
bool raspberryPilotInit();
int main() {
struct timeval tv_c;
struct timeval tv_l;
unsigned long timeDiff=0;
if (!raspberryPilotInit()) {
return 0;
}
gettimeofday(&tv_l,0);
while (!getLeaveFlyControlerFlag()) {
gettimeofday(&tv_c,0);
timeDiff=GET_USEC_TIMEDIFF(tv_c,tv_l);
if(timeDiff >=((unsigned long) (getAdjustPeriod() * 5000))){
pthread_mutex_lock(&controlMotorMutex);
if (flySystemIsEnable()) {
if (getPacketCounter() < MAX_COUNTER) {
if (getPidSp(&yawAttitudePidSettings) != 321.0) {
if(getFlippingFlag()!= FLIP_NONE){
motorControlerFlipping();
}else{
motorControler();
}
} else {
setFlippingFlag(FLIP_NONE);
setFlippingStep(0);
setThrottlePowerLevel(getMinPowerLevel());
setupAllMotorPoewrLevel(getMinPowerLevel(),
getMinPowerLevel(), getMinPowerLevel(),
getMinPowerLevel());
}
} else {
setFlippingFlag(FLIP_NONE);
setFlippingStep(0);
triggerSecurityMechanism();
}
} else {
setFlippingFlag(FLIP_NONE);
setFlippingStep(0);
setThrottlePowerLevel(0);
setupAllMotorPoewrLevel(0, 0, 0, 0);
}
pthread_mutex_unlock(&controlMotorMutex);
UPDATE_LAST_TIME(tv_c,tv_l);
}
usleep(500);
}
return 0;
}
bool raspberryPilotInit() {
if (!piSystemInit()) {
_ERROR("(%s-%d) Init Raspberry Pi failed!\\n", __func__, 139);
return 0;
}else{
securityMechanismInit();
pidInit();
ahrsInit();
}
if (!flyControlerInit()) {
_ERROR("(%s-%d) Init flyControlerInit failed!\\n", __func__, 148);
return 0;
}
if (!pca9685Init()) {
_ERROR("(%s-%d) Init PCA9685 failed!\\n", __func__, 153);
return 0;
}
if (!mpu6050Init()) {
_ERROR("(%s-%d) Init MPU6050 failed!\\n", __func__, 158);
return 0;
}
if (!initAltHold()) {
_ERROR("(%s-%d) Init altHold failed!\\n", __func__, 163);
}
if (!radioControlInit()) {
_ERROR("(%s-%d) radioControler init failed\\n", __func__, 167);
return 0;
}
if(!altitudeUpdateInit()){
_ERROR("(%s-%d) attitude update failed\\n", __func__, 172);
return 0;
}
_DEBUG(DEBUG_NORMAL, "(%s-%d) Raspberry Pilot init done\\n", __func__,
177);
return 1;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex ;
pthread_cond_t cond ;
int flag=0;
void thread1(void *arg) ;
void thread2(void *arg) ;
int main(void)
{
int count = 6;
pthread_t thid1, thid2 ;
pthread_mutex_init (&mutex, PTHREAD_MUTEX_TIMED_NP) ;
pthread_cond_init (&cond, 0) ;
if(pthread_create (&thid1, 0, (void *)thread1, 0)) {
printf ("thread1 create failed\\n") ;
}
if(pthread_create (&thid2, 0, (void *)thread2, 0)) {
printf ("thread2 create failed\\n") ;
}
while(count-- > 0) {
sleep(1);
pthread_cond_signal (&cond) ;
if(flag == 2) {
break;
}
}
return 0 ;
}
void thread1(void *arg)
{
int count= 3 ;
pthread_cleanup_push (pthread_mutex_unlock, &mutex) ;
while(count-- > 0) {
printf ("thread1 is runing\\n") ;
pthread_mutex_lock (&mutex) ;
pthread_cond_wait (&cond, &mutex) ;
printf ("thread1 get the condition\\n") ;
pthread_mutex_unlock (&mutex) ;
}
flag++ ;
pthread_cleanup_pop (0) ;
}
void thread2(void *arg)
{
int count = 2 ;
pthread_cleanup_push (pthread_mutex_unlock, &mutex) ;
printf ("thread2 is runing\\n") ;
while(count-- > 0) {
pthread_mutex_lock (&mutex) ;
pthread_cond_wait (&cond, &mutex) ;
printf ("thread2 get the condition\\n") ;
pthread_mutex_unlock (&mutex) ;
}
flag++ ;
pthread_cleanup_pop (0) ;
}
| 0
|
#include <pthread.h>
struct node {
int n_number;
struct node *n_next;
};
struct node *head = 0;
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static void cleanup_handler1(void *arg)
{
printf("Cleanup thread----[1].\\n");
free(arg);
(void)pthread_mutex_unlock(&mtx);
}
static void cleanup_handler2(void *arg)
{
printf("Cleanup thread----[2].\\n");
free(arg);
(void)pthread_mutex_unlock(&mtx);
}
static void *thread1(void *arg)
{
struct node *p = 0;
pthread_cleanup_push(cleanup_handler1, p);
while (1) {
pthread_mutex_lock(&mtx);
while (head == 0) {
pthread_cond_wait(&cond, &mtx);
}
p = head;
head = head->n_next;
printf("THREAD[1]: Got %d from front of queue.\\n", p->n_number);
free(p);
pthread_mutex_unlock(&mtx);
}
pthread_cleanup_pop(0);
return 0;
}
static void *thread2(void *arg)
{
struct node *p = 0;
pthread_cleanup_push(cleanup_handler2, p);
while (1) {
pthread_mutex_lock(&mtx);
while (head == 0) {
pthread_cond_wait(&cond, &mtx);
}
p = head;
head = head->n_next;
printf("THREAD[2]: Got %d from front of queue.\\n", p->n_number);
free(p);
pthread_mutex_unlock(&mtx);
}
pthread_cleanup_pop(0);
return 0;
}
int main(void)
{
pthread_t tid1, tid2;
int i;
struct node *p;
pthread_create(&tid1, 0, thread1, 0);
pthread_create(&tid2, 0, thread2, 0);
for (i = 0; i < 15; i++) {
p = malloc(sizeof(struct node));
p->n_number = i;
pthread_mutex_lock(&mtx);
p->n_next = head;
head = p;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mtx);
sleep(1);
}
printf("Parent thread wanna end the line. So cancel Child thread.\\n");
pthread_cancel(tid1);
pthread_cancel(tid2);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
printf("All done -- exiting.\\n");
return 0;
}
| 1
|
#include <pthread.h>
int sens= -1;
static pthread_mutex_t m= PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cOE= PTHREAD_COND_INITIALIZER;
static pthread_cond_t cEO= PTHREAD_COND_INITIALIZER;
static int nb= 0;
void initThreadSynchro() {
};
pthread_t AllumageTrain(void *arg) {
pthread_t th;
int res= pthread_create(& th, 0, train, arg);
if (res)
handle_fatalError("create", "trainmonitor.c");
return th;
}
void TerminaisonTrain(pthread_t t) {
int res = pthread_join(t, 0);
if (res)
handle_fatalError("join", "trainmonitor.c");
};
void entreeEO() {
pthread_mutex_lock(& m);
while(sens == OE && nb > 0)
pthread_cond_wait(&cEO, &m);
if (sens != EO) {
assert(nb == 0);
sens = EO;
pthread_cond_broadcast(& cEO);
}
nb ++;
pthread_mutex_unlock(& m);
}
void sortieEO() {
pthread_mutex_lock(& m);
nb --;
if (nb == 0)
pthread_cond_signal(& cOE);
pthread_mutex_unlock(& m);
}
void entreeOE() {
pthread_mutex_lock(& m);
while(sens == EO && nb > 0)
pthread_cond_wait(&cOE, &m);
if (sens != OE) {
sens = OE;
pthread_cond_broadcast(& cOE);
}
nb ++;
pthread_mutex_unlock(& m);
}
void sortieOE() {
pthread_mutex_lock(& m);
nb --;
if (nb == 0)
pthread_cond_signal(& cEO);
pthread_mutex_unlock(& m);
}
| 0
|
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
void *functionCount1();
void *functionCount2();
int count = 0;
void main()
{
pthread_t thread1, thread2;
pthread_create( &thread1, 0, &functionCount1, 0);
pthread_create( &thread2, 0, &functionCount2, 0);
pthread_join( thread1, 0);
pthread_join( thread2, 0);
exit(0);
}
void *functionCount1()
{
for(;;) {
pthread_mutex_lock( &count_mutex );
if ( count % 2 != 0 ) {
pthread_cond_wait( &condition_var, &count_mutex );
}
count++;
printf("Counter value functionCount1: %d\\n",count);
pthread_cond_signal( &condition_var );
if ( count >= 200 ) {
pthread_mutex_unlock( &count_mutex );
return(0);
}
pthread_mutex_unlock( &count_mutex );
}
}
void *functionCount2()
{
for(;;) {
pthread_mutex_lock( &count_mutex );
if ( count % 2 == 0 ) {
pthread_cond_wait( &condition_var, &count_mutex );
}
count++;
printf("Counter value functionCount2: %d\\n",count);
pthread_cond_signal( &condition_var );
if( count >= 200 ) {
pthread_mutex_unlock( &count_mutex );
return(0);
}
pthread_mutex_unlock( &count_mutex );
}
}
| 1
|
#include <pthread.h>
pthread_t philosopher[5];
pthread_mutex_t chopstick[5];
void *fun(void*);
int main(){
int i;
for(i=0; i<5; i++)
pthread_mutex_init(&chopstick[i],0);
for(i=0; i<5; i++)
pthread_create(&philosopher[i],0, fun, (void*)&i);
for(i=0; i<5; i++)
pthread_join(philosopher[i],0);
for(i=0; i<5; i++)
pthread_mutex_destroy(&chopstick[i]);
}
void *fun(void *n){
int num = *(int*)n;
printf("\\x1b[31m" "philosopher %d is thinking\\n" "\\x1b[0m", num+1);
pthread_mutex_lock(&chopstick[num]);
pthread_mutex_lock(&chopstick[(num+1)%5]);
printf("\\x1b[32m" "philosopher %d is eating using chopstick %d and %d \\n\\n" "\\x1b[0m",num+1,num+1, (num+1)%5+1);
sleep(5);
pthread_mutex_unlock(&chopstick[num]);
pthread_mutex_unlock(&chopstick[(num+1)%5]);
printf("\\x1b[36m" "Philosopher %d finished eating and freed %d and %d\\n" "\\x1b[0m",num+1, num+1 ,(num+1)%5+1);
}
| 0
|
#include <pthread.h>
int buffer[10];
int first = 0;
int num = 0;
pthread_mutex_t mon = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t itemCond = PTHREAD_COND_INITIALIZER;
pthread_cond_t slotCond = PTHREAD_COND_INITIALIZER;
static void fail( char const *msg );
void *producer(void *param) {
for ( int i=0; i < 1000; i++ ) {
int item = i;
printf ( "Produced item %d\\n", item ); fflush( stdout );
pthread_mutex_lock( &mon );
while ( num == 10 )
pthread_cond_wait( &slotCond, &mon );
buffer[ ( first + num ) % 10 ] = item;
num++;
pthread_cond_signal( &itemCond );
pthread_mutex_unlock( &mon );
}
return 0;
}
void *consumer(void *param) {
for ( int i = 0; i < 1000; i++ ) {
pthread_mutex_lock( &mon );
while ( num == 0 )
pthread_cond_wait( &itemCond, &mon );
int item = buffer[ first ];
first = ( first + 1 ) % 10;
num--;
pthread_cond_signal( &slotCond );
pthread_mutex_unlock( &mon );
printf ( "Consuming item %d\\n", item ); fflush( stdout );
}
return 0;
}
int main() {
pthread_t tid1, tid2;
if ( pthread_create(&tid1,0,producer,0) != 0 ||
pthread_create(&tid2,0,consumer,0) != 0 )
fail( "Unable to create consumer thread" );
pthread_join( tid1, 0 );
pthread_join( tid2, 0 );
return 0;
}
static void fail( char const *msg ) {
fprintf( stderr, "%s\\n", msg );
exit( -1 );
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex_var = PTHREAD_MUTEX_INITIALIZER;
int var;
int wait_barrier (int n){
pthread_mutex_lock(&mutex_var);
var++;
pthread_mutex_unlock(&mutex_var);
if( var == n ){
pthread_mutex_lock(&mutex);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
else{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
}
return 0;
}
void* thread_func (void *arg) {
printf ("avant barriere\\n");
wait_barrier (5);
printf ("apres barriere\\n");
pthread_exit ( (void*)0);
}
int main(int argc, char * argv[]){
int i, p,status;
int tab[5];
pthread_t tid[5];
var=0;
for(i=0; i<5; i++){
tab[i]=i;
if((p=pthread_create(&(tid[i]), 0, thread_func,0)) != 0){
perror("pthread_create");
exit(1);
}
}
for(i=0; i<5; i++){
if(pthread_join(tid[i],(void**) &status) != 0){
perror("pthread_join");
exit(1);
}
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
void *function(void *null) {
pthread_mutex_lock( &mutex1 );
counter++;
pthread_mutex_unlock( &mutex1 );
pthread_exit(0);
}
int main(void) {
pthread_t thread_id[10];
int i, j;
for(i=0; i < 10; i++) {
pthread_create( &thread_id[i], 0, function, 0 );
}
for(j=0; j < 10; j++) {
pthread_join( thread_id[j], 0);
}
printf("Final counter value: %d\\n", counter);
exit(0);
}
| 1
|
#include <pthread.h>
int wait=0;
pthread_mutex_t mutex;
pthread_cond_t cv;
int buf,wa=-1,wb=-1,c;
void * printa()
{
int j;
pthread_mutex_lock(&mutex);
int a,b;
printf("a recieved: %d \\n",buf);
if(wa==0)
{
a=buf;
pthread_cond_signal(&cv);
wb=0;
}
if(wb==0)
{
pthread_cond_wait(&cv,&mutex);
printf("b recieved: %d \\n",buf);
b=buf;
}
if (c!=0)
{ wait++;
pthread_cond_wait(&cv,&mutex);
}
j=a*b;
printf("mul: %d a:%d,b:%d\\n",j,a,b);
pthread_mutex_unlock(&mutex);
}
int main()
{ int k[2];
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cv, 0);
pthread_t t1;
pthread_create(&t1,0,printa,0);
pthread_mutex_lock(&mutex);
printf("ENTER THE Ist VALUE: ");
scanf("%d",&k[0]);
buf=k[0];
wa++;
if (wb!=0)
{
pthread_cond_wait(&cv,&mutex);
}
printf("ENTER THE II nd VALUE: ");
scanf("%d",&k[1]);
buf=k[1];
wb++;
if(wb==1)
{
pthread_cond_signal(&cv);
}
c=0;
if (wait!=0)
pthread_cond_signal(&cv);
pthread_mutex_unlock(&mutex);
pthread_join(t1,0);
}
| 0
|
#include <pthread.h>
void *horizontal_check(void *arg);
void *vertical_check(void *arg);
void *box_check(void *arg);
int find(int val, int *array);
int clear(int *array);
pthread_mutex_t valid_mutex;
int sudoku[9][9];
} sudoku;
int valid = 1;
int main(void){
FILE *file;
sudoku puzzle;
pthread_t tid[3];
file = fopen("puzzle.txt", "r");
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9; j++){
fscanf(file, "%d", &puzzle.sudoku[i][j]);
}
}
fclose(file);
pthread_create(&tid[0], 0, horizontal_check, (void*)&puzzle);
pthread_create(&tid[1], 0, vertical_check, (void*)&puzzle);
pthread_create(&tid[2], 0, box_check, (void*)&puzzle);
for(int i = 0; i < 3; i++){
pthread_join(tid[i], 0);
}
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9; j++){
printf("%d ", puzzle.sudoku[i][j]);
}
printf("\\n");
}
if(valid == 0){
printf("Invalid\\n");
}else{
printf("Valid\\n");
}
pthread_exit(0);
}
void *horizontal_check(void *arg){
int temp[9] = { 0 };
sudoku *puzzle = (sudoku*)arg;
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9; j++){
if(puzzle->sudoku[i][j] != 0){
if(find(puzzle->sudoku[i][j], temp) == 0){
pthread_mutex_lock(&valid_mutex);
valid = 0;
pthread_mutex_unlock(&valid_mutex);
pthread_exit(0);
}
temp[j] = puzzle->sudoku[i][j];
}
}
clear(&temp);
}
pthread_exit(0);
}
void *vertical_check(void *arg){
int temp[9] = { 0 };
sudoku *puzzle = (sudoku*)arg;
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9; j++){
if(puzzle->sudoku[j][i] != 0){
if(find(puzzle->sudoku[j][i], temp) == 0){
pthread_mutex_lock(&valid_mutex);
valid = 0;
pthread_mutex_unlock(&valid_mutex);
pthread_exit(0);
}
temp[j] = puzzle->sudoku[j][i];
}
}
clear(&temp);
}
pthread_exit(0);
}
void *box_check(void *arg){
int temp[9] = { 0 };
int x = 0;
sudoku *puzzle = (sudoku*)arg;
for(int l = 0; l < 9; l+=3){
for(int k = 0; k < 9; k+=3){
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
if(puzzle->sudoku[i+k][j+l] != 0){
if(find(puzzle->sudoku[i+k][j+l], temp) == 0){
pthread_mutex_lock(&valid_mutex);
valid = 0;
pthread_mutex_unlock(&valid_mutex);
pthread_exit(0);
}else{
temp[x++] = puzzle->sudoku[i+k][j+l];
}
}
}
}
clear(&temp);
x = 0;
}
}
pthread_exit(0);
}
int find(int val, int *array){
for(int i = 0; i < 9; i++){
if(val == array[i]){
return 0;
}
}
return 1;
}
int clear(int *array){
for(int i = 0; i < 9; i++){
array[i] = 0;
}
}
| 1
|
#include <pthread.h>
pthread_cond_t adultBoardOahu;
pthread_cond_t kidsBoardOahu;
pthread_cond_t onBoat;
pthread_cond_t onMolo;
int boatLoc;
int kidsOnBoard;
int adultsOnBoard;
int adultGoes;
void init() {
pthread_mutex_init(&lock, 0);
pthread_cond_init(&allReady, 0);
pthread_cond_init(&mayStart, 0);
pthread_cond_init(&allDone, 0);
pthread_cond_init(&adultBoardOahu, 0);
pthread_cond_init(&kidsBoardOahu, 0);
pthread_cond_init(&onBoat, 0);
pthread_cond_init(&onMolo, 0);
boatLoc = OAHU;
kidsOnBoard = 0;
adultsOnBoard = 0;
adultGoes = 0;
}
void* childThread(void* args) {
pthread_mutex_lock(&lock);
kidsOahu++;
pthread_cond_signal(&allReady);
while (!start) {
pthread_cond_wait(&mayStart, &lock);
}
while(kidsOahu > 0) {
while(adultsOahu > 0) {
while(boatLoc == MOLO || kidsOnBoard > 1 || adultsOnBoard > 0 || adultGoes == 1) {
pthread_cond_wait(&kidsBoardOahu, &lock);
}
boardBoat(KID, OAHU);
kidsOnBoard++;
kidsOahu--;
if(kidsOnBoard == 1) {
while(boatLoc == OAHU) {
pthread_cond_wait(&onBoat, &lock);
}
boatCross(MOLO, OAHU);
boatLoc = OAHU;
leaveBoat(KID, OAHU);
kidsOnBoard--;
kidsOahu++;
adultGoes = 1;
pthread_cond_signal(&adultBoardOahu);
} else {
boatCross(OAHU, MOLO);
boatLoc = MOLO;
leaveBoat(KID, MOLO);
kidsOnBoard--;
pthread_cond_signal(&onBoat);
while(boatLoc == OAHU || adultsOnBoard != 0 || kidsOnBoard != 0) {
pthread_cond_wait(&onMolo, &lock);
}
boardBoat(KID, MOLO);
kidsOnBoard++;
boatCross(MOLO, OAHU);
boatLoc = OAHU;
leaveBoat(KID, OAHU);
kidsOnBoard--;
kidsOahu++;
pthread_cond_signal(&kidsBoardOahu);
}
}
while(boatLoc == MOLO || kidsOnBoard > 1) {
pthread_cond_wait(&kidsBoardOahu, &lock);
}
boardBoat(KID, OAHU);
kidsOahu--;
kidsOnBoard++;
if(kidsOnBoard == 1) {
while(boatLoc == OAHU || kidsOnBoard == 2){
pthread_cond_wait(&onBoat, &lock);
}
if(kidsOahu != 0) {
boatCross(MOLO, OAHU);
boatLoc = OAHU;
leaveBoat(KID, OAHU);
kidsOnBoard--;
kidsOahu++;
pthread_cond_signal(&kidsBoardOahu);
} else {
leaveBoat(KID, MOLO);
kidsOnBoard--;
}
} else {
boatCross(OAHU, MOLO);
boatLoc = MOLO;
leaveBoat(KID, MOLO);
kidsOnBoard--;
pthread_cond_signal(&onBoat);
}
}
pthread_cond_signal(&allDone);
pthread_mutex_unlock(&lock);
return 0;
}
void* adultThread(void* args) {
pthread_mutex_lock(&lock);
adultsOahu++;
pthread_cond_signal(&allReady);
while (!start) {
pthread_cond_wait(&mayStart, &lock);
}
while(boatLoc == MOLO || kidsOnBoard > 0 || adultsOnBoard > 0 || adultGoes == 0) {
pthread_cond_wait(&adultBoardOahu, &lock);
}
boardBoat(ADULT, OAHU);
adultsOnBoard++;
adultGoes = 0;
adultsOahu--;
boatCross(OAHU, MOLO);
boatLoc = MOLO;
leaveBoat(ADULT, MOLO);
adultsOnBoard--;
pthread_cond_signal(&onMolo);
pthread_mutex_unlock(&lock);
return 0;
}
| 0
|
#include <pthread.h>
int philosopher[5];
int Fork[5];
pthread_mutex_t mutex;
void init();
int GetRandom(int min,int max);
void *func_thread(void *p);
int take(int fn, int pn);
void put(int fn, int pn);
void think(int num);
void eat(int num);
int main(int argc, char const *argv[])
{
init();
pthread_t pthread, pthread2, pthread3, pthread4, pthread5;
pthread_create(&pthread, 0, &func_thread, &philosopher[0]);
pthread_create(&pthread2, 0, &func_thread, &philosopher[1]);
pthread_create(&pthread3, 0, &func_thread, &philosopher[2]);
pthread_create(&pthread4, 0, &func_thread, &philosopher[3]);
pthread_create(&pthread5, 0, &func_thread, &philosopher[4]);
pthread_join(pthread, 0);
pthread_join(pthread2, 0);
pthread_join(pthread3, 0);
pthread_join(pthread4, 0);
pthread_join(pthread5, 0);
printf("Finish!!\\n");
return 0;
}
void init(){
int i;
for (i = 0; i < 5; ++i) {
philosopher[i] = i;
Fork[i] = -1;
}
}
int GetRandom(int min,int max)
{
srand((unsigned int)time(0));
return min + (int)(rand()*(max-min+1.0)/(1.0+32767));
}
void *func_thread(void *p){
int count = 0, num = *(int*)p;
int wait_count = 0;
int u1, u2;
if (num == 0){
u1 = 0;
u2 = 4;
} else{
u1 = num - 1;
u2 = num;
}
printf("start %d\\n", num);
while(count < 5){
pthread_mutex_lock(&mutex);
if (take(u1, num) || Fork[u1] == num){
if(take(u2, num)){
eat(num);
count++;
put(u2, num);
put(u1, num);
} else if(wait_count == 0){
usleep(GetRandom(1,3000000));
wait_count++;
} else{
put(u1, num);
wait_count = 0;
}
} else{
think(num);
}
pthread_mutex_unlock(&mutex);
}
printf("end %d\\n", num);
return 0;
}
int take(int fn, int pn){
if (Fork[fn] == -1){
Fork[fn] = pn;
return 1;
}
return 0;
}
void put(int fn, int pn){
if (Fork[fn] == pn){
Fork[fn] = -1;
}
}
void think(int num){
printf("philosopher %d is thinking.\\n", num);
sleep(1);
}
void eat(int num){
sleep(1);
printf("philosopher %d is eating.\\n", num);
}
| 1
|
#include <pthread.h>
pthread_t f_thread;
pthread_mutex_t f_mutex;
const char* string_debugs[] = {
"Allocation for struct PIECE",
"Allocation for struct GAME",
"Allocation for struct POSITION",
"Allocation for struct NODE",
"Allocation for struct LIST",
"Allocation for struct PLAYER",
"Allocation for struct TREE",
"Deallocation for struct PIECE",
"Deallocation for struct GAME",
"Deallocation for struct POSITION",
"Deallocation for struct NODE",
"Deallocation for struct LIST",
"Deallocation for struct PLAYER",
"Deallocation for struct TREE"
};
uint_fast32_t MEMALLOC_DEBUG_PIECE = 0 ;
uint_fast32_t MEMALLOC_DEBUG_GAME = 0 ;
uint_fast32_t MEMALLOC_DEBUG_POSITION = 0 ;
uint_fast32_t MEMALLOC_DEBUG_NODE = 0 ;
uint_fast32_t MEMALLOC_DEBUG_LIST = 0 ;
uint_fast32_t MEMALLOC_DEBUG_PLAYER = 0 ;
uint_fast32_t MEMALLOC_DEBUG_TREE = 0 ;
uint_fast32_t MEMDEALLOC_DEBUG_PIECE = 0 ;
uint_fast32_t MEMDEALLOC_DEBUG_GAME = 0 ;
uint_fast32_t MEMDEALLOC_DEBUG_POSITION = 0 ;
uint_fast32_t MEMDEALLOC_DEBUG_NODE = 0 ;
uint_fast32_t MEMDEALLOC_DEBUG_LIST = 0 ;
uint_fast32_t MEMDEALLOC_DEBUG_PLAYER = 0 ;
uint_fast32_t MEMDEALLOC_DEBUG_TREE = 0 ;
uint_fast32_t* ptr_on_res_ressources[MAX_DEBUG_VAR]={
&MEMALLOC_DEBUG_PIECE ,
&MEMALLOC_DEBUG_GAME ,
&MEMALLOC_DEBUG_POSITION ,
&MEMALLOC_DEBUG_NODE ,
&MEMALLOC_DEBUG_LIST ,
&MEMALLOC_DEBUG_PLAYER ,
&MEMALLOC_DEBUG_TREE ,
&MEMDEALLOC_DEBUG_PIECE,
&MEMDEALLOC_DEBUG_GAME,
&MEMDEALLOC_DEBUG_POSITION,
&MEMDEALLOC_DEBUG_NODE,
&MEMDEALLOC_DEBUG_LIST,
&MEMDEALLOC_DEBUG_PLAYER,
&MEMDEALLOC_DEBUG_TREE
};
void mem_debug_increment(const uint8_t ID ) {
pthread_mutex_lock(&f_mutex);
*(ptr_on_res_ressources[ID])+=1;
pthread_mutex_unlock(&f_mutex);
}
void destroy_mutex(){
pthread_mutex_destroy(&f_mutex);
}
void check_memleak(){
uint_fast32_t array[MAX_DEBUG_VAR]={
MEMALLOC_DEBUG_PIECE ,
MEMALLOC_DEBUG_GAME ,
MEMALLOC_DEBUG_POSITION ,
MEMALLOC_DEBUG_NODE ,
MEMALLOC_DEBUG_LIST ,
MEMALLOC_DEBUG_PLAYER ,
MEMALLOC_DEBUG_TREE ,
MEMDEALLOC_DEBUG_PIECE ,
MEMDEALLOC_DEBUG_GAME ,
MEMDEALLOC_DEBUG_POSITION ,
MEMDEALLOC_DEBUG_NODE ,
MEMDEALLOC_DEBUG_LIST ,
MEMDEALLOC_DEBUG_PLAYER ,
MEMDEALLOC_DEBUG_TREE
};
for(int i = 0 ; i < MAX_DEBUG_VAR/2 ; i++)
printf("%s:%i %s:%i \\n",string_debugs[i],(int)array[i],string_debugs[i+MAX_DEBUG_VAR/2],(int)array[i+MAX_DEBUG_VAR/2]);
}
| 0
|
#include <pthread.h>extern void __VERIFIER_assume(int);
extern void __VERIFIER_error() ;
int block;
int busy;
int inode;
pthread_mutex_t m_inode;
pthread_mutex_t m_busy;
void *allocator(){
pthread_mutex_lock(&m_inode);
if(inode == 0){
pthread_mutex_lock(&m_busy);
busy = 1;
pthread_mutex_unlock(&m_busy);
inode = 1;
}
block = 1;
if (!(block == 1)) ERROR: __VERIFIER_error();;
pthread_mutex_unlock(&m_inode);
return 0;
}
void *de_allocator(){
pthread_mutex_lock(&m_busy);
if(busy == 0){
block = 0;
if (!(block == 0)) ERROR: __VERIFIER_error();;
}
pthread_mutex_unlock(&m_busy);
return ((void *)0);
}
int main() {
pthread_t t1, t2;
__VERIFIER_assume(inode == busy);
pthread_mutex_init(&m_inode, 0);
pthread_mutex_init(&m_busy, 0);
pthread_create(&t1, 0, allocator, 0);
pthread_create(&t2, 0, de_allocator, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_mutex_destroy(&m_inode);
pthread_mutex_destroy(&m_busy);
return 0;
}
| 1
|
#include <pthread.h>
long ninc_per_thread;
long a;
long b;
long r;
long * p;
pthread_mutex_t * m;
} arg_t;
void * f(void * arg_) {
arg_t * arg = (arg_t *)arg_;
long a = arg->a, b = arg->b;
long ninc_per_thread = arg->ninc_per_thread;
if (b - a == 1) {
int i;
for (i = 0; i < ninc_per_thread; i++) {
pthread_mutex_lock(arg->m);
arg->p[0]++;
pthread_mutex_unlock(arg->m);
}
arg->r = a;
} else {
long c = (a + b) / 2;
arg_t cargs[2] = { { ninc_per_thread, a, c, 0, arg->p, arg->m },
{ ninc_per_thread, c, b, 0, arg->p, arg->m } };
pthread_t tid;
pthread_create(&tid, 0, f, cargs);
f(cargs + 1);
pthread_join(tid, 0);
arg->r = cargs[0].r + cargs[1].r;
}
return 0;
}
pthread_mutex_t m[1] = { PTHREAD_MUTEX_INITIALIZER };
int main(int argc, char ** argv) {
long nthreads = (argc > 1 ? atol(argv[1]) : 100);
long ninc_per_thread = (argc > 2 ? atol(argv[2]) : 10000);
long p[1] = { 0 };
arg_t arg[1] = { { ninc_per_thread, 0, nthreads, 0, p, m } };
pthread_t tid;
pthread_create(&tid, 0, f, arg);
pthread_join(tid, 0);
if (arg->r == (nthreads - 1) * nthreads / 2
&& arg->p[0] == nthreads * ninc_per_thread) {
printf("OK\\n");
return 0;
} else {
printf("NG: p = %ld != nthreads * ninc_per_thread = %ld\\n",
arg->p[0], nthreads * ninc_per_thread);
return 1;
}
}
| 0
|
#include <pthread.h>
int ranking;
int leader_id;
pthread_mutex_t lock;
} Best_ranking;
int tid;
int ranking;
int count;
} arg_t;
int nt;
pthread_mutex_t lock;
} Counter;
sem_t barrier1, barrier2;
Counter c;
Best_ranking best_ranking;
int Random_Generator(int *rankings, int *N){
int ret;
int k = *N;
int x = rand()%k;
ret = rankings[x];
rankings[x] = rankings[k-1];
k--;
(*N) = k;
return ret;
}
static void signal_handler(int signo){
if(signo == SIGUSR1){
signal(SIGUSR1, signal_handler);
}
}
void *Thread(void *args);
int main(int argc, char* argv[]){
int N, i, *rankings, not_assigned, tid, *threads_rand, not_assignedT;
pthread_t *threads;
arg_t *args;
if(argc < 2){
fprintf(stderr, "Invalid number of input parameters\\n"); return -1;
}
N = atoi(argv[1]);
if(N <= 8){
fprintf(stderr, "N must be greater than 8\\n"); return -1;
}
threads = (pthread_t*) malloc(N * sizeof(pthread_t));
args = (arg_t*) malloc(N * sizeof(pthread_t));
rankings = (int*) malloc(N * sizeof(int));
threads_rand = (int*) malloc(N * sizeof(int));
not_assigned = N;
srand(time(0));
for(i = 0; i < N; i++){
rankings[i] = i;
}
sem_init(&barrier1, 0, N-3);
sem_init(&barrier2, 0, 0);
pthread_mutex_init(&best_ranking.lock, 0);
pthread_mutex_init(&c.lock, 0);
for(i = 0; i < N; i++){
args[i].tid = i;
args[i].ranking = Random_Generator(rankings, ¬_assigned);
args[i].count = N - 3;
pthread_create(&threads[i], 0, Thread, (void*)&args[i]);
}
srand(time(0));
while(1){
int sleep_time = rand() % 4 +2;
sleep(sleep_time);
not_assignedT = N;
for(i = 0; i < N; i++)
threads_rand[i] = i;
fprintf(stdout, "\\n------------>New elections<------------\\n");
best_ranking.ranking = 0; best_ranking.leader_id = 0;
for(i = 0; i < N -3; i++){
tid = Random_Generator(threads_rand, ¬_assignedT);
pthread_kill(threads[tid], SIGUSR1);
}
}
return 0;
}
void *Thread(void *args){
arg_t *arg = (arg_t*) args;
int ranking = (*arg).ranking;
int tid = (*arg).tid;
int count = (*arg).count;
int i;
signal(SIGUSR1, signal_handler);
while(1){
pause();
sem_wait(&barrier1);
pthread_mutex_lock(&best_ranking.lock);
if(ranking > best_ranking.ranking){
best_ranking.ranking = ranking;
best_ranking.leader_id = tid;
}
pthread_mutex_unlock(&best_ranking.lock);
pthread_mutex_lock(&c.lock);
c.nt++;
if(c.nt == count){
for(i = 0; i < count; i++)
sem_post(&barrier2);
}
pthread_mutex_unlock(&c.lock);
sem_wait(&barrier2);
fprintf(stdout, "Thread n. %d rank = %d. Leader thread = %d best_ranking = %d\\n", tid, ranking, best_ranking.leader_id, best_ranking.ranking);
pthread_mutex_lock(&c.lock);
c.nt--;
if(c.nt == 0){
for(i = 0; i < count; i++)
sem_post(&barrier1);
}
pthread_mutex_unlock(&c.lock);
}
}
| 1
|
#include <pthread.h>
{
int id;
char name[20];
int flag;
int money;
}Person;
Person per[20];
double money = 0.0;
int num = 0;
pthread_mutex_t lock;
void *producer(void* value)
{
double n = *(double*)value;
pthread_mutex_lock(&lock);
money = n;
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
void *consumer(void *n)
{
int nn = *(int*)n;
pthread_mutex_lock(&lock);
if(money > 0 && per[nn].flag == 0)
{
if(num > 1)
{
srand((unsigned)time(0));
double avg = money / num;
double t = avg*2;
double randmoney = (rand()%(int)(t*100) + (int)0.01*100)/100.00 + 0.01;
money-=randmoney;
printf("%s取走%.2lf元\\n",per[nn].name,randmoney);
printf("剩余%.2lf元\\n",money);
per[nn].id = nn;
per[nn].money = randmoney;
per[nn].flag = 1;
num--;
}
else
{
printf("%s取走%.2lf元\\n",per[nn].name,money);
printf("剩余0元\\n");
money = 0;
per[nn].id = nn;
per[nn].money = money;
per[nn].flag = 1;
num--;
}
}
pthread_mutex_unlock(&lock);
pthread_cancel(pthread_self());
}
int main()
{
char *name[] = {"zy","tom","alice","tony","sam","fred","amy","zyu","ll","yl","eh","dh","tjm","lk","sx","jx","gl","yj","gc","efw"};
int i = 0;
double value = 0.0;
pthread_mutex_init(&lock,0);
while(1)
{
printf("请输入红包的金额:\\n");
scanf("%lf",&value);
printf("请输入红包个数:");
scanf("%d",&num);
if(value >= 0.01 && value <= 200)
{
break;
}
}
for(i = 0; i < 20; i++)
{
strcpy(per[i].name,name[i]);
per[i].flag = 0;
per[i].id = -1;
}
pthread_t th_a,th_b[20];
pthread_create(&th_a,0,producer,(void*)&value);
pthread_join(th_a,0);
int args[20];
for(i = 0; i < 20;i++)
{
args[i] = i;
if(per[i].flag == 0)
{
pthread_create(&th_b[i],0,consumer,(void*)&args[i]);
}
}
for(i = 0; i < 20; i++)
{
pthread_join(th_b[i],0);
}
pthread_mutex_destroy(&lock);
return 0;
}
| 0
|
#include <pthread.h>
int final_max = INT_MIN;
int final_min = 32767;
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int min;
int max;
} result_t;
int *arr;
struct timeval tval_before, tval_after, tval_result;
struct thread_args {
int arraySize;
int subSize;
int counter;
int *arr;
int offset;
};
void *thread_args(void *);
result_t find_min_and_max(int *subarray, int n) {
result_t ret;
ret.min = 32767;
ret.max = INT_MIN;
for (int i=0; i<n; i++) {
if (subarray[i] < ret.min) ret.min = subarray[i];
if (subarray[i] > ret.max) ret.max = subarray[i];
}
return ret;
}
void *threaded_task(void *argp){
struct thread_args *arg = argp;
int n = arg->arraySize;
int *arr = arg->arr;
int size = arg->subSize;
int i = arg->counter;
int offset = arg->offset;
result_t r = find_min_and_max(arr + (size*i), n + offset);
pthread_mutex_lock(&mutex1);
if (final_min < r.min) final_min = r.min;
if (final_max > r.max) final_max = r.max;
pthread_mutex_unlock(&mutex1);
pthread_exit(0);
}
int main(int argc, char** argv) {
if (argc < 4) {
printf("Usage: %s <seed> <array_size> <nprocs>\\n",argv[0]);
return 1;
}
int seed = atoi(argv[1]);
int n = atoi(argv[2]);
int nprocs = atoi(argv[3]);
int size = n/nprocs;
int offset = 0;
int rc;
pthread_t thread[nprocs];
arr = (int *)malloc(n * sizeof(int));
srand(seed);
for (int a=0; a<n; a++) {
arr[a] = rand();
}
gettimeofday(&tval_before, 0);
for (int i = 0; i < nprocs; i++) {
struct thread_args *args = malloc(sizeof *args);
args->arraySize = n;
args->arr = arr;
args->subSize = size;
args->counter = i;
args->offset = offset;
rc = pthread_create(&thread[i], 0, threaded_task, args);
if (rc) {
printf("Thread Error \\n");
exit(-1);
}
}
gettimeofday(&tval_after, 0);
printf("min = %d, max = %d\\n", final_min, final_max);
timersub(&tval_after, &tval_before, &tval_result);
printf("Time elapsed: %ld.%06ld\\n", (long int)tval_result.tv_sec, (long int)tval_result.tv_usec);
return 0;
}
| 1
|
#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(ARG_MAX);
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;
}
| 0
|
#include <pthread.h>
int add=0;
int gReaders = 0;
int gWaitingReaders = 0;
pthread_mutex_t mutex= PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t rCond = PTHREAD_COND_INITIALIZER;
pthread_cond_t wCond = PTHREAD_COND_INITIALIZER;
void *readerFunc (void *args);
void *writerFunc (void *args);
int main(int argc,char *argv){
int i;
int readerData[5];
int writerData[5];
pthread_t readerThreads[5];
pthread_t writerThreads[5];
for (i = 0; i < 5; i++) {
readerData[i] = i;
pthread_create(&readerThreads[i],0, readerFunc, &readerData[i]);
}
for (i = 0; i < 5; i++) {
writerData[i] = i;
pthread_create(&writerThreads[i], 0, writerFunc, &writerData[i]);
}
for(i = 0; i < 5; i++) {
pthread_join(readerThreads[i], 0);
}
for(i = 0; i < 5; i++) {
pthread_join(writerThreads[i], 0);
}
return 0;
}
void *readerFunc (void *args){
int i = 0;
int *data = args;
for (i = 0; i < 2; i++) {
pthread_mutex_lock(&mutex);
++gWaitingReaders;
while (gReaders == -1) {
pthread_cond_wait (&rCond,&mutex);
}
++gReaders;
--gWaitingReaders;
pthread_mutex_unlock(&mutex);
printf("(R) Data in thread: %d \\n", *data);
printf("Number of readers present: %d \\n", gReaders);
pthread_mutex_lock(&mutex);
--gReaders;
if (gWaitingReaders == 0) {
pthread_cond_signal(&wCond);
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void *writerFunc (void *args) {
int i = 0;
int *data = args;
for (i = 0; i < 2; i++) {
pthread_mutex_lock(&mutex);
while (gReaders != 0) {
pthread_cond_wait (&wCond,&mutex);
}
gReaders = -1;
pthread_mutex_unlock(&mutex);
printf("(W) Data in thread: %d \\n", *data);
printf("Number of readers present: %d \\n", gReaders);
pthread_mutex_lock(&mutex);
gReaders = 0;
if (gWaitingReaders)
pthread_cond_broadcast(&rCond);
else
pthread_cond_signal(&wCond);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int buffer[100];
int in = -1;
int out = -1;
int count = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t BUFFER_HAS_SPACE = PTHREAD_COND_INITIALIZER;
pthread_cond_t BUFFER_HAS_DATA = PTHREAD_COND_INITIALIZER;
void *Producer(void* arg)
{
int i;
for(i=0;i<100;i++)
{
sleep(1);
pthread_mutex_lock(&mutex);
if(count==100)
{
pthread_cond_wait(&BUFFER_HAS_SPACE,&mutex);
}
in++;
in%=100;
buffer[in]=i;
count++;
printf("Produce : %d \\n",i);
pthread_cond_signal(&BUFFER_HAS_DATA);
pthread_mutex_unlock(&mutex);
}
}
void *Consumer(void* arg)
{
int data;
int i;
for(i=0;i<100;i++)
{
sleep(1);
pthread_mutex_lock(&mutex);
if(count==0)
{
pthread_cond_wait(&BUFFER_HAS_DATA,&mutex);
}
out++;
out %=100;
data = buffer[out];
count --;
printf("Consume : %d\\n",data);
pthread_cond_signal(&BUFFER_HAS_SPACE);
pthread_mutex_unlock(&mutex);
}
}
int main()
{
int i;
for(i=0;i<100;i++){
buffer[i]= -1;
}
pthread_t threads[2];
pthread_create(&threads[0],0,Producer,0);
pthread_create(&threads[1],0,Consumer,0);
pthread_join(threads[0],0);
pthread_join(threads[1],0);
pthread_cond_destroy(&BUFFER_HAS_SPACE);
pthread_cond_destroy(&BUFFER_HAS_DATA);
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
int count = 0;
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *add(void *t)
{
int i;
long my_id = (long)t;
for (i=0; i < 100; i++) {
pthread_mutex_lock(&count_mutex);
count++;
pthread_cond_signal(&count_threshold_cv);
printf("add(): thread %ld, count = %d\\n",my_id, count);
pthread_mutex_unlock(&count_mutex);
}
pthread_exit(0);
}
void *watch_add(void *t)
{
long my_id = (long)t;
printf("Starting watch_add(): thread %ld\\n", my_id);
pthread_mutex_lock(&count_mutex);
while (count<2*100) {
pthread_cond_wait(&count_threshold_cv, &count_mutex);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int i,rc;
long t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, add, (void *)t1);
pthread_create(&threads[1], &attr, add, (void *)t2);
pthread_create(&threads[2], &attr, watch_add, (void *)t3);
for (i = 0; i < 3; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited and joined with %d threads. Value of count = %d. Done.\\n",
3, count);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit (0);
}
| 1
|
#include <pthread.h>
struct prodcons {
int buffer[16];
pthread_mutex_t lock;
int readpos, writepos;
pthread_cond_t notempty;
pthread_cond_t notfull;
};
void init(struct prodcons * b)
{
pthread_mutex_init(&b->lock, 0);
pthread_cond_init(&b->notempty, 0);
pthread_cond_init(&b->notfull, 0);
b->readpos = 0;
b->writepos = 0;
}
void put(struct prodcons * b, int data)
{
pthread_mutex_lock(&b->lock);
while ((b->writepos + 1) % 16 == b->readpos) {
pthread_cond_wait(&b->notfull, &b->lock);
}
b->buffer[b->writepos] = data;
b->writepos++;
if (b->writepos >= 16) b->writepos = 0;
pthread_cond_signal(&b->notempty);
pthread_mutex_unlock(&b->lock);
}
int get(struct prodcons * b)
{
int data;
pthread_mutex_lock(&b->lock);
while (b->writepos == b->readpos) {
pthread_cond_wait(&b->notempty, &b->lock);
}
data = b->buffer[b->readpos];
b->readpos++;
if (b->readpos >= 16) b->readpos = 0;
pthread_cond_signal(&b->notfull);
pthread_mutex_unlock(&b->lock);
return data;
}
struct prodcons buffer;
void * producer(void * data)
{
int n;
for (n = 0; n < 10000; n++) {
printf("%d --->\\n", n);
put(&buffer, n);
}
put(&buffer, (-1));
return 0;
}
void * consumer(void * data)
{
int d;
while (1) {
d = get(&buffer);
if (d == (-1)) break;
printf("---> %d\\n", d);
}
return 0;
}
int main()
{
pthread_t th_a, th_b;
void * retval;
init(&buffer);
pthread_create(&th_a, 0, producer, 0);
pthread_create(&th_b, 0, consumer, 0);
pthread_join(th_a, &retval);
pthread_join(th_b, &retval);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
long double pi = 0;
void *piCalculator(void *param);
void *piPrinter(void *param);
int maxIterations;
int maxExecTime;
clock_t start, end;
int iteration = 0;
int main(int argc, char* argv[])
{
pthread_t worker_thread, printer_thread;
if(argc != 3) {
printf("Usage: %s <max iterations> <max execution time>\\n", argv[0]);
return 0;
}
maxIterations = atoi(argv[1]);
maxExecTime = atoi(argv[2]) - 1;
start = clock();
pthread_create( &worker_thread, 0, piCalculator, 0);
pthread_create( &printer_thread, 0, piPrinter, 0);
pthread_join(worker_thread, 0);
pthread_mutex_destroy( &mutex );
end = clock();
printf("\\nexecution time = %.2fs\\n", (((double)end)-((double)start))/CLOCKS_PER_SEC);
printf("iterations = %d\\n", iteration);
printf("pi = %1.60Lf\\n", 4*pi);
return 0;
}
void *piPrinter(void *param)
{
while(1) {
printf("Iteration (%10d): %1.60Lf\\n", iteration, 4*pi);
sleep(1);
}
}
void *piCalculator(void *param)
{
while(iteration < maxIterations)
{
if( ((clock()-start)/CLOCKS_PER_SEC) > maxExecTime ) {
printf("Time limit reached!\\n");
pthread_exit(0);
}
pthread_mutex_lock( &mutex );
pi = pi + ( pow(-1, iteration)/(2*iteration+1) );
pthread_mutex_unlock( &mutex );
iteration++;
}
printf("Reached iteration limit!\\n");
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int pbs_orderjob_err(
int c,
char *job1,
char *job2,
char *extend,
int *local_errno)
{
struct batch_reply *reply;
int rc;
int sock;
struct tcp_chan *chan = 0;
if ((job1 == (char *)0) || (*job1 == '\\0') ||
(job2 == (char *)0) || (*job2 == '\\0'))
return (PBSE_IVALREQ);
pthread_mutex_lock(connection[c].ch_mutex);
sock = connection[c].ch_socket;
if ((chan = DIS_tcp_setup(sock)) == 0)
{
pthread_mutex_unlock(connection[c].ch_mutex);
rc = PBSE_PROTOCOL;
return rc;
}
else if ((rc = encode_DIS_ReqHdr(chan, PBS_BATCH_OrderJob, pbs_current_user))
|| (rc = encode_DIS_MoveJob(chan, job1, job2))
|| (rc = encode_DIS_ReqExtend(chan, extend)))
{
connection[c].ch_errtxt = strdup(dis_emsg[rc]);
pthread_mutex_unlock(connection[c].ch_mutex);
DIS_tcp_cleanup(chan);
return (PBSE_PROTOCOL);
}
if (DIS_tcp_wflush(chan))
{
pthread_mutex_unlock(connection[c].ch_mutex);
DIS_tcp_cleanup(chan);
return (PBSE_PROTOCOL);
}
reply = PBSD_rdrpy(local_errno, c);
PBSD_FreeReply(reply);
rc = connection[c].ch_errno;
pthread_mutex_unlock(connection[c].ch_mutex);
DIS_tcp_cleanup(chan);
return(rc);
}
int pbs_orderjob(
int c,
char *job1,
char *job2,
char *extend)
{
pbs_errno = 0;
return(pbs_orderjob_err(c, job1, job2, extend, &pbs_errno));
}
| 0
|
#include <pthread.h>
unsigned int v_in, v_out;
static pthread_cond_t cond_lance, cond_resultat;
static pthread_mutex_t mutex;
void *thread_entree_sortie(void *p)
{
pthread_mutex_lock(&mutex);
printf("Entrez une valeur : ");
scanf("%d", &v_in);
pthread_cond_signal(&cond_lance);
pthread_cond_wait(&cond_resultat,&mutex);
printf("Le resultat du calcul est : %d\\n", v_out);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void *thread_calcul(void *p)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond_lance,&mutex);
printf("On lance le calcul pour %d\\n", v_in);
v_out = v_in*v_in;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond_resultat);
pthread_exit(0);
}
int main (int argc, char *argv[])
{
pthread_t threads[2];
int i,
rc;
void *ret;
pthread_cond_init(&cond_lance, 0);
pthread_cond_init(&cond_resultat, 0);
pthread_mutex_init(&mutex, 0);
rc = pthread_create(&threads[0], 0, thread_calcul, 0);
if (rc){
printf("Erreur creation thread : %d\\n", rc);
exit(2);
}
rc = pthread_create(&threads[1], 0, thread_entree_sortie, 0);
if (rc){
printf("Erreur creation thread : %d\\n", rc);
exit(2);
}
for (i = 0; i < 2; ++i) {
(void)pthread_join (threads[i], &ret);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int sum = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void * sumDirectory(void *arg){
struct stat statbuf;
DIR *dp;
struct dirent *direntry;
pthread_t* childs = malloc(256 * sizeof(pthread_t));
int index_childs = -1;
int tempsum = 0;
dp = opendir((char*) arg);
while((direntry = readdir(dp)) != 0) {
char fullName [256];
sprintf(fullName, "%s/%s", (char*) arg, direntry->d_name);
stat(fullName,&statbuf);
if (!(S_ISDIR(statbuf.st_mode))) {
pthread_mutex_lock(&lock);
int fs = (int) statbuf.st_size;
tempsum += fs;
sum += fs;
pthread_mutex_unlock(&lock);
} else {
if (strcmp(direntry->d_name, ".") == 0 || strcmp(direntry->d_name, "..") == 0){
continue;
}
char* subdir = malloc(256 * sizeof(char));
sprintf(subdir, "%s/%s", (char*) arg, direntry->d_name);
pthread_t child_thread;
int n;
if (n = pthread_create(&child_thread, 0, sumDirectory, (void *) subdir)) {
fprintf(stderr, "pthread_create :%s\\n",strerror(n));
exit(1);
}
index_childs++;
childs[index_childs] = child_thread;
}
}
int m;
for (int i = 0; i<=index_childs;i++){
void *subdir_size;
if (m = pthread_join(childs[i], &subdir_size)){
fprintf(stderr, "pthread_join: %s\\n", strerror(m));
exit(1);
}
tempsum += (int)subdir_size;
}
free(childs);
printf("\\n%s: %d\\n", (char*) arg, tempsum);
return (void *)tempsum;
}
int main(int argc, char* argv[]){
char* input_dir_name;
input_dir_name = (char *) malloc(256 * sizeof(char));
printf("ENTER A RELATIVE PATH: \\n");
scanf("%s", input_dir_name);
char actualpath [PATH_MAX];
char *ptr;
ptr = realpath(input_dir_name, actualpath);
pthread_t main_thread;
int n;
if (n = pthread_create(&main_thread, 0, sumDirectory, (void *) actualpath)){
fprintf(stderr,"pthread_create :%s\\n",strerror(n));
exit(1);
}
if (n = pthread_join(main_thread, 0)){
fprintf(stderr, "pthread_join: %s\\n", strerror(n));
exit(1);
}
printf("the total size is: %d\\n", sum);
}
| 0
|
#include <pthread.h>
int balance;
int withdrawn;
pthread_mutex_t lock;
} ACCOUNT, *PACCOUNT;
PACCOUNT acc;
PACCOUNT create(int b) {
PACCOUNT acc = (PACCOUNT) malloc(sizeof(ACCOUNT));
acc->balance = b;
acc->withdrawn = 0;
pthread_mutex_init(&acc->lock, 0);
return acc;
}
int read() {
return acc->balance;
}
void *deposit(void *arg) {
int *n = (int*)arg;
pthread_mutex_lock(&acc->lock);
acc->balance = acc->balance + *n;
pthread_mutex_unlock(&acc->lock);
return 0;
}
void *withdraw(void *arg) {
int *n = (int*)arg;
int r;
r = read();
if (r >= *n) {
pthread_mutex_lock(&acc->lock);
acc->balance = r - *n;
pthread_mutex_unlock(&acc->lock);
acc->withdrawn = 1;
return 0;
}
acc->withdrawn = 0;
return 0;
}
int main(void) {
pthread_t tid1, tid2;
int x, y, z;
x = __VERIFIER_nondet_int();
y = __VERIFIER_nondet_int();
z = __VERIFIER_nondet_int();
acc = create(x);
pthread_create(&tid1, 0, deposit, &y);
pthread_create(&tid2, 0, withdraw, &z);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
assert(!acc->withdrawn || read() == x + y - z);
return 0;
}
| 1
|
#include <pthread.h>
void* f_jdg (void *v);
void enter_judge();
void confirm_judge();
void leave_judge();
void* f_jdg (void *v){
enter_judge();
confirm_judge();
leave_judge();
return 0;
}
void enter_judge(){
atomic_exchange(&judge_inside, 1);
printf("Judge entered.\\n");
sleep(2);
}
void confirm_judge(){
pthread_mutex_lock (&attentand);
while (entered_immi != checkin)
pthread_cond_wait (&all_check_in, &attentand);
pthread_mutex_lock (&attentand);
atomic_exchange(&judge_confirmed, 1);
printf("Judge has confirmed.\\n");
futex_wake(&judge_confirmed, checkin);
sleep(2);
pthread_mutex_unlock (&attentand);
}
void leave_judge(){
pthread_mutex_lock (&door);
while (checkin != 0)
pthread_cond_wait (&judge_can_leave, &door);
pthread_mutex_lock (&door);
judge_inside = 0;
judge_confirmed = 0;
printf("Judge has left.\\n");
futex_wake(&judge_inside, entered_immi + entered_spec);
entered_immi = 0;
pthread_mutex_unlock (&door);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condizione = PTHREAD_COND_INITIALIZER;
int n;
int i =0;
int flag=0;
void *scrittore(void *param){
char *buf = malloc(sizeof(int));
int fd = open("file.txt",O_WRONLY);
for(i=1;i<=n;i++){
pthread_mutex_lock(&mutex);
sprintf(buf, "%d", i);
write(fd,buf,sizeof(int));
pthread_mutex_unlock(&mutex);
usleep(500);
}
pthread_exit(0);
}
void *lettore(void *param){
char *buf = malloc(sizeof(int));
int fd = open("file.txt",O_RDONLY);
int byteRead=0;
do{
pthread_mutex_lock(&mutex);
byteRead=read(fd,buf,sizeof(int));
pthread_mutex_unlock(&mutex);
usleep(500);
printf("%s\\n",buf );
}while(byteRead>0);
flag=1;
pthread_mutex_lock(&mutex);
pthread_cond_signal(&condizione);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void *funzione(void *param){
pthread_mutex_lock(&mutex);
while(flag==0){
pthread_cond_wait(&condizione,&mutex);
}
pthread_mutex_unlock(&mutex);
sleep(3);
printf("FIINE\\n");
pthread_exit(0);
}
int main(int argc, char const *argv[])
{
pthread_t thread[3];
if (argc<2)
{
perror("Errore parametri");
}
n= atoi(argv[1]);
unlink("file.txt");
int fd = open("file.txt",O_CREAT,S_IRWXU|S_IRWXG,S_IRWXO);
close(fd);
pthread_create(&thread[0],0,scrittore,0);
pthread_create(&thread[1],0,lettore,0);
pthread_create(&thread[2],0,funzione,0);
for (int i = 0; i < 3; i++)
{
pthread_join(thread[i],0);
}
return 0;
}
| 1
|
#include <pthread.h>
void *thread_function(void *arg);
pthread_mutex_t work_mutex;
char work_area[1024];
int time_to_exit = 0;
int main()
{
int res;
pthread_t a_thread;
void *thread_result;
res = pthread_mutex_init(&work_mutex, 0);
if(res != 0)
{
perror("Initialization failed");
exit(1);
}
res = pthread_create(&a_thread, 0, thread_function, 0);
if(res != 0)
{
perror("Thread failed failed");
exit(1);
}
pthread_mutex_lock(&work_mutex);
printf("Input some text, enter 'end' to finish...\\n");
while(!time_to_exit)
{
fgets(work_area, 1024, stdin);
pthread_mutex_unlock(&work_mutex);
while(1)
{
pthread_mutex_lock(&work_mutex);
if(work_area[0] != '\\0')
{
pthread_mutex_unlock(&work_mutex);
sleep(1);
}
else
{
break;
}
}
}
pthread_mutex_unlock(&work_mutex);
printf("\\nWaiting for thread to finish...\\n");
res = pthread_join(a_thread, &thread_result);
if(res != 0)
{
perror("Thread joined failed");
exit(1);
}
printf("Thread joined, %s\\n", (char *)thread_result);
pthread_mutex_destroy(&work_mutex);
exit(0);
}
void *thread_function(void *arg)
{
sleep(1);
pthread_mutex_lock(&work_mutex);
while(strncmp("end", work_area, 3) != 0)
{
printf("You input %d characters\\n", strlen(work_area)-1);
work_area[0] = '\\0';
pthread_mutex_unlock(&work_mutex);
sleep(1);
pthread_mutex_lock(&work_mutex);
if(work_area[0] == '\\0')
{
pthread_mutex_unlock(&work_mutex);
sleep(1);
pthread_mutex_lock(&work_mutex);
}
}
time_to_exit = 1;
work_area[0] = '\\0';
pthread_mutex_unlock(&work_mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
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(ARG_MAX);
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);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t pc_mutex = PTHREAD_MUTEX_INITIALIZER;
static struct iface_stats *sample_buf;
static struct iface_stats *produce_ptr;
static struct iface_stats *consume_ptr;
void raw_sample_buf_init()
{
sample_buf = malloc((3 * sizeof(struct iface_stats)));
assert(sample_buf);
produce_ptr = sample_buf;
consume_ptr = sample_buf;
}
struct iface_stats *raw_sample_buf_produce_next()
{
pthread_mutex_lock(&pc_mutex);
produce_ptr++;
if ((uint8_t *)produce_ptr == ((uint8_t *)sample_buf + (3 * sizeof(struct iface_stats)))) {
produce_ptr = sample_buf;
}
assert(produce_ptr != consume_ptr);
pthread_mutex_unlock(&pc_mutex);
assert((uint8_t *)produce_ptr < ((uint8_t *)sample_buf + (3 * sizeof(struct iface_stats))));
return produce_ptr;
}
struct iface_stats *raw_sample_buf_consume_next()
{
pthread_mutex_lock(&pc_mutex);
consume_ptr++;
if ((uint8_t *)consume_ptr == ((uint8_t *)sample_buf + (3 * sizeof(struct iface_stats)))) {
consume_ptr = sample_buf;
}
assert(consume_ptr != produce_ptr);
pthread_mutex_unlock(&pc_mutex);
return consume_ptr;
}
| 0
|
#include <pthread.h>
int DownLoadHttp(struct arg *s_info)
{
char get[256];
char buf[1024]="";
char headhost[256];
char range[32];
int connected =0;
int i,j,starttext,boolprint=0;
int sock,nextthread=0,boolbyte=0;
unsigned long timeuse;
int readen,bytesget=0;
int inflen,index=0,offset=0;
int bytesleft=(s_info->a2)-(s_info->a1)+1;
struct timeval tv;
if(s_info->booldown==1&&s_info->allowotherdown==1)return 0;
if(s_info->threadnumber!=0){
while(g[(s_info->threadnumber)-1].booldown==0){
sleep(1);
}
}
while(1){
if((sock=ConnectHttp(host,port))<=0)sleep(1);
else{
connected=1;
break;
}
}
if(connected){
sprintf(get,"GET %s HTTP/1.1\\r\\nRange: bytes=%d-\\r\\nHost: %s:%d\\r\\n\\r\\n",path,s_info->a1,host,port);
if(send(sock,get,strlen(get),0)!=strlen(get)){
close(sock);
sleep(5);
DownLoadHttp(s_info);
return 0;
}
s_info->fd=open(filename,O_WRONLY|O_CREAT,0644);
lseek(s_info->fd,s_info->a1,0);
pthread_mutex_lock(&lock);
s_info->booldown=1;
pthread_mutex_unlock(&lock);
ClearBuf(buf);
while(bytesleft>0){
readen =ReadEn(sock,30);
if(readen<1){
close(sock);
close(s_info->fd);
sleep(2);
pthread_mutex_lock(&lock);
s_info->booldown=0;
s_info->allowotherdown=0;
pthread_mutex_unlock(&lock);
DownLoadHttp(s_info);
return 0;
}
boolprint++;
if(boolprint==10)boolprint=0;
if(bytesleft>=1024&&offset==0){
bytesget=recv(sock,buf,1024,MSG_WAITALL);
starttext=GetStartText(buf,bytesget);
write(s_info->fd,buf+starttext,1024-starttext);
bytesleft+=starttext-bytesget;
sizeget+=bytesget-starttext;
s_info->a1+=bytesget-starttext;
offset+=bytesget-starttext;
ClearBuf(buf);
continue;
}
else if(bytesleft>=1024){
bytesget=recv(sock,buf,1024,0);
if(bytesget==0)boolbyte++;
if(bytesget<0||(bytesget==0&&boolbyte>=10)){
close(sock);
close(s_info->fd);
pthread_mutex_lock(&lock);
s_info->booldown=0;
s_info->allowotherdown=0;
pthread_mutex_unlock(&lock);
DownLoadHttp(s_info);
return 0;
}
write(s_info->fd,buf,bytesget);
offset+=bytesget;
sizeget+=bytesget;
s_info->a1+=bytesget;
bytesleft-=bytesget;
ClearBuf(buf);
}
else{
if(offset==0){
bytesget=recv(sock,buf,2048,MSG_WAITALL);
starttext=GetStartText(buf,bytesget);
if(bytesleft!=bytesget-starttext){
close(sock);
close(s_info->fd);
sleep(2);
pthread_mutex_lock(&lock);
s_info->booldown=0;
s_info->allowotherdown=0;
pthread_mutex_unlock(&lock);
DownLoadHttp(s_info);
return 0;
}
write(s_info->fd,buf+starttext,strlen(buf)-starttext);
offset+=bytesget-starttext;
sizeget+=bytesget-starttext;
s_info->a1+=bytesget;
bytesleft-=bytesget-starttext;
}
else{
bytesget=recv(sock,buf,bytesleft,0);
if(bytesget==0)boolbyte++;
if(bytesget<0||(bytesget==0&&boolbyte>=10)){
close(sock);
close(s_info->fd);
pthread_mutex_lock(&lock);
s_info->booldown=0;
s_info->allowotherdown=0;
pthread_mutex_unlock(&lock);
DownLoadHttp(s_info);
return 0;
}
write(s_info->fd,buf,bytesget);
offset+=bytesget;
sizeget+=bytesget;
s_info->a1+=bytesget;
bytesleft-=bytesget;
if(bytesleft<=1024){
nextthread++;
}
}
ClearBuf(buf);
}
if(boolprint==0){
pthread_mutex_lock(&lock);
SaveThreadStat();
pthread_mutex_unlock(&lock);
gettimeofday(&tpend,0);
timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;
timeuse/=1000000;
printprocess(sizeget, filelength, timeuse);
}
}
close(sock);
return 0;
}
else return -1;
}
int GetHttpData()
{
char head[256];
char headhost[256];
char dataget[512];
int threadsize=0;
int i_sock,i;
pthread_t thrd[30];
float timeuse;
threadsize = GetThreadSize();
gettimeofday(&tpstart,0);
for(i=0;i<=(nthread)-1;i++){
if(getfromfile==0){
pthread_mutex_lock(&lock);
g[i].booldown=0;
pthread_mutex_unlock(&lock);
g[i].threadnumber=i;
g[i].a1=threadsize*i;
g[i].a2=g[i].a1+threadsize-1;
if(i==(nthread-1))g[i].a2=filelength-1;
g[i].bytesleft=g[i].a2-g[i].a1+1;
}
else{
if(g[i].boolend==1)g[i].booldown=1;
else g[i].booldown=0;
}
pthread_create(&thrd[i],0,(void*)DownLoadHttp,(void*)&g[i]);
}
for(i=0;i<=(nthread)-1;i++)
pthread_join(thrd[i],0);
return 0;
}
| 1
|
#include <pthread.h>
int **matrix;
pthread_t tid[3];
struct stack_record {
int value;
pthread_t id;
};
struct stack_record *stack;
int stack_iterator;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t var_cond = PTHREAD_COND_INITIALIZER;
sem_t *sem_with_name;
int n;
void *producer(void *args);
void *consumer(void *args);
int main(int args, char *argv[]) {
int i,j;
pthread_t ltid;
n = atoi(argv[1]);
sem_with_name = sem_open("sem_with_name",O_CREAT,0644,1);
if(sem_with_name == (void *)-1 ) {
printf("An error occured while creating semaphore\\n");
exit(0);
}
if((matrix = malloc(sizeof(int*)*n)) == (void *)-1) {
printf("An error occured while allocating matrix\\n");
exit(0);
}
if((stack = malloc(sizeof(struct stack_record)*n*n)) == (void *)-1) {
printf("An error occured while allocating stack\\n");
exit(0);
}
printf("Matrix:\\n");
for(i=0;i<n;i++) {
if((matrix[i] = malloc(sizeof(int)*n)) == (void *)-1) {
printf("An error occured while allocating matrix\\n");
exit(0);
}
for(j=0;j<n;j++) {
matrix[i][j] = rand()%10;
printf("%d ",matrix[i][j]);
}
printf("\\n");
}
pthread_create(<id,0,consumer,0);
for(i=0;i<3;i++) {
pthread_create(&tid[i],0,producer,0);
}
for(i=0;i<3;i++) {
pthread_join(tid[i],0);
}
pthread_join(ltid,0);
exit(0);
}
void *producer(void *args) {
int i,j;
struct timespec req;
req.tv_nsec=5000;
for( ; ; ) {
i = rand()%n;
j = rand()%n;
nanosleep(&req, 0);
sem_wait(sem_with_name);
if(stack_iterator == n*n) {
pthread_cond_signal(&var_cond);
sem_post(sem_with_name);
break;
}
else {
stack_iterator++;
stack[stack_iterator].value = matrix[i][j];
stack[stack_iterator].id = pthread_self();
}
sem_post(sem_with_name);
}
sem_destroy(sem_with_name);
pthread_exit(0);
}
void *consumer(void *args) {
int i,a,b,c;
a = 0;
b = 0;
c = 0;
int best_producer;
pthread_mutex_lock(&mutex);
if(stack_iterator < n*n)
pthread_cond_wait(&var_cond,&mutex);
pthread_mutex_unlock(&mutex);
for(i=0;i<n*n;i++) {
printf("thread: %d value: %d\\n",(int)stack[i].id, stack[i].value);
if(pthread_equal(stack[i].id,tid[0])) a++;
if(pthread_equal(stack[i].id,tid[1])) b++;
if(pthread_equal(stack[i].id,tid[2])) c++;
}
if(a > b) {
best_producer = (int)tid[0];
if(c > a) best_producer = (int)tid[2];
}
else {
best_producer = (int)tid[1];
if(c > b) best_producer = (int)tid[2];
}
printf("best_producer: %d", best_producer);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
char* key;
char* value;
size_t value_len;
struct hash_item** pprev;
struct hash_item* next;
} hash_item;
hash_item* hash[1024];
pthread_mutex_t hash_mutex[1024];
hash_item* hash_get(const char* key, int create) {
unsigned b = string_hash(key) % 1024;
hash_item* h = hash[b];
while (h != 0 && strcmp(h->key, key) != 0) {
h = h->next;
}
if (h == 0 && create) {
h = (hash_item*) malloc(sizeof(hash_item));
h->key = strdup(key);
h->value = 0;
h->value_len = 0;
h->pprev = &hash[b];
h->next = hash[b];
hash[b] = h;
if (h->next != 0) {
h->next->pprev = &h->next;
}
}
return h;
}
void* connection_thread(void* arg) {
int cfd = (int) (uintptr_t) arg;
FILE* fin = fdopen(cfd, "r");
FILE* f = fdopen(cfd, "w");
pthread_detach(pthread_self());
char buf[1024], key[1024], key2[1024];
size_t sz;
while (fgets(buf, 1024, fin)) {
if (sscanf(buf, "get %s ", key) == 1) {
unsigned b = string_hash(key);
pthread_mutex_lock(&hash_mutex[b]);
hash_item* h = hash_get(key, 0);
if (h != 0) {
fprintf(f, "VALUE %s %zu %p\\r\\n",
key, h->value_len, h);
fwrite(h->value, 1, h->value_len, f);
fprintf(f, "\\r\\n");
}
fprintf(f, "END\\r\\n");
fflush(f);
pthread_mutex_unlock(&hash_mutex[b]);
} else if (sscanf(buf, "set %s %zu ", key, &sz) == 2) {
unsigned b = string_hash(key);
pthread_mutex_lock(&hash_mutex[b]);
hash_item* h = hash_get(key, 1);
free(h->value);
h->value = (char*) malloc(sz);
h->value_len = sz;
fread(h->value, 1, sz, fin);
fprintf(f, "STORED %p\\r\\n", h);
fflush(f);
pthread_mutex_unlock(&hash_mutex[b]);
} else if (sscanf(buf, "delete %s ", key) == 1) {
unsigned b = string_hash(key);
pthread_mutex_lock(&hash_mutex[b]);
hash_item* h = hash_get(key, 0);
if (h != 0) {
free(h->key);
free(h->value);
*h->pprev = h->next;
if (h->next) {
h->next->pprev = h->pprev;
}
free(h);
fprintf(f, "DELETED %p\\r\\n", h);
} else {
fprintf(f, "NOT_FOUND\\r\\n");
}
fflush(f);
pthread_mutex_unlock(&hash_mutex[b]);
} else if (sscanf(buf, "exch %s %s ", key, key2) == 2) {
unsigned b = string_hash(key);
unsigned b2 = string_hash(key2);
pthread_mutex_lock(&hash_mutex[b]);
pthread_mutex_lock(&hash_mutex[b2]);
hash_item* h = hash_get(key, 0);
hash_item* h2 = hash_get(key2, 0);
if (h != 0 && h2 != 0) {
char* tmp = h->value;
h->value = h2->value;
h2->value = tmp;
size_t tmpsz = h->value_len;
h->value_len = h2->value_len;
h2->value_len = tmpsz;
fprintf(f, "EXCHANGED %p %p\\r\\n", h, h2);
} else {
fprintf(f, "NOT_FOUND\\r\\n");
}
fflush(f);
pthread_mutex_unlock(&hash_mutex[b]);
pthread_mutex_unlock(&hash_mutex[b2]);
} else if (remove_trailing_whitespace(buf)) {
fprintf(f, "ERROR\\r\\n");
fflush(f);
}
}
if (ferror(fin)) {
perror("read");
}
fclose(fin);
(void) fclose(f);
return 0;
}
int main(int argc, char** argv) {
for (int i = 0; i != 1024; ++i) {
pthread_mutex_init(&hash_mutex[i], 0);
}
int port = 6168;
if (argc >= 2) {
port = strtol(argv[1], 0, 0);
assert(port > 0 && port <= 65535);
}
int fd = open_listen_socket(port);
assert(fd >= 0);
while (1) {
int cfd = accept(fd, 0, 0);
if (cfd < 0) {
perror("accept");
exit(1);
}
pthread_t t;
int r = pthread_create(&t, 0, connection_thread,
(void*) (uintptr_t) cfd);
if (r != 0) {
perror("pthread_create");
exit(1);
}
}
}
| 1
|
#include <pthread.h>
enum PhilState { THINKING, HUNGRY, EATING };
pthread_t thread;
int id;
int prio;
int state;
struct philosopher_t *philLeft, *philRight;
} Philosopher;
pthread_cond_t forkLock = PTHREAD_COND_INITIALIZER;
pthread_mutex_t fmutex = PTHREAD_MUTEX_INITIALIZER;
Philosopher *phils;
int numPhils;
void setTheTable();
void invitePhilosophers();
void serveDinner();
void cleanDishes();
void killPhilosophers();
void * philDine(void *args);
void philThink(Philosopher *p);
void philHungry(Philosopher *p);
void philEat(Philosopher *p);
void philChangeState(Philosopher *p, int state);
void philPrintStates();
void philGrabForks(Philosopher *p);
int philCanEat(Philosopher *p);
void philReleaseForks(Philosopher *p);
int randomInt(int rangeMin, int rangeSize);
int count;
int main(int argc, char *argv[]) {
if(argc < 2) {
fprintf(stderr, "Usage: %s [numPhils]\\n", argv[0]);
exit(1);
}
numPhils = atoi(argv[1]);
count = 0;
setTheTable();
invitePhilosophers();
serveDinner();
cleanDishes();
killPhilosophers();
return 0;
}
void setTheTable() {
}
void invitePhilosophers() {
phils = malloc(sizeof(Philosopher) * numPhils);
for(int i = 0; i < numPhils; i++) {
Philosopher *p = &phils[i];
p->state = THINKING;
p->id = i;
p->prio = 0;
p->philLeft = &phils[(i+numPhils-1) % numPhils];
p->philRight = &phils[(i+1) % numPhils];
}
srand(time(0));
}
void cleanDishes() {
}
void killPhilosophers() {
free(phils);
}
void serveDinner() {
philPrintStates();
for(int i = 0; i < numPhils; i++) {
pthread_create(&phils[i].thread, 0, philDine, &phils[i]);
}
for(int i = 0; i < numPhils; i++) {
pthread_join(phils[i].thread, 0);
}
}
void *philDine(void *args) {
Philosopher *myself = (Philosopher *) args;
while(1) {
philThink(myself);
philHungry(myself);
philEat(myself);
}
return 0;
}
void philThink(Philosopher *p) {
int thinkingTime = randomInt(1, 10);
sleep(thinkingTime);
}
void philHungry(Philosopher *p) {
philGrabForks(p);
}
void philEat(Philosopher *p) {
int eatingTime = randomInt(1, 10);
sleep(eatingTime);
philReleaseForks(p);
}
void philChangeState(Philosopher *p, int state) {
static pthread_mutex_t smutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&smutex);
p->state = state;
p->prio = 0;
philPrintStates();
pthread_mutex_unlock(&smutex);
}
void philPrintStates() {
static const char stateToChar[] = { 'T', 'H', 'E' };
for(int i = 0; i < numPhils; i++) {
printf("%c ", stateToChar[phils[i].state]);
}
printf("\\n");
}
void philGrabForks(Philosopher *p) {
pthread_mutex_lock(&fmutex);
philChangeState(p, HUNGRY);
while(!philCanEat(p))
pthread_cond_wait(&forkLock, &fmutex);
philChangeState(p, EATING);
pthread_cond_signal(&forkLock);
pthread_mutex_unlock(&fmutex);
}
int philCanEat(Philosopher *p) {
int selfPrio = p->prio;
int leftState = p->philLeft->state;
int leftPrio = p->philLeft->prio;
int rightState = p->philRight->state;
int rightPrio = p->philRight->prio;
int canEat = leftState != EATING && rightState != EATING;
int shouldEat = (leftState == THINKING || (leftState == HUNGRY && selfPrio >= leftPrio)) &&
(rightState == THINKING || (rightState == HUNGRY && selfPrio >= rightPrio));
if(!canEat)
p->prio++;
if(!shouldEat)
pthread_cond_signal(&forkLock);
return canEat && shouldEat;
}
void philReleaseForks(Philosopher *p) {
pthread_mutex_lock(&fmutex);
philChangeState(p, THINKING);
pthread_mutex_unlock(&fmutex);
}
int randomInt(int rangeMin, int rangeSize) {
return rand() % rangeSize + rangeMin;
}
| 0
|
#include <pthread.h>
struct file
{
char* f_name;
char* f_host;
int f_fd;
int f_flags;
pthread_t f_tid;
} file[20];
int nconn;
int nfiles;
int nlefttoconn;
int nlefttoread;
void* do_get_read(void*);
void home_page(const char*,const char*);
void write_get_cmd(struct file*);
int min(int,int);
int ndone;
pthread_mutex_t ndone_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t ndone_cond = PTHREAD_COND_INITIALIZER;
int main(int argc,char* argv[])
{
int i;
int maxnconn;
pthread_t tid;
struct file* fptr;
if (argc < 5)
{
return -1;
}
maxnconn = atoi(argv[1]);
nfiles = min(argc - 4,20);
for (i = 0; i < nfiles; i++)
{
file[i].f_name = argv[i + 4];
file[i].f_host = argv[2];
file[i].f_flags = 0;
}
printf("nfiles = %d\\n",nfiles);
home_page(argv[2],argv[3]);
nlefttoread = nlefttoconn = nfiles;
nconn = 0;
while (nlefttoread > 0)
{
while (nconn < maxnconn && nlefttoconn > 0)
{
for (i = 0; i < nfiles; i++)
{
if (file[i].f_flags == 0)
{
break;
}
}
if (i == nfiles)
{
fprintf(stderr,"nlefttoconn = %d but nothing found\\n",nlefttoconn);
return -1;
}
file[i].f_flags = 1;
pthread_create(&tid,0,&do_get_read,&file[i]);
file[i].f_tid = tid;
nconn++;
nlefttoconn--;
}
pthread_mutex_lock(&ndone_mutex);
while (ndone == 0)
{
pthread_cond_wait(&ndone_cond,&ndone_mutex);
}
for (i = 0; i < nfiles; i++)
{
if (file[i].f_flags & 4)
{
pthread_join(file[i].f_tid,(void**)&fptr);
if (&file[i] != fptr)
{
fprintf(stderr,"file[i] != fptr\\n");
return -1;
}
fptr->f_flags = 8;
ndone--;
nconn--;
nlefttoread--;
printf("thread id %d for %s done\\n",(int)tid,fptr->f_name);
}
}
pthread_mutex_unlock(&ndone_mutex);
}
exit(0);
}
int min(int x,int y)
{
return x < y ? x : y;
}
void home_page(const char* host,const char* fname)
{
int fd;
int n;
char line[MAXLINE];
fd = tcp_connect(host,"80");
n = snprintf(line,sizeof(line),"GET %s/HTTP/1.0\\r\\n\\r\\n",fname);
writen(fd,line,n);
for (;;)
{
if ((n = read(fd,line,MAXLINE)) == 0)
break;
printf("read %d bytes of home page\\n",n);
}
printf("end-of-file on home page\\n");
close(fd);
}
void* do_get_read(void* vptr)
{
int fd;
int n;
char line[MAXLINE];
struct file* fptr;
fptr = (struct file*)vptr;
fd = tcp_connect(fptr->f_host,"80");
fptr->f_fd = fd;
printf("do_get_read for %s,fd %d,thread %d\\n",
fptr->f_name,fd,(int)(fptr->f_tid));
write_get_cmd(fptr);
for (;;)
{
if ((n = read(fd,line,MAXLINE)) == 0)
{
break;
}
printf("read %d bytes from %s\\n",n,fptr->f_name);
}
printf("end-of-file on %s\\n",fptr->f_name);
close(fd);
pthread_mutex_lock(&ndone_mutex);
fptr->f_flags = 4;
ndone++;
pthread_cond_signal(&ndone_cond);
pthread_mutex_unlock(&ndone_mutex);
return fptr;
}
void write_get_cmd(struct file* fptr)
{
int n;
char line[MAXLINE];
n = snprintf(line,sizeof(line),"GET %s/HTTP/1.0\\r\\n\\r\\n",fptr->f_name);
writen(fptr->f_fd,line,n);
printf("wrote %d bytes for %s \\n",n,fptr->f_name);
fptr->f_flags = 2;
}
| 1
|
#include <pthread.h>
int
gai_suspend (const struct gaicb *const list[], int ent,
const struct timespec *timeout)
{
struct waitlist waitlist[ent];
struct requestlist *requestlist[ent];
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int cnt;
int dummy;
int none = 1;
int result;
pthread_mutex_lock (&__gai_requests_mutex);
for (cnt = 0; cnt < ent; ++cnt)
if (list[cnt] != 0 && list[cnt]->__return == EAI_INPROGRESS)
{
requestlist[cnt] = __gai_find_request (list[cnt]);
if (requestlist[cnt] != 0)
{
waitlist[cnt].cond = &cond;
waitlist[cnt].next = requestlist[cnt]->waiting;
waitlist[cnt].counterp = &dummy;
waitlist[cnt].sigevp = 0;
waitlist[cnt].caller_pid = 0;
requestlist[cnt]->waiting = &waitlist[cnt];
none = 0;
}
}
if (none)
{
if (cnt < ent)
result = 0;
else
result = EAI_ALLDONE;
}
else
{
int oldstate;
pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &oldstate);
if (timeout == 0)
result = pthread_cond_wait (&cond, &__gai_requests_mutex);
else
{
struct timeval now;
struct timespec abstime;
__gettimeofday (&now, 0);
abstime.tv_nsec = timeout->tv_nsec + now.tv_usec * 1000;
abstime.tv_sec = timeout->tv_sec + now.tv_sec;
if (abstime.tv_nsec >= 1000000000)
{
abstime.tv_nsec -= 1000000000;
abstime.tv_sec += 1;
}
result = pthread_cond_timedwait (&cond, &__gai_requests_mutex,
&abstime);
}
for (cnt = 0; cnt < ent; ++cnt)
if (list[cnt] != 0 && list[cnt]->__return == EAI_INPROGRESS
&& requestlist[cnt] != 0)
{
struct waitlist **listp = &requestlist[cnt]->waiting;
while (*listp != 0 && *listp != &waitlist[cnt])
listp = &(*listp)->next;
if (*listp != 0)
*listp = (*listp)->next;
}
pthread_setcancelstate (oldstate, 0);
if (pthread_cond_destroy (&cond) != 0)
abort ();
if (result != 0)
{
if (__builtin_expect (result, ETIMEDOUT) == ETIMEDOUT)
result = EAI_AGAIN;
else if (result == EINTR)
result = EAI_INTR;
else
result = EAI_SYSTEM;
}
}
pthread_mutex_unlock (&__gai_requests_mutex);
return result;
}
| 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(&hashlock);
if (--fp->f-count==0) {
idx = (((unsigned long)fp)%29);
tfp = fh[idx];
if (tfp == fp) {
fh[idx] = fp->f_next;
} else {
while (tfp->f_next != fp)
tfp = tfp->f_next;
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
} else {
pthread_mutex_unlock(&hashlock);
}
}
void foo_release(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);
}
}
int main()
{
return 0;
}
| 1
|
#include <pthread.h>
double func(double x,double y, double z);
double integrate(double a, double b, double c, double d, double e, double f, int N, int M, int K);
void* proc(void *);
void* pthstat(void *);
double a, b, c, d, e, f, N, M, K;
unsigned pthnum;
double result = 0.0;
char *stat_list;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_t *threads;
pthread_t stat;
unsigned stat_flg;
int main(int argc, char* argv[])
{
if(argc == 1) {
puts("Usage: int3 [a] [b] [c] [d] [e] [f] [N] [M] [K] [pthreads number]");
return 0;
}
sscanf(argv[1], "%lf", &a);
sscanf(argv[2], "%lf", &b);
sscanf(argv[3], "%lf", &c);
sscanf(argv[4], "%lf", &d);
sscanf(argv[5], "%lf", &e);
sscanf(argv[6], "%lf", &f);
N = atoi(argv[7]);
M = atoi(argv[8]);
K = atoi(argv[9]);
stat_flg = pthnum = atoi(argv[10]);
time_t begtime, endtime, restime;
int i;
threads = (pthread_t *)malloc(sizeof(pthread_t) * pthnum);
stat_list = (char*)calloc(pthnum, sizeof(char));
for(i = 0; i < pthnum; i++)
stat_list[i] = '-';
begtime = time(0);
pthread_create(&stat, 0, pthstat, (void*)0);
for(i = 0; i < pthnum; i++)
pthread_create(threads + i, 0, proc, (void *)i);
pthread_join(stat, 0);
for(i = 0; i < pthnum; i++)
pthread_join(threads[i], 0);
endtime = time(0);
restime = endtime - begtime;
printf("Result = %lf\\nCalculating time = %d sec\\n", result, restime);
return 0;
}
double func(double x,double y, double z)
{
double t, r;
if((t = sqrt(x*x + y*y + z*z)) > 1)
r = 0.5;
if(t > 2)
r = 0;
if(t < 0.5)
r+= 0.5 * sin(t);
return r;
}
double integrate(double a, double b, double c, double d, double e, double f, int N, int M, int K)
{
double hx, hy, hz;
double x, y, z;
double res = 0;
int i, j, k;
hx = (b-a)/N;
hy = (d-c)/M;
hz = (f-e)/K;
for(i = 1; i < N; i++)
{
x = a + i * hx + 0.5 * hx;
for(j = 1; j < M; j++)
{
y = c + j * hy + 0.5 * hy;
for(k = 1; k < K; k++)
{
z = e + k * hz + 0.5 * hz;
res+= func(x, y, z) * hx * hy * hz;
}
}
}
return res;
}
void* proc(void *r)
{
int rank = (int)r;
int n;
double A, B, integral, len;
len = (b - a)/pthnum;
n = N/pthnum;
A = a + len * rank;
B = A + len;
integral = integrate(A, B, c, d, e, f, n, M, K);
pthread_mutex_lock(&mut);
result+= integral;
pthread_mutex_unlock(&mut);
stat_list[rank] = '+';
--stat_flg;
return 0;
}
void* pthstat(void *arg)
{
unsigned i = stat_flg;
while(stat_flg > 0)
if(stat_flg == i)
{
printf("%s\\n", stat_list);
--i;
}
return 0;
}
| 0
|
#include <pthread.h>
unsigned long long main_counter, counter[3];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
void* thread_worker(void*);
int main(int argc,char* argv[])
{
int i, rtn, ch;
pthread_t pthread_id[3] = {0};
for (i=0; i<3; i++)
{
pthread_mutex_lock(&mutex1);
pthread_create(&pthread_id[i],0,thread_worker,(void*)&i);
}
do
{
unsigned long long sum = 0;
pthread_mutex_lock(&mutex);
for (i=0; i<3; i++)
{
sum += counter[i];
printf("%llu ", counter[i]);
}
printf("%llu/%llu", main_counter, sum);
pthread_mutex_unlock(&mutex);
}while ((ch = getchar()) != 'q');
return 0;
}
void* thread_worker(void* p)
{
int thread_num;
thread_num = *(int*)p;
pthread_mutex_unlock(&mutex1);
for(;;)
{
pthread_mutex_lock(&mutex);
counter[thread_num]++;
main_counter++;
pthread_mutex_unlock(&mutex);
}
}
| 1
|
#include <pthread.h>
double ** Matrix;
double ** Result_thrd;
int row,col,N;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int get_rand(int n)
{
return ( ((double) rand()) / 32767 ) * n;
}
void InitializeMatrix()
{
int i,j;
Matrix = (double **) malloc(N * sizeof(double*));
for(i=0;i<N;i++)
{
Matrix[i] = (double*) malloc(N * sizeof(double));
for(j=0;j<N;j++)
Matrix[i][j] = get_rand(10);
}
}
int Check_result(double ** Result_seq)
{
int i,j,flag = 1;
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{
if(Result_thrd[i][j] != Result_seq[i][j])
{ flag =0;
break;
}
}
}
return flag;
}
double ** MatMul()
{
int i,j,k,sum;
double ** Result = (double **) malloc(N * sizeof(double*));
for(i=0;i<N;i++)
{
Result[i] = (double *) malloc(N * sizeof(double));
for(j=0;j<N;j++)
{ sum =0;
for(k=0;k<N;k++)
{
sum = sum + Matrix[i][k] * Matrix[k][j];
}
Result[i][j] = sum;
}
}
return Result;
}
void calculate(int r,int c)
{
int k,sum =0;
for(k=0;k<N;k++)
{
sum = sum + Matrix[r][k] * Matrix[k][c];
}
Result_thrd[r][c] = sum;
return;
}
void* Thread_work(void* lv)
{
int* ID = (int *) lv;
int count=0;
int r,c;
printf("\\nThread No %d : Started working\\n",*ID,count);
while(1)
{
pthread_mutex_lock(&mutex);
r = row;
c = col;
if(row == N)
{
pthread_mutex_unlock(&mutex);
break;
}
if(col == N-1)
{
row = row+1;
col =0;
}
else
col = col +1;
pthread_mutex_unlock(&mutex);
calculate(r,c);
count++;
}
printf("\\nThread No %d : Calculated %d elements\\n",*ID,count);
return 0;
}
void MatMul_thrd(int no_thrd)
{
int *tids;
pthread_t *thrds;
pthread_attr_t *attrs;
void *retval;
int i;
thrds = (pthread_t*) malloc(sizeof(pthread_t)*no_thrd);
attrs = (pthread_attr_t*) malloc(sizeof(pthread_attr_t)*no_thrd);
tids = (int*) malloc(sizeof(int)*no_thrd);
Result_thrd = (double **) malloc(N * sizeof(double*));
for(i=0;i<N;i++)
Result_thrd[i] = (double *) malloc(N * sizeof(double));
for(i = 0; i < no_thrd; i++)
{
if(pthread_attr_init(attrs+i))
{
perror("attr_init()");
}
tids[i] = i+1;
if(pthread_create(thrds+i, attrs+i, Thread_work, tids+i) != 0)
{
perror("pthread_create()");
exit(1);
}
}
for(i = 0; i < no_thrd; i++)
{
pthread_join(thrds[i], &retval);
}
free(attrs);
free(thrds);
free(tids);
return;
}
int main(int argc, char* argv[])
{
int i,j;
double **Result_Seq;
int no_thrd;
if(argc != 3)
{
fprintf(stderr, "missing arguments\\n", argv[0]);
exit(1);
}
N = atoi(argv[1]);
no_thrd = atoi(argv[2]);
InitializeMatrix();
Result_Seq = MatMul();
row =0;
col=0;
MatMul_thrd(no_thrd);
if(Check_result(Result_Seq))
printf("\\n----------------Results are same for both versions-------------------\\n\\n");
else
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
}TLckData;
void *lck_init(void) {
TLckData *lck = malloc(sizeof(TLckData));
if ( lck != 0 ) {
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&lck->mutex, &attr);
}
return lck;
}
void lck_lock(void *lck) {
if (lck != 0) {
pthread_mutex_lock(&((TLckData*)lck)->mutex);
}
}
void lck_unlock(void *lck) {
if (lck != 0) {
pthread_mutex_unlock(&((TLckData*)lck)->mutex);
}
}
int lck_unlock_r(void *lck, int result) {
lck_unlock(lck);
return result;
}
void lck_free(void *lck) {
if ( lck != 0 ) {
pthread_mutex_destroy(&((TLckData*)lck)->mutex);
free(lck);
}
}
| 1
|
#include <pthread.h>
static pthread_mutex_t lock;
static pthread_rwlock_t rwlock;
static int counter = 0;
static int rwvar = 0;
static void init(int cnt) {
pthread_mutex_init(&lock, 0);
pthread_rwlock_init(&rwlock, 0);
counter = cnt;
}
static void finalize(void) {
pthread_mutex_destroy(&lock);
pthread_rwlock_destroy(&rwlock);
}
void* thr_fn1(void* arg) {
for (int i = 0; i < 1000; i++) {
pthread_mutex_lock(&lock);
counter++;
pthread_mutex_unlock(&lock);
}
}
void* thr_fn2(void* arg) {
for (int i = 0; i < 1000; i++) {
pthread_mutex_lock(&lock);
counter++;
pthread_mutex_unlock(&lock);
}
}
void* thr_fn3(void* arg) {
for (int i = 0; i < 1000; i++) {
while (pthread_mutex_trylock(&lock)) sleep(1);
counter++;
pthread_mutex_unlock(&lock);
}
}
void* thr_fn4(void* arg) {
struct timespec tout;
tout.tv_sec += 1;
for (int i = 0; i < 1000; i++) {
clock_gettime(CLOCK_REALTIME, &tout);
tout.tv_sec += 1;
pthread_mutex_timedlock(&lock, &tout);
counter++;
pthread_mutex_unlock(&lock);
}
}
void* thr_fn5(void* arg) {
for (int i = 0; i < 1000; i++) {
pthread_rwlock_rdlock(&rwlock);
printf("the rwvar is %d\\n", rwvar);
pthread_rwlock_unlock(&rwlock);
}
}
void* thr_fn6(void* arg) {
for (int i = 0; i < 1000; i++) {
pthread_rwlock_wrlock(&rwlock);
rwvar++;
pthread_rwlock_unlock(&rwlock);
}
}
int main(int argc, char *argv[]) {
pthread_t tid1, tid2, tid3, tid4;
init(0);
atexit(finalize);
pthread_create(&tid1, 0, thr_fn1, 0);
pthread_create(&tid2, 0, thr_fn2, 0);
pthread_create(&tid3, 0, thr_fn3, 0);
pthread_create(&tid4, 0, thr_fn4, 0);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
pthread_join(tid3, 0);
pthread_join(tid4, 0);
printf("the counter is %d\\n", counter);
pthread_t tids[11];
for (int i = 0; i < 10; i++) {
pthread_create(&tids[i], 0, thr_fn5, 0);
if (i == 5) {
pthread_create(&tids[10], 0, thr_fn6, 0);
}
}
for (int i = 0; i < 11; i++) {
pthread_join(tids[i], 0);
}
printf("the rwvar is %d\\n", rwvar);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t var1;
pthread_cond_t var2;
int writeable;
int sharedData;
} buffer;
int tot = 0;
buffer buf = { .writeable = 1, .sharedData = 0 };
int store(int item, buffer *pb){
pb->sharedData = item;
}
int retrieve(buffer *pb){
int item = pb->sharedData;
pb->sharedData = 0;
return item;
}
void* producer(void * v){
int j;
for (j=0; j<100; j++){
pthread_mutex_lock(& lock);
while (buf.writeable == 0){
pthread_cond_wait(&var2, &lock);
}
store(j, &buf);
buf.writeable = 0;
pthread_cond_signal(&var1);
pthread_mutex_unlock(& lock);
printf ("producer produce %d\\n", j);
usleep(rand()%11);
}
}
void* consumer(void * v){
int j=0;
while (j< 100 -1){
pthread_mutex_lock(& lock);
while (buf.writeable == 1){
pthread_cond_wait(&var1, &lock);
}
j = retrieve(&buf);
buf.writeable = 1;
pthread_cond_signal(&var2);
pthread_mutex_unlock(& lock);
tot = tot + j;
usleep(rand()%11);
}
}
int main(int argc, char **argv){
pthread_t th[4];
int i;
while (1){
pthread_mutex_init(& lock, 0);
pthread_cond_init (& var1, 0);
pthread_cond_init (& var2, 0);
for (i = 0; i < 4/2; i++){
pthread_create(&th[i], 0, consumer, 0);
}
for (i = 4/2; i < 4; i++){
pthread_create(&th[i], 0, producer, 0);
}
for (i = 0; i < 4; i++){
pthread_join(th[i], 0);
}
printf ("valeur théorique de tot = %d\\n", ((100*(100 -1))/2)*4/2);
printf ("valeur réelle de tot = %d\\n", tot);
tot = 0;
sleep(3);
}
return 0;
}
| 1
|
#include <pthread.h>
void mb_dev_list_init(struct mb_device_list_s *dlist) {
memset(dlist, 0, sizeof(struct mb_device_list_s));
pthread_mutex_init(&dlist->mutex, 0);
}
int mb_dev_add_signal(struct mb_device_list_s *dlist, struct signal_s *signal) {
int mb_id = signal->s_register.dr_device.d_mb_id;
int addr = signal->s_register.dr_addr;
if(mb_id > MAX_DEVS) {
return -1;
}
if(addr > MAX_REG) {
return -1;
}
if(mb_id > dlist->dev_max) {
dlist->dev_max = mb_id;
}
struct mb_device_s *device = &dlist->device[mb_id];
struct mb_device_reg_s *reg = &device->reg[addr];
struct mb_signal_list_s *signal_entry = malloc(sizeof(struct mb_signal_list_s));
if(addr > device->mb_reg_max) {
device->mb_reg_max = addr;
}
signal_entry->signal = signal;
signal_entry->next = reg->signals;
reg->signals = signal_entry;
return 0;
}
void mb_dev_add_write_request(struct mb_device_list_s *dlist, struct signal_s *signal, int value) {
int mb_id = signal->s_register.dr_device.d_mb_id;
int addr = signal->s_register.dr_addr;
if(mb_id > MAX_DEVS) {
return;
}
if(addr > MAX_REG) {
return;
}
struct mb_device_s *device = &dlist->device[mb_id];
struct mb_device_reg_s *reg = &device->reg[addr];
struct mb_reg_write_request_s *req = malloc(sizeof(struct mb_reg_write_request_s));
req->dev_id = mb_id;
req->reg_id = addr;
req->reg = reg;
req->write_mask = 0xffff;
req->write_value = value;
if(signal->s_register.dr_type == 'b') {
req->write_mask = 1 << signal->s_register.dr_bit;
req->write_value = value ? (1 << signal->s_register.dr_bit) : 0;
}
pthread_mutex_lock(&dlist->mutex);
req->next = dlist->writes;
dlist->writes = req;
pthread_mutex_unlock(&dlist->mutex);
}
int mb_dev_update(struct mb_device_list_s *dlist) {
int i = 0, j;
int regvalue;
struct mb_reg_write_request_s *req, *reglist = 0;
pthread_mutex_lock(&dlist->mutex);
req = dlist->writes;
dlist->writes = 0;
pthread_mutex_unlock(&dlist->mutex);
while(req) {
int regvalue, regmask;
struct mb_reg_write_request_s *wr = req;
struct mb_device_reg_s *reg = wr->reg;
req = req->next;
regmask = wr->reg->write_mask | wr->write_mask;
regvalue = (wr->reg->write_value & ~(wr->write_mask)) | (wr->write_value & wr->write_mask);
if(!wr->reg->write_mask) {
wr->next = reglist;
reglist = wr;
} else {
free(wr);
}
reg->write_value = regvalue;
reg->write_mask = regmask;
}
while(reglist) {
struct mb_reg_write_request_s *wr = reglist;
reglist = reglist->next;
int regvalue = wr->reg->value;
regvalue = regvalue & ~(wr->write_mask);
regvalue = regvalue | (wr->write_value);
dlist->mb_write_device(dlist, wr->dev_id, wr->reg_id, regvalue);
wr->reg->write_value = 0;
wr->reg->write_mask = 0;
free(wr);
}
for(i = 0; i < dlist->dev_max; i ++) {
if(dlist->device[i].mb_reg_max > 0) {
dlist->mb_read_device(dlist, i, dlist->device[i].mb_reg_max);
}
}
}
int mb_dev_check_signal(struct mb_device_list_s *dlist, struct signal_s *signal) {
int mb_id = signal->s_register.dr_device.d_mb_id;
int addr = signal->s_register.dr_addr;
int i, result = 0;
if(mb_id > MAX_DEVS) {
return -1;
}
if(addr > MAX_REG) {
return -1;
}
struct mb_device_s *device = &dlist->device[mb_id];
struct mb_device_reg_s *reg = &device->reg[addr];
int value = 0;
switch(signal->s_register.dr_type) {
case 'i':
if(reg->value != signal->s_value) {
result = 1;
signal->s_value = reg->value;
}
break;
case 'b':
value = (reg->value & (1 << signal->s_register.dr_bit)) >> signal->s_register.dr_bit;
signal->s_value = signal->s_value ? 1 : 0;
if(value != signal->s_value) {
result = 1;
signal->s_value = value;
}
break;
}
return result;
}
| 0
|
#include <pthread.h>
int balance = 1000;
pthread_mutex_t mutx = PTHREAD_MUTEX_INITIALIZER;
void *deposit(void *arg)
{
int amt = 50, i;
for(i=0; i<50; i++)
{
pthread_mutex_lock(&mutx);
balance = balance + amt;
pthread_mutex_unlock(&mutx);
}
return 0;
}
void *withdraw(void *arg)
{
int amt = 20, i;
for(i=0; i<20; i++)
{
pthread_mutex_lock(&mutx);
balance = balance - amt;
pthread_mutex_unlock(&mutx);
}
return 0;
}
int main()
{
pthread_t t1, t2;
int ret;
ret = pthread_create(&t1, 0, deposit, 0);
if(ret != 0)
{
printf("Thread Create Error.\\n");
return 0;
}
ret = pthread_create(&t2, 0, withdraw, 0);
if(ret != 0)
{
printf("Thread Create Error.\\n");
return 0;
}
ret = pthread_join(t1, 0);
if(ret != 0)
{
printf("Thread Join Error.\\n");
return 0;
}
ret = pthread_join(t2, 0);
if(ret != 0)
{
printf("Thread Join Error.\\n");
return 0;
}
printf("Balance is : %d\\n", balance);
return 0;
}
| 1
|
#include <pthread.h>
static struct Logger* logger = 0;
static const int LOG_BUF_SIZE = 64;
static const int DEFAULT_THRESH = 1000000;
static struct LogQueue* newLogQueue()
{
struct LogQueue* queue = (struct LogQueue*)malloc(sizeof(struct LogQueue));
assert(queue != 0);
queue->head = 0;
queue->tail = 0;
pthread_mutex_init(&queue->lock, 0);
pthread_cond_init(&queue->cond, 0);
return queue;
}
static void pushLog(struct LogQueue* queue, char* buf, int len, int level)
{
assert(queue != 0 && buf != 0);
struct LogNode* node = (struct LogNode*)malloc(sizeof(struct LogNode));
assert(node != 0);
node->buf = buf;
node->len = len;
node->level = level;
node->next = 0;
pthread_mutex_lock(&queue->lock);
if(queue->head == 0)
{
queue->head = queue->tail = node;
}
else
{
queue->tail->next = node;
queue->tail = node;
}
pthread_cond_signal(&queue->cond);
pthread_mutex_unlock(&queue->lock);
}
static struct LogNode* popLog(struct LogQueue* queue)
{
assert(queue != 0);
pthread_mutex_lock(&queue->lock);
while(queue->head == 0)
{
pthread_cond_wait(&queue->cond, &queue->lock);
}
struct LogNode* node = queue->head;
queue->head = node->next;
if(queue->head == 0)
{
queue->tail = 0;
}
pthread_mutex_unlock(&queue->lock);
return node;
}
static void* logThread(void* arg)
{
assert(logger != 0);
while(logger->run)
{
struct LogNode* node = popLog(logger->queue);
assert(node != 0);
if(node->level >= logger->level)
{
int n = write(logger->logFile, node->buf, node->len);
assert(n == node->len);
if(++logger->logCount >= logger->thresh)
{
close(logger->logFile);
char name[70];
strncpy(name, logger->filePath, 70);
snprintf(name + strlen(name), sizeof(name) - strlen(name),
"_%d", ++logger->fileCount);
rename(logger->filePath, name);
logger->logFile = open(logger->filePath,
O_CREAT | O_RDWR | O_APPEND, 0644);
assert(logger->logFile >= 0);
}
}
free(node->buf);
free(node);
}
}
void logOpen(const char* logFile, int level)
{
assert(logFile != 0);
logger = (struct Logger*)malloc(sizeof(struct Logger));
assert(logger != 0);
strncpy(logger->filePath, logFile, 64);
logger->logFile = open(logFile, O_CREAT | O_RDWR | O_APPEND, 0644);
assert(logger->logFile >= 0);
logger->level = level;
logger->queue = newLogQueue();
logger->run = 1;
logger->thresh = DEFAULT_THRESH;
logger->logCount = 0;
logger->fileCount = 0;
pthread_create(&logger->tid, 0, logThread, 0);
}
void logClose()
{
logger->run = 0;
logPrintf(LOG_WARN, "quit!\\n");
}
void logPrintf(int level, const char* format, ...)
{
char* buf = (char*)malloc(LOG_BUF_SIZE * sizeof(char));
assert(buf != 0);
va_list p;
__builtin_va_start((p));
int n = vsnprintf(buf, LOG_BUF_SIZE - 1, format, p);
assert(n > 0 && n < LOG_BUF_SIZE);
;
pushLog(logger->queue, buf, n, level);
}
| 0
|
#include <pthread.h>
char c;
struct node* next;
}node;
node* head=0;
pthread_mutex_t m=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c=PTHREAD_COND_INITIALIZER;
void* printlist(void* q)
{
for (;;){
pthread_mutex_lock(&m);
pthread_cond_wait(&c,&m);
node* p;
while (head!=0){
write(1,&head->c,1);
p = head;
head = head->next;
free(p);
}
pthread_mutex_unlock(&m);
}
}
void* f1(void* p)
{
char i;
for (i='A'; i<='Z'; i++){
node*q = malloc(sizeof(node));
q->c = i;
pthread_mutex_lock(&m);
q->next = head;
usleep(100000);
head = q;
pthread_mutex_unlock(&m);
pthread_cond_signal(&c);
usleep(100000);
}
}
void* f2(void* p)
{
char i;
for (i='a'; i<='z'; i++){
node* q = malloc(sizeof(node));
q->c = i;
pthread_mutex_lock(&m);
q->next = head;
usleep(90000);
head = q;
pthread_mutex_unlock(&m);
pthread_cond_signal(&c);
usleep(90000);
}
}
int main()
{
pthread_t ids[3];
pthread_create(ids+2,0,printlist,0);
pthread_create(ids+0,0,f1,0);
pthread_create(ids+1,0,f2,0);
pthread_join(ids[0],0);
pthread_join(ids[1],0);
sleep(1);
pthread_cancel(ids[2]);
}
| 1
|
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
void *printHello();
void *printWorld();
int count = 0;
main()
{
pthread_t thread1, thread2;
pthread_create( &thread1, 0, &printHello, 0);
pthread_create( &thread2, 0, &printWorld, 0);
pthread_join( thread1, 0);
pthread_join( thread2, 0);
exit(0);
}
void *printHello()
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
if (count % 2 != 0) {
pthread_cond_wait( &condition_var, &count_mutex );
}
count++;
printf("HELLO \\n");
pthread_cond_signal( &condition_var );
if(count >= 19) {
pthread_mutex_unlock( &count_mutex );
return(0);
}
pthread_mutex_unlock( &count_mutex );
}
}
void *printWorld()
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
if (count % 2 == 0) {
pthread_cond_wait( &condition_var, &count_mutex );
}
count++;
printf("WORLD \\n");
pthread_cond_signal( &condition_var );
if(count >= 19) {
pthread_mutex_unlock( &count_mutex );
return(0);
}
pthread_mutex_unlock( &count_mutex );
}
}
| 0
|
#include <pthread.h>
void * t_func (void *);
pthread_mutex_t mux = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
enum tstate {
T_ALIVE,
T_TERMINATED,
T_JOIN
};
struct tinfo {
pthread_t tid;
enum tstate state;
int sleeptime;
}*threads;
int nthreads = 0;
int reaped = 0;
main(int argc, char *argv[])
{
int ret;
int i;
nthreads = argc - 1;
if (argc < 2 || (!strcmp(argv[1], "--help"))) {
printf ("Usage: %s $1 $2 ...", argv[0]);
exit(1);
}
threads = calloc (argc - 1, sizeof (*threads));
for (i = 0; i < (argc - 1); i++) {
threads[i].state = T_ALIVE;
threads[i].sleeptime = atoi (argv[i + 1]);
ret = pthread_create (&threads[i].tid, 0, t_func, (void *)i);
if (ret)
err_exit ("create failed for %d\\n", i);
}
pthread_mutex_lock (&mux);
while (reaped != nthreads) {
ret = pthread_cond_wait (&cond, &mux);
if (ret)
err_exit ("cond wait failed\\n");
for (i = 0; i < nthreads; i++) {
if (threads[i].state == T_TERMINATED) {
threads[i].state = T_JOIN;
pthread_join (threads[i].tid, 0);
reaped++;
}
}
}
pthread_mutex_unlock (&mux);
}
void *
t_func (void *idx)
{
int i = (int) idx;
printf ("sleeping thread %d for %d time\\n", i, threads[i].sleeptime);
sleep (threads[i].sleeptime);
threads[i].state = T_TERMINATED;
pthread_cond_signal (&cond);
return;
}
| 1
|
#include <pthread.h>
ssize_t r_read(int fd, void *buf, size_t len)
{
size_t bytestoread;
ssize_t bytesread;
ssize_t totalbytes;
char *ptr = 0;
for (ptr = buf, bytestoread = len, totalbytes = 0; bytestoread > 0; ptr += bytesread, bytestoread -= bytesread)
{
bytesread = read(fd, ptr, bytestoread);
if (-1 == bytesread && errno != EINTR)
return -1;
if (0 == bytesread)
break;
if (-1 == bytesread)
bytesread = 0;
totalbytes += bytesread;
}
return totalbytes;
}
ssize_t r_write(int fd, const void *buf, size_t len)
{
size_t bytestowrite;
ssize_t byteswritten;
size_t totalbytes;
const char *ptr = 0;
for (ptr = buf, bytestowrite = len, totalbytes = 0; bytestowrite > 0; ptr += byteswritten, bytestowrite -= byteswritten)
{
byteswritten = write(fd, ptr, bytestowrite);
if (-1 == byteswritten && errno != EINTR)
return -1;
if (-1 == byteswritten)
byteswritten = 0;
totalbytes += byteswritten;
}
return totalbytes;
}
int recvfilename(int sockfd, char *filename, size_t len)
{
if (0 == filename)
return -1;
if (len > MAX_FILENAME)
len = MAX_FILENAME;
filename[0] = '\\0';
if (-1 == read(sockfd, filename, len))
{
log_msg(logfd, ERROR, "server read filename error");
return -1;
}
log_msg(logfd, INFO, "server read filename successfully!\\n");
return 0;
}
int sendfile(int sockfd, const char *filename)
{
int fd;
long file_size, read_left;
int readlen, writelen;
char buffer[BUFSIZE];
struct stat file_stat;
if (-1 == (fd = open(filename, O_RDONLY)))
{
log_msg(logfd, ERROR, "server open file '%s' error", filename);
return -1;
}
if (-1 == fstat(fd, &file_stat))
{
log_msg(logfd, ERROR, "server get file-size error");
return -1;
}
file_size = file_stat.st_size;
read_left = file_size;
while (read_left > 0)
{
if (-1 == (readlen = r_read(fd, buffer, sizeof(buffer))))
{
log_msg(logfd, ERROR, "server r_read error");
return -1;
}
read_left -= readlen;
writelen = readlen;
if (-1 == r_write(sockfd, buffer, writelen))
{
log_msg(logfd, ERROR, "server r_write error");
return -1;
}
if (0 == readlen && read_left != 0)
{
log_msg(logfd, WARN, "The file isn't really fully, may be error!");
return -1;
}
}
close(sockfd);
return 0;
}
int getline(char buf[], int maxlen)
{
int n;
memset(buf, 0, maxlen);
fflush(stdin);
fgets(buf, maxlen, stdin);
n = strlen(buf);
buf[n - 1] = '\\0';
return (n - 1);
}
int chk_file_stat(const char *filename)
{
FILE *fp = 0;
if (0 == (fp = fopen(filename, "r")))
return FILE_NOT_EXIST;
else if (EOF == fgetc(fp))
{
fclose(fp);
return FILE_EMPTY;
}
rewind(fp);
fclose(fp);
return FILE_EXISTS_NOT_EMPTY;
}
void textattr(int f_color, int b_color, int cnt_mode)
{
pthread_mutex_lock(&mutex);
printf("\\033[%d;%d;%dm", cnt_mode, f_color, b_color);
fflush(stdout);
pthread_mutex_unlock(&mutex);
}
| 0
|
#include <pthread.h>
static unsigned int freqScanStartFreq;
static unsigned int freqScanEndFreq;
static short freqScanAmpBuf[518];
static short freqScanPhaseBuf[518];
void setFreqRange(unsigned int startFreq, unsigned int endFreq)
{
freqScanStartFreq = startFreq;
freqScanEndFreq = endFreq;
}
void* freqScanThread(void* para)
{
int i;
unsigned char hasAmpChannel, hasPhaseChannel;
struct command *pCmd = (struct command *) para;
hasAmpChannel = ((pCmd->para1 & 0x01) == 0x01);
hasPhaseChannel = ((pCmd->para1 & 0x02) == 0x02);
short delay = ((pCmd->para2) & 0xffff);
if(hasAmpChannel) DEBUG0("hasAmpChannel");
if(hasPhaseChannel) DEBUG0("hasPhaseChannel");
pthread_detach(pthread_self());
double startFreq = (double) freqScanStartFreq / 100.0;
double endFreq = (double) freqScanEndFreq / 100.0;
int currentTask;
double currentFreq;
DEBUG0("in freq scan thread");
DEBUG1("start freq = %f\\n", startFreq);
DEBUG1("end freq = %f\\n", endFreq);
DEBUG1("delay = %d\\n", (int)delay);
DEBUG0("STARTING FREQENCY SCANNING ..................................");
freqScanAmpBuf[0] = CMD_FREQ_SCAN;
freqScanPhaseBuf[0] = CMD_FREQ_SCAN;
freqScanAmpBuf[1] = 1024;
freqScanPhaseBuf[1] = 1024;
freqScanAmpBuf[2] = 512;
freqScanPhaseBuf[2] = 512;
freqScanAmpBuf[3] = 0x01;
freqScanPhaseBuf[3] = 0x02;
for(i = 0; i < 512; i++)
{
pthread_mutex_lock(&g_current_task_mutex);
currentTask = g_current_task;
pthread_mutex_unlock(&g_current_task_mutex);
if(currentTask == STOP) break;
currentFreq = startFreq + i * (endFreq - startFreq) / 512.0;
dds_Out(currentFreq);
udelay(delay);
if(hasAmpChannel) freqScanAmpBuf[6 + i] = read_AD_N( AD_OSAP, 30 );
if(hasPhaseChannel) freqScanPhaseBuf[6 + i] = read_AD_N( AD_PHASE, 30 );
}
if(hasAmpChannel)
{
send(connect_socket_fd, (char*)freqScanAmpBuf, 1036, 0);
DEBUG0("send(connect_socket_fd, (char*)&freqScanAmpBuf, 1036, 0);");
}
if(hasPhaseChannel)
{
send(connect_socket_fd, (char*)freqScanPhaseBuf, 1036, 0);
DEBUG0("send(connect_socket_fd, (char*)&freqScanPhaseBuf, 1036, 0);");
}
pthread_mutex_lock(&g_current_task_mutex);
g_current_task = STOP;
pthread_mutex_unlock(&g_current_task_mutex);
DEBUG0("End of freq scan thread ......");
return (void*)0;
}
| 1
|
#include <pthread.h>
struct glut_frame_buffer_t
{
int *buffer;
int width;
int height;
int flush_request;
};
static struct glut_frame_buffer_t *glut_frame_buffer;
void glut_frame_buffer_init(void)
{
glut_frame_buffer = xcalloc(1, sizeof(struct glut_frame_buffer_t));
glut_frame_buffer->flush_request = 1;
}
void glut_frame_buffer_done(void)
{
if (glut_frame_buffer->buffer)
free(glut_frame_buffer->buffer);
free(glut_frame_buffer);
}
void glut_frame_buffer_clear(void)
{
pthread_mutex_lock(&glut_mutex);
if (glut_frame_buffer->buffer)
memset(glut_frame_buffer->buffer, 0, glut_frame_buffer->width *
glut_frame_buffer->height * sizeof(int));
pthread_mutex_unlock(&glut_mutex);
}
void glut_frame_buffer_resize(int width, int height)
{
pthread_mutex_lock(&glut_mutex);
if (width < 1 || height < 1)
fatal("%s: invalid size (width = %d, height = %d)\\n",
__FUNCTION__, width, height);
if (glut_frame_buffer->width == width && glut_frame_buffer->height == height)
{
memset(glut_frame_buffer->buffer, 0, glut_frame_buffer->width *
glut_frame_buffer->height * sizeof(int));
goto out;
}
if (glut_frame_buffer->buffer)
free(glut_frame_buffer->buffer);
glut_frame_buffer->buffer = xcalloc(width * height, sizeof(int));
glut_frame_buffer->width = width;
glut_frame_buffer->height = height;
out:
pthread_mutex_unlock(&glut_mutex);
}
void glut_frame_buffer_pixel(int x, int y, int color)
{
pthread_mutex_lock(&glut_mutex);
if ((unsigned int) color > 0xffffff)
{
warning("%s: invalid pixel color", __FUNCTION__);
goto out;
}
if (!IN_RANGE(x, 0, glut_frame_buffer->width - 1))
{
warning("%s: invalid X coordinate", __FUNCTION__);
goto out;
}
if (!IN_RANGE(y, 0, glut_frame_buffer->height - 1))
{
warning("%s: invalid Y coordinate", __FUNCTION__);
goto out;
}
glut_frame_buffer->buffer[y * glut_frame_buffer->width + x] = color;
out:
pthread_mutex_unlock(&glut_mutex);
}
void glut_frame_buffer_get_size(int *width, int *height)
{
pthread_mutex_lock(&glut_mutex);
if (width)
*width = glut_frame_buffer->width;
if (height)
*height = glut_frame_buffer->height;
pthread_mutex_unlock(&glut_mutex);
}
void glut_frame_buffer_flush_request(void)
{
pthread_mutex_lock(&glut_mutex);
glut_frame_buffer->flush_request = 1;
pthread_mutex_unlock(&glut_mutex);
}
void glut_frame_buffer_flush_if_requested(void)
{
float red;
float green;
float blue;
int color;
int width;
int height;
int x;
int y;
pthread_mutex_lock(&glut_mutex);
if (!glut_frame_buffer->flush_request)
goto out;
width = glut_frame_buffer->width;
height = glut_frame_buffer->height;
glClear(GL_COLOR_BUFFER_BIT);
glPointSize(1.0);
glBegin(GL_POINTS);
for (x = 0; x < width; x++)
{
for (y = 0; y < height; y++)
{
color = glut_frame_buffer->buffer[y * width + x];
red = (float) (color >> 16) / 0xff;
green = (float) ((color >> 8) & 0xff) / 0xff;
blue = (float) (color & 0xff) / 0xff;
glColor3f(red, green, blue);
glVertex2i(x, y);
}
}
glEnd();
glFlush();
glut_frame_buffer->flush_request = 0;
out:
pthread_mutex_unlock(&glut_mutex);
}
| 0
|
#include <pthread.h>
void* naNewLock()
{
pthread_mutex_t* lock = naAlloc(sizeof(pthread_mutex_t));
pthread_mutex_init(lock, 0);
return lock;
}
void naFreeLock(void* lock)
{
pthread_mutex_destroy(lock);
naFree(lock);
}
void naLock(void* lock)
{
pthread_mutex_lock((pthread_mutex_t*)lock);
}
void naUnlock(void* lock)
{
pthread_mutex_unlock((pthread_mutex_t*)lock);
}
struct naSem {
pthread_mutex_t lock;
pthread_cond_t cvar;
int count;
};
void* naNewSem()
{
struct naSem* sem = naAlloc(sizeof(struct naSem));
pthread_mutex_init(&sem->lock , 0);
pthread_cond_init(&sem->cvar, 0);
sem->count = 0;
return sem;
}
void naFreeSem(void* p)
{
struct naSem* sem = p;
pthread_mutex_destroy(&sem->lock);
pthread_cond_destroy(&sem->cvar);
naFree(sem);
}
void naSemDown(void* sh)
{
struct naSem* sem = (struct naSem*)sh;
pthread_mutex_lock(&sem->lock);
while(sem->count <= 0)
pthread_cond_wait(&sem->cvar, &sem->lock);
sem->count--;
pthread_mutex_unlock(&sem->lock);
}
void naSemUp(void* sh, int count)
{
struct naSem* sem = (struct naSem*)sh;
pthread_mutex_lock(&sem->lock);
sem->count += count;
pthread_cond_broadcast(&sem->cvar);
pthread_mutex_unlock(&sem->lock);
}
extern int GccWarningWorkaround_IsoCForbidsAnEmptySourceFile;
| 1
|
#include <pthread.h>
struct arpQueueNode* addQueueNode(uint32_t ip, const char* interface){
struct sr_instance* sr = get_sr();
struct sr_router* subsystem = (struct sr_router*)sr_get_subsystem(sr);
struct arpQueueNode *cur = subsystem->arpQueue;
while(cur){
if( !strcmp(interface, cur->interface) && (ip == cur->dstIP) ){
return cur;
}
cur = cur->next;
}
cur = (struct arpQueueNode*)malloc(sizeof(struct arpQueueNode));
strcpy(cur->interface, interface);
cur->dstIP = ip;
cur->head = cur->tail = 0;
cur->prev = 0;
cur->next = subsystem->arpQueue;
if(subsystem->arpQueue) subsystem->arpQueue->prev = cur;
subsystem->arpQueue = cur;
return cur;
}
void queuePacket(uint8_t* packet, unsigned len, const char* interface, uint32_t dstIP){
int i;
pthread_mutex_lock(&queue_lock);
struct arpQueueNode *node = addQueueNode(dstIP, interface);
struct arpQueueItem *item = (struct arpQueueItem*)malloc(sizeof(struct arpQueueItem));
item->packet = (uint8_t*)malloc(len * sizeof(uint8_t));
for(i = 0; i < len; i++) item->packet[i] = packet[i];
item->len = len;
item->t = time(0);
item->prev = item->next = 0;
item->next = node->head;
if(node->head) node->head->prev = item;
node->head = item;
if(node->tail == 0) node->tail = item;
pthread_mutex_unlock(&queue_lock);
}
void queueSendLockless(uint32_t ip, const char* interface){
int i;
struct sr_instance* sr = get_sr();
struct sr_router* subsystem = (struct sr_router*)sr_get_subsystem(sr);
uint8_t *dstMAC = arpLookupTree(subsystem->arpTree, ip);
if(dstMAC){
struct arpQueueNode* cur = subsystem->arpQueue;
while(cur){
if( !strcmp(interface, cur->interface) && (ip == cur->dstIP) ){
while( cur->tail ){
for (i = 0; i < 6; i++) cur->tail->packet[i] = dstMAC[i];
sr_integ_low_level_output(sr, cur->tail->packet, cur->tail->len, cur->interface);
struct arpQueueItem* tmp = cur->tail;
if(cur->tail->prev)
cur->tail->prev->next = 0;
else
cur->head = 0;
cur->tail = cur->tail->prev;
free(tmp);
}
struct arpQueueNode* curTmp = cur;
cur = cur->next;
if(curTmp->prev)
curTmp->prev->next = curTmp->next;
else
subsystem->arpQueue = curTmp->next;
if(curTmp->next)
curTmp->next->prev = curTmp->prev;
free(curTmp);
break;
}
else{
cur = cur->next;
}
}
free(dstMAC);
}
}
void queueSend(uint32_t ip, const char* interface){
pthread_mutex_lock(&queue_lock);
queueSendLockless(ip, interface);
pthread_mutex_unlock(&queue_lock);
}
void arpQueueRefresh(void* dummy){
struct sr_instance* sr = get_sr();
struct sr_router* subsystem = (struct sr_router*)sr_get_subsystem(sr);
while(1){
loop_begin:
pthread_mutex_lock(&queue_lock);
struct arpQueueNode* cur = subsystem->arpQueue;
while(cur){
struct arpQueueNode* tmp = cur->next;
int delFlag = 0;
while(cur->tail){
if( (time(0) - cur->tail->t) > ARP_QUEUE_TIMEOUT){
struct arpQueueItem* curTmp = cur->tail;
if(curTmp->prev){
curTmp->prev->next = 0;
}
else{
cur->head = 0;
delFlag = 1;
}
cur->tail = cur->tail->prev;
pthread_mutex_unlock(&queue_lock);
dbgMsg("ARP queue timeout");
uint32_t srcIP = ntohl(*((uint32_t*)&curTmp->packet[ETHERNET_HEADER_LENGTH + 12]));
char *out_if = lp_match(&(subsystem->rtable), srcIP);
if(out_if && !isMyIP(srcIP)) sendICMPDestinationUnreachable(out_if, curTmp->packet, curTmp->len, 1);
free(out_if);
free(curTmp);
goto loop_begin;
}
else{
break;
}
}
if(delFlag){
struct arpQueueNode* curTmpN = cur;
if(curTmpN->prev)
curTmpN->prev->next = curTmpN->next;
else
subsystem->arpQueue = curTmpN->next;
if(curTmpN->next)
curTmpN->next->prev = curTmpN->prev;
free(curTmpN);
}
else{
queueSendLockless(cur->dstIP, cur->interface);
}
cur = tmp;
}
pthread_mutex_unlock(&queue_lock);
sleep(ARP_QUEUE_REFRESH);
}
}
| 0
|
#include <pthread.h>
pthread_cond_t Var_Cond;
pthread_mutex_t Verrou;
pthread_t Thread_Id;
int Threads_Finis;
} Zone_Part_t;
Zone_Part_t Zone_Part;
sem_t sem;
int main(int argc, char *argv[]){
pthread_t Tid_main, Threads[1000];
int i, Acquittes, Nbre_Threads;
void Un_Thread (void);
if (argc != 2){
printf("Utilisation : %s n (nbre de threads)\\n", argv[0]);
exit(1);
}
Nbre_Threads = atoi(argv[1]);
if (Nbre_Threads > 1000){
printf(" Pas plus de %d threads !\\n", Nbre_Threads);
exit(2);
}
srandom(time(0));
Tid_main=pthread_self();
Acquittes = 0;
Zone_Part.Threads_Finis = 0;
pthread_cond_init(&Zone_Part.Var_Cond, 0);
pthread_mutex_init(&Zone_Part.Verrou, 0);
sem_init(&sem, 0, 0);
for (i=0; i < Nbre_Threads ; i++){
pthread_create(&Threads[i], 0, (void *(*)(void *))Un_Thread, 0);
printf("main (Tid (0x)%x vient de creer : (0x)%x\\n", (int)Tid_main, (int)Threads[i]);
}
sem_post(&sem);
pthread_mutex_lock(&Zone_Part.Verrou);
while (Zone_Part.Threads_Finis < Nbre_Threads){
pthread_cond_wait(&Zone_Part.Var_Cond, &Zone_Part.Verrou);
Acquittes++;
printf("\\n\\n----------------%d----------------\\n\\n", Acquittes);
printf("main (Tid (0x)%x) : fin du thread (0x)%x\\n",
(int)Tid_main, (int)Zone_Part.Thread_Id);
sem_post(&sem);
}
pthread_mutex_unlock(&Zone_Part.Verrou);
printf("main (Tid (0x)%x) : FIN, nbre de threads acquittes : %d, nbre de threads termines : %d\\n",
(int)Tid_main, Acquittes,Zone_Part.Threads_Finis);
return 0;
}
void Un_Thread(void){
pthread_t Mon_Tid;
int i, Nbre_Iter;
Mon_Tid = pthread_self();
Nbre_Iter = random()/10000;
printf("Thread (0x)%x : DEBUT, %d iterations\\n", (int)Mon_Tid, Nbre_Iter);
sem_wait(&sem);
i=0;
while(i < Nbre_Iter) i++;
pthread_mutex_lock(&Zone_Part.Verrou);
Zone_Part.Thread_Id = Mon_Tid ;
Zone_Part.Threads_Finis++ ;
pthread_cond_signal(&Zone_Part.Var_Cond);
printf("Thread (0x)%x : FIN \\n", (int)Mon_Tid);
pthread_mutex_unlock(&Zone_Part.Verrou);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
int cnt;
} Counter;
int n, k, numThreads, finished = 0;
int *numer, *denom;
float result = 1.0;
Counter countNumerFactors, countDenomFactors, countNumerBarrier, countDenomBarrier;
sem_t *barrier1, *barrier2;
void* thNumerator(void* arg);
void* thDenominator(void* arg);
int main(int argc, char** argv) {
int i, *arg;
pthread_t* th;
if (argc != 4) {
fprintf(stderr, "Wrong number of arguments. Syntax: %s n k numThreads\\n", argv[0]);
return -1;
}
n = atoi(argv[1]);
k = atoi(argv[2]);
numThreads = atoi(argv[3]);
if (((n == 0) && (k == 0)) || (n == k)) {
fprintf(stdout, "The binomial coefficient is: 1\\n");
return 0;
}
if (numThreads >= k/2) {
numThreads = k/2;
}
barrier1 = (sem_t*)malloc(sizeof(sem_t));
barrier2 = (sem_t*)malloc(sizeof(sem_t));
sem_init(barrier1, 0, 0);
sem_init(barrier2, 0, 0);
countNumerFactors.cnt = n-k+1;
pthread_mutex_init(&countNumerFactors.mutex, 0);
countDenomFactors.cnt = 1;
pthread_mutex_init(&countDenomFactors.mutex, 0);
countNumerBarrier.cnt = 0;
pthread_mutex_init(&countNumerBarrier.mutex, 0);
countDenomBarrier.cnt = 0;
pthread_mutex_init(&countDenomBarrier.mutex, 0);
numer = (int*)malloc(numThreads*sizeof(int));
denom = (int*)malloc(numThreads*sizeof(int));
for (i=0; i<numThreads; i++) {
numer[i] = 1;
denom[i] = 1;
}
th = (pthread_t*)malloc(2*numThreads*sizeof(pthread_t));
for (i=0; i<numThreads; i++) {
arg = (int*)malloc(sizeof(int));
*arg = i;
pthread_create(&th[i], 0, (void*)thNumerator, arg);
pthread_create(&th[i+numThreads], 0, (void*)thDenominator, arg);
}
for (i=0; i<numThreads*2; i++) {
pthread_join(th[i], 0);
}
fprintf(stdout, "The binomial coefficient is: %.2f\\n", result);
return 0;
}
void* thNumerator(void* arg) {
int* argid = (int*) arg;
int id, i;
id = *argid;
while (!finished) {
pthread_mutex_lock(&countNumerFactors.mutex);
if (countNumerFactors.cnt <= n-1) {
numer[id] = countNumerFactors.cnt * (countNumerFactors.cnt + 1);
countNumerFactors.cnt += 2;
} else if (countNumerFactors.cnt == n) {
numer[id] = n;
countNumerFactors.cnt++;
} else {
numer[id] = 1;
countNumerFactors.cnt++;
}
pthread_mutex_unlock(&countNumerFactors.mutex);
pthread_mutex_lock(&countNumerBarrier.mutex);
pthread_mutex_lock(&countDenomBarrier.mutex);
countNumerBarrier.cnt++;
if (countNumerBarrier.cnt == numThreads && countDenomBarrier.cnt == numThreads) {
for (i=0; i<numThreads; i++) {
result *= numer[i] / (float) denom[i];
numer[i] = 1;
denom[i] = 1;
}
pthread_mutex_lock(&countNumerFactors.mutex);
pthread_mutex_lock(&countDenomFactors.mutex);
if (countNumerFactors.cnt > n && countDenomFactors.cnt > k) {
finished = 1;
}
pthread_mutex_unlock(&countDenomFactors.mutex);
pthread_mutex_unlock(&countNumerFactors.mutex);
for (i=0; i<numThreads*2; i++) {
sem_post(barrier1);
}
}
pthread_mutex_unlock(&countDenomBarrier.mutex);
pthread_mutex_unlock(&countNumerBarrier.mutex);
sem_wait(barrier1);
pthread_mutex_lock(&countNumerBarrier.mutex);
pthread_mutex_lock(&countDenomBarrier.mutex);
countNumerBarrier.cnt--;
if (countNumerBarrier.cnt == 0 && countDenomBarrier.cnt == 0) {
for (i=0; i<numThreads*2; i++) {
sem_post(barrier2);
}
}
pthread_mutex_unlock(&countDenomBarrier.mutex);
pthread_mutex_unlock(&countNumerBarrier.mutex);
sem_wait(barrier2);
}
pthread_exit(0);
}
void* thDenominator(void* arg) {
int* argid = (int*) arg;
int id, i;
id = *argid;
while (!finished) {
pthread_mutex_lock(&countDenomFactors.mutex);
if (countDenomFactors.cnt <= k-1) {
denom[id] = countDenomFactors.cnt * (countDenomFactors.cnt + 1);
countDenomFactors.cnt += 2;
} else if (countDenomFactors.cnt == k) {
denom[id] = k;
countDenomFactors.cnt++;
} else {
denom[id] = 1;
countDenomFactors.cnt++;
}
pthread_mutex_unlock(&countDenomFactors.mutex);
pthread_mutex_lock(&countNumerBarrier.mutex);
pthread_mutex_lock(&countDenomBarrier.mutex);
countDenomBarrier.cnt++;
if (countDenomBarrier.cnt == numThreads && countDenomBarrier.cnt == numThreads) {
for (i=0; i<numThreads; i++) {
result *= numer[i] / (float) denom[i];
numer[i] = 1;
denom[i] = 1;
}
pthread_mutex_lock(&countNumerFactors.mutex);
pthread_mutex_lock(&countDenomFactors.mutex);
if (countNumerFactors.cnt > n && countDenomFactors.cnt > k) {
finished = 1;
}
pthread_mutex_unlock(&countDenomFactors.mutex);
pthread_mutex_unlock(&countNumerFactors.mutex);
for (i=0; i<numThreads*2; i++) {
sem_post(barrier1);
}
}
pthread_mutex_unlock(&countDenomBarrier.mutex);
pthread_mutex_unlock(&countNumerBarrier.mutex);
sem_wait(barrier1);
pthread_mutex_lock(&countNumerBarrier.mutex);
pthread_mutex_lock(&countDenomBarrier.mutex);
countDenomBarrier.cnt--;
if (countNumerBarrier.cnt == 0 && countDenomBarrier.cnt == 0) {
for (i=0; i<numThreads*2; i++) {
sem_post(barrier2);
}
}
pthread_mutex_unlock(&countDenomBarrier.mutex);
pthread_mutex_unlock(&countNumerBarrier.mutex);
sem_wait(barrier2);
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_t threads[5];
pthread_mutex_t mutexsum;
{
int veclen;
double sum;
double *ap;
double *bp;
} DOTDATA_t;
DOTDATA_t dotstr;
{
pthread_t thread_id;
long offset;
double sum;
int rc;
} thread_data_t;
thread_data_t thread_data[5];
void *dotprod(void *tharg)
{
int ndx, start, end, veclen;
double mysum, *xp, *yp;
long thread = (long)tharg;
printf("thread %ld\\n",(long)thread);
veclen = dotstr.veclen;
start = thread * veclen;
end = start + veclen;
xp = dotstr.ap;
yp = dotstr.bp;
mysum = 0;
for (ndx=start; ndx<end ; ndx++)
{
mysum += (xp[ndx] * yp[ndx]);
}
printf("thread %ld sum %f\\n",(long)thread,mysum);
thread_data[thread].sum = mysum;
pthread_mutex_lock (&mutexsum);
dotstr.sum += mysum;
pthread_mutex_unlock (&mutexsum);
pthread_exit((void*)ndx);
}
int thread_data_create(int n, void *(*func)(void *))
{
int rc;
int tdx;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(tdx=0; tdx<5; tdx++)
{
threads[tdx] = tdx;
thread_data[tdx].thread_id = tdx;
thread_data[tdx].offset = tdx;
thread_data[tdx].sum = 0.0;
printf("Create thread %ld\\n",(long)tdx);
rc = pthread_create(&threads[tdx], &attr, dotprod, (void *)tdx);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
thread_data[tdx].rc = rc;
}
pthread_attr_destroy(&attr);
return(n);
}
int thread_data_join(int n)
{
int rc;
int tdx;
void* status;
for(tdx=0; tdx<5; tdx++)
{
rc = pthread_join(threads[tdx], &status);
if (rc) {
printf("ERROR; return code from pthread_join() is %d\\n", rc);
exit(-1);
}
printf("Join thread %ld, res %ld\\n",(long)tdx,(long)status);
thread_data[tdx].rc = rc;
}
return(n);
}
int create_data(int veclen)
{
int vndx;
double *ap, *bp;
ap = (double*) malloc (5*veclen*sizeof(double));
bp = (double*) malloc (5*veclen*sizeof(double));
if( !ap || !bp ) {
printf("malloc failed\\n");
exit(1);
}
for (vndx=0; vndx<veclen*5; vndx++)
{
ap[vndx]=1.0;
bp[vndx]=ap[vndx];
}
dotstr.veclen = veclen;
dotstr.ap = ap;
dotstr.bp = bp;
dotstr.sum=0;
return(veclen);
}
int free_data()
{
double* ap = dotstr.ap;
double* bp = dotstr.bp;
if( ap ) {
free (ap);
dotstr.ap = ap = 0;
}
if( bp ) {
free (bp);
dotstr.bp = bp = 0;
}
return(0);
}
int main (int argc, char *argv[])
{
create_data(1000);
pthread_mutex_init(&mutexsum, 0);
thread_data_create(5, dotprod);
thread_data_join(5);
printf ("Sum = %f \\n", dotstr.sum);
pthread_mutex_destroy(&mutexsum);
free_data();
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_cond_t CondVar = PTHREAD_COND_INITIALIZER;
pthread_mutex_t MutexCondVar = PTHREAD_MUTEX_INITIALIZER;
void* Thread1(void *data)
{
int rc;
while(1)
{
printf("1"); fflush(stdout);
rc = pthread_cond_broadcast(&CondVar);
if(rc){
perror("pthread_cond_signal/broadcast");
pthread_exit(0);
}
usleep(500*1000);
}
}
void* Thread2(void *data)
{
int rc;
while(1)
{
rc = pthread_mutex_lock(&MutexCondVar);
if(rc){
perror("pthread_mutex_lock");
pthread_exit(0);
}
rc = pthread_cond_wait(&CondVar, &MutexCondVar);
if (rc){
perror("pthread_cond_wait");
pthread_exit(0);
}
else{
printf("2"); fflush(stdout);
}
pthread_mutex_unlock(&MutexCondVar);
}
}
void* Thread3(void *data)
{
int rc;
while(1)
{
rc = pthread_mutex_lock(&MutexCondVar);
if(rc){
perror("pthread_mutex_lock");
pthread_exit(0);
}
rc = pthread_cond_wait(&CondVar, &MutexCondVar);
if (rc){
perror("pthread_cond_wait");
pthread_exit(0);
}
else{
printf("3"); fflush(stdout);
}
pthread_mutex_unlock(&MutexCondVar);
}
}
int main()
{
pthread_t p_thread[3];
printf("Main Start ...\\n");
pthread_create(&p_thread[0], 0, Thread1, 0);
pthread_create(&p_thread[1], 0, Thread2, 0);
pthread_create(&p_thread[2], 0, Thread3, 0);
pthread_detach(p_thread[0]);
pthread_detach(p_thread[1]);
pthread_detach(p_thread[2]);
pause();
printf("Main End ...\\n");
return 0;
}
| 0
|
#include <pthread.h>
pthread_t tid;
uint32_t thNumber;
}pthread_info_t;
uint32_t gCounter = 0;
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
void pthread_fn1 (void *args)
{
pthread_info_t *thInfo = (pthread_info_t *)args;
sleep(1);
do {
pthread_mutex_lock(&mutex1);
printf("[Thread ID:%u][ThreadNum:%u] gCounter=%u\\n", thInfo->tid, thInfo->thNumber, gCounter++);
pthread_cond_signal(&cond1);
pthread_mutex_unlock(&mutex1);
pthread_mutex_lock(&mutex2);
pthread_cond_wait(&cond2, &mutex2);
pthread_mutex_unlock(&mutex2);
}while (gCounter < 100);
}
void pthread_fn2 (void *args)
{
pthread_info_t *thInfo = (pthread_info_t *)args;
do {
pthread_mutex_lock(&mutex1);
pthread_cond_wait(&cond1, &mutex1);
printf("[ThreadID:%u][ThreadNum:%u] gCounter=%u\\n", thInfo->tid, thInfo->thNumber, gCounter++);
pthread_mutex_unlock(&mutex1);
pthread_mutex_lock(&mutex2);
pthread_cond_signal(&cond2);
pthread_mutex_unlock(&mutex2);
}while (gCounter <100);
}
int main()
{
pthread_info_t thInfo[2];
memset(thInfo, 0, sizeof(thInfo));
int32_t iret = -1;
thInfo[0].thNumber = 1;
thInfo[1].thNumber = 2;
iret = pthread_create(&thInfo[0].tid, 0, (void *)&pthread_fn1, (void *)&thInfo[0]);
if(iret != 0) {
printf("Failed to create thread number 1\\n");
return -1;
}
iret = pthread_create(&thInfo[1].tid, 0, (void *)&pthread_fn2, (void *)&thInfo[1]);
if(iret != 0) {
printf("Failed to create thread number 2\\n");
return -1;
}
iret = pthread_join(thInfo[0].tid, 0);
if(iret != 0) {
printf("pthread_join failed for thread number 1\\n");
return -1;
}
iret = pthread_join(thInfo[1].tid, 0);
if(iret != 0) {
printf("pthread_join failed for thread number 2\\n");
return -1;
}
return 0;
}
| 1
|
#include <pthread.h>
int isEnd = FALSE;
int product_count = 0;
int produce_times = 0;
pthread_mutex_t produce_mutex;
pthread_cond_t consume_cond;
pthread_cond_t produce_cond;
void* consume(void *pvoid) {
int pid = (int)pvoid;
while (TRUE) {
sleep((uint)(random() % 2));
RLOG("%d consume locking\\n", pid);
pthread_mutex_lock(&produce_mutex);
if (isEnd && product_count < 1) {
pthread_mutex_unlock(&produce_mutex);
break;
}
RLOG("%d consume get mutex\\n", pid);
if (product_count < 1) {
RLOG("%d waiting for produce\\n", pid);
pthread_cond_wait(&consume_cond, &produce_mutex);
RLOG("%d continue consume\\n", pid);
}
if (product_count > 0) {
--product_count;
pthread_cond_signal(&produce_cond);
RLOG("%d consume product left %d\\n", pid, product_count);
}
pthread_mutex_unlock(&produce_mutex);
}
RLOG("%d consume finished\\n", pid);
pthread_exit(0);
}
void* produce(void *pvoid) {
int pid = (int)pvoid;
while (!isEnd) {
sleep((unsigned int)(random() % 2));
pthread_mutex_lock(&produce_mutex);
if (product_count >= 10) {
RLOG("%d waiting for consume\\n", pid);
pthread_cond_wait(&produce_cond, &produce_mutex);
RLOG("%d continue produce\\n", pid);
}
if (produce_times >= 15) {
RLOG("%d produce finisehd left %d\\n", pid, product_count);
isEnd = TRUE;
} else {
if (product_count < 10) {
++product_count;
++produce_times;
}
RLOG("%d produce product left %d total %d\\n",
pid, product_count, produce_times);
}
pthread_cond_broadcast(&consume_cond);
pthread_mutex_unlock(&produce_mutex);
}
pthread_exit(0);
}
int main (int argc, char *argv[]) {
srandom((unsigned int)time(0));
pthread_mutex_init(&produce_mutex, 0);
pthread_cond_init(&consume_cond, 0);
pthread_cond_init(&produce_cond, 0);
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
int total_thread = 5 + 3;
pthread_t threads[total_thread];
for (int i = 0; i < total_thread; ++i) {
thread_routine routine = i >= 5 ? produce : consume;
pthread_create(&threads[i], &attr, routine, (void*)i);
}
for (int i = 0; i < total_thread; ++i) {
pthread_join(threads[i], 0);
}
pthread_mutex_destroy(&produce_mutex);
pthread_cond_destroy(&consume_cond);
pthread_cond_destroy(&produce_cond);
pthread_attr_destroy(&attr);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
static int g_running = 1;
static int g_complete = 0;
static pthread_mutex_t g_mutex;
static pthread_cond_t g_cond;
static void sigint_handler(int signal)
{
(void) signal;
fprintf(stderr, "sigint\\n");
pthread_mutex_lock(&g_mutex);
g_running = 0;
pthread_cond_signal(&g_cond);
pthread_mutex_unlock(&g_mutex);
}
static void logger(int severity, const char *message)
{
char *sev;
switch (severity)
{
case DSMCC_LOG_DEBUG:
sev = "[debug]";
break;
case DSMCC_LOG_WARN:
sev = "[warn]";
break;
case DSMCC_LOG_ERROR:
sev = "[error]";
break;
default:
sev = "";
break;
}
fprintf(stderr, "[dsmcc]%s %s\\n", sev, message);
}
static int get_pid_for_assoc_tag(void *arg, uint16_t assoc_tag, uint16_t *pid)
{
fprintf(stderr, "[main] Callback: Getting PID for association tag 0x%04x\\n", assoc_tag);
(void) arg;
(void) pid;
return -1;
}
static int add_section_filter(void *arg, uint16_t pid, uint8_t *pattern, uint8_t *equalmask, uint8_t *notequalmask, uint16_t depth)
{
char *p, *em, *nem;
int i;
(void) arg;
p = malloc(depth * 2 + 1);
em = malloc(depth * 2 + 1);
nem = malloc(depth * 2 + 1);
for (i = 0;i < depth; i++)
{
sprintf(p + i * 2, "%02hhx", pattern[i]);
sprintf(em + i * 2, "%02hhx", equalmask[i]);
sprintf(nem + i * 2, "%02hhx", notequalmask[i]);
}
fprintf(stderr, "[main] Callback: Add section filter on PID 0x%04x: %s|%s|%s\\n", pid, p, em, nem);
free(nem);
free(em);
free(p);
return 0;
}
static bool dentry_check(void *arg, uint32_t queue_id, uint32_t cid, bool dir, const char *path, const char *fullpath)
{
(void) arg;
fprintf(stderr, "[main] Callback(%u): Dentry check 0x%08x:%s:%s -> %s\\n",
queue_id, cid, dir ? "directory" : "file", path, fullpath);
return 1;
}
static void dentry_saved(void *arg, uint32_t queue_id, uint32_t cid, bool dir, const char *path, const char *fullpath)
{
(void) arg;
fprintf(stderr, "[main] Callback(%u): Dentry saved 0x%08x:%s:%s -> %s\\n",
queue_id, cid, dir ? "directory" : "file", path, fullpath);
};
static void download_progression(void *arg, uint32_t queue_id, uint32_t cid, uint32_t downloaded, uint32_t total)
{
(void) arg;
fprintf(stderr, "[main] Callback(%u): Carousel 0x%08x: %u/%u\\n",
queue_id, cid, downloaded, total);
}
static void carousel_status_changed(void *arg, uint32_t queue_id, uint32_t cid, int newstatus)
{
const char *status;
(void) arg;
switch (newstatus)
{
case DSMCC_STATUS_PARTIAL:
status = "PARTIAL";
break;
case DSMCC_STATUS_DOWNLOADING:
status = "DOWNLOADING";
break;
case DSMCC_STATUS_TIMEDOUT:
status = "TIMED-OUT";
break;
case DSMCC_STATUS_DONE:
status = "DONE";
break;
default:
status = "Unknown!";
break;
}
fprintf(stderr, "[main] Callback(%u): Carousel 0x%08x status changed to %s\\n",
queue_id, cid, status);
if (newstatus == DSMCC_STATUS_TIMEDOUT || newstatus == DSMCC_STATUS_DONE)
{
pthread_mutex_lock(&g_mutex);
g_complete = 1;
pthread_cond_signal(&g_cond);
pthread_mutex_unlock(&g_mutex);
}
};
static int parse_stream(FILE *ts, struct dsmcc_state *state, struct dsmcc_tsparser_buffer **buffers)
{
char buf[188];
int ret = 0;
int rc;
while (g_running && !g_complete)
{
rc = fread(buf, 1, 188, ts);
if (rc < 0)
{
fprintf(stderr, "read error : %s\\n", strerror(errno));
ret = -1;
break;
}
else if (rc == 0)
{
dsmcc_tsparser_parse_buffered_sections(state, *buffers);
break;
}
else
{
dsmcc_tsparser_parse_packet(state, buffers, (unsigned char*) buf, rc);
}
}
return ret;
}
int main(int argc, char **argv)
{
struct dsmcc_state *state;
int status = 0;
int carousel_type = DSMCC_OBJECT_CAROUSEL;
char *downloadpath;
FILE *ts;
uint16_t pid;
uint32_t qid;
int log_level = DSMCC_LOG_DEBUG;
struct dsmcc_tsparser_buffer *buffers = 0;
struct dsmcc_dvb_callbacks dvb_callbacks;
struct dsmcc_carousel_callbacks car_callbacks;
if(argc < 4)
{
fprintf(stderr, "usage %s [-d] [-q] <file> <pid> <downloadpath>\\n -q almost quiet\\n -d data carousel\\n", argv[0]);
return -1;
}
while(argc > 4)
{
if(!strcmp(argv[1], "-d"))
{
fprintf(stderr, "data carousel mode\\n");
carousel_type = DSMCC_DATA_CAROUSEL;
argv++;
argc--;
}
else if(!strcmp(argv[1], "-q"))
{
fprintf(stderr, "almost quiet mode\\n");
log_level = DSMCC_LOG_ERROR;
argv++;
argc--;
}
else
break;
}
sscanf(argv[2], "%hu", &pid);
downloadpath = argv[3];
signal(SIGINT, sigint_handler);
fprintf(stderr, "start\\n");
if (!strcmp(argv[1], "-"))
ts = stdin;
else
ts = fopen(argv[1], "r");
if (ts)
{
pthread_mutex_init(&g_mutex, 0);
pthread_cond_init(&g_cond, 0);
dsmcc_set_logger(&logger, log_level);
dvb_callbacks.get_pid_for_assoc_tag = &get_pid_for_assoc_tag;
dvb_callbacks.add_section_filter = &add_section_filter;
state = dsmcc_open("/tmp/dsmcc-cache", 1, &dvb_callbacks);
dsmcc_tsparser_add_pid(&buffers, pid);
car_callbacks.dentry_check = &dentry_check;
car_callbacks.dentry_saved = &dentry_saved;
car_callbacks.download_progression = &download_progression;
car_callbacks.carousel_status_changed = &carousel_status_changed;
qid = dsmcc_queue_carousel2(state, carousel_type, pid, 0, downloadpath, &car_callbacks);
status = parse_stream(ts, state, &buffers);
pthread_mutex_lock(&g_mutex);
if (!g_complete)
{
struct timeval now;
struct timespec ts;
fprintf(stderr, "Waiting 60s for carousel completion...\\n");
gettimeofday(&now, 0);
ts.tv_sec = now.tv_sec + 60;
ts.tv_nsec = now.tv_usec * 1000;
if (pthread_cond_timedwait(&g_cond, &g_mutex, &ts) == ETIMEDOUT)
fprintf(stderr, "Time out!\\n");
}
pthread_mutex_unlock(&g_mutex);
dsmcc_dequeue_carousel(state, qid);
dsmcc_close(state);
dsmcc_tsparser_free_buffers(&buffers);
}
else
{
fprintf(stderr, "open '%s' error : %s\\n", argv[1], strerror(errno));
return -1;
}
if (ts != stdin)
fclose(ts);
return status;
}
| 1
|
#include <pthread.h>
int kuz;
int sharmuta;
pthread_mutex_t zain = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t tutzke = PTHREAD_MUTEX_INITIALIZER;
void* suma(void*arg)
{
for(int i=0;i<10000;++i)
{
pthread_mutex_lock(&zain);
kuz= kuz +1;
pthread_mutex_lock(&tutzke);
sharmuta = sharmuta + 1;
pthread_mutex_unlock(&tutzke);
pthread_mutex_unlock(&zain);
}
pthread_exit(0);
}
void* resta(void*arg)
{
for(int i=0;i<10000;++i)
{
pthread_mutex_lock(&zain);
kuz= kuz-1;
pthread_mutex_lock(&tutzke);
sharmuta = sharmuta -1;
pthread_mutex_unlock(&tutzke);
pthread_mutex_unlock(&zain);
}
pthread_exit(0);
}
int main()
{
kuz =0;
sharmuta = 10000;
pthread_t* tids= (pthread_t*)malloc(2*sizeof(pthread_t));
pthread_create((tids),0,suma,0);
pthread_create((tids+1),0,resta,1);
pthread_join(*(tids),0);
pthread_join(*(tids+1),0);
printf("valor final de kuz:%d --valor resta: %d\\n",kuz,sharmuta);
return 0;
}
| 0
|
#include <pthread.h>
float array1[1024][1024];
float array2[1024][1024];
pthread_t t[16];
int num_of_iter = 0;
int not_converged = 1;
int count =0;
pthread_mutex_t count_lock;
pthread_cond_t ok_to_proceed;
} mylib_linear_barrier_t;
mylib_linear_barrier_t barrier1;
mylib_linear_barrier_t barrier2;
mylib_linear_barrier_t barrier3;
int check_for_convergence(int * thread_num);
double when();
void mylib_linear_barrier (mylib_linear_barrier_t * b);
void mylib_init_linear_barrier(mylib_linear_barrier_t * b);
void mylib_destroy_linear_barrier(mylib_linear_barrier_t * b);
int main(int argc, char* argv[])
{
double start_time;
double end_time;
start_time = when();
for(int i=0;i<1024;i++)
{
for(int j=0;j<1024;j++)
{
if(i==0 || j==0 || j==(1024 -1))
{
array1[i][j] = 0.0;
array2[i][j] = 0.0;
}
else if (i==1024 -1)
{
array1[i][j] = 100.0;
array2[i][j] = 100.0;
}
else if (i==400 && j<=330)
{
array1[i][j] = 100.0;
array2[i][j] = 100.0;
}
else if (i==200 && j ==500)
{
array1[i][j] = 100.0;
array2[i][j] = 100.0;
}
else
{
array1[i][j] = 50.0;
array2[i][j] = 50.0;
}
}
}
mylib_init_linear_barrier(&barrier1);
mylib_init_linear_barrier(&barrier2);
mylib_init_linear_barrier(&barrier3);
int n; int* arg;
for(int i=0;i<16;i++)
{
arg = malloc (sizeof(*arg));
*arg = i;
if(pthread_create(&t[i], 0,(void*) &check_for_convergence,arg)!=0)
printf("Thread creation failed\\n");
}
for(int i=0;i<16;i++)
{
pthread_join(t[i],0);
}
mylib_destroy_linear_barrier(&barrier1);
mylib_destroy_linear_barrier(&barrier2);
mylib_destroy_linear_barrier(&barrier3);
end_time=when();
printf("No of iterations = %d\\n",num_of_iter);
printf("Total execution time = %f\\n", end_time-start_time);
return 1;
}
int check_for_convergence(int * thread_num)
{
float convergence;
float temp;
int current_thread = *thread_num;
while(not_converged)
{
for(int i = current_thread ; i< 1024; i+=16)
{
for(int j=0; j< 1024; j++)
{
if( i==0 || (i==1024 -1) || j==0 || j== (1024 -1) ||
(i==400 && j<=330) || (i==200 && j ==500))
{
}
else
{
array2[i][j] = (array1[i+1][j] + array1[i-1][j] + array1[i][j+1]
+ array1[i][j-1] + (4 * array1[i][j]))/8.0;
}
}
}
mylib_linear_barrier(&barrier1);
for(int i = current_thread ; i< 1024; i+=16)
{
for(int j=0 ; j<1024 ; j++)
{
temp = array1[i][j];
array1[i][j] = array2[i][j];
array2[i][j] = temp;
}
}
mylib_linear_barrier(&barrier2);
if(current_thread == 0)
{
not_converged = 0;
for(int i = 0 ; i< 1024; i+=16)
{
for(int j=0;j<1024;j++)
{
if( i==0 || (i==1024 -1) || j==0 || j== (1024 -1) ||
(i==400 && j<=330) || (i==200 && j ==500))
{
}
else
{
convergence = array1[i][j]- ((array1[i+1][j] + array1[i-1][j]
+ array1[i][j+1] + array1[i][j-1])/4.0 );
if(fabs(convergence) > 0.1)
not_converged = 1;
}
}
}
num_of_iter++;
}
mylib_linear_barrier(&barrier3);
}
pthread_exit(0);
}
double when()
{
struct timeval tp;
gettimeofday(&tp, 0);
return ((double) tp.tv_sec + (double) tp.tv_usec * 1e-6);
}
void mylib_init_linear_barrier(mylib_linear_barrier_t * b)
{
pthread_mutex_init(&(b->count_lock),0);
pthread_cond_init(&(b->ok_to_proceed),0);
}
void mylib_linear_barrier (mylib_linear_barrier_t * b)
{
pthread_mutex_lock(&(b->count_lock));
count++;
if(count!=16)
pthread_cond_wait(&(b->ok_to_proceed),&(b->count_lock));
else
count = 0;
pthread_mutex_unlock(&(b->count_lock));
pthread_cond_broadcast(&(b->ok_to_proceed));
}
void mylib_destroy_linear_barrier(mylib_linear_barrier_t * b)
{
pthread_mutex_destroy(&b->count_lock);
pthread_cond_destroy(&b->ok_to_proceed);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutexid;
pthread_mutex_t mutexres;
int idcount = 0;
pthread_mutex_t joinmutex[2];
int join[2];
int result[2];
int target;
int sequence[(2 * 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 <= 2);
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[2];
int count;
i = __VERIFIER_nondet_int (0, (2 * 30)-1);
sequence[i] = __VERIFIER_nondet_int (0, 3);
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 < 2; 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++;
__VERIFIER_assert (i == 2);
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; }
if (i != 2)
{
return 0;
}
__VERIFIER_assert (i == 2);
count = 0;
for (i = 0; i < 2; 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 <= (2 * 30));
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t pingmtx = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t pongmtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t pingcv = PTHREAD_COND_INITIALIZER;
pthread_cond_t pongcv = PTHREAD_COND_INITIALIZER;
int minprio;
int maxprio;
int nrmlprio;
int specprio;
int main( int, char **);
void Ping(int *);
void Pong(int *);
static void SchedReport(char *,char *);
int main(
int argc,
char **argv)
{
pthread_attr_t attr;
pthread_t ping;
pthread_t pong;
int pingresult;
int pongresult;
struct sched_param mainsp;
minprio = sched_get_priority_min(SCHED_FIFO);
maxprio = sched_get_priority_max(SCHED_FIFO);
nrmlprio = (minprio + maxprio)/2;
specprio = nrmlprio + 1;
mainsp.sched_priority = nrmlprio;
pthread_setschedparam(pthread_self(),SCHED_FIFO,&mainsp);
pthread_attr_init(&attr);
pthread_attr_setschedpolicy(&attr,SCHED_FIFO);
pthread_attr_setschedparam(&attr,&mainsp);
pthread_create(&ping,&attr,(void *) Ping,&pingresult);
pthread_create(&pong,&attr,(void *) Pong,&pongresult);
sched_yield();
pthread_cond_signal(&pingcv);
pthread_join(ping,0);
pthread_join(pong,0);
printf("ping result=%d\\n","\\e[m",pingresult);
printf("pong result=%d\\n","\\e[m",pongresult);
}
void Ping(int *result)
{
int loop;
int i;
double x;
struct sched_param nrmlsp;
struct sched_param specsp;
nrmlsp.sched_priority= nrmlprio;
specsp.sched_priority= specprio;
for(loop= 0; loop < 100; ++loop) {
pthread_setschedparam(pthread_self(),SCHED_FIFO,&specsp);
SchedReport("\\e[32m","ping");
pthread_cond_signal(&pongcv);
pthread_mutex_lock(&pingmtx);
pthread_cond_wait(&pingcv,&pingmtx);
pthread_mutex_unlock(&pingmtx);
pthread_setschedparam(pthread_self(),SCHED_FIFO,&nrmlsp);
sched_yield();
for(i= 0, x= 0.; i < 10000; ++i) {
x+= sin((double) i*M_PI/10000);
}
}
printf("%sping now trying to exit\\n","\\e[33m"); fflush(stdout);
pthread_cond_signal(&pongcv);
*result= (int) x;
sched_yield();
pthread_exit(0);
}
void Pong(int *result)
{
int loop;
int i;
double x;
struct sched_param nrmlsp;
struct sched_param specsp;
nrmlsp.sched_priority= nrmlprio;
specsp.sched_priority= specprio;
for(loop= 0; loop < 100; ++loop) {
pthread_setschedparam(pthread_self(),SCHED_FIFO,&specsp);
SchedReport("\\e[31m","pong");
pthread_cond_signal(&pingcv);
pthread_mutex_lock(&pongmtx);
pthread_cond_wait(&pongcv,&pongmtx);
pthread_mutex_unlock(&pongmtx);
pthread_setschedparam(pthread_self(),SCHED_FIFO,&nrmlsp);
sched_yield();
for(i= 0, x= 0.; i < 10000; ++i) {
x+= sin((double) i*M_PI/10000);
}
}
printf("%spong now trying to exit\\n","\\e[33m"); fflush(stdout);
pthread_cond_signal(&pingcv);
*result= (int) x;
sched_yield();
pthread_exit(0);
}
static void SchedReport(char *escseq,char *thrdname)
{
struct sched_param sp;
int policy;
pthread_getschedparam(pthread_self(),&policy,&sp);
printf("%s%s : policy=%d<%s> priority=%d\\n",
escseq,thrdname,
policy,
(policy == SCHED_RR)? "rr" :
(policy == SCHED_FIFO)? "fifo" :
(policy == SCHED_OTHER)? "other" : "???",
sp.sched_priority);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t logLock;
int ptapp_logging_init(void)
{
int rv = 0;
FILE *fp;
rv = pthread_mutex_init(&logLock, 0);
_PTAPP_ASSERT_NET_ERROR( (rv == 0), "PTAPP : Error creating logging mutex \\n");
fp = fopen(PTAPP_COMMUNICATION_LOG_FILE_NEW, "w");
if (fp != 0)
{
fclose(fp);
}
fp = fopen(PTAPP_COMMUNICATION_LOG_FILE_OLD, "w");
if (fp != 0)
{
fclose(fp);
}
return 0;
}
int ptapp_message_log(char *message, int length, bool isFromAgent)
{
FILE *fp = 0;
char timeString[PTAPP_MAX_STRING_LENGTH] = { 0 };
time_t logtime;
struct tm *timeinfo;
int i = 0;
struct stat fileStat;
time(&logtime);
timeinfo = localtime(&logtime);
strftime(timeString, PTAPP_MAX_STRING_LENGTH, "%Y-%m-%d %H:%M:%S ", timeinfo);
pthread_mutex_lock(&logLock);
fp = fopen(PTAPP_COMMUNICATION_LOG_FILE_NEW, "a");
if (fp == 0)
{
_PTAPP_LOG(_PTAPP_DEBUG_ERROR, "Log : Unable to open file for logging [%d:%s] \\n",
errno, strerror(errno));
pthread_mutex_unlock(&logLock);
return -1;
}
fputs(timeString, fp);
if (isFromAgent)
{
fputs("Message from Agent \\n", fp);
}
else
{
fputs("Message to Agent \\n", fp);
}
for (i = 0; i < length; i++)
{
fputc(message[i], fp);
}
fputs("\\n", fp);
fclose(fp);
if (stat(PTAPP_COMMUNICATION_LOG_FILE_NEW, &fileStat) == 0)
{
if (PTAPP_COMMUNICATION_LOG_MAX_FILE_SIZE <= fileStat.st_size)
{
if (0 > remove(PTAPP_COMMUNICATION_LOG_FILE_OLD))
{
_PTAPP_LOG(_PTAPP_DEBUG_ERROR, "Log : Unable to remove old file for logging [%d:%s] \\n",
errno, strerror(errno));
}
if (0 > rename(PTAPP_COMMUNICATION_LOG_FILE_NEW, PTAPP_COMMUNICATION_LOG_FILE_OLD))
{
_PTAPP_LOG(_PTAPP_DEBUG_ERROR, "Log : Unable to rename new file to old file for logging [%d:%s] \\n",
errno, strerror(errno));
}
}
}
pthread_mutex_unlock(&logLock);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct thread_info {
double **A_matrix_pointer;
double **B_matrix_pointer;
double **C_matrix_pointer;
int b, d;
int * counter;
int src, dst;
};
void *subsum(void *arg) {
double s = 0;
struct thread_info t1 = *(struct thread_info *) (arg);
for (int i = t1.src; i < t1.dst; i++) {
for (int j = 0; j < t1.d; j++) {
s = 0;
for (int k = 0; k < t1.b; k++) {
s += t1.A_matrix_pointer[i][k] * t1.B_matrix_pointer[k][j];
}
t1.C_matrix_pointer[i][j] = s;
pthread_mutex_lock(&mutex);
(*t1.counter)++;
pthread_mutex_unlock(&mutex);
}
}
}
void mnoz(double **A, int a, int b, double **B, int c, int d, double **C, int N) {
N = N > a ? a : N;
int *status = malloc((N+1) * sizeof(int));
pthread_t *pthread_id = malloc((N+1) * sizeof(pthread_id));
struct thread_info* t1 = malloc((N+1) * sizeof(struct thread_info));
int thread_count = 0;
int counter = 0;
int i, j;
int div = a/N;
int rest = a - (div*N);
int from = 0, to = div;
for(int x = 0; x < N; x++) {
t1[thread_count].A_matrix_pointer = A;
t1[thread_count].B_matrix_pointer = B;
t1[thread_count].C_matrix_pointer = C;
t1[thread_count].src = from;
t1[thread_count].dst = to;
t1[thread_count].d = d;
t1[thread_count].b = b;
t1[thread_count].counter = &counter;
pthread_create(&pthread_id[thread_count], 0, &subsum, &t1[thread_count]);
thread_count++;
from += div;
to += div;
}
if(rest != 0) {
thread_count++;
}
while(counter != a*d) {
printf("%d\\n", counter);
sleep(0.000001);
}
for (i = 0; i < thread_count; i++) {
pthread_join(pthread_id[i], (void **)status[i]);
}
}
void print_matrix(double **A, int m, int n) {
int i, j;
printf("[");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%f ", A[i][j]);
}
printf("\\n");
}
printf("]\\n");
}
void print_sum(double **A, int m, int n) {
double sum = 0, frobenius = 0;
for(int i = 0; i<m; i++) {
for(int j = 0; j< n;j++) {
sum += A[i][j];
frobenius += A[i][j] * A[i][j];
}
}
printf("Suma elementów: %lf\\n", sum);
printf("Miara Frobeniusa: %lf\\n", sqrt(frobenius));
}
int main(int argc, char **argv) {
FILE *fpa;
FILE *fpb;
double **A;
double **B;
double **C;
int ma, mb, na, nb;
int i, j;
double x;
if(argc == 1) {
printf("Proszę podać liczbę kolumn!\\n");
return -1;
}
int N = atoi(argv[1]);
if(N <= 0) {
printf("Liczba wątków nie może być mniejsza lub równa 0!\\n");
return -1;
}
fpa = fopen("A.txt", "r");
fpb = fopen("B.txt", "r");
if (fpa == 0 || fpb == 0) {
perror("Błąd otwarcia pliku");
exit(-10);
}
fscanf(fpa, "%d", &ma);
fscanf(fpa, "%d", &na);
fscanf(fpb, "%d", &mb);
fscanf(fpb, "%d", &nb);
printf("Pierwsza macierz ma wymiar %d x %d, a druga %d x %d\\n", ma, na, mb, nb);
if (na != mb) {
printf("Złe wymiary macierzy!\\n");
return 1;
}
A = malloc(ma * sizeof(double));
for (i = 0; i < ma; i++) {
A[i] = malloc(na * sizeof(double));
}
B = malloc(mb * sizeof(double));
for (i = 0; i < mb; i++) {
B[i] = malloc(nb * sizeof(double));
}
C = malloc(ma * sizeof(double));
for (i = 0; i < ma; i++) {
C[i] = malloc(nb * sizeof(double));
}
printf("Rozmiar C: %dx%d\\n", ma, nb);
for (i = 0; i < ma; i++) {
for (j = 0; j < na; j++) {
fscanf(fpa, "%lf", &x);
A[i][j] = x;
}
}
for (i = 0; i < mb; i++) {
for (j = 0; j < nb; j++) {
fscanf(fpb, "%lf", &x);
B[i][j] = x;
}
}
mnoz(A, ma, na, B, mb, nb, C, N);
printf("C:\\n");
print_matrix(C, ma, nb);
print_sum(C, ma, nb);
for (i = 0; i < na; i++) {
free(A[i]);
}
free(A);
for (i = 0; i < nb; i++) {
free(B[i]);
}
free(B);
for (i = 0; i < nb; i++) {
free(C[i]);
}
free(C);
fclose(fpa);
fclose(fpb);
return 0;
}
| 1
|
#include <pthread.h>
int cur =0;
char content[4] = {'1', '2', '3', '4'};
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t ready = PTHREAD_COND_INITIALIZER;
void *thread_func(void *arg){
int x = (int)arg;
int i;
for(i=0; i<10;i++){
pthread_mutex_lock(&lock);
while(x != cur)
pthread_cond_wait(&ready, &lock);
printf("%c", content[cur]);
cur = (cur+1)%4;
pthread_mutex_unlock(&lock);
pthread_cond_broadcast(&ready);
}
}
int main(int argc, char **argv){
pthread_t tid[4];
int res ;
int i;
if(argc != 2){
printf("usage : a.out how\\n");
exit(-1);
}
cur = atoi(argv[1]);
for(i=0;i<4;i++){
res = pthread_create(&tid[i],0,thread_func,(void *)i);
if(res != 0)
exit(-1);
}
for(i=0;i<4;i++){
pthread_join(tid[i], 0);
}
printf("\\n");
return 0;
}
| 0
|
#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);
if (enqueue_flag)
{
for(
i=0; i<(20); i++)
{
value = __VERIFIER_nondet_int();
enqueue(&queue,value);
stored_elements[i]=value;
}
enqueue_flag=(0);
dequeue_flag=(1);
}
pthread_mutex_unlock(&m);
return 0;
}
void *t2(void *arg)
{
int i;
pthread_mutex_lock(&m);
if (dequeue_flag)
{
for(
i=0; i<(20); i++)
{
if (empty(&queue)!=(-1))
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;
}
| 1
|
#include <pthread.h>
struct data {
char **arr;
int mem_allocated;
double t_alloc, t_free, t_realloc, t_refree, t_total;
};
inline double curr_time(void)
{
struct timeval tv;
gettimeofday(&tv, 0);
return tv.tv_sec * 1e-6 + (double) tv.tv_usec;
}
void * malloc_local(void *args)
{
struct data *p = (struct data *) args;
unsigned long tid;
int i;
tid = pthread_self();
printf(" Thread %lu: malloc\\n", tid);
p->t_alloc = curr_time();
p->arr = malloc(sizeof(char *) * 1);
if (p->arr == 0) {
perror(0);
abort();
}
for (i = 0; i < 1; i++) {
p->arr[i] = (char *) malloc(sizeof(char) * 1048576);
if (p->arr[i] == 0) {
perror(0);
abort();
}
}
p->t_alloc = curr_time() - p->t_alloc;
printf(" Thread %lu: free\\n", tid);
p->t_free = curr_time();
for (i = 0; i < 1; i++)
free(p->arr[i]);
free(p->arr);
p->t_free = curr_time() - p->t_free;
printf(" Thread %lu: re-malloc\\n", tid);
p->t_realloc = curr_time();
p->arr = malloc(sizeof(char *) * 1);
if (p->arr == 0) {
perror(0);
abort();
}
for (i = 0; i < 1; i++) {
p->arr[i] = (char *) malloc(sizeof(char) * 1048576);
if (p->arr[i] == 0) {
perror(0);
abort();
}
}
p->t_realloc = curr_time() - p->t_realloc;
printf(" Thread %lu: re-free\\n", tid);
p->t_refree = curr_time();
for (i = 0; i < 1; i++)
free(p->arr[i]);
free(p->arr);
p->t_refree = curr_time() - p->t_refree;
p->t_total = p->t_alloc + p->t_free + p->t_realloc + p->t_refree;
printf(" Thread %lu: exit\\n", tid);
pthread_exit((void *) 0);
}
pthread_mutex_t mutex;
pthread_cond_t cond;
void * malloc_remote_from(void *args)
{
struct data *p = (void *) args;
unsigned long tid;
int i;
tid = pthread_self();
pthread_mutex_lock(&mutex);
printf(" Thread %lu: malloc\\n", tid);
p->t_alloc = curr_time();
p->arr = (char **) malloc(sizeof(char *) * 1);
if (p->arr == 0) {
perror(0);
abort();
}
for (i = 0; i < 1; i++) {
(p->arr)[i] = (char *) malloc(sizeof(char) * 1048576);
if ((p->arr)[i] == 0) {
perror(0);
abort();
}
}
p->t_alloc = curr_time() - p->t_alloc;
p->mem_allocated = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&mutex);
while (p->mem_allocated == 1)
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
p->t_total = p->t_alloc + p->t_free + p->t_realloc + p->t_refree;
printf(" Thread %lu: exit\\n", tid);
pthread_exit((void *) 0);
}
void * malloc_remote_to(void *args)
{
struct data *p = (void *) args;
unsigned long tid;
int i;
tid = pthread_self();
pthread_mutex_lock(&mutex);
while (p->mem_allocated == 0)
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
printf(" Thread %lu: free\\n", tid);
p->t_free = curr_time();
for (i = 0; i < 1; i++)
free(p->arr[i]);
free(p->arr);
p->t_free = curr_time() - p->t_free;
printf(" Thread %lu: re-malloc\\n", tid);
p->arr = malloc(sizeof(char *) * 1);
if (p->arr == 0) {
perror(0);
abort();
}
for (i = 0; i < 1; i++) {
p->arr[i] = (char *) malloc(sizeof(char) * 1048576);
if (p->arr[i] == 0) {
perror(0);
abort();
}
}
p->t_realloc = curr_time() - p->t_realloc;
printf(" Thread %lu: re-free\\n", tid);
p->t_refree = curr_time();
for (i = 0; i < 1; i++)
free(p->arr[i]);
free(p->arr);
p->t_refree = curr_time() - p->t_refree;
pthread_mutex_lock(&mutex);
p->mem_allocated = 0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
printf(" Thread %lu: exit\\n", tid);
pthread_exit((void *) 0);
}
int main(int argc, char **argv)
{
pthread_t tha, thb;
struct data dat;
int nthreads;
int ret;
nthreads = argc == 1 ? 1 : atoi(argv[1]);
printf("Memory management/migration test (usec)\\n");
if (nthreads == 1) {
printf("One thread...\\n");
pthread_create(&tha, 0, malloc_local, (void *) &dat);
pthread_join(tha, (void **) &ret);
printf(" malloc: %.2f\\n"
" free: %.2f\\n"
" re-malloc: %.2f\\n"
" re-free: %.2f\\n"
" Total: %.2f\\n", dat.t_alloc, dat.t_free,
dat.t_realloc, dat.t_refree, dat.t_total);
}
if (nthreads >= 2) {
printf("Two threads...\\n");
dat.mem_allocated = 0;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
pthread_create(&tha, 0, malloc_remote_from, (void *) &dat);
pthread_create(&thb, 0, malloc_remote_to, (void *) &dat);
pthread_join(tha, (void **) &ret);
pthread_join(thb, (void **) &ret);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
printf(" malloc: %.2f\\n"
" free: %.2f\\n"
" re-malloc: %.2f\\n"
" re-free: %.2f\\n"
" Total: %.2f\\n", dat.t_alloc, dat.t_free,
dat.t_realloc, dat.t_refree, dat.t_total);
}
return 0;
}
| 0
|
#include <pthread.h>
{
double *a;
double *b;
double sum;
int veclen;
} DOTDATA;
DOTDATA dotstr;
pthread_t callThd[4];
pthread_mutex_t mutexsum;
void *dotprod(void *arg)
{
int i, start, end, offset, len ;
double mysum, *x, *y;
offset = (int)arg;
len = dotstr.veclen;
start = offset*len;
end = start + len;
x = dotstr.a;
y = dotstr.b;
mysum = 0;
for (i=start; i<end ; i++)
{
mysum += (x[i] * y[i]);
}
pthread_mutex_lock (&mutexsum);
dotstr.sum += mysum;
pthread_mutex_unlock (&mutexsum);
pthread_exit((void*) 0);
}
int main (int argc, char *argv[])
{
int i;
double *a, *b;
void *status;
pthread_attr_t attr;
a = (double*) malloc (4*100*sizeof(double));
b = (double*) malloc (4*100*sizeof(double));
for (i=0; i<100*4; i++) {
a[i]=1;
b[i]=a[i];
}
dotstr.veclen = 100;
dotstr.a = a;
dotstr.b = b;
dotstr.sum=0;
pthread_mutex_init(&mutexsum, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i=0;i<4;i++)
{
pthread_create( &callThd[i], &attr, dotprod, (void *)i);
}
pthread_attr_destroy(&attr);
for(i=0;i<4;i++) {
pthread_join( callThd[i], &status);
}
printf ("Sum = %f \\n", dotstr.sum);
free (a);
free (b);
pthread_mutex_destroy(&mutexsum);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
extern sigset_t signal_set;
unsigned int bwritten = 0;
pthread_mutex_t bwritten_mutex = PTHREAD_MUTEX_INITIALIZER;
void * http_get(void *arg) {
struct thread_data *td;
int sd;
char *rbuf, *s;
long long dr, dw, i;
long long foffset;
pthread_t tid;
tid = pthread_self();
td = (struct thread_data *)arg;
foffset = td->foffset;
printf("foffset : %d\\n", foffset);
rbuf = (char *)calloc(GETRECVSIZ, sizeof(char));
if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
pthread_exit((void *)1);
}
if ((connect(sd, (const struct sockaddr *)&td->sin, sizeof(struct sockaddr))) == -1) {
pthread_exit((void *)1);
}
if ((send(sd, td->getstr, strlen(td->getstr), 0)) == -1) {
pthread_exit((void *)1);
}
if ((dr = recv(sd, rbuf, GETRECVSIZ, 0)) == -1) {
pthread_exit((void *)1);
}
handleHttpRetcode(rbuf);
if ((strstr(rbuf, "HTTP/1.1 206")) == 0) {
fprintf(stderr, "Something unhandled happened, shutting down...\\n");
exit(1);
}
s = rbuf;
i = 0;
while(1) {
if (*s == '\\n' && *(s - 1) == '\\r' && *(s - 2) == '\\n' && *(s - 3) == '\\r') {
s++;
i++;
break;
}
s++;
i++;
}
td->offset = td->soffset;
if ((dr - i ) > foffset)
dw = pwrite(td->fd, s, (foffset - i), td->soffset);
else
dw = pwrite(td->fd, s, (dr - i), td->soffset);
td->offset = td->soffset + dw;
pthread_mutex_lock(&bwritten_mutex);
bwritten += dw;
pthread_mutex_unlock(&bwritten_mutex);
printf("td->offset : %d\\n", td->offset);
while (td->offset < foffset) {
memset(rbuf, GETRECVSIZ, 0);
dr = recv(sd, rbuf, GETRECVSIZ, 0);
if ((td->offset + dr) > foffset)
dw = pwrite(td->fd, rbuf, foffset - td->offset, td->offset);
else
dw = pwrite(td->fd, rbuf, dr, td->offset);
td->offset += dw;
pthread_mutex_lock(&bwritten_mutex);
bwritten += dw;
pthread_mutex_unlock(&bwritten_mutex);
updateProgressBar(bwritten, td->clength);
}
if (td->offset == td->foffset)
td->status = STAT_OK;
close(sd);
return 0;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.