linux系统C++多线程

最近接触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);

}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值