Your code has some problems:
You’re using in some places “aspas inglesas”
instead of "aspas duplas comuns"
. This then does not compile. However, this is also very easy to arrange.
Its function Operacao
does not use callback soma
for nothing. And that callback is always NULL
.
The call to pthread_exit
in function main
is unnecessary because the function Operacao
already does that.
In its operation function, you read the number twice, but stores both read numbers in the same memory position n
. This way, the first reading will be discarded and only the result of the second will be used. How you display n + n
then it will display double the second read value.
It’s not good practice (and the compiler can give you a Warning) not use the return
in a function whose type of return is not void
(and remember that void *
is not the same as void
), even if there is no possible way by which the function could finish its execution normally. The solution is to put a return NULL;
in function Operacao
. This does not change the functioning of this function, but serves to make the compiler satisfied in cases where he will complain about it.
I think what you wanted was this:
#include <pthread.h>
#include <stdio.h>
void *operacao() {
int a, b;
printf("Digite o primeiro número: ");
scanf("%d", &a);
printf("Digite o segundo número: ");
scanf("%d", &b);
printf("A soma é %d.", a + b);
pthread_exit(NULL);
return NULL; // Nunca é executado.
}
int main() {
pthread_t thread;
printf("Criando uma nova thread\n");
int flag = pthread_create(&thread, NULL, operacao);
if (flag != 0) {
printf("Erro na criação de uma nova thread\n");
return 1;
}
operacao();
return 0;
}
Or, if you want to inform what the thread is at the time of asking the user for input:
#include <pthread.h>
#include <stdio.h>
void *operacao(const char *nome_thread) {
int a, b;
printf("A thread %s pede que você digite o primeiro número: ", nome_thread);
scanf("%d", &a);
printf("A thread %s pede que você digite o segundo número: ", nome_thread);
scanf("%d", &b);
printf("A soma é %d.", a + b);
pthread_exit(NULL);
return NULL; // Nunca é executado.
}
int main() {
pthread_t thread;
printf("Criando uma nova thread\n");
int flag = pthread_create(&thread, NULL, operacao, "auxiliar");
if (flag != 0) {
printf("Erro na criação de uma nova thread\n");
return 1;
}
operacao("principal");
return 0;
}
See here working on ideone.
What language? c++?
– user28595
Note the quotation marks that are not normal quotation marks used in programming, but quotation marks of a text editor Microsoft Word. Take advantage of this correction and also hit indentation for easier reading.
– Isac