fibonacci program c pthread

Solutions on MaxInterview for fibonacci program c pthread by the best coders in the world

showing results for - "fibonacci program c pthread"
Elias
19 Feb 2017
1/*============================================================================
2   Description :The Fibonacci sequence
3  ============================================================================ */
4#include <pthread.h>
5#include <stdio.h>
6#include <stdlib.h>
7
8int n;                          // size of fibonacci sequence.
9int *fibseq;                    // arry holds the value of each fibonacci term.
10int i;                          // counter for the threads.
11
12void *runn(void *arg);
13
14int main(int argc, char *argv[])
15{
16    if (argc != 2)
17    {
18        printf("format is:./a.out <intgervalue>\n");
19        return -1;
20    }                           // valdiate num of args.
21
22    if (atoi(argv[1]) < 0)
23    {
24        printf("%d must be>=0\n", atoi(argv[1]));
25        return -1;
26    }                           // valdiate value of arg1.
27
28    n = atoi(argv[1]);
29    fibseq = (int *)malloc(n * sizeof(int));
30    pthread_t *threads = (pthread_t *) malloc(n * sizeof(pthread_t));
31    pthread_attr_t attr;        // set of thread attribute
32
33    pthread_attr_init(&attr);
34
35    for (i = 0; i < n; i++)
36    {
37        pthread_create(&threads[i], &attr, runn, NULL);
38    }                           // End of creating threads.
39
40    int j;
41
42    for (j = 0; j < n; j++)
43    {
44        pthread_join(threads[j], NULL);
45    }                           // End of wating the threads to exit.
46
47    // printing fibseq.
48    printf("The Fibonacci sequence.:");
49    int k;
50
51    for (k = 0; k < n; k++)
52    {
53        printf("%d,", fibseq[k]);
54    }                           // End of printing fibseq.
55    return 0;
56}                               // End of main.
57
58void *runn(void *arg)
59{
60    if (i == 0)
61    {
62        fibseq[i] = 0;
63        pthread_exit(0);
64    }                           // first fib term
65
66    if (i == 1)
67    {
68        fibseq[i] = 1;
69        pthread_exit(0);
70    }                           // seconed fib term
71    else
72    {
73        fibseq[i] = fibseq[i - 1] + fibseq[i - 2];
74        // printf("fibseq[%d]%d,\n",i,fibseq[i]);
75        pthread_exit(0);        // thread exit.
76    }                           // End of else
77}                               // End of run.