threads

I declared my thread t in myClass and trying to create it from the main. How can I do this? I m not sure how to write &t part and reach to thread_Func in the myClass? THanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 

Class myClass{ 
public:
pthread_t t; 

void* thread_Func(void *arg)
{
	
	//some code
}


} 
int main(int argc, char** argv) 
{ 
thread_create(&t, NULL,thread_func, (void *)j); 

return 0; 
} 
Use standard C++ threads, perhaps?
http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-1-starting-threads.html

For instance:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <thread>
#include <string>
#include <atomic>
#include <chrono>
#include <future>

struct my_class
{
    int thread_fun( std::string name, int cnt ) const
    {
        name += suffix ;
        name += ' ' ;
        
        for( int i = 0 ; i < cnt ; ++i )
        {
            std::cout << name << std::flush ;
    
            static std::atomic<int> n(0) ;
            if( ++n%20 == 0 ) std::cout << std::endl ; 

            std::this_thread::sleep_for( std::chrono::milliseconds(5) ) ;
        }
        
        return cnt ;
    }
    
    char suffix ;
};

int main()
{
    my_class mc[5] { {'.'}, {'!'}, {'*'}, {'+'}, {'$'} } ;
    auto fn = &my_class::thread_fun ;
    std::thread threads[] = { std::thread( fn, mc, "one", 10 ), std::thread( fn, mc+1, "two", 15 ), std::thread( fn, mc+2, "three", 20 ) } ;
    std::future<int> futures[] = { std::async( std::launch::async, fn, mc+3, "four", 25 ), std::async( std::launch::async, fn, mc+4, "five", 30 ) } ;
    
    for( std::thread& t : threads ) t.join() ;
    for( auto& f : futures ) f.wait() ;
}

http://coliru.stacked-crooked.com/a/bdbf775c9ab8b08f
thanks. but i cannot use bind() I do not use C++11 I use an older version.
I tried this thread_create(&mc.t, NULL, mc.thread_func, (void*)j); but did not work out. and also i m sure i pass the j correctly because my methods header is void* thread_func(void *arg).
thanks
> I do not use C++11 I use an older version.

Make the thread function static. Something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
struct my_class
{
      pthread_t t; 

      static void* thread_Func( void* arg )
      {
	  my_class* object = static_cast< my_class* >(arg) ;
          // use object
          int i = object->i ;
 
	  //some code

          return 0 ; 
      }
     
     int i ;
     // ...
}; 

int main() 
{ 
    static my_class mc ;
    mc.i = 7 ;
    
    int status = pthread_create( &mc.t, NULL, &my_class::thread_func, &mc ) ;
    
    // ...
}
Topic archived. No new replies allowed.