473,396 Members | 2,061 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.

socket and pthread

15
Hi all.
I have a socket. I want to create two threads, one is to read from socket, and another is to write to socket. However, I want these two threads to be able to share the same data, so I created a mutex to lock the resource.
I don't know what happens with my two threads, but it always quits after it did some tasks.
Expand|Select|Wrap|Line Numbers
  1. #include "camel.h"
  2. #include "irc.h" 
  3.  
  4. pthread_t         gtid;
  5. pthread_mutex_t   gMutex;
  6.  
  7. // The shared resource between reading and writing thread
  8. char              gSntBuffer[MAX_SIZE_BUFFER];
  9.  
  10. void*
  11. SendRequest( INPUT void* pArg)
  12. {
  13.     int  lsockfd;
  14.     DBGSTR(3,
  15.            STATUS_SUCCESS,
  16.            "FUNCTION ENTRY",
  17.            "")
  18.     lsockfd = (int)pArg;       
  19.     while(1)
  20.     {
  21.         pthread_mutex_lock(&gMutex);
  22.  
  23.         if (gSntBuffer)
  24.         {
  25. #ifdef DBG
  26.             printf("Snt Buffer : %s\n", gSntBuffer);
  27. #endif
  28.             write(lsockfd, gSntBuffer, MAX_SIZE_BUFFER);
  29.         }
  30.  
  31.         pthread_mutex_unlock(&gMutex);
  32.     }
  33.     DBGSTR(3,
  34.            STATUS_SUCCESS,
  35.            "FUNCTION EXIT",
  36.            "")        
  37. }
  38.  
  39. void*
  40. ReceiveReply( INPUT void* pArg)
  41. {
  42.     int   lsockfd = (int)pArg;
  43.     char  lRcvBuffer[MAX_SIZE_BUFFER];
  44.     int   lBytes  = 0;
  45.     DBGSTR(3,
  46.            STATUS_SUCCESS,
  47.            "FUNCTION ENTRY",
  48.            "")    
  49.     while(1)
  50.     {
  51.         lBytes = read(lsockfd, lRcvBuffer, MAX_SIZE_BUFFER);
  52. #ifdef DBG
  53.         printf("Rcv Buffer : %s", lRcvBuffer);
  54. #endif
  55.         // here I have to filter the lRcvBuffer and 
  56.         // then write something back to socket by filling 
  57.         // the gSntBuffer only and let the SendRequest()
  58.         // do the rest of the job.
  59.         // 
  60.  
  61.         // .... CODE HERE
  62.     }
  63.     DBGSTR(3,
  64.            STATUS_SUCCESS,
  65.            "FUNCTION EXIT",
  66.            "")        
  67. }
  68.  
  69. tRtnCode
  70. ConnectIRC( INPUT tProfile profile )
  71. {
  72.     int                lsockfd;
  73.     struct sockaddr_in lservaddr;
  74.     int                lrvalue;
  75.  
  76.     pthread_attr_t     lattr;
  77.  
  78.     DBGSTR(3,
  79.            STATUS_SUCCESS,
  80.            "FUNCTION ENTRY",
  81.            "")           
  82.  
  83.     memset(&lservaddr, 0, sizeof(lservaddr));
  84.     lservaddr.sin_family      = AF_INET;
  85.     lservaddr.sin_port        = htons(profile.port);
  86.     lservaddr.sin_addr.s_addr = inet_addr(profile.server);
  87.  
  88.     if (0 >= (lsockfd = socket(AF_INET, SOCK_STREAM,0)))
  89.     {
  90.         DBGINT(1,
  91.                ERROR_SOCK_CANNOT_CREATE,
  92.                "lsockfd = ",
  93.                lsockfd)
  94.         return (ERROR_SOCK_CANNOT_CREATE);
  95.     }
  96.  
  97.     printf("SendRequest() : losckfd = %d\n", lsockfd);
  98.  
  99.     if (0 < (lrvalue = connect(lsockfd, (struct sockaddr*)&lservaddr, sizeof(lservaddr))))
  100.     {
  101.         DBGINT(1,
  102.                ERROR_SOCK_CANNOT_CONNECT,
  103.                "connect() returns ",
  104.                lrvalue)
  105.         return (ERROR_SOCK_CANNOT_CONNECT);
  106.     }
  107.  
  108.     // set attributes
  109.     pthread_attr_init(&lattr);
  110.     pthread_attr_setdetachstate(&lattr, PTHREAD_CREATE_DETACHED);
  111.     pthread_attr_setscope(&lattr, PTHREAD_SCOPE_SYSTEM);
  112.  
  113.     // init mutex
  114.     pthread_mutex_init(gMutex, NULL);
  115.     pthread_mutex_lock(&gMutex);
  116.  
  117.     snprintf(gSntBuffer, 
  118.              MAX_SIZE_BUFFER,
  119.              IRC_USER,
  120.              profile.username,
  121.              "",
  122.              "",
  123.              profile.fullname,
  124.              profile.nickname);
  125.  
  126.     pthread_mutex_unlock(&gMutex);
  127.  
  128.     // create 2 threads
  129.     // - read data
  130.     // - write data
  131.  
  132.     pthread_create(&gtid, &lattr, SendRequest,  (void*)lsockfd);
  133.     pthread_create(&gtid, &lattr, ReceiveReply, (void*)lsockfd);
  134.  
  135.     DBGSTR(3,
  136.            STATUS_SUCCESS,
  137.            "FUNCTION EXIT",
  138.            "")
  139. }
Sep 28 '09 #1
5 7237
Banfa
9,065 Expert Mod 8TB
It's not in the posted code but you need to ensure that main does not exit (i.e. return) until your threads have finished.
Sep 28 '09 #2
gpraghuram
1,275 Expert 1GB
HI,
R u creating the thread a sdetached or attached thread?
If you are creating it as a attcahed thred the call pthread_join() and return after the call.

Raghu
Sep 29 '09 #3
AmeL
15
Thank gpraghuram
oh yes....you're right. I forget to set the attribute to be JOINABLE, and join them to the main thread, so that the main thread could wait for all of the child threads to be terminated.
Sep 29 '09 #4
AmeL
15
Anyway, how about the same resource shared by two threads ?
I have to use the pthread_mutex_t to lock it right ?
I am not sure when to lock the resource. Let's say, there are 2 threads, one is to write data, and another is to read data, so in either reading or writing, we lock the resource ? or we lock only when we write ?
Sep 29 '09 #5
Banfa
9,065 Expert Mod 8TB
Lock for both reading and writing but for efficiency keep the lock for as short a time as possible.

If you don't lock for reading the writing thread may change the data in the middle of you reading it which could produce very strange results.
Sep 29 '09 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

7
by: lokb | last post by:
Hi, I am creating a detach thread as shown below and caling pthread_create in a while loop where the file names in the directory are fetched and is passed as a parmater to pthread create. The...
0
by: stefvienna | last post by:
Hi group, I'm trying compiling Python-2.4.1 and it fails builing the _socket extension with the following message: building '_socket' extension gcc -pthread -DNDEBUG -g -O3 -Wall...
9
by: nan.li.g | last post by:
Hello, all, I have an interesting problem about stl map and pthread on Linux and g++. The source code is as follows. //mt_map_test.cpp #include <string> #include <map> #include <unistd.h>...
10
by: david wolf | last post by:
The following pthread code cannot compile, I want to know why. Can somebody give me direction on this? if I replace the following line of code status1 = pthread_create(&threadID1, NULL, read,...
1
by: kanchan | last post by:
Hi, I am writing a client for a real time audio streaming server. I am using pthread for that. I have one thread receiving data on a socket from the server. After buffering some data, other thread...
1
by: Yim | last post by:
In below codes, After 10 seconds, function t() was called. So far everything is ok. Then I want to awake blocked read(). So want to exit program. In t(), how to do? (in t(), close(sockfd) don't...
10
by: noleander | last post by:
I've got an application that uses Pthread to do threading. Mostly Im using Condition Variables and the associated function calls: - pthread_cond_wait() - pthread_cond_signal() -...
1
by: Sean | last post by:
Hi, I am trying to write a simple chat/text messaging program but I am having some problems. I am a rookie when it comes to socket programming so I am not sure if I am doing the write thing or...
3
by: Stuart | last post by:
I am in the process of teaching myself socket programming. I am "playing around" with some simple echo server-client programs for m the book TCP/IP Sockets in C. The Server program is: ...
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: 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: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.