您的位置:首页 > 运维架构 > Linux

linux系统C++多线程

2016-04-27 09:36 691 查看
最近接触c++多线程,在这记录一下遇到的问题:

(1)编译方面:

线程头文件包含#include <pthread.h>,并在编译时添加-lpthread选项来链接线程库。

(2)线程创建函数:

int pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);

传参问题:pthread_create函数由于接口的限定,只接受一个void *型的指针,故传多个参数时得用结构体将其封装再作为整体传递。这样就实现了只通过一个参数传递,然后通过结构指针对结构数据成员的引用实现多参数的传递。(具体实现见下面的例子)

</pre><pre name="code" class="cpp">/* example.cpp*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <iostream>
using namespace std;

struct Data{
int flag;
char* str;

};
void* thread1(void* ptr);

int main(void)
{

struct Data data;
data.flag=10;
data.str="thread";

pthread_t id1;
int ret1;

ret1=pthread_create(&id1,NULL,thread1,&data);
if(ret1!=0){
printf ("Create pthread--1 error!\n");
exit (1);
}

for(int i=0;i<3;i++){
printf("This is the main process.\n");
sleep(1);
}

pthread_join(id1,NULL);
printf("This is the main process.\n");

return (0);
}

void* thread1(void* ptr)
{

struct Data *aa;
aa=(struct Data *)ptr;

int m=(*aa).flag;
char* f=(*aa).str;
printf("m=%d,f=%s \n",m,f);

}
编译命令  g++ example.cpp -o example -lpthread

线程函数:出现error:
argument of type ‘void(类名::~::)()’ does not match ‘void* (*)(void*)’这个问题,找了网上的资料,总结一下就是说,若将线程函数作为类成员函数,而由于类的成员函数中有一个隐形的this指针会作为默认参数传递,故会导致参数类型不匹配。而C++中静态函数没有this指针,所以线程函数写在类里面时必须为静态函数(static),但这样又会带来该线程函数无法访问到类的私有变量,但可以通过函数间接调用解决这一问题。即线程函数(如threadFunction函数)里不直接实现我们想要实现的内容,调用一个真正实现功能的成员变量(function)函数,将this指针作为参数传递给静态函数(threadFunction),这样就可以通过该this指针访问到所有的变量和函数。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
using namespace std;
class Thread{

private:
char *message;
public:
static void *thread_function(void *arg);
void function();
void relize();

};
int main(){
Thread thread;
thread.relize();
printf("this is a thread example");
}

void Thread::relize(){
int res;
pthread_t a_thread;

res=pthread_create(&a_thread,NULL,thread_function,this);
if(res!=0){
perror("Thread creation failed");
exit(EXIT_FAILURE);
}

printf("waiting for thread to finish...  \n");
res=pthread_join(a_thread,NULL);
if(res!=0){
perror("Thread creation failed");
exit(EXIT_FAILURE);
}

}
void Thread::function(){
message="hello world";
printf("message: %s\n",message);
}
void* Thread::thread_function(void* arg){
Thread *th=(Thread*)arg;
th->function();
sleep(1);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: