Ranma344
Ranma344

Reputation: 169

Issue with threads in C

I'm getting an error from my program, which is still a work in progress, and the error is confusing me. The program is one that uses threads to speed up the calculations of the sum of square roots in a number divisible by four. My code is as follows.

#include <pthread.h>
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#define NUM_THREADS 3;
int ARGV;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
int total;


void *calc(int t){
int ttl;
int i;
if (t == 0) {
    for (i == ((ARGV / 4) + 1); i < (ARGV / 2); i++){
        ttl = ttl + sqrt(i);
    }
} else if (t == 1) {
    for (i == ((ARGV / 2) + 1); i < ((3 * ARGV) / 4); i++){
        ttl = ttl + sqrt(i);
    }
} else if (t == 2) {
    for (i == (((3 * ARGV) + 1) / 4); i < ARGV; i++){
        ttl = ttl + sqrt(i);
    }
}
pthread_mutex_lock(&m);
total = total + ttl;
pthread_mutex_unlock;
}

int main(int argc, char* argv[]) {
    int i;
    int ttl;
    ARGV =  atoi(argv[1]);

    pthread_t ti[NUM_THREADS];

    for (i = 0; i < NUM_THREADS; i++) {
        pthread_create(&ti[i], NULL, calc, i);
    }
    for (i == 1; i < (ARGV / 4) ; i++){
            ttl = ttl + sqrt(i);
    }
    for (i = 0; i < NUM_THREADS; i++)   {
        pthread_join(&ti[i], NULL);
    }
    total = total + ttl;
}

The error I'm getting is thr.c:37: error: expected ']' before ';' token, which I don't understand, because the symbol that is expected is there. Any help is greatly appreciated.

Upvotes: 0

Views: 69

Answers (3)

abelenky
abelenky

Reputation: 64730

Do not put semi-colons at the end of your #define statements.

It should be

#define NUM_THREADS 3

All your for loops look wrong:

for (i == ((ARGV / 4) + 1); i < (ARGV / 2); i++)

the double-equal (==) is used to test a value.
So i == ((ARGV/4) + 1); will be true-or-false, depending on the value of i.

Typically, the first statement in a for-loop assigns a value, as in:

for (i = ARGV/4 + 1; i < (ARGV / 2); i++)

(unless you actually mean to test the value of i? for reasons that are not clear)

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182885

#define NUM_THREADS 3;

So:

pthread_t ti[NUM_THREADS];

Expands to:

pthread_t ti[3;];

The ] should be before the ;, as the error says.

Upvotes: 6

Mihai Maruseac
Mihai Maruseac

Reputation: 21460

You should have

#define NUM_THREADS 3

instead of

#define NUM_THREADS 3;

No ; at the end.

That is because the substitution is done textually so thread_t ti[NUM_THREADS]; gets expanded as thread_t ti[3;]; and from here you get the error.

Hint: When macros are involved in the error you can compile with -E and look at the expansions for debugging.

Upvotes: 4

Related Questions