Your code has some problems:
-
You are currently using “aspas inglesas”
instead of "aspas duplas comuns"
. That does not compile. However, this is also very easy to fix.
-
Your Operacao
function does not use the soma
callback at all. And this callback is always NULL
.
-
The call to pthread_exit
in the main
function is unnecessary because the Operacao
function already does this.
-
In its operation function, you read the number twice, but store both numbers read in the same memory location n
. In this way, the first reading will be discarded and only the result of the second will be used. Since you display n + n
after, it will display double the second value read.
-
It is not good practice (and the compiler can give you a warning) does not use return
in a function whose return type is not void
(and remember which void *
is not the same as void
), even if there is no possible way in which the function could finish its execution normally. The workaround is to set return NULL;
to Operacao
. This does not change the function of this function, but it serves to make the compiler satisfied in cases where it claims to do so.
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 tell the thread at the time of requesting the user:
#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.