| 1 | /*****************************************************************************
|
|---|
| 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
|
|---|
| 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
|
|---|
| 9 | * if the thread never needs to join later. Compare with the join.cvl program
|
|---|
| 10 | * where the threads are created joinable.
|
|---|
| 11 | * Command line execution:
|
|---|
| 12 | * civl verify -inputNUM_THREADS=4 detached.cvl
|
|---|
| 13 | ******************************************************************************/
|
|---|
| 14 | #include "pthread.cvh"
|
|---|
| 15 | #include <civlc.h>
|
|---|
| 16 | #include <stdio.h>
|
|---|
| 17 | #include <stdlib.h>
|
|---|
| 18 | #include "math.cvh"
|
|---|
| 19 |
|
|---|
| 20 | $input int NUM_THREADS;
|
|---|
| 21 |
|
|---|
| 22 | void *BusyWork(void *t)
|
|---|
| 23 | {
|
|---|
| 24 | long i,tid;
|
|---|
| 25 | double result=0.0;
|
|---|
| 26 | tid = (long)*t;
|
|---|
| 27 | printf("Thread %d starting...\n",tid);
|
|---|
| 28 | for (i=0; i<1000000; i++) {
|
|---|
| 29 | result = result + sin(i) * tan(i);
|
|---|
| 30 | }
|
|---|
| 31 | printf("Thread %d done. Result = %e\n",tid, result);
|
|---|
| 32 | pthread_exit(NULL, false, NULL, 0);
|
|---|
| 33 | }
|
|---|
| 34 |
|
|---|
| 35 | int main(void)
|
|---|
| 36 | {
|
|---|
| 37 | pthread_t thread[NUM_THREADS];
|
|---|
| 38 | pthread_attr_t attr;
|
|---|
| 39 | int rc;
|
|---|
| 40 | long t;
|
|---|
| 41 | long j[NUM_THREADS];
|
|---|
| 42 |
|
|---|
| 43 | /* Initialize and set thread detached attribute */
|
|---|
| 44 | pthread_attr_init(&attr);
|
|---|
| 45 | pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
|
|---|
| 46 |
|
|---|
| 47 | for(t=0;t<NUM_THREADS;t++) {
|
|---|
| 48 | printf("Main: creating thread %d\n", t);
|
|---|
| 49 | j[t] = (long)t;
|
|---|
| 50 | rc = pthread_create(&thread[t], &attr, BusyWork, (void *)&j[t]);
|
|---|
| 51 | if (rc) {
|
|---|
| 52 | $assert($false, "ERROR; return code from pthread_create() is %d", rc);
|
|---|
| 53 | return 0;
|
|---|
| 54 | }
|
|---|
| 55 | }
|
|---|
| 56 |
|
|---|
| 57 | /* We're done with the attribute object, so we can destroy it */
|
|---|
| 58 | pthread_attr_destroy(&attr);
|
|---|
| 59 |
|
|---|
| 60 | /* The main thread is done, so we need to call pthread_exit explicitly to
|
|---|
| 61 | * permit the working threads to continue even after main completes.
|
|---|
| 62 | */
|
|---|
| 63 | printf("Main: program completed. Exiting.\n");
|
|---|
| 64 | pthread_exit(NULL, true, thread, NUM_THREADS);
|
|---|
| 65 | }
|
|---|
| 66 |
|
|---|