473,396 Members | 1,843 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

creating a thread

Hi,

I am having difficulty in creating a thread using pthread_create. It
seems that pthread_create does not execute 'program', and returns -1;
I have checked the API but I am not sure why this isn't working.
#include <stdio.h>
#include <pthread.h>

void *program(void *param)
{ char* word = (char*)param;

printf("%s\n", word);
return;
}

int main()
{ int state;
void* program(void*);
pthread_t tid;

char word[] = "word";
state = pthread_create(&tid, NULL, program, (void*)word);
printf("state is: %d", state);
}

Nov 13 '05 #1
7 7824
On Tue, 07 Oct 2003 01:48:53 GMT, mike <mi**@saleweaver.com> wrote in
comp.lang.c:
Hi,

I am having difficulty in creating a thread using pthread_create. It
seems that pthread_create does not execute 'program', and returns -1;
I have checked the API but I am not sure why this isn't working.
#include <stdio.h>
#include <pthread.h>


Sorry, but you're asking in the wrong place. There is no header named
pthread.h in C, nor is there a function named pthread_create. These
are extensions to the language supported by your particular
compiler/operating system combination.

We don't discuss platform specific extensions here, so you will need
to ask about them in a group for your particular platform. Most
likely news:comp.unix.programmer or
news:comp.os.linux.development.apps.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
Nov 13 '05 #2
mike wrote:
Hi,

I am having difficulty in creating a thread using pthread_create.


Your basic problem here is that you are trying to create a thread in the
wrong environment. Try creating it in comp.unix.programmer instead. :-)

<snip>

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #3
Even though this isn't relevant to the group, here are a couple of
examples that may help.
It's a client-server program, well documented.

mike wrote:
Hi,

I am having difficulty in creating a thread using pthread_create. It
seems that pthread_create does not execute 'program', and returns -1;
I have checked the API but I am not sure why this isn't working.
#include <stdio.h>
#include <pthread.h>

void *program(void *param)
{ char* word = (char*)param;

printf("%s\n", word);
return;
}

int main()
{ int state;
void* program(void*);
pthread_t tid;

char word[] = "word";
state = pthread_create(&tid, NULL, program, (void*)word);
printf("state is: %d", state);
}

/*1************************************************ *************************/
/* */
/* Author: PUSHKAR S. PRADHAN */
/* CS6733 - Spring 2001 */
/* Section - 2 */
/* HomeWork 2 */
/* File Name: pradhan-server.cpp */
/* Description: Implements server which listens for file request from */
/* clients. It reads in the file and sends it to the client in parts. */
/************************************************** ************************/
#include <errno.h> // print error no.
#include <fcntl.h> // for open
#include <iostream.h> // cin/cout
#include <pthread.h> // pthread functions
#include <signal.h> // handle signals
#include <siginfo.h> // print signal info.
#include <stdio.h> // perror
#include <string.h> // strcpy, memset
#include <sys/ipc.h> // IPC_CREAT, IPC_NOWAIT
#include <sys/msg.h> // message queues
#include <sys/types.h> // key_t
#include <unistd.h> // getpid, read

using namespace std;

#define NUM_THREADS 5 // max. no. of threads
#define MSGSZ 128 // max. message size
#define VALID 1 // flags for filbuf structure
#define INVALID 0

// Declare the message structure.
typedef struct mesgbuf {
long mtype;
char mtext[MSGSZ];
} message_buf;

typedef struct filbuf {
long mtype;
long valid;
long mlength;
char mtext[MSGSZ];
} file_buf;

void cleanUp(int sig);
void *opFile(void *arg[]); // thread routine

int main () {

int i;
int msqid;
int msgflg = IPC_CREAT | 0666;

pid_t serverPid;
key_t key;
size_t buf_length;
pthread_t tid[NUM_THREADS]; // array of thread IDs

// Use the current process PID to create
// the message queue id for the server
// Also print out the process PID to
// pass it on the commandline to the client
serverPid = getpid();
cout << "process pid: " << serverPid << endl;

key = (int)serverPid;
if ((msqid = msgget(key, msgflg)) < 0) {
perror("server: msgget error:");
cout << msqid << endl;
exit(-1);
}

// server must be killed explicitly using ^C
if( signal(SIGINT, cleanUp) == SIG_ERR) {
perror("server: signal:");
exit(-1);
}

while(1)
{
// create threads
for ( i = 0; i < NUM_THREADS; i++) {
int ret = pthread_create(&tid[i], NULL, opFile, (void *)NULL);
if (ret != 0) {
perror("server: Thread creation error:");
exit(-1);
}
}

// wait for them to complete
for ( i = 0; i < NUM_THREADS; i++) {
if(pthread_join(tid[i], NULL) != 0)
exit(-1);
}

}

} // end of main

/************************************************** **************************/
/* Function to fetch requested file */
/************************************************** **************************/
void *opFile(void *arg[]) {

pid_t x;

key_t tempKey;
key_t key1;

size_t buf_length;

file_buf sbuf; // send file contents
message_buf rbuf; // recv file name and client PID

int i;
int msqid_1;
int msqid_2;
int fs; // file des. for file

char buffer[MSGSZ]; // to read file contents
char fileName[MSGSZ]; // to get requested file name

// set buffer contents to NULL
for(int i = 0; i < MSGSZ; i++) {
memset(&rbuf.mtext[i], '\0', sizeof(char));
memset(&sbuf.mtext[i], '\0', sizeof(char));
}

// connect to the msg. que. created by the server
// to recv file requests
x = getpid();
key1 = (int)x;
if ((msqid_1 = msgget(key1, 0666)) < 0) {
cout << pthread_self() << endl;
perror("server: opFile: msgget:");
cout << msqid_1 << endl;
pthread_exit(NULL);
}

// Recv mesg. of type 1 in rbuf
int bytRecv = msgrcv(msqid_1, &rbuf, MSGSZ, 1, 0);
if(bytRecv < 0) {
cout << pthread_self() << endl;
perror("server: opFile: msgrcv error:");
pthread_exit(NULL);
}

// decode message
int index = 0;
memcpy(&x, (char *)&rbuf.mtext[index], sizeof(x));
index += sizeof(x);

// file name
i = 0;
for(;;) {
fileName[i] = (char)rbuf.mtext[index];
i++;
index++;
if(fileName[i-1] == '\0')
break;
}

cout << "server: opFile: client pid: " << x;
cout << ", File requested: " << fileName << endl;

// connect to the mesg. que. created by the client
// to recv. file contents
tempKey = (int)x;
if ((msqid_2 = msgget(tempKey, 0666)) < 0) {
perror("server: opFile: msgget:");
pthread_exit(NULL);
}

// open file whose contents must be
// sent to the client
if ( (fs = open(fileName, O_RDONLY)) < 0) {
perror("server: opFile: File open error:");

// send a mesg. to the client to inform it
// about this situation
sbuf.mtype = 2;
sbuf.valid = INVALID;
sbuf.mlength = sizeof(sbuf.mlength) + sizeof(sbuf.valid);
buf_length = sizeof(sbuf.mlength) + sizeof(sbuf.valid);
// strncpy(sbuf.mtext, buffer, n);
if (msgsnd(msqid_2, &sbuf, buf_length, 0) < 0)
perror("server: opFile: msgsnd:");

pthread_exit(NULL);
}

// read file contents into a buffer and send them to
// the message que. (created for this) of the client
int n;
while ( (n = read(fs, buffer, sizeof(buffer))) != 0)
{
if (n < 0)
{
perror("server: opFile: Read error:");
pthread_exit(NULL);
}
else
{
sbuf.mtype = 2;
sbuf.valid = VALID;
sbuf.mlength = n + sizeof(sbuf.mlength) + sizeof(sbuf.valid);
strncpy(sbuf.mtext, buffer, n);
buf_length = n + sizeof(sbuf.mlength) + sizeof(sbuf.valid);
// Send file contents until EOF is reached
if (msgsnd(msqid_2, &sbuf, buf_length, 0) < 0) {
perror("server: opFile: msgsnd:");
pthread_exit(NULL);
}
}
}

// send zero length mesg., EOF has been reached
sbuf.mtype = 2;
sbuf.valid = VALID;
sbuf.mlength = sizeof(sbuf.mlength) + sizeof(sbuf.valid);
buf_length = n + sizeof(sbuf.mlength) + sizeof(sbuf.valid);
// For this mesg. the contents are not important
if (msgsnd(msqid_2, &sbuf, buf_length, 0) < 0) {
perror("server: opFile: msgsnd:");
pthread_exit(NULL);
}

return (NULL);
} // function opFile ends

/************************************************** **************************/
/* Function to remove message queue */
/************************************************** **************************/
void cleanUp(int sig) {

int msqid;

pid_t temp = getpid();
key_t key = (int)temp;

psignal(sig, "Received signal:"); // print recv. signal

// connect to the mesg. queue
if ((msqid = msgget(key, 0666)) < 0) {
perror("server: cleanUp: msgget:");
cout << msqid << endl;
exit(-1);
}

// Remove the message queue
if (msgctl(msqid, IPC_RMID, 0) < 0) {
perror("server: cleanUp: msgctl:");
exit(-1);
}

exit(0);
} // function cleanUp ends

/************************************************** ************************/
/* */
/* Author: PUSHKAR S. PRADHAN */
/* CS6733 - Spring 2001 */
/* Section - 2 */
/* HomeWork 2 */
/* File Name: pradhan-client.cpp */
/* Description: This is the client, which requests a file's contents. */
/* The server sends the contents in parts and the client prints them */
/* to the standard output. */
/* The server PID (message queue ID) and the filename are the command */
/* line arguments for this program. */
/************************************************** ************************/
#include <errno.h> // print error no.
#include <iostream.h> // standard output
#include <stdio.h> // perror
#include <stdlib.h> // atoi
#include <string.h> // memset
#include <sys/ipc.h> // IPC_CREAT, IPC_NOWAIT
#include <sys/msg.h> // msgsnd
#include <unistd.h> // getpid

using namespace std;

#define MSGSZ 128 // max. mesg. size
#define VALID 1 // flags for filbuf structure
#define INVALID 0

// Declare the message structures.
typedef struct mesgbuf {
long mtype;
char mtext[MSGSZ];
} message_buf;

typedef struct filbuf {
long mtype;
long valid;
long mlength;
char mtext[MSGSZ];
} file_buf;

int main (int argc, char * argv[]) {

int msqid_1; // to send filename
int msqid_2; // to recv contents
int msgflg = IPC_CREAT | 0666;

pid_t clientPid;

key_t key1;
key_t key2;

message_buf sbuf; // to send file name
file_buf rbuf; // to recv file contents

size_t buf_length;

if (argc != 3) {
// check for valid arguments
cout << "Usage: " << argv[0];
cout << " <server PID> <filename> " << endl;
exit(-1);
}

clientPid = getpid(); // get pid of current process
cout << "client pid: " << clientPid << endl;

// create a separate message queue to recv.
// the file contents from the server
// Use the current process PID for the
// msg. queue id
key2 = (int)clientPid;
if ((msqid_2 = msgget(key2, msgflg)) < 0) {
perror("client: msgget:");
exit(-1);
}

// connect to mesg. que. created by server
key1 = atoi(argv[1]);
if ((msqid_1 = msgget(key1, 0666)) < 0) {
perror("client: msgget:");
cout << msqid_1 << endl;
exit(-1);
}

// set buffer contents to NULL
for(int i = 0; i < MSGSZ; i++)
memset(&sbuf.mtext[i], '\0', sizeof(char));

// create message with client's PID (msg. key)
// and requested filename
sbuf.mtype = 1;
int index = 0;
memcpy(&sbuf.mtext[index], (char *)&clientPid, sizeof(clientPid));
index += sizeof(clientPid);
memcpy(&sbuf.mtext[index], argv[2], strlen(argv[2])+1);
index = index + (strlen(argv[2]) + 1);
buf_length = index;

// Send a message of type 1
if (msgsnd(msqid_1, &sbuf, buf_length, 0) < 0) {
cout << "msgsend: " << msqid_1 << " " << sbuf.mtype << " " <<
sbuf.mtext << "" << buf_length << endl;
perror("client: msgsnd:");
exit(-1);
}
else
cout << "File request sent" << endl;

// o/p contents to terminal
cout << argv[2] << ":" << endl;

// Receive a message of type 2 in rbuf
for(;;) {
int bytRecv = msgrcv(msqid_2, &rbuf,
(MSGSZ+sizeof(rbuf.mlength)+sizeof(rbuf.valid)),
2, 0);
if(bytRecv < 0) {
perror("client: msgrcv error:");
exit(-1);
}

if(rbuf.mlength == sizeof(rbuf.mlength) + sizeof(rbuf.valid)) {
if(rbuf.valid == INVALID)
cout << "no such file" << endl;
else {} // end of file is reached
break;
}

for(int i = 0; i < (bytRecv-sizeof(rbuf.mlength)-sizeof(rbuf.valid)); i++)
cout << rbuf.mtext[i];
}
// Remove the message queue
if (msgctl(msqid_2,IPC_RMID,0) < 0) {
perror("client: msgctl:");
exit(-1);
}

} // end of main

Nov 13 '05 #4
On Mon, 06 Oct 2003 23:17:46 -0500, Pushkar Pradhan wrote:
Even though this isn't relevant to the group, here are a couple of
examples that may help.
It's a client-server program, well documented.


<code snipped>

funny, your code didn't even compile for me!

[sheldon@wsxyz]$ gcc --version
gcc (GCC) 3.3.1
Copyright (C) 2003 Free Software Foundation, Inc.
Dies ist freie Software; die Kopierbedingungen stehen in den Quellen. Es
gibt KEINE Garantie; auch nicht für VERKAUFBARKEIT oder FÜR SPEZIELLE ZWECKE.

[sheldon@wsxyz]$ gcc -Wall -O2 -std=c99 test.c
test.c:13:36: iostream.h: Datei oder Verzeichnis nicht gefunden
test.c:16:46: siginfo.h: Datei oder Verzeichnis nicht gefunden
In file included from test.c:19:
/usr/include/sys/ipc.h:25:3: Warnung: #warning "Files using this header must be compiled with _SVID_SOURCE or
_XOPEN_SOURCE"
test.c:24: error: parse error before "namespace"
test.c:24: Warnung: type defaults to `int' in declaration of `std'
test.c:24: Warnung: data definition has no type or storage class
test.c: In function `main':
test.c:63: error: `cout' undeclared (first use in this function)
test.c:63: error: (Each undeclared identifier is reported only once
test.c:63: error: for each function it appears in.)
test.c:63: error: `endl' undeclared (first use in this function)
test.c:69: Warnung: implicit declaration of function `exit'
test.c:82: Warnung: passing arg 3 of `pthread_create' from incompatible pointer type
test.c:55: Warnung: unused variable `buf_length'
test.c: In function `opFile':
test.c:133: error: `cout' undeclared (first use in this function)
test.c:133: error: `endl' undeclared (first use in this function)
test.c: In function `cleanUp':
test.c:240: Warnung: implicit declaration of function `psignal'
test.c:245: error: `cout' undeclared (first use in this function)
test.c:245: error: `endl' undeclared (first use in this function)
test.c:271:43: iostream.h: Datei oder Verzeichnis nicht gefunden
test.c: At top level:
test.c:279: error: parse error before "namespace"
test.c:279: Warnung: type defaults to `int' in declaration of `std'
test.c:279: Warnung: data definition has no type or storage class
test.c:286: error: redefinition of `struct mesgbuf'
test.c:289: error: redefinition of `message_buf'
test.c:35: error: `message_buf' previously declared here
test.c:291: error: redefinition of `struct filbuf'
test.c:296: error: redefinition of `file_buf'
test.c:42: error: `file_buf' previously declared here
test.c:298: error: redefinition of `main'
test.c:47: error: `main' previously defined here
test.c: In function `main':
test.c:316: error: `cout' undeclared (first use in this function)
test.c:317: error: `endl' undeclared (first use in this function)
[sheldon@wsxyz]$
Nov 13 '05 #5
In article <3F**************@saleweaver.com>, mi**@saleweaver.com says...
Hi,

I am having difficulty in creating a thread using pthread_create. It
seems that pthread_create does not execute 'program', and returns -1;
I have checked the API but I am not sure why this isn't working.


You've been redirected to some other newsgroups, but by far the most
likely to get you the right answer quickly is comp.programming.threads.

--
Randy Howard _o
2reply remove FOOBAR \<,
______________________()/ ()______________________________________________
SCO Spam-magnet: po********@sco.com
Nov 13 '05 #6
Pushkar Pradhan wrote:
Even though this isn't relevant to the group, here are a couple of
examples that may help.


In no particular order,

(1) The question and, consequently, your reply were off-topic.
(2) Your reply was top-posted.
(3) Your reply included attachments.
(4) Your code was written in a programming language different from
the one discussed in this group.
(5) You quoted the entire message in your reply

You have a gift!

Nov 13 '05 #7
mike wrote:
Hi,

I am having difficulty in creating a thread using pthread_create. It
seems that pthread_create does not execute 'program', and returns -1;
I have checked the API but I am not sure why this isn't working.
#include <stdio.h>
#include <pthread.h>

void *program(void *param)
{ char* word = (char*)param;

printf("%s\n", word);
return;
}

int main()
{ int state;
void* program(void*);
pthread_t tid;

char word[] = "word";
state = pthread_create(&tid, NULL, program, (void*)word);
printf("state is: %d", state);
}

----------------------------------------
The value of state = 0, i tried. To execute the function use pthread_join

Nov 13 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Ajay | last post by:
hi! i have an application that runs on a pocket pc. the application has a server which responds to UDP requests. each request contains the address of another server (say, server_b). the pocket...
1
by: Daylor | last post by:
hi. by creating new AppDomain, is that mean, the net framework creating implicitly new thread for that new AppDomain ? second q. thread can only run in one and the same one appdomain ?
5
by: Adam Clauss | last post by:
I am creating a plugin for MS Outlook. Upon clicking a toolbar button, I create series of threads (variable number each time). Within each thread, I start a form using Application.Run(...). This...
6
by: Simon Verona | last post by:
I would normally use code such as : Dim Customer as new Customer Dim t as new threading.thread(AddressOf Customer.DisplayCustomer) Customer.CustomerId=MyCustomerId t.start Which would create...
3
by: EnglishMan69 | last post by:
Hello All, I am using VB2005 Beta 2 in VS 2005 and am running into a small problem. I need to be able to add a picture box to the main form from within a thread. The program goes to a web...
12
by: Mats Lycken | last post by:
Hi, I'm creating a CMS that I would like to be plug-in based with different plugins handling different kinds of content. What I really want is to be able to load/unload plugins on the fly without...
15
by: David Thielen | last post by:
Hi; My ASP.NET app (C# calling J# under .net 2.0) creates a png file in a subdirectory to display as part of the created page. However, the bitmap will not display due to a security violation. ...
13
by: LordHog | last post by:
Hello all, I have a little application that needs to poll a device (CAN communications) every 10 to 15 ms otherwise the hardware buffer might overflow when there are message burst on the bus. I...
5
by: dk60 | last post by:
Here is a problem I encountered concerning threads: Here is the code in Form1 button click handler: AddForm addForm = new AddForm(booksDataSet.Titles); Thread addTitleThread=new Thread(new...
9
by: =?Utf-8?B?YmJn?= | last post by:
Hi all, I read somewhere "using kernel stuff in thread is not good.." if ManualResetEvent object is created in thread but not actually used, will it affect performance? Bob
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.