SortUtils: fix random sorting always being the same after restart #1448

Merged
merged 2 commits into from Sep 23, 2012
Jump to file or symbol
Failed to load files and symbols.
+32 −2
Split
View
@@ -32,11 +32,12 @@
#ifdef _LINUX
#include <sys/types.h>
#include <dirent.h>
-#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#endif
+#include <stdlib.h>
+
#include "Application.h"
#include "Util.h"
#include "addons/Addon.h"
@@ -112,6 +113,10 @@ static uint16_t flashrampGreen[256];
static uint16_t flashrampBlue[256];
#endif
+#if !defined(TARGET_WINDOWS)
+unsigned int CUtil::s_randomSeed = time(NULL);
+#endif
+
CUtil::CUtil(void)
{
}
@@ -2607,3 +2612,16 @@ bool CUtil::CanBindPrivileged()
#endif //_LINUX
}
+int CUtil::GetRandomNumber()
+{
+#ifdef TARGET_WINDOWS
+ unsigned int number;
+ if (rand_s(&number) == 0)
+ return (int)number;
+#else
+ return rand_r(&s_randomSeed);
+#endif
+
+ return rand();
+}
+
View
@@ -189,6 +189,16 @@ class CUtil
static CStdString GetFrameworksPath(bool forPython = false);
static bool CanBindPrivileged();
+
+ /*!
+ * \brief Thread-safe random number generation
+ */
+ static int GetRandomNumber();
+
+#if !defined(TARGET_WINDOWS)
+private:
+ static unsigned int s_randomSeed;
+#endif
};
View
@@ -20,6 +20,7 @@
#include "SortUtils.h"
#include "URL.h"
+#include "Util.h"
#include "XBDateTime.h"
#include "settings/AdvancedSettings.h"
#include "utils/CharsetConverter.h"
@@ -395,7 +396,7 @@ string ByListeners(SortAttribute attributes, const SortItem &values)
string ByRandom(SortAttribute attributes, const SortItem &values)
{
CStdString label;
- label.Format("%i", rand());
+ label.Format("%i", CUtil::GetRandomNumber());
return label;
}
View
@@ -1,4 +1,5 @@
#pragma once
+#define _CRT_RAND_S
#include <vector>
#include <map>
#include <string>