源C程序
#include
1<stdio.h>
2#include <unistd.h>
3#include <stdlib.h>
4#include <pthread.h>
5void *thread_function(void *arg);
6char message[]="Hello World";
7int main()
8{
9int res;
10pthread_t a_thread;
11void *thread_result;
12res=pthread_create(&a_thread,NULL,thread_function,(void *)message);
13if(res!=0)
14{
15perror("Thread creation failed");
16exit(EXIT_FAILURE);
17}
18printf("Waiting for thread to finish...\n");
19res=pthread_join(a_thread,&thread_result);
20if(res!=0)
21{
22perror("Thread join failed");
23exit(EXIT_FAILURE);
24}
25printf("Thread joined,it returned %s\n",(char *)thread_result);
26printf("Message is now %s\n",message);
27exit(EXIT_SUCCESS);
28}
29void *thread_function(void *arg)
30{
31printf("thread_function is running.Argument was %s\n",arg);
32sleep(3);
33strcpy(message,"bye!");
34pthread_exit("Thank you for the CPU time");
35}
36
37我改写的程序,但编译不通过。
38test.h:
39
40#ifndef __TEST_H__
41#define __TEST_H__
42#include <stdio.h>
43#include <unistd.h>
44#include <stdlib.h>
45#include <pthread.h>
46#include <string.h>
47class test
48{
49public:
50
51int res;
52pthread_t a_thread;
53void *thread_result;
54char message[10];
55void *thread_function(void *arg);
56int start();
57};
58#endif
59
60test.cpp:
61
62#include "Serial1.h"
63main()
64{
65test main;
66main.start();
67}
68
69int test::start()
70{
71char a[]="Hello World";
72strcpy(message,a);
73res=pthread_create(&a_thread,NULL,thread_function,(void *)message);
74if(res!=0)
75{
76perror("Thread creation failed");
77exit(EXIT_FAILURE);
78}
79printf("Waiting for thread to finish...\n");
80res=pthread_join(a_thread,&thread_result);
81if(res!=0)
82{
83perror("Thread join failed");
84exit(EXIT_FAILURE);
85}
86printf("Thread joined,it returned %s\n",(char *)thread_result);
87
88printf("Message is now %s\n",(char *)message);
89exit(EXIT_SUCCESS);
90
91}
92void * test::thread_function(void *arg)
93{
94printf("thread_function is running.Argument was %s\n",arg);
95sleep(3);
96strcpy((char *)arg,"bye!");
97pthread_exit(arg);
98}
99
100请大家帮忙修改,指点!!
101
102\---------------------------------------------------------------
103
104在test的申明中, 把void *thread_function(void *arg); 改为
105static void *thread_function(void *arg); 就可以了
106\---------------------------------------------------------------
107
108因为pthread_create()不是class test的成员函数也不是友元函数。当将class test的成员函数thread_function()以传址方式传递给pthread_create()时,因为pthread_create()无法直接访问class test成员函数,将会出现访问权限错误。加上static后,因为static以面向对象来理解,在某个class中以static修饰的成员都将作为类直接成员,即不再只是类实例(instance)成员处理,这时的类成员跟结构体(struct)中的成员非常相似,就可以以“类名::成员”的方式,以类似全局作用域的方式进行访问。因此就不会出现访问权限错误。</string.h></pthread.h></stdlib.h></unistd.h></stdio.h></pthread.h></stdlib.h></unistd.h></stdio.h>