我正在尝试pthread示例.这是我的代码:
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void*AsalK1(void *gelen);
int main(){
int *i;
i= new int;
*i=1;
int sonSayi;
pthread_t th1, th2, th3, th4;
printf("---------------------------------------------\n");
printf("| Threadler ile Asal Sayi Bulma |\n");
printf("---------------------------------------------\n");
printf("Son sayi degeri: 1000000 \n");
int r1=pthread_create( &th1, NULL, AsalK1, (void *)i);
*i=3;
int r2=pthread_create( &th2, NULL, AsalK1, (void *)i);
*i=5;
int r3=pthread_create( &th3, NULL, AsalK1, (void *)i);
*i=7;
int r4=pthread_create( &th4, NULL, AsalK1, (void *)i);
pthread_join( th1, NULL);
pthread_join( th2, NULL);
pthread_join( th3, NULL);
pthread_join( th4, NULL);
return 0;
}
void *AsalK1(void *gelen){
int bas= *gelen;
printf("bas :&d\n",bas);
}
Run Code Online (Sandbox Code Playgroud)
我用这段代码编译:
gcc -lpthread ThreadDeneme.cpp
Run Code Online (Sandbox Code Playgroud)
要么
g++ -lpthread ThreadDeneme.cpp
Run Code Online (Sandbox Code Playgroud)
错误说:
无法使用'void'类型的左值初始化'int'类型的变量int bas =*gelen;
我用这个:
int bas =(int*)gelen;
但错误仍在进行中.
我读:
1)你不能解除引用a void *.所以,
int bas= *gelen;
Run Code Online (Sandbox Code Playgroud)
不会起作用.正确的阅读方式int是:
int bas= *(int*)gelen;
Run Code Online (Sandbox Code Playgroud)
2)但这也不会起作用.因为相同的地址i被传递给所有4个线程并导致数据竞争.因此,您需要将不同的地址传递给每个线程,以避免数据争用(或使用某种形式的同步).
3)你的线程函数AsalK1()应该返回一个指针(参见pthread_create()对线程函数的要求).您可以简单地返回一个NULL指针,因为您没有从线程返回任何东西到主线程.
4)另一个潜在的问题是如何编译:
gcc -lpthread ThreadDeneme.cpp
Run Code Online (Sandbox Code Playgroud)
该库应位于命令行选项的末尾.所以,你编译为:
gcc ThreadDeneme.cpp -lpthread
Run Code Online (Sandbox Code Playgroud)
另一个相关的建议:你可以使用数组而不是使用4个不同的线程id变量(th1..4).它允许使用循环来创建和连接线程,您也可以轻松地更改线程数.
| 归档时间: |
|
| 查看次数: |
10645 次 |
| 最近记录: |