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