| 1 | /*****************************************************************************
|
|---|
| 2 | * FILE: detached.c
|
|---|
| 3 | * DESCRIPTION:
|
|---|
| 4 | * This example demonstrates how to explicitly create a thread in a
|
|---|
| 5 | * detached state. This might be done to conserve some system resources
|
|---|
| 6 | * if the thread never needs to join later. Compare with the join.c program
|
|---|
| 7 | * where the threads are created joinable.
|
|---|
| 8 | * AUTHOR: 01/30/08 Blaise Barney
|
|---|
| 9 | * LAST REVISED: 01/29/09
|
|---|
| 10 | ******************************************************************************/
|
|---|
| 11 | #include "pthread.cvh"
|
|---|
| 12 | #include <civlc.h>
|
|---|
| 13 | #include <stdio.h>
|
|---|
| 14 | #include <stdlib.h>
|
|---|
| 15 | #define NUM_THREADS 4
|
|---|
| 16 |
|
|---|
| 17 | void *BusyWork(void *t)
|
|---|
| 18 | {
|
|---|
| 19 | long i, tid;
|
|---|
| 20 | double result=0.0;
|
|---|
| 21 | tid = (long)t;
|
|---|
| 22 | printf("Thread %ld starting...\n",tid);
|
|---|
| 23 | for (i=0; i<1000000; i++) {
|
|---|
| 24 | result = result + sin(i) * tan(i);
|
|---|
| 25 | }
|
|---|
| 26 | printf("Thread %ld done. Result = %e\n",tid, result);
|
|---|
| 27 | }
|
|---|
| 28 |
|
|---|
| 29 | int main(int argc, char *argv[])
|
|---|
| 30 | {
|
|---|
| 31 | pthread_t thread[NUM_THREADS];
|
|---|
| 32 | pthread_attr_t attr;
|
|---|
| 33 | int rc;
|
|---|
| 34 | long t;
|
|---|
| 35 |
|
|---|
| 36 | /* Initialize and set thread detached attribute */
|
|---|
| 37 | pthread_attr_init(&attr);
|
|---|
| 38 | pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
|
|---|
| 39 |
|
|---|
| 40 | for(t=0;t<NUM_THREADS;t++) {
|
|---|
| 41 | printf("Main: creating thread %ld\n", t);
|
|---|
| 42 | rc = pthread_create(&thread[t], &attr, BusyWork, (void *)t);
|
|---|
| 43 | if (rc) {
|
|---|
| 44 | printf("ERROR; return code from pthread_create() is %d\n", rc);
|
|---|
| 45 | exit(-1);
|
|---|
| 46 | }
|
|---|
| 47 | }
|
|---|
| 48 |
|
|---|
| 49 | /* We're done with the attribute object, so we can destroy it */
|
|---|
| 50 | pthread_attr_destroy(&attr);
|
|---|
| 51 |
|
|---|
| 52 | /* The main thread is done, so we need to call pthread_exit explicitly to
|
|---|
| 53 | * permit the working threads to continue even after main completes.
|
|---|
| 54 | */
|
|---|
| 55 | printf("Main: program completed. Exiting.\n");
|
|---|
| 56 | pthread_exit(NULL);
|
|---|
| 57 | }
|
|---|
| 58 |
|
|---|