how to create a new thread using carbon c++?

Discussion in 'Mac Programming' started by chidambaram, Apr 3, 2008.

  1. macrumors member

    Joined:
    Mar 9, 2008
    #1
    Hi all,

    I am working in carbon c++ application using XCode in MAC Machine.

    I have to create two new threads in my program.

    How can i create a thread and use it in my program.

    Please give some sample samples.

    Thanks in advance and urgent plz.........
     
  2. Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
  3. thread starter macrumors member

    Joined:
    Mar 9, 2008
    #3
    Thanks for ur reply..

    Is it possible to place function PosixThreadMainRoutine (which in given in the program of your link) in a class.

    If i use that function as member function then following errors will occur

    1. ISO c++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. Say '&MainWindow::posixThreadMainRoutine'

    2. Cannot convert 'void*(MainWindow::*)(void*)' to 'void*(*)(void*)' for argument 3 to int pthread_create(_opaque-pthread_t**,const pthread_attr_t*,void*(*)(void*),void*)'

    In my class i declared the function as

    void * PosixThreadMainRoutine(void*)

    I called that function as

    void MainWindow::posixThreadMainRoutine(void *data)
    {
    printf("This is function");

    }
     
  4. Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #4
    I don't think you can have it call directly into a C++ function, but the callback function can take a pointer to some user data, which you set in the last argument of pthread_create(). I don't have an example but you need to set the argument to "this" and then reference that inside the thread.
     
  5. macrumors G5

    gnasher729

    Joined:
    Nov 25, 2005
    #5
    Find a good tutorial about pthreads. There are plenty on the web. Most explain how to do what you want to do. Here's what you do: Write your class. In the implementation of the class, write a static function (not a class member, a plain static function) posix_thread_func that has the form that you need for the posix thread. In some class member function you will create the thread; that member function will create the posix thread and pass posix_thread_func and its own "this" pointer to the thread creation. As a result, posix_thread_func will be called with "this" as its argument. Cast the argument to the proper class pointer, and you are there.
     

Share This Page