473,765 Members | 1,977 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Thread-Safety in Functions: A Random String Generator

Greetings everyone,

Here is a random string generator I wrote for an application
and I'm wondering about the thread-safety of this function.
I was told using static and global variables cause
potential problems for thread-safety. So far, I'm only confused.
I need a proper explanation for the concept so I can understand how
to write thread-safe functions in the future.

My apologies for posting a long routine.

#include <stdlib.h>
#include <time.h>

/* ---( PRIVATE )--- */
#define RANDSTR_MIN 32
#define RANDSTR_MAX 126
#define RANDSTR_RANGE ((RANDSTR_MAX + 1) - RANDSTR_MIN) + RANDSTR_MIN

char *
garbage (
char * buf, /* pointer to the buffer that will contain the garbage */
size_t count, /* including the last null character. */
const char * chrs /* character range used */
)
{
char * eosbuf = buf;
const char * eoschrs = NULL;
time_t timeval;

/* static & 0 IMPORTANT! Thread-safe? */
static unsigned int seed = 0;
/* (A)
* If the seed is 0 (not created yet), we generate a seed.
*/
if (seed == 0)
{
timeval = time((time_t*)N ULL);

/*
* check if time is available on system
*/
if (timeval == (time_t)-1)
return (NULL);
seed = (unsigned) timeval;

/*
* Seed the random number generation algo, so we can call rand()
*/
srand (seed);
}
/* (B)
* if chrs is an empty string, choose our own range
* of characters from ASCII 32 to ASCII 126
*/
if (NULL == chrs || '\0' == *chrs)
{
/* generate only the required number of characters */
while (count-- > 1)
*eosbuf++ = (char) (rand () % RANDSTR_RANGE);
}
/* we are using a user-specified range. */
else
{
eoschrs = chrs;

/* get a pointer to point to the last character '\0' of the range.
*/
while (*eoschrs)
++eoschrs;

/* generate the random string. MAX == length of range. */
while (count-- > 1)
*eosbuf++ = *(chrs + (rand () % (size_t)(eoschr s - chrs)));
}
/* (C)
* Important: terminate the string!
*/
*eosbuf = (char) '\0';
/* (D)
* Return pointer to the buffer.
*/
return (buf);
}
Sample Usage:
=============
char buf[11]; /* 10 chars + 1 '\0' */

garbage (
buf,
sizeof (buf),
"0aA1bB2cC3dD4e E5fF6gG7hH8iI9j Jk9Kl8Lm7Mn6No5 Op4Pq3Qr2Rs1StT 0uVvWwXxYyZz"
);

puts (buf);
Regards,
Jonathan.
Nov 14 '05 #1
4 6652

On Thu, 6 Jan 2005, Jonathan Burd wrote:

Here is a random string generator I wrote for an application
and I'm wondering about the thread-safety of this function.
I was told using static and global variables cause
potential problems for thread-safety. So far, I'm only confused.
I need a proper explanation for the concept so I can understand how
to write thread-safe functions in the future.
"Thread safety" generally just means that you need to make sure
that if two or more threads are calling this function at the same
time, nothing bad will happen. "Bad," in this context, means
"undefined behavior."
(In fact, in this newsgroup we don't even have the concept of
"threading, " which is not provided by standard C. You might get
much better answers if you asked in a newsgroup devoted to your
particular platform and/or thread model. So take everything I say
below --- and everything anyone else in this newsgroup says in this
thread --- with a large grain of salt.)
My apologies for posting a long routine.
My apologies for posting a long response. ;)
#include <stdlib.h>
#include <time.h>
Coding note 1:
Your "sample usage" requires #include <stdio.h> as well.
/* ---( PRIVATE )--- */
#define RANDSTR_MIN 32
#define RANDSTR_MAX 126
#define RANDSTR_RANGE ((RANDSTR_MAX + 1) - RANDSTR_MIN) + RANDSTR_MIN
Coding note 2:
For the benefit of your code's maintainer, put in the extra parentheses
around the whole expression in the definition of 'RANDSTR_RANGE' . That
way, when he writes 'half = RANDSTR_RANGE/2', he won't be surprised at
the result.
...Wait! On second glance, this is utterly stupid! You're not
using this macro as a "range" at all, but as a kind of half-calculation!
Save the obfuscated text-substitution stunts for the IOCCC, please.
char *
garbage (
Style note 1: 'garbage'?!
char * buf, /* pointer to the buffer that will contain the garbage */
size_t count, /* including the last null character. */
const char * chrs /* character range used */
)
{
char * eosbuf = buf;
const char * eoschrs = NULL;
time_t timeval;

/* static & 0 IMPORTANT! Thread-safe? */
static unsigned int seed = 0;
Thread-safety note 1:
The above line is thread-safe. But the 'if' statement below is not
really what you want. First of all, suppose you do generate a random
seed, and that seed turns out to be 0? Then you keep generating new
seeds. So your random number generator has a bias, which is just
intrinsically a Bad Thing.
And here's the thread-safety part: Suppose Thread A calls this
function, and 'seed' has not been initialized. Then Thread A enters
the 'if' body, and calls 'time'. Meanwhile, Thread B has called this
function also, and since 'seed' is still zero (Thread A hasn't changed
it yet), Thread B enters the 'if' body. Then we have a "race condition"
(look it up) on the assignment to 'seed' --- a harmless one in this
case (on some implementations ), perhaps, but a race condition
nevertheless. So you need to (at least!) look up "mutex" and figure
out how to apply it to 'seed'. Or continue reading, and I'll show you
a Standard-conforming way to avoid the problem.
/* (A)
* If the seed is 0 (not created yet), we generate a seed.
*/
if (seed == 0)
{
timeval = time((time_t*)N ULL);
Coding note 3:
The cast is redundant and distracts the reader from what's really
happening. I won't flag the other redundant and bogus casts in this
function, but remember that casts are hardly ever necessary in C.
/*
* check if time is available on system
*/
if (timeval == (time_t)-1)
return (NULL);
Style note 2: 'return' is not a function. I suggest you follow
widespread modern style in omitting the redundant parentheses.
seed = (unsigned) timeval;

/*
* Seed the random number generation algo, so we can call rand()
*/
srand (seed);
Thread-safety note 2:
Another possible race condition; 'srand' may not be thread-safe
itself. In general, if you use any library function in your threaded
code, you need to look it up to see whether it's guaranteed to be
thread-safe on your particular implementation. Usually (IMLE), functions
like 'sin' and 'time' will be safe; functions like 'printf' will be
safe but might give funny output if you call them with two threads at
once; and functions like 'strtok' and 'srand' probably won't be.
}
/* (B)
* if chrs is an empty string, choose our own range
* of characters from ASCII 32 to ASCII 126
*/
if (NULL == chrs || '\0' == *chrs)
{
/* generate only the required number of characters */
while (count-- > 1)
Style note 3: Ick.
*eosbuf++ = (char) (rand () % RANDSTR_RANGE);
Coding note 4: See the FAQ about how to generate "nice" random numbers.
Modding by the range is often not the best way to do it.
}
/* we are using a user-specified range. */
else
{
eoschrs = chrs;

/* get a pointer to point to the last character '\0' of the range.
*/
while (*eoschrs)
++eoschrs;
Coding note 5: Why use a hand-coded loop when your implementation
provides optimized assembly versions of 'strlen' and 'strchr' for
exactly this purpose? [Use eoschrs=chrs+st rlen(chrs) or
eoschrs=strchr( chrs,'\0') instead of the loop.]
/* generate the random string. MAX == length of range. */
while (count-- > 1)
*eosbuf++ = *(chrs + (rand () % (size_t)(eoschr s - chrs)));
In fact, you never use the value of 'eoschrs' /per se/ at all;
just write 'size_t len = strlen(chrs);' and use 'len' in place
of '(size_t)(eosch rs - chrs)' here.
}
/* (C)
* Important: terminate the string!
*/
*eosbuf = (char) '\0';
Coding note 6: What if count==0?

/* (D)
* Return pointer to the buffer.
*/
return (buf);
}
Sample Usage:
=============
char buf[11]; /* 10 chars + 1 '\0' */

garbage (
buf,
sizeof (buf),
"0aA1bB2cC3dD4e E5fF6gG7hH8iI9j Jk9Kl8Lm7Mn6No5 Op4Pq3Qr2Rs1StT 0uVvWwXxYyZz"
);

puts (buf);

Now for the standard method I promised. Instead of using a single
static variable in the function itself (which means one variable shared
by all the threads and therefore needing to be protected from race
conditions), just use one variable per thread. The way we do that is
to have each thread store its own copy of the "state" of the function,
and pass that state as a parameter, like this: [UNTESTED CODE]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define RANDSTR_MIN 32
#define RANDSTR_MAX 126

typedef struct {
unsigned int seed;
} rndstr_state;

char *rndstr(char *buf, size_t buflen, const char *chrs, rndstr_state *state)
{
size_t i, m;

if (state->seed == 0)
{
time_t timeval = time(NULL);
if (timeval == (time_t)-1)
return NULL;
state->seed = timeval;
/*
Note: |srand| is probably still not thread-safe. You
may need to find a third-party PRNG that will fit your
needs, and use it here. Its state information must be
kept in the |rndstr_state| struct as well.
*/
srand(state->seed);
}

if (NULL == chrs || '\0' == *chrs)
chrs = " !\"#$%&'()*+,-./0123456789:;<=> ?@"
"ABCDEFGHIJKLMN OPQRSTUVWXYZ[\]^_`ab"
"cdefghijklmnop qrstuvwxyz{|}~" ;

m = strlen(chrs);
if (buflen <= 0)
return buf;
for (i=0; i < buflen-1; ++i)
buf[i] = chrs[rand() % m];
buf[i] = '\0';

return buf;
}
Sample Usage:
=============
char buf[11]; /* 10 chars + 1 '\0' */
rndstr_state state = {0};
rndstr(
buf,
sizeof (buf),
"0aA1bB2cC3dD4e E5fF6gG7hH8iI9j Jk9Kl8Lm7Mn6No5 Op4Pq3Qr2Rs1StT 0uVvWwXxYyZz",
&state
);

puts(buf);
-Arthur
Nov 14 '05 #2
Arthur J. O'Dwyer wrote:

On Thu, 6 Jan 2005, Jonathan Burd wrote:
[...]

-Arthur


:) I love when my code gets thrashed. Heh. Thanks for those tips. They
are invaluable. I get an opportunity to improve.
Nov 14 '05 #3
Jonathan Burd wrote:
Here is a random string generator [that] I wrote for an application.
I'm wondering about the thread-safety of this function.
I was told using static and global variables
[can] cause potential problems for thread-safety.
So far, I'm only confused.
I need a proper explanation for the concept [of thread safety]
so [that] I can understand how to write thread-safe functions in the future.

My apologies for posting a long routine. cat garbage.c

#include <stdlib.h>
#include <time.h>

/* ---( PRIVATE )--- */
#define RANDSTR_MIN 32
#define RANDSTR_MAX 126
#define RANDSTR_RANGE \
((RANDSTR_MAX + 1) - RANDSTR_MIN) + RANDSTR_MIN

char* garbage( // pointer to the buffer
char* buf, // that will contain the garbage
size_t count, // including the last null character.
const
char* chrs // character range used
) {

// static & 0 IMPORTANT! Thread-safe?
static unsigned int seed = 0;
// (A)
// If the seed is 0 (not created yet), we generate a seed.

if (0 == seed) {
time_t timeval = time((time_t*)N ULL);

// Check if time is available on system.

if (timeval == (time_t)-1)
return (NULL);
seed = (unsigned) timeval; // Not thread safe!

// Seed the random number generation algo,
// so we can call rand().
srand(seed); // Not thread safe!
}
// (B)
// If chrs is an empty string, choose our own range
// of characters from ASCII 32 to ASCII 126.

char* eosbuf = buf;
if (NULL == chrs || '\0' == *chrs) {
// generate only the required number of characters
while (1 < count--)
*eosbuf++ = (char)(rand()%R ANDSTR_RANGE);
}
else { // We are using a user-specified range.
const
char* eoschrs = chrs;

// Get a pointer
// to point to the last character '\0' of the range.

while (*eoschrs)
++eoschrs;

// Generate the random string. MAX == length of range.
while (1 < count--)
*eosbuf++ = *(chrs + (rand()%(size_t )(eoschrs - chrs)));
}
// (C)
// Important: terminate the string!

*eosbuf = (char)'\0';
// (D)
// Return pointer to the buffer.

return buf;
}

srand() and rand() modify a global "state" variable.
Suppose that two threads are running this code
and the first thread executes srand() but,
before it can complete the random string,
it is interrupted by the second thread
which rests the global state variable by executing srand() again
before the first thread takes control again
and completes the random string
with the same sequence of characters with which it began.

This may or may not be a serious problem for your application.

The ANSI/ISO C standards do *not* guarantee thread safety
even if you avoid static and global variables
(and function libraries that are not thread safe).
Compilers are allowed to use static or global variable
to store temporary intermediate results but, in fact,
all viable standard compliant implementations will emit
thread safe code if you avoid static and global variables
and function libraries that are not thread safe.

Also, be aware that some people use the term "thread safe"
when they are actually talking about library functions
that invoke mutual exclusion explicitly.
Such libraries are more correctly described as "threaded"
and typically use some thread library to implement mutual exclusion.
Nov 14 '05 #4
Jonathan Burd wrote:

Greetings everyone,

Here is a random string generator I wrote for an application
and I'm wondering about the thread-safety of this function.
I was told using static and global variables cause
potential problems for thread-safety. So far, I'm only confused.
I need a proper explanation for the concept so I can understand how
to write thread-safe functions in the future.


static and global variables cause potential problems for thread-safety.

Replace the static duration object
with an automatic object delcared in main,
and pass it's value or address to all the functions
which will call the prng().

seed = prng(seed);

or if your prng takes an array of seeds

number = prng(unsigned *array);
Nov 14 '05 #5

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

Similar topics

14
2179
by: adeger | last post by:
Having trouble with my first forays into threads. Basically, the threads don't seem to be working in parallel (or you might say are blocking). I've boiled my problems to the following short code block and ensuing output. Seems like the output should be all interleaved and of course it's not. Running Python 2.2 from ActiveState on Windows XP (also doesn't work on Windows 2000). Thanks in advance! adeger
4
2897
by: Gilles Leblanc | last post by:
Hi I have started a small project with PyOpenGL. I am wondering what are the options for a GUI. So far I checked PyUI but it has some problems with 3d rendering outside the Windows platform. I know of WxPython but I don't know if I can create a WxPython window, use gl rendering code in it and then put widgets on top of that...
7
2705
by: Ivan | last post by:
Hi I have following problem: I'm creating two threads who are performing some tasks. When one thread finished I would like to restart her again (e.g. new job). Following example demonstrates that. Problem is that when program is started many threads are created (see output section), when only two should be running at any time. Can you please help me to identify me where the problem is? Best regards
5
2830
by: Razzie | last post by:
Hi all, A question from someone on a website got me thinking about this, and I wondered if anyone could explain this. A System.Threading.Timer object is garbage collected if it has no references to it. But what about threads? If I start a new thread that only does 1+1, is it garbage collected after that? If so, do all threads get garbage collected eventually that are 'done'? And if not, why not? Are there references to the thread that...
9
3078
by: mareal | last post by:
I have noticed how the thread I created just stops running. I have added several exceptions to the thread System.Threading.SynchronizationLockException System.Threading.ThreadAbortException System.Threading.ThreadInterruptedException System.Threading.ThreadStateException to see if I could get more information about why the thread stops running but that code is never executed. Any ideas on how I can debug this?
7
2695
by: Charles Law | last post by:
My first thought was to call WorkerThread.Suspend but the help cautions against this (for good reason) because the caller has no control over where the thread actually stops, and it might have a lock pending, for example. I want to be able to stop a thread temporarily, and then optionally resume it or stop it for good.
4
6220
by: jayesah | last post by:
Hi All, I am writting a Thread class with using pthread library. I have some problem in saving thread function type and argument type. How to make Thread class generic ? /* This is my global Function */ template < class FunType, class ArgType> Thread makeThread(Funtype fun, ArgType arg)
6
5128
by: HolyShea | last post by:
All, Not sure if this is possible or not - I've created a class which performs an asynchronous operation and provides notification when the operation is complete. I'd like the notification to be performed on the same thread thread that instantiated the class. One way to do this is to pass an ISynchronizeInvoke into the class and use it to synchronize the callback. In the constructor of the class, could I take note of the current thread...
3
35369
by: John Nagle | last post by:
There's no way to set thread priorities within Python, is there? We have some threads that go compute-bound, and would like to reduce their priority slightly so the other operations, like accessing the database and servicing queries, aren't slowed as much. John Nagle
34
2812
by: Creativ | last post by:
Why does Thread class not support IDisposable? It's creating quite some problem. Namely, it can exhaust the resource and you have not control over it.
0
9399
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9957
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8832
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7379
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5276
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.