int main(int argc, char *argv[]) { pthread_t t1, t2; int loops, s; loops = (argc > 1) ? getInt(argv[1], GN_GT_0, "num-loops") : 10000000; /* Initialize a semaphore with the value 1 */ if (sem_init(&sem, 0, 1) == -1) errExit("sem_init"); /* Create two threads that increment 'glob' */ s = pthread_create(&t1, NULL, threadFunc, &loops); if (s != 0) errExitEN(s, "pthread_create"); s = pthread_create(&t2, NULL, threadFunc, &loops); if (s != 0) errExitEN(s, "pthread_create"); /* Wait for threads to terminate */ s = pthread_join(t1, NULL); if (s != 0) errExitEN(s, "pthread_join"); s = pthread_join(t2, NULL); if (s != 0) errExitEN(s, "pthread_join"); printf("glob = %d\n", glob); exit(EXIT_SUCCESS); }
static void * threadFunc(void *arg) { int cnt = atoi((char *) arg); int s, j; for (j = 0; j < cnt; j++) { sleep(1); /* Code to produce a unit omitted */ s = pthread_mutex_lock(&mtx); if (s != 0) errExitEN(s, "pthread_mutex_lock"); avail++; /* Let consumer know another unit is available */ s = pthread_mutex_unlock(&mtx); if (s != 0) errExitEN(s, "pthread_mutex_unlock"); s = pthread_cond_signal(&cond); /* Wake sleeping consumer */ if (s != 0) errExitEN(s, "pthread_cond_signal"); } return NULL; }
LogQueue& LogQueue::pop(std::pair<int,Msg> &log) { //add mutex int s = pthread_mutex_lock(&m_mutex); if(s != 0) errExitEN(s,"pthread_mutex_lock"); while(m_logs.empty()) { // std::cout << "-------wait------ " << std::endl; s = pthread_cond_wait(&m_cond,&m_mutex); if(s != 0) { // std::cout << "---------s!=0------" <<std::endl; errExitEN(s,"pthread_cond_wait"); } } log = *(m_logs.begin()); m_logs.erase(m_logs.begin()); usleep(1000); s = pthread_mutex_unlock(&m_mutex); // std::cout << "--------pop queue-------" << std::endl; if(s != 0) errExitEN(s,"pthread_mutex_unlock"); return *this; }
int main(int argc, char *argv[]) { pthread_t t1, t2; int s; /* Create two threads, both of which will call one_time_init() */ s = pthread_create(&t1, NULL, threadFunc, (void *) 1); if (s != 0) errExitEN(s, "pthread_create"); s = pthread_create(&t2, NULL, threadFunc, (void *) 2); if (s != 0) errExitEN(s, "pthread_create"); s = pthread_join(t1, NULL); if (s != 0) errExitEN(s, "pthread_join"); printf("First thread returned\n"); s = pthread_join(t2, NULL); if (s != 0) errExitEN(s, "pthread_join"); printf("Second thread returned\n"); exit(EXIT_SUCCESS); }
char * strerror(int err) { int s; char *buf; /* Make first caller allocate key for thread-specific data */ s = pthread_once(&once, createKey); if (s != 0) errExitEN(s, "pthread_once"); buf = pthread_getspecific(strerrorKey); if (buf == NULL) { /* If first call from this thread, allocate buffer for thread, and save its location */ buf = malloc(MAX_ERROR_LEN); if (buf == NULL) errExit("malloc"); s = pthread_setspecific(strerrorKey, buf); if (s != 0) errExitEN(s, "pthread_setspecific"); } if (err < 0 || err >= _sys_nerr || _sys_errlist[err] == NULL) { snprintf(buf, MAX_ERROR_LEN, "Unknown error %d", err); } else { strncpy(buf, _sys_errlist[err], MAX_ERROR_LEN - 1); buf[MAX_ERROR_LEN - 1] = '\0'; /* Ensure null termination */ } return buf; }
static void * /* start function for threads */ threadFunc(void *arg) { int idx = *((int *) arg); int s; sleep(thread[idx].sleepTime); /* Simulate doing some work */ printf("Thread %d terminating\n", idx); s = pthread_mutex_lock(&threadMutex); if (s != 0) errExitEN(s, "pthread_mutex_lock"); numUnjoined++; thread[idx].state = TS_TERMINATED; s = pthread_mutex_unlock(&threadMutex); if (s != 0) errExitEN(s, "pthread_mutex_unlock"); s = pthread_cond_signal(&threadDied); if (s != 0) errExitEN(s, "pthread_cond_signal"); return NULL; }
int main(int argc, char *argv[]) { pthread_t t1, t2; int loops, s; loops = (argc > 1) ? getInt(argv[1], GN_GT_0, "num-loops") : 10000000; s = pthread_create(&t1, NULL, threadFunc, &loops); if (s != 0) errExitEN(s, "pthread_create"); s = pthread_create(&t2, NULL, threadFunc, &loops); if (s != 0) errExitEN(s, "pthread_create"); s = pthread_join(t1, NULL); if (s != 0) errExitEN(s, "pthread_join"); s = pthread_join(t2, NULL); if (s != 0) errExitEN(s, "pthread_join"); printf("glob = %d\n", glob); exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { pthread_t thr; pthread_attr_t attr; int s; s = pthread_attr_init(&attr); /* Assigns default values */ if (s != 0) errExitEN(s, "pthread_attr_init"); s = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); if (s != 0) errExitEN(s, "pthread_attr_setdetachstate"); s = pthread_create(&thr, &attr, threadFunc, (void *) 1); if (s != 0) errExitEN(s, "pthread_create"); s = pthread_attr_destroy(&attr); /* No longer needed */ if (s != 0) errExitEN(s, "pthread_attr_destroy"); s = pthread_join(thr, NULL); if (s != 0) errExitEN(s, "pthread_join failed as expected"); exit(EXIT_SUCCESS); }
static void * threadFunc(void *arg) { int s; void *buf = NULL; /* Buffer allocated by thread */ buf = malloc(0x10000); /* Not a cancellation point */ printf("thread: allocated memory at %p\n", buf); s = pthread_mutex_lock(&mtx); /* Not a cancellation point */ if (s != 0) errExitEN(s, "pthread_mutex_lock"); pthread_cleanup_push(cleanupHandler, buf); while (glob == 0) { s = pthread_cond_wait(&cond, &mtx); /* A cancellation point */ if (s != 0) errExitEN(s, "pthread_cond_wait"); } printf("thread: condition wait loop completed\n"); pthread_cleanup_pop(1); /* Executes cleanup handler */ return NULL; }
static void /* Thread notification function */ threadFunc(union sigval sv) { timer_t *tidptr; int s; tidptr = sv.sival_ptr; printf("[%s] Thread notify\n", currTime("%T")); printf(" timer ID=%ld\n", (long) *tidptr); printf(" timer_getoverrun()=%d\n", timer_getoverrun(*tidptr)); /* Increment counter variable shared with main thread and signal condition variable to notify main thread of the change. */ s = pthread_mutex_lock(&mtx); if (s != 0) errExitEN(s, "pthread_mutex_lock"); expireCnt += 1 + timer_getoverrun(*tidptr); s = pthread_mutex_unlock(&mtx); if (s != 0) errExitEN(s, "pthread_mutex_unlock"); s = pthread_cond_signal(&cond); if (s != 0) errExitEN(s, "pthread_cond_signal"); }
int main(int argc, char *argv[]) { pthread_t thr; int s; void *res; s = pthread_create(&thr, NULL, threadFunc, NULL); if (s != 0) errExitEN(s, "pthread_create"); sleep(3); /* Allow new thread to run a while */ s = pthread_cancel(thr); if (s != 0) errExitEN(s, "pthread_cancel"); s = pthread_join(thr, &res); if (s != 0) errExitEN(s, "pthread_join"); if (res == PTHREAD_CANCELED) printf("Thread was canceled\n"); else printf("Thread was not canceled (should not happen!)\n"); exit(EXIT_SUCCESS); }
static void *threadFunc(void *arg) { int s; void *buf = NULL; // buffer allocated by thread buf = malloc(0x10000); // not a cancellation point printf("thread: allocated memory at %p\n", buf); s = pthread_mutex_lock(&mtx); // not a cancellation point if (s != 0) { errExitEN(s, "pthread_mutex_lock"); } pthread_cleanup_push(cleanupHandler, buf); while (glob == 0) { s = pthread_cond_wait(&cond, &mtx); // a cancellation point if (s != 0) { errExitEN(s, "pthread_cond_wait"); } } printf("thread: condition wait loop completed\n"); pthread_cleanup_pop(1); // does not work because it's a macro with braces // if (1) { // pthread_cleanup_pop(1); // } return NULL; }
int main(int argc, char *argv[]) { pthread_t tid; int s, j; int totRequired; /* Total number of units that all threads will produce */ int numConsumed; /* Total units so far consumed */ Boolean done; time_t t; t = time(NULL); /* Create all threads */ totRequired = 0; for (j = 1; j < argc; j++) { totRequired += atoi(argv[j]); s = pthread_create(&tid, NULL, threadFunc, argv[j]); if (s != 0) errExitEN(s, "pthread_create"); } /* Use a polling loop to check for available units */ numConsumed = 0; done = FALSE; for (;;) { s = pthread_mutex_lock(&mtx); if (s != 0) errExitEN(s, "pthread_mutex_lock"); while (avail > 0) { /* Consume all available units */ /* Do something with produced unit */ numConsumed ++; avail--; printf("T=%ld: numConsumed=%d\n", (long) (time(NULL) - t), numConsumed); done = numConsumed >= totRequired; } s = pthread_mutex_unlock(&mtx); if (s != 0) errExitEN(s, "pthread_mutex_unlock"); if (done) break; /* Perhaps do other work here that does not require mutex lock */ } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int s, idx; if (argc < 2 || strcmp(argv[1], "--help") == 0) usageErr("%s nsecs...\n", argv[0]); thread = calloc(argc - 1, sizeof(*thread)); if (thread == NULL) errExit("calloc"); /* Create all threads */ for (idx = 0; idx < argc - 1; idx++) { thread[idx].sleepTime = getInt(argv[idx + 1], GN_NONNEG, NULL); thread[idx].state = TS_ALIVE; s = pthread_create(&thread[idx].tid, NULL, threadFunc, &idx); if (s != 0) errExitEN(s, "pthread_create"); } totThreads = argc - 1; numLive = totThreads; /* Join with terminated threads */ while (numLive > 0) { s = pthread_mutex_lock(&threadMutex); if (s != 0) errExitEN(s, "pthread_mutex_lock"); while (numUnjoined == 0) { s = pthread_cond_wait(&threadDied, &threadMutex); if (s != 0) errExitEN(s, "pthread_cond_wait"); } for (idx = 0; idx < totThreads; idx++) { if (thread[idx].state == TS_TERMINATED){ s = pthread_join(thread[idx].tid, NULL); if (s != 0) errExitEN(s, "pthread_join"); thread[idx].state = TS_JOINED; numLive--; numUnjoined--; printf("Reaped thread %d (numLive=%d)\n", idx, numLive); } } s = pthread_mutex_unlock(&threadMutex); if (s != 0) errExitEN(s, "pthread_mutex_unlock"); } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int s, numThreads; long threadNum; pthread_t *tid; if (argc != 3 || strcmp(argv[1], "--help") == 0) usageErr("%s num-barriers num-threads\n", argv[0]); numBarriers = atoi(argv[1]); numThreads = atoi(argv[2]); /* Allocate array to hold thread IDs */ tid = calloc(sizeof(pthread_t), numThreads); if (tid == NULL) errExit("calloc"); /* Initialize the barrier. The final argument specifies the number of threads that must call pthread_barrier_wait() before any thread will unblock from that call. */ s = pthread_barrier_init(&barrier, NULL, numThreads); if (s != 0) errExitEN(s, "pthread_barrier_init"); /* Create 'numThreads' threads */ for (threadNum = 0; threadNum < numThreads; threadNum++) { s = pthread_create(&tid[threadNum], NULL, threadFunc, (void *) threadNum); if (s != 0) errExitEN(s, "pthread_create"); } /* Each thread prints a start-up message. We briefly delay, and then print a newline character so that an empty line appears after the start-up messages. */ usleep(100000); printf("\n"); /* Wait for all of the threads to terminate */ for (threadNum = 0; threadNum < numThreads; threadNum++) { s = pthread_join(tid[threadNum], NULL); if (s != 0) errExitEN(s, "pthread_join"); } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct sigevent sev; struct itimerspec ts; timer_t *tidlist; int s, j; if (argc < 2) usageErr("%s secs[/nsecs][:int-secs[/int-nsecs]]...\n", argv[0]); tidlist = calloc(argc - 1, sizeof(timer_t)); if (tidlist == NULL) errExit("malloc"); sev.sigev_notify = SIGEV_THREAD; /* Notify via thread */ sev.sigev_notify_function = threadFunc; /* Thread start function */ sev.sigev_notify_attributes = NULL; /* Could be pointer to pthread_attr_t structure */ /* Create and start one timer for each command-line argument */ for (j = 0; j < argc - 1; j++) { itimerspecFromStr(argv[j + 1], &ts); sev.sigev_value.sival_ptr = &tidlist[j]; /* Passed as argument to threadFunc() */ if (timer_create(CLOCK_REALTIME, &sev, &tidlist[j]) == -1) errExit("timer_create"); printf("Timer ID: %ld (%s)\n", (long) tidlist[j], argv[j + 1]); if (timer_settime(tidlist[j], 0, &ts, NULL) == -1) errExit("timer_settime"); } /* The main thread waits on a condition variable that is signaled on each invocation of the thread notification function. We print a message so that the user can see that this occurred. */ s = pthread_mutex_lock(&mtx); if (s != 0) errExitEN(s, "pthread_mutex_lock"); for (;;) { s = pthread_cond_wait(&cond, &mtx); if (s != 0) errExitEN(s, "pthread_cond_wait"); printf("main(): expireCnt = %d\n", expireCnt); } }
int main(int argc,char *argv[]) { pthread_t thr; void *res; int s; s = pthread_create(&thr,NULL,threadFunc,NULL); if (s != 0) { errExitEN(s,"pthread_create"); } sleep(2); /* Give threaed a chance to get started */ if (argc == 1) /* Cancel thread */ { printf("main: about to cancel thread\n"); s = pthread_cancel(thr); if (s != 0) { errExitEN(s,"pthread_cancel"); } } else { printf("main: about to signal condition variable\n"); glob = 1; s = pthread_cond_signal(&cond); if (s != 0) { errExitEN(s,"pthread_cond_signal"); } } s = pthread_join(thr,&res); if (s != 0) { errExitEN(s,"pthread_join"); } if (res == PTHREAD_CANCELED) { printf("main: thread was canceled\n"); }else { printf("main: thread terminated normally\n"); } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { struct passwd pwd; struct passwd *result; char *buf; size_t bufSize; int s; if (argc != 2 || strcmp(argv[1], "--help") == 0) usageErr("%s username\n", argv[0]); bufSize = sysconf(_SC_GETPW_R_SIZE_MAX); buf = malloc(bufSize); if (buf == NULL) errExit("malloc %d", bufSize); s = getpwnam_r(argv[1], &pwd, buf, bufSize, &result); if (s != 0) errExitEN(s, "getpwnam_r"); if (result != NULL) printf("Name: %s\n", pwd.pw_gecos); else printf("Not found\n"); exit(EXIT_SUCCESS); }
static void *thread_func(void *arg) { int s, sig; sigset_t set; Boolean blocked; char buf[2049]; sig = (int) arg; sigemptyset(&set); sigaddset(&set, sig); s = pthread_sigmask(SIG_BLOCK, &set, NULL); if (s != 0) errExitEN(s, "pthread_sigmask"); for (;;) { sleep(1); sigpending(&set); snprintf(buf, 2049, "%ld: Signal pending: ", (long) pthread_self()); blocked = FALSE; for (sig = 1; sig < NSIG; sig++) { if (sigismember(&set, sig)) { if (blocked == TRUE) strncat(buf, ", ", 2048); else blocked = TRUE; strncat(buf, strsignal(sig), 2048); } } if (blocked == FALSE) strncat(buf, "<empty signal set>", 2048); buf[2048] = '\0'; printf("%s\n", buf); } }
LogQueue& LogQueue::push(int conn,Msg &log) { //add mutex // std::cout << "-------push queue-------" << std::endl; int s = pthread_mutex_lock(&m_mutex); if(s != 0) errExitEN(s,"pthread_mutex_lock"); // m_logs.insert(std::make_pair(conn,log)); usleep(1000); s = pthread_mutex_unlock(&m_mutex); // std::cout << "--------push queue end------" << std::endl; if(s != 0) errExitEN(s,"pthread_mutex_unlock"); s = pthread_cond_signal(&m_cond); if(s != 0) errExitEN(s, "pthread_cond_signal"); return *this; }
int main(int argc, char **argv) { pthread_t thr; void *res; int s; s = pthread_create(&thr, NULL, threadFunc, "Hello world\n"); if (s != 0) errExitEN(s, "pthread_create"); printf("Message from main()\n"); s = pthread_join(thr, &res); if (s != 0) errExitEN(s, "pthread_join"); printf("Thread returned %ld\n", (long) res); exit(EXIT_SUCCESS); }
static int one_time_init(struct once_struct *once_control, void (*init)(void)) { int s; s = pthread_mutex_lock(&(once_control->mtx)); if (s == -1) errExitEN(s, "pthread_mutex_lock"); if (!once_control->called) { (*init)(); once_control->called = 1; } s = pthread_mutex_unlock(&(once_control->mtx)); if (s == -1) errExitEN(s, "pthread_mutex_unlock"); return 0; }
int main(int argc, char *argv[]) { pthread_t t; int s; char *str; str = strerror(EINVAL); printf("Main thread has called strerror()\n"); s = pthread_create(&t, NULL, threadFunc, NULL); if (s != 0) errExitEN(s, "pthread_create"); s = pthread_join(t, NULL); if (s != 0) errExitEN(s, "pthread_join"); printf("Main thread: str (%p) = %s\n", str, str); exit(EXIT_SUCCESS); }
static void /* One-time key creation function */ createKey(void) { int s; /* Allocate a unique thread-specific data key and save the address of the destructor for thread-specific data buffers */ s = pthread_key_create(&strerrorKey, destructor); if (s != 0) errExitEN(s, "pthread_key_create"); }
int main(int argc, char *argv[]) { pthread_t t1, t2; sigset_t set; int s; sigemptyset(&set); sigaddset(&set, SIGINT); s = pthread_sigmask(SIG_BLOCK, &set, NULL); if (s != 0) errExitEN(s, "pthread_sigmask"); s = pthread_create(&t1, NULL, thread_func, (void *) SIGUSR1); if (s != 0) errExitEN(s, "pthread_sigmask"); s = pthread_create(&t2, NULL, thread_func, (void *) SIGUSR2); if (s != 0) errExitEN(s, "pthread_sigmask"); sleep(2); s = pthread_kill(t1, SIGINT); printf("Sent SIGINT to Thread 1\n"); sleep(1); s = pthread_kill(t2, SIGINT); printf("Sent SIGINT to Thread 2\n"); sleep(1); s = pthread_kill(t1, SIGUSR1); printf("Sent SIGUSR1 to Thread 1\n"); sleep(1); s = pthread_kill(t2, SIGUSR2); printf("Sent SIGUSR2 to Thread 2\n"); sleep(1); return 0; }
static void *threadFunc(void *arg) { int loops = *((int*)arg); int loc, j,s; for(j = 0 ; j < loops ; j++) { s = pthread_mutex_lock(&mtx); if(s!=0) errExitEN(s, "pthread_mutex_lock"); loc = glob; loc++; glob = loc; //glob++; s = pthread_mutex_unlock(&mtx); if(s!=0) errExitEN(s, "pthread_mutex_unlock"); } return NULL; }
static void /* Free memory pointed to by 'arg' and unlock mutex */ cleanupHandler(void *arg) { int s; printf("cleanup: freeing block at %p\n", arg); free(arg); printf("cleanup: unlocking mutex\n"); s = pthread_mutex_unlock(&mtx); if (s != 0) errExitEN(s, "pthread_mutex_unlock"); }
ssize_t jwritev(int fd, const struct iovec *iov, int iovcnt) { int i; ssize_t write_len, total; total = 0; for (i = 0; i < iovcnt; ++i) { write_len = write(fd, iov[i].iov_base, iov[i].iov_len); if (write_len == -1) { errExitEN(-1, "jwritev.write"); } total += write_len; } return total; }
static void cleanupHandler(void *arg) { int s; printf("Cleanup: freeing block at %p\n", arg); free(arg); printf("Cleanup: unlocking mutex\n"); s = pthread_mutex_unlock(&mtx); if (s != 0) { errExitEN(s, "pthread_mutex_unlock"); } }
static void * /* Loop 'arg' times incrementing 'glob' */ threadFunc(void *arg) { int loops = *((int *) arg); int loc, j, s; for (j = 0; j < loops; j++) { s = pthread_mutex_lock(&mtx); if (s != 0) errExitEN(s, "pthread_mutex_lock"); loc = glob; loc++; glob = loc; s = pthread_mutex_unlock(&mtx); if (s != 0) errExitEN(s, "pthread_mutex_unlock"); } return NULL; }